repo_name stringclasses 5 values | pr_number int64 1.52k 15.5k | pr_title stringlengths 8 143 | pr_description stringlengths 0 10.2k | author stringlengths 3 18 | date_created timestamp[ns, tz=UTC] | date_merged timestamp[ns, tz=UTC] | previous_commit stringlengths 40 40 | pr_commit stringlengths 40 40 | query stringlengths 11 10.2k | filepath stringlengths 6 220 | before_content stringlengths 0 597M | after_content stringlengths 0 597M | label int64 -1 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apolloconfig/apollo | 3,679 | fix[apollo-configService]: Solve configService startup exception | ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | klboke | 2021-05-12T10:46:18Z | 2021-05-18T00:03:38Z | d60bf888c57dcea93568fdfa4ae3c5836f632d3d | 1cc8f5501fa037a449f560788b8deedb70bc6f62 | fix[apollo-configService]: Solve configService startup exception. ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | ./apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ResourceUtils.java | package com.ctrip.framework.apollo.core.utils;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.nio.file.Paths;
import java.util.Properties;
public class ResourceUtils {
private static final Logger logger = LoggerFactory.getLogger(ResourceUtils.class);
private static final String[] DEFAULT_FILE_SEARCH_LOCATIONS = new String[]{"./config/", "./"};
@SuppressWarnings("unchecked")
public static Properties readConfigFile(String configPath, Properties defaults) {
Properties props = new Properties();
if (defaults != null) {
props.putAll(defaults);
}
InputStream in = loadConfigFileFromDefaultSearchLocations(configPath);
try {
if (in != null) {
props.load(in);
}
} catch (IOException ex) {
logger.warn("Reading config failed: {}", ex.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
logger.warn("Close config failed: {}", ex.getMessage());
}
}
}
if (logger.isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
for (String propertyName : props.stringPropertyNames()) {
sb.append(propertyName).append('=').append(props.getProperty(propertyName)).append('\n');
}
if (sb.length() > 0) {
logger.debug("Reading properties: \n" + sb.toString());
} else {
logger.warn("No available properties: {}", configPath);
}
}
return props;
}
private static InputStream loadConfigFileFromDefaultSearchLocations(String configPath) {
try {
// load from default search locations
for (String searchLocation : DEFAULT_FILE_SEARCH_LOCATIONS) {
File candidate = Paths.get(searchLocation, configPath).toFile();
if (candidate.exists() && candidate.isFile() && candidate.canRead()) {
logger.debug("Reading config from resource {}", candidate.getAbsolutePath());
return new FileInputStream(candidate);
}
}
// load from classpath
URL url = ClassLoaderUtil.getLoader().getResource(configPath);
if (url != null) {
InputStream in = getResourceAsStream(url);
if (in != null) {
logger.debug("Reading config from resource {}", url.getPath());
return in;
}
}
// load outside resource under current user path
File candidate = new File(System.getProperty("user.dir"), configPath);
if (candidate.exists() && candidate.isFile() && candidate.canRead()) {
logger.debug("Reading config from resource {}", candidate.getAbsolutePath());
return new FileInputStream(candidate);
}
} catch (FileNotFoundException e) {
//ignore
}
return null;
}
private static InputStream getResourceAsStream(URL url) {
try {
return url != null ? url.openStream() : null;
} catch (IOException e) {
return null;
}
}
}
| package com.ctrip.framework.apollo.core.utils;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.nio.file.Paths;
import java.util.Properties;
public class ResourceUtils {
private static final Logger logger = LoggerFactory.getLogger(ResourceUtils.class);
private static final String[] DEFAULT_FILE_SEARCH_LOCATIONS = new String[]{"./config/", "./"};
@SuppressWarnings("unchecked")
public static Properties readConfigFile(String configPath, Properties defaults) {
Properties props = new Properties();
if (defaults != null) {
props.putAll(defaults);
}
InputStream in = loadConfigFileFromDefaultSearchLocations(configPath);
try {
if (in != null) {
props.load(in);
}
} catch (IOException ex) {
logger.warn("Reading config failed: {}", ex.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
logger.warn("Close config failed: {}", ex.getMessage());
}
}
}
if (logger.isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
for (String propertyName : props.stringPropertyNames()) {
sb.append(propertyName).append('=').append(props.getProperty(propertyName)).append('\n');
}
if (sb.length() > 0) {
logger.debug("Reading properties: \n" + sb.toString());
} else {
logger.warn("No available properties: {}", configPath);
}
}
return props;
}
private static InputStream loadConfigFileFromDefaultSearchLocations(String configPath) {
try {
// load from default search locations
for (String searchLocation : DEFAULT_FILE_SEARCH_LOCATIONS) {
File candidate = Paths.get(searchLocation, configPath).toFile();
if (candidate.exists() && candidate.isFile() && candidate.canRead()) {
logger.debug("Reading config from resource {}", candidate.getAbsolutePath());
return new FileInputStream(candidate);
}
}
// load from classpath
URL url = ClassLoaderUtil.getLoader().getResource(configPath);
if (url != null) {
InputStream in = getResourceAsStream(url);
if (in != null) {
logger.debug("Reading config from resource {}", url.getPath());
return in;
}
}
// load outside resource under current user path
File candidate = new File(System.getProperty("user.dir"), configPath);
if (candidate.exists() && candidate.isFile() && candidate.canRead()) {
logger.debug("Reading config from resource {}", candidate.getAbsolutePath());
return new FileInputStream(candidate);
}
} catch (FileNotFoundException e) {
//ignore
}
return null;
}
private static InputStream getResourceAsStream(URL url) {
try {
return url != null ? url.openStream() : null;
} catch (IOException e) {
return null;
}
}
}
| -1 |
apolloconfig/apollo | 3,679 | fix[apollo-configService]: Solve configService startup exception | ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | klboke | 2021-05-12T10:46:18Z | 2021-05-18T00:03:38Z | d60bf888c57dcea93568fdfa4ae3c5836f632d3d | 1cc8f5501fa037a449f560788b8deedb70bc6f62 | fix[apollo-configService]: Solve configService startup exception. ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/BaseEntity.java | package com.ctrip.framework.apollo.common.entity;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Id")
private long id;
@Column(name = "IsDeleted", columnDefinition = "Bit default '0'")
protected boolean isDeleted = false;
@Column(name = "DataChange_CreatedBy", nullable = false)
private String dataChangeCreatedBy;
@Column(name = "DataChange_CreatedTime", nullable = false)
private Date dataChangeCreatedTime;
@Column(name = "DataChange_LastModifiedBy")
private String dataChangeLastModifiedBy;
@Column(name = "DataChange_LastTime")
private Date dataChangeLastModifiedTime;
public String getDataChangeCreatedBy() {
return dataChangeCreatedBy;
}
public Date getDataChangeCreatedTime() {
return dataChangeCreatedTime;
}
public String getDataChangeLastModifiedBy() {
return dataChangeLastModifiedBy;
}
public Date getDataChangeLastModifiedTime() {
return dataChangeLastModifiedTime;
}
public long getId() {
return id;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDataChangeCreatedBy(String dataChangeCreatedBy) {
this.dataChangeCreatedBy = dataChangeCreatedBy;
}
public void setDataChangeCreatedTime(Date dataChangeCreatedTime) {
this.dataChangeCreatedTime = dataChangeCreatedTime;
}
public void setDataChangeLastModifiedBy(String dataChangeLastModifiedBy) {
this.dataChangeLastModifiedBy = dataChangeLastModifiedBy;
}
public void setDataChangeLastModifiedTime(Date dataChangeLastModifiedTime) {
this.dataChangeLastModifiedTime = dataChangeLastModifiedTime;
}
public void setDeleted(boolean deleted) {
isDeleted = deleted;
}
public void setId(long id) {
this.id = id;
}
@PrePersist
protected void prePersist() {
if (this.dataChangeCreatedTime == null) {
dataChangeCreatedTime = new Date();
}
if (this.dataChangeLastModifiedTime == null) {
dataChangeLastModifiedTime = new Date();
}
}
@PreUpdate
protected void preUpdate() {
this.dataChangeLastModifiedTime = new Date();
}
@PreRemove
protected void preRemove() {
this.dataChangeLastModifiedTime = new Date();
}
protected ToStringHelper toStringHelper() {
return MoreObjects.toStringHelper(this).omitNullValues().add("id", id)
.add("dataChangeCreatedBy", dataChangeCreatedBy)
.add("dataChangeCreatedTime", dataChangeCreatedTime)
.add("dataChangeLastModifiedBy", dataChangeLastModifiedBy)
.add("dataChangeLastModifiedTime", dataChangeLastModifiedTime);
}
public String toString(){
return toStringHelper().toString();
}
}
| package com.ctrip.framework.apollo.common.entity;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "Id")
private long id;
@Column(name = "IsDeleted", columnDefinition = "Bit default '0'")
protected boolean isDeleted = false;
@Column(name = "DataChange_CreatedBy", nullable = false)
private String dataChangeCreatedBy;
@Column(name = "DataChange_CreatedTime", nullable = false)
private Date dataChangeCreatedTime;
@Column(name = "DataChange_LastModifiedBy")
private String dataChangeLastModifiedBy;
@Column(name = "DataChange_LastTime")
private Date dataChangeLastModifiedTime;
public String getDataChangeCreatedBy() {
return dataChangeCreatedBy;
}
public Date getDataChangeCreatedTime() {
return dataChangeCreatedTime;
}
public String getDataChangeLastModifiedBy() {
return dataChangeLastModifiedBy;
}
public Date getDataChangeLastModifiedTime() {
return dataChangeLastModifiedTime;
}
public long getId() {
return id;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDataChangeCreatedBy(String dataChangeCreatedBy) {
this.dataChangeCreatedBy = dataChangeCreatedBy;
}
public void setDataChangeCreatedTime(Date dataChangeCreatedTime) {
this.dataChangeCreatedTime = dataChangeCreatedTime;
}
public void setDataChangeLastModifiedBy(String dataChangeLastModifiedBy) {
this.dataChangeLastModifiedBy = dataChangeLastModifiedBy;
}
public void setDataChangeLastModifiedTime(Date dataChangeLastModifiedTime) {
this.dataChangeLastModifiedTime = dataChangeLastModifiedTime;
}
public void setDeleted(boolean deleted) {
isDeleted = deleted;
}
public void setId(long id) {
this.id = id;
}
@PrePersist
protected void prePersist() {
if (this.dataChangeCreatedTime == null) {
dataChangeCreatedTime = new Date();
}
if (this.dataChangeLastModifiedTime == null) {
dataChangeLastModifiedTime = new Date();
}
}
@PreUpdate
protected void preUpdate() {
this.dataChangeLastModifiedTime = new Date();
}
@PreRemove
protected void preRemove() {
this.dataChangeLastModifiedTime = new Date();
}
protected ToStringHelper toStringHelper() {
return MoreObjects.toStringHelper(this).omitNullValues().add("id", id)
.add("dataChangeCreatedBy", dataChangeCreatedBy)
.add("dataChangeCreatedTime", dataChangeCreatedTime)
.add("dataChangeLastModifiedBy", dataChangeLastModifiedBy)
.add("dataChangeLastModifiedTime", dataChangeLastModifiedTime);
}
public String toString(){
return toStringHelper().toString();
}
}
| -1 |
apolloconfig/apollo | 3,679 | fix[apollo-configService]: Solve configService startup exception | ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | klboke | 2021-05-12T10:46:18Z | 2021-05-18T00:03:38Z | d60bf888c57dcea93568fdfa4ae3c5836f632d3d | 1cc8f5501fa037a449f560788b8deedb70bc6f62 | fix[apollo-configService]: Solve configService startup exception. ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/po/ServerConfig.java | package com.ctrip.framework.apollo.portal.entity.po;
import com.ctrip.framework.apollo.common.entity.BaseEntity;
import javax.validation.constraints.NotBlank;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@Entity
@Table(name = "ServerConfig")
@SQLDelete(sql = "Update ServerConfig set isDeleted = 1 where id = ?")
@Where(clause = "isDeleted = 0")
public class ServerConfig extends BaseEntity {
@NotBlank(message = "ServerConfig.Key cannot be blank")
@Column(name = "Key", nullable = false)
private String key;
@NotBlank(message = "ServerConfig.Value cannot be blank")
@Column(name = "Value", nullable = false)
private String value;
@Column(name = "Comment", nullable = false)
private String comment;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String toString() {
return toStringHelper().add("key", key).add("value", value).add("comment", comment).toString();
}
}
| package com.ctrip.framework.apollo.portal.entity.po;
import com.ctrip.framework.apollo.common.entity.BaseEntity;
import javax.validation.constraints.NotBlank;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@Entity
@Table(name = "ServerConfig")
@SQLDelete(sql = "Update ServerConfig set isDeleted = 1 where id = ?")
@Where(clause = "isDeleted = 0")
public class ServerConfig extends BaseEntity {
@NotBlank(message = "ServerConfig.Key cannot be blank")
@Column(name = "Key", nullable = false)
private String key;
@NotBlank(message = "ServerConfig.Value cannot be blank")
@Column(name = "Value", nullable = false)
private String value;
@Column(name = "Comment", nullable = false)
private String comment;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String toString() {
return toStringHelper().add("key", key).add("value", value).add("comment", comment).toString();
}
}
| -1 |
apolloconfig/apollo | 3,679 | fix[apollo-configService]: Solve configService startup exception | ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | klboke | 2021-05-12T10:46:18Z | 2021-05-18T00:03:38Z | d60bf888c57dcea93568fdfa4ae3c5836f632d3d | 1cc8f5501fa037a449f560788b8deedb70bc6f62 | fix[apollo-configService]: Solve configService startup exception. ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | ./apollo-core/src/test/java/com/ctrip/framework/foundation/internals/provider/DefaultApplicationProviderTest.java | package com.ctrip.framework.foundation.internals.provider;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import org.junit.Before;
import org.junit.Test;
public class DefaultApplicationProviderTest {
private DefaultApplicationProvider defaultApplicationProvider;
String PREDEFINED_APP_ID = "110402";
@Before
public void setUp() throws Exception {
defaultApplicationProvider = new DefaultApplicationProvider();
}
@Test
public void testLoadAppProperties() throws Exception {
defaultApplicationProvider.initialize();
assertEquals(PREDEFINED_APP_ID, defaultApplicationProvider.getAppId());
assertTrue(defaultApplicationProvider.isAppIdSet());
}
@Test
public void testLoadAppPropertiesWithUTF8Bom() throws Exception {
File baseDir = new File("src/test/resources/META-INF");
File appProperties = new File(baseDir, "app-with-utf8bom.properties");
defaultApplicationProvider.initialize(new FileInputStream(appProperties));
assertEquals(PREDEFINED_APP_ID, defaultApplicationProvider.getAppId());
assertTrue(defaultApplicationProvider.isAppIdSet());
}
@Test
public void testLoadAppPropertiesWithSystemProperty() throws Exception {
String someAppId = "someAppId";
String someSecret = "someSecret";
System.setProperty("app.id", someAppId);
System.setProperty("apollo.accesskey.secret", someSecret);
defaultApplicationProvider.initialize();
System.clearProperty("app.id");
System.clearProperty("apollo.accesskey.secret");
assertEquals(someAppId, defaultApplicationProvider.getAppId());
assertTrue(defaultApplicationProvider.isAppIdSet());
assertEquals(someSecret, defaultApplicationProvider.getAccessKeySecret());
}
@Test
public void testLoadAppPropertiesFailed() throws Exception {
File baseDir = new File("src/test/resources/META-INF");
File appProperties = new File(baseDir, "some-invalid-app.properties");
defaultApplicationProvider.initialize(new FileInputStream(appProperties));
assertEquals(null, defaultApplicationProvider.getAppId());
assertFalse(defaultApplicationProvider.isAppIdSet());
}
}
| package com.ctrip.framework.foundation.internals.provider;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import org.junit.Before;
import org.junit.Test;
public class DefaultApplicationProviderTest {
private DefaultApplicationProvider defaultApplicationProvider;
String PREDEFINED_APP_ID = "110402";
@Before
public void setUp() throws Exception {
defaultApplicationProvider = new DefaultApplicationProvider();
}
@Test
public void testLoadAppProperties() throws Exception {
defaultApplicationProvider.initialize();
assertEquals(PREDEFINED_APP_ID, defaultApplicationProvider.getAppId());
assertTrue(defaultApplicationProvider.isAppIdSet());
}
@Test
public void testLoadAppPropertiesWithUTF8Bom() throws Exception {
File baseDir = new File("src/test/resources/META-INF");
File appProperties = new File(baseDir, "app-with-utf8bom.properties");
defaultApplicationProvider.initialize(new FileInputStream(appProperties));
assertEquals(PREDEFINED_APP_ID, defaultApplicationProvider.getAppId());
assertTrue(defaultApplicationProvider.isAppIdSet());
}
@Test
public void testLoadAppPropertiesWithSystemProperty() throws Exception {
String someAppId = "someAppId";
String someSecret = "someSecret";
System.setProperty("app.id", someAppId);
System.setProperty("apollo.accesskey.secret", someSecret);
defaultApplicationProvider.initialize();
System.clearProperty("app.id");
System.clearProperty("apollo.accesskey.secret");
assertEquals(someAppId, defaultApplicationProvider.getAppId());
assertTrue(defaultApplicationProvider.isAppIdSet());
assertEquals(someSecret, defaultApplicationProvider.getAccessKeySecret());
}
@Test
public void testLoadAppPropertiesFailed() throws Exception {
File baseDir = new File("src/test/resources/META-INF");
File appProperties = new File(baseDir, "some-invalid-app.properties");
defaultApplicationProvider.initialize(new FileInputStream(appProperties));
assertEquals(null, defaultApplicationProvider.getAppId());
assertFalse(defaultApplicationProvider.isAppIdSet());
}
}
| -1 |
apolloconfig/apollo | 3,679 | fix[apollo-configService]: Solve configService startup exception | ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | klboke | 2021-05-12T10:46:18Z | 2021-05-18T00:03:38Z | d60bf888c57dcea93568fdfa4ae3c5836f632d3d | 1cc8f5501fa037a449f560788b8deedb70bc6f62 | fix[apollo-configService]: Solve configService startup exception. ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/util/NamespaceBOUtils.java | package com.ctrip.framework.apollo.portal.util;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.core.utils.PropertiesUtil;
import com.ctrip.framework.apollo.portal.controller.ConfigsExportController;
import com.ctrip.framework.apollo.portal.entity.bo.ItemBO;
import com.ctrip.framework.apollo.portal.entity.bo.NamespaceBO;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
/**
* @author wxq
*/
public class NamespaceBOUtils {
/**
* namespace must not be {@link ConfigFileFormat#Properties}.
* the content of namespace in item's value which item's key is {@link ConfigConsts#CONFIG_FILE_CONTENT_KEY}.
* @param namespaceBO namespace
* @return content of non-properties's namespace
*/
static String convertNonProperties2configFileContent(NamespaceBO namespaceBO) {
List<ItemBO> itemBOS = namespaceBO.getItems();
for (ItemBO itemBO : itemBOS) {
String key = itemBO.getItem().getKey();
// special namespace format(not properties)
if (ConfigConsts.CONFIG_FILE_CONTENT_KEY.equals(key)) {
return itemBO.getItem().getValue();
}
}
// If there is no items?
// return empty string ""
return "";
}
/**
* copy from old {@link ConfigsExportController}.
* convert {@link NamespaceBO} to a file content.
* @return content of config file
* @throws IllegalStateException if convert properties to string fail
*/
public static String convert2configFileContent(NamespaceBO namespaceBO) {
// early return if it is not a properties format namespace
if (!ConfigFileFormat.Properties.equals(ConfigFileFormat.fromString(namespaceBO.getFormat()))) {
// it is not a properties namespace
return convertNonProperties2configFileContent(namespaceBO);
}
// it must be a properties format namespace
List<ItemBO> itemBOS = namespaceBO.getItems();
// save the kev value pair
Properties properties = new Properties();
for (ItemBO itemBO : itemBOS) {
String key = itemBO.getItem().getKey();
String value = itemBO.getItem().getValue();
// ignore comment, so the comment will lack
properties.put(key, value);
}
// use a special method convert properties to string
final String configFileContent;
try {
configFileContent = PropertiesUtil.toString(properties);
} catch (IOException e) {
throw new IllegalStateException("convert properties to string fail.", e);
}
return configFileContent;
}
}
| package com.ctrip.framework.apollo.portal.util;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.core.utils.PropertiesUtil;
import com.ctrip.framework.apollo.portal.controller.ConfigsExportController;
import com.ctrip.framework.apollo.portal.entity.bo.ItemBO;
import com.ctrip.framework.apollo.portal.entity.bo.NamespaceBO;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
/**
* @author wxq
*/
public class NamespaceBOUtils {
/**
* namespace must not be {@link ConfigFileFormat#Properties}.
* the content of namespace in item's value which item's key is {@link ConfigConsts#CONFIG_FILE_CONTENT_KEY}.
* @param namespaceBO namespace
* @return content of non-properties's namespace
*/
static String convertNonProperties2configFileContent(NamespaceBO namespaceBO) {
List<ItemBO> itemBOS = namespaceBO.getItems();
for (ItemBO itemBO : itemBOS) {
String key = itemBO.getItem().getKey();
// special namespace format(not properties)
if (ConfigConsts.CONFIG_FILE_CONTENT_KEY.equals(key)) {
return itemBO.getItem().getValue();
}
}
// If there is no items?
// return empty string ""
return "";
}
/**
* copy from old {@link ConfigsExportController}.
* convert {@link NamespaceBO} to a file content.
* @return content of config file
* @throws IllegalStateException if convert properties to string fail
*/
public static String convert2configFileContent(NamespaceBO namespaceBO) {
// early return if it is not a properties format namespace
if (!ConfigFileFormat.Properties.equals(ConfigFileFormat.fromString(namespaceBO.getFormat()))) {
// it is not a properties namespace
return convertNonProperties2configFileContent(namespaceBO);
}
// it must be a properties format namespace
List<ItemBO> itemBOS = namespaceBO.getItems();
// save the kev value pair
Properties properties = new Properties();
for (ItemBO itemBO : itemBOS) {
String key = itemBO.getItem().getKey();
String value = itemBO.getItem().getValue();
// ignore comment, so the comment will lack
properties.put(key, value);
}
// use a special method convert properties to string
final String configFileContent;
try {
configFileContent = PropertiesUtil.toString(properties);
} catch (IOException e) {
throw new IllegalStateException("convert properties to string fail.", e);
}
return configFileContent;
}
}
| -1 |
apolloconfig/apollo | 3,679 | fix[apollo-configService]: Solve configService startup exception | ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | klboke | 2021-05-12T10:46:18Z | 2021-05-18T00:03:38Z | d60bf888c57dcea93568fdfa4ae3c5836f632d3d | 1cc8f5501fa037a449f560788b8deedb70bc6f62 | fix[apollo-configService]: Solve configService startup exception. ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/environment/PortalMetaServerProvider.java | package com.ctrip.framework.apollo.portal.environment;
/**
* For the supporting of multiple meta server address providers.
* From configuration file,
* from OS environment,
* From database,
* ...
* Just implement this interface
* @author wxq
*/
public interface PortalMetaServerProvider {
/**
* @param targetEnv environment
* @return meta server address matched environment
*/
String getMetaServerAddress(Env targetEnv);
/**
* @param targetEnv environment
* @return environment's meta server address exists or not
*/
boolean exists(Env targetEnv);
/**
* reload the meta server address in runtime
*/
void reload();
}
| package com.ctrip.framework.apollo.portal.environment;
/**
* For the supporting of multiple meta server address providers.
* From configuration file,
* from OS environment,
* From database,
* ...
* Just implement this interface
* @author wxq
*/
public interface PortalMetaServerProvider {
/**
* @param targetEnv environment
* @return meta server address matched environment
*/
String getMetaServerAddress(Env targetEnv);
/**
* @param targetEnv environment
* @return environment's meta server address exists or not
*/
boolean exists(Env targetEnv);
/**
* reload the meta server address in runtime
*/
void reload();
}
| -1 |
apolloconfig/apollo | 3,679 | fix[apollo-configService]: Solve configService startup exception | ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | klboke | 2021-05-12T10:46:18Z | 2021-05-18T00:03:38Z | d60bf888c57dcea93568fdfa4ae3c5836f632d3d | 1cc8f5501fa037a449f560788b8deedb70bc6f62 | fix[apollo-configService]: Solve configService startup exception. ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | ./apollo-configservice/src/test/resources/data.sql | INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('100003171','apollo-config-service','刘一鸣','liuym@ctrip.com');
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('100003172','apollo-admin-service','宋顺','song_s@ctrip.com');
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('100003173','apollo-portal','张乐','zhanglea@ctrip.com');
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('fxhermesproducer','fx-hermes-producer','梁锦华','jhliang@ctrip.com');
INSERT INTO Cluster (AppId, Name) VALUES ('100003171', 'default');
INSERT INTO Cluster (AppId, Name) VALUES ('100003171', 'cluster1');
INSERT INTO Cluster (AppId, Name) VALUES ('100003172', 'default');
INSERT INTO Cluster (AppId, Name) VALUES ('100003172', 'cluster2');
INSERT INTO Cluster (AppId, Name) VALUES ('100003173', 'default');
INSERT INTO Cluster (AppId, Name) VALUES ('100003173', 'cluster3');
INSERT INTO Cluster (AppId, Name) VALUES ('fxhermesproducer', 'default');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003171', 'application');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003171', 'fx.apollo.config');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003172', 'application');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003172', 'fx.apollo.admin');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003173', 'application');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003173', 'fx.apollo.portal');
INSERT INTO AppNamespace (AppID, Name) VALUES ('fxhermesproducer', 'fx.hermes.producer');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (1, '100003171', 'default', 'application');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (2, 'fxhermesproducer', 'default', 'fx.hermes.producer');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (3, '100003172', 'default', 'application');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (4, '100003173', 'default', 'application');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (5, '100003171', 'default', 'application');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (1, 'k1', 'v1', 'comment1');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (1, 'k2', 'v2', 'comment2');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (2, 'k3', 'v3', 'comment3');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (5, 'k3', 'v4', 'comment4');
INSERT INTO RELEASE (ReleaseKey, Name, Comment, AppId, ClusterName, NamespaceName, Configurations) VALUES ('TEST-RELEASE-KEY', 'REV1','First Release','100003171', 'default', 'application', '{"k1":"v1"}');
| INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('100003171','apollo-config-service','刘一鸣','liuym@ctrip.com');
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('100003172','apollo-admin-service','宋顺','song_s@ctrip.com');
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('100003173','apollo-portal','张乐','zhanglea@ctrip.com');
INSERT INTO App (AppId, Name, OwnerName, OwnerEmail) VALUES ('fxhermesproducer','fx-hermes-producer','梁锦华','jhliang@ctrip.com');
INSERT INTO Cluster (AppId, Name) VALUES ('100003171', 'default');
INSERT INTO Cluster (AppId, Name) VALUES ('100003171', 'cluster1');
INSERT INTO Cluster (AppId, Name) VALUES ('100003172', 'default');
INSERT INTO Cluster (AppId, Name) VALUES ('100003172', 'cluster2');
INSERT INTO Cluster (AppId, Name) VALUES ('100003173', 'default');
INSERT INTO Cluster (AppId, Name) VALUES ('100003173', 'cluster3');
INSERT INTO Cluster (AppId, Name) VALUES ('fxhermesproducer', 'default');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003171', 'application');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003171', 'fx.apollo.config');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003172', 'application');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003172', 'fx.apollo.admin');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003173', 'application');
INSERT INTO AppNamespace (AppId, Name) VALUES ('100003173', 'fx.apollo.portal');
INSERT INTO AppNamespace (AppID, Name) VALUES ('fxhermesproducer', 'fx.hermes.producer');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (1, '100003171', 'default', 'application');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (2, 'fxhermesproducer', 'default', 'fx.hermes.producer');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (3, '100003172', 'default', 'application');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (4, '100003173', 'default', 'application');
INSERT INTO Namespace (Id, AppId, ClusterName, NamespaceName) VALUES (5, '100003171', 'default', 'application');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (1, 'k1', 'v1', 'comment1');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (1, 'k2', 'v2', 'comment2');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (2, 'k3', 'v3', 'comment3');
INSERT INTO Item (NamespaceId, `Key`, Value, Comment) VALUES (5, 'k3', 'v4', 'comment4');
INSERT INTO RELEASE (ReleaseKey, Name, Comment, AppId, ClusterName, NamespaceName, Configurations) VALUES ('TEST-RELEASE-KEY', 'REV1','First Release','100003171', 'default', 'application', '{"k1":"v1"}');
| -1 |
apolloconfig/apollo | 3,679 | fix[apollo-configService]: Solve configService startup exception | ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | klboke | 2021-05-12T10:46:18Z | 2021-05-18T00:03:38Z | d60bf888c57dcea93568fdfa4ae3c5836f632d3d | 1cc8f5501fa037a449f560788b8deedb70bc6f62 | fix[apollo-configService]: Solve configService startup exception. ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/config/RefreshablePropertySource.java | package com.ctrip.framework.apollo.common.config;
import org.springframework.core.env.MapPropertySource;
import java.util.Map;
public abstract class RefreshablePropertySource extends MapPropertySource {
public RefreshablePropertySource(String name, Map<String, Object> source) {
super(name, source);
}
@Override
public Object getProperty(String name) {
return this.source.get(name);
}
/**
* refresh property
*/
protected abstract void refresh();
}
| package com.ctrip.framework.apollo.common.config;
import org.springframework.core.env.MapPropertySource;
import java.util.Map;
public abstract class RefreshablePropertySource extends MapPropertySource {
public RefreshablePropertySource(String name, Map<String, Object> source) {
super(name, source);
}
@Override
public Object getProperty(String name) {
return this.source.get(name);
}
/**
* refresh property
*/
protected abstract void refresh();
}
| -1 |
apolloconfig/apollo | 3,679 | fix[apollo-configService]: Solve configService startup exception | ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | klboke | 2021-05-12T10:46:18Z | 2021-05-18T00:03:38Z | d60bf888c57dcea93568fdfa4ae3c5836f632d3d | 1cc8f5501fa037a449f560788b8deedb70bc6f62 | fix[apollo-configService]: Solve configService startup exception. ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | ./apollo-client/src/test/resources/spring/XmlConfigAnnotationTest4.xml | <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<apollo:config/>
<bean class="com.ctrip.framework.apollo.spring.XMLConfigAnnotationTest.TestApolloConfigChangeListenerBean2"/>
</beans>
| <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<apollo:config/>
<bean class="com.ctrip.framework.apollo.spring.XMLConfigAnnotationTest.TestApolloConfigChangeListenerBean2"/>
</beans>
| -1 |
apolloconfig/apollo | 3,679 | fix[apollo-configService]: Solve configService startup exception | ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | klboke | 2021-05-12T10:46:18Z | 2021-05-18T00:03:38Z | d60bf888c57dcea93568fdfa4ae3c5836f632d3d | 1cc8f5501fa037a449f560788b8deedb70bc6f62 | fix[apollo-configService]: Solve configService startup exception. ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | ./docs/zh/faq/faq.md | ## 1. Apollo是什么?
Apollo(阿波罗)是携程框架部门研发的配置管理平台,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性。
更多介绍,可以参考[Apollo配置中心介绍](zh/design/apollo-introduction)
## 2. Cluster是什么?
一个应用下不同实例的分组,比如典型的可以按照数据中心分,把A机房的应用实例分为一个集群,把B机房的应用实例分为另一个集群。
## 3. Namespace是什么?
一个应用下不同配置的分组。
请参考[Apollo核心概念之“Namespace”](zh/design/apollo-core-concept-namespace)
## 4. 我想要接入Apollo,该如何操作?
请参考[Apollo使用指南](zh/usage/apollo-user-guide)
## 5. 我的应用需要不同机房的配置不一样,Apollo是否能支持?
Apollo是支持的。请参考[Apollo使用指南](zh/usage/apollo-user-guide)中的`三、集群独立配置说明`
## 6. 我有多个应用需要使用同一份配置,Apollo是否能支持?
Apollo是支持的。请参考[Apollo使用指南](zh/usage/apollo-user-guide)中的`四、多个AppId使用同一份配置`
## 7. Apollo是否支持查看权限控制或者配置加密?
从1.1.0版本开始,apollo-portal增加了查看权限的支持,可以支持配置某个环境只允许项目成员查看私有Namespace的配置。
这里的项目成员是指:
1. 项目的管理员
2. 具备该私有Namespace在该环境下的修改或发布权限
配置方式很简单,用超级管理员账号登录后,进入`管理员工具 - 系统参数`页面新增或修改`configView.memberOnly.envs`配置项即可。

配置加密可以参考[spring-boot-encrypt demo项目](https://github.com/ctripcorp/apollo-use-cases/tree/master/spring-boot-encrypt)
## 8. 如果有多个config server,打包时如何配置meta server地址?
有多台meta server可以通过nginx反向代理,通过一个域名代理多个meta server实现ha。
## 9. Apollo相比于Spring Cloud Config有什么优势?
Spring Cloud Config的精妙之处在于它的配置存储于Git,这就天然的把配置的修改、权限、版本等问题隔离在外。通过这个设计使得Spring Cloud Config整体很简单,不过也带来了一些不便之处。
下面尝试做一个简单的小结:
| 功能点 | Apollo | Spring Cloud Config | 备注 |
|------------------|--------------------------------------------|-------------------------------------------------|----------------------------------------------------------------------------|
| 配置界面 | 一个界面管理不同环境、不同集群配置 | 无,需要通过git操作 | |
| 配置生效时间 | 实时 | 重启生效,或手动refresh生效 | Spring Cloud Config需要通过Git webhook,加上额外的消息队列才能支持实时生效 |
| 版本管理 | 界面上直接提供发布历史和回滚按钮 | 无,需要通过git操作 | |
| 灰度发布 | 支持 | 不支持 | |
| 授权、审核、审计 | 界面上直接支持,而且支持修改、发布权限分离 | 需要通过git仓库设置,且不支持修改、发布权限分离 | |
| 实例配置监控 | 可以方便的看到当前哪些客户端在使用哪些配置 | 不支持 | |
| 配置获取性能 | 快,通过数据库访问,还有缓存支持 | 较慢,需要从git clone repository,然后从文件系统读取 | |
| 客户端支持 | 原生支持所有Java和.Net应用,提供API支持其它语言应用,同时也支持Spring annotation获取配置 | 支持Spring应用,提供annotation获取配置 | Apollo的适用范围更广一些 |
## 10. Apollo和Disconf相比有什么优点?
由于我们自己并非Disconf的资深用户,所以无法主观地给出评价。
不过之前Apollo技术支持群中的热心网友[@Krast](https://github.com/krast)做了一个[开源配置中心对比矩阵](https://github.com/ctripcorp/apollo/files/983064/default.pdf),可以参考一下。 | ## 1. Apollo是什么?
Apollo(阿波罗)是携程框架部门研发的配置管理平台,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性。
更多介绍,可以参考[Apollo配置中心介绍](zh/design/apollo-introduction)
## 2. Cluster是什么?
一个应用下不同实例的分组,比如典型的可以按照数据中心分,把A机房的应用实例分为一个集群,把B机房的应用实例分为另一个集群。
## 3. Namespace是什么?
一个应用下不同配置的分组。
请参考[Apollo核心概念之“Namespace”](zh/design/apollo-core-concept-namespace)
## 4. 我想要接入Apollo,该如何操作?
请参考[Apollo使用指南](zh/usage/apollo-user-guide)
## 5. 我的应用需要不同机房的配置不一样,Apollo是否能支持?
Apollo是支持的。请参考[Apollo使用指南](zh/usage/apollo-user-guide)中的`三、集群独立配置说明`
## 6. 我有多个应用需要使用同一份配置,Apollo是否能支持?
Apollo是支持的。请参考[Apollo使用指南](zh/usage/apollo-user-guide)中的`四、多个AppId使用同一份配置`
## 7. Apollo是否支持查看权限控制或者配置加密?
从1.1.0版本开始,apollo-portal增加了查看权限的支持,可以支持配置某个环境只允许项目成员查看私有Namespace的配置。
这里的项目成员是指:
1. 项目的管理员
2. 具备该私有Namespace在该环境下的修改或发布权限
配置方式很简单,用超级管理员账号登录后,进入`管理员工具 - 系统参数`页面新增或修改`configView.memberOnly.envs`配置项即可。

配置加密可以参考[spring-boot-encrypt demo项目](https://github.com/ctripcorp/apollo-use-cases/tree/master/spring-boot-encrypt)
## 8. 如果有多个config server,打包时如何配置meta server地址?
有多台meta server可以通过nginx反向代理,通过一个域名代理多个meta server实现ha。
## 9. Apollo相比于Spring Cloud Config有什么优势?
Spring Cloud Config的精妙之处在于它的配置存储于Git,这就天然的把配置的修改、权限、版本等问题隔离在外。通过这个设计使得Spring Cloud Config整体很简单,不过也带来了一些不便之处。
下面尝试做一个简单的小结:
| 功能点 | Apollo | Spring Cloud Config | 备注 |
|------------------|--------------------------------------------|-------------------------------------------------|----------------------------------------------------------------------------|
| 配置界面 | 一个界面管理不同环境、不同集群配置 | 无,需要通过git操作 | |
| 配置生效时间 | 实时 | 重启生效,或手动refresh生效 | Spring Cloud Config需要通过Git webhook,加上额外的消息队列才能支持实时生效 |
| 版本管理 | 界面上直接提供发布历史和回滚按钮 | 无,需要通过git操作 | |
| 灰度发布 | 支持 | 不支持 | |
| 授权、审核、审计 | 界面上直接支持,而且支持修改、发布权限分离 | 需要通过git仓库设置,且不支持修改、发布权限分离 | |
| 实例配置监控 | 可以方便的看到当前哪些客户端在使用哪些配置 | 不支持 | |
| 配置获取性能 | 快,通过数据库访问,还有缓存支持 | 较慢,需要从git clone repository,然后从文件系统读取 | |
| 客户端支持 | 原生支持所有Java和.Net应用,提供API支持其它语言应用,同时也支持Spring annotation获取配置 | 支持Spring应用,提供annotation获取配置 | Apollo的适用范围更广一些 |
## 10. Apollo和Disconf相比有什么优点?
由于我们自己并非Disconf的资深用户,所以无法主观地给出评价。
不过之前Apollo技术支持群中的热心网友[@Krast](https://github.com/krast)做了一个[开源配置中心对比矩阵](https://github.com/ctripcorp/apollo/files/983064/default.pdf),可以参考一下。 | -1 |
apolloconfig/apollo | 3,679 | fix[apollo-configService]: Solve configService startup exception | ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | klboke | 2021-05-12T10:46:18Z | 2021-05-18T00:03:38Z | d60bf888c57dcea93568fdfa4ae3c5836f632d3d | 1cc8f5501fa037a449f560788b8deedb70bc6f62 | fix[apollo-configService]: Solve configService startup exception. ## What's the purpose of this PR
fix[apollo-configService]: Solve configService startup exception | ./apollo-client/src/test/java/com/ctrip/framework/apollo/internals/PropertiesConfigFileTest.java | package com.ctrip.framework.apollo.internals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.ConfigFileChangeListener;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.enums.PropertyChangeType;
import com.ctrip.framework.apollo.model.ConfigFileChangeEvent;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import com.google.common.util.concurrent.SettableFuture;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import org.mockito.stubbing.Answer;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@RunWith(MockitoJUnitRunner.class)
public class PropertiesConfigFileTest {
private String someNamespace;
@Mock
private ConfigRepository configRepository;
@Mock
private PropertiesFactory propertiesFactory;
@Before
public void setUp() throws Exception {
someNamespace = "someName";
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new Properties();
}
});
MockInjector.setInstance(PropertiesFactory.class, propertiesFactory);
}
@After
public void tearDown() throws Exception {
MockInjector.reset();
}
@Test
public void testWhenHasContent() throws Exception {
Properties someProperties = new Properties();
String someKey = "someKey";
String someValue = "someValue";
someProperties.setProperty(someKey, someValue);
when(configRepository.getConfig()).thenReturn(someProperties);
PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository);
assertEquals(ConfigFileFormat.Properties, configFile.getConfigFileFormat());
assertEquals(someNamespace, configFile.getNamespace());
assertTrue(configFile.hasContent());
assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue)));
}
@Test
public void testWhenHasNoContent() throws Exception {
when(configRepository.getConfig()).thenReturn(null);
PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository);
assertFalse(configFile.hasContent());
assertNull(configFile.getContent());
}
@Test
public void testWhenConfigRepositoryHasError() throws Exception {
when(configRepository.getConfig()).thenThrow(new RuntimeException("someError"));
PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository);
assertFalse(configFile.hasContent());
assertNull(configFile.getContent());
}
@Test
public void testOnRepositoryChange() throws Exception {
Properties someProperties = new Properties();
String someKey = "someKey";
String someValue = "someValue";
String anotherValue = "anotherValue";
someProperties.setProperty(someKey, someValue);
when(configRepository.getConfig()).thenReturn(someProperties);
PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository);
assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue)));
Properties anotherProperties = new Properties();
anotherProperties.setProperty(someKey, anotherValue);
final SettableFuture<ConfigFileChangeEvent> configFileChangeFuture = SettableFuture.create();
ConfigFileChangeListener someListener = new ConfigFileChangeListener() {
@Override
public void onChange(ConfigFileChangeEvent changeEvent) {
configFileChangeFuture.set(changeEvent);
}
};
configFile.addChangeListener(someListener);
configFile.onRepositoryChange(someNamespace, anotherProperties);
ConfigFileChangeEvent changeEvent = configFileChangeFuture.get(500, TimeUnit.MILLISECONDS);
assertFalse(configFile.getContent().contains(String.format("%s=%s", someKey, someValue)));
assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, anotherValue)));
assertEquals(someNamespace, changeEvent.getNamespace());
assertTrue(changeEvent.getOldValue().contains(String.format("%s=%s", someKey, someValue)));
assertTrue(changeEvent.getNewValue().contains(String.format("%s=%s", someKey, anotherValue)));
assertEquals(PropertyChangeType.MODIFIED, changeEvent.getChangeType());
}
@Test
public void testWhenConfigRepositoryHasErrorAndThenRecovered() throws Exception {
Properties someProperties = new Properties();
String someKey = "someKey";
String someValue = "someValue";
someProperties.setProperty(someKey, someValue);
when(configRepository.getConfig()).thenThrow(new RuntimeException("someError"));
PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository);
assertFalse(configFile.hasContent());
assertNull(configFile.getContent());
configFile.onRepositoryChange(someNamespace, someProperties);
assertTrue(configFile.hasContent());
assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue)));
}
}
| package com.ctrip.framework.apollo.internals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.ConfigFileChangeListener;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.enums.PropertyChangeType;
import com.ctrip.framework.apollo.model.ConfigFileChangeEvent;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import com.google.common.util.concurrent.SettableFuture;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import org.mockito.stubbing.Answer;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@RunWith(MockitoJUnitRunner.class)
public class PropertiesConfigFileTest {
private String someNamespace;
@Mock
private ConfigRepository configRepository;
@Mock
private PropertiesFactory propertiesFactory;
@Before
public void setUp() throws Exception {
someNamespace = "someName";
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new Properties();
}
});
MockInjector.setInstance(PropertiesFactory.class, propertiesFactory);
}
@After
public void tearDown() throws Exception {
MockInjector.reset();
}
@Test
public void testWhenHasContent() throws Exception {
Properties someProperties = new Properties();
String someKey = "someKey";
String someValue = "someValue";
someProperties.setProperty(someKey, someValue);
when(configRepository.getConfig()).thenReturn(someProperties);
PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository);
assertEquals(ConfigFileFormat.Properties, configFile.getConfigFileFormat());
assertEquals(someNamespace, configFile.getNamespace());
assertTrue(configFile.hasContent());
assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue)));
}
@Test
public void testWhenHasNoContent() throws Exception {
when(configRepository.getConfig()).thenReturn(null);
PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository);
assertFalse(configFile.hasContent());
assertNull(configFile.getContent());
}
@Test
public void testWhenConfigRepositoryHasError() throws Exception {
when(configRepository.getConfig()).thenThrow(new RuntimeException("someError"));
PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository);
assertFalse(configFile.hasContent());
assertNull(configFile.getContent());
}
@Test
public void testOnRepositoryChange() throws Exception {
Properties someProperties = new Properties();
String someKey = "someKey";
String someValue = "someValue";
String anotherValue = "anotherValue";
someProperties.setProperty(someKey, someValue);
when(configRepository.getConfig()).thenReturn(someProperties);
PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository);
assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue)));
Properties anotherProperties = new Properties();
anotherProperties.setProperty(someKey, anotherValue);
final SettableFuture<ConfigFileChangeEvent> configFileChangeFuture = SettableFuture.create();
ConfigFileChangeListener someListener = new ConfigFileChangeListener() {
@Override
public void onChange(ConfigFileChangeEvent changeEvent) {
configFileChangeFuture.set(changeEvent);
}
};
configFile.addChangeListener(someListener);
configFile.onRepositoryChange(someNamespace, anotherProperties);
ConfigFileChangeEvent changeEvent = configFileChangeFuture.get(500, TimeUnit.MILLISECONDS);
assertFalse(configFile.getContent().contains(String.format("%s=%s", someKey, someValue)));
assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, anotherValue)));
assertEquals(someNamespace, changeEvent.getNamespace());
assertTrue(changeEvent.getOldValue().contains(String.format("%s=%s", someKey, someValue)));
assertTrue(changeEvent.getNewValue().contains(String.format("%s=%s", someKey, anotherValue)));
assertEquals(PropertyChangeType.MODIFIED, changeEvent.getChangeType());
}
@Test
public void testWhenConfigRepositoryHasErrorAndThenRecovered() throws Exception {
Properties someProperties = new Properties();
String someKey = "someKey";
String someValue = "someValue";
someProperties.setProperty(someKey, someValue);
when(configRepository.getConfig()).thenThrow(new RuntimeException("someError"));
PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository);
assertFalse(configFile.hasContent());
assertNull(configFile.getContent());
configFile.onRepositoryChange(someNamespace, someProperties);
assertTrue(configFile.hasContent());
assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue)));
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigFile.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.ConfigFileChangeListener;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.enums.PropertyChangeType;
import com.ctrip.framework.apollo.model.ConfigFileChangeEvent;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import com.google.common.collect.Lists;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public abstract class AbstractConfigFile implements ConfigFile, RepositoryChangeListener {
private static final Logger logger = LoggerFactory.getLogger(AbstractConfigFile.class);
private static ExecutorService m_executorService;
protected final ConfigRepository m_configRepository;
protected final String m_namespace;
protected final AtomicReference<Properties> m_configProperties;
private final List<ConfigFileChangeListener> m_listeners = Lists.newCopyOnWriteArrayList();
protected final PropertiesFactory propertiesFactory;
private volatile ConfigSourceType m_sourceType = ConfigSourceType.NONE;
static {
m_executorService = Executors.newCachedThreadPool(ApolloThreadFactory
.create("ConfigFile", true));
}
public AbstractConfigFile(String namespace, ConfigRepository configRepository) {
m_configRepository = configRepository;
m_namespace = namespace;
m_configProperties = new AtomicReference<>();
propertiesFactory = ApolloInjector.getInstance(PropertiesFactory.class);
initialize();
}
private void initialize() {
try {
m_configProperties.set(m_configRepository.getConfig());
m_sourceType = m_configRepository.getSourceType();
} catch (Throwable ex) {
Tracer.logError(ex);
logger.warn("Init Apollo Config File failed - namespace: {}, reason: {}.",
m_namespace, ExceptionUtil.getDetailMessage(ex));
} finally {
//register the change listener no matter config repository is working or not
//so that whenever config repository is recovered, config could get changed
m_configRepository.addChangeListener(this);
}
}
@Override
public String getNamespace() {
return m_namespace;
}
protected abstract void update(Properties newProperties);
@Override
public synchronized void onRepositoryChange(String namespace, Properties newProperties) {
if (newProperties.equals(m_configProperties.get())) {
return;
}
Properties newConfigProperties = propertiesFactory.getPropertiesInstance();
newConfigProperties.putAll(newProperties);
String oldValue = getContent();
update(newProperties);
m_sourceType = m_configRepository.getSourceType();
String newValue = getContent();
PropertyChangeType changeType = PropertyChangeType.MODIFIED;
if (oldValue == null) {
changeType = PropertyChangeType.ADDED;
} else if (newValue == null) {
changeType = PropertyChangeType.DELETED;
}
this.fireConfigChange(new ConfigFileChangeEvent(m_namespace, oldValue, newValue, changeType));
Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace);
}
@Override
public void addChangeListener(ConfigFileChangeListener listener) {
if (!m_listeners.contains(listener)) {
m_listeners.add(listener);
}
}
@Override
public boolean removeChangeListener(ConfigFileChangeListener listener) {
return m_listeners.remove(listener);
}
@Override
public ConfigSourceType getSourceType() {
return m_sourceType;
}
private void fireConfigChange(final ConfigFileChangeEvent changeEvent) {
for (final ConfigFileChangeListener listener : m_listeners) {
m_executorService.submit(new Runnable() {
@Override
public void run() {
String listenerName = listener.getClass().getName();
Transaction transaction = Tracer.newTransaction("Apollo.ConfigFileChangeListener", listenerName);
try {
listener.onChange(changeEvent);
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
Tracer.logError(ex);
logger.error("Failed to invoke config file change listener {}", listenerName, ex);
} finally {
transaction.complete();
}
}
});
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.ConfigFileChangeListener;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.enums.PropertyChangeType;
import com.ctrip.framework.apollo.model.ConfigFileChangeEvent;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import com.google.common.collect.Lists;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public abstract class AbstractConfigFile implements ConfigFile, RepositoryChangeListener {
private static final Logger logger = DeferredLoggerFactory.getLogger(AbstractConfigFile.class);
private static ExecutorService m_executorService;
protected final ConfigRepository m_configRepository;
protected final String m_namespace;
protected final AtomicReference<Properties> m_configProperties;
private final List<ConfigFileChangeListener> m_listeners = Lists.newCopyOnWriteArrayList();
protected final PropertiesFactory propertiesFactory;
private volatile ConfigSourceType m_sourceType = ConfigSourceType.NONE;
static {
m_executorService = Executors.newCachedThreadPool(ApolloThreadFactory
.create("ConfigFile", true));
}
public AbstractConfigFile(String namespace, ConfigRepository configRepository) {
m_configRepository = configRepository;
m_namespace = namespace;
m_configProperties = new AtomicReference<>();
propertiesFactory = ApolloInjector.getInstance(PropertiesFactory.class);
initialize();
}
private void initialize() {
try {
m_configProperties.set(m_configRepository.getConfig());
m_sourceType = m_configRepository.getSourceType();
} catch (Throwable ex) {
Tracer.logError(ex);
logger.warn("Init Apollo Config File failed - namespace: {}, reason: {}.",
m_namespace, ExceptionUtil.getDetailMessage(ex));
} finally {
//register the change listener no matter config repository is working or not
//so that whenever config repository is recovered, config could get changed
m_configRepository.addChangeListener(this);
}
}
@Override
public String getNamespace() {
return m_namespace;
}
protected abstract void update(Properties newProperties);
@Override
public synchronized void onRepositoryChange(String namespace, Properties newProperties) {
if (newProperties.equals(m_configProperties.get())) {
return;
}
Properties newConfigProperties = propertiesFactory.getPropertiesInstance();
newConfigProperties.putAll(newProperties);
String oldValue = getContent();
update(newProperties);
m_sourceType = m_configRepository.getSourceType();
String newValue = getContent();
PropertyChangeType changeType = PropertyChangeType.MODIFIED;
if (oldValue == null) {
changeType = PropertyChangeType.ADDED;
} else if (newValue == null) {
changeType = PropertyChangeType.DELETED;
}
this.fireConfigChange(new ConfigFileChangeEvent(m_namespace, oldValue, newValue, changeType));
Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace);
}
@Override
public void addChangeListener(ConfigFileChangeListener listener) {
if (!m_listeners.contains(listener)) {
m_listeners.add(listener);
}
}
@Override
public boolean removeChangeListener(ConfigFileChangeListener listener) {
return m_listeners.remove(listener);
}
@Override
public ConfigSourceType getSourceType() {
return m_sourceType;
}
private void fireConfigChange(final ConfigFileChangeEvent changeEvent) {
for (final ConfigFileChangeListener listener : m_listeners) {
m_executorService.submit(new Runnable() {
@Override
public void run() {
String listenerName = listener.getClass().getName();
Transaction transaction = Tracer.newTransaction("Apollo.ConfigFileChangeListener", listenerName);
try {
listener.onChange(changeEvent);
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
Tracer.logError(ex);
logger.error("Failed to invoke config file change listener {}", listenerName, ex);
} finally {
transaction.complete();
}
}
});
}
}
}
| 1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfig.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
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.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil;
import com.ctrip.framework.apollo.enums.PropertyChangeType;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.RateLimiter;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class DefaultConfig extends AbstractConfig implements RepositoryChangeListener {
private static final Logger logger = LoggerFactory.getLogger(DefaultConfig.class);
private final String m_namespace;
private final Properties m_resourceProperties;
private final AtomicReference<Properties> m_configProperties;
private final ConfigRepository m_configRepository;
private final RateLimiter m_warnLogRateLimiter;
private volatile ConfigSourceType m_sourceType = ConfigSourceType.NONE;
/**
* Constructor.
*
* @param namespace the namespace of this config instance
* @param configRepository the config repository for this config instance
*/
public DefaultConfig(String namespace, ConfigRepository configRepository) {
m_namespace = namespace;
m_resourceProperties = loadFromResource(m_namespace);
m_configRepository = configRepository;
m_configProperties = new AtomicReference<>();
m_warnLogRateLimiter = RateLimiter.create(0.017); // 1 warning log output per minute
initialize();
}
private void initialize() {
try {
updateConfig(m_configRepository.getConfig(), m_configRepository.getSourceType());
} catch (Throwable ex) {
Tracer.logError(ex);
logger.warn("Init Apollo Local Config failed - namespace: {}, reason: {}.",
m_namespace, ExceptionUtil.getDetailMessage(ex));
} finally {
//register the change listener no matter config repository is working or not
//so that whenever config repository is recovered, config could get changed
m_configRepository.addChangeListener(this);
}
}
@Override
public String getProperty(String key, String defaultValue) {
// step 1: check system properties, i.e. -Dkey=value
String value = System.getProperty(key);
// step 2: check local cached properties file
if (value == null && m_configProperties.get() != null) {
value = m_configProperties.get().getProperty(key);
}
/**
* step 3: check env variable, i.e. PATH=...
* normally system environment variables are in UPPERCASE, however there might be exceptions.
* so the caller should provide the key in the right case
*/
if (value == null) {
value = System.getenv(key);
}
// step 4: check properties file from classpath
if (value == null && m_resourceProperties != null) {
value = m_resourceProperties.getProperty(key);
}
if (value == null && m_configProperties.get() == null && m_warnLogRateLimiter.tryAcquire()) {
logger.warn("Could not load config for namespace {} from Apollo, please check whether the configs are released in Apollo! Return default value now!", m_namespace);
}
return value == null ? defaultValue : value;
}
@Override
public Set<String> getPropertyNames() {
Properties properties = m_configProperties.get();
if (properties == null) {
return Collections.emptySet();
}
return stringPropertyNames(properties);
}
@Override
public ConfigSourceType getSourceType() {
return m_sourceType;
}
private Set<String> stringPropertyNames(Properties properties) {
//jdk9以下版本Properties#enumerateStringProperties方法存在性能问题,keys() + get(k) 重复迭代, jdk9之后改为entrySet遍历.
Map<String, String> h = new LinkedHashMap<>();
for (Map.Entry<Object, Object> e : properties.entrySet()) {
Object k = e.getKey();
Object v = e.getValue();
if (k instanceof String && v instanceof String) {
h.put((String) k, (String) v);
}
}
return h.keySet();
}
@Override
public synchronized void onRepositoryChange(String namespace, Properties newProperties) {
if (newProperties.equals(m_configProperties.get())) {
return;
}
ConfigSourceType sourceType = m_configRepository.getSourceType();
Properties newConfigProperties = propertiesFactory.getPropertiesInstance();
newConfigProperties.putAll(newProperties);
Map<String, ConfigChange> actualChanges = updateAndCalcConfigChanges(newConfigProperties, sourceType);
//check double checked result
if (actualChanges.isEmpty()) {
return;
}
this.fireConfigChange(new ConfigChangeEvent(m_namespace, actualChanges));
Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace);
}
private void updateConfig(Properties newConfigProperties, ConfigSourceType sourceType) {
m_configProperties.set(newConfigProperties);
m_sourceType = sourceType;
}
private Map<String, ConfigChange> updateAndCalcConfigChanges(Properties newConfigProperties,
ConfigSourceType sourceType) {
List<ConfigChange> configChanges =
calcPropertyChanges(m_namespace, m_configProperties.get(), newConfigProperties);
ImmutableMap.Builder<String, ConfigChange> actualChanges =
new ImmutableMap.Builder<>();
/** === Double check since DefaultConfig has multiple config sources ==== **/
//1. use getProperty to update configChanges's old value
for (ConfigChange change : configChanges) {
change.setOldValue(this.getProperty(change.getPropertyName(), change.getOldValue()));
}
//2. update m_configProperties
updateConfig(newConfigProperties, sourceType);
clearConfigCache();
//3. use getProperty to update configChange's new value and calc the final changes
for (ConfigChange change : configChanges) {
change.setNewValue(this.getProperty(change.getPropertyName(), change.getNewValue()));
switch (change.getChangeType()) {
case ADDED:
if (Objects.equals(change.getOldValue(), change.getNewValue())) {
break;
}
if (change.getOldValue() != null) {
change.setChangeType(PropertyChangeType.MODIFIED);
}
actualChanges.put(change.getPropertyName(), change);
break;
case MODIFIED:
if (!Objects.equals(change.getOldValue(), change.getNewValue())) {
actualChanges.put(change.getPropertyName(), change);
}
break;
case DELETED:
if (Objects.equals(change.getOldValue(), change.getNewValue())) {
break;
}
if (change.getNewValue() != null) {
change.setChangeType(PropertyChangeType.MODIFIED);
}
actualChanges.put(change.getPropertyName(), change);
break;
default:
//do nothing
break;
}
}
return actualChanges.build();
}
private Properties loadFromResource(String namespace) {
String name = String.format("META-INF/config/%s.properties", namespace);
InputStream in = ClassLoaderUtil.getLoader().getResourceAsStream(name);
Properties properties = null;
if (in != null) {
properties = propertiesFactory.getPropertiesInstance();
try {
properties.load(in);
} catch (IOException ex) {
Tracer.logError(ex);
logger.error("Load resource config for namespace {} failed", namespace, ex);
} finally {
try {
in.close();
} catch (IOException ex) {
// ignore
}
}
}
return properties;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
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.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil;
import com.ctrip.framework.apollo.enums.PropertyChangeType;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.RateLimiter;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class DefaultConfig extends AbstractConfig implements RepositoryChangeListener {
private static final Logger logger = DeferredLoggerFactory.getLogger(DefaultConfig.class);
private final String m_namespace;
private final Properties m_resourceProperties;
private final AtomicReference<Properties> m_configProperties;
private final ConfigRepository m_configRepository;
private final RateLimiter m_warnLogRateLimiter;
private volatile ConfigSourceType m_sourceType = ConfigSourceType.NONE;
/**
* Constructor.
*
* @param namespace the namespace of this config instance
* @param configRepository the config repository for this config instance
*/
public DefaultConfig(String namespace, ConfigRepository configRepository) {
m_namespace = namespace;
m_resourceProperties = loadFromResource(m_namespace);
m_configRepository = configRepository;
m_configProperties = new AtomicReference<>();
m_warnLogRateLimiter = RateLimiter.create(0.017); // 1 warning log output per minute
initialize();
}
private void initialize() {
try {
updateConfig(m_configRepository.getConfig(), m_configRepository.getSourceType());
} catch (Throwable ex) {
Tracer.logError(ex);
logger.warn("Init Apollo Local Config failed - namespace: {}, reason: {}.",
m_namespace, ExceptionUtil.getDetailMessage(ex));
} finally {
//register the change listener no matter config repository is working or not
//so that whenever config repository is recovered, config could get changed
m_configRepository.addChangeListener(this);
}
}
@Override
public String getProperty(String key, String defaultValue) {
// step 1: check system properties, i.e. -Dkey=value
String value = System.getProperty(key);
// step 2: check local cached properties file
if (value == null && m_configProperties.get() != null) {
value = m_configProperties.get().getProperty(key);
}
/**
* step 3: check env variable, i.e. PATH=...
* normally system environment variables are in UPPERCASE, however there might be exceptions.
* so the caller should provide the key in the right case
*/
if (value == null) {
value = System.getenv(key);
}
// step 4: check properties file from classpath
if (value == null && m_resourceProperties != null) {
value = m_resourceProperties.getProperty(key);
}
if (value == null && m_configProperties.get() == null && m_warnLogRateLimiter.tryAcquire()) {
logger.warn(
"Could not load config for namespace {} from Apollo, please check whether the configs are released in Apollo! Return default value now!",
m_namespace);
}
return value == null ? defaultValue : value;
}
@Override
public Set<String> getPropertyNames() {
Properties properties = m_configProperties.get();
if (properties == null) {
return Collections.emptySet();
}
return stringPropertyNames(properties);
}
@Override
public ConfigSourceType getSourceType() {
return m_sourceType;
}
private Set<String> stringPropertyNames(Properties properties) {
//jdk9以下版本Properties#enumerateStringProperties方法存在性能问题,keys() + get(k) 重复迭代, jdk9之后改为entrySet遍历.
Map<String, String> h = new LinkedHashMap<>();
for (Map.Entry<Object, Object> e : properties.entrySet()) {
Object k = e.getKey();
Object v = e.getValue();
if (k instanceof String && v instanceof String) {
h.put((String) k, (String) v);
}
}
return h.keySet();
}
@Override
public synchronized void onRepositoryChange(String namespace, Properties newProperties) {
if (newProperties.equals(m_configProperties.get())) {
return;
}
ConfigSourceType sourceType = m_configRepository.getSourceType();
Properties newConfigProperties = propertiesFactory.getPropertiesInstance();
newConfigProperties.putAll(newProperties);
Map<String, ConfigChange> actualChanges = updateAndCalcConfigChanges(newConfigProperties,
sourceType);
//check double checked result
if (actualChanges.isEmpty()) {
return;
}
this.fireConfigChange(new ConfigChangeEvent(m_namespace, actualChanges));
Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace);
}
private void updateConfig(Properties newConfigProperties, ConfigSourceType sourceType) {
m_configProperties.set(newConfigProperties);
m_sourceType = sourceType;
}
private Map<String, ConfigChange> updateAndCalcConfigChanges(Properties newConfigProperties,
ConfigSourceType sourceType) {
List<ConfigChange> configChanges =
calcPropertyChanges(m_namespace, m_configProperties.get(), newConfigProperties);
ImmutableMap.Builder<String, ConfigChange> actualChanges =
new ImmutableMap.Builder<>();
/** === Double check since DefaultConfig has multiple config sources ==== **/
//1. use getProperty to update configChanges's old value
for (ConfigChange change : configChanges) {
change.setOldValue(this.getProperty(change.getPropertyName(), change.getOldValue()));
}
//2. update m_configProperties
updateConfig(newConfigProperties, sourceType);
clearConfigCache();
//3. use getProperty to update configChange's new value and calc the final changes
for (ConfigChange change : configChanges) {
change.setNewValue(this.getProperty(change.getPropertyName(), change.getNewValue()));
switch (change.getChangeType()) {
case ADDED:
if (Objects.equals(change.getOldValue(), change.getNewValue())) {
break;
}
if (change.getOldValue() != null) {
change.setChangeType(PropertyChangeType.MODIFIED);
}
actualChanges.put(change.getPropertyName(), change);
break;
case MODIFIED:
if (!Objects.equals(change.getOldValue(), change.getNewValue())) {
actualChanges.put(change.getPropertyName(), change);
}
break;
case DELETED:
if (Objects.equals(change.getOldValue(), change.getNewValue())) {
break;
}
if (change.getNewValue() != null) {
change.setChangeType(PropertyChangeType.MODIFIED);
}
actualChanges.put(change.getPropertyName(), change);
break;
default:
//do nothing
break;
}
}
return actualChanges.build();
}
private Properties loadFromResource(String namespace) {
String name = String.format("META-INF/config/%s.properties", namespace);
InputStream in = ClassLoaderUtil.getLoader().getResourceAsStream(name);
Properties properties = null;
if (in != null) {
properties = propertiesFactory.getPropertiesInstance();
try {
properties.load(in);
} catch (IOException ex) {
Tracer.logError(ex);
logger.error("Load resource config for namespace {} failed", namespace, ex);
} finally {
try {
in.close();
} catch (IOException ex) {
// ignore
}
}
}
return properties;
}
}
| 1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProvider.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.core.spi.MetaServerProvider;
import com.ctrip.framework.foundation.Foundation;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultMetaServerProvider implements MetaServerProvider {
public static final int ORDER = 0;
private static final Logger logger = LoggerFactory.getLogger(DefaultMetaServerProvider.class);
private final String metaServerAddress;
public DefaultMetaServerProvider() {
metaServerAddress = initMetaServerAddress();
}
private String initMetaServerAddress() {
// 1. Get from System Property
String metaAddress = System.getProperty(ConfigConsts.APOLLO_META_KEY);
if (Strings.isNullOrEmpty(metaAddress)) {
// 2. Get from OS environment variable, which could not contain dot and is normally in UPPER case
metaAddress = System.getenv("APOLLO_META");
}
if (Strings.isNullOrEmpty(metaAddress)) {
// 3. Get from server.properties
metaAddress = Foundation.server().getProperty(ConfigConsts.APOLLO_META_KEY, null);
}
if (Strings.isNullOrEmpty(metaAddress)) {
// 4. Get from app.properties
metaAddress = Foundation.app().getProperty(ConfigConsts.APOLLO_META_KEY, null);
}
if (Strings.isNullOrEmpty(metaAddress)) {
logger.warn("Could not find meta server address, because it is not available in neither (1) JVM system property 'apollo.meta', (2) OS env variable 'APOLLO_META' (3) property 'apollo.meta' from server.properties nor (4) property 'apollo.meta' from app.properties");
} else {
metaAddress = metaAddress.trim();
logger.info("Located meta services from apollo.meta configuration: {}!", metaAddress);
}
return metaAddress;
}
@Override
public String getMetaServerAddress(Env targetEnv) {
//for default meta server provider, we don't care the actual environment
return metaServerAddress;
}
@Override
public int getOrder() {
return ORDER;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.core.spi.MetaServerProvider;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import com.ctrip.framework.foundation.Foundation;
import com.google.common.base.Strings;
import org.slf4j.Logger;
public class DefaultMetaServerProvider implements MetaServerProvider {
public static final int ORDER = 0;
private static final Logger logger = DeferredLoggerFactory
.getLogger(DefaultMetaServerProvider.class);
private final String metaServerAddress;
public DefaultMetaServerProvider() {
metaServerAddress = initMetaServerAddress();
}
private String initMetaServerAddress() {
// 1. Get from System Property
String metaAddress = System.getProperty(ConfigConsts.APOLLO_META_KEY);
if (Strings.isNullOrEmpty(metaAddress)) {
// 2. Get from OS environment variable, which could not contain dot and is normally in UPPER case
metaAddress = System.getenv("APOLLO_META");
}
if (Strings.isNullOrEmpty(metaAddress)) {
// 3. Get from server.properties
metaAddress = Foundation.server().getProperty(ConfigConsts.APOLLO_META_KEY, null);
}
if (Strings.isNullOrEmpty(metaAddress)) {
// 4. Get from app.properties
metaAddress = Foundation.app().getProperty(ConfigConsts.APOLLO_META_KEY, null);
}
if (Strings.isNullOrEmpty(metaAddress)) {
logger.warn(
"Could not find meta server address, because it is not available in neither (1) JVM system property 'apollo.meta', (2) OS env variable 'APOLLO_META' (3) property 'apollo.meta' from server.properties nor (4) property 'apollo.meta' from app.properties");
} else {
metaAddress = metaAddress.trim();
logger.info("Located meta services from apollo.meta configuration: {}!", metaAddress);
}
return metaAddress;
}
@Override
public String getMetaServerAddress(Env targetEnv) {
//for default meta server provider, we don't care the actual environment
return metaServerAddress;
}
@Override
public int getOrder() {
return ORDER;
}
}
| 1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepository.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class LocalFileConfigRepository extends AbstractConfigRepository
implements RepositoryChangeListener {
private static final Logger logger = LoggerFactory.getLogger(LocalFileConfigRepository.class);
private static final String CONFIG_DIR = "/config-cache";
private final String m_namespace;
private File m_baseDir;
private final ConfigUtil m_configUtil;
private volatile Properties m_fileProperties;
private volatile ConfigRepository m_upstream;
private volatile ConfigSourceType m_sourceType = ConfigSourceType.LOCAL;
/**
* Constructor.
*
* @param namespace the namespace
*/
public LocalFileConfigRepository(String namespace) {
this(namespace, null);
}
public LocalFileConfigRepository(String namespace, ConfigRepository upstream) {
m_namespace = namespace;
m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
this.setLocalCacheDir(findLocalCacheDir(), false);
this.setUpstreamRepository(upstream);
this.trySync();
}
void setLocalCacheDir(File baseDir, boolean syncImmediately) {
m_baseDir = baseDir;
this.checkLocalConfigCacheDir(m_baseDir);
if (syncImmediately) {
this.trySync();
}
}
private File findLocalCacheDir() {
try {
String defaultCacheDir = m_configUtil.getDefaultLocalCacheDir();
Path path = Paths.get(defaultCacheDir);
if (!Files.exists(path)) {
Files.createDirectories(path);
}
if (Files.exists(path) && Files.isWritable(path)) {
return new File(defaultCacheDir, CONFIG_DIR);
}
} catch (Throwable ex) {
//ignore
}
return new File(ClassLoaderUtil.getClassPath(), CONFIG_DIR);
}
@Override
public Properties getConfig() {
if (m_fileProperties == null) {
sync();
}
Properties result = propertiesFactory.getPropertiesInstance();
result.putAll(m_fileProperties);
return result;
}
@Override
public void setUpstreamRepository(ConfigRepository upstreamConfigRepository) {
if (upstreamConfigRepository == null) {
return;
}
//clear previous listener
if (m_upstream != null) {
m_upstream.removeChangeListener(this);
}
m_upstream = upstreamConfigRepository;
upstreamConfigRepository.addChangeListener(this);
}
@Override
public ConfigSourceType getSourceType() {
return m_sourceType;
}
@Override
public void onRepositoryChange(String namespace, Properties newProperties) {
if (newProperties.equals(m_fileProperties)) {
return;
}
Properties newFileProperties = propertiesFactory.getPropertiesInstance();
newFileProperties.putAll(newProperties);
updateFileProperties(newFileProperties, m_upstream.getSourceType());
this.fireRepositoryChange(namespace, newProperties);
}
@Override
protected void sync() {
//sync with upstream immediately
boolean syncFromUpstreamResultSuccess = trySyncFromUpstream();
if (syncFromUpstreamResultSuccess) {
return;
}
Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "syncLocalConfig");
Throwable exception = null;
try {
transaction.addData("Basedir", m_baseDir.getAbsolutePath());
m_fileProperties = this.loadFromLocalCacheFile(m_baseDir, m_namespace);
m_sourceType = ConfigSourceType.LOCAL;
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
transaction.setStatus(ex);
exception = ex;
//ignore
} finally {
transaction.complete();
}
if (m_fileProperties == null) {
m_sourceType = ConfigSourceType.NONE;
throw new ApolloConfigException(
"Load config from local config failed!", exception);
}
}
private boolean trySyncFromUpstream() {
if (m_upstream == null) {
return false;
}
try {
updateFileProperties(m_upstream.getConfig(), m_upstream.getSourceType());
return true;
} catch (Throwable ex) {
Tracer.logError(ex);
logger
.warn("Sync config from upstream repository {} failed, reason: {}", m_upstream.getClass(),
ExceptionUtil.getDetailMessage(ex));
}
return false;
}
private synchronized void updateFileProperties(Properties newProperties, ConfigSourceType sourceType) {
this.m_sourceType = sourceType;
if (newProperties.equals(m_fileProperties)) {
return;
}
this.m_fileProperties = newProperties;
persistLocalCacheFile(m_baseDir, m_namespace);
}
private Properties loadFromLocalCacheFile(File baseDir, String namespace) throws IOException {
Preconditions.checkNotNull(baseDir, "Basedir cannot be null");
File file = assembleLocalCacheFile(baseDir, namespace);
Properties properties = null;
if (file.isFile() && file.canRead()) {
InputStream in = null;
try {
in = new FileInputStream(file);
properties = propertiesFactory.getPropertiesInstance();
properties.load(in);
logger.debug("Loading local config file {} successfully!", file.getAbsolutePath());
} catch (IOException ex) {
Tracer.logError(ex);
throw new ApolloConfigException(String
.format("Loading config from local cache file %s failed", file.getAbsolutePath()), ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
// ignore
}
}
} else {
throw new ApolloConfigException(
String.format("Cannot read from local cache file %s", file.getAbsolutePath()));
}
return properties;
}
void persistLocalCacheFile(File baseDir, String namespace) {
if (baseDir == null) {
return;
}
File file = assembleLocalCacheFile(baseDir, namespace);
OutputStream out = null;
Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "persistLocalConfigFile");
transaction.addData("LocalConfigFile", file.getAbsolutePath());
try {
out = new FileOutputStream(file);
m_fileProperties.store(out, "Persisted by DefaultConfig");
transaction.setStatus(Transaction.SUCCESS);
} catch (IOException ex) {
ApolloConfigException exception =
new ApolloConfigException(
String.format("Persist local cache file %s failed", file.getAbsolutePath()), ex);
Tracer.logError(exception);
transaction.setStatus(exception);
logger.warn("Persist local cache file {} failed, reason: {}.", file.getAbsolutePath(),
ExceptionUtil.getDetailMessage(ex));
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ex) {
//ignore
}
}
transaction.complete();
}
}
private void checkLocalConfigCacheDir(File baseDir) {
if (baseDir.exists()) {
return;
}
Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "createLocalConfigDir");
transaction.addData("BaseDir", baseDir.getAbsolutePath());
try {
Files.createDirectory(baseDir.toPath());
transaction.setStatus(Transaction.SUCCESS);
} catch (IOException ex) {
ApolloConfigException exception =
new ApolloConfigException(
String.format("Create local config directory %s failed", baseDir.getAbsolutePath()),
ex);
Tracer.logError(exception);
transaction.setStatus(exception);
logger.warn(
"Unable to create local config cache directory {}, reason: {}. Will not able to cache config file.",
baseDir.getAbsolutePath(), ExceptionUtil.getDetailMessage(ex));
} finally {
transaction.complete();
}
}
File assembleLocalCacheFile(File baseDir, String namespace) {
String fileName =
String.format("%s.properties", Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR)
.join(m_configUtil.getAppId(), m_configUtil.getCluster(), namespace));
return new File(baseDir, fileName);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import org.slf4j.Logger;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class LocalFileConfigRepository extends AbstractConfigRepository
implements RepositoryChangeListener {
private static final Logger logger = DeferredLoggerFactory.getLogger(LocalFileConfigRepository.class);
private static final String CONFIG_DIR = "/config-cache";
private final String m_namespace;
private File m_baseDir;
private final ConfigUtil m_configUtil;
private volatile Properties m_fileProperties;
private volatile ConfigRepository m_upstream;
private volatile ConfigSourceType m_sourceType = ConfigSourceType.LOCAL;
/**
* Constructor.
*
* @param namespace the namespace
*/
public LocalFileConfigRepository(String namespace) {
this(namespace, null);
}
public LocalFileConfigRepository(String namespace, ConfigRepository upstream) {
m_namespace = namespace;
m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
this.setLocalCacheDir(findLocalCacheDir(), false);
this.setUpstreamRepository(upstream);
this.trySync();
}
void setLocalCacheDir(File baseDir, boolean syncImmediately) {
m_baseDir = baseDir;
this.checkLocalConfigCacheDir(m_baseDir);
if (syncImmediately) {
this.trySync();
}
}
private File findLocalCacheDir() {
try {
String defaultCacheDir = m_configUtil.getDefaultLocalCacheDir();
Path path = Paths.get(defaultCacheDir);
if (!Files.exists(path)) {
Files.createDirectories(path);
}
if (Files.exists(path) && Files.isWritable(path)) {
return new File(defaultCacheDir, CONFIG_DIR);
}
} catch (Throwable ex) {
//ignore
}
return new File(ClassLoaderUtil.getClassPath(), CONFIG_DIR);
}
@Override
public Properties getConfig() {
if (m_fileProperties == null) {
sync();
}
Properties result = propertiesFactory.getPropertiesInstance();
result.putAll(m_fileProperties);
return result;
}
@Override
public void setUpstreamRepository(ConfigRepository upstreamConfigRepository) {
if (upstreamConfigRepository == null) {
return;
}
//clear previous listener
if (m_upstream != null) {
m_upstream.removeChangeListener(this);
}
m_upstream = upstreamConfigRepository;
upstreamConfigRepository.addChangeListener(this);
}
@Override
public ConfigSourceType getSourceType() {
return m_sourceType;
}
@Override
public void onRepositoryChange(String namespace, Properties newProperties) {
if (newProperties.equals(m_fileProperties)) {
return;
}
Properties newFileProperties = propertiesFactory.getPropertiesInstance();
newFileProperties.putAll(newProperties);
updateFileProperties(newFileProperties, m_upstream.getSourceType());
this.fireRepositoryChange(namespace, newProperties);
}
@Override
protected void sync() {
//sync with upstream immediately
boolean syncFromUpstreamResultSuccess = trySyncFromUpstream();
if (syncFromUpstreamResultSuccess) {
return;
}
Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "syncLocalConfig");
Throwable exception = null;
try {
transaction.addData("Basedir", m_baseDir.getAbsolutePath());
m_fileProperties = this.loadFromLocalCacheFile(m_baseDir, m_namespace);
m_sourceType = ConfigSourceType.LOCAL;
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
transaction.setStatus(ex);
exception = ex;
//ignore
} finally {
transaction.complete();
}
if (m_fileProperties == null) {
m_sourceType = ConfigSourceType.NONE;
throw new ApolloConfigException(
"Load config from local config failed!", exception);
}
}
private boolean trySyncFromUpstream() {
if (m_upstream == null) {
return false;
}
try {
updateFileProperties(m_upstream.getConfig(), m_upstream.getSourceType());
return true;
} catch (Throwable ex) {
Tracer.logError(ex);
logger
.warn("Sync config from upstream repository {} failed, reason: {}", m_upstream.getClass(),
ExceptionUtil.getDetailMessage(ex));
}
return false;
}
private synchronized void updateFileProperties(Properties newProperties, ConfigSourceType sourceType) {
this.m_sourceType = sourceType;
if (newProperties.equals(m_fileProperties)) {
return;
}
this.m_fileProperties = newProperties;
persistLocalCacheFile(m_baseDir, m_namespace);
}
private Properties loadFromLocalCacheFile(File baseDir, String namespace) throws IOException {
Preconditions.checkNotNull(baseDir, "Basedir cannot be null");
File file = assembleLocalCacheFile(baseDir, namespace);
Properties properties = null;
if (file.isFile() && file.canRead()) {
InputStream in = null;
try {
in = new FileInputStream(file);
properties = propertiesFactory.getPropertiesInstance();
properties.load(in);
logger.debug("Loading local config file {} successfully!", file.getAbsolutePath());
} catch (IOException ex) {
Tracer.logError(ex);
throw new ApolloConfigException(String
.format("Loading config from local cache file %s failed", file.getAbsolutePath()), ex);
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
// ignore
}
}
} else {
throw new ApolloConfigException(
String.format("Cannot read from local cache file %s", file.getAbsolutePath()));
}
return properties;
}
void persistLocalCacheFile(File baseDir, String namespace) {
if (baseDir == null) {
return;
}
File file = assembleLocalCacheFile(baseDir, namespace);
OutputStream out = null;
Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "persistLocalConfigFile");
transaction.addData("LocalConfigFile", file.getAbsolutePath());
try {
out = new FileOutputStream(file);
m_fileProperties.store(out, "Persisted by DefaultConfig");
transaction.setStatus(Transaction.SUCCESS);
} catch (IOException ex) {
ApolloConfigException exception =
new ApolloConfigException(
String.format("Persist local cache file %s failed", file.getAbsolutePath()), ex);
Tracer.logError(exception);
transaction.setStatus(exception);
logger.warn("Persist local cache file {} failed, reason: {}.", file.getAbsolutePath(),
ExceptionUtil.getDetailMessage(ex));
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ex) {
//ignore
}
}
transaction.complete();
}
}
private void checkLocalConfigCacheDir(File baseDir) {
if (baseDir.exists()) {
return;
}
Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "createLocalConfigDir");
transaction.addData("BaseDir", baseDir.getAbsolutePath());
try {
Files.createDirectory(baseDir.toPath());
transaction.setStatus(Transaction.SUCCESS);
} catch (IOException ex) {
ApolloConfigException exception =
new ApolloConfigException(
String.format("Create local config directory %s failed", baseDir.getAbsolutePath()),
ex);
Tracer.logError(exception);
transaction.setStatus(exception);
logger.warn(
"Unable to create local config cache directory {}, reason: {}. Will not able to cache config file.",
baseDir.getAbsolutePath(), ExceptionUtil.getDetailMessage(ex));
} finally {
transaction.complete();
}
}
File assembleLocalCacheFile(File baseDir, String namespace) {
String fileName =
String.format("%s.properties", Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR)
.join(m_configUtil.getAppId(), m_configUtil.getCluster(), namespace));
return new File(baseDir, fileName);
}
}
| 1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.Apollo;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.ctrip.framework.apollo.core.dto.ApolloNotificationMessages;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.ctrip.framework.apollo.core.schedule.ExponentialSchedulePolicy;
import com.ctrip.framework.apollo.core.schedule.SchedulePolicy;
import com.ctrip.framework.apollo.core.signature.Signature;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import com.ctrip.framework.apollo.util.http.HttpRequest;
import com.ctrip.framework.apollo.util.http.HttpResponse;
import com.ctrip.framework.apollo.util.http.HttpClient;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.escape.Escaper;
import com.google.common.net.UrlEscapers;
import com.google.common.util.concurrent.RateLimiter;
import com.google.gson.Gson;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class RemoteConfigRepository extends AbstractConfigRepository {
private static final Logger logger = LoggerFactory.getLogger(RemoteConfigRepository.class);
private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR);
private static final Joiner.MapJoiner MAP_JOINER = Joiner.on("&").withKeyValueSeparator("=");
private static final Escaper pathEscaper = UrlEscapers.urlPathSegmentEscaper();
private static final Escaper queryParamEscaper = UrlEscapers.urlFormParameterEscaper();
private final ConfigServiceLocator m_serviceLocator;
private final HttpClient m_httpClient;
private final ConfigUtil m_configUtil;
private final RemoteConfigLongPollService remoteConfigLongPollService;
private volatile AtomicReference<ApolloConfig> m_configCache;
private final String m_namespace;
private final static ScheduledExecutorService m_executorService;
private final AtomicReference<ServiceDTO> m_longPollServiceDto;
private final AtomicReference<ApolloNotificationMessages> m_remoteMessages;
private final RateLimiter m_loadConfigRateLimiter;
private final AtomicBoolean m_configNeedForceRefresh;
private final SchedulePolicy m_loadConfigFailSchedulePolicy;
private static final Gson GSON = new Gson();
static {
m_executorService = Executors.newScheduledThreadPool(1,
ApolloThreadFactory.create("RemoteConfigRepository", true));
}
/**
* Constructor.
*
* @param namespace the namespace
*/
public RemoteConfigRepository(String namespace) {
m_namespace = namespace;
m_configCache = new AtomicReference<>();
m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
m_httpClient = ApolloInjector.getInstance(HttpClient.class);
m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
remoteConfigLongPollService = ApolloInjector.getInstance(RemoteConfigLongPollService.class);
m_longPollServiceDto = new AtomicReference<>();
m_remoteMessages = new AtomicReference<>();
m_loadConfigRateLimiter = RateLimiter.create(m_configUtil.getLoadConfigQPS());
m_configNeedForceRefresh = new AtomicBoolean(true);
m_loadConfigFailSchedulePolicy = new ExponentialSchedulePolicy(m_configUtil.getOnErrorRetryInterval(),
m_configUtil.getOnErrorRetryInterval() * 8);
this.trySync();
this.schedulePeriodicRefresh();
this.scheduleLongPollingRefresh();
}
@Override
public Properties getConfig() {
if (m_configCache.get() == null) {
this.sync();
}
return transformApolloConfigToProperties(m_configCache.get());
}
@Override
public void setUpstreamRepository(ConfigRepository upstreamConfigRepository) {
//remote config doesn't need upstream
}
@Override
public ConfigSourceType getSourceType() {
return ConfigSourceType.REMOTE;
}
private void schedulePeriodicRefresh() {
logger.debug("Schedule periodic refresh with interval: {} {}",
m_configUtil.getRefreshInterval(), m_configUtil.getRefreshIntervalTimeUnit());
m_executorService.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
Tracer.logEvent("Apollo.ConfigService", String.format("periodicRefresh: %s", m_namespace));
logger.debug("refresh config for namespace: {}", m_namespace);
trySync();
Tracer.logEvent("Apollo.Client.Version", Apollo.VERSION);
}
}, m_configUtil.getRefreshInterval(), m_configUtil.getRefreshInterval(),
m_configUtil.getRefreshIntervalTimeUnit());
}
@Override
protected synchronized void sync() {
Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "syncRemoteConfig");
try {
ApolloConfig previous = m_configCache.get();
ApolloConfig current = loadApolloConfig();
//reference equals means HTTP 304
if (previous != current) {
logger.debug("Remote Config refreshed!");
m_configCache.set(current);
this.fireRepositoryChange(m_namespace, this.getConfig());
}
if (current != null) {
Tracer.logEvent(String.format("Apollo.Client.Configs.%s", current.getNamespaceName()),
current.getReleaseKey());
}
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
throw ex;
} finally {
transaction.complete();
}
}
private Properties transformApolloConfigToProperties(ApolloConfig apolloConfig) {
Properties result = propertiesFactory.getPropertiesInstance();
result.putAll(apolloConfig.getConfigurations());
return result;
}
private ApolloConfig loadApolloConfig() {
if (!m_loadConfigRateLimiter.tryAcquire(5, TimeUnit.SECONDS)) {
//wait at most 5 seconds
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
}
}
String appId = m_configUtil.getAppId();
String cluster = m_configUtil.getCluster();
String dataCenter = m_configUtil.getDataCenter();
String secret = m_configUtil.getAccessKeySecret();
Tracer.logEvent("Apollo.Client.ConfigMeta", STRING_JOINER.join(appId, cluster, m_namespace));
int maxRetries = m_configNeedForceRefresh.get() ? 2 : 1;
long onErrorSleepTime = 0; // 0 means no sleep
Throwable exception = null;
List<ServiceDTO> configServices = getConfigServices();
String url = null;
retryLoopLabel:
for (int i = 0; i < maxRetries; i++) {
List<ServiceDTO> randomConfigServices = Lists.newLinkedList(configServices);
Collections.shuffle(randomConfigServices);
//Access the server which notifies the client first
if (m_longPollServiceDto.get() != null) {
randomConfigServices.add(0, m_longPollServiceDto.getAndSet(null));
}
for (ServiceDTO configService : randomConfigServices) {
if (onErrorSleepTime > 0) {
logger.warn(
"Load config failed, will retry in {} {}. appId: {}, cluster: {}, namespaces: {}",
onErrorSleepTime, m_configUtil.getOnErrorRetryIntervalTimeUnit(), appId, cluster, m_namespace);
try {
m_configUtil.getOnErrorRetryIntervalTimeUnit().sleep(onErrorSleepTime);
} catch (InterruptedException e) {
//ignore
}
}
url = assembleQueryConfigUrl(configService.getHomepageUrl(), appId, cluster, m_namespace,
dataCenter, m_remoteMessages.get(), m_configCache.get());
logger.debug("Loading config from {}", url);
HttpRequest request = new HttpRequest(url);
if (!StringUtils.isBlank(secret)) {
Map<String, String> headers = Signature.buildHttpHeaders(url, appId, secret);
request.setHeaders(headers);
}
Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "queryConfig");
transaction.addData("Url", url);
try {
HttpResponse<ApolloConfig> response = m_httpClient.doGet(request, ApolloConfig.class);
m_configNeedForceRefresh.set(false);
m_loadConfigFailSchedulePolicy.success();
transaction.addData("StatusCode", response.getStatusCode());
transaction.setStatus(Transaction.SUCCESS);
if (response.getStatusCode() == 304) {
logger.debug("Config server responds with 304 HTTP status code.");
return m_configCache.get();
}
ApolloConfig result = response.getBody();
logger.debug("Loaded config for {}: {}", m_namespace, result);
return result;
} catch (ApolloConfigStatusCodeException ex) {
ApolloConfigStatusCodeException statusCodeException = ex;
//config not found
if (ex.getStatusCode() == 404) {
String message = String.format(
"Could not find config for namespace - appId: %s, cluster: %s, namespace: %s, " +
"please check whether the configs are released in Apollo!",
appId, cluster, m_namespace);
statusCodeException = new ApolloConfigStatusCodeException(ex.getStatusCode(),
message);
}
Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(statusCodeException));
transaction.setStatus(statusCodeException);
exception = statusCodeException;
if(ex.getStatusCode() == 404) {
break retryLoopLabel;
}
} catch (Throwable ex) {
Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
transaction.setStatus(ex);
exception = ex;
} finally {
transaction.complete();
}
// if force refresh, do normal sleep, if normal config load, do exponential sleep
onErrorSleepTime = m_configNeedForceRefresh.get() ? m_configUtil.getOnErrorRetryInterval() :
m_loadConfigFailSchedulePolicy.fail();
}
}
String message = String.format(
"Load Apollo Config failed - appId: %s, cluster: %s, namespace: %s, url: %s",
appId, cluster, m_namespace, url);
throw new ApolloConfigException(message, exception);
}
String assembleQueryConfigUrl(String uri, String appId, String cluster, String namespace,
String dataCenter, ApolloNotificationMessages remoteMessages, ApolloConfig previousConfig) {
String path = "configs/%s/%s/%s";
List<String> pathParams =
Lists.newArrayList(pathEscaper.escape(appId), pathEscaper.escape(cluster),
pathEscaper.escape(namespace));
Map<String, String> queryParams = Maps.newHashMap();
if (previousConfig != null) {
queryParams.put("releaseKey", queryParamEscaper.escape(previousConfig.getReleaseKey()));
}
if (!Strings.isNullOrEmpty(dataCenter)) {
queryParams.put("dataCenter", queryParamEscaper.escape(dataCenter));
}
String localIp = m_configUtil.getLocalIp();
if (!Strings.isNullOrEmpty(localIp)) {
queryParams.put("ip", queryParamEscaper.escape(localIp));
}
if (remoteMessages != null) {
queryParams.put("messages", queryParamEscaper.escape(GSON.toJson(remoteMessages)));
}
String pathExpanded = String.format(path, pathParams.toArray());
if (!queryParams.isEmpty()) {
pathExpanded += "?" + MAP_JOINER.join(queryParams);
}
if (!uri.endsWith("/")) {
uri += "/";
}
return uri + pathExpanded;
}
private void scheduleLongPollingRefresh() {
remoteConfigLongPollService.submit(m_namespace, this);
}
public void onLongPollNotified(ServiceDTO longPollNotifiedServiceDto, ApolloNotificationMessages remoteMessages) {
m_longPollServiceDto.set(longPollNotifiedServiceDto);
m_remoteMessages.set(remoteMessages);
m_executorService.submit(new Runnable() {
@Override
public void run() {
m_configNeedForceRefresh.set(true);
trySync();
}
});
}
private List<ServiceDTO> getConfigServices() {
List<ServiceDTO> services = m_serviceLocator.getConfigServices();
if (services.size() == 0) {
throw new ApolloConfigException("No available config service");
}
return services;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.Apollo;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.ctrip.framework.apollo.core.dto.ApolloNotificationMessages;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.ctrip.framework.apollo.core.schedule.ExponentialSchedulePolicy;
import com.ctrip.framework.apollo.core.schedule.SchedulePolicy;
import com.ctrip.framework.apollo.core.signature.Signature;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import com.ctrip.framework.apollo.util.http.HttpRequest;
import com.ctrip.framework.apollo.util.http.HttpResponse;
import com.ctrip.framework.apollo.util.http.HttpClient;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.escape.Escaper;
import com.google.common.net.UrlEscapers;
import com.google.common.util.concurrent.RateLimiter;
import com.google.gson.Gson;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class RemoteConfigRepository extends AbstractConfigRepository {
private static final Logger logger = DeferredLoggerFactory.getLogger(RemoteConfigRepository.class);
private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR);
private static final Joiner.MapJoiner MAP_JOINER = Joiner.on("&").withKeyValueSeparator("=");
private static final Escaper pathEscaper = UrlEscapers.urlPathSegmentEscaper();
private static final Escaper queryParamEscaper = UrlEscapers.urlFormParameterEscaper();
private final ConfigServiceLocator m_serviceLocator;
private final HttpClient m_httpClient;
private final ConfigUtil m_configUtil;
private final RemoteConfigLongPollService remoteConfigLongPollService;
private volatile AtomicReference<ApolloConfig> m_configCache;
private final String m_namespace;
private final static ScheduledExecutorService m_executorService;
private final AtomicReference<ServiceDTO> m_longPollServiceDto;
private final AtomicReference<ApolloNotificationMessages> m_remoteMessages;
private final RateLimiter m_loadConfigRateLimiter;
private final AtomicBoolean m_configNeedForceRefresh;
private final SchedulePolicy m_loadConfigFailSchedulePolicy;
private static final Gson GSON = new Gson();
static {
m_executorService = Executors.newScheduledThreadPool(1,
ApolloThreadFactory.create("RemoteConfigRepository", true));
}
/**
* Constructor.
*
* @param namespace the namespace
*/
public RemoteConfigRepository(String namespace) {
m_namespace = namespace;
m_configCache = new AtomicReference<>();
m_configUtil = ApolloInjector.getInstance(ConfigUtil.class);
m_httpClient = ApolloInjector.getInstance(HttpClient.class);
m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class);
remoteConfigLongPollService = ApolloInjector.getInstance(RemoteConfigLongPollService.class);
m_longPollServiceDto = new AtomicReference<>();
m_remoteMessages = new AtomicReference<>();
m_loadConfigRateLimiter = RateLimiter.create(m_configUtil.getLoadConfigQPS());
m_configNeedForceRefresh = new AtomicBoolean(true);
m_loadConfigFailSchedulePolicy = new ExponentialSchedulePolicy(m_configUtil.getOnErrorRetryInterval(),
m_configUtil.getOnErrorRetryInterval() * 8);
this.trySync();
this.schedulePeriodicRefresh();
this.scheduleLongPollingRefresh();
}
@Override
public Properties getConfig() {
if (m_configCache.get() == null) {
this.sync();
}
return transformApolloConfigToProperties(m_configCache.get());
}
@Override
public void setUpstreamRepository(ConfigRepository upstreamConfigRepository) {
//remote config doesn't need upstream
}
@Override
public ConfigSourceType getSourceType() {
return ConfigSourceType.REMOTE;
}
private void schedulePeriodicRefresh() {
logger.debug("Schedule periodic refresh with interval: {} {}",
m_configUtil.getRefreshInterval(), m_configUtil.getRefreshIntervalTimeUnit());
m_executorService.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
Tracer.logEvent("Apollo.ConfigService", String.format("periodicRefresh: %s", m_namespace));
logger.debug("refresh config for namespace: {}", m_namespace);
trySync();
Tracer.logEvent("Apollo.Client.Version", Apollo.VERSION);
}
}, m_configUtil.getRefreshInterval(), m_configUtil.getRefreshInterval(),
m_configUtil.getRefreshIntervalTimeUnit());
}
@Override
protected synchronized void sync() {
Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "syncRemoteConfig");
try {
ApolloConfig previous = m_configCache.get();
ApolloConfig current = loadApolloConfig();
//reference equals means HTTP 304
if (previous != current) {
logger.debug("Remote Config refreshed!");
m_configCache.set(current);
this.fireRepositoryChange(m_namespace, this.getConfig());
}
if (current != null) {
Tracer.logEvent(String.format("Apollo.Client.Configs.%s", current.getNamespaceName()),
current.getReleaseKey());
}
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
throw ex;
} finally {
transaction.complete();
}
}
private Properties transformApolloConfigToProperties(ApolloConfig apolloConfig) {
Properties result = propertiesFactory.getPropertiesInstance();
result.putAll(apolloConfig.getConfigurations());
return result;
}
private ApolloConfig loadApolloConfig() {
if (!m_loadConfigRateLimiter.tryAcquire(5, TimeUnit.SECONDS)) {
//wait at most 5 seconds
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
}
}
String appId = m_configUtil.getAppId();
String cluster = m_configUtil.getCluster();
String dataCenter = m_configUtil.getDataCenter();
String secret = m_configUtil.getAccessKeySecret();
Tracer.logEvent("Apollo.Client.ConfigMeta", STRING_JOINER.join(appId, cluster, m_namespace));
int maxRetries = m_configNeedForceRefresh.get() ? 2 : 1;
long onErrorSleepTime = 0; // 0 means no sleep
Throwable exception = null;
List<ServiceDTO> configServices = getConfigServices();
String url = null;
retryLoopLabel:
for (int i = 0; i < maxRetries; i++) {
List<ServiceDTO> randomConfigServices = Lists.newLinkedList(configServices);
Collections.shuffle(randomConfigServices);
//Access the server which notifies the client first
if (m_longPollServiceDto.get() != null) {
randomConfigServices.add(0, m_longPollServiceDto.getAndSet(null));
}
for (ServiceDTO configService : randomConfigServices) {
if (onErrorSleepTime > 0) {
logger.warn(
"Load config failed, will retry in {} {}. appId: {}, cluster: {}, namespaces: {}",
onErrorSleepTime, m_configUtil.getOnErrorRetryIntervalTimeUnit(), appId, cluster, m_namespace);
try {
m_configUtil.getOnErrorRetryIntervalTimeUnit().sleep(onErrorSleepTime);
} catch (InterruptedException e) {
//ignore
}
}
url = assembleQueryConfigUrl(configService.getHomepageUrl(), appId, cluster, m_namespace,
dataCenter, m_remoteMessages.get(), m_configCache.get());
logger.debug("Loading config from {}", url);
HttpRequest request = new HttpRequest(url);
if (!StringUtils.isBlank(secret)) {
Map<String, String> headers = Signature.buildHttpHeaders(url, appId, secret);
request.setHeaders(headers);
}
Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "queryConfig");
transaction.addData("Url", url);
try {
HttpResponse<ApolloConfig> response = m_httpClient.doGet(request, ApolloConfig.class);
m_configNeedForceRefresh.set(false);
m_loadConfigFailSchedulePolicy.success();
transaction.addData("StatusCode", response.getStatusCode());
transaction.setStatus(Transaction.SUCCESS);
if (response.getStatusCode() == 304) {
logger.debug("Config server responds with 304 HTTP status code.");
return m_configCache.get();
}
ApolloConfig result = response.getBody();
logger.debug("Loaded config for {}: {}", m_namespace, result);
return result;
} catch (ApolloConfigStatusCodeException ex) {
ApolloConfigStatusCodeException statusCodeException = ex;
//config not found
if (ex.getStatusCode() == 404) {
String message = String.format(
"Could not find config for namespace - appId: %s, cluster: %s, namespace: %s, " +
"please check whether the configs are released in Apollo!",
appId, cluster, m_namespace);
statusCodeException = new ApolloConfigStatusCodeException(ex.getStatusCode(),
message);
}
Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(statusCodeException));
transaction.setStatus(statusCodeException);
exception = statusCodeException;
if(ex.getStatusCode() == 404) {
break retryLoopLabel;
}
} catch (Throwable ex) {
Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
transaction.setStatus(ex);
exception = ex;
} finally {
transaction.complete();
}
// if force refresh, do normal sleep, if normal config load, do exponential sleep
onErrorSleepTime = m_configNeedForceRefresh.get() ? m_configUtil.getOnErrorRetryInterval() :
m_loadConfigFailSchedulePolicy.fail();
}
}
String message = String.format(
"Load Apollo Config failed - appId: %s, cluster: %s, namespace: %s, url: %s",
appId, cluster, m_namespace, url);
throw new ApolloConfigException(message, exception);
}
String assembleQueryConfigUrl(String uri, String appId, String cluster, String namespace,
String dataCenter, ApolloNotificationMessages remoteMessages, ApolloConfig previousConfig) {
String path = "configs/%s/%s/%s";
List<String> pathParams =
Lists.newArrayList(pathEscaper.escape(appId), pathEscaper.escape(cluster),
pathEscaper.escape(namespace));
Map<String, String> queryParams = Maps.newHashMap();
if (previousConfig != null) {
queryParams.put("releaseKey", queryParamEscaper.escape(previousConfig.getReleaseKey()));
}
if (!Strings.isNullOrEmpty(dataCenter)) {
queryParams.put("dataCenter", queryParamEscaper.escape(dataCenter));
}
String localIp = m_configUtil.getLocalIp();
if (!Strings.isNullOrEmpty(localIp)) {
queryParams.put("ip", queryParamEscaper.escape(localIp));
}
if (remoteMessages != null) {
queryParams.put("messages", queryParamEscaper.escape(GSON.toJson(remoteMessages)));
}
String pathExpanded = String.format(path, pathParams.toArray());
if (!queryParams.isEmpty()) {
pathExpanded += "?" + MAP_JOINER.join(queryParams);
}
if (!uri.endsWith("/")) {
uri += "/";
}
return uri + pathExpanded;
}
private void scheduleLongPollingRefresh() {
remoteConfigLongPollService.submit(m_namespace, this);
}
public void onLongPollNotified(ServiceDTO longPollNotifiedServiceDto, ApolloNotificationMessages remoteMessages) {
m_longPollServiceDto.set(longPollNotifiedServiceDto);
m_remoteMessages.set(remoteMessages);
m_executorService.submit(new Runnable() {
@Override
public void run() {
m_configNeedForceRefresh.set(true);
trySync();
}
});
}
private List<ServiceDTO> getConfigServices() {
List<ServiceDTO> services = m_serviceLocator.getConfigServices();
if (services.size() == 0) {
throw new ApolloConfigException("No available config service");
}
return services;
}
}
| 1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializer.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.boot;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.spring.config.ConfigPropertySourceFactory;
import com.ctrip.framework.apollo.spring.config.PropertySourcesConstants;
import com.ctrip.framework.apollo.spring.util.SpringInjector;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
/**
* Initialize apollo system properties and inject the Apollo config in Spring Boot bootstrap phase
*
* <p>Configuration example:</p>
* <pre class="code">
* # set app.id
* app.id = 100004458
* # enable apollo bootstrap config and inject 'application' namespace in bootstrap phase
* apollo.bootstrap.enabled = true
* </pre>
*
* or
*
* <pre class="code">
* # set app.id
* app.id = 100004458
* # enable apollo bootstrap config
* apollo.bootstrap.enabled = true
* # will inject 'application' and 'FX.apollo' namespaces in bootstrap phase
* apollo.bootstrap.namespaces = application,FX.apollo
* </pre>
*
*
* If you want to load Apollo configurations even before Logging System Initialization Phase,
* add
* <pre class="code">
* # set apollo.bootstrap.eagerLoad.enabled
* apollo.bootstrap.eagerLoad.enabled = true
* </pre>
*
* This would be very helpful when your logging configurations is set by Apollo.
*
* for example, you have defined logback-spring.xml in your project, and you want to inject some attributes into logback-spring.xml.
*
*/
public class ApolloApplicationContextInitializer implements
ApplicationContextInitializer<ConfigurableApplicationContext> , EnvironmentPostProcessor, Ordered {
public static final int DEFAULT_ORDER = 0;
private static final Logger logger = LoggerFactory.getLogger(ApolloApplicationContextInitializer.class);
private static final Splitter NAMESPACE_SPLITTER = Splitter.on(",").omitEmptyStrings().trimResults();
private static final String[] APOLLO_SYSTEM_PROPERTIES = {"app.id", ConfigConsts.APOLLO_CLUSTER_KEY,
"apollo.cacheDir", "apollo.accesskey.secret", ConfigConsts.APOLLO_META_KEY, PropertiesFactory.APOLLO_PROPERTY_ORDER_ENABLE};
private final ConfigPropertySourceFactory configPropertySourceFactory = SpringInjector
.getInstance(ConfigPropertySourceFactory.class);
private int order = DEFAULT_ORDER;
@Override
public void initialize(ConfigurableApplicationContext context) {
ConfigurableEnvironment environment = context.getEnvironment();
if (!environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, Boolean.class, false)) {
logger.debug("Apollo bootstrap config is not enabled for context {}, see property: ${{}}", context, PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED);
return;
}
logger.debug("Apollo bootstrap config is enabled for context {}", context);
initialize(environment);
}
/**
* Initialize Apollo Configurations Just after environment is ready.
*
* @param environment
*/
protected void initialize(ConfigurableEnvironment environment) {
if (environment.getPropertySources().contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
//already initialized
return;
}
String namespaces = environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, ConfigConsts.NAMESPACE_APPLICATION);
logger.debug("Apollo bootstrap namespaces: {}", namespaces);
List<String> namespaceList = NAMESPACE_SPLITTER.splitToList(namespaces);
CompositePropertySource composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME);
for (String namespace : namespaceList) {
Config config = ConfigService.getConfig(namespace);
composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config));
}
environment.getPropertySources().addFirst(composite);
}
/**
* To fill system properties from environment config
*/
void initializeSystemProperty(ConfigurableEnvironment environment) {
for (String propertyName : APOLLO_SYSTEM_PROPERTIES) {
fillSystemPropertyFromEnvironment(environment, propertyName);
}
}
private void fillSystemPropertyFromEnvironment(ConfigurableEnvironment environment, String propertyName) {
if (System.getProperty(propertyName) != null) {
return;
}
String propertyValue = environment.getProperty(propertyName);
if (Strings.isNullOrEmpty(propertyValue)) {
return;
}
System.setProperty(propertyName, propertyValue);
}
/**
*
* In order to load Apollo configurations as early as even before Spring loading logging system phase,
* this EnvironmentPostProcessor can be called Just After ConfigFileApplicationListener has succeeded.
*
* <br />
* The processing sequence would be like this: <br />
* Load Bootstrap properties and application properties -----> load Apollo configuration properties ----> Initialize Logging systems
*
* @param configurableEnvironment
* @param springApplication
*/
@Override
public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
// should always initialize system properties like app.id in the first place
initializeSystemProperty(configurableEnvironment);
Boolean eagerLoadEnabled = configurableEnvironment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, Boolean.class, false);
//EnvironmentPostProcessor should not be triggered if you don't want Apollo Loading before Logging System Initialization
if (!eagerLoadEnabled) {
return;
}
Boolean bootstrapEnabled = configurableEnvironment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, Boolean.class, false);
if (bootstrapEnabled) {
initialize(configurableEnvironment);
}
}
/**
* @since 1.3.0
*/
@Override
public int getOrder() {
return order;
}
/**
* @since 1.3.0
*/
public void setOrder(int order) {
this.order = order;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.boot;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.utils.DeferredLogger;
import com.ctrip.framework.apollo.spring.config.ConfigPropertySourceFactory;
import com.ctrip.framework.apollo.spring.config.PropertySourcesConstants;
import com.ctrip.framework.apollo.spring.util.SpringInjector;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
/**
* Initialize apollo system properties and inject the Apollo config in Spring Boot bootstrap phase
*
* <p>Configuration example:</p>
* <pre class="code">
* # set app.id
* app.id = 100004458
* # enable apollo bootstrap config and inject 'application' namespace in bootstrap phase
* apollo.bootstrap.enabled = true
* </pre>
*
* or
*
* <pre class="code">
* # set app.id
* app.id = 100004458
* # enable apollo bootstrap config
* apollo.bootstrap.enabled = true
* # will inject 'application' and 'FX.apollo' namespaces in bootstrap phase
* apollo.bootstrap.namespaces = application,FX.apollo
* </pre>
*
*
* If you want to load Apollo configurations even before Logging System Initialization Phase,
* add
* <pre class="code">
* # set apollo.bootstrap.eagerLoad.enabled
* apollo.bootstrap.eagerLoad.enabled = true
* </pre>
*
* This would be very helpful when your logging configurations is set by Apollo.
*
* for example, you have defined logback-spring.xml in your project, and you want to inject some attributes into logback-spring.xml.
*
*/
public class ApolloApplicationContextInitializer implements
ApplicationContextInitializer<ConfigurableApplicationContext> , EnvironmentPostProcessor, Ordered {
public static final int DEFAULT_ORDER = 0;
private static final Logger logger = LoggerFactory.getLogger(ApolloApplicationContextInitializer.class);
private static final Splitter NAMESPACE_SPLITTER = Splitter.on(",").omitEmptyStrings().trimResults();
private static final String[] APOLLO_SYSTEM_PROPERTIES = {"app.id", ConfigConsts.APOLLO_CLUSTER_KEY,
"apollo.cacheDir", "apollo.accesskey.secret", ConfigConsts.APOLLO_META_KEY, PropertiesFactory.APOLLO_PROPERTY_ORDER_ENABLE};
private final ConfigPropertySourceFactory configPropertySourceFactory = SpringInjector
.getInstance(ConfigPropertySourceFactory.class);
private int order = DEFAULT_ORDER;
@Override
public void initialize(ConfigurableApplicationContext context) {
ConfigurableEnvironment environment = context.getEnvironment();
if (!environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, Boolean.class, false)) {
logger.debug("Apollo bootstrap config is not enabled for context {}, see property: ${{}}", context, PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED);
return;
}
logger.debug("Apollo bootstrap config is enabled for context {}", context);
initialize(environment);
}
/**
* Initialize Apollo Configurations Just after environment is ready.
*
* @param environment
*/
protected void initialize(ConfigurableEnvironment environment) {
if (environment.getPropertySources().contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
//already initialized, replay the logs that were printed before the logging system was initialized
DeferredLogger.replayTo();
return;
}
String namespaces = environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, ConfigConsts.NAMESPACE_APPLICATION);
logger.debug("Apollo bootstrap namespaces: {}", namespaces);
List<String> namespaceList = NAMESPACE_SPLITTER.splitToList(namespaces);
CompositePropertySource composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME);
for (String namespace : namespaceList) {
Config config = ConfigService.getConfig(namespace);
composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config));
}
environment.getPropertySources().addFirst(composite);
}
/**
* To fill system properties from environment config
*/
void initializeSystemProperty(ConfigurableEnvironment environment) {
for (String propertyName : APOLLO_SYSTEM_PROPERTIES) {
fillSystemPropertyFromEnvironment(environment, propertyName);
}
}
private void fillSystemPropertyFromEnvironment(ConfigurableEnvironment environment, String propertyName) {
if (System.getProperty(propertyName) != null) {
return;
}
String propertyValue = environment.getProperty(propertyName);
if (Strings.isNullOrEmpty(propertyValue)) {
return;
}
System.setProperty(propertyName, propertyValue);
}
/**
*
* In order to load Apollo configurations as early as even before Spring loading logging system phase,
* this EnvironmentPostProcessor can be called Just After ConfigFileApplicationListener has succeeded.
*
* <br />
* The processing sequence would be like this: <br />
* Load Bootstrap properties and application properties -----> load Apollo configuration properties ----> Initialize Logging systems
*
* @param configurableEnvironment
* @param springApplication
*/
@Override
public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
// should always initialize system properties like app.id in the first place
initializeSystemProperty(configurableEnvironment);
Boolean eagerLoadEnabled = configurableEnvironment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, Boolean.class, false);
//EnvironmentPostProcessor should not be triggered if you don't want Apollo Loading before Logging System Initialization
if (!eagerLoadEnabled) {
return;
}
Boolean bootstrapEnabled = configurableEnvironment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, Boolean.class, false);
if (bootstrapEnabled) {
DeferredLogger.enable();
initialize(configurableEnvironment);
}
}
/**
* @since 1.3.0
*/
@Override
public int getOrder() {
return order;
}
/**
* @since 1.3.0
*/
public void setOrder(int order) {
this.order = order;
}
}
| 1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-core/src/main/java/com/ctrip/framework/apollo/core/MetaDomainConsts.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.core;
import com.ctrip.framework.apollo.core.enums.Env;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctrip.framework.apollo.core.spi.MetaServerProvider;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.core.utils.NetUtil;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.ctrip.framework.foundation.internals.ServiceBootstrap;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* The meta domain will try to load the meta server address from MetaServerProviders, the default ones are:
*
* <ul>
* <li>com.ctrip.framework.apollo.core.internals.LegacyMetaServerProvider</li>
* </ul>
*
* If no provider could provide the meta server url, the default meta url will be used(http://apollo.meta).
* <br />
*
* 3rd party MetaServerProvider could be injected by typical Java Service Loader pattern.
*
* @see com.ctrip.framework.apollo.core.internals.LegacyMetaServerProvider
*/
public class MetaDomainConsts {
public static final String DEFAULT_META_URL = "http://apollo.meta";
// env -> meta server address cache
private static final Map<Env, String> metaServerAddressCache = Maps.newConcurrentMap();
private static volatile List<MetaServerProvider> metaServerProviders = null;
private static final long REFRESH_INTERVAL_IN_SECOND = 60;// 1 min
private static final Logger logger = LoggerFactory.getLogger(MetaDomainConsts.class);
// comma separated meta server address -> selected single meta server address cache
private static final Map<String, String> selectedMetaServerAddressCache = Maps.newConcurrentMap();
private static final AtomicBoolean periodicRefreshStarted = new AtomicBoolean(false);
private static final Object LOCK = new Object();
/**
* Return one meta server address. If multiple meta server addresses are configured, will select one.
*/
public static String getDomain(Env env) {
String metaServerAddress = getMetaServerAddress(env);
// if there is more than one address, need to select one
if (metaServerAddress.contains(",")) {
return selectMetaServerAddress(metaServerAddress);
}
return metaServerAddress;
}
/**
* Return meta server address. If multiple meta server addresses are configured, will return the comma separated string.
*/
public static String getMetaServerAddress(Env env) {
if (!metaServerAddressCache.containsKey(env)) {
initMetaServerAddress(env);
}
return metaServerAddressCache.get(env);
}
private static void initMetaServerAddress(Env env) {
if (metaServerProviders == null) {
synchronized (LOCK) {
if (metaServerProviders == null) {
metaServerProviders = initMetaServerProviders();
}
}
}
String metaAddress = null;
for (MetaServerProvider provider : metaServerProviders) {
metaAddress = provider.getMetaServerAddress(env);
if (!Strings.isNullOrEmpty(metaAddress)) {
logger.info("Located meta server address {} for env {} from {}", metaAddress, env,
provider.getClass().getName());
break;
}
}
if (Strings.isNullOrEmpty(metaAddress)) {
// Fallback to default meta address
metaAddress = DEFAULT_META_URL;
logger.warn(
"Meta server address fallback to {} for env {}, because it is not available in all MetaServerProviders",
metaAddress, env);
}
metaServerAddressCache.put(env, metaAddress.trim());
}
private static List<MetaServerProvider> initMetaServerProviders() {
Iterator<MetaServerProvider> metaServerProviderIterator = ServiceBootstrap.loadAll(MetaServerProvider.class);
List<MetaServerProvider> metaServerProviders = Lists.newArrayList(metaServerProviderIterator);
Collections.sort(metaServerProviders, new Comparator<MetaServerProvider>() {
@Override
public int compare(MetaServerProvider o1, MetaServerProvider o2) {
// the smaller order has higher priority
return Integer.compare(o1.getOrder(), o2.getOrder());
}
});
return metaServerProviders;
}
/**
* Select one available meta server from the comma separated meta server addresses, e.g.
* http://1.2.3.4:8080,http://2.3.4.5:8080
*
* <br />
*
* In production environment, we still suggest using one single domain like http://config.xxx.com(backed by software
* load balancers like nginx) instead of multiple ip addresses
*/
private static String selectMetaServerAddress(String metaServerAddresses) {
String metaAddressSelected = selectedMetaServerAddressCache.get(metaServerAddresses);
if (metaAddressSelected == null) {
// initialize
if (periodicRefreshStarted.compareAndSet(false, true)) {
schedulePeriodicRefresh();
}
updateMetaServerAddresses(metaServerAddresses);
metaAddressSelected = selectedMetaServerAddressCache.get(metaServerAddresses);
}
return metaAddressSelected;
}
private static void updateMetaServerAddresses(String metaServerAddresses) {
logger.debug("Selecting meta server address for: {}", metaServerAddresses);
Transaction transaction = Tracer.newTransaction("Apollo.MetaService", "refreshMetaServerAddress");
transaction.addData("Url", metaServerAddresses);
try {
List<String> metaServers = Lists.newArrayList(metaServerAddresses.split(","));
// random load balancing
Collections.shuffle(metaServers);
boolean serverAvailable = false;
for (String address : metaServers) {
address = address.trim();
//check whether /services/config is accessible
if (NetUtil.pingUrl(address + "/services/config")) {
// select the first available meta server
selectedMetaServerAddressCache.put(metaServerAddresses, address);
serverAvailable = true;
logger.debug("Selected meta server address {} for {}", address, metaServerAddresses);
break;
}
}
// we need to make sure the map is not empty, e.g. the first update might be failed
if (!selectedMetaServerAddressCache.containsKey(metaServerAddresses)) {
selectedMetaServerAddressCache.put(metaServerAddresses, metaServers.get(0).trim());
}
if (!serverAvailable) {
logger.warn("Could not find available meta server for configured meta server addresses: {}, fallback to: {}",
metaServerAddresses, selectedMetaServerAddressCache.get(metaServerAddresses));
}
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
throw ex;
} finally {
transaction.complete();
}
}
private static void schedulePeriodicRefresh() {
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(1, ApolloThreadFactory.create("MetaServiceLocator", true));
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
for (String metaServerAddresses : selectedMetaServerAddressCache.keySet()) {
updateMetaServerAddresses(metaServerAddresses);
}
} catch (Throwable ex) {
logger.warn(String.format("Refreshing meta server address failed, will retry in %d seconds",
REFRESH_INTERVAL_IN_SECOND), ex);
}
}
}, REFRESH_INTERVAL_IN_SECOND, REFRESH_INTERVAL_IN_SECOND, TimeUnit.SECONDS);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.core;
import com.ctrip.framework.apollo.core.enums.Env;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import org.slf4j.Logger;
import com.ctrip.framework.apollo.core.spi.MetaServerProvider;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.core.utils.NetUtil;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.ctrip.framework.foundation.internals.ServiceBootstrap;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* The meta domain will try to load the meta server address from MetaServerProviders, the default
* ones are:
*
* <ul>
* <li>com.ctrip.framework.apollo.core.internals.LegacyMetaServerProvider</li>
* </ul>
* <p>
* If no provider could provide the meta server url, the default meta url will be used(http://apollo.meta).
* <br />
* <p>
* 3rd party MetaServerProvider could be injected by typical Java Service Loader pattern.
*
* @see com.ctrip.framework.apollo.core.internals.LegacyMetaServerProvider
*/
public class MetaDomainConsts {
public static final String DEFAULT_META_URL = "http://apollo.meta";
// env -> meta server address cache
private static final Map<Env, String> metaServerAddressCache = Maps.newConcurrentMap();
private static volatile List<MetaServerProvider> metaServerProviders = null;
private static final long REFRESH_INTERVAL_IN_SECOND = 60;// 1 min
private static final Logger logger = DeferredLoggerFactory.getLogger(MetaDomainConsts.class);
// comma separated meta server address -> selected single meta server address cache
private static final Map<String, String> selectedMetaServerAddressCache = Maps.newConcurrentMap();
private static final AtomicBoolean periodicRefreshStarted = new AtomicBoolean(false);
private static final Object LOCK = new Object();
/**
* Return one meta server address. If multiple meta server addresses are configured, will select
* one.
*/
public static String getDomain(Env env) {
String metaServerAddress = getMetaServerAddress(env);
// if there is more than one address, need to select one
if (metaServerAddress.contains(",")) {
return selectMetaServerAddress(metaServerAddress);
}
return metaServerAddress;
}
/**
* Return meta server address. If multiple meta server addresses are configured, will return the
* comma separated string.
*/
public static String getMetaServerAddress(Env env) {
if (!metaServerAddressCache.containsKey(env)) {
initMetaServerAddress(env);
}
return metaServerAddressCache.get(env);
}
private static void initMetaServerAddress(Env env) {
if (metaServerProviders == null) {
synchronized (LOCK) {
if (metaServerProviders == null) {
metaServerProviders = initMetaServerProviders();
}
}
}
String metaAddress = null;
for (MetaServerProvider provider : metaServerProviders) {
metaAddress = provider.getMetaServerAddress(env);
if (!Strings.isNullOrEmpty(metaAddress)) {
logger.info("Located meta server address {} for env {} from {}", metaAddress, env,
provider.getClass().getName());
break;
}
}
if (Strings.isNullOrEmpty(metaAddress)) {
// Fallback to default meta address
metaAddress = DEFAULT_META_URL;
logger.warn(
"Meta server address fallback to {} for env {}, because it is not available in all MetaServerProviders",
metaAddress, env);
}
metaServerAddressCache.put(env, metaAddress.trim());
}
private static List<MetaServerProvider> initMetaServerProviders() {
Iterator<MetaServerProvider> metaServerProviderIterator = ServiceBootstrap
.loadAll(MetaServerProvider.class);
List<MetaServerProvider> metaServerProviders = Lists.newArrayList(metaServerProviderIterator);
Collections.sort(metaServerProviders, new Comparator<MetaServerProvider>() {
@Override
public int compare(MetaServerProvider o1, MetaServerProvider o2) {
// the smaller order has higher priority
return Integer.compare(o1.getOrder(), o2.getOrder());
}
});
return metaServerProviders;
}
/**
* Select one available meta server from the comma separated meta server addresses, e.g.
* http://1.2.3.4:8080,http://2.3.4.5:8080
* <p>
* <br />
* <p>
* In production environment, we still suggest using one single domain like
* http://config.xxx.com(backed by software load balancers like nginx) instead of multiple ip
* addresses
*/
private static String selectMetaServerAddress(String metaServerAddresses) {
String metaAddressSelected = selectedMetaServerAddressCache.get(metaServerAddresses);
if (metaAddressSelected == null) {
// initialize
if (periodicRefreshStarted.compareAndSet(false, true)) {
schedulePeriodicRefresh();
}
updateMetaServerAddresses(metaServerAddresses);
metaAddressSelected = selectedMetaServerAddressCache.get(metaServerAddresses);
}
return metaAddressSelected;
}
private static void updateMetaServerAddresses(String metaServerAddresses) {
logger.debug("Selecting meta server address for: {}", metaServerAddresses);
Transaction transaction = Tracer
.newTransaction("Apollo.MetaService", "refreshMetaServerAddress");
transaction.addData("Url", metaServerAddresses);
try {
List<String> metaServers = Lists.newArrayList(metaServerAddresses.split(","));
// random load balancing
Collections.shuffle(metaServers);
boolean serverAvailable = false;
for (String address : metaServers) {
address = address.trim();
//check whether /services/config is accessible
if (NetUtil.pingUrl(address + "/services/config")) {
// select the first available meta server
selectedMetaServerAddressCache.put(metaServerAddresses, address);
serverAvailable = true;
logger.debug("Selected meta server address {} for {}", address, metaServerAddresses);
break;
}
}
// we need to make sure the map is not empty, e.g. the first update might be failed
if (!selectedMetaServerAddressCache.containsKey(metaServerAddresses)) {
selectedMetaServerAddressCache.put(metaServerAddresses, metaServers.get(0).trim());
}
if (!serverAvailable) {
logger.warn(
"Could not find available meta server for configured meta server addresses: {}, fallback to: {}",
metaServerAddresses, selectedMetaServerAddressCache.get(metaServerAddresses));
}
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
throw ex;
} finally {
transaction.complete();
}
}
private static void schedulePeriodicRefresh() {
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(1, ApolloThreadFactory.create("MetaServiceLocator", true));
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
for (String metaServerAddresses : selectedMetaServerAddressCache.keySet()) {
updateMetaServerAddresses(metaServerAddresses);
}
} catch (Throwable ex) {
logger
.warn(String.format("Refreshing meta server address failed, will retry in %d seconds",
REFRESH_INTERVAL_IN_SECOND), ex);
}
}
}, REFRESH_INTERVAL_IN_SECOND, REFRESH_INTERVAL_IN_SECOND, TimeUnit.SECONDS);
}
}
| 1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/DefaultApplicationProvider.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.foundation.internals.provider;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctrip.framework.foundation.internals.Utils;
import com.ctrip.framework.foundation.internals.io.BOMInputStream;
import com.ctrip.framework.foundation.spi.provider.ApplicationProvider;
import com.ctrip.framework.foundation.spi.provider.Provider;
public class DefaultApplicationProvider implements ApplicationProvider {
private static final Logger logger = LoggerFactory.getLogger(DefaultApplicationProvider.class);
public static final String APP_PROPERTIES_CLASSPATH = "/META-INF/app.properties";
private Properties m_appProperties = new Properties();
private String m_appId;
private String accessKeySecret;
@Override
public void initialize() {
try {
InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(APP_PROPERTIES_CLASSPATH.substring(1));
if (in == null) {
in = DefaultApplicationProvider.class.getResourceAsStream(APP_PROPERTIES_CLASSPATH);
}
initialize(in);
} catch (Throwable ex) {
logger.error("Initialize DefaultApplicationProvider failed.", ex);
}
}
@Override
public void initialize(InputStream in) {
try {
if (in != null) {
try {
m_appProperties
.load(new InputStreamReader(new BOMInputStream(in), StandardCharsets.UTF_8));
} finally {
in.close();
}
}
initAppId();
initAccessKey();
} catch (Throwable ex) {
logger.error("Initialize DefaultApplicationProvider failed.", ex);
}
}
@Override
public String getAppId() {
return m_appId;
}
@Override
public String getAccessKeySecret() {
return accessKeySecret;
}
@Override
public boolean isAppIdSet() {
return !Utils.isBlank(m_appId);
}
@Override
public String getProperty(String name, String defaultValue) {
if ("app.id".equals(name)) {
String val = getAppId();
return val == null ? defaultValue : val;
}
if ("apollo.accesskey.secret".equals(name)) {
String val = getAccessKeySecret();
return val == null ? defaultValue : val;
}
String val = m_appProperties.getProperty(name, defaultValue);
return val == null ? defaultValue : val;
}
@Override
public Class<? extends Provider> getType() {
return ApplicationProvider.class;
}
private void initAppId() {
// 1. Get app.id from System Property
m_appId = System.getProperty("app.id");
if (!Utils.isBlank(m_appId)) {
m_appId = m_appId.trim();
logger.info("App ID is set to {} by app.id property from System Property", m_appId);
return;
}
//2. Try to get app id from OS environment variable
m_appId = System.getenv("APP_ID");
if (!Utils.isBlank(m_appId)) {
m_appId = m_appId.trim();
logger.info("App ID is set to {} by APP_ID property from OS environment variable", m_appId);
return;
}
// 3. Try to get app id from app.properties.
m_appId = m_appProperties.getProperty("app.id");
if (!Utils.isBlank(m_appId)) {
m_appId = m_appId.trim();
logger.info("App ID is set to {} by app.id property from {}", m_appId,
APP_PROPERTIES_CLASSPATH);
return;
}
m_appId = null;
logger.warn("app.id is not available from System Property and {}. It is set to null",
APP_PROPERTIES_CLASSPATH);
}
private void initAccessKey() {
// 1. Get accesskey secret from System Property
accessKeySecret = System.getProperty("apollo.accesskey.secret");
if (!Utils.isBlank(accessKeySecret)) {
accessKeySecret = accessKeySecret.trim();
logger
.info("ACCESSKEY SECRET is set by apollo.accesskey.secret property from System Property");
return;
}
//2. Try to get accesskey secret from OS environment variable
accessKeySecret = System.getenv("APOLLO_ACCESSKEY_SECRET");
if (!Utils.isBlank(accessKeySecret)) {
accessKeySecret = accessKeySecret.trim();
logger.info(
"ACCESSKEY SECRET is set by APOLLO_ACCESSKEY_SECRET property from OS environment variable");
return;
}
// 3. Try to get accesskey secret from app.properties.
accessKeySecret = m_appProperties.getProperty("apollo.accesskey.secret");
if (!Utils.isBlank(accessKeySecret)) {
accessKeySecret = accessKeySecret.trim();
logger.info("ACCESSKEY SECRET is set by apollo.accesskey.secret property from {}",
APP_PROPERTIES_CLASSPATH);
return;
}
accessKeySecret = null;
}
@Override
public String toString() {
return "appId [" + getAppId() + "] properties: " + m_appProperties
+ " (DefaultApplicationProvider)";
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.foundation.internals.provider;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import org.slf4j.Logger;
import com.ctrip.framework.foundation.internals.Utils;
import com.ctrip.framework.foundation.internals.io.BOMInputStream;
import com.ctrip.framework.foundation.spi.provider.ApplicationProvider;
import com.ctrip.framework.foundation.spi.provider.Provider;
public class DefaultApplicationProvider implements ApplicationProvider {
private static final Logger logger = DeferredLoggerFactory
.getLogger(DefaultApplicationProvider.class);
public static final String APP_PROPERTIES_CLASSPATH = "/META-INF/app.properties";
private Properties m_appProperties = new Properties();
private String m_appId;
private String accessKeySecret;
@Override
public void initialize() {
try {
InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(APP_PROPERTIES_CLASSPATH.substring(1));
if (in == null) {
in = DefaultApplicationProvider.class.getResourceAsStream(APP_PROPERTIES_CLASSPATH);
}
initialize(in);
} catch (Throwable ex) {
logger.error("Initialize DefaultApplicationProvider failed.", ex);
}
}
@Override
public void initialize(InputStream in) {
try {
if (in != null) {
try {
m_appProperties
.load(new InputStreamReader(new BOMInputStream(in), StandardCharsets.UTF_8));
} finally {
in.close();
}
}
initAppId();
initAccessKey();
} catch (Throwable ex) {
logger.error("Initialize DefaultApplicationProvider failed.", ex);
}
}
@Override
public String getAppId() {
return m_appId;
}
@Override
public String getAccessKeySecret() {
return accessKeySecret;
}
@Override
public boolean isAppIdSet() {
return !Utils.isBlank(m_appId);
}
@Override
public String getProperty(String name, String defaultValue) {
if ("app.id".equals(name)) {
String val = getAppId();
return val == null ? defaultValue : val;
}
if ("apollo.accesskey.secret".equals(name)) {
String val = getAccessKeySecret();
return val == null ? defaultValue : val;
}
String val = m_appProperties.getProperty(name, defaultValue);
return val == null ? defaultValue : val;
}
@Override
public Class<? extends Provider> getType() {
return ApplicationProvider.class;
}
private void initAppId() {
// 1. Get app.id from System Property
m_appId = System.getProperty("app.id");
if (!Utils.isBlank(m_appId)) {
m_appId = m_appId.trim();
logger.info("App ID is set to {} by app.id property from System Property", m_appId);
return;
}
//2. Try to get app id from OS environment variable
m_appId = System.getenv("APP_ID");
if (!Utils.isBlank(m_appId)) {
m_appId = m_appId.trim();
logger.info("App ID is set to {} by APP_ID property from OS environment variable", m_appId);
return;
}
// 3. Try to get app id from app.properties.
m_appId = m_appProperties.getProperty("app.id");
if (!Utils.isBlank(m_appId)) {
m_appId = m_appId.trim();
logger.info("App ID is set to {} by app.id property from {}", m_appId,
APP_PROPERTIES_CLASSPATH);
return;
}
m_appId = null;
logger.warn("app.id is not available from System Property and {}. It is set to null",
APP_PROPERTIES_CLASSPATH);
}
private void initAccessKey() {
// 1. Get accesskey secret from System Property
accessKeySecret = System.getProperty("apollo.accesskey.secret");
if (!Utils.isBlank(accessKeySecret)) {
accessKeySecret = accessKeySecret.trim();
logger
.info("ACCESSKEY SECRET is set by apollo.accesskey.secret property from System Property");
return;
}
//2. Try to get accesskey secret from OS environment variable
accessKeySecret = System.getenv("APOLLO_ACCESSKEY_SECRET");
if (!Utils.isBlank(accessKeySecret)) {
accessKeySecret = accessKeySecret.trim();
logger.info(
"ACCESSKEY SECRET is set by APOLLO_ACCESSKEY_SECRET property from OS environment variable");
return;
}
// 3. Try to get accesskey secret from app.properties.
accessKeySecret = m_appProperties.getProperty("apollo.accesskey.secret");
if (!Utils.isBlank(accessKeySecret)) {
accessKeySecret = accessKeySecret.trim();
logger.info("ACCESSKEY SECRET is set by apollo.accesskey.secret property from {}",
APP_PROPERTIES_CLASSPATH);
return;
}
accessKeySecret = null;
}
@Override
public String toString() {
return "appId [" + getAppId() + "] properties: " + m_appProperties
+ " (DefaultApplicationProvider)";
}
}
| 1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/DefaultServerProvider.java | /*
* Copyright 2021 Apollo 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.
*
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.foundation.internals.provider;
import com.google.common.base.Strings;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import com.ctrip.framework.foundation.internals.Utils;
import com.ctrip.framework.foundation.internals.io.BOMInputStream;
import com.ctrip.framework.foundation.spi.provider.Provider;
import com.ctrip.framework.foundation.spi.provider.ServerProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DefaultServerProvider implements ServerProvider {
private static final Logger logger = LoggerFactory.getLogger(DefaultServerProvider.class);
static final String DEFAULT_SERVER_PROPERTIES_PATH_ON_LINUX = "/opt/settings/server.properties";
static final String DEFAULT_SERVER_PROPERTIES_PATH_ON_WINDOWS = "C:/opt/settings/server.properties";
private String m_env;
private String m_dc;
private final Properties m_serverProperties = new Properties();
String getServerPropertiesPath() {
final String serverPropertiesPath = getCustomizedServerPropertiesPath();
if (!Strings.isNullOrEmpty(serverPropertiesPath)) {
return serverPropertiesPath;
}
return Utils.isOSWindows() ? DEFAULT_SERVER_PROPERTIES_PATH_ON_WINDOWS : DEFAULT_SERVER_PROPERTIES_PATH_ON_LINUX;
}
private String getCustomizedServerPropertiesPath() {
// 1. Get from System Property
final String serverPropertiesPathFromSystemProperty = System
.getProperty("apollo.path.server.properties");
if (!Strings.isNullOrEmpty(serverPropertiesPathFromSystemProperty)) {
return serverPropertiesPathFromSystemProperty;
}
// 2. Get from OS environment variable
final String serverPropertiesPathFromEnvironment = System
.getenv("APOLLO_PATH_SERVER_PROPERTIES");
if (!Strings.isNullOrEmpty(serverPropertiesPathFromEnvironment)) {
return serverPropertiesPathFromEnvironment;
}
// last, return null if there is no custom value
return null;
}
@Override
public void initialize() {
try {
File file = new File(this.getServerPropertiesPath());
if (file.exists() && file.canRead()) {
logger.info("Loading {}", file.getAbsolutePath());
FileInputStream fis = new FileInputStream(file);
initialize(fis);
return;
}
initialize(null);
} catch (Throwable ex) {
logger.error("Initialize DefaultServerProvider failed.", ex);
}
}
@Override
public void initialize(InputStream in) {
try {
if (in != null) {
try {
m_serverProperties.load(new InputStreamReader(new BOMInputStream(in), StandardCharsets.UTF_8));
} finally {
in.close();
}
}
initEnvType();
initDataCenter();
} catch (Throwable ex) {
logger.error("Initialize DefaultServerProvider failed.", ex);
}
}
@Override
public String getDataCenter() {
return m_dc;
}
@Override
public boolean isDataCenterSet() {
return m_dc != null;
}
@Override
public String getEnvType() {
return m_env;
}
@Override
public boolean isEnvTypeSet() {
return m_env != null;
}
@Override
public String getProperty(String name, String defaultValue) {
if ("env".equalsIgnoreCase(name)) {
String val = getEnvType();
return val == null ? defaultValue : val;
}
if ("dc".equalsIgnoreCase(name)) {
String val = getDataCenter();
return val == null ? defaultValue : val;
}
String val = m_serverProperties.getProperty(name, defaultValue);
return val == null ? defaultValue : val.trim();
}
@Override
public Class<? extends Provider> getType() {
return ServerProvider.class;
}
private void initEnvType() {
// 1. Try to get environment from JVM system property
m_env = System.getProperty("env");
if (!Utils.isBlank(m_env)) {
m_env = m_env.trim();
logger.info("Environment is set to [{}] by JVM system property 'env'.", m_env);
return;
}
// 2. Try to get environment from OS environment variable
m_env = System.getenv("ENV");
if (!Utils.isBlank(m_env)) {
m_env = m_env.trim();
logger.info("Environment is set to [{}] by OS env variable 'ENV'.", m_env);
return;
}
// 3. Try to get environment from file "server.properties"
m_env = m_serverProperties.getProperty("env");
if (!Utils.isBlank(m_env)) {
m_env = m_env.trim();
logger.info("Environment is set to [{}] by property 'env' in server.properties.", m_env);
return;
}
// 4. Set environment to null.
m_env = null;
logger.info("Environment is set to null. Because it is not available in either (1) JVM system property 'env', (2) OS env variable 'ENV' nor (3) property 'env' from the properties InputStream.");
}
private void initDataCenter() {
// 1. Try to get environment from JVM system property
m_dc = System.getProperty("idc");
if (!Utils.isBlank(m_dc)) {
m_dc = m_dc.trim();
logger.info("Data Center is set to [{}] by JVM system property 'idc'.", m_dc);
return;
}
// 2. Try to get idc from OS environment variable
m_dc = System.getenv("IDC");
if (!Utils.isBlank(m_dc)) {
m_dc = m_dc.trim();
logger.info("Data Center is set to [{}] by OS env variable 'IDC'.", m_dc);
return;
}
// 3. Try to get idc from from file "server.properties"
m_dc = m_serverProperties.getProperty("idc");
if (!Utils.isBlank(m_dc)) {
m_dc = m_dc.trim();
logger.info("Data Center is set to [{}] by property 'idc' in server.properties.", m_dc);
return;
}
// 4. Set Data Center to null.
m_dc = null;
logger.debug("Data Center is set to null. Because it is not available in either (1) JVM system property 'idc', (2) OS env variable 'IDC' nor (3) property 'idc' from the properties InputStream.");
}
@Override
public String toString() {
return "environment [" + getEnvType() + "] data center [" + getDataCenter() + "] properties: " + m_serverProperties
+ " (DefaultServerProvider)";
}
}
| /*
* Copyright 2021 Apollo 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.
*
*/
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.foundation.internals.provider;
import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory;
import com.google.common.base.Strings;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import com.ctrip.framework.foundation.internals.Utils;
import com.ctrip.framework.foundation.internals.io.BOMInputStream;
import com.ctrip.framework.foundation.spi.provider.Provider;
import com.ctrip.framework.foundation.spi.provider.ServerProvider;
import org.slf4j.Logger;
public class DefaultServerProvider implements ServerProvider {
private static final Logger logger = DeferredLoggerFactory.getLogger(DefaultServerProvider.class);
static final String DEFAULT_SERVER_PROPERTIES_PATH_ON_LINUX = "/opt/settings/server.properties";
static final String DEFAULT_SERVER_PROPERTIES_PATH_ON_WINDOWS = "C:/opt/settings/server.properties";
private String m_env;
private String m_dc;
private final Properties m_serverProperties = new Properties();
String getServerPropertiesPath() {
final String serverPropertiesPath = getCustomizedServerPropertiesPath();
if (!Strings.isNullOrEmpty(serverPropertiesPath)) {
return serverPropertiesPath;
}
return Utils.isOSWindows() ? DEFAULT_SERVER_PROPERTIES_PATH_ON_WINDOWS
: DEFAULT_SERVER_PROPERTIES_PATH_ON_LINUX;
}
private String getCustomizedServerPropertiesPath() {
// 1. Get from System Property
final String serverPropertiesPathFromSystemProperty = System
.getProperty("apollo.path.server.properties");
if (!Strings.isNullOrEmpty(serverPropertiesPathFromSystemProperty)) {
return serverPropertiesPathFromSystemProperty;
}
// 2. Get from OS environment variable
final String serverPropertiesPathFromEnvironment = System
.getenv("APOLLO_PATH_SERVER_PROPERTIES");
if (!Strings.isNullOrEmpty(serverPropertiesPathFromEnvironment)) {
return serverPropertiesPathFromEnvironment;
}
// last, return null if there is no custom value
return null;
}
@Override
public void initialize() {
try {
File file = new File(this.getServerPropertiesPath());
if (file.exists() && file.canRead()) {
logger.info("Loading {}", file.getAbsolutePath());
FileInputStream fis = new FileInputStream(file);
initialize(fis);
return;
}
initialize(null);
} catch (Throwable ex) {
logger.error("Initialize DefaultServerProvider failed.", ex);
}
}
@Override
public void initialize(InputStream in) {
try {
if (in != null) {
try {
m_serverProperties
.load(new InputStreamReader(new BOMInputStream(in), StandardCharsets.UTF_8));
} finally {
in.close();
}
}
initEnvType();
initDataCenter();
} catch (Throwable ex) {
logger.error("Initialize DefaultServerProvider failed.", ex);
}
}
@Override
public String getDataCenter() {
return m_dc;
}
@Override
public boolean isDataCenterSet() {
return m_dc != null;
}
@Override
public String getEnvType() {
return m_env;
}
@Override
public boolean isEnvTypeSet() {
return m_env != null;
}
@Override
public String getProperty(String name, String defaultValue) {
if ("env".equalsIgnoreCase(name)) {
String val = getEnvType();
return val == null ? defaultValue : val;
}
if ("dc".equalsIgnoreCase(name)) {
String val = getDataCenter();
return val == null ? defaultValue : val;
}
String val = m_serverProperties.getProperty(name, defaultValue);
return val == null ? defaultValue : val.trim();
}
@Override
public Class<? extends Provider> getType() {
return ServerProvider.class;
}
private void initEnvType() {
// 1. Try to get environment from JVM system property
m_env = System.getProperty("env");
if (!Utils.isBlank(m_env)) {
m_env = m_env.trim();
logger.info("Environment is set to [{}] by JVM system property 'env'.", m_env);
return;
}
// 2. Try to get environment from OS environment variable
m_env = System.getenv("ENV");
if (!Utils.isBlank(m_env)) {
m_env = m_env.trim();
logger.info("Environment is set to [{}] by OS env variable 'ENV'.", m_env);
return;
}
// 3. Try to get environment from file "server.properties"
m_env = m_serverProperties.getProperty("env");
if (!Utils.isBlank(m_env)) {
m_env = m_env.trim();
logger.info("Environment is set to [{}] by property 'env' in server.properties.", m_env);
return;
}
// 4. Set environment to null.
m_env = null;
logger.info(
"Environment is set to null. Because it is not available in either (1) JVM system property 'env', (2) OS env variable 'ENV' nor (3) property 'env' from the properties InputStream.");
}
private void initDataCenter() {
// 1. Try to get environment from JVM system property
m_dc = System.getProperty("idc");
if (!Utils.isBlank(m_dc)) {
m_dc = m_dc.trim();
logger.info("Data Center is set to [{}] by JVM system property 'idc'.", m_dc);
return;
}
// 2. Try to get idc from OS environment variable
m_dc = System.getenv("IDC");
if (!Utils.isBlank(m_dc)) {
m_dc = m_dc.trim();
logger.info("Data Center is set to [{}] by OS env variable 'IDC'.", m_dc);
return;
}
// 3. Try to get idc from from file "server.properties"
m_dc = m_serverProperties.getProperty("idc");
if (!Utils.isBlank(m_dc)) {
m_dc = m_dc.trim();
logger.info("Data Center is set to [{}] by property 'idc' in server.properties.", m_dc);
return;
}
// 4. Set Data Center to null.
m_dc = null;
logger.debug(
"Data Center is set to null. Because it is not available in either (1) JVM system property 'idc', (2) OS env variable 'IDC' nor (3) property 'idc' from the properties InputStream.");
}
@Override
public String toString() {
return "environment [" + getEnvType() + "] data center [" + getDataCenter() + "] properties: "
+ m_serverProperties
+ " (DefaultServerProvider)";
}
}
| 1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-core/src/test/resources/log4j2.xml | <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<configuration monitorInterval="60">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="[apollo-client][%t]%d %-5p [%c] %m%n"/>
</Console>
<Async name="Async" includeLocation="true">
<AppenderRef ref="Console"/>
</Async>
</appenders>
<loggers>
<logger name="com.ctrip.framework.apollo" additivity="false" level="trace">
<AppenderRef ref="Async" level="WARN"/>
</logger>
<root level="INFO">
<AppenderRef ref="Async"/>
</root>
</loggers>
</configuration>
| <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<configuration monitorInterval="60">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="[apollo-client][%t]%d %-5p [%c] %m%n"/>
</Console>
<Async name="Async" includeLocation="true">
<AppenderRef ref="Console"/>
</Async>
</appenders>
<loggers>
<logger name="com.ctrip.framework.apollo" additivity="false" level="trace">
<AppenderRef ref="Async" level="WARN"/>
</logger>
<root level="debug">
<AppenderRef ref="Async"/>
</root>
</loggers>
</configuration>
| 1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-demo/src/main/resources/application.yml | #
# Copyright 2021 Apollo 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.
#
apollo:
bootstrap:
enabled: true
# will inject 'application' and 'TEST1.apollo' namespaces in bootstrap phase
namespaces: application,TEST1.apollo,application.yaml
| #
# Copyright 2021 Apollo 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.
#
apollo:
bootstrap:
enabled: true
eagerLoad:
enabled: true
# will inject 'application' and 'TEST1.apollo' namespaces in bootstrap phase
namespaces: application,TEST1.apollo,application.yaml
| 1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./docs/zh/usage/java-sdk-user-guide.md | >注意:本文档适用对象是Apollo系统的使用者,如果你是公司内Apollo系统的开发者/维护人员,建议先参考[Apollo开发指南](zh/development/apollo-development-guide)。
#
# 一、准备工作
## 1.1 环境要求
* Java: 1.7+
* Guava: 15.0+
* Apollo客户端默认会引用Guava 19,如果你的项目引用了其它版本,请确保版本号大于等于15.0
>注:对于Apollo客户端,如果有需要的话,可以做少量代码修改来降级到Java 1.6,详细信息可以参考[Issue 483](https://github.com/ctripcorp/apollo/issues/483)
## 1.2 必选设置
Apollo客户端依赖于`AppId`,`Apollo Meta Server`等环境信息来工作,所以请确保阅读下面的说明并且做正确的配置:
### 1.2.1 AppId
AppId是应用的身份信息,是从服务端获取配置的一个重要信息。
有以下几种方式设置,按照优先级从高到低分别为:
1. System Property
Apollo 0.7.0+支持通过System Property传入app.id信息,如
```bash
-Dapp.id=YOUR-APP-ID
```
2. 操作系统的System Environment
Apollo 1.4.0+支持通过操作系统的System Environment `APP_ID`来传入app.id信息,如
```bash
APP_ID=YOUR-APP-ID
```
3. Spring Boot application.properties
Apollo 1.0.0+支持通过Spring Boot的application.properties文件配置,如
```properties
app.id=YOUR-APP-ID
```
> 该配置方式不适用于多个war包部署在同一个tomcat的使用场景
4. app.properties
确保classpath:/META-INF/app.properties文件存在,并且其中内容形如:
>app.id=YOUR-APP-ID
文件位置参考如下:

> 注:app.id是用来标识应用身份的唯一id,格式为string。
### 1.2.2 Apollo Meta Server
Apollo支持应用在不同的环境有不同的配置,所以需要在运行提供给Apollo客户端当前环境的[Apollo Meta Server](zh/design/apollo-design?id=_133-meta-server)信息。默认情况下,meta server和config service是部署在同一个JVM进程,所以meta server的地址就是config service的地址。
为了实现meta server的高可用,推荐通过SLB(Software Load Balancer)做动态负载均衡。Meta server地址也可以填入IP,如`http://1.1.1.1:8080,http://2.2.2.2:8080`,不过生产环境还是建议使用域名(走slb),因为机器扩容、缩容等都可能导致IP列表的变化。
1.0.0版本开始支持以下方式配置apollo meta server信息,按照优先级从高到低分别为:
1. 通过Java System Property `apollo.meta`
* 可以通过Java的System Property `apollo.meta`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.meta=http://config-service-url`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.meta=http://config-service-url -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.meta", "http://config-service-url");`
2. 通过Spring Boot的配置文件
* 可以在Spring Boot的`application.properties`或`bootstrap.properties`中指定`apollo.meta=http://config-service-url`
> 该配置方式不适用于多个war包部署在同一个tomcat的使用场景
3. 通过操作系统的System Environment`APOLLO_META`
* 可以通过操作系统的System Environment `APOLLO_META`来指定
* 注意key为全大写,且中间是`_`分隔
4. 通过`server.properties`配置文件
* 可以在`server.properties`配置文件中指定`apollo.meta=http://config-service-url`
* 对于Mac/Linux,默认文件位置为`/opt/settings/server.properties`
* 对于Windows,默认文件位置为`C:\opt\settings\server.properties`
5. 通过`app.properties`配置文件
* 可以在`classpath:/META-INF/app.properties`指定`apollo.meta=http://config-service-url`
6. 通过Java system property `${env}_meta`
* 如果当前[env](#_1241-environment)是`dev`,那么用户可以配置`-Ddev_meta=http://config-service-url`
* 使用该配置方式,那么就必须要正确配置Environment,详见[1.2.4.1 Environment](#_1241-environment)
7. 通过操作系统的System Environment `${ENV}_META` (1.2.0版本开始支持)
* 如果当前[env](#_1241-environment)是`dev`,那么用户可以配置操作系统的System Environment `DEV_META=http://config-service-url`
* 注意key为全大写
* 使用该配置方式,那么就必须要正确配置Environment,详见[1.2.4.1 Environment](#_1241-environment)
8. 通过`apollo-env.properties`文件
* 用户也可以创建一个`apollo-env.properties`,放在程序的classpath下,或者放在spring boot应用的config目录下
* 使用该配置方式,那么就必须要正确配置Environment,详见[1.2.4.1 Environment](#_1241-environment)
* 文件内容形如:
```properties
dev.meta=http://1.1.1.1:8080
fat.meta=http://apollo.fat.xxx.com
uat.meta=http://apollo.uat.xxx.com
pro.meta=http://apollo.xxx.com
```
> 如果通过以上各种手段都无法获取到Meta Server地址,Apollo最终会fallback到`http://apollo.meta`作为Meta Server地址
#### 1.2.2.1 自定义Apollo Meta Server地址定位逻辑
在1.0.0版本中,Apollo提供了[MetaServerProvider SPI](https://github.com/ctripcorp/apollo/blob/master/apollo-core/src/main/java/com/ctrip/framework/apollo/core/spi/MetaServerProvider.java),用户可以注入自己的MetaServerProvider来自定义Meta Server地址定位逻辑。
由于我们使用典型的[Java Service Loader模式](https://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html),所以实现起来还是比较简单的。
有一点需要注意的是,apollo会在运行时按照顺序遍历所有的MetaServerProvider,直到某一个MetaServerProvider提供了一个非空的Meta Server地址,因此用户需要格外注意自定义MetaServerProvider的Order。规则是较小的Order具有较高的优先级,因此Order=0的MetaServerProvider会排在Order=1的MetaServerProvider的前面。
**如果你的公司有很多应用需要接入Apollo,建议封装一个jar包,然后提供自定义的Apollo Meta Server定位逻辑,从而可以让接入Apollo的应用零配置使用。比如自己写一个`xx-company-apollo-client`,该jar包依赖`apollo-client`,在该jar包中通过spi方式定义自定义的MetaServerProvider实现,然后应用直接依赖`xx-company-apollo-client`即可。**
MetaServerProvider的实现可以参考[LegacyMetaServerProvider](https://github.com/ctripcorp/apollo/blob/master/apollo-core/src/main/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProvider.java)和[DefaultMetaServerProvider](https://github.com/ctripcorp/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProvider.java)。
#### 1.2.2.2 跳过Apollo Meta Server服务发现
> 适用于apollo-client 0.11.0及以上版本
一般情况下都建议使用Apollo的Meta Server机制来实现Config Service的服务发现,从而可以实现Config Service的高可用。不过apollo-client也支持跳过Meta Server服务发现,主要用于以下场景:
1. Config Service部署在公有云上,注册到Meta Server的是内网地址,本地开发环境无法直接连接
* 如果通过公网 SLB 对外暴露 Config Service的话,记得要设置 IP 白名单,避免数据泄露
2. Config Service部署在docker环境中,注册到Meta Server的是docker内网地址,本地开发环境无法直接连接
3. Config Service部署在kubernetes中,希望使用kubernetes自带的服务发现能力(Service)
针对以上场景,可以通过直接指定Config Service地址的方式来跳过Meta Server服务发现,按照优先级从高到低分别为:
1. 通过Java System Property `apollo.configService`
* 可以通过Java的System Property `apollo.configService`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.configService=http://config-service-url:port`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.configService=http://config-service-url:port -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.configService", "http://config-service-url:port");`
2. 通过操作系统的System Environment`APOLLO_CONFIGSERVICE`
* 可以通过操作系统的System Environment `APOLLO_CONFIGSERVICE`来指定
* 注意key为全大写,且中间是`_`分隔
4. 通过`server.properties`配置文件
* 可以在`server.properties`配置文件中指定`apollo.configService=http://config-service-url:port`
* 对于Mac/Linux,默认文件位置为`/opt/settings/server.properties`
* 对于Windows,默认文件位置为`C:\opt\settings\server.properties`
### 1.2.3 本地缓存路径
Apollo客户端会把从服务端获取到的配置在本地文件系统缓存一份,用于在遇到服务不可用,或网络不通的时候,依然能从本地恢复配置,不影响应用正常运行。
本地缓存路径默认位于以下路径,所以请确保`/opt/data`或`C:\opt\data\`目录存在,且应用有读写权限。
* **Mac/Linux**: /opt/data/{_appId_}/config-cache
* **Windows**: C:\opt\data\\{_appId_}\config-cache
本地配置文件会以下面的文件名格式放置于本地缓存路径下:
**_{appId}+{cluster}+{namespace}.properties_**
* appId就是应用自己的appId,如100004458
* cluster就是应用使用的集群,一般在本地模式下没有做过配置的话,就是default
* namespace就是应用使用的配置namespace,一般是application

文件内容以properties格式存储,比如如果有两个key,一个是request.timeout,另一个是batch,那么文件内容就是如下格式:
```properties
request.timeout=2000
batch=2000
```
#### 1.2.3.1 自定义缓存路径
1.0.0版本开始支持以下方式自定义缓存路径,按照优先级从高到低分别为:
1. 通过Java System Property `apollo.cacheDir`
* 可以通过Java的System Property `apollo.cacheDir`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.cacheDir=/opt/data/some-cache-dir`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.cacheDir=/opt/data/some-cache-dir -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.cacheDir", "/opt/data/some-cache-dir");`
2. 通过Spring Boot的配置文件
* 可以在Spring Boot的`application.properties`或`bootstrap.properties`中指定`apollo.cacheDir=/opt/data/some-cache-dir`
3. 通过操作系统的System Environment`APOLLO_CACHEDIR`
* 可以通过操作系统的System Environment `APOLLO_CACHEDIR`来指定
* 注意key为全大写,且中间是`_`分隔
4. 通过`server.properties`配置文件
* 可以在`server.properties`配置文件中指定`apollo.cacheDir=/opt/data/some-cache-dir`
* 对于Mac/Linux,默认文件位置为`/opt/settings/server.properties`
* 对于Windows,默认文件位置为`C:\opt\settings\server.properties`
> 注:本地缓存路径也可用于容灾目录,如果应用在所有config service都挂掉的情况下需要扩容,那么也可以先把配置从已有机器上的缓存路径复制到新机器上的相同缓存路径
### 1.2.4 可选设置
#### 1.2.4.1 Environment
Environment可以通过以下3种方式的任意一个配置:
1. 通过Java System Property
* 可以通过Java的System Property `env`来指定环境
* 在Java程序启动脚本中,可以指定`-Denv=YOUR-ENVIRONMENT`
* 如果是运行jar文件,需要注意格式是`java -Denv=YOUR-ENVIRONMENT -jar xxx.jar`
* 注意key为全小写
2. 通过操作系统的System Environment
* 还可以通过操作系统的System Environment `ENV`来指定
* 注意key为全大写
3. 通过配置文件
* 最后一个推荐的方式是通过配置文件来指定`env=YOUR-ENVIRONMENT`
* 对于Mac/Linux,默认文件位置为`/opt/settings/server.properties`
* 对于Windows,默认文件位置为`C:\opt\settings\server.properties`
文件内容形如:
```properties
env=DEV
```
目前,`env`支持以下几个值(大小写不敏感):
* DEV
* Development environment
* FAT
* Feature Acceptance Test environment
* UAT
* User Acceptance Test environment
* PRO
* Production environment
更多环境定义,可以参考[Env.java](https://github.com/ctripcorp/apollo/blob/master/apollo-core/src/main/java/com/ctrip/framework/apollo/core/enums/Env.java)
#### 1.2.4.2 Cluster(集群)
Apollo支持配置按照集群划分,也就是说对于一个appId和一个环境,对不同的集群可以有不同的配置。
1.0.0版本开始支持以下方式集群,按照优先级从高到低分别为:
1. 通过Java System Property `apollo.cluster`
* 可以通过Java的System Property `apollo.cluster`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.cluster=SomeCluster`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.cluster=SomeCluster -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.cluster", "SomeCluster");`
2. 通过Spring Boot的配置文件
* 可以在Spring Boot的`application.properties`或`bootstrap.properties`中指定`apollo.cluster=SomeCluster`
3. 通过Java System Property
* 可以通过Java的System Property `idc`来指定环境
* 在Java程序启动脚本中,可以指定`-Didc=xxx`
* 如果是运行jar文件,需要注意格式是`java -Didc=xxx -jar xxx.jar`
* 注意key为全小写
4. 通过操作系统的System Environment
* 还可以通过操作系统的System Environment `IDC`来指定
* 注意key为全大写
5. 通过`server.properties`配置文件
* 可以在`server.properties`配置文件中指定`idc=xxx`
* 对于Mac/Linux,默认文件位置为`/opt/settings/server.properties`
* 对于Windows,默认文件位置为`C:\opt\settings\server.properties`
**Cluster Precedence**(集群顺序)
1. 如果`apollo.cluster`和`idc`同时指定:
* 我们会首先尝试从`apollo.cluster`指定的集群加载配置
* 如果没找到任何配置,会尝试从`idc`指定的集群加载配置
* 如果还是没找到,会从默认的集群(`default`)加载
2. 如果只指定了`apollo.cluster`:
* 我们会首先尝试从`apollo.cluster`指定的集群加载配置
* 如果没找到,会从默认的集群(`default`)加载
3. 如果只指定了`idc`:
* 我们会首先尝试从`idc`指定的集群加载配置
* 如果没找到,会从默认的集群(`default`)加载
4. 如果`apollo.cluster`和`idc`都没有指定:
* 我们会从默认的集群(`default`)加载配置
#### 1.2.4.3 设置内存中的配置项是否保持和页面上的顺序一致
> 适用于1.6.0及以上版本
默认情况下,apollo client内存中的配置存放在Properties中(底下是Hashtable),不会刻意保持和页面上看到的顺序一致,对绝大部分的场景是没有影响的。不过有些场景会强依赖配置项的顺序(如spring cloud zuul的路由规则),针对这种情况,可以开启OrderedProperties特性来使得内存中的配置顺序和页面上看到的一致。
配置方式按照优先级从高到低分别为:
1. 通过Java System Property `apollo.property.order.enable`
* 可以通过Java的System Property `apollo.property.order.enable`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.property.order.enable=true`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.property.order.enable=true -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.property.order.enable", "true");`
2. 通过Spring Boot的配置文件
* 可以在Spring Boot的`application.properties`或`bootstrap.properties`中指定`apollo.property.order.enable=true`
3. 通过`app.properties`配置文件
* 可以在`classpath:/META-INF/app.properties`指定`apollo.property.order.enable=true`
#### 1.2.4.4 配置访问密钥
> 适用于1.6.0及以上版本
Apollo从1.6.0版本开始增加访问密钥机制,从而只有经过身份验证的客户端才能访问敏感配置。如果应用开启了访问密钥,客户端需要配置密钥,否则无法获取配置。
配置方式按照优先级从高到低分别为:
1. 通过Java System Property `apollo.accesskey.secret`
* 可以通过Java的System Property `apollo.accesskey.secret`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.accesskey.secret=1cf998c4e2ad4704b45a98a509d15719`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.accesskey.secret=1cf998c4e2ad4704b45a98a509d15719 -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.accesskey.secret", "1cf998c4e2ad4704b45a98a509d15719");`
2. 通过Spring Boot的配置文件
* 可以在Spring Boot的`application.properties`或`bootstrap.properties`中指定`apollo.accesskey.secret=1cf998c4e2ad4704b45a98a509d15719`
3. 通过操作系统的System Environment
* 还可以通过操作系统的System Environment `APOLLO_ACCESSKEY_SECRET`来指定
* 注意key为全大写
4. 通过`app.properties`配置文件
* 可以在`classpath:/META-INF/app.properties`指定`apollo.accesskey.secret=1cf998c4e2ad4704b45a98a509d15719`
#### 1.2.4.5 自定义server.properties路径
> 适用于1.8.0及以上版本
1.8.0版本开始支持以下方式自定义server.properties路径,按照优先级从高到低分别为:
1. 通过Java System Property `apollo.path.server.properties`
* 可以通过Java的System Property `apollo.path.server.properties`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.path.server.properties=/some-dir/some-file.properties`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.path.server.properties=/some-dir/some-file.properties -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.path.server.properties", "/some-dir/some-file.properties");`
2. 通过操作系统的System Environment`APOLLO_PATH_SERVER_PROPERTIES`
* 可以通过操作系统的System Environment `APOLLO_PATH_SERVER_PROPERTIES`来指定
* 注意key为全大写,且中间是`_`分隔
# 二、Maven Dependency
Apollo的客户端jar包已经上传到中央仓库,应用在实际使用时只需要按照如下方式引入即可。
```xml
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.7.0</version>
</dependency>
```
# 三、客户端用法
Apollo支持API方式和Spring整合方式,该怎么选择用哪一种方式?
* API方式灵活,功能完备,配置值实时更新(热发布),支持所有Java环境。
* Spring方式接入简单,结合Spring有N种酷炫的玩法,如
* Placeholder方式:
* 代码中直接使用,如:`@Value("${someKeyFromApollo:someDefaultValue}")`
* 配置文件中使用替换placeholder,如:`spring.datasource.url: ${someKeyFromApollo:someDefaultValue}`
* 直接托管spring的配置,如在apollo中直接配置`spring.datasource.url=jdbc:mysql://localhost:3306/somedb?characterEncoding=utf8`
* Spring boot的[@ConfigurationProperties](http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/properties/ConfigurationProperties.html)方式
* 从v0.10.0开始的版本支持placeholder在运行时自动更新,具体参见[PR #972](https://github.com/ctripcorp/apollo/pull/972)。(v0.10.0之前的版本在配置变化后不会重新注入,需要重启才会更新,如果需要配置值实时更新,可以参考后续[3.2.2 Spring Placeholder的使用](#_322-spring-placeholder的使用)的说明)
* Spring方式也可以结合API方式使用,如注入Apollo的Config对象,就可以照常通过API方式获取配置了:
```java
@ApolloConfig
private Config config; //inject config for namespace application
```
* 更多有意思的实际使用场景和示例代码,请参考[apollo-use-cases](https://github.com/ctripcorp/apollo-use-cases)
## 3.1 API使用方式
API方式是最简单、高效使用Apollo配置的方式,不依赖Spring框架即可使用。
### 3.1.1 获取默认namespace的配置(application)
```java
Config config = ConfigService.getAppConfig(); //config instance is singleton for each namespace and is never null
String someKey = "someKeyFromDefaultNamespace";
String someDefaultValue = "someDefaultValueForTheKey";
String value = config.getProperty(someKey, someDefaultValue);
```
通过上述的**config.getProperty**可以获取到someKey对应的实时最新的配置值。
另外,配置值从内存中获取,所以不需要应用自己做缓存。
### 3.1.2 监听配置变化事件
监听配置变化事件只在应用真的关心配置变化,需要在配置变化时得到通知时使用,比如:数据库连接串变化后需要重建连接等。
如果只是希望每次都取到最新的配置的话,只需要按照上面的例子,调用**config.getProperty**即可。
```java
Config config = ConfigService.getAppConfig(); //config instance is singleton for each namespace and is never null
config.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
System.out.println("Changes for namespace " + changeEvent.getNamespace());
for (String key : changeEvent.changedKeys()) {
ConfigChange change = changeEvent.getChange(key);
System.out.println(String.format("Found change - key: %s, oldValue: %s, newValue: %s, changeType: %s", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()));
}
}
});
```
### 3.1.3 获取公共Namespace的配置
```java
String somePublicNamespace = "CAT";
Config config = ConfigService.getConfig(somePublicNamespace); //config instance is singleton for each namespace and is never null
String someKey = "someKeyFromPublicNamespace";
String someDefaultValue = "someDefaultValueForTheKey";
String value = config.getProperty(someKey, someDefaultValue);
```
### 3.1.4 获取非properties格式namespace的配置
#### 3.1.4.1 yaml/yml格式的namespace
apollo-client 1.3.0版本开始对yaml/yml做了更好的支持,使用起来和properties格式一致。
```java
Config config = ConfigService.getConfig("application.yml");
String someKey = "someKeyFromYmlNamespace";
String someDefaultValue = "someDefaultValueForTheKey";
String value = config.getProperty(someKey, someDefaultValue);
```
#### 3.1.4.2 非yaml/yml格式的namespace
获取时需要使用`ConfigService.getConfigFile`接口并指定Format,如`ConfigFileFormat.XML`。
```java
String someNamespace = "test";
ConfigFile configFile = ConfigService.getConfigFile("test", ConfigFileFormat.XML);
String content = configFile.getContent();
```
## 3.2 Spring整合方式
### 3.2.1 配置
Apollo也支持和Spring整合(Spring 3.1.1+),只需要做一些简单的配置就可以了。
Apollo目前既支持比较传统的`基于XML`的配置,也支持目前比较流行的`基于Java(推荐)`的配置。
如果是Spring Boot环境,建议参照[3.2.1.3 Spring Boot集成方式(推荐)](#_3213-spring-boot集成方式(推荐))配置。
需要注意的是,如果之前有使用`org.springframework.beans.factory.config.PropertyPlaceholderConfigurer`的,请替换成`org.springframework.context.support.PropertySourcesPlaceholderConfigurer`。Spring 3.1以后就不建议使用PropertyPlaceholderConfigurer了,要改用PropertySourcesPlaceholderConfigurer。
如果之前有使用`<context:property-placeholder>`,请注意xml中引入的`spring-context.xsd`版本需要是3.1以上(一般只要没有指定版本会自动升级的),建议使用不带版本号的形式引入,如:`http://www.springframework.org/schema/context/spring-context.xsd`
> 注1:yaml/yml格式的namespace从1.3.0版本开始支持和Spring整合,注入时需要填写带后缀的完整名字,比如application.yml
> 注2:非properties、非yaml/yml格式(如xml,json等)的namespace暂不支持和Spring整合。
#### 3.2.1.1 基于XML的配置
>注:需要把apollo相关的xml namespace加到配置文件头上,不然会报xml语法错误。
1.注入默认namespace的配置到Spring中
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<!-- 这个是最简单的配置形式,一般应用用这种形式就可以了,用来指示Apollo注入application namespace的配置到Spring环境中 -->
<apollo:config/>
<bean class="com.ctrip.framework.apollo.spring.TestXmlBean">
<property name="timeout" value="${timeout:100}"/>
<property name="batch" value="${batch:200}"/>
</bean>
</beans>
```
2.注入多个namespace的配置到Spring中
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<!-- 这个是最简单的配置形式,一般应用用这种形式就可以了,用来指示Apollo注入application namespace的配置到Spring环境中 -->
<apollo:config/>
<!-- 这个是稍微复杂一些的配置形式,指示Apollo注入FX.apollo和application.yml namespace的配置到Spring环境中 -->
<apollo:config namespaces="FX.apollo,application.yml"/>
<bean class="com.ctrip.framework.apollo.spring.TestXmlBean">
<property name="timeout" value="${timeout:100}"/>
<property name="batch" value="${batch:200}"/>
</bean>
</beans>
```
3.注入多个namespace,并且指定顺序
Spring的配置是有顺序的,如果多个property source都有同一个key,那么最终是顺序在前的配置生效。
<apollo:config>如果不指定order,那么默认是最低优先级。
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<apollo:config order="2"/>
<!-- 这个是最复杂的配置形式,指示Apollo注入FX.apollo和application.yml namespace的配置到Spring环境中,并且顺序在application前面 -->
<apollo:config namespaces="FX.apollo,application.yml" order="1"/>
<bean class="com.ctrip.framework.apollo.spring.TestXmlBean">
<property name="timeout" value="${timeout:100}"/>
<property name="batch" value="${batch:200}"/>
</bean>
</beans>
```
#### 3.2.1.2 基于Java的配置(推荐)
相对于基于XML的配置,基于Java的配置是目前比较流行的方式。
注意`@EnableApolloConfig`要和`@Configuration`一起使用,不然不会生效。
1.注入默认namespace的配置到Spring中
```java
//这个是最简单的配置形式,一般应用用这种形式就可以了,用来指示Apollo注入application namespace的配置到Spring环境中
@Configuration
@EnableApolloConfig
public class AppConfig {
@Bean
public TestJavaConfigBean javaConfigBean() {
return new TestJavaConfigBean();
}
}
```
2.注入多个namespace的配置到Spring中
```java
@Configuration
@EnableApolloConfig
public class SomeAppConfig {
@Bean
public TestJavaConfigBean javaConfigBean() {
return new TestJavaConfigBean();
}
}
//这个是稍微复杂一些的配置形式,指示Apollo注入FX.apollo和application.yml namespace的配置到Spring环境中
@Configuration
@EnableApolloConfig({"FX.apollo", "application.yml"})
public class AnotherAppConfig {}
```
3.注入多个namespace,并且指定顺序
```java
//这个是最复杂的配置形式,指示Apollo注入FX.apollo和application.yml namespace的配置到Spring环境中,并且顺序在application前面
@Configuration
@EnableApolloConfig(order = 2)
public class SomeAppConfig {
@Bean
public TestJavaConfigBean javaConfigBean() {
return new TestJavaConfigBean();
}
}
@Configuration
@EnableApolloConfig(value = {"FX.apollo", "application.yml"}, order = 1)
public class AnotherAppConfig {}
```
#### 3.2.1.3 Spring Boot集成方式(推荐)
Spring Boot除了支持上述两种集成方式以外,还支持通过application.properties/bootstrap.properties来配置,该方式能使配置在更早的阶段注入,比如使用`@ConditionalOnProperty`的场景或者是有一些spring-boot-starter在启动阶段就需要读取配置做一些事情(如[dubbo-spring-boot-project](https://github.com/apache/incubator-dubbo-spring-boot-project)),所以对于Spring Boot环境建议通过以下方式来接入Apollo(需要0.10.0及以上版本)。
使用方式很简单,只需要在application.properties/bootstrap.properties中按照如下样例配置即可。
1. 注入默认`application` namespace的配置示例
```properties
# will inject 'application' namespace in bootstrap phase
apollo.bootstrap.enabled = true
```
2. 注入非默认`application` namespace或多个namespace的配置示例
```properties
apollo.bootstrap.enabled = true
# will inject 'application', 'FX.apollo' and 'application.yml' namespaces in bootstrap phase
apollo.bootstrap.namespaces = application,FX.apollo,application.yml
```
3. 将Apollo配置加载提到初始化日志系统之前(1.2.0+)
从1.2.0版本开始,如果希望把日志相关的配置(如`logging.level.root=info`或`logback-spring.xml`中的参数)也放在Apollo管理,那么可以额外配置`apollo.bootstrap.eagerLoad.enabled=true`来使Apollo的加载顺序放到日志系统加载之前,不过这会导致Apollo的启动过程无法通过日志的方式输出(因为执行Apollo加载的时候,日志系统压根没有准备好呢!所以在Apollo代码中使用Slf4j的日志输出便没有任何内容),更多信息可以参考[PR 1614](https://github.com/ctripcorp/apollo/pull/1614)。参考配置示例如下:
```properties
# will inject 'application' namespace in bootstrap phase
apollo.bootstrap.enabled = true
# put apollo initialization before logging system initialization
apollo.bootstrap.eagerLoad.enabled=true
```
### 3.2.2 Spring Placeholder的使用
Spring应用通常会使用Placeholder来注入配置,使用的格式形如${someKey:someDefaultValue},如${timeout:100}。冒号前面的是key,冒号后面的是默认值。
建议在实际使用时尽量给出默认值,以免由于key没有定义导致运行时错误。
从v0.10.0开始的版本支持placeholder在运行时自动更新,具体参见[PR #972](https://github.com/ctripcorp/apollo/pull/972)。
如果需要关闭placeholder在运行时自动更新功能,可以通过以下两种方式关闭:
1. 通过设置System Property `apollo.autoUpdateInjectedSpringProperties`,如启动时传入`-Dapollo.autoUpdateInjectedSpringProperties=false`
2. 通过设置META-INF/app.properties中的`apollo.autoUpdateInjectedSpringProperties`属性,如
```properties
app.id=SampleApp
apollo.autoUpdateInjectedSpringProperties=false
```
#### 3.2.2.1 XML使用方式
假设我有一个TestXmlBean,它有两个配置项需要注入:
```java
public class TestXmlBean {
private int timeout;
private int batch;
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public void setBatch(int batch) {
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
```
那么,我在XML中会使用如下方式来定义(假设应用默认的application namespace中有timeout和batch的配置项):
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<apollo:config/>
<bean class="com.ctrip.framework.apollo.spring.TestXmlBean">
<property name="timeout" value="${timeout:100}"/>
<property name="batch" value="${batch:200}"/>
</bean>
</beans>
```
#### 3.2.2.2 Java Config使用方式
假设我有一个TestJavaConfigBean,通过Java Config的方式还可以使用@Value的方式注入:
```java
public class TestJavaConfigBean {
@Value("${timeout:100}")
private int timeout;
private int batch;
@Value("${batch:200}")
public void setBatch(int batch) {
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
```
在Configuration类中按照下面的方式使用(假设应用默认的application namespace中有`timeout`和`batch`的配置项):
```java
@Configuration
@EnableApolloConfig
public class AppConfig {
@Bean
public TestJavaConfigBean javaConfigBean() {
return new TestJavaConfigBean();
}
}
```
#### 3.2.2.3 ConfigurationProperties使用方式
Spring Boot提供了[@ConfigurationProperties](http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/properties/ConfigurationProperties.html)把配置注入到bean对象中。
Apollo也支持这种方式,下面的例子会把`redis.cache.expireSeconds`和`redis.cache.commandTimeout`分别注入到SampleRedisConfig的`expireSeconds`和`commandTimeout`字段中。
```java
@ConfigurationProperties(prefix = "redis.cache")
public class SampleRedisConfig {
private int expireSeconds;
private int commandTimeout;
public void setExpireSeconds(int expireSeconds) {
this.expireSeconds = expireSeconds;
}
public void setCommandTimeout(int commandTimeout) {
this.commandTimeout = commandTimeout;
}
}
```
在Configuration类中按照下面的方式使用(假设应用默认的application namespace中有`redis.cache.expireSeconds`和`redis.cache.commandTimeout`的配置项):
```java
@Configuration
@EnableApolloConfig
public class AppConfig {
@Bean
public SampleRedisConfig sampleRedisConfig() {
return new SampleRedisConfig();
}
}
```
需要注意的是,`@ConfigurationProperties`如果需要在Apollo配置变化时自动更新注入的值,需要配合使用[EnvironmentChangeEvent](https://cloud.spring.io/spring-cloud-static/spring-cloud.html#_environment_changes)或[RefreshScope](https://cloud.spring.io/spring-cloud-static/spring-cloud.html#_refresh_scope)。相关代码实现,可以参考apollo-use-cases项目中的[ZuulPropertiesRefresher.java](https://github.com/ctripcorp/apollo-use-cases/blob/master/spring-cloud-zuul/src/main/java/com/ctrip/framework/apollo/use/cases/spring/cloud/zuul/ZuulPropertiesRefresher.java#L48)和apollo-demo项目中的[SampleRedisConfig.java](https://github.com/ctripcorp/apollo/blob/master/apollo-demo/src/main/java/com/ctrip/framework/apollo/demo/spring/springBootDemo/config/SampleRedisConfig.java)以及[SpringBootApolloRefreshConfig.java](https://github.com/ctripcorp/apollo/blob/master/apollo-demo/src/main/java/com/ctrip/framework/apollo/demo/spring/springBootDemo/refresh/SpringBootApolloRefreshConfig.java)
### 3.2.3 Spring Annotation支持
Apollo同时还增加了几个新的Annotation来简化在Spring环境中的使用。
1. @ApolloConfig
* 用来自动注入Config对象
2. @ApolloConfigChangeListener
* 用来自动注册ConfigChangeListener
3. @ApolloJsonValue
* 用来把配置的json字符串自动注入为对象
使用样例如下:
```java
public class TestApolloAnnotationBean {
@ApolloConfig
private Config config; //inject config for namespace application
@ApolloConfig("application")
private Config anotherConfig; //inject config for namespace application
@ApolloConfig("FX.apollo")
private Config yetAnotherConfig; //inject config for namespace FX.apollo
@ApolloConfig("application.yml")
private Config ymlConfig; //inject config for namespace application.yml
/**
* ApolloJsonValue annotated on fields example, the default value is specified as empty list - []
* <br />
* jsonBeanProperty=[{"someString":"hello","someInt":100},{"someString":"world!","someInt":200}]
*/
@ApolloJsonValue("${jsonBeanProperty:[]}")
private List<JsonBean> anotherJsonBeans;
@Value("${batch:100}")
private int batch;
//config change listener for namespace application
@ApolloConfigChangeListener
private void someOnChange(ConfigChangeEvent changeEvent) {
//update injected value of batch if it is changed in Apollo
if (changeEvent.isChanged("batch")) {
batch = config.getIntProperty("batch", 100);
}
}
//config change listener for namespace application
@ApolloConfigChangeListener("application")
private void anotherOnChange(ConfigChangeEvent changeEvent) {
//do something
}
//config change listener for namespaces application, FX.apollo and application.yml
@ApolloConfigChangeListener({"application", "FX.apollo", "application.yml"})
private void yetAnotherOnChange(ConfigChangeEvent changeEvent) {
//do something
}
//example of getting config from Apollo directly
//this will always return the latest value of timeout
public int getTimeout() {
return config.getIntProperty("timeout", 200);
}
//example of getting config from injected value
//the program needs to update the injected value when batch is changed in Apollo using @ApolloConfigChangeListener shown above
public int getBatch() {
return this.batch;
}
private static class JsonBean{
private String someString;
private int someInt;
}
}
```
在Configuration类中按照下面的方式使用:
```java
@Configuration
@EnableApolloConfig
public class AppConfig {
@Bean
public TestApolloAnnotationBean testApolloAnnotationBean() {
return new TestApolloAnnotationBean();
}
}
```
### 3.2.4 已有配置迁移
很多情况下,应用可能已经有不少配置了,比如Spring Boot的应用,就会有bootstrap.properties/yml, application.properties/yml等配置。
在应用接入Apollo之后,这些配置是可以非常方便的迁移到Apollo的,具体步骤如下:
1. 在Apollo为应用新建项目
2. 在应用中配置好META-INF/app.properties
3. 建议把原先配置先转为properties格式,然后通过Apollo提供的文本编辑模式全部粘帖到应用的application namespace,发布配置
* 如果原来格式是yml,可以使用[YamlPropertiesFactoryBean.getObject](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/config/YamlPropertiesFactoryBean.html#getObject--)转成properties格式
4. 如果原来是yml,想继续使用yml来编辑配置,那么可以创建私有的application.yml namespace,把原来的配置全部粘贴进去,发布配置
* 需要apollo-client是1.3.0及以上版本
5. 把原先的配置文件如bootstrap.properties/yml, application.properties/yml从项目中删除
* 如果需要保留本地配置文件,需要注意部分配置如`server.port`必须确保本地文件已经删除该配置项
如:
```properties
spring.application.name = reservation-service
server.port = 8080
logging.level = ERROR
eureka.client.serviceUrl.defaultZone = http://127.0.0.1:8761/eureka/
eureka.client.healthcheck.enabled = true
eureka.client.registerWithEureka = true
eureka.client.fetchRegistry = true
eureka.client.eurekaServiceUrlPollIntervalSeconds = 60
eureka.instance.preferIpAddress = true
```

## 3.3 Demo
项目中有一个样例客户端的项目:`apollo-demo`,具体信息可以参考[Apollo开发指南](zh/development/apollo-development-guide)中的[2.3 Java样例客户端启动](zh/development/apollo-development-guide?id=_23-java样例客户端启动)部分。
更多使用案例Demo可以参考[Apollo使用场景和示例代码](https://github.com/ctripcorp/apollo-use-cases)。
# 四、客户端设计

上图简要描述了Apollo客户端的实现原理:
1. 客户端和服务端保持了一个长连接,从而能第一时间获得配置更新的推送。(通过Http Long Polling实现)
2. 客户端还会定时从Apollo配置中心服务端拉取应用的最新配置。
* 这是一个fallback机制,为了防止推送机制失效导致配置不更新
* 客户端定时拉取会上报本地版本,所以一般情况下,对于定时拉取的操作,服务端都会返回304 - Not Modified
* 定时频率默认为每5分钟拉取一次,客户端也可以通过在运行时指定System Property: `apollo.refreshInterval`来覆盖,单位为分钟。
3. 客户端从Apollo配置中心服务端获取到应用的最新配置后,会保存在内存中
4. 客户端会把从服务端获取到的配置在本地文件系统缓存一份
* 在遇到服务不可用,或网络不通的时候,依然能从本地恢复配置
5. 应用程序可以从Apollo客户端获取最新的配置、订阅配置更新通知
# 五、本地开发模式
Apollo客户端还支持本地开发模式,这个主要用于当开发环境无法连接Apollo服务器的时候,比如在邮轮、飞机上做相关功能开发。
在本地开发模式下,Apollo只会从本地文件读取配置信息,不会从Apollo服务器读取配置。
可以通过下面的步骤开启Apollo本地开发模式。
## 5.1 修改环境
修改/opt/settings/server.properties(Mac/Linux)或C:\opt\settings\server.properties(Windows)文件,设置env为Local:
```properties
env=Local
```
更多配置环境的方式请参考[1.2.4.1 Environment](#_1241-environment)
## 5.2 准备本地配置文件
在本地开发模式下,Apollo客户端会从本地读取文件,所以我们需要事先准备好配置文件。
### 5.2.1 本地配置目录
本地配置目录位于:
* **Mac/Linux**: /opt/data/{_appId_}/config-cache
* **Windows**: C:\opt\data\\{_appId_}\config-cache
appId就是应用的appId,如100004458。
请确保该目录存在,且应用程序对该目录有读权限。
**【小技巧】** 推荐的方式是先在普通模式下使用Apollo,这样Apollo会自动创建该目录并在目录下生成配置文件。
### 5.2.2 本地配置文件
本地配置文件需要按照一定的文件名格式放置于本地配置目录下,文件名格式如下:
**_{appId}+{cluster}+{namespace}.properties_**
* appId就是应用自己的appId,如100004458
* cluster就是应用使用的集群,一般在本地模式下没有做过配置的话,就是default
* namespace就是应用使用的配置namespace,一般是application

文件内容以properties格式存储,比如如果有两个key,一个是request.timeout,另一个是batch,那么文件内容就是如下格式:
```properties
request.timeout=2000
batch=2000
```
## 5.3 修改配置
在本地开发模式下,Apollo不会实时监测文件内容是否有变化,所以如果修改了配置,需要重启应用生效。
# 六、测试模式
1.1.0版本开始增加了`apollo-mockserver`,从而可以很好地支持单元测试时需要mock配置的场景,使用方法如下:
## 6.1 引入pom依赖
```xml
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-mockserver</artifactId>
<version>1.7.0</version>
</dependency>
```
## 6.2 在test的resources下放置mock的数据
文件名格式约定为`mockdata-{namespace}.properties`

## 6.3 写测试类
更多使用demo可以参考[ApolloMockServerApiTest.java](https://github.com/ctripcorp/apollo/blob/master/apollo-mockserver/src/test/java/com/ctrip/framework/apollo/mockserver/ApolloMockServerApiTest.java)和[ApolloMockServerSpringIntegrationTest.java](https://github.com/ctripcorp/apollo/blob/master/apollo-mockserver/src/test/java/com/ctrip/framework/apollo/mockserver/ApolloMockServerSpringIntegrationTest.java)。
```java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
public class SpringIntegrationTest {
// 启动apollo的mockserver
@ClassRule
public static EmbeddedApollo embeddedApollo = new EmbeddedApollo();
@Test
@DirtiesContext // 这个注解很有必要,因为配置注入会弄脏应用上下文
public void testPropertyInject(){
assertEquals("value1", testBean.key1);
assertEquals("value2", testBean.key2);
}
@Test
@DirtiesContext
public void testListenerTriggeredByAdd() throws InterruptedException, ExecutionException, TimeoutException {
String otherNamespace = "othernamespace";
embeddedApollo.addOrModifyPropery(otherNamespace,"someKey","someValue");
ConfigChangeEvent changeEvent = testBean.futureData.get(5000, TimeUnit.MILLISECONDS);
assertEquals(otherNamespace, changeEvent.getNamespace());
assertEquals("someValue", changeEvent.getChange("someKey").getNewValue());
}
@EnableApolloConfig("application")
@Configuration
static class TestConfiguration{
@Bean
public TestBean testBean(){
return new TestBean();
}
}
static class TestBean{
@Value("${key1:default}")
String key1;
@Value("${key2:default}")
String key2;
SettableFuture<ConfigChangeEvent> futureData = SettableFuture.create();
@ApolloConfigChangeListener("othernamespace")
private void onChange(ConfigChangeEvent changeEvent) {
futureData.set(changeEvent);
}
}
}
```
| >注意:本文档适用对象是Apollo系统的使用者,如果你是公司内Apollo系统的开发者/维护人员,建议先参考[Apollo开发指南](zh/development/apollo-development-guide)。
#
# 一、准备工作
## 1.1 环境要求
* Java: 1.7+
* Guava: 15.0+
* Apollo客户端默认会引用Guava 19,如果你的项目引用了其它版本,请确保版本号大于等于15.0
>注:对于Apollo客户端,如果有需要的话,可以做少量代码修改来降级到Java 1.6,详细信息可以参考[Issue 483](https://github.com/ctripcorp/apollo/issues/483)
## 1.2 必选设置
Apollo客户端依赖于`AppId`,`Apollo Meta Server`等环境信息来工作,所以请确保阅读下面的说明并且做正确的配置:
### 1.2.1 AppId
AppId是应用的身份信息,是从服务端获取配置的一个重要信息。
有以下几种方式设置,按照优先级从高到低分别为:
1. System Property
Apollo 0.7.0+支持通过System Property传入app.id信息,如
```bash
-Dapp.id=YOUR-APP-ID
```
2. 操作系统的System Environment
Apollo 1.4.0+支持通过操作系统的System Environment `APP_ID`来传入app.id信息,如
```bash
APP_ID=YOUR-APP-ID
```
3. Spring Boot application.properties
Apollo 1.0.0+支持通过Spring Boot的application.properties文件配置,如
```properties
app.id=YOUR-APP-ID
```
> 该配置方式不适用于多个war包部署在同一个tomcat的使用场景
4. app.properties
确保classpath:/META-INF/app.properties文件存在,并且其中内容形如:
>app.id=YOUR-APP-ID
文件位置参考如下:

> 注:app.id是用来标识应用身份的唯一id,格式为string。
### 1.2.2 Apollo Meta Server
Apollo支持应用在不同的环境有不同的配置,所以需要在运行提供给Apollo客户端当前环境的[Apollo Meta Server](zh/design/apollo-design?id=_133-meta-server)信息。默认情况下,meta server和config service是部署在同一个JVM进程,所以meta server的地址就是config service的地址。
为了实现meta server的高可用,推荐通过SLB(Software Load Balancer)做动态负载均衡。Meta server地址也可以填入IP,如`http://1.1.1.1:8080,http://2.2.2.2:8080`,不过生产环境还是建议使用域名(走slb),因为机器扩容、缩容等都可能导致IP列表的变化。
1.0.0版本开始支持以下方式配置apollo meta server信息,按照优先级从高到低分别为:
1. 通过Java System Property `apollo.meta`
* 可以通过Java的System Property `apollo.meta`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.meta=http://config-service-url`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.meta=http://config-service-url -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.meta", "http://config-service-url");`
2. 通过Spring Boot的配置文件
* 可以在Spring Boot的`application.properties`或`bootstrap.properties`中指定`apollo.meta=http://config-service-url`
> 该配置方式不适用于多个war包部署在同一个tomcat的使用场景
3. 通过操作系统的System Environment`APOLLO_META`
* 可以通过操作系统的System Environment `APOLLO_META`来指定
* 注意key为全大写,且中间是`_`分隔
4. 通过`server.properties`配置文件
* 可以在`server.properties`配置文件中指定`apollo.meta=http://config-service-url`
* 对于Mac/Linux,默认文件位置为`/opt/settings/server.properties`
* 对于Windows,默认文件位置为`C:\opt\settings\server.properties`
5. 通过`app.properties`配置文件
* 可以在`classpath:/META-INF/app.properties`指定`apollo.meta=http://config-service-url`
6. 通过Java system property `${env}_meta`
* 如果当前[env](#_1241-environment)是`dev`,那么用户可以配置`-Ddev_meta=http://config-service-url`
* 使用该配置方式,那么就必须要正确配置Environment,详见[1.2.4.1 Environment](#_1241-environment)
7. 通过操作系统的System Environment `${ENV}_META` (1.2.0版本开始支持)
* 如果当前[env](#_1241-environment)是`dev`,那么用户可以配置操作系统的System Environment `DEV_META=http://config-service-url`
* 注意key为全大写
* 使用该配置方式,那么就必须要正确配置Environment,详见[1.2.4.1 Environment](#_1241-environment)
8. 通过`apollo-env.properties`文件
* 用户也可以创建一个`apollo-env.properties`,放在程序的classpath下,或者放在spring boot应用的config目录下
* 使用该配置方式,那么就必须要正确配置Environment,详见[1.2.4.1 Environment](#_1241-environment)
* 文件内容形如:
```properties
dev.meta=http://1.1.1.1:8080
fat.meta=http://apollo.fat.xxx.com
uat.meta=http://apollo.uat.xxx.com
pro.meta=http://apollo.xxx.com
```
> 如果通过以上各种手段都无法获取到Meta Server地址,Apollo最终会fallback到`http://apollo.meta`作为Meta Server地址
#### 1.2.2.1 自定义Apollo Meta Server地址定位逻辑
在1.0.0版本中,Apollo提供了[MetaServerProvider SPI](https://github.com/ctripcorp/apollo/blob/master/apollo-core/src/main/java/com/ctrip/framework/apollo/core/spi/MetaServerProvider.java),用户可以注入自己的MetaServerProvider来自定义Meta Server地址定位逻辑。
由于我们使用典型的[Java Service Loader模式](https://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html),所以实现起来还是比较简单的。
有一点需要注意的是,apollo会在运行时按照顺序遍历所有的MetaServerProvider,直到某一个MetaServerProvider提供了一个非空的Meta Server地址,因此用户需要格外注意自定义MetaServerProvider的Order。规则是较小的Order具有较高的优先级,因此Order=0的MetaServerProvider会排在Order=1的MetaServerProvider的前面。
**如果你的公司有很多应用需要接入Apollo,建议封装一个jar包,然后提供自定义的Apollo Meta Server定位逻辑,从而可以让接入Apollo的应用零配置使用。比如自己写一个`xx-company-apollo-client`,该jar包依赖`apollo-client`,在该jar包中通过spi方式定义自定义的MetaServerProvider实现,然后应用直接依赖`xx-company-apollo-client`即可。**
MetaServerProvider的实现可以参考[LegacyMetaServerProvider](https://github.com/ctripcorp/apollo/blob/master/apollo-core/src/main/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProvider.java)和[DefaultMetaServerProvider](https://github.com/ctripcorp/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProvider.java)。
#### 1.2.2.2 跳过Apollo Meta Server服务发现
> 适用于apollo-client 0.11.0及以上版本
一般情况下都建议使用Apollo的Meta Server机制来实现Config Service的服务发现,从而可以实现Config Service的高可用。不过apollo-client也支持跳过Meta Server服务发现,主要用于以下场景:
1. Config Service部署在公有云上,注册到Meta Server的是内网地址,本地开发环境无法直接连接
* 如果通过公网 SLB 对外暴露 Config Service的话,记得要设置 IP 白名单,避免数据泄露
2. Config Service部署在docker环境中,注册到Meta Server的是docker内网地址,本地开发环境无法直接连接
3. Config Service部署在kubernetes中,希望使用kubernetes自带的服务发现能力(Service)
针对以上场景,可以通过直接指定Config Service地址的方式来跳过Meta Server服务发现,按照优先级从高到低分别为:
1. 通过Java System Property `apollo.configService`
* 可以通过Java的System Property `apollo.configService`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.configService=http://config-service-url:port`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.configService=http://config-service-url:port -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.configService", "http://config-service-url:port");`
2. 通过操作系统的System Environment`APOLLO_CONFIGSERVICE`
* 可以通过操作系统的System Environment `APOLLO_CONFIGSERVICE`来指定
* 注意key为全大写,且中间是`_`分隔
4. 通过`server.properties`配置文件
* 可以在`server.properties`配置文件中指定`apollo.configService=http://config-service-url:port`
* 对于Mac/Linux,默认文件位置为`/opt/settings/server.properties`
* 对于Windows,默认文件位置为`C:\opt\settings\server.properties`
### 1.2.3 本地缓存路径
Apollo客户端会把从服务端获取到的配置在本地文件系统缓存一份,用于在遇到服务不可用,或网络不通的时候,依然能从本地恢复配置,不影响应用正常运行。
本地缓存路径默认位于以下路径,所以请确保`/opt/data`或`C:\opt\data\`目录存在,且应用有读写权限。
* **Mac/Linux**: /opt/data/{_appId_}/config-cache
* **Windows**: C:\opt\data\\{_appId_}\config-cache
本地配置文件会以下面的文件名格式放置于本地缓存路径下:
**_{appId}+{cluster}+{namespace}.properties_**
* appId就是应用自己的appId,如100004458
* cluster就是应用使用的集群,一般在本地模式下没有做过配置的话,就是default
* namespace就是应用使用的配置namespace,一般是application

文件内容以properties格式存储,比如如果有两个key,一个是request.timeout,另一个是batch,那么文件内容就是如下格式:
```properties
request.timeout=2000
batch=2000
```
#### 1.2.3.1 自定义缓存路径
1.0.0版本开始支持以下方式自定义缓存路径,按照优先级从高到低分别为:
1. 通过Java System Property `apollo.cacheDir`
* 可以通过Java的System Property `apollo.cacheDir`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.cacheDir=/opt/data/some-cache-dir`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.cacheDir=/opt/data/some-cache-dir -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.cacheDir", "/opt/data/some-cache-dir");`
2. 通过Spring Boot的配置文件
* 可以在Spring Boot的`application.properties`或`bootstrap.properties`中指定`apollo.cacheDir=/opt/data/some-cache-dir`
3. 通过操作系统的System Environment`APOLLO_CACHEDIR`
* 可以通过操作系统的System Environment `APOLLO_CACHEDIR`来指定
* 注意key为全大写,且中间是`_`分隔
4. 通过`server.properties`配置文件
* 可以在`server.properties`配置文件中指定`apollo.cacheDir=/opt/data/some-cache-dir`
* 对于Mac/Linux,默认文件位置为`/opt/settings/server.properties`
* 对于Windows,默认文件位置为`C:\opt\settings\server.properties`
> 注:本地缓存路径也可用于容灾目录,如果应用在所有config service都挂掉的情况下需要扩容,那么也可以先把配置从已有机器上的缓存路径复制到新机器上的相同缓存路径
### 1.2.4 可选设置
#### 1.2.4.1 Environment
Environment可以通过以下3种方式的任意一个配置:
1. 通过Java System Property
* 可以通过Java的System Property `env`来指定环境
* 在Java程序启动脚本中,可以指定`-Denv=YOUR-ENVIRONMENT`
* 如果是运行jar文件,需要注意格式是`java -Denv=YOUR-ENVIRONMENT -jar xxx.jar`
* 注意key为全小写
2. 通过操作系统的System Environment
* 还可以通过操作系统的System Environment `ENV`来指定
* 注意key为全大写
3. 通过配置文件
* 最后一个推荐的方式是通过配置文件来指定`env=YOUR-ENVIRONMENT`
* 对于Mac/Linux,默认文件位置为`/opt/settings/server.properties`
* 对于Windows,默认文件位置为`C:\opt\settings\server.properties`
文件内容形如:
```properties
env=DEV
```
目前,`env`支持以下几个值(大小写不敏感):
* DEV
* Development environment
* FAT
* Feature Acceptance Test environment
* UAT
* User Acceptance Test environment
* PRO
* Production environment
更多环境定义,可以参考[Env.java](https://github.com/ctripcorp/apollo/blob/master/apollo-core/src/main/java/com/ctrip/framework/apollo/core/enums/Env.java)
#### 1.2.4.2 Cluster(集群)
Apollo支持配置按照集群划分,也就是说对于一个appId和一个环境,对不同的集群可以有不同的配置。
1.0.0版本开始支持以下方式集群,按照优先级从高到低分别为:
1. 通过Java System Property `apollo.cluster`
* 可以通过Java的System Property `apollo.cluster`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.cluster=SomeCluster`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.cluster=SomeCluster -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.cluster", "SomeCluster");`
2. 通过Spring Boot的配置文件
* 可以在Spring Boot的`application.properties`或`bootstrap.properties`中指定`apollo.cluster=SomeCluster`
3. 通过Java System Property
* 可以通过Java的System Property `idc`来指定环境
* 在Java程序启动脚本中,可以指定`-Didc=xxx`
* 如果是运行jar文件,需要注意格式是`java -Didc=xxx -jar xxx.jar`
* 注意key为全小写
4. 通过操作系统的System Environment
* 还可以通过操作系统的System Environment `IDC`来指定
* 注意key为全大写
5. 通过`server.properties`配置文件
* 可以在`server.properties`配置文件中指定`idc=xxx`
* 对于Mac/Linux,默认文件位置为`/opt/settings/server.properties`
* 对于Windows,默认文件位置为`C:\opt\settings\server.properties`
**Cluster Precedence**(集群顺序)
1. 如果`apollo.cluster`和`idc`同时指定:
* 我们会首先尝试从`apollo.cluster`指定的集群加载配置
* 如果没找到任何配置,会尝试从`idc`指定的集群加载配置
* 如果还是没找到,会从默认的集群(`default`)加载
2. 如果只指定了`apollo.cluster`:
* 我们会首先尝试从`apollo.cluster`指定的集群加载配置
* 如果没找到,会从默认的集群(`default`)加载
3. 如果只指定了`idc`:
* 我们会首先尝试从`idc`指定的集群加载配置
* 如果没找到,会从默认的集群(`default`)加载
4. 如果`apollo.cluster`和`idc`都没有指定:
* 我们会从默认的集群(`default`)加载配置
#### 1.2.4.3 设置内存中的配置项是否保持和页面上的顺序一致
> 适用于1.6.0及以上版本
默认情况下,apollo client内存中的配置存放在Properties中(底下是Hashtable),不会刻意保持和页面上看到的顺序一致,对绝大部分的场景是没有影响的。不过有些场景会强依赖配置项的顺序(如spring cloud zuul的路由规则),针对这种情况,可以开启OrderedProperties特性来使得内存中的配置顺序和页面上看到的一致。
配置方式按照优先级从高到低分别为:
1. 通过Java System Property `apollo.property.order.enable`
* 可以通过Java的System Property `apollo.property.order.enable`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.property.order.enable=true`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.property.order.enable=true -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.property.order.enable", "true");`
2. 通过Spring Boot的配置文件
* 可以在Spring Boot的`application.properties`或`bootstrap.properties`中指定`apollo.property.order.enable=true`
3. 通过`app.properties`配置文件
* 可以在`classpath:/META-INF/app.properties`指定`apollo.property.order.enable=true`
#### 1.2.4.4 配置访问密钥
> 适用于1.6.0及以上版本
Apollo从1.6.0版本开始增加访问密钥机制,从而只有经过身份验证的客户端才能访问敏感配置。如果应用开启了访问密钥,客户端需要配置密钥,否则无法获取配置。
配置方式按照优先级从高到低分别为:
1. 通过Java System Property `apollo.accesskey.secret`
* 可以通过Java的System Property `apollo.accesskey.secret`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.accesskey.secret=1cf998c4e2ad4704b45a98a509d15719`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.accesskey.secret=1cf998c4e2ad4704b45a98a509d15719 -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.accesskey.secret", "1cf998c4e2ad4704b45a98a509d15719");`
2. 通过Spring Boot的配置文件
* 可以在Spring Boot的`application.properties`或`bootstrap.properties`中指定`apollo.accesskey.secret=1cf998c4e2ad4704b45a98a509d15719`
3. 通过操作系统的System Environment
* 还可以通过操作系统的System Environment `APOLLO_ACCESSKEY_SECRET`来指定
* 注意key为全大写
4. 通过`app.properties`配置文件
* 可以在`classpath:/META-INF/app.properties`指定`apollo.accesskey.secret=1cf998c4e2ad4704b45a98a509d15719`
#### 1.2.4.5 自定义server.properties路径
> 适用于1.8.0及以上版本
1.8.0版本开始支持以下方式自定义server.properties路径,按照优先级从高到低分别为:
1. 通过Java System Property `apollo.path.server.properties`
* 可以通过Java的System Property `apollo.path.server.properties`来指定
* 在Java程序启动脚本中,可以指定`-Dapollo.path.server.properties=/some-dir/some-file.properties`
* 如果是运行jar文件,需要注意格式是`java -Dapollo.path.server.properties=/some-dir/some-file.properties -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("apollo.path.server.properties", "/some-dir/some-file.properties");`
2. 通过操作系统的System Environment`APOLLO_PATH_SERVER_PROPERTIES`
* 可以通过操作系统的System Environment `APOLLO_PATH_SERVER_PROPERTIES`来指定
* 注意key为全大写,且中间是`_`分隔
# 二、Maven Dependency
Apollo的客户端jar包已经上传到中央仓库,应用在实际使用时只需要按照如下方式引入即可。
```xml
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.7.0</version>
</dependency>
```
# 三、客户端用法
Apollo支持API方式和Spring整合方式,该怎么选择用哪一种方式?
* API方式灵活,功能完备,配置值实时更新(热发布),支持所有Java环境。
* Spring方式接入简单,结合Spring有N种酷炫的玩法,如
* Placeholder方式:
* 代码中直接使用,如:`@Value("${someKeyFromApollo:someDefaultValue}")`
* 配置文件中使用替换placeholder,如:`spring.datasource.url: ${someKeyFromApollo:someDefaultValue}`
* 直接托管spring的配置,如在apollo中直接配置`spring.datasource.url=jdbc:mysql://localhost:3306/somedb?characterEncoding=utf8`
* Spring boot的[@ConfigurationProperties](http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/properties/ConfigurationProperties.html)方式
* 从v0.10.0开始的版本支持placeholder在运行时自动更新,具体参见[PR #972](https://github.com/ctripcorp/apollo/pull/972)。(v0.10.0之前的版本在配置变化后不会重新注入,需要重启才会更新,如果需要配置值实时更新,可以参考后续[3.2.2 Spring Placeholder的使用](#_322-spring-placeholder的使用)的说明)
* Spring方式也可以结合API方式使用,如注入Apollo的Config对象,就可以照常通过API方式获取配置了:
```java
@ApolloConfig
private Config config; //inject config for namespace application
```
* 更多有意思的实际使用场景和示例代码,请参考[apollo-use-cases](https://github.com/ctripcorp/apollo-use-cases)
## 3.1 API使用方式
API方式是最简单、高效使用Apollo配置的方式,不依赖Spring框架即可使用。
### 3.1.1 获取默认namespace的配置(application)
```java
Config config = ConfigService.getAppConfig(); //config instance is singleton for each namespace and is never null
String someKey = "someKeyFromDefaultNamespace";
String someDefaultValue = "someDefaultValueForTheKey";
String value = config.getProperty(someKey, someDefaultValue);
```
通过上述的**config.getProperty**可以获取到someKey对应的实时最新的配置值。
另外,配置值从内存中获取,所以不需要应用自己做缓存。
### 3.1.2 监听配置变化事件
监听配置变化事件只在应用真的关心配置变化,需要在配置变化时得到通知时使用,比如:数据库连接串变化后需要重建连接等。
如果只是希望每次都取到最新的配置的话,只需要按照上面的例子,调用**config.getProperty**即可。
```java
Config config = ConfigService.getAppConfig(); //config instance is singleton for each namespace and is never null
config.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
System.out.println("Changes for namespace " + changeEvent.getNamespace());
for (String key : changeEvent.changedKeys()) {
ConfigChange change = changeEvent.getChange(key);
System.out.println(String.format("Found change - key: %s, oldValue: %s, newValue: %s, changeType: %s", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()));
}
}
});
```
### 3.1.3 获取公共Namespace的配置
```java
String somePublicNamespace = "CAT";
Config config = ConfigService.getConfig(somePublicNamespace); //config instance is singleton for each namespace and is never null
String someKey = "someKeyFromPublicNamespace";
String someDefaultValue = "someDefaultValueForTheKey";
String value = config.getProperty(someKey, someDefaultValue);
```
### 3.1.4 获取非properties格式namespace的配置
#### 3.1.4.1 yaml/yml格式的namespace
apollo-client 1.3.0版本开始对yaml/yml做了更好的支持,使用起来和properties格式一致。
```java
Config config = ConfigService.getConfig("application.yml");
String someKey = "someKeyFromYmlNamespace";
String someDefaultValue = "someDefaultValueForTheKey";
String value = config.getProperty(someKey, someDefaultValue);
```
#### 3.1.4.2 非yaml/yml格式的namespace
获取时需要使用`ConfigService.getConfigFile`接口并指定Format,如`ConfigFileFormat.XML`。
```java
String someNamespace = "test";
ConfigFile configFile = ConfigService.getConfigFile("test", ConfigFileFormat.XML);
String content = configFile.getContent();
```
## 3.2 Spring整合方式
### 3.2.1 配置
Apollo也支持和Spring整合(Spring 3.1.1+),只需要做一些简单的配置就可以了。
Apollo目前既支持比较传统的`基于XML`的配置,也支持目前比较流行的`基于Java(推荐)`的配置。
如果是Spring Boot环境,建议参照[3.2.1.3 Spring Boot集成方式(推荐)](#_3213-spring-boot集成方式(推荐))配置。
需要注意的是,如果之前有使用`org.springframework.beans.factory.config.PropertyPlaceholderConfigurer`的,请替换成`org.springframework.context.support.PropertySourcesPlaceholderConfigurer`。Spring 3.1以后就不建议使用PropertyPlaceholderConfigurer了,要改用PropertySourcesPlaceholderConfigurer。
如果之前有使用`<context:property-placeholder>`,请注意xml中引入的`spring-context.xsd`版本需要是3.1以上(一般只要没有指定版本会自动升级的),建议使用不带版本号的形式引入,如:`http://www.springframework.org/schema/context/spring-context.xsd`
> 注1:yaml/yml格式的namespace从1.3.0版本开始支持和Spring整合,注入时需要填写带后缀的完整名字,比如application.yml
> 注2:非properties、非yaml/yml格式(如xml,json等)的namespace暂不支持和Spring整合。
#### 3.2.1.1 基于XML的配置
>注:需要把apollo相关的xml namespace加到配置文件头上,不然会报xml语法错误。
1.注入默认namespace的配置到Spring中
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<!-- 这个是最简单的配置形式,一般应用用这种形式就可以了,用来指示Apollo注入application namespace的配置到Spring环境中 -->
<apollo:config/>
<bean class="com.ctrip.framework.apollo.spring.TestXmlBean">
<property name="timeout" value="${timeout:100}"/>
<property name="batch" value="${batch:200}"/>
</bean>
</beans>
```
2.注入多个namespace的配置到Spring中
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<!-- 这个是最简单的配置形式,一般应用用这种形式就可以了,用来指示Apollo注入application namespace的配置到Spring环境中 -->
<apollo:config/>
<!-- 这个是稍微复杂一些的配置形式,指示Apollo注入FX.apollo和application.yml namespace的配置到Spring环境中 -->
<apollo:config namespaces="FX.apollo,application.yml"/>
<bean class="com.ctrip.framework.apollo.spring.TestXmlBean">
<property name="timeout" value="${timeout:100}"/>
<property name="batch" value="${batch:200}"/>
</bean>
</beans>
```
3.注入多个namespace,并且指定顺序
Spring的配置是有顺序的,如果多个property source都有同一个key,那么最终是顺序在前的配置生效。
<apollo:config>如果不指定order,那么默认是最低优先级。
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<apollo:config order="2"/>
<!-- 这个是最复杂的配置形式,指示Apollo注入FX.apollo和application.yml namespace的配置到Spring环境中,并且顺序在application前面 -->
<apollo:config namespaces="FX.apollo,application.yml" order="1"/>
<bean class="com.ctrip.framework.apollo.spring.TestXmlBean">
<property name="timeout" value="${timeout:100}"/>
<property name="batch" value="${batch:200}"/>
</bean>
</beans>
```
#### 3.2.1.2 基于Java的配置(推荐)
相对于基于XML的配置,基于Java的配置是目前比较流行的方式。
注意`@EnableApolloConfig`要和`@Configuration`一起使用,不然不会生效。
1.注入默认namespace的配置到Spring中
```java
//这个是最简单的配置形式,一般应用用这种形式就可以了,用来指示Apollo注入application namespace的配置到Spring环境中
@Configuration
@EnableApolloConfig
public class AppConfig {
@Bean
public TestJavaConfigBean javaConfigBean() {
return new TestJavaConfigBean();
}
}
```
2.注入多个namespace的配置到Spring中
```java
@Configuration
@EnableApolloConfig
public class SomeAppConfig {
@Bean
public TestJavaConfigBean javaConfigBean() {
return new TestJavaConfigBean();
}
}
//这个是稍微复杂一些的配置形式,指示Apollo注入FX.apollo和application.yml namespace的配置到Spring环境中
@Configuration
@EnableApolloConfig({"FX.apollo", "application.yml"})
public class AnotherAppConfig {}
```
3.注入多个namespace,并且指定顺序
```java
//这个是最复杂的配置形式,指示Apollo注入FX.apollo和application.yml namespace的配置到Spring环境中,并且顺序在application前面
@Configuration
@EnableApolloConfig(order = 2)
public class SomeAppConfig {
@Bean
public TestJavaConfigBean javaConfigBean() {
return new TestJavaConfigBean();
}
}
@Configuration
@EnableApolloConfig(value = {"FX.apollo", "application.yml"}, order = 1)
public class AnotherAppConfig {}
```
#### 3.2.1.3 Spring Boot集成方式(推荐)
Spring Boot除了支持上述两种集成方式以外,还支持通过application.properties/bootstrap.properties来配置,该方式能使配置在更早的阶段注入,比如使用`@ConditionalOnProperty`的场景或者是有一些spring-boot-starter在启动阶段就需要读取配置做一些事情(如[dubbo-spring-boot-project](https://github.com/apache/incubator-dubbo-spring-boot-project)),所以对于Spring Boot环境建议通过以下方式来接入Apollo(需要0.10.0及以上版本)。
使用方式很简单,只需要在application.properties/bootstrap.properties中按照如下样例配置即可。
1. 注入默认`application` namespace的配置示例
```properties
# will inject 'application' namespace in bootstrap phase
apollo.bootstrap.enabled = true
```
2. 注入非默认`application` namespace或多个namespace的配置示例
```properties
apollo.bootstrap.enabled = true
# will inject 'application', 'FX.apollo' and 'application.yml' namespaces in bootstrap phase
apollo.bootstrap.namespaces = application,FX.apollo,application.yml
```
3. 将Apollo配置加载提到初始化日志系统之前(1.2.0+)
从1.2.0版本开始,如果希望把日志相关的配置(如`logging.level.root=info`或`logback-spring.xml`中的参数)也放在Apollo管理,那么可以额外配置`apollo.bootstrap.eagerLoad.enabled=true`来使Apollo的加载顺序放到日志系统加载之前,更多信息可以参考[PR 1614](https://github.com/ctripcorp/apollo/pull/1614)。参考配置示例如下:
```properties
# will inject 'application' namespace in bootstrap phase
apollo.bootstrap.enabled = true
# put apollo initialization before logging system initialization
apollo.bootstrap.eagerLoad.enabled=true
```
### 3.2.2 Spring Placeholder的使用
Spring应用通常会使用Placeholder来注入配置,使用的格式形如${someKey:someDefaultValue},如${timeout:100}。冒号前面的是key,冒号后面的是默认值。
建议在实际使用时尽量给出默认值,以免由于key没有定义导致运行时错误。
从v0.10.0开始的版本支持placeholder在运行时自动更新,具体参见[PR #972](https://github.com/ctripcorp/apollo/pull/972)。
如果需要关闭placeholder在运行时自动更新功能,可以通过以下两种方式关闭:
1. 通过设置System Property `apollo.autoUpdateInjectedSpringProperties`,如启动时传入`-Dapollo.autoUpdateInjectedSpringProperties=false`
2. 通过设置META-INF/app.properties中的`apollo.autoUpdateInjectedSpringProperties`属性,如
```properties
app.id=SampleApp
apollo.autoUpdateInjectedSpringProperties=false
```
#### 3.2.2.1 XML使用方式
假设我有一个TestXmlBean,它有两个配置项需要注入:
```java
public class TestXmlBean {
private int timeout;
private int batch;
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public void setBatch(int batch) {
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
```
那么,我在XML中会使用如下方式来定义(假设应用默认的application namespace中有timeout和batch的配置项):
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<apollo:config/>
<bean class="com.ctrip.framework.apollo.spring.TestXmlBean">
<property name="timeout" value="${timeout:100}"/>
<property name="batch" value="${batch:200}"/>
</bean>
</beans>
```
#### 3.2.2.2 Java Config使用方式
假设我有一个TestJavaConfigBean,通过Java Config的方式还可以使用@Value的方式注入:
```java
public class TestJavaConfigBean {
@Value("${timeout:100}")
private int timeout;
private int batch;
@Value("${batch:200}")
public void setBatch(int batch) {
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
```
在Configuration类中按照下面的方式使用(假设应用默认的application namespace中有`timeout`和`batch`的配置项):
```java
@Configuration
@EnableApolloConfig
public class AppConfig {
@Bean
public TestJavaConfigBean javaConfigBean() {
return new TestJavaConfigBean();
}
}
```
#### 3.2.2.3 ConfigurationProperties使用方式
Spring Boot提供了[@ConfigurationProperties](http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/properties/ConfigurationProperties.html)把配置注入到bean对象中。
Apollo也支持这种方式,下面的例子会把`redis.cache.expireSeconds`和`redis.cache.commandTimeout`分别注入到SampleRedisConfig的`expireSeconds`和`commandTimeout`字段中。
```java
@ConfigurationProperties(prefix = "redis.cache")
public class SampleRedisConfig {
private int expireSeconds;
private int commandTimeout;
public void setExpireSeconds(int expireSeconds) {
this.expireSeconds = expireSeconds;
}
public void setCommandTimeout(int commandTimeout) {
this.commandTimeout = commandTimeout;
}
}
```
在Configuration类中按照下面的方式使用(假设应用默认的application namespace中有`redis.cache.expireSeconds`和`redis.cache.commandTimeout`的配置项):
```java
@Configuration
@EnableApolloConfig
public class AppConfig {
@Bean
public SampleRedisConfig sampleRedisConfig() {
return new SampleRedisConfig();
}
}
```
需要注意的是,`@ConfigurationProperties`如果需要在Apollo配置变化时自动更新注入的值,需要配合使用[EnvironmentChangeEvent](https://cloud.spring.io/spring-cloud-static/spring-cloud.html#_environment_changes)或[RefreshScope](https://cloud.spring.io/spring-cloud-static/spring-cloud.html#_refresh_scope)。相关代码实现,可以参考apollo-use-cases项目中的[ZuulPropertiesRefresher.java](https://github.com/ctripcorp/apollo-use-cases/blob/master/spring-cloud-zuul/src/main/java/com/ctrip/framework/apollo/use/cases/spring/cloud/zuul/ZuulPropertiesRefresher.java#L48)和apollo-demo项目中的[SampleRedisConfig.java](https://github.com/ctripcorp/apollo/blob/master/apollo-demo/src/main/java/com/ctrip/framework/apollo/demo/spring/springBootDemo/config/SampleRedisConfig.java)以及[SpringBootApolloRefreshConfig.java](https://github.com/ctripcorp/apollo/blob/master/apollo-demo/src/main/java/com/ctrip/framework/apollo/demo/spring/springBootDemo/refresh/SpringBootApolloRefreshConfig.java)
### 3.2.3 Spring Annotation支持
Apollo同时还增加了几个新的Annotation来简化在Spring环境中的使用。
1. @ApolloConfig
* 用来自动注入Config对象
2. @ApolloConfigChangeListener
* 用来自动注册ConfigChangeListener
3. @ApolloJsonValue
* 用来把配置的json字符串自动注入为对象
使用样例如下:
```java
public class TestApolloAnnotationBean {
@ApolloConfig
private Config config; //inject config for namespace application
@ApolloConfig("application")
private Config anotherConfig; //inject config for namespace application
@ApolloConfig("FX.apollo")
private Config yetAnotherConfig; //inject config for namespace FX.apollo
@ApolloConfig("application.yml")
private Config ymlConfig; //inject config for namespace application.yml
/**
* ApolloJsonValue annotated on fields example, the default value is specified as empty list - []
* <br />
* jsonBeanProperty=[{"someString":"hello","someInt":100},{"someString":"world!","someInt":200}]
*/
@ApolloJsonValue("${jsonBeanProperty:[]}")
private List<JsonBean> anotherJsonBeans;
@Value("${batch:100}")
private int batch;
//config change listener for namespace application
@ApolloConfigChangeListener
private void someOnChange(ConfigChangeEvent changeEvent) {
//update injected value of batch if it is changed in Apollo
if (changeEvent.isChanged("batch")) {
batch = config.getIntProperty("batch", 100);
}
}
//config change listener for namespace application
@ApolloConfigChangeListener("application")
private void anotherOnChange(ConfigChangeEvent changeEvent) {
//do something
}
//config change listener for namespaces application, FX.apollo and application.yml
@ApolloConfigChangeListener({"application", "FX.apollo", "application.yml"})
private void yetAnotherOnChange(ConfigChangeEvent changeEvent) {
//do something
}
//example of getting config from Apollo directly
//this will always return the latest value of timeout
public int getTimeout() {
return config.getIntProperty("timeout", 200);
}
//example of getting config from injected value
//the program needs to update the injected value when batch is changed in Apollo using @ApolloConfigChangeListener shown above
public int getBatch() {
return this.batch;
}
private static class JsonBean{
private String someString;
private int someInt;
}
}
```
在Configuration类中按照下面的方式使用:
```java
@Configuration
@EnableApolloConfig
public class AppConfig {
@Bean
public TestApolloAnnotationBean testApolloAnnotationBean() {
return new TestApolloAnnotationBean();
}
}
```
### 3.2.4 已有配置迁移
很多情况下,应用可能已经有不少配置了,比如Spring Boot的应用,就会有bootstrap.properties/yml, application.properties/yml等配置。
在应用接入Apollo之后,这些配置是可以非常方便的迁移到Apollo的,具体步骤如下:
1. 在Apollo为应用新建项目
2. 在应用中配置好META-INF/app.properties
3. 建议把原先配置先转为properties格式,然后通过Apollo提供的文本编辑模式全部粘帖到应用的application namespace,发布配置
* 如果原来格式是yml,可以使用[YamlPropertiesFactoryBean.getObject](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/config/YamlPropertiesFactoryBean.html#getObject--)转成properties格式
4. 如果原来是yml,想继续使用yml来编辑配置,那么可以创建私有的application.yml namespace,把原来的配置全部粘贴进去,发布配置
* 需要apollo-client是1.3.0及以上版本
5. 把原先的配置文件如bootstrap.properties/yml, application.properties/yml从项目中删除
* 如果需要保留本地配置文件,需要注意部分配置如`server.port`必须确保本地文件已经删除该配置项
如:
```properties
spring.application.name = reservation-service
server.port = 8080
logging.level = ERROR
eureka.client.serviceUrl.defaultZone = http://127.0.0.1:8761/eureka/
eureka.client.healthcheck.enabled = true
eureka.client.registerWithEureka = true
eureka.client.fetchRegistry = true
eureka.client.eurekaServiceUrlPollIntervalSeconds = 60
eureka.instance.preferIpAddress = true
```

## 3.3 Demo
项目中有一个样例客户端的项目:`apollo-demo`,具体信息可以参考[Apollo开发指南](zh/development/apollo-development-guide)中的[2.3 Java样例客户端启动](zh/development/apollo-development-guide?id=_23-java样例客户端启动)部分。
更多使用案例Demo可以参考[Apollo使用场景和示例代码](https://github.com/ctripcorp/apollo-use-cases)。
# 四、客户端设计

上图简要描述了Apollo客户端的实现原理:
1. 客户端和服务端保持了一个长连接,从而能第一时间获得配置更新的推送。(通过Http Long Polling实现)
2. 客户端还会定时从Apollo配置中心服务端拉取应用的最新配置。
* 这是一个fallback机制,为了防止推送机制失效导致配置不更新
* 客户端定时拉取会上报本地版本,所以一般情况下,对于定时拉取的操作,服务端都会返回304 - Not Modified
* 定时频率默认为每5分钟拉取一次,客户端也可以通过在运行时指定System Property: `apollo.refreshInterval`来覆盖,单位为分钟。
3. 客户端从Apollo配置中心服务端获取到应用的最新配置后,会保存在内存中
4. 客户端会把从服务端获取到的配置在本地文件系统缓存一份
* 在遇到服务不可用,或网络不通的时候,依然能从本地恢复配置
5. 应用程序可以从Apollo客户端获取最新的配置、订阅配置更新通知
# 五、本地开发模式
Apollo客户端还支持本地开发模式,这个主要用于当开发环境无法连接Apollo服务器的时候,比如在邮轮、飞机上做相关功能开发。
在本地开发模式下,Apollo只会从本地文件读取配置信息,不会从Apollo服务器读取配置。
可以通过下面的步骤开启Apollo本地开发模式。
## 5.1 修改环境
修改/opt/settings/server.properties(Mac/Linux)或C:\opt\settings\server.properties(Windows)文件,设置env为Local:
```properties
env=Local
```
更多配置环境的方式请参考[1.2.4.1 Environment](#_1241-environment)
## 5.2 准备本地配置文件
在本地开发模式下,Apollo客户端会从本地读取文件,所以我们需要事先准备好配置文件。
### 5.2.1 本地配置目录
本地配置目录位于:
* **Mac/Linux**: /opt/data/{_appId_}/config-cache
* **Windows**: C:\opt\data\\{_appId_}\config-cache
appId就是应用的appId,如100004458。
请确保该目录存在,且应用程序对该目录有读权限。
**【小技巧】** 推荐的方式是先在普通模式下使用Apollo,这样Apollo会自动创建该目录并在目录下生成配置文件。
### 5.2.2 本地配置文件
本地配置文件需要按照一定的文件名格式放置于本地配置目录下,文件名格式如下:
**_{appId}+{cluster}+{namespace}.properties_**
* appId就是应用自己的appId,如100004458
* cluster就是应用使用的集群,一般在本地模式下没有做过配置的话,就是default
* namespace就是应用使用的配置namespace,一般是application

文件内容以properties格式存储,比如如果有两个key,一个是request.timeout,另一个是batch,那么文件内容就是如下格式:
```properties
request.timeout=2000
batch=2000
```
## 5.3 修改配置
在本地开发模式下,Apollo不会实时监测文件内容是否有变化,所以如果修改了配置,需要重启应用生效。
# 六、测试模式
1.1.0版本开始增加了`apollo-mockserver`,从而可以很好地支持单元测试时需要mock配置的场景,使用方法如下:
## 6.1 引入pom依赖
```xml
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-mockserver</artifactId>
<version>1.7.0</version>
</dependency>
```
## 6.2 在test的resources下放置mock的数据
文件名格式约定为`mockdata-{namespace}.properties`

## 6.3 写测试类
更多使用demo可以参考[ApolloMockServerApiTest.java](https://github.com/ctripcorp/apollo/blob/master/apollo-mockserver/src/test/java/com/ctrip/framework/apollo/mockserver/ApolloMockServerApiTest.java)和[ApolloMockServerSpringIntegrationTest.java](https://github.com/ctripcorp/apollo/blob/master/apollo-mockserver/src/test/java/com/ctrip/framework/apollo/mockserver/ApolloMockServerSpringIntegrationTest.java)。
```java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
public class SpringIntegrationTest {
// 启动apollo的mockserver
@ClassRule
public static EmbeddedApollo embeddedApollo = new EmbeddedApollo();
@Test
@DirtiesContext // 这个注解很有必要,因为配置注入会弄脏应用上下文
public void testPropertyInject(){
assertEquals("value1", testBean.key1);
assertEquals("value2", testBean.key2);
}
@Test
@DirtiesContext
public void testListenerTriggeredByAdd() throws InterruptedException, ExecutionException, TimeoutException {
String otherNamespace = "othernamespace";
embeddedApollo.addOrModifyPropery(otherNamespace,"someKey","someValue");
ConfigChangeEvent changeEvent = testBean.futureData.get(5000, TimeUnit.MILLISECONDS);
assertEquals(otherNamespace, changeEvent.getNamespace());
assertEquals("someValue", changeEvent.getChange("someKey").getNewValue());
}
@EnableApolloConfig("application")
@Configuration
static class TestConfiguration{
@Bean
public TestBean testBean(){
return new TestBean();
}
}
static class TestBean{
@Value("${key1:default}")
String key1;
@Value("${key2:default}")
String key2;
SettableFuture<ConfigChangeEvent> futureData = SettableFuture.create();
@ApolloConfigChangeListener("othernamespace")
private void onChange(ConfigChangeEvent changeEvent) {
futureData.set(changeEvent);
}
}
}
```
| 1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/test/resources/application.yml | #
# Copyright 2021 Apollo 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.
#
server:
port: 8070
spring:
application:
name: apollo-portal
logging:
level:
org.springframework.cloud: 'DEBUG'
file:
name: /opt/logs/100003173/apollo-portal.log
apollo:
portal:
envs: local
management:
health:
status:
order: DOWN, OUT_OF_SERVICE, UNKNOWN, UP
| #
# Copyright 2021 Apollo 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.
#
server:
port: 8070
spring:
application:
name: apollo-portal
logging:
level:
org.springframework.cloud: 'DEBUG'
file:
name: /opt/logs/100003173/apollo-portal.log
apollo:
portal:
envs: local
management:
health:
status:
order: DOWN, OUT_OF_SERVICE, UNKNOWN, UP
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/model/Verifiable.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.entity.model;
public interface Verifiable {
boolean isInvalid();
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.entity.model;
public interface Verifiable {
boolean isInvalid();
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/exception/NotFoundException.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.exception;
import org.springframework.http.HttpStatus;
public class NotFoundException extends AbstractApolloHttpException {
public NotFoundException(String str) {
super(str);
setHttpStatus(HttpStatus.NOT_FOUND);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.exception;
import org.springframework.http.HttpStatus;
public class NotFoundException extends AbstractApolloHttpException {
public NotFoundException(String str) {
super(str);
setHttpStatus(HttpStatus.NOT_FOUND);
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-configservice/src/test/java/com/ctrip/framework/apollo/configservice/service/AccessKeyServiceWithCacheTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.when;
import static org.awaitility.Awaitility.*;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import com.ctrip.framework.apollo.biz.entity.AccessKey;
import com.ctrip.framework.apollo.biz.repository.AccessKeyRepository;
import com.google.common.collect.Lists;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.awaitility.Awaitility;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
/**
* @author nisiyong
*/
@RunWith(MockitoJUnitRunner.Silent.class)
public class AccessKeyServiceWithCacheTest {
private AccessKeyServiceWithCache accessKeyServiceWithCache;
@Mock
private AccessKeyRepository accessKeyRepository;
@Mock
private BizConfig bizConfig;
private int scanInterval;
private TimeUnit scanIntervalTimeUnit;
@Before
public void setUp() {
accessKeyServiceWithCache = new AccessKeyServiceWithCache(accessKeyRepository, bizConfig);
scanInterval = 50;
scanIntervalTimeUnit = TimeUnit.MILLISECONDS;
when(bizConfig.accessKeyCacheScanInterval()).thenReturn(scanInterval);
when(bizConfig.accessKeyCacheScanIntervalTimeUnit()).thenReturn(scanIntervalTimeUnit);
when(bizConfig.accessKeyCacheRebuildInterval()).thenReturn(scanInterval);
when(bizConfig.accessKeyCacheRebuildIntervalTimeUnit()).thenReturn(scanIntervalTimeUnit);
Awaitility.reset();
Awaitility.setDefaultTimeout(scanInterval * 100, scanIntervalTimeUnit);
Awaitility.setDefaultPollInterval(scanInterval, scanIntervalTimeUnit);
}
@Test
public void testGetAvailableSecrets() throws Exception {
String appId = "someAppId";
AccessKey firstAccessKey = assembleAccessKey(1L, appId, "secret-1", false,
false, 1577808000000L);
AccessKey secondAccessKey = assembleAccessKey(2L, appId, "secret-2", false,
false, 1577808001000L);
AccessKey thirdAccessKey = assembleAccessKey(3L, appId, "secret-3", true,
false, 1577808005000L);
// Initialize
accessKeyServiceWithCache.afterPropertiesSet();
assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId)).isEmpty();
// Add access key, disable by default
when(accessKeyRepository.findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(new Date(0L)))
.thenReturn(Lists.newArrayList(firstAccessKey, secondAccessKey));
when(accessKeyRepository.findAllById(anyList()))
.thenReturn(Lists.newArrayList(firstAccessKey, secondAccessKey));
await().untilAsserted(() -> assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId)).isEmpty());
// Update access key, enable both of them
firstAccessKey = assembleAccessKey(1L, appId, "secret-1", true, false, 1577808002000L);
secondAccessKey = assembleAccessKey(2L, appId, "secret-2", true, false, 1577808003000L);
when(accessKeyRepository.findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(new Date(1577808001000L)))
.thenReturn(Lists.newArrayList(firstAccessKey, secondAccessKey));
when(accessKeyRepository.findAllById(anyList()))
.thenReturn(Lists.newArrayList(firstAccessKey, secondAccessKey));
await().untilAsserted(() -> assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId))
.containsExactly("secret-1", "secret-2"));
// should also work with appid in different case
assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId.toUpperCase()))
.containsExactly("secret-1", "secret-2");
assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId.toLowerCase()))
.containsExactly("secret-1", "secret-2");
// Update access key, disable the first one
firstAccessKey = assembleAccessKey(1L, appId, "secret-1", false, false, 1577808004000L);
when(accessKeyRepository.findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(new Date(1577808003000L)))
.thenReturn(Lists.newArrayList(firstAccessKey));
when(accessKeyRepository.findAllById(anyList()))
.thenReturn(Lists.newArrayList(firstAccessKey, secondAccessKey));
await().untilAsserted(() -> assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId))
.containsExactly("secret-2"));
// Delete access key, delete the second one
when(accessKeyRepository.findAllById(anyList()))
.thenReturn(Lists.newArrayList(firstAccessKey));
await().untilAsserted(
() -> assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId)).isEmpty());
// Add new access key in runtime, enable by default
when(accessKeyRepository.findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(new Date(1577808004000L)))
.thenReturn(Lists.newArrayList(thirdAccessKey));
when(accessKeyRepository.findAllById(anyList()))
.thenReturn(Lists.newArrayList(firstAccessKey, thirdAccessKey));
await().untilAsserted(() -> assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId))
.containsExactly("secret-3"));
}
public AccessKey assembleAccessKey(Long id, String appId, String secret, boolean enabled,
boolean deleted, long dataChangeLastModifiedTime) {
AccessKey accessKey = new AccessKey();
accessKey.setId(id);
accessKey.setAppId(appId);
accessKey.setSecret(secret);
accessKey.setEnabled(enabled);
accessKey.setDeleted(deleted);
accessKey.setDataChangeLastModifiedTime(new Date(dataChangeLastModifiedTime));
return accessKey;
}
} | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.when;
import static org.awaitility.Awaitility.*;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import com.ctrip.framework.apollo.biz.entity.AccessKey;
import com.ctrip.framework.apollo.biz.repository.AccessKeyRepository;
import com.google.common.collect.Lists;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.awaitility.Awaitility;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
/**
* @author nisiyong
*/
@RunWith(MockitoJUnitRunner.Silent.class)
public class AccessKeyServiceWithCacheTest {
private AccessKeyServiceWithCache accessKeyServiceWithCache;
@Mock
private AccessKeyRepository accessKeyRepository;
@Mock
private BizConfig bizConfig;
private int scanInterval;
private TimeUnit scanIntervalTimeUnit;
@Before
public void setUp() {
accessKeyServiceWithCache = new AccessKeyServiceWithCache(accessKeyRepository, bizConfig);
scanInterval = 50;
scanIntervalTimeUnit = TimeUnit.MILLISECONDS;
when(bizConfig.accessKeyCacheScanInterval()).thenReturn(scanInterval);
when(bizConfig.accessKeyCacheScanIntervalTimeUnit()).thenReturn(scanIntervalTimeUnit);
when(bizConfig.accessKeyCacheRebuildInterval()).thenReturn(scanInterval);
when(bizConfig.accessKeyCacheRebuildIntervalTimeUnit()).thenReturn(scanIntervalTimeUnit);
Awaitility.reset();
Awaitility.setDefaultTimeout(scanInterval * 100, scanIntervalTimeUnit);
Awaitility.setDefaultPollInterval(scanInterval, scanIntervalTimeUnit);
}
@Test
public void testGetAvailableSecrets() throws Exception {
String appId = "someAppId";
AccessKey firstAccessKey = assembleAccessKey(1L, appId, "secret-1", false,
false, 1577808000000L);
AccessKey secondAccessKey = assembleAccessKey(2L, appId, "secret-2", false,
false, 1577808001000L);
AccessKey thirdAccessKey = assembleAccessKey(3L, appId, "secret-3", true,
false, 1577808005000L);
// Initialize
accessKeyServiceWithCache.afterPropertiesSet();
assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId)).isEmpty();
// Add access key, disable by default
when(accessKeyRepository.findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(new Date(0L)))
.thenReturn(Lists.newArrayList(firstAccessKey, secondAccessKey));
when(accessKeyRepository.findAllById(anyList()))
.thenReturn(Lists.newArrayList(firstAccessKey, secondAccessKey));
await().untilAsserted(() -> assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId)).isEmpty());
// Update access key, enable both of them
firstAccessKey = assembleAccessKey(1L, appId, "secret-1", true, false, 1577808002000L);
secondAccessKey = assembleAccessKey(2L, appId, "secret-2", true, false, 1577808003000L);
when(accessKeyRepository.findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(new Date(1577808001000L)))
.thenReturn(Lists.newArrayList(firstAccessKey, secondAccessKey));
when(accessKeyRepository.findAllById(anyList()))
.thenReturn(Lists.newArrayList(firstAccessKey, secondAccessKey));
await().untilAsserted(() -> assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId))
.containsExactly("secret-1", "secret-2"));
// should also work with appid in different case
assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId.toUpperCase()))
.containsExactly("secret-1", "secret-2");
assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId.toLowerCase()))
.containsExactly("secret-1", "secret-2");
// Update access key, disable the first one
firstAccessKey = assembleAccessKey(1L, appId, "secret-1", false, false, 1577808004000L);
when(accessKeyRepository.findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(new Date(1577808003000L)))
.thenReturn(Lists.newArrayList(firstAccessKey));
when(accessKeyRepository.findAllById(anyList()))
.thenReturn(Lists.newArrayList(firstAccessKey, secondAccessKey));
await().untilAsserted(() -> assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId))
.containsExactly("secret-2"));
// Delete access key, delete the second one
when(accessKeyRepository.findAllById(anyList()))
.thenReturn(Lists.newArrayList(firstAccessKey));
await().untilAsserted(
() -> assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId)).isEmpty());
// Add new access key in runtime, enable by default
when(accessKeyRepository.findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(new Date(1577808004000L)))
.thenReturn(Lists.newArrayList(thirdAccessKey));
when(accessKeyRepository.findAllById(anyList()))
.thenReturn(Lists.newArrayList(firstAccessKey, thirdAccessKey));
await().untilAsserted(() -> assertThat(accessKeyServiceWithCache.getAvailableSecrets(appId))
.containsExactly("secret-3"));
}
public AccessKey assembleAccessKey(Long id, String appId, String secret, boolean enabled,
boolean deleted, long dataChangeLastModifiedTime) {
AccessKey accessKey = new AccessKey();
accessKey.setId(id);
accessKey.setAppId(appId);
accessKey.setSecret(secret);
accessKey.setEnabled(enabled);
accessKey.setDeleted(deleted);
accessKey.setDataChangeLastModifiedTime(new Date(dataChangeLastModifiedTime));
return accessKey;
}
} | -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/configuration/AuthConfiguration.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi.configuration;
import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.repository.UserRepository;
import com.ctrip.framework.apollo.portal.spi.LogoutHandler;
import com.ctrip.framework.apollo.portal.spi.SsoHeartbeatHandler;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.UserService;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripLogoutHandler;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripSsoHeartbeatHandler;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripUserService;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultLogoutHandler;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultSsoHeartbeatHandler;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultUserService;
import com.ctrip.framework.apollo.portal.spi.ldap.ApolloLdapAuthenticationProvider;
import com.ctrip.framework.apollo.portal.spi.ldap.FilterLdapByGroupUserSearch;
import com.ctrip.framework.apollo.portal.spi.ldap.LdapUserService;
import com.ctrip.framework.apollo.portal.spi.oidc.ExcludeClientCredentialsClientRegistrationRepository;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcAuthenticationSuccessEventListener;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcLocalUserService;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcLogoutHandler;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.springsecurity.SpringSecurityUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.springsecurity.SpringSecurityUserService;
import com.google.common.collect.Maps;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.LdapOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.ldap.authentication.BindAuthenticator;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
import org.springframework.security.ldap.search.FilterBasedLdapUserSearch;
import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.Collections;
import java.util.EventListener;
import java.util.Map;
@Configuration
public class AuthConfiguration {
private static final String[] BY_PASS_URLS = {"/prometheus/**", "/metrics/**", "/openapi/**",
"/vendor/**", "/styles/**", "/scripts/**", "/views/**", "/img/**", "/i18n/**", "/prefix-path",
"/health"};
/**
* spring.profiles.active = ctrip
*/
@Configuration
@Profile("ctrip")
static class CtripAuthAutoConfiguration {
private final PortalConfig portalConfig;
public CtripAuthAutoConfiguration(final PortalConfig portalConfig) {
this.portalConfig = portalConfig;
}
@Bean
public ServletListenerRegistrationBean redisAppSettingListner() {
ServletListenerRegistrationBean redisAppSettingListener = new ServletListenerRegistrationBean();
redisAppSettingListener
.setListener(listener("org.jasig.cas.client.credis.CRedisAppSettingListner"));
return redisAppSettingListener;
}
@Bean
public ServletListenerRegistrationBean singleSignOutHttpSessionListener() {
ServletListenerRegistrationBean singleSignOutHttpSessionListener = new ServletListenerRegistrationBean();
singleSignOutHttpSessionListener
.setListener(listener("org.jasig.cas.client.session.SingleSignOutHttpSessionListener"));
return singleSignOutHttpSessionListener;
}
@Bean
public FilterRegistrationBean casFilter() {
FilterRegistrationBean singleSignOutFilter = new FilterRegistrationBean();
singleSignOutFilter.setFilter(filter("org.jasig.cas.client.session.SingleSignOutFilter"));
singleSignOutFilter.addUrlPatterns("/*");
singleSignOutFilter.setOrder(1);
return singleSignOutFilter;
}
@Bean
public FilterRegistrationBean authenticationFilter() {
FilterRegistrationBean casFilter = new FilterRegistrationBean();
Map<String, String> filterInitParam = Maps.newHashMap();
filterInitParam.put("redisClusterName", "casClientPrincipal");
filterInitParam.put("serverName", portalConfig.portalServerName());
filterInitParam.put("casServerLoginUrl", portalConfig.casServerLoginUrl());
//we don't want to use session to store login information, since we will be deployed to a cluster, not a single instance
filterInitParam.put("useSession", "false");
filterInitParam.put("/openapi.*", "exclude");
casFilter.setInitParameters(filterInitParam);
casFilter
.setFilter(filter("com.ctrip.framework.apollo.sso.filter.ApolloAuthenticationFilter"));
casFilter.addUrlPatterns("/*");
casFilter.setOrder(2);
return casFilter;
}
@Bean
public FilterRegistrationBean casValidationFilter() {
FilterRegistrationBean casValidationFilter = new FilterRegistrationBean();
Map<String, String> filterInitParam = Maps.newHashMap();
filterInitParam.put("casServerUrlPrefix", portalConfig.casServerUrlPrefix());
filterInitParam.put("serverName", portalConfig.portalServerName());
filterInitParam.put("encoding", "UTF-8");
//we don't want to use session to store login information, since we will be deployed to a cluster, not a single instance
filterInitParam.put("useSession", "false");
filterInitParam.put("useRedis", "true");
filterInitParam.put("redisClusterName", "casClientPrincipal");
casValidationFilter
.setFilter(
filter("org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter"));
casValidationFilter.setInitParameters(filterInitParam);
casValidationFilter.addUrlPatterns("/*");
casValidationFilter.setOrder(3);
return casValidationFilter;
}
@Bean
public FilterRegistrationBean assertionHolder() {
FilterRegistrationBean assertionHolderFilter = new FilterRegistrationBean();
Map<String, String> filterInitParam = Maps.newHashMap();
filterInitParam.put("/openapi.*", "exclude");
assertionHolderFilter.setInitParameters(filterInitParam);
assertionHolderFilter.setFilter(
filter("com.ctrip.framework.apollo.sso.filter.ApolloAssertionThreadLocalFilter"));
assertionHolderFilter.addUrlPatterns("/*");
assertionHolderFilter.setOrder(4);
return assertionHolderFilter;
}
@Bean
public CtripUserInfoHolder ctripUserInfoHolder() {
return new CtripUserInfoHolder();
}
@Bean
public CtripLogoutHandler logoutHandler() {
return new CtripLogoutHandler();
}
private Filter filter(String className) {
Class clazz = null;
try {
clazz = Class.forName(className);
Object obj = clazz.newInstance();
return (Filter) obj;
} catch (Exception e) {
throw new RuntimeException("instance filter fail", e);
}
}
private EventListener listener(String className) {
Class clazz = null;
try {
clazz = Class.forName(className);
Object obj = clazz.newInstance();
return (EventListener) obj;
} catch (Exception e) {
throw new RuntimeException("instance listener fail", e);
}
}
@Bean
public UserService ctripUserService(PortalConfig portalConfig) {
return new CtripUserService(portalConfig);
}
@Bean
public SsoHeartbeatHandler ctripSsoHeartbeatHandler() {
return new CtripSsoHeartbeatHandler();
}
}
/**
* spring.profiles.active = auth
*/
@Configuration
@Profile("auth")
static class SpringSecurityAuthAutoConfiguration {
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public UserInfoHolder springSecurityUserInfoHolder() {
return new SpringSecurityUserInfoHolder();
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public LogoutHandler logoutHandler() {
return new DefaultLogoutHandler();
}
@Bean
public JdbcUserDetailsManager jdbcUserDetailsManager(AuthenticationManagerBuilder auth,
DataSource datasource) throws Exception {
JdbcUserDetailsManager jdbcUserDetailsManager = auth.jdbcAuthentication()
.passwordEncoder(new BCryptPasswordEncoder()).dataSource(datasource)
.usersByUsernameQuery("select Username,Password,Enabled from `Users` where Username = ?")
.authoritiesByUsernameQuery(
"select Username,Authority from `Authorities` where Username = ?")
.getUserDetailsService();
jdbcUserDetailsManager.setUserExistsSql("select Username from `Users` where Username = ?");
jdbcUserDetailsManager
.setCreateUserSql("insert into `Users` (Username, Password, Enabled) values (?,?,?)");
jdbcUserDetailsManager
.setUpdateUserSql("update `Users` set Password = ?, Enabled = ? where id = (select u.id from (select id from `Users` where Username = ?) as u)");
jdbcUserDetailsManager.setDeleteUserSql("delete from `Users` where id = (select u.id from (select id from `Users` where Username = ?) as u)");
jdbcUserDetailsManager
.setCreateAuthoritySql("insert into `Authorities` (Username, Authority) values (?,?)");
jdbcUserDetailsManager
.setDeleteUserAuthoritiesSql("delete from `Authorities` where id in (select a.id from (select id from `Authorities` where Username = ?) as a)");
jdbcUserDetailsManager
.setChangePasswordSql("update `Users` set Password = ? where id = (select u.id from (select id from `Users` where Username = ?) as u)");
return jdbcUserDetailsManager;
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService springSecurityUserService() {
return new SpringSecurityUserService();
}
}
@Order(99)
@Profile("auth")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter {
public static final String USER_ROLE = "user";
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
http.authorizeRequests()
.antMatchers(BY_PASS_URLS).permitAll()
.antMatchers("/**").hasAnyRole(USER_ROLE);
http.formLogin().loginPage("/signin").defaultSuccessUrl("/", true).permitAll().failureUrl("/signin?#/error").and()
.httpBasic();
http.logout().logoutUrl("/user/logout").invalidateHttpSession(true).clearAuthentication(true)
.logoutSuccessUrl("/signin?#/logout");
http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/signin"));
}
}
/**
* spring.profiles.active = ldap
*/
@Configuration
@Profile("ldap")
@EnableConfigurationProperties({LdapProperties.class,LdapExtendProperties.class})
static class SpringSecurityLDAPAuthAutoConfiguration {
private final LdapProperties properties;
private final Environment environment;
public SpringSecurityLDAPAuthAutoConfiguration(final LdapProperties properties, final Environment environment) {
this.properties = properties;
this.environment = environment;
}
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public UserInfoHolder springSecurityUserInfoHolder() {
return new SpringSecurityUserInfoHolder();
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public LogoutHandler logoutHandler() {
return new DefaultLogoutHandler();
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService springSecurityUserService() {
return new LdapUserService();
}
@Bean
@ConditionalOnMissingBean
public ContextSource ldapContextSource() {
LdapContextSource source = new LdapContextSource();
source.setUserDn(this.properties.getUsername());
source.setPassword(this.properties.getPassword());
source.setAnonymousReadOnly(this.properties.getAnonymousReadOnly());
source.setBase(this.properties.getBase());
source.setUrls(this.properties.determineUrls(this.environment));
source.setBaseEnvironmentProperties(
Collections.unmodifiableMap(this.properties.getBaseEnvironment()));
return source;
}
@Bean
@ConditionalOnMissingBean(LdapOperations.class)
public LdapTemplate ldapTemplate(ContextSource contextSource) {
LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
ldapTemplate.setIgnorePartialResultException(true);
return ldapTemplate;
}
}
@Order(99)
@Profile("ldap")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class SpringSecurityLDAPConfigurer extends WebSecurityConfigurerAdapter {
private final LdapProperties ldapProperties;
private final LdapContextSource ldapContextSource;
private final LdapExtendProperties ldapExtendProperties;
public SpringSecurityLDAPConfigurer(final LdapProperties ldapProperties,
final LdapContextSource ldapContextSource,
final LdapExtendProperties ldapExtendProperties) {
this.ldapProperties = ldapProperties;
this.ldapContextSource = ldapContextSource;
this.ldapExtendProperties = ldapExtendProperties;
}
@Bean
public FilterBasedLdapUserSearch userSearch() {
if (ldapExtendProperties.getGroup() == null || StringUtils
.isBlank(ldapExtendProperties.getGroup().getGroupSearch())) {
FilterBasedLdapUserSearch filterBasedLdapUserSearch = new FilterBasedLdapUserSearch("",
ldapProperties.getSearchFilter(), ldapContextSource);
filterBasedLdapUserSearch.setSearchSubtree(true);
return filterBasedLdapUserSearch;
}
FilterLdapByGroupUserSearch filterLdapByGroupUserSearch = new FilterLdapByGroupUserSearch(
ldapProperties.getBase(), ldapProperties.getSearchFilter(), ldapExtendProperties.getGroup().getGroupBase(),
ldapContextSource, ldapExtendProperties.getGroup().getGroupSearch(),
ldapExtendProperties.getMapping().getRdnKey(),
ldapExtendProperties.getGroup().getGroupMembership(),ldapExtendProperties.getMapping().getLoginId());
filterLdapByGroupUserSearch.setSearchSubtree(true);
return filterLdapByGroupUserSearch;
}
@Bean
public LdapAuthenticationProvider ldapAuthProvider() {
BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
bindAuthenticator.setUserSearch(userSearch());
DefaultLdapAuthoritiesPopulator defaultAuthAutoConfiguration = new DefaultLdapAuthoritiesPopulator(
ldapContextSource, null);
defaultAuthAutoConfiguration.setIgnorePartialResultException(true);
defaultAuthAutoConfiguration.setSearchSubtree(true);
// Rewrite the logic of LdapAuthenticationProvider with ApolloLdapAuthenticationProvider,
// use userId in LDAP system instead of userId input by user.
return new ApolloLdapAuthenticationProvider(
bindAuthenticator, defaultAuthAutoConfiguration, ldapExtendProperties);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
http.authorizeRequests()
.antMatchers(BY_PASS_URLS).permitAll()
.antMatchers("/**").authenticated();
http.formLogin().loginPage("/signin").defaultSuccessUrl("/", true).permitAll().failureUrl("/signin?#/error").and()
.httpBasic();
http.logout().logoutUrl("/user/logout").invalidateHttpSession(true).clearAuthentication(true)
.logoutSuccessUrl("/signin?#/logout");
http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/signin"));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(ldapAuthProvider());
}
}
@Profile("oidc")
@EnableConfigurationProperties({OAuth2ClientProperties.class, OAuth2ResourceServerProperties.class})
@Configuration
static class OidcAuthAutoConfiguration {
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public UserInfoHolder oidcUserInfoHolder() {
return new OidcUserInfoHolder();
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public LogoutHandler oidcLogoutHandler() {
return new OidcLogoutHandler();
}
@Bean
@ConditionalOnMissingBean(JdbcUserDetailsManager.class)
public JdbcUserDetailsManager jdbcUserDetailsManager(AuthenticationManagerBuilder auth,
DataSource datasource) throws Exception {
return new SpringSecurityAuthAutoConfiguration().jdbcUserDetailsManager(auth, datasource);
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public OidcLocalUserService oidcLocalUserService(JdbcUserDetailsManager userDetailsManager,
UserRepository userRepository) {
return new OidcLocalUserService(userDetailsManager, userRepository);
}
@Bean
public OidcAuthenticationSuccessEventListener oidcAuthenticationSuccessEventListener(OidcLocalUserService oidcLocalUserService) {
return new OidcAuthenticationSuccessEventListener(oidcLocalUserService);
}
}
@Profile("oidc")
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
static class OidcWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
private final InMemoryClientRegistrationRepository clientRegistrationRepository;
private final OAuth2ResourceServerProperties oauth2ResourceServerProperties;
public OidcWebSecurityConfigurerAdapter(
InMemoryClientRegistrationRepository clientRegistrationRepository,
OAuth2ResourceServerProperties oauth2ResourceServerProperties) {
this.clientRegistrationRepository = clientRegistrationRepository;
this.oauth2ResourceServerProperties = oauth2ResourceServerProperties;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests(requests -> requests.antMatchers(BY_PASS_URLS).permitAll());
http.authorizeRequests(requests -> requests.anyRequest().authenticated());
http.oauth2Login(configure ->
configure.clientRegistrationRepository(
new ExcludeClientCredentialsClientRegistrationRepository(
this.clientRegistrationRepository)));
http.oauth2Client();
http.logout(configure -> {
OidcClientInitiatedLogoutSuccessHandler logoutSuccessHandler = new OidcClientInitiatedLogoutSuccessHandler(
this.clientRegistrationRepository);
logoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}");
configure.logoutSuccessHandler(logoutSuccessHandler);
});
// make jwt optional
String jwtIssuerUri = this.oauth2ResourceServerProperties.getJwt().getIssuerUri();
if (!StringUtils.isBlank(jwtIssuerUri)) {
http.oauth2ResourceServer().jwt();
}
}
}
/**
* default profile
*/
@Configuration
@ConditionalOnMissingProfile({"ctrip", "auth", "ldap", "oidc"})
static class DefaultAuthAutoConfiguration {
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public DefaultUserInfoHolder defaultUserInfoHolder() {
return new DefaultUserInfoHolder();
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public DefaultLogoutHandler logoutHandler() {
return new DefaultLogoutHandler();
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService defaultUserService() {
return new DefaultUserService();
}
}
@ConditionalOnMissingProfile({"auth", "ldap", "oidc"})
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class DefaultWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi.configuration;
import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.repository.UserRepository;
import com.ctrip.framework.apollo.portal.spi.LogoutHandler;
import com.ctrip.framework.apollo.portal.spi.SsoHeartbeatHandler;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.UserService;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripLogoutHandler;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripSsoHeartbeatHandler;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripUserService;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultLogoutHandler;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultSsoHeartbeatHandler;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultUserService;
import com.ctrip.framework.apollo.portal.spi.ldap.ApolloLdapAuthenticationProvider;
import com.ctrip.framework.apollo.portal.spi.ldap.FilterLdapByGroupUserSearch;
import com.ctrip.framework.apollo.portal.spi.ldap.LdapUserService;
import com.ctrip.framework.apollo.portal.spi.oidc.ExcludeClientCredentialsClientRegistrationRepository;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcAuthenticationSuccessEventListener;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcLocalUserService;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcLogoutHandler;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.springsecurity.SpringSecurityUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.springsecurity.SpringSecurityUserService;
import com.google.common.collect.Maps;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.LdapOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.ldap.authentication.BindAuthenticator;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
import org.springframework.security.ldap.search.FilterBasedLdapUserSearch;
import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.Collections;
import java.util.EventListener;
import java.util.Map;
@Configuration
public class AuthConfiguration {
private static final String[] BY_PASS_URLS = {"/prometheus/**", "/metrics/**", "/openapi/**",
"/vendor/**", "/styles/**", "/scripts/**", "/views/**", "/img/**", "/i18n/**", "/prefix-path",
"/health"};
/**
* spring.profiles.active = ctrip
*/
@Configuration
@Profile("ctrip")
static class CtripAuthAutoConfiguration {
private final PortalConfig portalConfig;
public CtripAuthAutoConfiguration(final PortalConfig portalConfig) {
this.portalConfig = portalConfig;
}
@Bean
public ServletListenerRegistrationBean redisAppSettingListner() {
ServletListenerRegistrationBean redisAppSettingListener = new ServletListenerRegistrationBean();
redisAppSettingListener
.setListener(listener("org.jasig.cas.client.credis.CRedisAppSettingListner"));
return redisAppSettingListener;
}
@Bean
public ServletListenerRegistrationBean singleSignOutHttpSessionListener() {
ServletListenerRegistrationBean singleSignOutHttpSessionListener = new ServletListenerRegistrationBean();
singleSignOutHttpSessionListener
.setListener(listener("org.jasig.cas.client.session.SingleSignOutHttpSessionListener"));
return singleSignOutHttpSessionListener;
}
@Bean
public FilterRegistrationBean casFilter() {
FilterRegistrationBean singleSignOutFilter = new FilterRegistrationBean();
singleSignOutFilter.setFilter(filter("org.jasig.cas.client.session.SingleSignOutFilter"));
singleSignOutFilter.addUrlPatterns("/*");
singleSignOutFilter.setOrder(1);
return singleSignOutFilter;
}
@Bean
public FilterRegistrationBean authenticationFilter() {
FilterRegistrationBean casFilter = new FilterRegistrationBean();
Map<String, String> filterInitParam = Maps.newHashMap();
filterInitParam.put("redisClusterName", "casClientPrincipal");
filterInitParam.put("serverName", portalConfig.portalServerName());
filterInitParam.put("casServerLoginUrl", portalConfig.casServerLoginUrl());
//we don't want to use session to store login information, since we will be deployed to a cluster, not a single instance
filterInitParam.put("useSession", "false");
filterInitParam.put("/openapi.*", "exclude");
casFilter.setInitParameters(filterInitParam);
casFilter
.setFilter(filter("com.ctrip.framework.apollo.sso.filter.ApolloAuthenticationFilter"));
casFilter.addUrlPatterns("/*");
casFilter.setOrder(2);
return casFilter;
}
@Bean
public FilterRegistrationBean casValidationFilter() {
FilterRegistrationBean casValidationFilter = new FilterRegistrationBean();
Map<String, String> filterInitParam = Maps.newHashMap();
filterInitParam.put("casServerUrlPrefix", portalConfig.casServerUrlPrefix());
filterInitParam.put("serverName", portalConfig.portalServerName());
filterInitParam.put("encoding", "UTF-8");
//we don't want to use session to store login information, since we will be deployed to a cluster, not a single instance
filterInitParam.put("useSession", "false");
filterInitParam.put("useRedis", "true");
filterInitParam.put("redisClusterName", "casClientPrincipal");
casValidationFilter
.setFilter(
filter("org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter"));
casValidationFilter.setInitParameters(filterInitParam);
casValidationFilter.addUrlPatterns("/*");
casValidationFilter.setOrder(3);
return casValidationFilter;
}
@Bean
public FilterRegistrationBean assertionHolder() {
FilterRegistrationBean assertionHolderFilter = new FilterRegistrationBean();
Map<String, String> filterInitParam = Maps.newHashMap();
filterInitParam.put("/openapi.*", "exclude");
assertionHolderFilter.setInitParameters(filterInitParam);
assertionHolderFilter.setFilter(
filter("com.ctrip.framework.apollo.sso.filter.ApolloAssertionThreadLocalFilter"));
assertionHolderFilter.addUrlPatterns("/*");
assertionHolderFilter.setOrder(4);
return assertionHolderFilter;
}
@Bean
public CtripUserInfoHolder ctripUserInfoHolder() {
return new CtripUserInfoHolder();
}
@Bean
public CtripLogoutHandler logoutHandler() {
return new CtripLogoutHandler();
}
private Filter filter(String className) {
Class clazz = null;
try {
clazz = Class.forName(className);
Object obj = clazz.newInstance();
return (Filter) obj;
} catch (Exception e) {
throw new RuntimeException("instance filter fail", e);
}
}
private EventListener listener(String className) {
Class clazz = null;
try {
clazz = Class.forName(className);
Object obj = clazz.newInstance();
return (EventListener) obj;
} catch (Exception e) {
throw new RuntimeException("instance listener fail", e);
}
}
@Bean
public UserService ctripUserService(PortalConfig portalConfig) {
return new CtripUserService(portalConfig);
}
@Bean
public SsoHeartbeatHandler ctripSsoHeartbeatHandler() {
return new CtripSsoHeartbeatHandler();
}
}
/**
* spring.profiles.active = auth
*/
@Configuration
@Profile("auth")
static class SpringSecurityAuthAutoConfiguration {
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public UserInfoHolder springSecurityUserInfoHolder() {
return new SpringSecurityUserInfoHolder();
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public LogoutHandler logoutHandler() {
return new DefaultLogoutHandler();
}
@Bean
public JdbcUserDetailsManager jdbcUserDetailsManager(AuthenticationManagerBuilder auth,
DataSource datasource) throws Exception {
JdbcUserDetailsManager jdbcUserDetailsManager = auth.jdbcAuthentication()
.passwordEncoder(new BCryptPasswordEncoder()).dataSource(datasource)
.usersByUsernameQuery("select Username,Password,Enabled from `Users` where Username = ?")
.authoritiesByUsernameQuery(
"select Username,Authority from `Authorities` where Username = ?")
.getUserDetailsService();
jdbcUserDetailsManager.setUserExistsSql("select Username from `Users` where Username = ?");
jdbcUserDetailsManager
.setCreateUserSql("insert into `Users` (Username, Password, Enabled) values (?,?,?)");
jdbcUserDetailsManager
.setUpdateUserSql("update `Users` set Password = ?, Enabled = ? where id = (select u.id from (select id from `Users` where Username = ?) as u)");
jdbcUserDetailsManager.setDeleteUserSql("delete from `Users` where id = (select u.id from (select id from `Users` where Username = ?) as u)");
jdbcUserDetailsManager
.setCreateAuthoritySql("insert into `Authorities` (Username, Authority) values (?,?)");
jdbcUserDetailsManager
.setDeleteUserAuthoritiesSql("delete from `Authorities` where id in (select a.id from (select id from `Authorities` where Username = ?) as a)");
jdbcUserDetailsManager
.setChangePasswordSql("update `Users` set Password = ? where id = (select u.id from (select id from `Users` where Username = ?) as u)");
return jdbcUserDetailsManager;
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService springSecurityUserService() {
return new SpringSecurityUserService();
}
}
@Order(99)
@Profile("auth")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter {
public static final String USER_ROLE = "user";
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
http.authorizeRequests()
.antMatchers(BY_PASS_URLS).permitAll()
.antMatchers("/**").hasAnyRole(USER_ROLE);
http.formLogin().loginPage("/signin").defaultSuccessUrl("/", true).permitAll().failureUrl("/signin?#/error").and()
.httpBasic();
http.logout().logoutUrl("/user/logout").invalidateHttpSession(true).clearAuthentication(true)
.logoutSuccessUrl("/signin?#/logout");
http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/signin"));
}
}
/**
* spring.profiles.active = ldap
*/
@Configuration
@Profile("ldap")
@EnableConfigurationProperties({LdapProperties.class,LdapExtendProperties.class})
static class SpringSecurityLDAPAuthAutoConfiguration {
private final LdapProperties properties;
private final Environment environment;
public SpringSecurityLDAPAuthAutoConfiguration(final LdapProperties properties, final Environment environment) {
this.properties = properties;
this.environment = environment;
}
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public UserInfoHolder springSecurityUserInfoHolder() {
return new SpringSecurityUserInfoHolder();
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public LogoutHandler logoutHandler() {
return new DefaultLogoutHandler();
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService springSecurityUserService() {
return new LdapUserService();
}
@Bean
@ConditionalOnMissingBean
public ContextSource ldapContextSource() {
LdapContextSource source = new LdapContextSource();
source.setUserDn(this.properties.getUsername());
source.setPassword(this.properties.getPassword());
source.setAnonymousReadOnly(this.properties.getAnonymousReadOnly());
source.setBase(this.properties.getBase());
source.setUrls(this.properties.determineUrls(this.environment));
source.setBaseEnvironmentProperties(
Collections.unmodifiableMap(this.properties.getBaseEnvironment()));
return source;
}
@Bean
@ConditionalOnMissingBean(LdapOperations.class)
public LdapTemplate ldapTemplate(ContextSource contextSource) {
LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
ldapTemplate.setIgnorePartialResultException(true);
return ldapTemplate;
}
}
@Order(99)
@Profile("ldap")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class SpringSecurityLDAPConfigurer extends WebSecurityConfigurerAdapter {
private final LdapProperties ldapProperties;
private final LdapContextSource ldapContextSource;
private final LdapExtendProperties ldapExtendProperties;
public SpringSecurityLDAPConfigurer(final LdapProperties ldapProperties,
final LdapContextSource ldapContextSource,
final LdapExtendProperties ldapExtendProperties) {
this.ldapProperties = ldapProperties;
this.ldapContextSource = ldapContextSource;
this.ldapExtendProperties = ldapExtendProperties;
}
@Bean
public FilterBasedLdapUserSearch userSearch() {
if (ldapExtendProperties.getGroup() == null || StringUtils
.isBlank(ldapExtendProperties.getGroup().getGroupSearch())) {
FilterBasedLdapUserSearch filterBasedLdapUserSearch = new FilterBasedLdapUserSearch("",
ldapProperties.getSearchFilter(), ldapContextSource);
filterBasedLdapUserSearch.setSearchSubtree(true);
return filterBasedLdapUserSearch;
}
FilterLdapByGroupUserSearch filterLdapByGroupUserSearch = new FilterLdapByGroupUserSearch(
ldapProperties.getBase(), ldapProperties.getSearchFilter(), ldapExtendProperties.getGroup().getGroupBase(),
ldapContextSource, ldapExtendProperties.getGroup().getGroupSearch(),
ldapExtendProperties.getMapping().getRdnKey(),
ldapExtendProperties.getGroup().getGroupMembership(),ldapExtendProperties.getMapping().getLoginId());
filterLdapByGroupUserSearch.setSearchSubtree(true);
return filterLdapByGroupUserSearch;
}
@Bean
public LdapAuthenticationProvider ldapAuthProvider() {
BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
bindAuthenticator.setUserSearch(userSearch());
DefaultLdapAuthoritiesPopulator defaultAuthAutoConfiguration = new DefaultLdapAuthoritiesPopulator(
ldapContextSource, null);
defaultAuthAutoConfiguration.setIgnorePartialResultException(true);
defaultAuthAutoConfiguration.setSearchSubtree(true);
// Rewrite the logic of LdapAuthenticationProvider with ApolloLdapAuthenticationProvider,
// use userId in LDAP system instead of userId input by user.
return new ApolloLdapAuthenticationProvider(
bindAuthenticator, defaultAuthAutoConfiguration, ldapExtendProperties);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
http.authorizeRequests()
.antMatchers(BY_PASS_URLS).permitAll()
.antMatchers("/**").authenticated();
http.formLogin().loginPage("/signin").defaultSuccessUrl("/", true).permitAll().failureUrl("/signin?#/error").and()
.httpBasic();
http.logout().logoutUrl("/user/logout").invalidateHttpSession(true).clearAuthentication(true)
.logoutSuccessUrl("/signin?#/logout");
http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/signin"));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(ldapAuthProvider());
}
}
@Profile("oidc")
@EnableConfigurationProperties({OAuth2ClientProperties.class, OAuth2ResourceServerProperties.class})
@Configuration
static class OidcAuthAutoConfiguration {
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public UserInfoHolder oidcUserInfoHolder() {
return new OidcUserInfoHolder();
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public LogoutHandler oidcLogoutHandler() {
return new OidcLogoutHandler();
}
@Bean
@ConditionalOnMissingBean(JdbcUserDetailsManager.class)
public JdbcUserDetailsManager jdbcUserDetailsManager(AuthenticationManagerBuilder auth,
DataSource datasource) throws Exception {
return new SpringSecurityAuthAutoConfiguration().jdbcUserDetailsManager(auth, datasource);
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public OidcLocalUserService oidcLocalUserService(JdbcUserDetailsManager userDetailsManager,
UserRepository userRepository) {
return new OidcLocalUserService(userDetailsManager, userRepository);
}
@Bean
public OidcAuthenticationSuccessEventListener oidcAuthenticationSuccessEventListener(OidcLocalUserService oidcLocalUserService) {
return new OidcAuthenticationSuccessEventListener(oidcLocalUserService);
}
}
@Profile("oidc")
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
static class OidcWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
private final InMemoryClientRegistrationRepository clientRegistrationRepository;
private final OAuth2ResourceServerProperties oauth2ResourceServerProperties;
public OidcWebSecurityConfigurerAdapter(
InMemoryClientRegistrationRepository clientRegistrationRepository,
OAuth2ResourceServerProperties oauth2ResourceServerProperties) {
this.clientRegistrationRepository = clientRegistrationRepository;
this.oauth2ResourceServerProperties = oauth2ResourceServerProperties;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests(requests -> requests.antMatchers(BY_PASS_URLS).permitAll());
http.authorizeRequests(requests -> requests.anyRequest().authenticated());
http.oauth2Login(configure ->
configure.clientRegistrationRepository(
new ExcludeClientCredentialsClientRegistrationRepository(
this.clientRegistrationRepository)));
http.oauth2Client();
http.logout(configure -> {
OidcClientInitiatedLogoutSuccessHandler logoutSuccessHandler = new OidcClientInitiatedLogoutSuccessHandler(
this.clientRegistrationRepository);
logoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}");
configure.logoutSuccessHandler(logoutSuccessHandler);
});
// make jwt optional
String jwtIssuerUri = this.oauth2ResourceServerProperties.getJwt().getIssuerUri();
if (!StringUtils.isBlank(jwtIssuerUri)) {
http.oauth2ResourceServer().jwt();
}
}
}
/**
* default profile
*/
@Configuration
@ConditionalOnMissingProfile({"ctrip", "auth", "ldap", "oidc"})
static class DefaultAuthAutoConfiguration {
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public DefaultUserInfoHolder defaultUserInfoHolder() {
return new DefaultUserInfoHolder();
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public DefaultLogoutHandler logoutHandler() {
return new DefaultLogoutHandler();
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService defaultUserService() {
return new DefaultUserService();
}
}
@ConditionalOnMissingProfile({"auth", "ldap", "oidc"})
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class DefaultWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
}
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/service/AccessKeyService.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.service;
import com.ctrip.framework.apollo.biz.entity.AccessKey;
import com.ctrip.framework.apollo.biz.entity.Audit;
import com.ctrip.framework.apollo.biz.repository.AccessKeyRepository;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author nisiyong
*/
@Service
public class AccessKeyService {
private static final int ACCESSKEY_COUNT_LIMIT = 5;
private final AccessKeyRepository accessKeyRepository;
private final AuditService auditService;
public AccessKeyService(
AccessKeyRepository accessKeyRepository,
AuditService auditService) {
this.accessKeyRepository = accessKeyRepository;
this.auditService = auditService;
}
public List<AccessKey> findByAppId(String appId) {
return accessKeyRepository.findByAppId(appId);
}
@Transactional
public AccessKey create(String appId, AccessKey entity) {
long count = accessKeyRepository.countByAppId(appId);
if (count >= ACCESSKEY_COUNT_LIMIT) {
throw new BadRequestException("AccessKeys count limit exceeded");
}
entity.setId(0L);
entity.setAppId(appId);
entity.setDataChangeLastModifiedBy(entity.getDataChangeCreatedBy());
AccessKey accessKey = accessKeyRepository.save(entity);
auditService.audit(AccessKey.class.getSimpleName(), accessKey.getId(), Audit.OP.INSERT,
accessKey.getDataChangeCreatedBy());
return accessKey;
}
@Transactional
public AccessKey update(String appId, AccessKey entity) {
long id = entity.getId();
String operator = entity.getDataChangeLastModifiedBy();
AccessKey accessKey = accessKeyRepository.findOneByAppIdAndId(appId, id);
if (accessKey == null) {
throw new BadRequestException("AccessKey not exist");
}
accessKey.setEnabled(entity.isEnabled());
accessKey.setDataChangeLastModifiedBy(operator);
accessKeyRepository.save(accessKey);
auditService.audit(AccessKey.class.getSimpleName(), id, Audit.OP.UPDATE, operator);
return accessKey;
}
@Transactional
public void delete(String appId, long id, String operator) {
AccessKey accessKey = accessKeyRepository.findOneByAppIdAndId(appId, id);
if (accessKey == null) {
throw new BadRequestException("AccessKey not exist");
}
if (accessKey.isEnabled()) {
throw new BadRequestException("AccessKey should disable first");
}
accessKey.setDeleted(Boolean.TRUE);
accessKey.setDataChangeLastModifiedBy(operator);
accessKeyRepository.save(accessKey);
auditService.audit(AccessKey.class.getSimpleName(), id, Audit.OP.DELETE, operator);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.service;
import com.ctrip.framework.apollo.biz.entity.AccessKey;
import com.ctrip.framework.apollo.biz.entity.Audit;
import com.ctrip.framework.apollo.biz.repository.AccessKeyRepository;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author nisiyong
*/
@Service
public class AccessKeyService {
private static final int ACCESSKEY_COUNT_LIMIT = 5;
private final AccessKeyRepository accessKeyRepository;
private final AuditService auditService;
public AccessKeyService(
AccessKeyRepository accessKeyRepository,
AuditService auditService) {
this.accessKeyRepository = accessKeyRepository;
this.auditService = auditService;
}
public List<AccessKey> findByAppId(String appId) {
return accessKeyRepository.findByAppId(appId);
}
@Transactional
public AccessKey create(String appId, AccessKey entity) {
long count = accessKeyRepository.countByAppId(appId);
if (count >= ACCESSKEY_COUNT_LIMIT) {
throw new BadRequestException("AccessKeys count limit exceeded");
}
entity.setId(0L);
entity.setAppId(appId);
entity.setDataChangeLastModifiedBy(entity.getDataChangeCreatedBy());
AccessKey accessKey = accessKeyRepository.save(entity);
auditService.audit(AccessKey.class.getSimpleName(), accessKey.getId(), Audit.OP.INSERT,
accessKey.getDataChangeCreatedBy());
return accessKey;
}
@Transactional
public AccessKey update(String appId, AccessKey entity) {
long id = entity.getId();
String operator = entity.getDataChangeLastModifiedBy();
AccessKey accessKey = accessKeyRepository.findOneByAppIdAndId(appId, id);
if (accessKey == null) {
throw new BadRequestException("AccessKey not exist");
}
accessKey.setEnabled(entity.isEnabled());
accessKey.setDataChangeLastModifiedBy(operator);
accessKeyRepository.save(accessKey);
auditService.audit(AccessKey.class.getSimpleName(), id, Audit.OP.UPDATE, operator);
return accessKey;
}
@Transactional
public void delete(String appId, long id, String operator) {
AccessKey accessKey = accessKeyRepository.findOneByAppIdAndId(appId, id);
if (accessKey == null) {
throw new BadRequestException("AccessKey not exist");
}
if (accessKey.isEnabled()) {
throw new BadRequestException("AccessKey should disable first");
}
accessKey.setDeleted(Boolean.TRUE);
accessKey.setDataChangeLastModifiedBy(operator);
accessKeyRepository.save(accessKey);
auditService.audit(AccessKey.class.getSimpleName(), id, Audit.OP.DELETE, operator);
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/test/java/com/ctrip/framework/apollo/portal/controller/CommitControllerTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.portal.AbstractIntegrationTest;
import java.util.List;
import org.junit.Test;
import org.springframework.web.client.HttpClientErrorException;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Created by kezhenxu at 2019/1/14 12:49.
*
* @author kezhenxu (kezhenxu at lizhi dot fm)
*/
public class CommitControllerTest extends AbstractIntegrationTest {
@Test
public void shouldFailWhenPageOrSiseIsNegative() {
try {
restTemplate.getForEntity(
url("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/commits?page=-1"),
List.class, "1", "env", "cl", "ns"
);
fail("should throw");
} catch (final HttpClientErrorException e) {
assertThat(
new String(e.getResponseBodyAsByteArray()), containsString("page should be positive or 0")
);
}
try {
restTemplate.getForEntity(
url("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/commits?size=0"),
List.class, "1", "env", "cl", "ns"
);
fail("should throw");
} catch (final HttpClientErrorException e) {
assertThat(
new String(e.getResponseBodyAsByteArray()), containsString("size should be positive number")
);
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.portal.AbstractIntegrationTest;
import java.util.List;
import org.junit.Test;
import org.springframework.web.client.HttpClientErrorException;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* Created by kezhenxu at 2019/1/14 12:49.
*
* @author kezhenxu (kezhenxu at lizhi dot fm)
*/
public class CommitControllerTest extends AbstractIntegrationTest {
@Test
public void shouldFailWhenPageOrSiseIsNegative() {
try {
restTemplate.getForEntity(
url("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/commits?page=-1"),
List.class, "1", "env", "cl", "ns"
);
fail("should throw");
} catch (final HttpClientErrorException e) {
assertThat(
new String(e.getResponseBodyAsByteArray()), containsString("page should be positive or 0")
);
}
try {
restTemplate.getForEntity(
url("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/commits?size=0"),
List.class, "1", "env", "cl", "ns"
);
fail("should throw");
} catch (final HttpClientErrorException e) {
assertThat(
new String(e.getResponseBodyAsByteArray()), containsString("size should be positive number")
);
}
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/vo/EnvironmentInfo.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.entity.vo;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.ctrip.framework.apollo.portal.environment.Env;
public class EnvironmentInfo {
private String env;
private boolean active;
private String metaServerAddress;
private ServiceDTO[] configServices;
private ServiceDTO[] adminServices;
private String errorMessage;
public Env getEnv() {
return Env.valueOf(env);
}
public void setEnv(Env env) {
this.env = env.toString();
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getMetaServerAddress() {
return metaServerAddress;
}
public void setMetaServerAddress(String metaServerAddress) {
this.metaServerAddress = metaServerAddress;
}
public ServiceDTO[] getConfigServices() {
return configServices;
}
public void setConfigServices(ServiceDTO[] configServices) {
this.configServices = configServices;
}
public ServiceDTO[] getAdminServices() {
return adminServices;
}
public void setAdminServices(ServiceDTO[] adminServices) {
this.adminServices = adminServices;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.entity.vo;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.ctrip.framework.apollo.portal.environment.Env;
public class EnvironmentInfo {
private String env;
private boolean active;
private String metaServerAddress;
private ServiceDTO[] configServices;
private ServiceDTO[] adminServices;
private String errorMessage;
public Env getEnv() {
return Env.valueOf(env);
}
public void setEnv(Env env) {
this.env = env.toString();
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getMetaServerAddress() {
return metaServerAddress;
}
public void setMetaServerAddress(String metaServerAddress) {
this.metaServerAddress = metaServerAddress;
}
public ServiceDTO[] getConfigServices() {
return configServices;
}
public void setConfigServices(ServiceDTO[] configServices) {
this.configServices = configServices;
}
public ServiceDTO[] getAdminServices() {
return adminServices;
}
public void setAdminServices(ServiceDTO[] adminServices) {
this.adminServices = adminServices;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/util/factory/PropertiesFactory.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.util.factory;
import java.util.Properties;
/**
* Factory interface to construct Properties instances.
*
* @author songdragon@zts.io
*/
public interface PropertiesFactory {
/**
* Configuration to keep properties order as same as line order in .yml/.yaml/.properties file.
*/
String APOLLO_PROPERTY_ORDER_ENABLE = "apollo.property.order.enable";
/**
* <pre>
* Default implementation:
* 1. if {@link APOLLO_PROPERTY_ORDER_ENABLE} is true return a new
* instance of {@link com.ctrip.framework.apollo.util.OrderedProperties}.
* 2. else return a new instance of {@link Properties}
* </pre>
*
* @return
*/
Properties getPropertiesInstance();
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.util.factory;
import java.util.Properties;
/**
* Factory interface to construct Properties instances.
*
* @author songdragon@zts.io
*/
public interface PropertiesFactory {
/**
* Configuration to keep properties order as same as line order in .yml/.yaml/.properties file.
*/
String APOLLO_PROPERTY_ORDER_ENABLE = "apollo.property.order.enable";
/**
* <pre>
* Default implementation:
* 1. if {@link APOLLO_PROPERTY_ORDER_ENABLE} is true return a new
* instance of {@link com.ctrip.framework.apollo.util.OrderedProperties}.
* 2. else return a new instance of {@link Properties}
* </pre>
*
* @return
*/
Properties getPropertiesInstance();
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/DefaultApolloConfigRegistrarHelper.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.spi;
import com.ctrip.framework.apollo.core.spi.Ordered;
import com.ctrip.framework.apollo.spring.annotation.ApolloAnnotationProcessor;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.SpringValueProcessor;
import com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor;
import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor;
import com.ctrip.framework.apollo.spring.util.BeanRegistrationUtil;
import com.google.common.collect.Lists;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
public class DefaultApolloConfigRegistrarHelper implements ApolloConfigRegistrarHelper {
private Environment environment;
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(importingClassMetadata.getAnnotationAttributes(EnableApolloConfig.class.getName()));
final String[] namespaces = attributes.getStringArray("value");
final int order = attributes.getNumber("order");
final String[] resolvedNamespaces = this.resolveNamespaces(namespaces);
PropertySourcesProcessor.addNamespaces(Lists.newArrayList(resolvedNamespaces), order);
Map<String, Object> propertySourcesPlaceholderPropertyValues = new HashMap<>();
// to make sure the default PropertySourcesPlaceholderConfigurer's priority is higher than PropertyPlaceholderConfigurer
propertySourcesPlaceholderPropertyValues.put("order", 0);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class.getName(),
PropertySourcesPlaceholderConfigurer.class, propertySourcesPlaceholderPropertyValues);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesProcessor.class.getName(),
PropertySourcesProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloAnnotationProcessor.class.getName(),
ApolloAnnotationProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueProcessor.class.getName(),
SpringValueProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueDefinitionProcessor.class.getName(),
SpringValueDefinitionProcessor.class);
}
private String[] resolveNamespaces(String[] namespaces) {
String[] resolvedNamespaces = new String[namespaces.length];
for (int i = 0; i < namespaces.length; i++) {
// throw IllegalArgumentException if given text is null or if any placeholders are unresolvable
resolvedNamespaces[i] = this.environment.resolveRequiredPlaceholders(namespaces[i]);
}
return resolvedNamespaces;
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.spi;
import com.ctrip.framework.apollo.core.spi.Ordered;
import com.ctrip.framework.apollo.spring.annotation.ApolloAnnotationProcessor;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.SpringValueProcessor;
import com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor;
import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor;
import com.ctrip.framework.apollo.spring.util.BeanRegistrationUtil;
import com.google.common.collect.Lists;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;
public class DefaultApolloConfigRegistrarHelper implements ApolloConfigRegistrarHelper {
private Environment environment;
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
AnnotationAttributes attributes = AnnotationAttributes
.fromMap(importingClassMetadata.getAnnotationAttributes(EnableApolloConfig.class.getName()));
final String[] namespaces = attributes.getStringArray("value");
final int order = attributes.getNumber("order");
final String[] resolvedNamespaces = this.resolveNamespaces(namespaces);
PropertySourcesProcessor.addNamespaces(Lists.newArrayList(resolvedNamespaces), order);
Map<String, Object> propertySourcesPlaceholderPropertyValues = new HashMap<>();
// to make sure the default PropertySourcesPlaceholderConfigurer's priority is higher than PropertyPlaceholderConfigurer
propertySourcesPlaceholderPropertyValues.put("order", 0);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class.getName(),
PropertySourcesPlaceholderConfigurer.class, propertySourcesPlaceholderPropertyValues);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesProcessor.class.getName(),
PropertySourcesProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloAnnotationProcessor.class.getName(),
ApolloAnnotationProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueProcessor.class.getName(),
SpringValueProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueDefinitionProcessor.class.getName(),
SpringValueDefinitionProcessor.class);
}
private String[] resolveNamespaces(String[] namespaces) {
String[] resolvedNamespaces = new String[namespaces.length];
for (int i = 0; i < namespaces.length; i++) {
// throw IllegalArgumentException if given text is null or if any placeholders are unresolvable
resolvedNamespaces[i] = this.environment.resolveRequiredPlaceholders(namespaces[i]);
}
return resolvedNamespaces;
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/config/PortalConfig.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.component.config;
import com.ctrip.framework.apollo.common.config.RefreshableConfig;
import com.ctrip.framework.apollo.common.config.RefreshablePropertySource;
import com.ctrip.framework.apollo.portal.entity.vo.Organization;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.service.PortalDBPropertySource;
import com.ctrip.framework.apollo.portal.service.SystemRoleManagerService;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.lang.reflect.Type;
import java.util.*;
@Component
public class PortalConfig extends RefreshableConfig {
private static final Logger logger = LoggerFactory.getLogger(PortalConfig.class);
private static final Gson GSON = new Gson();
private static final Type ORGANIZATION = new TypeToken<List<Organization>>() {
}.getType();
/**
* meta servers config in "PortalDB.ServerConfig"
*/
private static final Type META_SERVERS = new TypeToken<Map<String, String>>(){}.getType();
private final PortalDBPropertySource portalDBPropertySource;
public PortalConfig(final PortalDBPropertySource portalDBPropertySource) {
this.portalDBPropertySource = portalDBPropertySource;
}
@Override
public List<RefreshablePropertySource> getRefreshablePropertySources() {
return Collections.singletonList(portalDBPropertySource);
}
/***
* Level: important
**/
public List<Env> portalSupportedEnvs() {
String[] configurations = getArrayProperty("apollo.portal.envs", new String[]{"FAT", "UAT", "PRO"});
List<Env> envs = Lists.newLinkedList();
for (String env : configurations) {
envs.add(Env.addEnvironment(env));
}
return envs;
}
/**
* @return the relationship between environment and its meta server. empty if meet exception
*/
public Map<String, String> getMetaServers() {
final String key = "apollo.portal.meta.servers";
String jsonContent = getValue(key);
if(null == jsonContent) {
return Collections.emptyMap();
}
// watch out that the format of content may be wrong
// that will cause exception
Map<String, String> map = Collections.emptyMap();
try {
// try to parse
map = GSON.fromJson(jsonContent, META_SERVERS);
} catch (Exception e) {
logger.error("Wrong format for: {}", key, e);
}
return map;
}
public List<String> superAdmins() {
String superAdminConfig = getValue("superAdmin", "");
if (Strings.isNullOrEmpty(superAdminConfig)) {
return Collections.emptyList();
}
return splitter.splitToList(superAdminConfig);
}
public Set<Env> emailSupportedEnvs() {
String[] configurations = getArrayProperty("email.supported.envs", null);
Set<Env> result = Sets.newHashSet();
if (configurations == null || configurations.length == 0) {
return result;
}
for (String env : configurations) {
result.add(Env.valueOf(env));
}
return result;
}
public Set<Env> webHookSupportedEnvs() {
String[] configurations = getArrayProperty("webhook.supported.envs", null);
Set<Env> result = Sets.newHashSet();
if (configurations == null || configurations.length == 0) {
return result;
}
for (String env : configurations) {
result.add(Env.valueOf(env));
}
return result;
}
public boolean isConfigViewMemberOnly(String env) {
String[] configViewMemberOnlyEnvs = getArrayProperty("configView.memberOnly.envs", new String[0]);
for (String memberOnlyEnv : configViewMemberOnlyEnvs) {
if (memberOnlyEnv.equalsIgnoreCase(env)) {
return true;
}
}
return false;
}
/***
* Level: normal
**/
public int connectTimeout() {
return getIntProperty("api.connectTimeout", 3000);
}
public int readTimeout() {
return getIntProperty("api.readTimeout", 10000);
}
public List<Organization> organizations() {
String organizations = getValue("organizations");
return organizations == null ? Collections.emptyList() : GSON.fromJson(organizations, ORGANIZATION);
}
public String portalAddress() {
return getValue("apollo.portal.address");
}
public boolean isEmergencyPublishAllowed(Env env) {
String targetEnv = env.name();
String[] emergencyPublishSupportedEnvs = getArrayProperty("emergencyPublish.supported.envs", new String[0]);
for (String supportedEnv : emergencyPublishSupportedEnvs) {
if (Objects.equals(targetEnv, supportedEnv.toUpperCase().trim())) {
return true;
}
}
return false;
}
/***
* Level: low
**/
public Set<Env> publishTipsSupportedEnvs() {
String[] configurations = getArrayProperty("namespace.publish.tips.supported.envs", null);
Set<Env> result = Sets.newHashSet();
if (configurations == null || configurations.length == 0) {
return result;
}
for (String env : configurations) {
result.add(Env.valueOf(env));
}
return result;
}
public String consumerTokenSalt() {
return getValue("consumer.token.salt", "apollo-portal");
}
public boolean isEmailEnabled() {
return getBooleanProperty("email.enabled", false);
}
public String emailConfigHost() {
return getValue("email.config.host", "");
}
public String emailConfigUser() {
return getValue("email.config.user", "");
}
public String emailConfigPassword() {
return getValue("email.config.password", "");
}
public String emailSender() {
String value = getValue("email.sender", "");
if (Strings.isNullOrEmpty(value)) {
value = emailConfigUser();
}
return value;
}
public String emailTemplateFramework() {
return getValue("email.template.framework", "");
}
public String emailReleaseDiffModuleTemplate() {
return getValue("email.template.release.module.diff", "");
}
public String emailRollbackDiffModuleTemplate() {
return getValue("email.template.rollback.module.diff", "");
}
public String emailGrayRulesModuleTemplate() {
return getValue("email.template.release.module.rules", "");
}
public String wikiAddress() {
return getValue("wiki.address", "https://www.apolloconfig.com");
}
public boolean canAppAdminCreatePrivateNamespace() {
return getBooleanProperty("admin.createPrivateNamespace.switch", true);
}
public boolean isCreateApplicationPermissionEnabled() {
return getBooleanProperty(SystemRoleManagerService.CREATE_APPLICATION_LIMIT_SWITCH_KEY, false);
}
public boolean isManageAppMasterPermissionEnabled() {
return getBooleanProperty(SystemRoleManagerService.MANAGE_APP_MASTER_LIMIT_SWITCH_KEY, false);
}
public String getAdminServiceAccessTokens() {
return getValue("admin-service.access.tokens");
}
/***
* The following configurations are used in ctrip profile
**/
public int appId() {
return getIntProperty("ctrip.appid", 0);
}
//send code & template id. apply from ewatch
public String sendCode() {
return getValue("ctrip.email.send.code");
}
public int templateId() {
return getIntProperty("ctrip.email.template.id", 0);
}
//email retention time in email server queue.TimeUnit: hour
public int survivalDuration() {
return getIntProperty("ctrip.email.survival.duration", 5);
}
public boolean isSendEmailAsync() {
return getBooleanProperty("email.send.async", true);
}
public String portalServerName() {
return getValue("serverName");
}
public String casServerLoginUrl() {
return getValue("casServerLoginUrl");
}
public String casServerUrlPrefix() {
return getValue("casServerUrlPrefix");
}
public String credisServiceUrl() {
return getValue("credisServiceUrl");
}
public String userServiceUrl() {
return getValue("userService.url");
}
public String userServiceAccessToken() {
return getValue("userService.accessToken");
}
public String soaServerAddress() {
return getValue("soa.server.address");
}
public String cloggingUrl() {
return getValue("clogging.server.url");
}
public String cloggingPort() {
return getValue("clogging.server.port");
}
public String hermesServerAddress() {
return getValue("hermes.server.address");
}
public String[] webHookUrls() {
return getArrayProperty("config.release.webhook.service.url", null);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.component.config;
import com.ctrip.framework.apollo.common.config.RefreshableConfig;
import com.ctrip.framework.apollo.common.config.RefreshablePropertySource;
import com.ctrip.framework.apollo.portal.entity.vo.Organization;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.service.PortalDBPropertySource;
import com.ctrip.framework.apollo.portal.service.SystemRoleManagerService;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.lang.reflect.Type;
import java.util.*;
@Component
public class PortalConfig extends RefreshableConfig {
private static final Logger logger = LoggerFactory.getLogger(PortalConfig.class);
private static final Gson GSON = new Gson();
private static final Type ORGANIZATION = new TypeToken<List<Organization>>() {
}.getType();
/**
* meta servers config in "PortalDB.ServerConfig"
*/
private static final Type META_SERVERS = new TypeToken<Map<String, String>>(){}.getType();
private final PortalDBPropertySource portalDBPropertySource;
public PortalConfig(final PortalDBPropertySource portalDBPropertySource) {
this.portalDBPropertySource = portalDBPropertySource;
}
@Override
public List<RefreshablePropertySource> getRefreshablePropertySources() {
return Collections.singletonList(portalDBPropertySource);
}
/***
* Level: important
**/
public List<Env> portalSupportedEnvs() {
String[] configurations = getArrayProperty("apollo.portal.envs", new String[]{"FAT", "UAT", "PRO"});
List<Env> envs = Lists.newLinkedList();
for (String env : configurations) {
envs.add(Env.addEnvironment(env));
}
return envs;
}
/**
* @return the relationship between environment and its meta server. empty if meet exception
*/
public Map<String, String> getMetaServers() {
final String key = "apollo.portal.meta.servers";
String jsonContent = getValue(key);
if(null == jsonContent) {
return Collections.emptyMap();
}
// watch out that the format of content may be wrong
// that will cause exception
Map<String, String> map = Collections.emptyMap();
try {
// try to parse
map = GSON.fromJson(jsonContent, META_SERVERS);
} catch (Exception e) {
logger.error("Wrong format for: {}", key, e);
}
return map;
}
public List<String> superAdmins() {
String superAdminConfig = getValue("superAdmin", "");
if (Strings.isNullOrEmpty(superAdminConfig)) {
return Collections.emptyList();
}
return splitter.splitToList(superAdminConfig);
}
public Set<Env> emailSupportedEnvs() {
String[] configurations = getArrayProperty("email.supported.envs", null);
Set<Env> result = Sets.newHashSet();
if (configurations == null || configurations.length == 0) {
return result;
}
for (String env : configurations) {
result.add(Env.valueOf(env));
}
return result;
}
public Set<Env> webHookSupportedEnvs() {
String[] configurations = getArrayProperty("webhook.supported.envs", null);
Set<Env> result = Sets.newHashSet();
if (configurations == null || configurations.length == 0) {
return result;
}
for (String env : configurations) {
result.add(Env.valueOf(env));
}
return result;
}
public boolean isConfigViewMemberOnly(String env) {
String[] configViewMemberOnlyEnvs = getArrayProperty("configView.memberOnly.envs", new String[0]);
for (String memberOnlyEnv : configViewMemberOnlyEnvs) {
if (memberOnlyEnv.equalsIgnoreCase(env)) {
return true;
}
}
return false;
}
/***
* Level: normal
**/
public int connectTimeout() {
return getIntProperty("api.connectTimeout", 3000);
}
public int readTimeout() {
return getIntProperty("api.readTimeout", 10000);
}
public List<Organization> organizations() {
String organizations = getValue("organizations");
return organizations == null ? Collections.emptyList() : GSON.fromJson(organizations, ORGANIZATION);
}
public String portalAddress() {
return getValue("apollo.portal.address");
}
public boolean isEmergencyPublishAllowed(Env env) {
String targetEnv = env.name();
String[] emergencyPublishSupportedEnvs = getArrayProperty("emergencyPublish.supported.envs", new String[0]);
for (String supportedEnv : emergencyPublishSupportedEnvs) {
if (Objects.equals(targetEnv, supportedEnv.toUpperCase().trim())) {
return true;
}
}
return false;
}
/***
* Level: low
**/
public Set<Env> publishTipsSupportedEnvs() {
String[] configurations = getArrayProperty("namespace.publish.tips.supported.envs", null);
Set<Env> result = Sets.newHashSet();
if (configurations == null || configurations.length == 0) {
return result;
}
for (String env : configurations) {
result.add(Env.valueOf(env));
}
return result;
}
public String consumerTokenSalt() {
return getValue("consumer.token.salt", "apollo-portal");
}
public boolean isEmailEnabled() {
return getBooleanProperty("email.enabled", false);
}
public String emailConfigHost() {
return getValue("email.config.host", "");
}
public String emailConfigUser() {
return getValue("email.config.user", "");
}
public String emailConfigPassword() {
return getValue("email.config.password", "");
}
public String emailSender() {
String value = getValue("email.sender", "");
if (Strings.isNullOrEmpty(value)) {
value = emailConfigUser();
}
return value;
}
public String emailTemplateFramework() {
return getValue("email.template.framework", "");
}
public String emailReleaseDiffModuleTemplate() {
return getValue("email.template.release.module.diff", "");
}
public String emailRollbackDiffModuleTemplate() {
return getValue("email.template.rollback.module.diff", "");
}
public String emailGrayRulesModuleTemplate() {
return getValue("email.template.release.module.rules", "");
}
public String wikiAddress() {
return getValue("wiki.address", "https://www.apolloconfig.com");
}
public boolean canAppAdminCreatePrivateNamespace() {
return getBooleanProperty("admin.createPrivateNamespace.switch", true);
}
public boolean isCreateApplicationPermissionEnabled() {
return getBooleanProperty(SystemRoleManagerService.CREATE_APPLICATION_LIMIT_SWITCH_KEY, false);
}
public boolean isManageAppMasterPermissionEnabled() {
return getBooleanProperty(SystemRoleManagerService.MANAGE_APP_MASTER_LIMIT_SWITCH_KEY, false);
}
public String getAdminServiceAccessTokens() {
return getValue("admin-service.access.tokens");
}
/***
* The following configurations are used in ctrip profile
**/
public int appId() {
return getIntProperty("ctrip.appid", 0);
}
//send code & template id. apply from ewatch
public String sendCode() {
return getValue("ctrip.email.send.code");
}
public int templateId() {
return getIntProperty("ctrip.email.template.id", 0);
}
//email retention time in email server queue.TimeUnit: hour
public int survivalDuration() {
return getIntProperty("ctrip.email.survival.duration", 5);
}
public boolean isSendEmailAsync() {
return getBooleanProperty("email.send.async", true);
}
public String portalServerName() {
return getValue("serverName");
}
public String casServerLoginUrl() {
return getValue("casServerLoginUrl");
}
public String casServerUrlPrefix() {
return getValue("casServerUrlPrefix");
}
public String credisServiceUrl() {
return getValue("credisServiceUrl");
}
public String userServiceUrl() {
return getValue("userService.url");
}
public String userServiceAccessToken() {
return getValue("userService.accessToken");
}
public String soaServerAddress() {
return getValue("soa.server.address");
}
public String cloggingUrl() {
return getValue("clogging.server.url");
}
public String cloggingPort() {
return getValue("clogging.server.port");
}
public String hermesServerAddress() {
return getValue("hermes.server.address");
}
public String[] webHookUrls() {
return getArrayProperty("config.release.webhook.service.url", null);
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/NullTransaction.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.tracer.internals;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class NullTransaction implements Transaction {
@Override
public void setStatus(String status) {
}
@Override
public void setStatus(Throwable e) {
}
@Override
public void addData(String key, Object value) {
}
@Override
public void complete() {
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.tracer.internals;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class NullTransaction implements Transaction {
@Override
public void setStatus(String status) {
}
@Override
public void setStatus(Throwable e) {
}
@Override
public void addData(String key, Object value) {
}
@Override
public void complete() {
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YamlConfigFile.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctrip.framework.apollo.PropertiesCompatibleConfigFile;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.util.yaml.YamlParser;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class YamlConfigFile extends PlainTextConfigFile implements PropertiesCompatibleConfigFile {
private static final Logger logger = LoggerFactory.getLogger(YamlConfigFile.class);
private volatile Properties cachedProperties;
public YamlConfigFile(String namespace, ConfigRepository configRepository) {
super(namespace, configRepository);
tryTransformToProperties();
}
@Override
public ConfigFileFormat getConfigFileFormat() {
return ConfigFileFormat.YAML;
}
@Override
protected void update(Properties newProperties) {
super.update(newProperties);
tryTransformToProperties();
}
@Override
public Properties asProperties() {
if (cachedProperties == null) {
transformToProperties();
}
return cachedProperties;
}
private boolean tryTransformToProperties() {
try {
transformToProperties();
return true;
} catch (Throwable ex) {
Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
logger.warn("yaml to properties failed, reason: {}", ExceptionUtil.getDetailMessage(ex));
}
return false;
}
private synchronized void transformToProperties() {
cachedProperties = toProperties();
}
private Properties toProperties() {
if (!this.hasContent()) {
return propertiesFactory.getPropertiesInstance();
}
try {
return ApolloInjector.getInstance(YamlParser.class).yamlToProperties(getContent());
} catch (Throwable ex) {
ApolloConfigException exception = new ApolloConfigException(
"Parse yaml file content failed for namespace: " + m_namespace, ex);
Tracer.logError(exception);
throw exception;
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.util.ExceptionUtil;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctrip.framework.apollo.PropertiesCompatibleConfigFile;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.util.yaml.YamlParser;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class YamlConfigFile extends PlainTextConfigFile implements PropertiesCompatibleConfigFile {
private static final Logger logger = LoggerFactory.getLogger(YamlConfigFile.class);
private volatile Properties cachedProperties;
public YamlConfigFile(String namespace, ConfigRepository configRepository) {
super(namespace, configRepository);
tryTransformToProperties();
}
@Override
public ConfigFileFormat getConfigFileFormat() {
return ConfigFileFormat.YAML;
}
@Override
protected void update(Properties newProperties) {
super.update(newProperties);
tryTransformToProperties();
}
@Override
public Properties asProperties() {
if (cachedProperties == null) {
transformToProperties();
}
return cachedProperties;
}
private boolean tryTransformToProperties() {
try {
transformToProperties();
return true;
} catch (Throwable ex) {
Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex));
logger.warn("yaml to properties failed, reason: {}", ExceptionUtil.getDetailMessage(ex));
}
return false;
}
private synchronized void transformToProperties() {
cachedProperties = toProperties();
}
private Properties toProperties() {
if (!this.hasContent()) {
return propertiesFactory.getPropertiesInstance();
}
try {
return ApolloInjector.getInstance(YamlParser.class).yamlToProperties(getContent());
} catch (Throwable ex) {
ApolloConfigException exception = new ApolloConfigException(
"Parse yaml file content failed for namespace: " + m_namespace, ex);
Tracer.logError(exception);
throw exception;
}
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/test/java/com/ctrip/framework/apollo/portal/environment/PortalMetaDomainServiceTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.environment;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class PortalMetaDomainServiceTest extends BaseIntegrationTest {
private PortalMetaDomainService portalMetaDomainService;
@Mock
private PortalConfig portalConfig;
@Before
public void init() {
final Map<String, String> map = new HashMap<>();
map.put("nothing", "http://unknown.com");
Mockito.when(portalConfig.getMetaServers()).thenReturn(map);
portalMetaDomainService = new PortalMetaDomainService(portalConfig);
}
@Test
public void testGetMetaDomain() {
// local
String localMetaServerAddress = "http://localhost:8080";
mockMetaServerAddress(Env.LOCAL, localMetaServerAddress);
assertEquals(localMetaServerAddress, portalMetaDomainService.getDomain(Env.LOCAL));
// add this environment without meta server address
String randomEnvironment = "randomEnvironment";
Env.addEnvironment(randomEnvironment);
assertEquals(PortalMetaDomainService.DEFAULT_META_URL, portalMetaDomainService.getDomain(Env.valueOf(randomEnvironment)));
}
@Test
public void testGetValidAddress() throws Exception {
String someResponse = "some response";
startServerWithHandlers(mockServerHandler(HttpServletResponse.SC_OK, someResponse));
String validServer = " http://localhost:" + PORT + " ";
String invalidServer = "http://localhost:" + findFreePort();
mockMetaServerAddress(Env.FAT, validServer + "," + invalidServer);
mockMetaServerAddress(Env.UAT, invalidServer + "," + validServer);
portalMetaDomainService.reload();
assertEquals(validServer.trim(), portalMetaDomainService.getDomain(Env.FAT));
assertEquals(validServer.trim(), portalMetaDomainService.getDomain(Env.UAT));
}
@Test
public void testInvalidAddress() {
String invalidServer = "http://localhost:" + findFreePort() + " ";
String anotherInvalidServer = "http://localhost:" + findFreePort() + " ";
mockMetaServerAddress(Env.LPT, invalidServer + "," + anotherInvalidServer);
portalMetaDomainService.reload();
String metaServer = portalMetaDomainService.getDomain(Env.LPT);
assertTrue(metaServer.equals(invalidServer.trim()) || metaServer.equals(anotherInvalidServer.trim()));
}
private void mockMetaServerAddress(Env env, String metaServerAddress) {
// add it to system's property
System.setProperty(env.getName() + "_meta", metaServerAddress);
}
} | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.environment;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class PortalMetaDomainServiceTest extends BaseIntegrationTest {
private PortalMetaDomainService portalMetaDomainService;
@Mock
private PortalConfig portalConfig;
@Before
public void init() {
final Map<String, String> map = new HashMap<>();
map.put("nothing", "http://unknown.com");
Mockito.when(portalConfig.getMetaServers()).thenReturn(map);
portalMetaDomainService = new PortalMetaDomainService(portalConfig);
}
@Test
public void testGetMetaDomain() {
// local
String localMetaServerAddress = "http://localhost:8080";
mockMetaServerAddress(Env.LOCAL, localMetaServerAddress);
assertEquals(localMetaServerAddress, portalMetaDomainService.getDomain(Env.LOCAL));
// add this environment without meta server address
String randomEnvironment = "randomEnvironment";
Env.addEnvironment(randomEnvironment);
assertEquals(PortalMetaDomainService.DEFAULT_META_URL, portalMetaDomainService.getDomain(Env.valueOf(randomEnvironment)));
}
@Test
public void testGetValidAddress() throws Exception {
String someResponse = "some response";
startServerWithHandlers(mockServerHandler(HttpServletResponse.SC_OK, someResponse));
String validServer = " http://localhost:" + PORT + " ";
String invalidServer = "http://localhost:" + findFreePort();
mockMetaServerAddress(Env.FAT, validServer + "," + invalidServer);
mockMetaServerAddress(Env.UAT, invalidServer + "," + validServer);
portalMetaDomainService.reload();
assertEquals(validServer.trim(), portalMetaDomainService.getDomain(Env.FAT));
assertEquals(validServer.trim(), portalMetaDomainService.getDomain(Env.UAT));
}
@Test
public void testInvalidAddress() {
String invalidServer = "http://localhost:" + findFreePort() + " ";
String anotherInvalidServer = "http://localhost:" + findFreePort() + " ";
mockMetaServerAddress(Env.LPT, invalidServer + "," + anotherInvalidServer);
portalMetaDomainService.reload();
String metaServer = portalMetaDomainService.getDomain(Env.LPT);
assertTrue(metaServer.equals(invalidServer.trim()) || metaServer.equals(anotherInvalidServer.trim()));
}
private void mockMetaServerAddress(Env env, String metaServerAddress) {
// add it to system's property
System.setProperty(env.getName() + "_meta", metaServerAddress);
}
} | -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/test/java/com/ctrip/framework/apollo/spring/XmlConfigPlaceholderAutoUpdateTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.internals.SimpleConfig;
import com.ctrip.framework.apollo.spring.XmlConfigPlaceholderTest.TestXmlBean;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.google.common.primitives.Ints;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlConfigPlaceholderAutoUpdateTest extends AbstractSpringIntegrationTest {
private static final String TIMEOUT_PROPERTY = "timeout";
private static final int DEFAULT_TIMEOUT = 100;
private static final String BATCH_PROPERTY = "batch";
private static final int DEFAULT_BATCH = 200;
private static final String FX_APOLLO_NAMESPACE = "FX.apollo";
@Test
public void testAutoUpdateWithOneNamespace() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout),
BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateDisabled() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
MockConfigUtil mockConfigUtil = new MockConfigUtil();
mockConfigUtil.setAutoUpdateInjectedSpringProperties(false);
MockInjector.setInstance(ConfigUtil.class, mockConfigUtil);
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout),
BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespaces() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(initialTimeout));
Properties fxApolloProperties = assembleProperties(BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION,
applicationProperties);
SimpleConfig fxApolloConfig = prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest3.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(newTimeout));
applicationConfig
.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newFxApolloProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(newBatch));
fxApolloConfig.onRepositoryChange(FX_APOLLO_NAMESPACE, newFxApolloProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespacesWithSameProperties() throws Exception {
int someTimeout = 1000;
int someBatch = 2000;
int anotherBatch = 3000;
int someNewTimeout = 1001;
int someNewBatch = 2001;
Properties applicationProperties = assembleProperties(BATCH_PROPERTY,
String.valueOf(someBatch));
Properties fxApolloProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch));
prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties);
SimpleConfig fxApolloConfig = prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest3.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
Properties newFxApolloProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(someNewTimeout), BATCH_PROPERTY, String.valueOf(someNewBatch));
fxApolloConfig.onRepositoryChange(FX_APOLLO_NAMESPACE, newFxApolloProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithNewProperties() throws Exception {
int initialTimeout = 1000;
int newTimeout = 1001;
int newBatch = 2001;
Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(initialTimeout));
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION,
applicationProperties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
applicationConfig
.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithIrrelevantProperties() throws Exception {
int initialTimeout = 1000;
String someIrrelevantKey = "someIrrelevantKey";
String someIrrelevantValue = "someIrrelevantValue";
String anotherIrrelevantKey = "anotherIrrelevantKey";
String anotherIrrelevantValue = "anotherIrrelevantValue";
Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(initialTimeout), someIrrelevantKey, someIrrelevantValue);
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION,
applicationProperties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(initialTimeout), anotherIrrelevantKey, anotherIrrelevantValue);
applicationConfig
.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
}
@Test
public void testAutoUpdateWithDeletedProperties() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = new Properties();
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(DEFAULT_TIMEOUT, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespacesWithSamePropertiesDeleted() throws Exception {
int someTimeout = 1000;
int someBatch = 2000;
int anotherBatch = 3000;
Properties applicationProperties = assembleProperties(BATCH_PROPERTY,
String.valueOf(someBatch));
Properties fxApolloProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch));
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION,
applicationProperties);
prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest3.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
Properties newProperties = new Properties();
applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(anotherBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithDeletedPropertiesWithNoDefaultValue() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest7.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(300);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithTypeMismatch() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
String newBatch = "newBatch";
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout),
BATCH_PROPERTY, newBatch);
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(300);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithValueInjectedAsConstructorArgs() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest8.xml");
TestXmlBeanWithConstructorArgs bean = context.getBean(TestXmlBeanWithConstructorArgs.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout),
BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
// Does not support this scenario
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithValueAndProperty() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest9.xml");
TestXmlBeanWithInjectedValue bean = context.getBean(TestXmlBeanWithInjectedValue.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout),
BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithAllKindsOfDataTypes() throws Exception {
int someInt = 1000;
int someNewInt = 1001;
int[] someIntArray = {1, 2, 3, 4};
int[] someNewIntArray = {5, 6, 7, 8};
long someLong = 2000L;
long someNewLong = 2001L;
short someShort = 3000;
short someNewShort = 3001;
float someFloat = 1.2F;
float someNewFloat = 2.2F;
double someDouble = 3.10D;
double someNewDouble = 4.10D;
byte someByte = 123;
byte someNewByte = 124;
boolean someBoolean = true;
boolean someNewBoolean = !someBoolean;
String someString = "someString";
String someNewString = "someNewString";
String someDateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
Date someDate = assembleDate(2018, 2, 23, 20, 1, 2, 123);
Date someNewDate = assembleDate(2018, 2, 23, 21, 2, 3, 345);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(someDateFormat, Locale.US);
Properties properties = new Properties();
properties.setProperty("intProperty", String.valueOf(someInt));
properties.setProperty("intArrayProperty", Ints.join(", ", someIntArray));
properties.setProperty("longProperty", String.valueOf(someLong));
properties.setProperty("shortProperty", String.valueOf(someShort));
properties.setProperty("floatProperty", String.valueOf(someFloat));
properties.setProperty("doubleProperty", String.valueOf(someDouble));
properties.setProperty("byteProperty", String.valueOf(someByte));
properties.setProperty("booleanProperty", String.valueOf(someBoolean));
properties.setProperty("stringProperty", someString);
properties.setProperty("dateFormat", someDateFormat);
properties.setProperty("dateProperty", simpleDateFormat.format(someDate));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest10.xml");
TestAllKindsOfDataTypesBean bean = context.getBean(TestAllKindsOfDataTypesBean.class);
assertEquals(someInt, bean.getIntProperty());
assertArrayEquals(someIntArray, bean.getIntArrayProperty());
assertEquals(someLong, bean.getLongProperty());
assertEquals(someShort, bean.getShortProperty());
assertEquals(someFloat, bean.getFloatProperty(), 0.001F);
assertEquals(someDouble, bean.getDoubleProperty(), 0.001D);
assertEquals(someByte, bean.getByteProperty());
assertEquals(someBoolean, bean.getBooleanProperty());
assertEquals(someString, bean.getStringProperty());
assertEquals(someDate, bean.getDateProperty());
Properties newProperties = new Properties();
newProperties.setProperty("intProperty", String.valueOf(someNewInt));
newProperties.setProperty("intArrayProperty", Ints.join(", ", someNewIntArray));
newProperties.setProperty("longProperty", String.valueOf(someNewLong));
newProperties.setProperty("shortProperty", String.valueOf(someNewShort));
newProperties.setProperty("floatProperty", String.valueOf(someNewFloat));
newProperties.setProperty("doubleProperty", String.valueOf(someNewDouble));
newProperties.setProperty("byteProperty", String.valueOf(someNewByte));
newProperties.setProperty("booleanProperty", String.valueOf(someNewBoolean));
newProperties.setProperty("stringProperty", someNewString);
newProperties.setProperty("dateFormat", someDateFormat);
newProperties.setProperty("dateProperty", simpleDateFormat.format(someNewDate));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewInt, bean.getIntProperty());
assertArrayEquals(someNewIntArray, bean.getIntArrayProperty());
assertEquals(someNewLong, bean.getLongProperty());
assertEquals(someNewShort, bean.getShortProperty());
assertEquals(someNewFloat, bean.getFloatProperty(), 0.001F);
assertEquals(someNewDouble, bean.getDoubleProperty(), 0.001D);
assertEquals(someNewByte, bean.getByteProperty());
assertEquals(someNewBoolean, bean.getBooleanProperty());
assertEquals(someNewString, bean.getStringProperty());
assertEquals(someNewDate, bean.getDateProperty());
}
public static class TestXmlBeanWithConstructorArgs {
private final int timeout;
private final int batch;
public TestXmlBeanWithConstructorArgs(int timeout, int batch) {
this.timeout = timeout;
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
public static class TestXmlBeanWithInjectedValue {
@Value("${timeout}")
private int timeout;
private int batch;
public void setBatch(int batch) {
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
static class TestAllKindsOfDataTypesBean {
private int intProperty;
private int[] intArrayProperty;
private long longProperty;
private short shortProperty;
private float floatProperty;
private double doubleProperty;
private byte byteProperty;
private boolean booleanProperty;
private String stringProperty;
private Date dateProperty;
public void setDateProperty(Date dateProperty) {
this.dateProperty = dateProperty;
}
public void setIntProperty(int intProperty) {
this.intProperty = intProperty;
}
public void setIntArrayProperty(int[] intArrayProperty) {
this.intArrayProperty = intArrayProperty;
}
public void setLongProperty(long longProperty) {
this.longProperty = longProperty;
}
public void setShortProperty(short shortProperty) {
this.shortProperty = shortProperty;
}
public void setFloatProperty(float floatProperty) {
this.floatProperty = floatProperty;
}
public void setDoubleProperty(double doubleProperty) {
this.doubleProperty = doubleProperty;
}
public void setByteProperty(byte byteProperty) {
this.byteProperty = byteProperty;
}
public void setBooleanProperty(boolean booleanProperty) {
this.booleanProperty = booleanProperty;
}
public void setStringProperty(String stringProperty) {
this.stringProperty = stringProperty;
}
public int getIntProperty() {
return intProperty;
}
public int[] getIntArrayProperty() {
return intArrayProperty;
}
public long getLongProperty() {
return longProperty;
}
public short getShortProperty() {
return shortProperty;
}
public float getFloatProperty() {
return floatProperty;
}
public double getDoubleProperty() {
return doubleProperty;
}
public byte getByteProperty() {
return byteProperty;
}
public boolean getBooleanProperty() {
return booleanProperty;
}
public String getStringProperty() {
return stringProperty;
}
public Date getDateProperty() {
return dateProperty;
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.internals.SimpleConfig;
import com.ctrip.framework.apollo.spring.XmlConfigPlaceholderTest.TestXmlBean;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.google.common.primitives.Ints;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlConfigPlaceholderAutoUpdateTest extends AbstractSpringIntegrationTest {
private static final String TIMEOUT_PROPERTY = "timeout";
private static final int DEFAULT_TIMEOUT = 100;
private static final String BATCH_PROPERTY = "batch";
private static final int DEFAULT_BATCH = 200;
private static final String FX_APOLLO_NAMESPACE = "FX.apollo";
@Test
public void testAutoUpdateWithOneNamespace() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout),
BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateDisabled() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
MockConfigUtil mockConfigUtil = new MockConfigUtil();
mockConfigUtil.setAutoUpdateInjectedSpringProperties(false);
MockInjector.setInstance(ConfigUtil.class, mockConfigUtil);
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout),
BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespaces() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(initialTimeout));
Properties fxApolloProperties = assembleProperties(BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION,
applicationProperties);
SimpleConfig fxApolloConfig = prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest3.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(newTimeout));
applicationConfig
.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newFxApolloProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(newBatch));
fxApolloConfig.onRepositoryChange(FX_APOLLO_NAMESPACE, newFxApolloProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespacesWithSameProperties() throws Exception {
int someTimeout = 1000;
int someBatch = 2000;
int anotherBatch = 3000;
int someNewTimeout = 1001;
int someNewBatch = 2001;
Properties applicationProperties = assembleProperties(BATCH_PROPERTY,
String.valueOf(someBatch));
Properties fxApolloProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch));
prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties);
SimpleConfig fxApolloConfig = prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest3.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
Properties newFxApolloProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(someNewTimeout), BATCH_PROPERTY, String.valueOf(someNewBatch));
fxApolloConfig.onRepositoryChange(FX_APOLLO_NAMESPACE, newFxApolloProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithNewProperties() throws Exception {
int initialTimeout = 1000;
int newTimeout = 1001;
int newBatch = 2001;
Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(initialTimeout));
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION,
applicationProperties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
applicationConfig
.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithIrrelevantProperties() throws Exception {
int initialTimeout = 1000;
String someIrrelevantKey = "someIrrelevantKey";
String someIrrelevantValue = "someIrrelevantValue";
String anotherIrrelevantKey = "anotherIrrelevantKey";
String anotherIrrelevantValue = "anotherIrrelevantValue";
Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(initialTimeout), someIrrelevantKey, someIrrelevantValue);
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION,
applicationProperties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(initialTimeout), anotherIrrelevantKey, anotherIrrelevantValue);
applicationConfig
.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
}
@Test
public void testAutoUpdateWithDeletedProperties() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = new Properties();
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(DEFAULT_TIMEOUT, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespacesWithSamePropertiesDeleted() throws Exception {
int someTimeout = 1000;
int someBatch = 2000;
int anotherBatch = 3000;
Properties applicationProperties = assembleProperties(BATCH_PROPERTY,
String.valueOf(someBatch));
Properties fxApolloProperties = assembleProperties(TIMEOUT_PROPERTY,
String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch));
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION,
applicationProperties);
prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest3.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
Properties newProperties = new Properties();
applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(anotherBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithDeletedPropertiesWithNoDefaultValue() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest7.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(300);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithTypeMismatch() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
String newBatch = "newBatch";
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml");
TestXmlBean bean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout),
BATCH_PROPERTY, newBatch);
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(300);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithValueInjectedAsConstructorArgs() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest8.xml");
TestXmlBeanWithConstructorArgs bean = context.getBean(TestXmlBeanWithConstructorArgs.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout),
BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
// Does not support this scenario
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithValueAndProperty() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest9.xml");
TestXmlBeanWithInjectedValue bean = context.getBean(TestXmlBeanWithInjectedValue.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout),
BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithAllKindsOfDataTypes() throws Exception {
int someInt = 1000;
int someNewInt = 1001;
int[] someIntArray = {1, 2, 3, 4};
int[] someNewIntArray = {5, 6, 7, 8};
long someLong = 2000L;
long someNewLong = 2001L;
short someShort = 3000;
short someNewShort = 3001;
float someFloat = 1.2F;
float someNewFloat = 2.2F;
double someDouble = 3.10D;
double someNewDouble = 4.10D;
byte someByte = 123;
byte someNewByte = 124;
boolean someBoolean = true;
boolean someNewBoolean = !someBoolean;
String someString = "someString";
String someNewString = "someNewString";
String someDateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
Date someDate = assembleDate(2018, 2, 23, 20, 1, 2, 123);
Date someNewDate = assembleDate(2018, 2, 23, 21, 2, 3, 345);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(someDateFormat, Locale.US);
Properties properties = new Properties();
properties.setProperty("intProperty", String.valueOf(someInt));
properties.setProperty("intArrayProperty", Ints.join(", ", someIntArray));
properties.setProperty("longProperty", String.valueOf(someLong));
properties.setProperty("shortProperty", String.valueOf(someShort));
properties.setProperty("floatProperty", String.valueOf(someFloat));
properties.setProperty("doubleProperty", String.valueOf(someDouble));
properties.setProperty("byteProperty", String.valueOf(someByte));
properties.setProperty("booleanProperty", String.valueOf(someBoolean));
properties.setProperty("stringProperty", someString);
properties.setProperty("dateFormat", someDateFormat);
properties.setProperty("dateProperty", simpleDateFormat.format(someDate));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest10.xml");
TestAllKindsOfDataTypesBean bean = context.getBean(TestAllKindsOfDataTypesBean.class);
assertEquals(someInt, bean.getIntProperty());
assertArrayEquals(someIntArray, bean.getIntArrayProperty());
assertEquals(someLong, bean.getLongProperty());
assertEquals(someShort, bean.getShortProperty());
assertEquals(someFloat, bean.getFloatProperty(), 0.001F);
assertEquals(someDouble, bean.getDoubleProperty(), 0.001D);
assertEquals(someByte, bean.getByteProperty());
assertEquals(someBoolean, bean.getBooleanProperty());
assertEquals(someString, bean.getStringProperty());
assertEquals(someDate, bean.getDateProperty());
Properties newProperties = new Properties();
newProperties.setProperty("intProperty", String.valueOf(someNewInt));
newProperties.setProperty("intArrayProperty", Ints.join(", ", someNewIntArray));
newProperties.setProperty("longProperty", String.valueOf(someNewLong));
newProperties.setProperty("shortProperty", String.valueOf(someNewShort));
newProperties.setProperty("floatProperty", String.valueOf(someNewFloat));
newProperties.setProperty("doubleProperty", String.valueOf(someNewDouble));
newProperties.setProperty("byteProperty", String.valueOf(someNewByte));
newProperties.setProperty("booleanProperty", String.valueOf(someNewBoolean));
newProperties.setProperty("stringProperty", someNewString);
newProperties.setProperty("dateFormat", someDateFormat);
newProperties.setProperty("dateProperty", simpleDateFormat.format(someNewDate));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewInt, bean.getIntProperty());
assertArrayEquals(someNewIntArray, bean.getIntArrayProperty());
assertEquals(someNewLong, bean.getLongProperty());
assertEquals(someNewShort, bean.getShortProperty());
assertEquals(someNewFloat, bean.getFloatProperty(), 0.001F);
assertEquals(someNewDouble, bean.getDoubleProperty(), 0.001D);
assertEquals(someNewByte, bean.getByteProperty());
assertEquals(someNewBoolean, bean.getBooleanProperty());
assertEquals(someNewString, bean.getStringProperty());
assertEquals(someNewDate, bean.getDateProperty());
}
public static class TestXmlBeanWithConstructorArgs {
private final int timeout;
private final int batch;
public TestXmlBeanWithConstructorArgs(int timeout, int batch) {
this.timeout = timeout;
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
public static class TestXmlBeanWithInjectedValue {
@Value("${timeout}")
private int timeout;
private int batch;
public void setBatch(int batch) {
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
static class TestAllKindsOfDataTypesBean {
private int intProperty;
private int[] intArrayProperty;
private long longProperty;
private short shortProperty;
private float floatProperty;
private double doubleProperty;
private byte byteProperty;
private boolean booleanProperty;
private String stringProperty;
private Date dateProperty;
public void setDateProperty(Date dateProperty) {
this.dateProperty = dateProperty;
}
public void setIntProperty(int intProperty) {
this.intProperty = intProperty;
}
public void setIntArrayProperty(int[] intArrayProperty) {
this.intArrayProperty = intArrayProperty;
}
public void setLongProperty(long longProperty) {
this.longProperty = longProperty;
}
public void setShortProperty(short shortProperty) {
this.shortProperty = shortProperty;
}
public void setFloatProperty(float floatProperty) {
this.floatProperty = floatProperty;
}
public void setDoubleProperty(double doubleProperty) {
this.doubleProperty = doubleProperty;
}
public void setByteProperty(byte byteProperty) {
this.byteProperty = byteProperty;
}
public void setBooleanProperty(boolean booleanProperty) {
this.booleanProperty = booleanProperty;
}
public void setStringProperty(String stringProperty) {
this.stringProperty = stringProperty;
}
public int getIntProperty() {
return intProperty;
}
public int[] getIntArrayProperty() {
return intArrayProperty;
}
public long getLongProperty() {
return longProperty;
}
public short getShortProperty() {
return shortProperty;
}
public float getFloatProperty() {
return floatProperty;
}
public double getDoubleProperty() {
return doubleProperty;
}
public byte getByteProperty() {
return byteProperty;
}
public boolean getBooleanProperty() {
return booleanProperty;
}
public String getStringProperty() {
return stringProperty;
}
public Date getDateProperty() {
return dateProperty;
}
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-configservice/src/test/java/com/ctrip/framework/apollo/configservice/integration/ConfigFileControllerIntegrationTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.integration;
import com.ctrip.framework.apollo.configservice.service.AppNamespaceServiceWithCache;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.ctrip.framework.apollo.biz.entity.Namespace;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.netflix.servo.util.Strings;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.jdbc.Sql;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class ConfigFileControllerIntegrationTest extends AbstractBaseIntegrationTest {
private String someAppId;
private String somePublicAppId;
private String someCluster;
private String someNamespace;
private String somePublicNamespace;
private String someDC;
private String someDefaultCluster;
private String grayClientIp;
private String nonGrayClientIp;
private static final Gson GSON = new Gson();
private ExecutorService executorService;
private Type mapResponseType = new TypeToken<Map<String, String>>(){}.getType();
@Autowired
private AppNamespaceServiceWithCache appNamespaceServiceWithCache;
@Before
public void setUp() throws Exception {
ReflectionTestUtils.invokeMethod(appNamespaceServiceWithCache, "reset");
someDefaultCluster = ConfigConsts.CLUSTER_NAME_DEFAULT;
someAppId = "someAppId";
somePublicAppId = "somePublicAppId";
someCluster = "someCluster";
someNamespace = "someNamespace";
somePublicNamespace = "somePublicNamespace";
someDC = "someDC";
grayClientIp = "1.1.1.1";
nonGrayClientIp = "2.2.2.2";
executorService = Executors.newSingleThreadExecutor();
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryConfigAsProperties() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}", String.class,
getHostUrl(), someAppId, someCluster, someNamespace);
String result = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(result.contains("k2=v2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-gray-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryConfigAsPropertiesWithGrayRelease() throws Exception {
AtomicBoolean stop = new AtomicBoolean();
periodicSendMessage(executorService, assembleKey(someAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, ConfigConsts.NAMESPACE_APPLICATION),
stop);
TimeUnit.MILLISECONDS.sleep(500);
stop.set(true);
ResponseEntity<String> response =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}?ip={clientIp}", String.class,
getHostUrl(), someAppId, someDefaultCluster, ConfigConsts.NAMESPACE_APPLICATION, grayClientIp);
ResponseEntity<String> anotherResponse =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}?ip={clientIp}", String.class,
getHostUrl(), someAppId, someDefaultCluster, ConfigConsts.NAMESPACE_APPLICATION, nonGrayClientIp);
String result = response.getBody();
String anotherResult = anotherResponse.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(result.contains("k1=v1-gray"));
assertEquals(HttpStatus.OK, anotherResponse.getStatusCode());
assertFalse(anotherResult.contains("k1=v1-gray"));
assertTrue(anotherResult.contains("k1=v1"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-dc-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigAsProperties() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}?dataCenter={dateCenter}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace, someDC);
String result = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(result.contains("k1=override-someDC-v1"));
assertTrue(result.contains("k2=someDC-v2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryConfigAsJson() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity("http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}", String.class,
getHostUrl(), someAppId, someCluster, someNamespace);
Map<String, String> configs = GSON.fromJson(response.getBody(), mapResponseType);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("v2", configs.get("k2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryConfigAsJsonWithIncorrectCase() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity("http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}", String.class,
getHostUrl(), someAppId, someCluster, someNamespace.toUpperCase());
Map<String, String> configs = GSON.fromJson(response.getBody(), mapResponseType);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("v2", configs.get("k2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-dc-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigAsJson() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?dataCenter={dateCenter}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace, someDC);
Map<String, String> configs = GSON.fromJson(response.getBody(), mapResponseType);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("override-someDC-v1", configs.get("k1"));
assertEquals("someDC-v2", configs.get("k2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-dc-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigAsJsonWithIncorrectCase() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?dataCenter={dateCenter}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace.toUpperCase(), someDC);
Map<String, String> configs = GSON.fromJson(response.getBody(), mapResponseType);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("override-someDC-v1", configs.get("k1"));
assertEquals("someDC-v2", configs.get("k2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-default-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-gray-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigAsJsonWithGrayRelease() throws Exception {
AtomicBoolean stop = new AtomicBoolean();
periodicSendMessage(executorService, assembleKey(somePublicAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, somePublicNamespace),
stop);
TimeUnit.MILLISECONDS.sleep(500);
stop.set(true);
ResponseEntity<String> response =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?ip={clientIp}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace, grayClientIp);
ResponseEntity<String> anotherResponse =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?ip={clientIp}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace, nonGrayClientIp);
Map<String, String> configs = GSON.fromJson(response.getBody(), mapResponseType);
Map<String, String> anotherConfigs = GSON.fromJson(anotherResponse.getBody(), mapResponseType);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(HttpStatus.OK, anotherResponse.getStatusCode());
assertEquals("override-v1", configs.get("k1"));
assertEquals("gray-v2", configs.get("k2"));
assertEquals("override-v1", anotherConfigs.get("k1"));
assertEquals("default-v2", anotherConfigs.get("k2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-default-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-gray-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigAsJsonWithGrayReleaseAndIncorrectCase() throws Exception {
AtomicBoolean stop = new AtomicBoolean();
periodicSendMessage(executorService, assembleKey(somePublicAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, somePublicNamespace),
stop);
TimeUnit.MILLISECONDS.sleep(500);
stop.set(true);
ResponseEntity<String> response =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?ip={clientIp}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace.toUpperCase(), grayClientIp);
ResponseEntity<String> anotherResponse =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?ip={clientIp}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace.toUpperCase(), nonGrayClientIp);
Map<String, String> configs = GSON.fromJson(response.getBody(), mapResponseType);
Map<String, String> anotherConfigs = GSON.fromJson(anotherResponse.getBody(), mapResponseType);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(HttpStatus.OK, anotherResponse.getStatusCode());
assertEquals("override-v1", configs.get("k1"));
assertEquals("gray-v2", configs.get("k2"));
assertEquals("override-v1", anotherConfigs.get("k1"));
assertEquals("default-v2", anotherConfigs.get("k2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testConfigChanged() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}", String.class,
getHostUrl(), someAppId, someCluster, someNamespace);
String result = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(result.contains("k2=v2"));
String someReleaseName = "someReleaseName";
String someReleaseComment = "someReleaseComment";
Namespace namespace = new Namespace();
namespace.setAppId(someAppId);
namespace.setClusterName(someCluster);
namespace.setNamespaceName(someNamespace);
String someOwner = "someOwner";
Map<String, String> newConfigurations = ImmutableMap.of("k1", "v1-changed", "k2", "v2-changed");
buildRelease(someReleaseName, someReleaseComment, namespace, newConfigurations, someOwner);
ResponseEntity<String> anotherResponse =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}", String.class,
getHostUrl(), someAppId, someCluster, someNamespace);
assertEquals(response.getBody(), anotherResponse.getBody());
List<String> keys = Lists.newArrayList(someAppId, someCluster, someNamespace);
String message = Strings.join(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR, keys.iterator());
sendReleaseMessage(message);
TimeUnit.MILLISECONDS.sleep(500);
ResponseEntity<String> newResponse =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}", String.class,
getHostUrl(), someAppId, someCluster, someNamespace);
result = newResponse.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(result.contains("k1=v1-changed"));
assertTrue(result.contains("k2=v2-changed"));
}
private String assembleKey(String appId, String cluster, String namespace) {
return Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR).join(appId, cluster, namespace);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.integration;
import com.ctrip.framework.apollo.configservice.service.AppNamespaceServiceWithCache;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.ctrip.framework.apollo.biz.entity.Namespace;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.netflix.servo.util.Strings;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.jdbc.Sql;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class ConfigFileControllerIntegrationTest extends AbstractBaseIntegrationTest {
private String someAppId;
private String somePublicAppId;
private String someCluster;
private String someNamespace;
private String somePublicNamespace;
private String someDC;
private String someDefaultCluster;
private String grayClientIp;
private String nonGrayClientIp;
private static final Gson GSON = new Gson();
private ExecutorService executorService;
private Type mapResponseType = new TypeToken<Map<String, String>>(){}.getType();
@Autowired
private AppNamespaceServiceWithCache appNamespaceServiceWithCache;
@Before
public void setUp() throws Exception {
ReflectionTestUtils.invokeMethod(appNamespaceServiceWithCache, "reset");
someDefaultCluster = ConfigConsts.CLUSTER_NAME_DEFAULT;
someAppId = "someAppId";
somePublicAppId = "somePublicAppId";
someCluster = "someCluster";
someNamespace = "someNamespace";
somePublicNamespace = "somePublicNamespace";
someDC = "someDC";
grayClientIp = "1.1.1.1";
nonGrayClientIp = "2.2.2.2";
executorService = Executors.newSingleThreadExecutor();
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryConfigAsProperties() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}", String.class,
getHostUrl(), someAppId, someCluster, someNamespace);
String result = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(result.contains("k2=v2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-gray-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryConfigAsPropertiesWithGrayRelease() throws Exception {
AtomicBoolean stop = new AtomicBoolean();
periodicSendMessage(executorService, assembleKey(someAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, ConfigConsts.NAMESPACE_APPLICATION),
stop);
TimeUnit.MILLISECONDS.sleep(500);
stop.set(true);
ResponseEntity<String> response =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}?ip={clientIp}", String.class,
getHostUrl(), someAppId, someDefaultCluster, ConfigConsts.NAMESPACE_APPLICATION, grayClientIp);
ResponseEntity<String> anotherResponse =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}?ip={clientIp}", String.class,
getHostUrl(), someAppId, someDefaultCluster, ConfigConsts.NAMESPACE_APPLICATION, nonGrayClientIp);
String result = response.getBody();
String anotherResult = anotherResponse.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(result.contains("k1=v1-gray"));
assertEquals(HttpStatus.OK, anotherResponse.getStatusCode());
assertFalse(anotherResult.contains("k1=v1-gray"));
assertTrue(anotherResult.contains("k1=v1"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-dc-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigAsProperties() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}?dataCenter={dateCenter}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace, someDC);
String result = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(result.contains("k1=override-someDC-v1"));
assertTrue(result.contains("k2=someDC-v2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryConfigAsJson() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity("http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}", String.class,
getHostUrl(), someAppId, someCluster, someNamespace);
Map<String, String> configs = GSON.fromJson(response.getBody(), mapResponseType);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("v2", configs.get("k2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryConfigAsJsonWithIncorrectCase() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity("http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}", String.class,
getHostUrl(), someAppId, someCluster, someNamespace.toUpperCase());
Map<String, String> configs = GSON.fromJson(response.getBody(), mapResponseType);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("v2", configs.get("k2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-dc-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigAsJson() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?dataCenter={dateCenter}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace, someDC);
Map<String, String> configs = GSON.fromJson(response.getBody(), mapResponseType);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("override-someDC-v1", configs.get("k1"));
assertEquals("someDC-v2", configs.get("k2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-dc-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigAsJsonWithIncorrectCase() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?dataCenter={dateCenter}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace.toUpperCase(), someDC);
Map<String, String> configs = GSON.fromJson(response.getBody(), mapResponseType);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("override-someDC-v1", configs.get("k1"));
assertEquals("someDC-v2", configs.get("k2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-default-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-gray-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigAsJsonWithGrayRelease() throws Exception {
AtomicBoolean stop = new AtomicBoolean();
periodicSendMessage(executorService, assembleKey(somePublicAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, somePublicNamespace),
stop);
TimeUnit.MILLISECONDS.sleep(500);
stop.set(true);
ResponseEntity<String> response =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?ip={clientIp}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace, grayClientIp);
ResponseEntity<String> anotherResponse =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?ip={clientIp}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace, nonGrayClientIp);
Map<String, String> configs = GSON.fromJson(response.getBody(), mapResponseType);
Map<String, String> anotherConfigs = GSON.fromJson(anotherResponse.getBody(), mapResponseType);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(HttpStatus.OK, anotherResponse.getStatusCode());
assertEquals("override-v1", configs.get("k1"));
assertEquals("gray-v2", configs.get("k2"));
assertEquals("override-v1", anotherConfigs.get("k1"));
assertEquals("default-v2", anotherConfigs.get("k2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-default-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-gray-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigAsJsonWithGrayReleaseAndIncorrectCase() throws Exception {
AtomicBoolean stop = new AtomicBoolean();
periodicSendMessage(executorService, assembleKey(somePublicAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, somePublicNamespace),
stop);
TimeUnit.MILLISECONDS.sleep(500);
stop.set(true);
ResponseEntity<String> response =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?ip={clientIp}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace.toUpperCase(), grayClientIp);
ResponseEntity<String> anotherResponse =
restTemplate
.getForEntity(
"http://{baseurl}/configfiles/json/{appId}/{clusterName}/{namespace}?ip={clientIp}",
String.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace.toUpperCase(), nonGrayClientIp);
Map<String, String> configs = GSON.fromJson(response.getBody(), mapResponseType);
Map<String, String> anotherConfigs = GSON.fromJson(anotherResponse.getBody(), mapResponseType);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(HttpStatus.OK, anotherResponse.getStatusCode());
assertEquals("override-v1", configs.get("k1"));
assertEquals("gray-v2", configs.get("k2"));
assertEquals("override-v1", anotherConfigs.get("k1"));
assertEquals("default-v2", anotherConfigs.get("k2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testConfigChanged() throws Exception {
ResponseEntity<String> response =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}", String.class,
getHostUrl(), someAppId, someCluster, someNamespace);
String result = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(result.contains("k2=v2"));
String someReleaseName = "someReleaseName";
String someReleaseComment = "someReleaseComment";
Namespace namespace = new Namespace();
namespace.setAppId(someAppId);
namespace.setClusterName(someCluster);
namespace.setNamespaceName(someNamespace);
String someOwner = "someOwner";
Map<String, String> newConfigurations = ImmutableMap.of("k1", "v1-changed", "k2", "v2-changed");
buildRelease(someReleaseName, someReleaseComment, namespace, newConfigurations, someOwner);
ResponseEntity<String> anotherResponse =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}", String.class,
getHostUrl(), someAppId, someCluster, someNamespace);
assertEquals(response.getBody(), anotherResponse.getBody());
List<String> keys = Lists.newArrayList(someAppId, someCluster, someNamespace);
String message = Strings.join(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR, keys.iterator());
sendReleaseMessage(message);
TimeUnit.MILLISECONDS.sleep(500);
ResponseEntity<String> newResponse =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}", String.class,
getHostUrl(), someAppId, someCluster, someNamespace);
result = newResponse.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(result.contains("k1=v1-changed"));
assertTrue(result.contains("k2=v2-changed"));
}
private String assembleKey(String appId, String cluster, String namespace) {
return Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR).join(appId, cluster, namespace);
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/ClusterOpenApiService.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.openapi.client.service;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.openapi.dto.OpenClusterDTO;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
public class ClusterOpenApiService extends AbstractOpenApiService {
public ClusterOpenApiService(CloseableHttpClient client, String baseUrl, Gson gson) {
super(client, baseUrl, gson);
}
public OpenClusterDTO getCluster(String appId, String env, String clusterName) {
checkNotEmpty(appId, "App id");
checkNotEmpty(env, "Env");
if (Strings.isNullOrEmpty(clusterName)) {
clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT;
}
String path = String.format("envs/%s/apps/%s/clusters/%s", escapePath(env), escapePath(appId),
escapePath(clusterName));
try (CloseableHttpResponse response = get(path)) {
return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenClusterDTO.class);
} catch (Throwable ex) {
throw new RuntimeException(String
.format("Get cluster for appId: %s, cluster: %s in env: %s failed", appId, clusterName, env), ex);
}
}
public OpenClusterDTO createCluster(String env, OpenClusterDTO openClusterDTO) {
checkNotEmpty(openClusterDTO.getAppId(), "App id");
checkNotEmpty(env, "Env");
checkNotEmpty(openClusterDTO.getName(), "Cluster name");
checkNotEmpty(openClusterDTO.getDataChangeCreatedBy(), "Created by");
String path = String.format("envs/%s/apps/%s/clusters", escapePath(env), escapePath(openClusterDTO.getAppId()));
try (CloseableHttpResponse response = post(path, openClusterDTO)) {
return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenClusterDTO.class);
} catch (Throwable ex) {
throw new RuntimeException(String
.format("Create cluster: %s for appId: %s in env: %s failed", openClusterDTO.getName(),
openClusterDTO.getAppId(), env), ex);
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.openapi.client.service;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.openapi.dto.OpenClusterDTO;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
public class ClusterOpenApiService extends AbstractOpenApiService {
public ClusterOpenApiService(CloseableHttpClient client, String baseUrl, Gson gson) {
super(client, baseUrl, gson);
}
public OpenClusterDTO getCluster(String appId, String env, String clusterName) {
checkNotEmpty(appId, "App id");
checkNotEmpty(env, "Env");
if (Strings.isNullOrEmpty(clusterName)) {
clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT;
}
String path = String.format("envs/%s/apps/%s/clusters/%s", escapePath(env), escapePath(appId),
escapePath(clusterName));
try (CloseableHttpResponse response = get(path)) {
return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenClusterDTO.class);
} catch (Throwable ex) {
throw new RuntimeException(String
.format("Get cluster for appId: %s, cluster: %s in env: %s failed", appId, clusterName, env), ex);
}
}
public OpenClusterDTO createCluster(String env, OpenClusterDTO openClusterDTO) {
checkNotEmpty(openClusterDTO.getAppId(), "App id");
checkNotEmpty(env, "Env");
checkNotEmpty(openClusterDTO.getName(), "Cluster name");
checkNotEmpty(openClusterDTO.getDataChangeCreatedBy(), "Created by");
String path = String.format("envs/%s/apps/%s/clusters", escapePath(env), escapePath(openClusterDTO.getAppId()));
try (CloseableHttpResponse response = post(path, openClusterDTO)) {
return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenClusterDTO.class);
} catch (Throwable ex) {
throw new RuntimeException(String
.format("Create cluster: %s for appId: %s in env: %s failed", openClusterDTO.getName(),
openClusterDTO.getAppId(), env), ex);
}
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/repository/AppNamespaceRepository.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
import java.util.Set;
public interface AppNamespaceRepository extends PagingAndSortingRepository<AppNamespace, Long>{
AppNamespace findByAppIdAndName(String appId, String namespaceName);
List<AppNamespace> findByAppIdAndNameIn(String appId, Set<String> namespaceNames);
AppNamespace findByNameAndIsPublicTrue(String namespaceName);
List<AppNamespace> findByNameInAndIsPublicTrue(Set<String> namespaceNames);
List<AppNamespace> findByAppIdAndIsPublic(String appId, boolean isPublic);
List<AppNamespace> findByAppId(String appId);
List<AppNamespace> findFirst500ByIdGreaterThanOrderByIdAsc(long id);
@Modifying
@Query("UPDATE AppNamespace SET IsDeleted=1,DataChange_LastModifiedBy = ?2 WHERE AppId=?1")
int batchDeleteByAppId(String appId, String operator);
@Modifying
@Query("UPDATE AppNamespace SET IsDeleted=1,DataChange_LastModifiedBy = ?3 WHERE AppId=?1 and Name = ?2")
int delete(String appId, String namespaceName, String operator);
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
import java.util.Set;
public interface AppNamespaceRepository extends PagingAndSortingRepository<AppNamespace, Long>{
AppNamespace findByAppIdAndName(String appId, String namespaceName);
List<AppNamespace> findByAppIdAndNameIn(String appId, Set<String> namespaceNames);
AppNamespace findByNameAndIsPublicTrue(String namespaceName);
List<AppNamespace> findByNameInAndIsPublicTrue(Set<String> namespaceNames);
List<AppNamespace> findByAppIdAndIsPublic(String appId, boolean isPublic);
List<AppNamespace> findByAppId(String appId);
List<AppNamespace> findFirst500ByIdGreaterThanOrderByIdAsc(long id);
@Modifying
@Query("UPDATE AppNamespace SET IsDeleted=1,DataChange_LastModifiedBy = ?2 WHERE AppId=?1")
int batchDeleteByAppId(String appId, String operator);
@Modifying
@Query("UPDATE AppNamespace SET IsDeleted=1,DataChange_LastModifiedBy = ?3 WHERE AppId=?1 and Name = ?2")
int delete(String appId, String namespaceName, String operator);
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/test/java/com/ctrip/framework/apollo/internals/YamlConfigFileTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.util.OrderedProperties;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import com.ctrip.framework.apollo.util.yaml.YamlParser;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
@RunWith(MockitoJUnitRunner.class)
public class YamlConfigFileTest {
private String someNamespace;
@Mock
private ConfigRepository configRepository;
@Mock
private YamlParser yamlParser;
@Mock
private PropertiesFactory propertiesFactory;
private ConfigSourceType someSourceType;
@Before
public void setUp() throws Exception {
someNamespace = "someName";
MockInjector.setInstance(YamlParser.class, yamlParser);
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new Properties();
}
});
MockInjector.setInstance(PropertiesFactory.class, propertiesFactory);
}
@After
public void tearDown() throws Exception {
MockInjector.reset();
}
@Test
public void testWhenHasContent() throws Exception {
Properties someProperties = new Properties();
String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY;
String someContent = "someKey: 'someValue'";
someProperties.setProperty(key, someContent);
someSourceType = ConfigSourceType.LOCAL;
Properties yamlProperties = new Properties();
yamlProperties.setProperty("someKey", "someValue");
when(configRepository.getConfig()).thenReturn(someProperties);
when(configRepository.getSourceType()).thenReturn(someSourceType);
when(yamlParser.yamlToProperties(someContent)).thenReturn(yamlProperties);
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertSame(someContent, configFile.getContent());
assertSame(yamlProperties, configFile.asProperties());
}
@Test
public void testWhenHasContentWithOrder() throws Exception {
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new OrderedProperties();
}
});
Properties someProperties = new Properties();
String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY;
String someContent = "someKey: 'someValue'\nsomeKey2: 'someValue2'";
someProperties.setProperty(key, someContent);
someSourceType = ConfigSourceType.LOCAL;
Properties yamlProperties = new YamlParser().yamlToProperties(someContent);
when(configRepository.getConfig()).thenReturn(someProperties);
when(configRepository.getSourceType()).thenReturn(someSourceType);
when(yamlParser.yamlToProperties(someContent)).thenReturn(yamlProperties);
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertSame(someContent, configFile.getContent());
assertSame(yamlProperties, configFile.asProperties());
String[] actualArrays = configFile.asProperties().keySet().toArray(new String[]{});
String[] expectedArrays = {"someKey", "someKey2"};
assertArrayEquals(expectedArrays, actualArrays);
}
@Test
public void testWhenHasNoContent() throws Exception {
when(configRepository.getConfig()).thenReturn(null);
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertFalse(configFile.hasContent());
assertNull(configFile.getContent());
Properties properties = configFile.asProperties();
assertTrue(properties.isEmpty());
}
@Test
public void testWhenInvalidYamlContent() throws Exception {
Properties someProperties = new Properties();
String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY;
String someInvalidContent = ",";
someProperties.setProperty(key, someInvalidContent);
someSourceType = ConfigSourceType.LOCAL;
when(configRepository.getConfig()).thenReturn(someProperties);
when(configRepository.getSourceType()).thenReturn(someSourceType);
when(yamlParser.yamlToProperties(someInvalidContent))
.thenThrow(new RuntimeException("some exception"));
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertSame(someInvalidContent, configFile.getContent());
Throwable exceptionThrown = null;
try {
configFile.asProperties();
} catch (Throwable ex) {
exceptionThrown = ex;
}
assertTrue(exceptionThrown instanceof ApolloConfigException);
assertNotNull(exceptionThrown.getCause());
}
@Test
public void testWhenConfigRepositoryHasError() throws Exception {
when(configRepository.getConfig()).thenThrow(new RuntimeException("someError"));
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertFalse(configFile.hasContent());
assertNull(configFile.getContent());
assertEquals(ConfigSourceType.NONE, configFile.getSourceType());
Properties properties = configFile.asProperties();
assertTrue(properties.isEmpty());
}
@Test
public void testOnRepositoryChange() throws Exception {
Properties someProperties = new Properties();
String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY;
String someValue = "someKey: 'someValue'";
String anotherValue = "anotherKey: 'anotherValue'";
someProperties.setProperty(key, someValue);
someSourceType = ConfigSourceType.LOCAL;
Properties someYamlProperties = new Properties();
someYamlProperties.setProperty("someKey", "someValue");
Properties anotherYamlProperties = new Properties();
anotherYamlProperties.setProperty("anotherKey", "anotherValue");
when(configRepository.getConfig()).thenReturn(someProperties);
when(configRepository.getSourceType()).thenReturn(someSourceType);
when(yamlParser.yamlToProperties(someValue)).thenReturn(someYamlProperties);
when(yamlParser.yamlToProperties(anotherValue)).thenReturn(anotherYamlProperties);
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertEquals(someValue, configFile.getContent());
assertEquals(someSourceType, configFile.getSourceType());
assertSame(someYamlProperties, configFile.asProperties());
Properties anotherProperties = new Properties();
anotherProperties.setProperty(key, anotherValue);
ConfigSourceType anotherSourceType = ConfigSourceType.REMOTE;
when(configRepository.getSourceType()).thenReturn(anotherSourceType);
configFile.onRepositoryChange(someNamespace, anotherProperties);
assertEquals(anotherValue, configFile.getContent());
assertEquals(anotherSourceType, configFile.getSourceType());
assertSame(anotherYamlProperties, configFile.asProperties());
}
@Test
public void testWhenConfigRepositoryHasErrorAndThenRecovered() throws Exception {
Properties someProperties = new Properties();
String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY;
String someValue = "someKey: 'someValue'";
someProperties.setProperty(key, someValue);
someSourceType = ConfigSourceType.LOCAL;
Properties someYamlProperties = new Properties();
someYamlProperties.setProperty("someKey", "someValue");
when(configRepository.getConfig()).thenThrow(new RuntimeException("someError"));
when(configRepository.getSourceType()).thenReturn(someSourceType);
when(yamlParser.yamlToProperties(someValue)).thenReturn(someYamlProperties);
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertFalse(configFile.hasContent());
assertNull(configFile.getContent());
assertEquals(ConfigSourceType.NONE, configFile.getSourceType());
assertTrue(configFile.asProperties().isEmpty());
configFile.onRepositoryChange(someNamespace, someProperties);
assertTrue(configFile.hasContent());
assertEquals(someValue, configFile.getContent());
assertEquals(someSourceType, configFile.getSourceType());
assertSame(someYamlProperties, configFile.asProperties());
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.util.OrderedProperties;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import com.ctrip.framework.apollo.util.yaml.YamlParser;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
@RunWith(MockitoJUnitRunner.class)
public class YamlConfigFileTest {
private String someNamespace;
@Mock
private ConfigRepository configRepository;
@Mock
private YamlParser yamlParser;
@Mock
private PropertiesFactory propertiesFactory;
private ConfigSourceType someSourceType;
@Before
public void setUp() throws Exception {
someNamespace = "someName";
MockInjector.setInstance(YamlParser.class, yamlParser);
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new Properties();
}
});
MockInjector.setInstance(PropertiesFactory.class, propertiesFactory);
}
@After
public void tearDown() throws Exception {
MockInjector.reset();
}
@Test
public void testWhenHasContent() throws Exception {
Properties someProperties = new Properties();
String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY;
String someContent = "someKey: 'someValue'";
someProperties.setProperty(key, someContent);
someSourceType = ConfigSourceType.LOCAL;
Properties yamlProperties = new Properties();
yamlProperties.setProperty("someKey", "someValue");
when(configRepository.getConfig()).thenReturn(someProperties);
when(configRepository.getSourceType()).thenReturn(someSourceType);
when(yamlParser.yamlToProperties(someContent)).thenReturn(yamlProperties);
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertSame(someContent, configFile.getContent());
assertSame(yamlProperties, configFile.asProperties());
}
@Test
public void testWhenHasContentWithOrder() throws Exception {
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new OrderedProperties();
}
});
Properties someProperties = new Properties();
String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY;
String someContent = "someKey: 'someValue'\nsomeKey2: 'someValue2'";
someProperties.setProperty(key, someContent);
someSourceType = ConfigSourceType.LOCAL;
Properties yamlProperties = new YamlParser().yamlToProperties(someContent);
when(configRepository.getConfig()).thenReturn(someProperties);
when(configRepository.getSourceType()).thenReturn(someSourceType);
when(yamlParser.yamlToProperties(someContent)).thenReturn(yamlProperties);
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertSame(someContent, configFile.getContent());
assertSame(yamlProperties, configFile.asProperties());
String[] actualArrays = configFile.asProperties().keySet().toArray(new String[]{});
String[] expectedArrays = {"someKey", "someKey2"};
assertArrayEquals(expectedArrays, actualArrays);
}
@Test
public void testWhenHasNoContent() throws Exception {
when(configRepository.getConfig()).thenReturn(null);
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertFalse(configFile.hasContent());
assertNull(configFile.getContent());
Properties properties = configFile.asProperties();
assertTrue(properties.isEmpty());
}
@Test
public void testWhenInvalidYamlContent() throws Exception {
Properties someProperties = new Properties();
String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY;
String someInvalidContent = ",";
someProperties.setProperty(key, someInvalidContent);
someSourceType = ConfigSourceType.LOCAL;
when(configRepository.getConfig()).thenReturn(someProperties);
when(configRepository.getSourceType()).thenReturn(someSourceType);
when(yamlParser.yamlToProperties(someInvalidContent))
.thenThrow(new RuntimeException("some exception"));
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertSame(someInvalidContent, configFile.getContent());
Throwable exceptionThrown = null;
try {
configFile.asProperties();
} catch (Throwable ex) {
exceptionThrown = ex;
}
assertTrue(exceptionThrown instanceof ApolloConfigException);
assertNotNull(exceptionThrown.getCause());
}
@Test
public void testWhenConfigRepositoryHasError() throws Exception {
when(configRepository.getConfig()).thenThrow(new RuntimeException("someError"));
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertFalse(configFile.hasContent());
assertNull(configFile.getContent());
assertEquals(ConfigSourceType.NONE, configFile.getSourceType());
Properties properties = configFile.asProperties();
assertTrue(properties.isEmpty());
}
@Test
public void testOnRepositoryChange() throws Exception {
Properties someProperties = new Properties();
String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY;
String someValue = "someKey: 'someValue'";
String anotherValue = "anotherKey: 'anotherValue'";
someProperties.setProperty(key, someValue);
someSourceType = ConfigSourceType.LOCAL;
Properties someYamlProperties = new Properties();
someYamlProperties.setProperty("someKey", "someValue");
Properties anotherYamlProperties = new Properties();
anotherYamlProperties.setProperty("anotherKey", "anotherValue");
when(configRepository.getConfig()).thenReturn(someProperties);
when(configRepository.getSourceType()).thenReturn(someSourceType);
when(yamlParser.yamlToProperties(someValue)).thenReturn(someYamlProperties);
when(yamlParser.yamlToProperties(anotherValue)).thenReturn(anotherYamlProperties);
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertEquals(someValue, configFile.getContent());
assertEquals(someSourceType, configFile.getSourceType());
assertSame(someYamlProperties, configFile.asProperties());
Properties anotherProperties = new Properties();
anotherProperties.setProperty(key, anotherValue);
ConfigSourceType anotherSourceType = ConfigSourceType.REMOTE;
when(configRepository.getSourceType()).thenReturn(anotherSourceType);
configFile.onRepositoryChange(someNamespace, anotherProperties);
assertEquals(anotherValue, configFile.getContent());
assertEquals(anotherSourceType, configFile.getSourceType());
assertSame(anotherYamlProperties, configFile.asProperties());
}
@Test
public void testWhenConfigRepositoryHasErrorAndThenRecovered() throws Exception {
Properties someProperties = new Properties();
String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY;
String someValue = "someKey: 'someValue'";
someProperties.setProperty(key, someValue);
someSourceType = ConfigSourceType.LOCAL;
Properties someYamlProperties = new Properties();
someYamlProperties.setProperty("someKey", "someValue");
when(configRepository.getConfig()).thenThrow(new RuntimeException("someError"));
when(configRepository.getSourceType()).thenReturn(someSourceType);
when(yamlParser.yamlToProperties(someValue)).thenReturn(someYamlProperties);
YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository);
assertFalse(configFile.hasContent());
assertNull(configFile.getContent());
assertEquals(ConfigSourceType.NONE, configFile.getSourceType());
assertTrue(configFile.asProperties().isEmpty());
configFile.onRepositoryChange(someNamespace, someProperties);
assertTrue(configFile.hasContent());
assertEquals(someValue, configFile.getContent());
assertEquals(someSourceType, configFile.getSourceType());
assertSame(someYamlProperties, configFile.asProperties());
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/service/ItemSetService.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.service;
import com.ctrip.framework.apollo.biz.entity.Audit;
import com.ctrip.framework.apollo.biz.entity.Commit;
import com.ctrip.framework.apollo.biz.entity.Item;
import com.ctrip.framework.apollo.biz.entity.Namespace;
import com.ctrip.framework.apollo.biz.utils.ConfigChangeContentBuilder;
import com.ctrip.framework.apollo.common.dto.ItemChangeSets;
import com.ctrip.framework.apollo.common.dto.ItemDTO;
import com.ctrip.framework.apollo.common.exception.NotFoundException;
import com.ctrip.framework.apollo.common.utils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
@Service
public class ItemSetService {
private final AuditService auditService;
private final CommitService commitService;
private final ItemService itemService;
public ItemSetService(
final AuditService auditService,
final CommitService commitService,
final ItemService itemService) {
this.auditService = auditService;
this.commitService = commitService;
this.itemService = itemService;
}
@Transactional
public ItemChangeSets updateSet(Namespace namespace, ItemChangeSets changeSets){
return updateSet(namespace.getAppId(), namespace.getClusterName(), namespace.getNamespaceName(), changeSets);
}
@Transactional
public ItemChangeSets updateSet(String appId, String clusterName,
String namespaceName, ItemChangeSets changeSet) {
String operator = changeSet.getDataChangeLastModifiedBy();
ConfigChangeContentBuilder configChangeContentBuilder = new ConfigChangeContentBuilder();
if (!CollectionUtils.isEmpty(changeSet.getCreateItems())) {
for (ItemDTO item : changeSet.getCreateItems()) {
Item entity = BeanUtils.transform(Item.class, item);
entity.setDataChangeCreatedBy(operator);
entity.setDataChangeLastModifiedBy(operator);
Item createdItem = itemService.save(entity);
configChangeContentBuilder.createItem(createdItem);
}
auditService.audit("ItemSet", null, Audit.OP.INSERT, operator);
}
if (!CollectionUtils.isEmpty(changeSet.getUpdateItems())) {
for (ItemDTO item : changeSet.getUpdateItems()) {
Item entity = BeanUtils.transform(Item.class, item);
Item managedItem = itemService.findOne(entity.getId());
if (managedItem == null) {
throw new NotFoundException(String.format("item not found.(key=%s)", entity.getKey()));
}
Item beforeUpdateItem = BeanUtils.transform(Item.class, managedItem);
//protect. only value,comment,lastModifiedBy,lineNum can be modified
managedItem.setValue(entity.getValue());
managedItem.setComment(entity.getComment());
managedItem.setLineNum(entity.getLineNum());
managedItem.setDataChangeLastModifiedBy(operator);
Item updatedItem = itemService.update(managedItem);
configChangeContentBuilder.updateItem(beforeUpdateItem, updatedItem);
}
auditService.audit("ItemSet", null, Audit.OP.UPDATE, operator);
}
if (!CollectionUtils.isEmpty(changeSet.getDeleteItems())) {
for (ItemDTO item : changeSet.getDeleteItems()) {
Item deletedItem = itemService.delete(item.getId(), operator);
configChangeContentBuilder.deleteItem(deletedItem);
}
auditService.audit("ItemSet", null, Audit.OP.DELETE, operator);
}
if (configChangeContentBuilder.hasContent()){
createCommit(appId, clusterName, namespaceName, configChangeContentBuilder.build(),
changeSet.getDataChangeLastModifiedBy());
}
return changeSet;
}
private void createCommit(String appId, String clusterName, String namespaceName, String configChangeContent,
String operator) {
Commit commit = new Commit();
commit.setAppId(appId);
commit.setClusterName(clusterName);
commit.setNamespaceName(namespaceName);
commit.setChangeSets(configChangeContent);
commit.setDataChangeCreatedBy(operator);
commit.setDataChangeLastModifiedBy(operator);
commitService.save(commit);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.service;
import com.ctrip.framework.apollo.biz.entity.Audit;
import com.ctrip.framework.apollo.biz.entity.Commit;
import com.ctrip.framework.apollo.biz.entity.Item;
import com.ctrip.framework.apollo.biz.entity.Namespace;
import com.ctrip.framework.apollo.biz.utils.ConfigChangeContentBuilder;
import com.ctrip.framework.apollo.common.dto.ItemChangeSets;
import com.ctrip.framework.apollo.common.dto.ItemDTO;
import com.ctrip.framework.apollo.common.exception.NotFoundException;
import com.ctrip.framework.apollo.common.utils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
@Service
public class ItemSetService {
private final AuditService auditService;
private final CommitService commitService;
private final ItemService itemService;
public ItemSetService(
final AuditService auditService,
final CommitService commitService,
final ItemService itemService) {
this.auditService = auditService;
this.commitService = commitService;
this.itemService = itemService;
}
@Transactional
public ItemChangeSets updateSet(Namespace namespace, ItemChangeSets changeSets){
return updateSet(namespace.getAppId(), namespace.getClusterName(), namespace.getNamespaceName(), changeSets);
}
@Transactional
public ItemChangeSets updateSet(String appId, String clusterName,
String namespaceName, ItemChangeSets changeSet) {
String operator = changeSet.getDataChangeLastModifiedBy();
ConfigChangeContentBuilder configChangeContentBuilder = new ConfigChangeContentBuilder();
if (!CollectionUtils.isEmpty(changeSet.getCreateItems())) {
for (ItemDTO item : changeSet.getCreateItems()) {
Item entity = BeanUtils.transform(Item.class, item);
entity.setDataChangeCreatedBy(operator);
entity.setDataChangeLastModifiedBy(operator);
Item createdItem = itemService.save(entity);
configChangeContentBuilder.createItem(createdItem);
}
auditService.audit("ItemSet", null, Audit.OP.INSERT, operator);
}
if (!CollectionUtils.isEmpty(changeSet.getUpdateItems())) {
for (ItemDTO item : changeSet.getUpdateItems()) {
Item entity = BeanUtils.transform(Item.class, item);
Item managedItem = itemService.findOne(entity.getId());
if (managedItem == null) {
throw new NotFoundException(String.format("item not found.(key=%s)", entity.getKey()));
}
Item beforeUpdateItem = BeanUtils.transform(Item.class, managedItem);
//protect. only value,comment,lastModifiedBy,lineNum can be modified
managedItem.setValue(entity.getValue());
managedItem.setComment(entity.getComment());
managedItem.setLineNum(entity.getLineNum());
managedItem.setDataChangeLastModifiedBy(operator);
Item updatedItem = itemService.update(managedItem);
configChangeContentBuilder.updateItem(beforeUpdateItem, updatedItem);
}
auditService.audit("ItemSet", null, Audit.OP.UPDATE, operator);
}
if (!CollectionUtils.isEmpty(changeSet.getDeleteItems())) {
for (ItemDTO item : changeSet.getDeleteItems()) {
Item deletedItem = itemService.delete(item.getId(), operator);
configChangeContentBuilder.deleteItem(deletedItem);
}
auditService.audit("ItemSet", null, Audit.OP.DELETE, operator);
}
if (configChangeContentBuilder.hasContent()){
createCommit(appId, clusterName, namespaceName, configChangeContentBuilder.build(),
changeSet.getDataChangeLastModifiedBy());
}
return changeSet;
}
private void createCommit(String appId, String clusterName, String namespaceName, String configChangeContent,
String operator) {
Commit commit = new Commit();
commit.setAppId(appId);
commit.setClusterName(clusterName);
commit.setNamespaceName(namespaceName);
commit.setChangeSets(configChangeContent);
commit.setDataChangeCreatedBy(operator);
commit.setDataChangeLastModifiedBy(operator);
commitService.save(commit);
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/entity/AppNamespace.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.entity;
import com.ctrip.framework.apollo.common.utils.InputValidator;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "AppNamespace")
@SQLDelete(sql = "Update AppNamespace set isDeleted = 1 where id = ?")
@Where(clause = "isDeleted = 0")
public class AppNamespace extends BaseEntity {
@NotBlank(message = "AppNamespace Name cannot be blank")
@Pattern(
regexp = InputValidator.CLUSTER_NAMESPACE_VALIDATOR,
message = "Invalid Namespace format: " + InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE + " & " + InputValidator.INVALID_NAMESPACE_NAMESPACE_MESSAGE
)
@Column(name = "Name", nullable = false)
private String name;
@NotBlank(message = "AppId cannot be blank")
@Column(name = "AppId", nullable = false)
private String appId;
@Column(name = "Format", nullable = false)
private String format;
@Column(name = "IsPublic", columnDefinition = "Bit default '0'")
private boolean isPublic = false;
@Column(name = "Comment")
private String comment;
public String getAppId() {
return appId;
}
public String getComment() {
return comment;
}
public String getName() {
return name;
}
public void setAppId(String appId) {
this.appId = appId;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setName(String name) {
this.name = name;
}
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean aPublic) {
isPublic = aPublic;
}
public ConfigFileFormat formatAsEnum() {
return ConfigFileFormat.fromString(this.format);
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String toString() {
return toStringHelper().add("name", name).add("appId", appId).add("comment", comment)
.add("format", format).add("isPublic", isPublic).toString();
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.entity;
import com.ctrip.framework.apollo.common.utils.InputValidator;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "AppNamespace")
@SQLDelete(sql = "Update AppNamespace set isDeleted = 1 where id = ?")
@Where(clause = "isDeleted = 0")
public class AppNamespace extends BaseEntity {
@NotBlank(message = "AppNamespace Name cannot be blank")
@Pattern(
regexp = InputValidator.CLUSTER_NAMESPACE_VALIDATOR,
message = "Invalid Namespace format: " + InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE + " & " + InputValidator.INVALID_NAMESPACE_NAMESPACE_MESSAGE
)
@Column(name = "Name", nullable = false)
private String name;
@NotBlank(message = "AppId cannot be blank")
@Column(name = "AppId", nullable = false)
private String appId;
@Column(name = "Format", nullable = false)
private String format;
@Column(name = "IsPublic", columnDefinition = "Bit default '0'")
private boolean isPublic = false;
@Column(name = "Comment")
private String comment;
public String getAppId() {
return appId;
}
public String getComment() {
return comment;
}
public String getName() {
return name;
}
public void setAppId(String appId) {
this.appId = appId;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setName(String name) {
this.name = name;
}
public boolean isPublic() {
return isPublic;
}
public void setPublic(boolean aPublic) {
isPublic = aPublic;
}
public ConfigFileFormat formatAsEnum() {
return ConfigFileFormat.fromString(this.format);
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public String toString() {
return toStringHelper().add("name", name).add("appId", appId).add("comment", comment)
.add("format", format).add("isPublic", isPublic).toString();
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/exception/BadRequestException.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.exception;
import org.springframework.http.HttpStatus;
public class BadRequestException extends AbstractApolloHttpException {
public BadRequestException(String str) {
super(str);
setHttpStatus(HttpStatus.BAD_REQUEST);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.exception;
import org.springframework.http.HttpStatus;
public class BadRequestException extends AbstractApolloHttpException {
public BadRequestException(String str) {
super(str);
setHttpStatus(HttpStatus.BAD_REQUEST);
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-demo/src/main/resources/log4j2.xml | <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<configuration monitorInterval="60">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="[apollo-demo][%t]%d %-5p [%c] %m%n"/>
</Console>
<Async name="Async" includeLocation="true">
<AppenderRef ref="Console"/>
</Async>
</appenders>
<loggers>
<logger name="com.ctrip.framework.apollo" additivity="false" level="INFO">
<AppenderRef ref="Async"/>
</logger>
<logger name="com.ctrip.framework.apollo.demo" additivity="false" level="DEBUG">
<AppenderRef ref="Async"/>
</logger>
<root level="INFO">
<AppenderRef ref="Async"/>
</root>
</loggers>
</configuration>
| <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<configuration monitorInterval="60">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="[apollo-demo][%t]%d %-5p [%c] %m%n"/>
</Console>
<Async name="Async" includeLocation="true">
<AppenderRef ref="Console"/>
</Async>
</appenders>
<loggers>
<logger name="com.ctrip.framework.apollo" additivity="false" level="INFO">
<AppenderRef ref="Async"/>
</logger>
<logger name="com.ctrip.framework.apollo.demo" additivity="false" level="DEBUG">
<AppenderRef ref="Async"/>
</logger>
<root level="INFO">
<AppenderRef ref="Async"/>
</root>
</loggers>
</configuration>
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-configservice/src/test/java/com/ctrip/framework/apollo/configservice/controller/NotificationControllerTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.controller;
import com.ctrip.framework.apollo.biz.entity.ReleaseMessage;
import com.ctrip.framework.apollo.biz.message.Topics;
import com.ctrip.framework.apollo.biz.utils.EntityManagerUtil;
import com.ctrip.framework.apollo.configservice.service.ReleaseMessageServiceWithCache;
import com.ctrip.framework.apollo.configservice.util.NamespaceUtil;
import com.ctrip.framework.apollo.configservice.util.WatchKeysUtil;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification;
import com.google.common.base.Joiner;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.context.request.async.DeferredResult;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@RunWith(MockitoJUnitRunner.class)
public class NotificationControllerTest {
private NotificationController controller;
private String someAppId;
private String someCluster;
private String defaultNamespace;
private String someDataCenter;
private long someNotificationId;
private String someClientIp;
@Mock
private ReleaseMessageServiceWithCache releaseMessageService;
@Mock
private EntityManagerUtil entityManagerUtil;
@Mock
private NamespaceUtil namespaceUtil;
@Mock
private WatchKeysUtil watchKeysUtil;
private Multimap<String, DeferredResult<ResponseEntity<ApolloConfigNotification>>>
deferredResults;
@Before
public void setUp() throws Exception {
controller = new NotificationController(watchKeysUtil, releaseMessageService, entityManagerUtil, namespaceUtil);
someAppId = "someAppId";
someCluster = "someCluster";
defaultNamespace = ConfigConsts.NAMESPACE_APPLICATION;
someDataCenter = "someDC";
someNotificationId = 1;
someClientIp = "someClientIp";
when(namespaceUtil.filterNamespaceName(defaultNamespace)).thenReturn(defaultNamespace);
deferredResults =
(Multimap<String, DeferredResult<ResponseEntity<ApolloConfigNotification>>>) ReflectionTestUtils
.getField(controller, "deferredResults");
}
@Test
public void testPollNotificationWithDefaultNamespace() throws Exception {
String someWatchKey = "someKey";
String anotherWatchKey = "anotherKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey, anotherWatchKey);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, defaultNamespace,
someDataCenter)).thenReturn(
watchKeys);
DeferredResult<ResponseEntity<ApolloConfigNotification>>
deferredResult = controller
.pollNotification(someAppId, someCluster, defaultNamespace, someDataCenter,
someNotificationId, someClientIp);
assertEquals(watchKeys.size(), deferredResults.size());
for (String watchKey : watchKeys) {
assertTrue(deferredResults.get(watchKey).contains(deferredResult));
}
}
@Test
public void testPollNotificationWithDefaultNamespaceAsFile() throws Exception {
String namespace = String.format("%s.%s", defaultNamespace, "properties");
when(namespaceUtil.filterNamespaceName(namespace)).thenReturn(defaultNamespace);
String someWatchKey = "someKey";
String anotherWatchKey = "anotherKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey, anotherWatchKey);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, defaultNamespace,
someDataCenter)).thenReturn(
watchKeys);
DeferredResult<ResponseEntity<ApolloConfigNotification>>
deferredResult = controller
.pollNotification(someAppId, someCluster, namespace, someDataCenter,
someNotificationId, someClientIp);
assertEquals(watchKeys.size(), deferredResults.size());
for (String watchKey : watchKeys) {
assertTrue(deferredResults.get(watchKey).contains(deferredResult));
}
}
@Test
public void testPollNotificationWithSomeNamespaceAsFile() throws Exception {
String namespace = String.format("someNamespace.xml");
when(namespaceUtil.filterNamespaceName(namespace)).thenReturn(namespace);
String someWatchKey = "someKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, namespace, someDataCenter))
.thenReturn(
watchKeys);
DeferredResult<ResponseEntity<ApolloConfigNotification>>
deferredResult = controller
.pollNotification(someAppId, someCluster, namespace, someDataCenter,
someNotificationId, someClientIp);
assertEquals(watchKeys.size(), deferredResults.size());
for (String watchKey : watchKeys) {
assertTrue(deferredResults.get(watchKey).contains(deferredResult));
}
}
@Test
public void testPollNotificationWithDefaultNamespaceWithNotificationIdOutDated()
throws Exception {
long notificationId = someNotificationId + 1;
ReleaseMessage someReleaseMessage = mock(ReleaseMessage.class);
String someWatchKey = "someKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, defaultNamespace,
someDataCenter))
.thenReturn(
watchKeys);
when(someReleaseMessage.getId()).thenReturn(notificationId);
when(releaseMessageService.findLatestReleaseMessageForMessages(watchKeys))
.thenReturn(someReleaseMessage);
DeferredResult<ResponseEntity<ApolloConfigNotification>>
deferredResult = controller
.pollNotification(someAppId, someCluster, defaultNamespace, someDataCenter,
someNotificationId, someClientIp);
ResponseEntity<ApolloConfigNotification> result =
(ResponseEntity<ApolloConfigNotification>) deferredResult.getResult();
assertEquals(HttpStatus.OK, result.getStatusCode());
assertEquals(defaultNamespace, result.getBody().getNamespaceName());
assertEquals(notificationId, result.getBody().getNotificationId());
}
@Test
public void testPollNotificationWithDefaultNamespaceAndHandleMessage() throws Exception {
String someWatchKey = "someKey";
String anotherWatchKey = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR)
.join(someAppId, someCluster, defaultNamespace);
Set<String> watchKeys = Sets.newHashSet(someWatchKey, anotherWatchKey);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, defaultNamespace,
someDataCenter)).thenReturn(
watchKeys);
DeferredResult<ResponseEntity<ApolloConfigNotification>>
deferredResult = controller
.pollNotification(someAppId, someCluster, defaultNamespace, someDataCenter,
someNotificationId, someClientIp);
long someId = 1;
ReleaseMessage someReleaseMessage = new ReleaseMessage(anotherWatchKey);
someReleaseMessage.setId(someId);
controller.handleMessage(someReleaseMessage, Topics.APOLLO_RELEASE_TOPIC);
ResponseEntity<ApolloConfigNotification> response =
(ResponseEntity<ApolloConfigNotification>) deferredResult.getResult();
ApolloConfigNotification notification = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(defaultNamespace, notification.getNamespaceName());
assertEquals(someId, notification.getNotificationId());
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.controller;
import com.ctrip.framework.apollo.biz.entity.ReleaseMessage;
import com.ctrip.framework.apollo.biz.message.Topics;
import com.ctrip.framework.apollo.biz.utils.EntityManagerUtil;
import com.ctrip.framework.apollo.configservice.service.ReleaseMessageServiceWithCache;
import com.ctrip.framework.apollo.configservice.util.NamespaceUtil;
import com.ctrip.framework.apollo.configservice.util.WatchKeysUtil;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification;
import com.google.common.base.Joiner;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.context.request.async.DeferredResult;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@RunWith(MockitoJUnitRunner.class)
public class NotificationControllerTest {
private NotificationController controller;
private String someAppId;
private String someCluster;
private String defaultNamespace;
private String someDataCenter;
private long someNotificationId;
private String someClientIp;
@Mock
private ReleaseMessageServiceWithCache releaseMessageService;
@Mock
private EntityManagerUtil entityManagerUtil;
@Mock
private NamespaceUtil namespaceUtil;
@Mock
private WatchKeysUtil watchKeysUtil;
private Multimap<String, DeferredResult<ResponseEntity<ApolloConfigNotification>>>
deferredResults;
@Before
public void setUp() throws Exception {
controller = new NotificationController(watchKeysUtil, releaseMessageService, entityManagerUtil, namespaceUtil);
someAppId = "someAppId";
someCluster = "someCluster";
defaultNamespace = ConfigConsts.NAMESPACE_APPLICATION;
someDataCenter = "someDC";
someNotificationId = 1;
someClientIp = "someClientIp";
when(namespaceUtil.filterNamespaceName(defaultNamespace)).thenReturn(defaultNamespace);
deferredResults =
(Multimap<String, DeferredResult<ResponseEntity<ApolloConfigNotification>>>) ReflectionTestUtils
.getField(controller, "deferredResults");
}
@Test
public void testPollNotificationWithDefaultNamespace() throws Exception {
String someWatchKey = "someKey";
String anotherWatchKey = "anotherKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey, anotherWatchKey);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, defaultNamespace,
someDataCenter)).thenReturn(
watchKeys);
DeferredResult<ResponseEntity<ApolloConfigNotification>>
deferredResult = controller
.pollNotification(someAppId, someCluster, defaultNamespace, someDataCenter,
someNotificationId, someClientIp);
assertEquals(watchKeys.size(), deferredResults.size());
for (String watchKey : watchKeys) {
assertTrue(deferredResults.get(watchKey).contains(deferredResult));
}
}
@Test
public void testPollNotificationWithDefaultNamespaceAsFile() throws Exception {
String namespace = String.format("%s.%s", defaultNamespace, "properties");
when(namespaceUtil.filterNamespaceName(namespace)).thenReturn(defaultNamespace);
String someWatchKey = "someKey";
String anotherWatchKey = "anotherKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey, anotherWatchKey);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, defaultNamespace,
someDataCenter)).thenReturn(
watchKeys);
DeferredResult<ResponseEntity<ApolloConfigNotification>>
deferredResult = controller
.pollNotification(someAppId, someCluster, namespace, someDataCenter,
someNotificationId, someClientIp);
assertEquals(watchKeys.size(), deferredResults.size());
for (String watchKey : watchKeys) {
assertTrue(deferredResults.get(watchKey).contains(deferredResult));
}
}
@Test
public void testPollNotificationWithSomeNamespaceAsFile() throws Exception {
String namespace = String.format("someNamespace.xml");
when(namespaceUtil.filterNamespaceName(namespace)).thenReturn(namespace);
String someWatchKey = "someKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, namespace, someDataCenter))
.thenReturn(
watchKeys);
DeferredResult<ResponseEntity<ApolloConfigNotification>>
deferredResult = controller
.pollNotification(someAppId, someCluster, namespace, someDataCenter,
someNotificationId, someClientIp);
assertEquals(watchKeys.size(), deferredResults.size());
for (String watchKey : watchKeys) {
assertTrue(deferredResults.get(watchKey).contains(deferredResult));
}
}
@Test
public void testPollNotificationWithDefaultNamespaceWithNotificationIdOutDated()
throws Exception {
long notificationId = someNotificationId + 1;
ReleaseMessage someReleaseMessage = mock(ReleaseMessage.class);
String someWatchKey = "someKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, defaultNamespace,
someDataCenter))
.thenReturn(
watchKeys);
when(someReleaseMessage.getId()).thenReturn(notificationId);
when(releaseMessageService.findLatestReleaseMessageForMessages(watchKeys))
.thenReturn(someReleaseMessage);
DeferredResult<ResponseEntity<ApolloConfigNotification>>
deferredResult = controller
.pollNotification(someAppId, someCluster, defaultNamespace, someDataCenter,
someNotificationId, someClientIp);
ResponseEntity<ApolloConfigNotification> result =
(ResponseEntity<ApolloConfigNotification>) deferredResult.getResult();
assertEquals(HttpStatus.OK, result.getStatusCode());
assertEquals(defaultNamespace, result.getBody().getNamespaceName());
assertEquals(notificationId, result.getBody().getNotificationId());
}
@Test
public void testPollNotificationWithDefaultNamespaceAndHandleMessage() throws Exception {
String someWatchKey = "someKey";
String anotherWatchKey = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR)
.join(someAppId, someCluster, defaultNamespace);
Set<String> watchKeys = Sets.newHashSet(someWatchKey, anotherWatchKey);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someCluster, defaultNamespace,
someDataCenter)).thenReturn(
watchKeys);
DeferredResult<ResponseEntity<ApolloConfigNotification>>
deferredResult = controller
.pollNotification(someAppId, someCluster, defaultNamespace, someDataCenter,
someNotificationId, someClientIp);
long someId = 1;
ReleaseMessage someReleaseMessage = new ReleaseMessage(anotherWatchKey);
someReleaseMessage.setId(someId);
controller.handleMessage(someReleaseMessage, Topics.APOLLO_RELEASE_TOPIC);
ResponseEntity<ApolloConfigNotification> response =
(ResponseEntity<ApolloConfigNotification>) deferredResult.getResult();
ApolloConfigNotification notification = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(defaultNamespace, notification.getNamespaceName());
assertEquals(someId, notification.getNotificationId());
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-adminservice/src/main/java/com/ctrip/framework/apollo/adminservice/controller/ClusterController.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.adminservice.controller;
import com.ctrip.framework.apollo.biz.entity.Cluster;
import com.ctrip.framework.apollo.biz.service.ClusterService;
import com.ctrip.framework.apollo.common.dto.ClusterDTO;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.common.exception.NotFoundException;
import com.ctrip.framework.apollo.common.utils.BeanUtils;
import com.ctrip.framework.apollo.core.ConfigConsts;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;
@RestController
public class ClusterController {
private final ClusterService clusterService;
public ClusterController(final ClusterService clusterService) {
this.clusterService = clusterService;
}
@PostMapping("/apps/{appId}/clusters")
public ClusterDTO create(@PathVariable("appId") String appId,
@RequestParam(value = "autoCreatePrivateNamespace", defaultValue = "true") boolean autoCreatePrivateNamespace,
@Valid @RequestBody ClusterDTO dto) {
Cluster entity = BeanUtils.transform(Cluster.class, dto);
Cluster managedEntity = clusterService.findOne(appId, entity.getName());
if (managedEntity != null) {
throw new BadRequestException("cluster already exist.");
}
if (autoCreatePrivateNamespace) {
entity = clusterService.saveWithInstanceOfAppNamespaces(entity);
} else {
entity = clusterService.saveWithoutInstanceOfAppNamespaces(entity);
}
return BeanUtils.transform(ClusterDTO.class, entity);
}
@DeleteMapping("/apps/{appId}/clusters/{clusterName:.+}")
public void delete(@PathVariable("appId") String appId,
@PathVariable("clusterName") String clusterName, @RequestParam String operator) {
Cluster entity = clusterService.findOne(appId, clusterName);
if (entity == null) {
throw new NotFoundException("cluster not found for clusterName " + clusterName);
}
if(ConfigConsts.CLUSTER_NAME_DEFAULT.equals(entity.getName())){
throw new BadRequestException("can not delete default cluster!");
}
clusterService.delete(entity.getId(), operator);
}
@GetMapping("/apps/{appId}/clusters")
public List<ClusterDTO> find(@PathVariable("appId") String appId) {
List<Cluster> clusters = clusterService.findParentClusters(appId);
return BeanUtils.batchTransform(ClusterDTO.class, clusters);
}
@GetMapping("/apps/{appId}/clusters/{clusterName:.+}")
public ClusterDTO get(@PathVariable("appId") String appId,
@PathVariable("clusterName") String clusterName) {
Cluster cluster = clusterService.findOne(appId, clusterName);
if (cluster == null) {
throw new NotFoundException("cluster not found for name " + clusterName);
}
return BeanUtils.transform(ClusterDTO.class, cluster);
}
@GetMapping("/apps/{appId}/cluster/{clusterName}/unique")
public boolean isAppIdUnique(@PathVariable("appId") String appId,
@PathVariable("clusterName") String clusterName) {
return clusterService.isClusterNameUnique(appId, clusterName);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.adminservice.controller;
import com.ctrip.framework.apollo.biz.entity.Cluster;
import com.ctrip.framework.apollo.biz.service.ClusterService;
import com.ctrip.framework.apollo.common.dto.ClusterDTO;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.common.exception.NotFoundException;
import com.ctrip.framework.apollo.common.utils.BeanUtils;
import com.ctrip.framework.apollo.core.ConfigConsts;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;
@RestController
public class ClusterController {
private final ClusterService clusterService;
public ClusterController(final ClusterService clusterService) {
this.clusterService = clusterService;
}
@PostMapping("/apps/{appId}/clusters")
public ClusterDTO create(@PathVariable("appId") String appId,
@RequestParam(value = "autoCreatePrivateNamespace", defaultValue = "true") boolean autoCreatePrivateNamespace,
@Valid @RequestBody ClusterDTO dto) {
Cluster entity = BeanUtils.transform(Cluster.class, dto);
Cluster managedEntity = clusterService.findOne(appId, entity.getName());
if (managedEntity != null) {
throw new BadRequestException("cluster already exist.");
}
if (autoCreatePrivateNamespace) {
entity = clusterService.saveWithInstanceOfAppNamespaces(entity);
} else {
entity = clusterService.saveWithoutInstanceOfAppNamespaces(entity);
}
return BeanUtils.transform(ClusterDTO.class, entity);
}
@DeleteMapping("/apps/{appId}/clusters/{clusterName:.+}")
public void delete(@PathVariable("appId") String appId,
@PathVariable("clusterName") String clusterName, @RequestParam String operator) {
Cluster entity = clusterService.findOne(appId, clusterName);
if (entity == null) {
throw new NotFoundException("cluster not found for clusterName " + clusterName);
}
if(ConfigConsts.CLUSTER_NAME_DEFAULT.equals(entity.getName())){
throw new BadRequestException("can not delete default cluster!");
}
clusterService.delete(entity.getId(), operator);
}
@GetMapping("/apps/{appId}/clusters")
public List<ClusterDTO> find(@PathVariable("appId") String appId) {
List<Cluster> clusters = clusterService.findParentClusters(appId);
return BeanUtils.batchTransform(ClusterDTO.class, clusters);
}
@GetMapping("/apps/{appId}/clusters/{clusterName:.+}")
public ClusterDTO get(@PathVariable("appId") String appId,
@PathVariable("clusterName") String clusterName) {
Cluster cluster = clusterService.findOne(appId, clusterName);
if (cluster == null) {
throw new NotFoundException("cluster not found for name " + clusterName);
}
return BeanUtils.transform(ClusterDTO.class, cluster);
}
@GetMapping("/apps/{appId}/cluster/{clusterName}/unique")
public boolean isAppIdUnique(@PathVariable("appId") String appId,
@PathVariable("clusterName") String clusterName) {
return clusterService.isClusterNameUnique(appId, clusterName);
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/condition/ConditionalOnMissingProfile.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.condition;
import org.springframework.context.annotation.Conditional;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* {@link Conditional} that only matches when the specified profiles are inactive.
*
* @author Jason Song(song_s@ctrip.com)
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnProfileCondition.class)
public @interface ConditionalOnMissingProfile {
/**
* The profiles that should be inactive
* @return
*/
String[] value() default {};
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.condition;
import org.springframework.context.annotation.Conditional;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* {@link Conditional} that only matches when the specified profiles are inactive.
*
* @author Jason Song(song_s@ctrip.com)
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnProfileCondition.class)
public @interface ConditionalOnMissingProfile {
/**
* The profiles that should be inactive
* @return
*/
String[] value() default {};
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/SpringValueProcessor.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.annotation;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.spring.property.PlaceholderHelper;
import com.ctrip.framework.apollo.spring.property.SpringValue;
import com.ctrip.framework.apollo.spring.property.SpringValueDefinition;
import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor;
import com.ctrip.framework.apollo.spring.property.SpringValueRegistry;
import com.ctrip.framework.apollo.spring.util.SpringInjector;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.Bean;
/**
* Spring value processor of field or method which has @Value and xml config placeholders.
*
* @author github.com/zhegexiaohuozi seimimaster@gmail.com
* @since 2017/12/20.
*/
public class SpringValueProcessor extends ApolloProcessor implements BeanFactoryPostProcessor, BeanFactoryAware {
private static final Logger logger = LoggerFactory.getLogger(SpringValueProcessor.class);
private final ConfigUtil configUtil;
private final PlaceholderHelper placeholderHelper;
private final SpringValueRegistry springValueRegistry;
private BeanFactory beanFactory;
private Multimap<String, SpringValueDefinition> beanName2SpringValueDefinitions;
public SpringValueProcessor() {
configUtil = ApolloInjector.getInstance(ConfigUtil.class);
placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class);
springValueRegistry = SpringInjector.getInstance(SpringValueRegistry.class);
beanName2SpringValueDefinitions = LinkedListMultimap.create();
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled() && beanFactory instanceof BeanDefinitionRegistry) {
beanName2SpringValueDefinitions = SpringValueDefinitionProcessor
.getBeanName2SpringValueDefinitions((BeanDefinitionRegistry) beanFactory);
}
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) {
super.postProcessBeforeInitialization(bean, beanName);
processBeanPropertyValues(bean, beanName);
}
return bean;
}
@Override
protected void processField(Object bean, String beanName, Field field) {
// register @Value on field
Value value = field.getAnnotation(Value.class);
if (value == null) {
return;
}
Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value());
if (keys.isEmpty()) {
return;
}
for (String key : keys) {
SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, field, false);
springValueRegistry.register(beanFactory, key, springValue);
logger.debug("Monitoring {}", springValue);
}
}
@Override
protected void processMethod(Object bean, String beanName, Method method) {
//register @Value on method
Value value = method.getAnnotation(Value.class);
if (value == null) {
return;
}
//skip Configuration bean methods
if (method.getAnnotation(Bean.class) != null) {
return;
}
if (method.getParameterTypes().length != 1) {
logger.error("Ignore @Value setter {}.{}, expecting 1 parameter, actual {} parameters",
bean.getClass().getName(), method.getName(), method.getParameterTypes().length);
return;
}
Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value());
if (keys.isEmpty()) {
return;
}
for (String key : keys) {
SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, method, false);
springValueRegistry.register(beanFactory, key, springValue);
logger.info("Monitoring {}", springValue);
}
}
private void processBeanPropertyValues(Object bean, String beanName) {
Collection<SpringValueDefinition> propertySpringValues = beanName2SpringValueDefinitions
.get(beanName);
if (propertySpringValues == null || propertySpringValues.isEmpty()) {
return;
}
for (SpringValueDefinition definition : propertySpringValues) {
try {
PropertyDescriptor pd = BeanUtils
.getPropertyDescriptor(bean.getClass(), definition.getPropertyName());
Method method = pd.getWriteMethod();
if (method == null) {
continue;
}
SpringValue springValue = new SpringValue(definition.getKey(), definition.getPlaceholder(),
bean, beanName, method, false);
springValueRegistry.register(beanFactory, definition.getKey(), springValue);
logger.debug("Monitoring {}", springValue);
} catch (Throwable ex) {
logger.error("Failed to enable auto update feature for {}.{}", bean.getClass(),
definition.getPropertyName());
}
}
// clear
beanName2SpringValueDefinitions.removeAll(beanName);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.annotation;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.spring.property.PlaceholderHelper;
import com.ctrip.framework.apollo.spring.property.SpringValue;
import com.ctrip.framework.apollo.spring.property.SpringValueDefinition;
import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor;
import com.ctrip.framework.apollo.spring.property.SpringValueRegistry;
import com.ctrip.framework.apollo.spring.util.SpringInjector;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.Multimap;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.Bean;
/**
* Spring value processor of field or method which has @Value and xml config placeholders.
*
* @author github.com/zhegexiaohuozi seimimaster@gmail.com
* @since 2017/12/20.
*/
public class SpringValueProcessor extends ApolloProcessor implements BeanFactoryPostProcessor, BeanFactoryAware {
private static final Logger logger = LoggerFactory.getLogger(SpringValueProcessor.class);
private final ConfigUtil configUtil;
private final PlaceholderHelper placeholderHelper;
private final SpringValueRegistry springValueRegistry;
private BeanFactory beanFactory;
private Multimap<String, SpringValueDefinition> beanName2SpringValueDefinitions;
public SpringValueProcessor() {
configUtil = ApolloInjector.getInstance(ConfigUtil.class);
placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class);
springValueRegistry = SpringInjector.getInstance(SpringValueRegistry.class);
beanName2SpringValueDefinitions = LinkedListMultimap.create();
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled() && beanFactory instanceof BeanDefinitionRegistry) {
beanName2SpringValueDefinitions = SpringValueDefinitionProcessor
.getBeanName2SpringValueDefinitions((BeanDefinitionRegistry) beanFactory);
}
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) {
super.postProcessBeforeInitialization(bean, beanName);
processBeanPropertyValues(bean, beanName);
}
return bean;
}
@Override
protected void processField(Object bean, String beanName, Field field) {
// register @Value on field
Value value = field.getAnnotation(Value.class);
if (value == null) {
return;
}
Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value());
if (keys.isEmpty()) {
return;
}
for (String key : keys) {
SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, field, false);
springValueRegistry.register(beanFactory, key, springValue);
logger.debug("Monitoring {}", springValue);
}
}
@Override
protected void processMethod(Object bean, String beanName, Method method) {
//register @Value on method
Value value = method.getAnnotation(Value.class);
if (value == null) {
return;
}
//skip Configuration bean methods
if (method.getAnnotation(Bean.class) != null) {
return;
}
if (method.getParameterTypes().length != 1) {
logger.error("Ignore @Value setter {}.{}, expecting 1 parameter, actual {} parameters",
bean.getClass().getName(), method.getName(), method.getParameterTypes().length);
return;
}
Set<String> keys = placeholderHelper.extractPlaceholderKeys(value.value());
if (keys.isEmpty()) {
return;
}
for (String key : keys) {
SpringValue springValue = new SpringValue(key, value.value(), bean, beanName, method, false);
springValueRegistry.register(beanFactory, key, springValue);
logger.info("Monitoring {}", springValue);
}
}
private void processBeanPropertyValues(Object bean, String beanName) {
Collection<SpringValueDefinition> propertySpringValues = beanName2SpringValueDefinitions
.get(beanName);
if (propertySpringValues == null || propertySpringValues.isEmpty()) {
return;
}
for (SpringValueDefinition definition : propertySpringValues) {
try {
PropertyDescriptor pd = BeanUtils
.getPropertyDescriptor(bean.getClass(), definition.getPropertyName());
Method method = pd.getWriteMethod();
if (method == null) {
continue;
}
SpringValue springValue = new SpringValue(definition.getKey(), definition.getPlaceholder(),
bean, beanName, method, false);
springValueRegistry.register(beanFactory, definition.getKey(), springValue);
logger.debug("Monitoring {}", springValue);
} catch (Throwable ex) {
logger.error("Failed to enable auto update feature for {}.{}", bean.getClass(),
definition.getPropertyName());
}
}
// clear
beanName2SpringValueDefinitions.removeAll(beanName);
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/dto/NamespaceLockDTO.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.dto;
public class NamespaceLockDTO extends BaseDTO{
private long namespaceId;
public long getNamespaceId() {
return namespaceId;
}
public void setNamespaceId(long namespaceId) {
this.namespaceId = namespaceId;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.dto;
public class NamespaceLockDTO extends BaseDTO{
private long namespaceId;
public long getNamespaceId() {
return namespaceId;
}
public void setNamespaceId(long namespaceId) {
this.namespaceId = namespaceId;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/AccessKeyService.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.service;
import com.ctrip.framework.apollo.common.dto.AccessKeyDTO;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI.AccessKeyAPI;
import com.ctrip.framework.apollo.portal.constant.TracerEventType;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.tracer.Tracer;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccessKeyService {
private final AdminServiceAPI.AccessKeyAPI accessKeyAPI;
public AccessKeyService(AccessKeyAPI accessKeyAPI) {
this.accessKeyAPI = accessKeyAPI;
}
public List<AccessKeyDTO> findByAppId(Env env, String appId) {
return accessKeyAPI.findByAppId(env, appId);
}
public AccessKeyDTO createAccessKey(Env env, AccessKeyDTO accessKey) {
AccessKeyDTO accessKeyDTO = accessKeyAPI.create(env, accessKey);
Tracer.logEvent(TracerEventType.CREATE_ACCESS_KEY, accessKey.getAppId());
return accessKeyDTO;
}
public void deleteAccessKey(Env env, String appId, long id, String operator) {
accessKeyAPI.delete(env, appId, id, operator);
}
public void enable(Env env, String appId, long id, String operator) {
accessKeyAPI.enable(env, appId, id, operator);
}
public void disable(Env env, String appId, long id, String operator) {
accessKeyAPI.disable(env, appId, id, operator);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.service;
import com.ctrip.framework.apollo.common.dto.AccessKeyDTO;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI.AccessKeyAPI;
import com.ctrip.framework.apollo.portal.constant.TracerEventType;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.tracer.Tracer;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class AccessKeyService {
private final AdminServiceAPI.AccessKeyAPI accessKeyAPI;
public AccessKeyService(AccessKeyAPI accessKeyAPI) {
this.accessKeyAPI = accessKeyAPI;
}
public List<AccessKeyDTO> findByAppId(Env env, String appId) {
return accessKeyAPI.findByAppId(env, appId);
}
public AccessKeyDTO createAccessKey(Env env, AccessKeyDTO accessKey) {
AccessKeyDTO accessKeyDTO = accessKeyAPI.create(env, accessKey);
Tracer.logEvent(TracerEventType.CREATE_ACCESS_KEY, accessKey.getAppId());
return accessKeyDTO;
}
public void deleteAccessKey(Env env, String appId, long id, String operator) {
accessKeyAPI.delete(env, appId, id, operator);
}
public void enable(Env env, String appId, long id, String operator) {
accessKeyAPI.enable(env, appId, id, operator);
}
public void disable(Env env, String appId, long id, String operator) {
accessKeyAPI.disable(env, appId, id, operator);
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/ConfigsExportController.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.common.exception.ServiceException;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.portal.entity.bo.NamespaceBO;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.service.ConfigsExportService;
import com.ctrip.framework.apollo.portal.service.NamespaceService;
import com.ctrip.framework.apollo.portal.util.NamespaceBOUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* jian.tan
*/
@RestController
public class ConfigsExportController {
private static final Logger logger = LoggerFactory.getLogger(ConfigsExportController.class);
private final ConfigsExportService configsExportService;
private final NamespaceService namespaceService;
public ConfigsExportController(
final ConfigsExportService configsExportService,
final @Lazy NamespaceService namespaceService
) {
this.configsExportService = configsExportService;
this.namespaceService = namespaceService;
}
/**
* export one config as file.
* keep compatibility.
* file name examples:
* <pre>
* application.properties
* application.yml
* application.json
* </pre>
*/
@PreAuthorize(value = "!@permissionValidator.shouldHideConfigToCurrentUser(#appId, #env, #namespaceName)")
@GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/items/export")
public void exportItems(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName, @PathVariable String namespaceName,
HttpServletResponse res) {
List<String> fileNameSplit = Splitter.on(".").splitToList(namespaceName);
String fileName = fileNameSplit.size() <= 1 ? Joiner.on(".")
.join(namespaceName, ConfigFileFormat.Properties.getValue()) : namespaceName;
NamespaceBO namespaceBO = namespaceService.loadNamespaceBO(appId, Env.valueOf
(env), clusterName, namespaceName);
//generate a file.
res.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
// file content
final String configFileContent = NamespaceBOUtils.convert2configFileContent(namespaceBO);
try {
// write content to net
res.getOutputStream().write(configFileContent.getBytes());
} catch (Exception e) {
throw new ServiceException("export items failed:{}", e);
}
}
/**
* Export all configs in a compressed file.
* Just export namespace which current exists read permission.
* The permission check in service.
*/
@GetMapping("/export")
public void exportAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
// filename must contain the information of time
final String filename = "apollo_config_export_" + DateFormatUtils.format(new Date(), "yyyy_MMdd_HH_mm_ss") + ".zip";
// log who download the configs
logger.info("Download configs, remote addr [{}], remote host [{}]. Filename is [{}]", request.getRemoteAddr(), request.getRemoteHost(), filename);
// set downloaded filename
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename);
try (OutputStream outputStream = response.getOutputStream()) {
configsExportService.exportAllTo(outputStream);
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.common.exception.ServiceException;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.portal.entity.bo.NamespaceBO;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.service.ConfigsExportService;
import com.ctrip.framework.apollo.portal.service.NamespaceService;
import com.ctrip.framework.apollo.portal.util.NamespaceBOUtils;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* jian.tan
*/
@RestController
public class ConfigsExportController {
private static final Logger logger = LoggerFactory.getLogger(ConfigsExportController.class);
private final ConfigsExportService configsExportService;
private final NamespaceService namespaceService;
public ConfigsExportController(
final ConfigsExportService configsExportService,
final @Lazy NamespaceService namespaceService
) {
this.configsExportService = configsExportService;
this.namespaceService = namespaceService;
}
/**
* export one config as file.
* keep compatibility.
* file name examples:
* <pre>
* application.properties
* application.yml
* application.json
* </pre>
*/
@PreAuthorize(value = "!@permissionValidator.shouldHideConfigToCurrentUser(#appId, #env, #namespaceName)")
@GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/items/export")
public void exportItems(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName, @PathVariable String namespaceName,
HttpServletResponse res) {
List<String> fileNameSplit = Splitter.on(".").splitToList(namespaceName);
String fileName = fileNameSplit.size() <= 1 ? Joiner.on(".")
.join(namespaceName, ConfigFileFormat.Properties.getValue()) : namespaceName;
NamespaceBO namespaceBO = namespaceService.loadNamespaceBO(appId, Env.valueOf
(env), clusterName, namespaceName);
//generate a file.
res.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
// file content
final String configFileContent = NamespaceBOUtils.convert2configFileContent(namespaceBO);
try {
// write content to net
res.getOutputStream().write(configFileContent.getBytes());
} catch (Exception e) {
throw new ServiceException("export items failed:{}", e);
}
}
/**
* Export all configs in a compressed file.
* Just export namespace which current exists read permission.
* The permission check in service.
*/
@GetMapping("/export")
public void exportAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
// filename must contain the information of time
final String filename = "apollo_config_export_" + DateFormatUtils.format(new Date(), "yyyy_MMdd_HH_mm_ss") + ".zip";
// log who download the configs
logger.info("Download configs, remote addr [{}], remote host [{}]. Filename is [{}]", request.getRemoteAddr(), request.getRemoteHost(), filename);
// set downloaded filename
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename);
try (OutputStream outputStream = response.getOutputStream()) {
configsExportService.exportAllTo(outputStream);
}
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ClassLoaderUtil.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.core.utils;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URL;
import java.net.URLDecoder;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class ClassLoaderUtil {
private static final Logger logger = LoggerFactory.getLogger(ClassLoaderUtil.class);
private static ClassLoader loader = Thread.currentThread().getContextClassLoader();
private static String classPath = "";
static {
if (loader == null) {
logger.warn("Using system class loader");
loader = ClassLoader.getSystemClassLoader();
}
try {
URL url = loader.getResource("");
// get class path
if (url != null) {
classPath = url.getPath();
classPath = URLDecoder.decode(classPath, "utf-8");
}
// 如果是jar包内的,则返回当前路径
if (Strings.isNullOrEmpty(classPath) || classPath.contains(".jar!")) {
classPath = System.getProperty("user.dir");
}
} catch (Throwable ex) {
classPath = System.getProperty("user.dir");
logger.warn("Failed to locate class path, fallback to user.dir: {}", classPath, ex);
}
}
public static ClassLoader getLoader() {
return loader;
}
public static String getClassPath() {
return classPath;
}
public static boolean isClassPresent(String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException ex) {
return false;
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.core.utils;
import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URL;
import java.net.URLDecoder;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class ClassLoaderUtil {
private static final Logger logger = LoggerFactory.getLogger(ClassLoaderUtil.class);
private static ClassLoader loader = Thread.currentThread().getContextClassLoader();
private static String classPath = "";
static {
if (loader == null) {
logger.warn("Using system class loader");
loader = ClassLoader.getSystemClassLoader();
}
try {
URL url = loader.getResource("");
// get class path
if (url != null) {
classPath = url.getPath();
classPath = URLDecoder.decode(classPath, "utf-8");
}
// 如果是jar包内的,则返回当前路径
if (Strings.isNullOrEmpty(classPath) || classPath.contains(".jar!")) {
classPath = System.getProperty("user.dir");
}
} catch (Throwable ex) {
classPath = System.getProperty("user.dir");
logger.warn("Failed to locate class path, fallback to user.dir: {}", classPath, ex);
}
}
public static ClassLoader getLoader() {
return loader;
}
public static String getClassPath() {
return classPath;
}
public static boolean isClassPresent(String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException ex) {
return false;
}
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./docs/zh/deployment/distributed-deployment-guide.md | 本文档介绍了如何按照分布式部署的方式编译、打包、部署Apollo配置中心,从而可以在开发、测试、生产等环境分别部署运行。
> 如果只是需要在本地快速部署试用Apollo的话,可以参考[Quick Start](zh/deployment/quick-start)
#
# 一、准备工作
## 1.1 运行时环境
### 1.1.1 OS
服务端基于Spring Boot,启动脚本理论上支持所有Linux发行版,建议[CentOS 7](https://www.centos.org/)。
### 1.1.2 Java
* Apollo服务端:1.8+
* Apollo客户端:1.7+
由于需要同时运行服务端和客户端,所以建议安装Java 1.8+。
>对于Apollo客户端,运行时环境只需要1.7+即可。
>注:对于Apollo客户端,如果有需要的话,可以做少量代码修改来降级到Java 1.6,详细信息可以参考[Issue 483](https://github.com/ctripcorp/apollo/issues/483)
在配置好后,可以通过如下命令检查:
```sh
java -version
```
样例输出:
```sh
java version "1.8.0_74"
Java(TM) SE Runtime Environment (build 1.8.0_74-b02)
Java HotSpot(TM) 64-Bit Server VM (build 25.74-b02, mixed mode)
```
## 1.2 MySQL
* 版本要求:5.6.5+
Apollo的表结构对`timestamp`使用了多个default声明,所以需要5.6.5以上版本。
连接上MySQL后,可以通过如下命令检查:
```sql
SHOW VARIABLES WHERE Variable_name = 'version';
```
| Variable_name | Value |
|---------------|--------|
| version | 5.7.11 |
> 注1:MySQL版本可以降级到5.5,详见[mysql 依赖降级讨论](https://github.com/ctripcorp/apollo/issues/481)。
> 注2:如果希望使用Oracle的话,可以参考[vanpersl](https://github.com/vanpersl)在Apollo 0.8.0基础上开发的[Oracle适配代码](https://github.com/ctripcorp/apollo/compare/v0.8.0...vanpersl:db-oracle),Oracle版本为10.2.0.1.0。
> 注3:如果希望使用Postgres的话,可以参考[oaksharks](https://github.com/oaksharks)在Apollo 0.9.1基础上开发的[Pg适配代码](https://github.com/oaksharks/apollo/compare/ac10768ee2e11c488523ca0e845984f6f71499ac...oaksharks:pg),Postgres的版本为9.3.20,也可以参考[xiao0yy](https://github.com/xiao0yy)在Apollo 0.10.2基础上开发的[Pg适配代码](https://github.com/ctripcorp/apollo/issues/1293),Postgres的版本为9.5。
## 1.3 环境
分布式部署需要事先确定部署的环境以及部署方式。
Apollo目前支持以下环境:
* DEV
* 开发环境
* FAT
* 测试环境,相当于alpha环境(功能测试)
* UAT
* 集成环境,相当于beta环境(回归测试)
* PRO
* 生产环境
> 如果希望添加自定义的环境名称,具体步骤可以参考[Portal如何增加环境](zh/faq/common-issues-in-deployment-and-development-phase?id=_4-portal如何增加环境?)
以ctrip为例,我们的部署策略如下:

* Portal部署在生产环境的机房,通过它来直接管理FAT、UAT、PRO等环境的配置
* Meta Server、Config Service和Admin Service在每个环境都单独部署,使用独立的数据库
* Meta Server、Config Service和Admin Service在生产环境部署在两个机房,实现双活
* Meta Server和Config Service部署在同一个JVM进程内,Admin Service部署在同一台服务器的另一个JVM进程内
另外也可以参考下[@lyliyongblue](https://github.com/lyliyongblue) 贡献的样例部署图(建议右键新窗口打开看大图):

## 1.4 网络策略
分布式部署的时候,`apollo-configservice`和`apollo-adminservice`需要把自己的IP和端口注册到Meta Server(apollo-configservice本身)。
Apollo客户端和Portal会从Meta Server获取服务的地址(IP+端口),然后通过服务地址直接访问。
需要注意的是,`apollo-configservice`和`apollo-adminservice`是基于内网可信网络设计的,所以出于安全考虑,**请不要将`apollo-configservice`和`apollo-adminservice`直接暴露在公网**。
所以如果实际部署的机器有多块网卡(如docker),或者存在某些网卡的IP是Apollo客户端和Portal无法访问的(如网络安全限制),那么我们就需要在`apollo-configservice`和`apollo-adminservice`中做相关配置来解决连通性问题。
### 1.4.1 忽略某些网卡
可以分别修改`apollo-configservice`和`apollo-adminservice`的startup.sh,通过JVM System Property传入-D参数,也可以通过OS Environment Variable传入,下面的例子会把`docker0`和`veth`开头的网卡在注册到Eureka时忽略掉。
JVM System Property示例:
```properties
-Dspring.cloud.inetutils.ignoredInterfaces[0]=docker0
-Dspring.cloud.inetutils.ignoredInterfaces[1]=veth.*
```
OS Environment Variable示例:
```properties
SPRING_CLOUD_INETUTILS_IGNORED_INTERFACES[0]=docker0
SPRING_CLOUD_INETUTILS_IGNORED_INTERFACES[1]=veth.*
```
### 1.4.2 指定要注册的IP
可以分别修改`apollo-configservice`和`apollo-adminservice`的startup.sh,通过JVM System Property传入-D参数,也可以通过OS Environment Variable传入,下面的例子会指定注册的IP为`1.2.3.4`。
JVM System Property示例:
```properties
-Deureka.instance.ip-address=1.2.3.4
```
OS Environment Variable示例:
```properties
EUREKA_INSTANCE_IP_ADDRESS=1.2.3.4
```
### 1.4.3 指定要注册的URL
可以分别修改`apollo-configservice`和`apollo-adminservice`的startup.sh,通过JVM System Property传入-D参数,也可以通过OS Environment Variable传入,下面的例子会指定注册的URL为`http://1.2.3.4:8080`。
JVM System Property示例:
```properties
-Deureka.instance.homePageUrl=http://1.2.3.4:8080
-Deureka.instance.preferIpAddress=false
```
OS Environment Variable示例:
```properties
EUREKA_INSTANCE_HOME_PAGE_URL=http://1.2.3.4:8080
EUREKA_INSTANCE_PREFER_IP_ADDRESS=false
```
### 1.4.4 直接指定apollo-configservice地址
如果Apollo部署在公有云上,本地开发环境无法连接,但又需要做开发测试的话,客户端可以升级到0.11.0版本及以上,然后配置[跳过Apollo Meta Server服务发现](zh/usage/java-sdk-user-guide#_1222-跳过apollo-meta-server服务发现)
# 二、部署步骤
部署步骤总体还是比较简单的,Apollo的唯一依赖是数据库,所以需要首先把数据库准备好,然后根据实际情况,选择不同的部署方式:
> [@lingjiaju](https://github.com/lingjiaju)录制了一系列Apollo快速上手视频,如果看文档觉得略繁琐的话,不妨可以先看一下他的[视频教程](https://pan.baidu.com/s/1blv87EOZS77NWT8Amkijkw#list/path=%2F)。
> 如果部署过程中遇到了问题,可以参考[部署&开发遇到的常见问题](zh/faq/common-issues-in-deployment-and-development-phase),一般都能找到答案。
## 2.1 创建数据库
Apollo服务端共需要两个数据库:`ApolloPortalDB`和`ApolloConfigDB`,我们把数据库、表的创建和样例数据都分别准备了sql文件,只需要导入数据库即可。
需要注意的是ApolloPortalDB只需要在生产环境部署一个即可,而ApolloConfigDB需要在每个环境部署一套,如fat、uat和pro分别部署3套ApolloConfigDB。
> 注意:如果你本地已经创建过Apollo数据库,请注意备份数据。我们准备的sql文件会清空Apollo相关的表。
### 2.1.1 创建ApolloPortalDB
可以根据实际情况选择通过手动导入SQL或是通过[Flyway](https://flywaydb.org/)自动导入SQL创建。
#### 2.1.1.1 手动导入SQL创建
通过各种MySQL客户端导入[apolloportaldb.sql](https://github.com/ctripcorp/apollo/blob/master/scripts/sql/apolloportaldb.sql)即可。
以MySQL原生客户端为例:
```sql
source /your_local_path/scripts/sql/apolloportaldb.sql
```
#### 2.1.1.2 通过Flyway导入SQL创建
> 需要1.3.0及以上版本
1. 根据实际情况修改[flyway-portaldb.properties](https://github.com/ctripcorp/apollo/blob/master/scripts/flyway/flyway-portaldb.properties)中的`flyway.user`、`flyway.password`和`flyway.url`配置
2. 在apollo项目根目录下执行`mvn -N -Pportaldb flyway:migrate`
#### 2.1.1.3 验证
导入成功后,可以通过执行以下sql语句来验证:
```sql
select `Id`, `Key`, `Value`, `Comment` from `ApolloPortalDB`.`ServerConfig` limit 1;
```
| Id | Key | Value | Comment |
|----|--------------------|-------|------------------|
| 1 | apollo.portal.envs | dev | 可支持的环境列表 |
> 注:ApolloPortalDB只需要在生产环境部署一个即可
### 2.1.2 创建ApolloConfigDB
可以根据实际情况选择通过手动导入SQL或是通过[Flyway](https://flywaydb.org/)自动导入SQL创建。
#### 2.1.2.1 手动导入SQL
通过各种MySQL客户端导入[apolloconfigdb.sql](https://github.com/ctripcorp/apollo/blob/master/scripts/sql/apolloconfigdb.sql)即可。
以MySQL原生客户端为例:
```sql
source /your_local_path/scripts/sql/apolloconfigdb.sql
```
#### 2.1.2.2 通过Flyway导入SQL
> 需要1.3.0及以上版本
1. 根据实际情况修改[flyway-configdb.properties](https://github.com/ctripcorp/apollo/blob/master/scripts/flyway/flyway-configdb.properties)中的`flyway.user`、`flyway.password`和`flyway.url`配置
2. 在apollo项目根目录下执行`mvn -N -Pconfigdb flyway:migrate`
#### 2.1.2.3 验证
导入成功后,可以通过执行以下sql语句来验证:
```sql
select `Id`, `Key`, `Value`, `Comment` from `ApolloConfigDB`.`ServerConfig` limit 1;
```
| Id | Key | Value | Comment |
|----|--------------------|-------------------------------|---------------|
| 1 | eureka.service.url | http://127.0.0.1:8080/eureka/ | Eureka服务Url |
> 注:ApolloConfigDB需要在每个环境部署一套,如fat、uat和pro分别部署3套ApolloConfigDB
#### 2.1.2.4 从别的环境导入ApolloConfigDB的项目数据
如果是全新部署的Apollo配置中心,请忽略此步。
如果不是全新部署的Apollo配置中心,比如已经使用了一段时间,这时在Apollo配置中心已经创建了不少项目以及namespace等,那么在新环境中的ApolloConfigDB中需要从其它正常运行的环境中导入必要的项目数据。
主要涉及ApolloConfigDB的下面4张表,下面同时附上需要导入的数据查询语句:
1. App
* 导入全部的App
* 如:insert into `新环境的ApolloConfigDB`.`App` select * from `其它环境的ApolloConfigDB`.`App` where `IsDeleted` = 0;
2. AppNamespace
* 导入全部的AppNamespace
* 如:insert into `新环境的ApolloConfigDB`.`AppNamespace` select * from `其它环境的ApolloConfigDB`.`AppNamespace` where `IsDeleted` = 0;
3. Cluster
* 导入默认的default集群
* 如:insert into `新环境的ApolloConfigDB`.`Cluster` select * from `其它环境的ApolloConfigDB`.`Cluster` where `Name` = 'default' and `IsDeleted` = 0;
4. Namespace
* 导入默认的default集群中的namespace
* 如:insert into `新环境的ApolloConfigDB`.`Namespace` select * from `其它环境的ApolloConfigDB`.`Namespace` where `ClusterName` = 'default' and `IsDeleted` = 0;
同时也别忘了通知用户在新的环境给自己的项目设置正确的配置信息,尤其是一些影响面比较大的公共namespace配置。
> 如果是为正在运行的环境迁移数据,建议迁移完重启一下config service,因为config service中有appnamespace的缓存数据
### 2.1.3 调整服务端配置
Apollo自身的一些配置是放在数据库里面的,所以需要针对实际情况做一些调整,具体参数说明请参考[三、服务端配置说明](#三、服务端配置说明)。
大部分配置可以先使用默认值,不过 [apollo.portal.envs](#_311-apolloportalenvs-可支持的环境列表) 和 [eureka.service.url](#_321-eurekaserviceurl-eureka服务url) 请务必配置正确后再进行下面的部署步骤。
## 2.2 虚拟机/物理机部署
### 2.2.1 获取安装包
可以通过两种方式获取安装包:
1. 直接下载安装包
* 从[GitHub Release](https://github.com/ctripcorp/apollo/releases)页面下载预先打好的安装包
* 如果对Apollo的代码没有定制需求,建议使用这种方式,可以省去本地打包的过程
2. 通过源码构建
* 从[GitHub Release](https://github.com/ctripcorp/apollo/releases)页面下载Source code包或直接clone[源码](https://github.com/ctripcorp/apollo)后在本地构建
* 如果需要对Apollo的做定制开发,需要使用这种方式
#### 2.2.1.1 直接下载安装包
##### 2.2.1.1.1 获取apollo-configservice、apollo-adminservice、apollo-portal安装包
从[GitHub Release](https://github.com/ctripcorp/apollo/releases)页面下载最新版本的`apollo-configservice-x.x.x-github.zip`、`apollo-adminservice-x.x.x-github.zip`和`apollo-portal-x.x.x-github.zip`即可。
##### 2.2.1.1.2 配置数据库连接信息
Apollo服务端需要知道如何连接到你前面创建的数据库,数据库连接串信息位于上一步下载的压缩包中的`config/application-github.properties`中。
###### 2.2.1.1.2.1 配置apollo-configservice的数据库连接信息
1. 解压`apollo-configservice-x.x.x-github.zip`
2. 用程序员专用编辑器(如vim,notepad++,sublime等)打开`config`目录下的`application-github.properties`文件
3. 填写正确的ApolloConfigDB数据库连接串信息,注意用户名和密码后面不要有空格!
4. 修改完的效果如下:
```properties
# DataSource
spring.datasource.url = jdbc:mysql://localhost:3306/ApolloConfigDB?useSSL=false&characterEncoding=utf8
spring.datasource.username = someuser
spring.datasource.password = somepwd
```
> 注:由于ApolloConfigDB在每个环境都有部署,所以对不同的环境config-service需要配置对应环境的数据库参数
###### 2.2.1.1.2.2 配置apollo-adminservice的数据库连接信息
1. 解压`apollo-adminservice-x.x.x-github.zip`
2. 用程序员专用编辑器(如vim,notepad++,sublime等)打开`config`目录下的`application-github.properties`文件
3. 填写正确的ApolloConfigDB数据库连接串信息,注意用户名和密码后面不要有空格!
4. 修改完的效果如下:
```properties
# DataSource
spring.datasource.url = jdbc:mysql://localhost:3306/ApolloConfigDB?useSSL=false&characterEncoding=utf8
spring.datasource.username = someuser
spring.datasource.password = somepwd
```
> 注:由于ApolloConfigDB在每个环境都有部署,所以对不同的环境admin-service需要配置对应环境的数据库参数
###### 2.2.1.1.2.3 配置apollo-portal的数据库连接信息
1. 解压`apollo-portal-x.x.x-github.zip`
2. 用程序员专用编辑器(如vim,notepad++,sublime等)打开`config`目录下的`application-github.properties`文件
3. 填写正确的ApolloPortalDB数据库连接串信息,注意用户名和密码后面不要有空格!
4. 修改完的效果如下:
```properties
# DataSource
spring.datasource.url = jdbc:mysql://localhost:3306/ApolloPortalDB?useSSL=false&characterEncoding=utf8
spring.datasource.username = someuser
spring.datasource.password = somepwd
```
###### 2.2.1.1.2.4 配置apollo-portal的meta service信息
Apollo Portal需要在不同的环境访问不同的meta service(apollo-configservice)地址,所以我们需要在配置中提供这些信息。默认情况下,meta service和config service是部署在同一个JVM进程,所以meta service的地址就是config service的地址。
> 对于1.6.0及以上版本,可以通过ApolloPortalDB.ServerConfig中的配置项来配置Meta Service地址,详见[apollo.portal.meta.servers - 各环境Meta Service列表](#_312-apolloportalmetaservers-各环境meta-service列表)
使用程序员专用编辑器(如vim,notepad++,sublime等)打开`apollo-portal-x.x.x-github.zip`中`config`目录下的`apollo-env.properties`文件。
假设DEV的apollo-configservice未绑定域名,地址是1.1.1.1:8080,FAT的apollo-configservice绑定了域名apollo.fat.xxx.com,UAT的apollo-configservice绑定了域名apollo.uat.xxx.com,PRO的apollo-configservice绑定了域名apollo.xxx.com,那么可以如下修改各环境meta service服务地址,格式为`${env}.meta=http://${config-service-url:port}`,如果某个环境不需要,也可以直接删除对应的配置项(如lpt.meta):
```sh
dev.meta=http://1.1.1.1:8080
fat.meta=http://apollo.fat.xxx.com
uat.meta=http://apollo.uat.xxx.com
pro.meta=http://apollo.xxx.com
```
除了通过`apollo-env.properties`方式配置meta service以外,apollo也支持在运行时指定meta service(优先级比`apollo-env.properties`高):
1. 通过Java System Property `${env}_meta`
* 可以通过Java的System Property `${env}_meta`来指定
* 如`java -Ddev_meta=http://config-service-url -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("dev_meta", "http://config-service-url");`
2. 通过操作系统的System Environment`${ENV}_META`
* 如`DEV_META=http://config-service-url`
* 注意key为全大写,且中间是`_`分隔
>注1: 为了实现meta service的高可用,推荐通过SLB(Software Load Balancer)做动态负载均衡
>注2: meta service地址也可以填入IP,0.11.0版本之前只支持填入一个IP。从0.11.0版本开始支持填入以逗号分隔的多个地址([PR #1214](https://github.com/ctripcorp/apollo/pull/1214)),如`http://1.1.1.1:8080,http://2.2.2.2:8080`,不过生产环境还是建议使用域名(走slb),因为机器扩容、缩容等都可能导致IP列表的变化。
#### 2.2.1.2 通过源码构建
##### 2.2.1.2.1 配置数据库连接信息
Apollo服务端需要知道如何连接到你前面创建的数据库,所以需要编辑[scripts/build.sh](https://github.com/ctripcorp/apollo/blob/master/scripts/build.sh),修改ApolloPortalDB和ApolloConfigDB相关的数据库连接串信息。
> 注意:填入的用户需要具备对ApolloPortalDB和ApolloConfigDB数据的读写权限。
```sh
#apollo config db info
apollo_config_db_url=jdbc:mysql://localhost:3306/ApolloConfigDB?useSSL=false&characterEncoding=utf8
apollo_config_db_username=用户名
apollo_config_db_password=密码(如果没有密码,留空即可)
# apollo portal db info
apollo_portal_db_url=jdbc:mysql://localhost:3306/ApolloPortalDB?useSSL=false&characterEncoding=utf8
apollo_portal_db_username=用户名
apollo_portal_db_password=密码(如果没有密码,留空即可)
```
> 注1:由于ApolloConfigDB在每个环境都有部署,所以对不同的环境config-service和admin-service需要使用不同的数据库参数打不同的包,portal只需要打一次包即可
> 注2:如果不想config-service和admin-service每个环境打一个包的话,也可以通过运行时传入数据库连接串信息实现,具体可以参考 [Issue 869](https://github.com/ctripcorp/apollo/issues/869)
> 注3:每个环境都需要独立部署一套config-service、admin-service和ApolloConfigDB
##### 2.2.1.2.2 配置各环境meta service地址
Apollo Portal需要在不同的环境访问不同的meta service(apollo-configservice)地址,所以需要在打包时提供这些信息。
假设DEV的apollo-configservice未绑定域名,地址是1.1.1.1:8080,FAT的apollo-configservice绑定了域名apollo.fat.xxx.com,UAT的apollo-configservice绑定了域名apollo.uat.xxx.com,PRO的apollo-configservice绑定了域名apollo.xxx.com,那么编辑[scripts/build.sh](https://github.com/ctripcorp/apollo/blob/master/scripts/build.sh),如下修改各环境meta service服务地址,格式为`${env}_meta=http://${config-service-url:port}`,如果某个环境不需要,也可以直接删除对应的配置项:
```sh
dev_meta=http://1.1.1.1:8080
fat_meta=http://apollo.fat.xxx.com
uat_meta=http://apollo.uat.xxx.com
pro_meta=http://apollo.xxx.com
META_SERVERS_OPTS="-Ddev_meta=$dev_meta -Dfat_meta=$fat_meta -Duat_meta=$uat_meta -Dpro_meta=$pro_meta"
```
除了在打包时配置meta service以外,apollo也支持在运行时指定meta service:
1. 通过Java System Property `${env}_meta`
* 可以通过Java的System Property `${env}_meta`来指定
* 如`java -Ddev_meta=http://config-service-url -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("dev_meta", "http://config-service-url");`
2. 通过操作系统的System Environment`${ENV}_META`
* 如`DEV_META=http://config-service-url`
* 注意key为全大写,且中间是`_`分隔
>注1: 为了实现meta service的高可用,推荐通过SLB(Software Load Balancer)做动态负载均衡
>注2: meta service地址也可以填入IP,0.11.0版本之前只支持填入一个IP。从0.11.0版本开始支持填入以逗号分隔的多个地址([PR #1214](https://github.com/ctripcorp/apollo/pull/1214)),如`http://1.1.1.1:8080,http://2.2.2.2:8080`,不过生产环境还是建议使用域名(走slb),因为机器扩容、缩容等都可能导致IP列表的变化。
##### 2.2.1.2.3 执行编译、打包
做完上述配置后,就可以执行编译和打包了。
> 注:初次编译会从Maven中央仓库下载不少依赖,如果网络情况不佳时很容易出错,建议使用国内的Maven仓库源,比如[阿里云Maven镜像](http://www.cnblogs.com/geektown/p/5705405.html)
```sh
./build.sh
```
该脚本会依次打包apollo-configservice, apollo-adminservice, apollo-portal。
> 注:由于ApolloConfigDB在每个环境都有部署,所以对不同环境的config-service和admin-service需要使用不同的数据库连接信息打不同的包,portal只需要打一次包即可
##### 2.2.1.2.4 获取apollo-configservice安装包
位于`apollo-configservice/target/`目录下的`apollo-configservice-x.x.x-github.zip`
需要注意的是由于ApolloConfigDB在每个环境都有部署,所以对不同环境的config-service需要使用不同的数据库参数打不同的包后分别部署
##### 2.2.1.2.5 获取apollo-adminservice安装包
位于`apollo-adminservice/target/`目录下的`apollo-adminservice-x.x.x-github.zip`
需要注意的是由于ApolloConfigDB在每个环境都有部署,所以对不同环境的admin-service需要使用不同的数据库参数打不同的包后分别部署
##### 2.2.1.2.6 获取apollo-portal安装包
位于`apollo-portal/target/`目录下的`apollo-portal-x.x.x-github.zip`
##### 2.2.1.2.7 启用外部nacos服务注册中心替换内置eureka
1. 修改build.sh/build.bat,将config-service和admin-service的maven编译命令更改为
```shell
mvn clean package -Pgithub,nacos-discovery -DskipTests -pl apollo-configservice,apollo-adminservice -am -Dapollo_profile=github,nacos-discovery -Dspring_datasource_url=$apollo_config_db_url -Dspring_datasource_username=$apollo_config_db_username -Dspring_datasource_password=$apollo_config_db_password
```
2. 分别修改apollo-configservice和apollo-adminservice安装包中config目录下的application-github.properties,配置nacos服务器地址
```properties
nacos.discovery.server-addr=127.0.0.1:8848
# 更多 nacos 配置
nacos.discovery.access-key=
nacos.discovery.username=
nacos.discovery.password=
nacos.discovery.secret-key=
nacos.discovery.namespace=
nacos.discovery.context-path=
```
##### 2.2.1.2.8 启用外部Consul服务注册中心替换内置eureka
1. 修改build.sh/build.bat,将config-service和admin-service的maven编译命令更改为
```shell
mvn clean package -Pgithub -DskipTests -pl apollo-configservice,apollo-adminservice -am -Dapollo_profile=github,consul-discovery -Dspring_datasource_url=$apollo_config_db_url -Dspring_datasource_username=$apollo_config_db_username -Dspring_datasource_password=$apollo_config_db_password
```
2. 分别修改apollo-configservice和apollo-adminservice安装包中config目录下的application-github.properties,配置consul服务器地址
```properties
spring.cloud.consul.host=127.0.0.1
spring.cloud.consul.port=8500
```
### 2.2.2 部署Apollo服务端
#### 2.2.2.1 部署apollo-configservice
将对应环境的`apollo-configservice-x.x.x-github.zip`上传到服务器上,解压后执行scripts/startup.sh即可。如需停止服务,执行scripts/shutdown.sh.
记得在scripts/startup.sh中按照实际的环境设置一个JVM内存,以下是我们的默认设置,供参考:
```bash
export JAVA_OPTS="-server -Xms6144m -Xmx6144m -Xss256k -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=384m -XX:NewSize=4096m -XX:MaxNewSize=4096m -XX:SurvivorRatio=18"
```
> 注1:如果需要修改JVM参数,可以修改scripts/startup.sh的`JAVA_OPTS`部分。
> 注2:如要调整服务的日志输出路径,可以修改scripts/startup.sh和apollo-configservice.conf中的`LOG_DIR`。
> 注3:如要调整服务的监听端口,可以修改scripts/startup.sh中的`SERVER_PORT`。另外apollo-configservice同时承担meta server职责,如果要修改端口,注意要同时ApolloConfigDB.ServerConfig表中的`eureka.service.url`配置项以及apollo-portal和apollo-client中的使用到的meta server信息,详见:[2.2.1.1.2.4 配置apollo-portal的meta service信息](#_221124-配置apollo-portal的meta-service信息)和[1.2.2 Apollo Meta Server](zh/usage/java-sdk-user-guide#_122-apollo-meta-server)。
> 注4:如果ApolloConfigDB.ServerConfig的eureka.service.url只配了当前正在启动的机器的话,在启动apollo-configservice的过程中会在日志中输出eureka注册失败的信息,如`com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused`。需要注意的是,这个是预期的情况,因为apollo-configservice需要向Meta Server(它自己)注册服务,但是因为在启动过程中,自己还没起来,所以会报这个错。后面会进行重试的动作,所以等自己服务起来后就会注册正常了。
> 注5:如果你看到了这里,相信你一定是一个细心阅读文档的人,而且离成功就差一点点了,继续加油,应该很快就能完成Apollo的分布式部署了!不过你是否有感觉Apollo的分布式部署步骤有点繁琐?是否有啥建议想要和作者说?如果答案是肯定的话,请移步 [#1424](https://github.com/ctripcorp/apollo/issues/1424),期待你的建议!
#### 2.2.2.2 部署apollo-adminservice
将对应环境的`apollo-adminservice-x.x.x-github.zip`上传到服务器上,解压后执行scripts/startup.sh即可。如需停止服务,执行scripts/shutdown.sh.
记得在scripts/startup.sh中按照实际的环境设置一个JVM内存,以下是我们的默认设置,供参考:
```bash
export JAVA_OPTS="-server -Xms2560m -Xmx2560m -Xss256k -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=384m -XX:NewSize=1024m -XX:MaxNewSize=1024m -XX:SurvivorRatio=22"
```
> 注1:如果需要修改JVM参数,可以修改scripts/startup.sh的`JAVA_OPTS`部分。
> 注2:如要调整服务的日志输出路径,可以修改scripts/startup.sh和apollo-adminservice.conf中的`LOG_DIR`。
> 注3:如要调整服务的监听端口,可以修改scripts/startup.sh中的`SERVER_PORT`。
#### 2.2.2.3 部署apollo-portal
将`apollo-portal-x.x.x-github.zip`上传到服务器上,解压后执行scripts/startup.sh即可。如需停止服务,执行scripts/shutdown.sh.
记得在startup.sh中按照实际的环境设置一个JVM内存,以下是我们的默认设置,供参考:
```bash
export JAVA_OPTS="-server -Xms4096m -Xmx4096m -Xss256k -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=384m -XX:NewSize=1536m -XX:MaxNewSize=1536m -XX:SurvivorRatio=22"
```
> 注1:如果需要修改JVM参数,可以修改scripts/startup.sh的`JAVA_OPTS`部分。
> 注2:如要调整服务的日志输出路径,可以修改scripts/startup.sh和apollo-portal.conf中的`LOG_DIR`。
> 注3:如要调整服务的监听端口,可以修改scripts/startup.sh中的`SERVER_PORT`。
## 2.3 Docker部署
### 2.3.1 1.7.0及以上版本
Apollo 1.7.0版本开始会默认上传Docker镜像到[Docker Hub](https://hub.docker.com/u/apolloconfig),可以按照如下步骤获取
#### 2.3.1.1 Apollo Config Service
##### 2.3.1.1.1 获取镜像
```bash
docker pull apolloconfig/apollo-configservice:${version}
```
##### 2.3.1.1.2 运行镜像
示例:
```bash
docker run -p 8080:8080 \
-e SPRING_DATASOURCE_URL="jdbc:mysql://fill-in-the-correct-server:3306/ApolloConfigDB?characterEncoding=utf8" \
-e SPRING_DATASOURCE_USERNAME=FillInCorrectUser -e SPRING_DATASOURCE_PASSWORD=FillInCorrectPassword \
-d -v /tmp/logs:/opt/logs --name apollo-configservice apolloconfig/apollo-configservice:${version}
```
参数说明:
* SPRING_DATASOURCE_URL: 对应环境ApolloConfigDB的地址
* SPRING_DATASOURCE_USERNAME: 对应环境ApolloConfigDB的用户名
* SPRING_DATASOURCE_PASSWORD: 对应环境ApolloConfigDB的密码
#### 2.3.1.2 Apollo Admin Service
##### 2.3.1.2.1 获取镜像
```bash
docker pull apolloconfig/apollo-adminservice:${version}
```
##### 2.3.1.2.2 运行镜像
示例:
```bash
docker run -p 8090:8090 \
-e SPRING_DATASOURCE_URL="jdbc:mysql://fill-in-the-correct-server:3306/ApolloConfigDB?characterEncoding=utf8" \
-e SPRING_DATASOURCE_USERNAME=FillInCorrectUser -e SPRING_DATASOURCE_PASSWORD=FillInCorrectPassword \
-d -v /tmp/logs:/opt/logs --name apollo-adminservice apolloconfig/apollo-adminservice:${version}
```
参数说明:
* SPRING_DATASOURCE_URL: 对应环境ApolloConfigDB的地址
* SPRING_DATASOURCE_USERNAME: 对应环境ApolloConfigDB的用户名
* SPRING_DATASOURCE_PASSWORD: 对应环境ApolloConfigDB的密码
#### 2.3.1.3 Apollo Portal
##### 2.3.1.3.1 获取镜像
```bash
docker pull apolloconfig/apollo-portal:${version}
```
##### 2.3.1.3.2 运行镜像
示例:
```bash
docker run -p 8070:8070 \
-e SPRING_DATASOURCE_URL="jdbc:mysql://fill-in-the-correct-server:3306/ApolloPortalDB?characterEncoding=utf8" \
-e SPRING_DATASOURCE_USERNAME=FillInCorrectUser -e SPRING_DATASOURCE_PASSWORD=FillInCorrectPassword \
-e APOLLO_PORTAL_ENVS=dev,pro \
-e DEV_META=http://fill-in-dev-meta-server:8080 -e PRO_META=http://fill-in-pro-meta-server:8080 \
-d -v /tmp/logs:/opt/logs --name apollo-portal apolloconfig/apollo-portal:${version}
```
参数说明:
* SPRING_DATASOURCE_URL: 对应环境ApolloPortalDB的地址
* SPRING_DATASOURCE_USERNAME: 对应环境ApolloPortalDB的用户名
* SPRING_DATASOURCE_PASSWORD: 对应环境ApolloPortalDB的密码
* APOLLO_PORTAL_ENVS(可选): 对应ApolloPortalDB中的[apollo.portal.envs](#_311-apolloportalenvs-可支持的环境列表)配置项,如果没有在数据库中配置的话,可以通过此环境参数配置
* DEV_META/PRO_META(可选): 配置对应环境的Meta Service地址,以${ENV}_META命名,需要注意的是如果配置了ApolloPortalDB中的[apollo.portal.meta.servers](#_312-apolloportalmetaservers-各环境meta-service列表)配置,则以apollo.portal.meta.servers中的配置为准
#### 2.3.1.4 通过源码构建 Docker 镜像
如果修改了 apollo 服务端的代码,希望通过源码构建 Docker 镜像,可以参考下面的步骤:
1. 通过源码构建安装包:`./scripts/build.sh`
2. 构建 Docker 镜像:`mvn docker:build -pl apollo-configservice,apollo-adminservice,apollo-portal`
### 2.3.2 1.7.0之前的版本
Apollo项目已经自带了Docker file,可以参照[2.2.1 获取安装包](#_221-获取安装包)配置好安装包后通过下面的文件来打Docker镜像:
1. [apollo-configservice](https://github.com/ctripcorp/apollo/blob/master/apollo-configservice/src/main/docker/Dockerfile)
2. [apollo-adminservice](https://github.com/ctripcorp/apollo/blob/master/apollo-adminservice/src/main/docker/Dockerfile)
3. [apollo-portal](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/docker/Dockerfile)
也可以参考Apollo用户[@kulovecc](https://github.com/kulovecc)的[docker-apollo](https://github.com/kulovecc/docker-apollo)项目和[@idoop](https://github.com/idoop)的[docker-apollo](https://github.com/idoop/docker-apollo)项目。
## 2.4 Kubernetes部署
### 2.4.1 基于Kubernetes原生服务发现
Apollo 1.7.0版本增加了基于Kubernetes原生服务发现的部署模式,由于不再使用内置的Eureka,所以在整体部署上有很大简化,同时也提供了Helm Charts,便于部署。
> 更多设计说明可以参考[#3054](https://github.com/ctripcorp/apollo/issues/3054)。
#### 2.4.1.1 环境要求
- Kubernetes 1.10+
- Helm 3
#### 2.4.1.2 添加Apollo Helm Chart仓库
```bash
$ helm repo add apollo https://www.apolloconfig.com/charts
$ helm search repo apollo
```
#### 2.4.1.3 部署apollo-configservice和apollo-adminservice
##### 2.4.1.3.1 安装apollo-configservice和apollo-adminservice
需要在每个环境中安装apollo-configservice和apollo-adminservice,所以建议在release名称中加入环境信息,例如:`apollo-service-dev`
```bash
$ helm install apollo-service-dev \
--set configdb.host=1.2.3.4 \
--set configdb.userName=apollo \
--set configdb.password=apollo \
--set configdb.service.enabled=true \
--set configService.replicaCount=1 \
--set adminService.replicaCount=1 \
-n your-namespace \
apollo/apollo-service
```
一般部署建议通过 values.yaml 来配置:
```bash
$ helm install apollo-service-dev -f values.yaml -n your-namespace apollo/apollo-service
```
安装完成后会提示对应环境的Meta Server地址,需要记录下来,apollo-portal安装时需要用到:
```bash
Get meta service url for current release by running these commands:
echo http://apollo-service-dev-apollo-configservice:8080
```
> 更多配置项说明可以参考[2.4.1.3.3 配置项说明](#_24133-配置项说明)
##### 2.4.1.3.2 卸载apollo-configservice和apollo-adminservice
例如要卸载`apollo-service-dev`的部署:
```bash
$ helm uninstall -n your-namespace apollo-service-dev
```
##### 2.4.1.3.3 配置项说明
下表列出了apollo-service chart的可配置参数及其默认值:
| Parameter | Description | Default |
|----------------------|---------------------------------------------|---------------------|
| `configdb.host` | The host for apollo config db | `nil` |
| `configdb.port` | The port for apollo config db | `3306` |
| `configdb.dbName` | The database name for apollo config db | `ApolloConfigDB` |
| `configdb.userName` | The user name for apollo config db | `nil` |
| `configdb.password` | The password for apollo config db | `nil` |
| `configdb.connectionStringProperties` | The connection string properties for apollo config db | `characterEncoding=utf8` |
| `configdb.service.enabled` | Whether to create a Kubernetes Service for `configdb.host` or not. Set it to `true` if `configdb.host` is an endpoint outside of the kubernetes cluster | `false` |
| `configdb.service.fullNameOverride` | Override the service name for apollo config db | `nil` |
| `configdb.service.port` | The port for the service of apollo config db | `3306` |
| `configdb.service.type` | The service type of apollo config db: `ClusterIP` or `ExternalName`. If the host is a DNS name, please specify `ExternalName` as the service type, e.g. `xxx.mysql.rds.aliyuncs.com` | `ClusterIP` |
| `configService.fullNameOverride` | Override the deployment name for apollo-configservice | `nil` |
| `configService.replicaCount` | Replica count of apollo-configservice | `2` |
| `configService.containerPort` | Container port of apollo-configservice | `8080` |
| `configService.image.repository` | Image repository of apollo-configservice | `apolloconfig/apollo-configservice` |
| `configService.image.tag` | Image tag of apollo-configservice, e.g. `1.8.0`, leave it to `nil` to use the default version. _(chart version >= 0.2.0)_ | `nil` |
| `configService.image.pullPolicy` | Image pull policy of apollo-configservice | `IfNotPresent` |
| `configService.imagePullSecrets` | Image pull secrets of apollo-configservice | `[]` |
| `configService.service.fullNameOverride` | Override the service name for apollo-configservice | `nil` |
| `configService.service.port` | The port for the service of apollo-configservice | `8080` |
| `configService.service.targetPort` | The target port for the service of apollo-configservice | `8080` |
| `configService.service.type` | The service type of apollo-configservice | `ClusterIP` |
| `configService.ingress.enabled` | Whether to enable the ingress for config-service or not. _(chart version >= 0.2.0)_ | `false` |
| `configService.ingress.annotations` | The annotations of the ingress for config-service. _(chart version >= 0.2.0)_ | `{}` |
| `configService.ingress.hosts.host` | The host of the ingress for config-service. _(chart version >= 0.2.0)_ | `nil` |
| `configService.ingress.hosts.paths` | The paths of the ingress for config-service. _(chart version >= 0.2.0)_ | `[]` |
| `configService.ingress.tls` | The tls definition of the ingress for config-service. _(chart version >= 0.2.0)_ | `[]` |
| `configService.liveness.initialDelaySeconds` | The initial delay seconds of liveness probe | `100` |
| `configService.liveness.periodSeconds` | The period seconds of liveness probe | `10` |
| `configService.readiness.initialDelaySeconds` | The initial delay seconds of readiness probe | `30` |
| `configService.readiness.periodSeconds` | The period seconds of readiness probe | `5` |
| `configService.config.profiles` | specify the spring profiles to activate | `github,kubernetes` |
| `configService.config.configServiceUrlOverride` | Override `apollo.config-service.url`: config service url to be accessed by apollo-client, e.g. `http://apollo-config-service-dev:8080` | `nil` |
| `configService.config.adminServiceUrlOverride` | Override `apollo.admin-service.url`: admin service url to be accessed by apollo-portal, e.g. `http://apollo-admin-service-dev:8090` | `nil` |
| `configService.config.contextPath` | specify the context path, e.g. `/apollo`, then users could access config service via `http://{config_service_address}/apollo`. _(chart version >= 0.2.0)_ | `nil` |
| `configService.env` | Environment variables passed to the container, e.g. <br />`JAVA_OPTS: -Xss256k` | `{}` |
| `configService.strategy` | The deployment strategy of apollo-configservice | `{}` |
| `configService.resources` | The resources definition of apollo-configservice | `{}` |
| `configService.nodeSelector` | The node selector definition of apollo-configservice | `{}` |
| `configService.tolerations` | The tolerations definition of apollo-configservice | `[]` |
| `configService.affinity` | The affinity definition of apollo-configservice | `{}` |
| `adminService.fullNameOverride` | Override the deployment name for apollo-adminservice | `nil` |
| `adminService.replicaCount` | Replica count of apollo-adminservice | `2` |
| `adminService.containerPort` | Container port of apollo-adminservice | `8090` |
| `adminService.image.repository` | Image repository of apollo-adminservice | `apolloconfig/apollo-adminservice` |
| `adminService.image.tag` | Image tag of apollo-adminservice, e.g. `1.8.0`, leave it to `nil` to use the default version. _(chart version >= 0.2.0)_ | `nil` |
| `adminService.image.pullPolicy` | Image pull policy of apollo-adminservice | `IfNotPresent` |
| `adminService.imagePullSecrets` | Image pull secrets of apollo-adminservice | `[]` |
| `adminService.service.fullNameOverride` | Override the service name for apollo-adminservice | `nil` |
| `adminService.service.port` | The port for the service of apollo-adminservice | `8090` |
| `adminService.service.targetPort` | The target port for the service of apollo-adminservice | `8090` |
| `adminService.service.type` | The service type of apollo-adminservice | `ClusterIP` |
| `adminService.ingress.enabled` | Whether to enable the ingress for admin-service or not. _(chart version >= 0.2.0)_ | `false` |
| `adminService.ingress.annotations` | The annotations of the ingress for admin-service. _(chart version >= 0.2.0)_ | `{}` |
| `adminService.ingress.hosts.host` | The host of the ingress for admin-service. _(chart version >= 0.2.0)_ | `nil` |
| `adminService.ingress.hosts.paths` | The paths of the ingress for admin-service. _(chart version >= 0.2.0)_ | `[]` |
| `adminService.ingress.tls` | The tls definition of the ingress for admin-service. _(chart version >= 0.2.0)_ | `[]` |
| `adminService.liveness.initialDelaySeconds` | The initial delay seconds of liveness probe | `100` |
| `adminService.liveness.periodSeconds` | The period seconds of liveness probe | `10` |
| `adminService.readiness.initialDelaySeconds` | The initial delay seconds of readiness probe | `30` |
| `adminService.readiness.periodSeconds` | The period seconds of readiness probe | `5` |
| `adminService.config.profiles` | specify the spring profiles to activate | `github,kubernetes` |
| `adminService.config.contextPath` | specify the context path, e.g. `/apollo`, then users could access admin service via `http://{admin_service_address}/apollo`. _(chart version >= 0.2.0)_ | `nil` |
| `adminService.env` | Environment variables passed to the container, e.g. <br />`JAVA_OPTS: -Xss256k` | `{}` |
| `adminService.strategy` | The deployment strategy of apollo-adminservice | `{}` |
| `adminService.resources` | The resources definition of apollo-adminservice | `{}` |
| `adminService.nodeSelector` | The node selector definition of apollo-adminservice | `{}` |
| `adminService.tolerations` | The tolerations definition of apollo-adminservice | `[]` |
| `adminService.affinity` | The affinity definition of apollo-adminservice | `{}` |
##### 2.4.1.3.4 配置样例
###### 2.4.1.3.4.1 ConfigDB的host是k8s集群外的IP
```yaml
configdb:
host: 1.2.3.4
dbName: ApolloConfigDBName
userName: someUserName
password: somePassword
connectionStringProperties: characterEncoding=utf8&useSSL=false
service:
enabled: true
```
###### 2.4.1.3.4.2 ConfigDB的host是k8s集群外的域名
```yaml
configdb:
host: xxx.mysql.rds.aliyuncs.com
dbName: ApolloConfigDBName
userName: someUserName
password: somePassword
connectionStringProperties: characterEncoding=utf8&useSSL=false
service:
enabled: true
type: ExternalName
```
###### 2.4.1.3.4.3 ConfigDB的host是k8s集群内的一个服务
```yaml
configdb:
host: apollodb-mysql.mysql
dbName: ApolloConfigDBName
userName: someUserName
password: somePassword
connectionStringProperties: characterEncoding=utf8&useSSL=false
```
###### 2.4.1.3.4.4 指定Meta Server返回的apollo-configservice地址
如果apollo-client无法直接访问apollo-configservice的Service(比如不在同一个k8s集群),那么可以参照下面的示例指定Meta Server返回给apollo-client的地址(比如可以通过nodeport访问)
```yaml
configService:
config:
configServiceUrlOverride: http://1.2.3.4:12345
```
###### 2.4.1.3.4.5 指定Meta Server返回的apollo-adminservice地址
如果apollo-portal无法直接访问apollo-adminservice的Service(比如不在同一个k8s集群),那么可以参照下面的示例指定Meta Server返回给apollo-portal的地址(比如可以通过nodeport访问)
```yaml
configService:
config:
adminServiceUrlOverride: http://1.2.3.4:23456
```
###### 2.4.1.3.4.6 以Ingress配置自定义路径`/config`形式暴露apollo-configservice服务
```yaml
# use /config as root, should specify configService.config.contextPath as /config
configService:
config:
contextPath: /config
ingress:
enabled: true
hosts:
- paths:
- /config
```
###### 2.4.1.3.4.7 以Ingress配置自定义路径`/admin`形式暴露apollo-adminservice服务
```yaml
# use /admin as root, should specify adminService.config.contextPath as /admin
adminService:
config:
contextPath: /admin
ingress:
enabled: true
hosts:
- paths:
- /admin
```
#### 2.4.1.4 部署apollo-portal
##### 2.4.1.4.1 安装apollo-portal
假设有dev, pro两个环境,且meta server地址分别为`http://apollo-service-dev-apollo-configservice:8080`和`http://apollo-service-pro-apollo-configservice:8080`:
```bash
$ helm install apollo-portal \
--set portaldb.host=1.2.3.4 \
--set portaldb.userName=apollo \
--set portaldb.password=apollo \
--set portaldb.service.enabled=true \
--set config.envs="dev\,pro" \
--set config.metaServers.dev=http://apollo-service-dev-apollo-configservice:8080 \
--set config.metaServers.pro=http://apollo-service-pro-apollo-configservice:8080 \
--set replicaCount=1 \
-n your-namespace \
apollo/apollo-portal
```
一般部署建议通过 values.yaml 来配置:
```bash
$ helm install apollo-portal -f values.yaml -n your-namespace apollo/apollo-portal
```
> 更多配置项说明可以参考[2.4.1.4.3 配置项说明](#_24143-配置项说明)
##### 2.4.1.4.2 卸载apollo-portal
例如要卸载`apollo-portal`的部署:
```bash
$ helm uninstall -n your-namespace apollo-portal
```
##### 2.4.1.4.3 配置项说明
下表列出了apollo-portal chart的可配置参数及其默认值:
| Parameter | Description | Default |
|----------------------|---------------------------------------------|-----------------------|
| `fullNameOverride` | Override the deployment name for apollo-portal | `nil` |
| `replicaCount` | Replica count of apollo-portal | `2` |
| `containerPort` | Container port of apollo-portal | `8070` |
| `image.repository` | Image repository of apollo-portal | `apolloconfig/apollo-portal` |
| `image.tag` | Image tag of apollo-portal, e.g. `1.8.0`, leave it to `nil` to use the default version. _(chart version >= 0.2.0)_ | `nil` |
| `image.pullPolicy` | Image pull policy of apollo-portal | `IfNotPresent` |
| `imagePullSecrets` | Image pull secrets of apollo-portal | `[]` |
| `service.fullNameOverride` | Override the service name for apollo-portal | `nil` |
| `service.port` | The port for the service of apollo-portal | `8070` |
| `service.targetPort` | The target port for the service of apollo-portal | `8070` |
| `service.type` | The service type of apollo-portal | `ClusterIP` |
| `service.sessionAffinity` | The session affinity for the service of apollo-portal | `ClientIP` |
| `ingress.enabled` | Whether to enable the ingress or not | `false` |
| `ingress.annotations` | The annotations of the ingress | `{}` |
| `ingress.hosts.host` | The host of the ingress | `nil` |
| `ingress.hosts.paths` | The paths of the ingress | `[]` |
| `ingress.tls` | The tls definition of the ingress | `[]` |
| `liveness.initialDelaySeconds` | The initial delay seconds of liveness probe | `100` |
| `liveness.periodSeconds` | The period seconds of liveness probe | `10` |
| `readiness.initialDelaySeconds` | The initial delay seconds of readiness probe | `30` |
| `readiness.periodSeconds` | The period seconds of readiness probe | `5` |
| `env` | Environment variables passed to the container, e.g. <br />`JAVA_OPTS: -Xss256k` | `{}` |
| `strategy` | The deployment strategy of apollo-portal | `{}` |
| `resources` | The resources definition of apollo-portal | `{}` |
| `nodeSelector` | The node selector definition of apollo-portal | `{}` |
| `tolerations` | The tolerations definition of apollo-portal | `[]` |
| `affinity` | The affinity definition of apollo-portal | `{}` |
| `config.profiles` | specify the spring profiles to activate | `github,auth` |
| `config.envs` | specify the env names, e.g. `dev,pro` | `nil` |
| `config.contextPath` | specify the context path, e.g. `/apollo`, then users could access portal via `http://{portal_address}/apollo` | `nil` |
| `config.metaServers` | specify the meta servers, e.g.<br />`dev: http://apollo-configservice-dev:8080`<br />`pro: http://apollo-configservice-pro:8080` | `{}` |
| `config.files` | specify the extra config files for apollo-portal, e.g. `application-ldap.yml` | `{}` |
| `portaldb.host` | The host for apollo portal db | `nil` |
| `portaldb.port` | The port for apollo portal db | `3306` |
| `portaldb.dbName` | The database name for apollo portal db | `ApolloPortalDB` |
| `portaldb.userName` | The user name for apollo portal db | `nil` |
| `portaldb.password` | The password for apollo portal db | `nil` |
| `portaldb.connectionStringProperties` | The connection string properties for apollo portal db | `characterEncoding=utf8` |
| `portaldb.service.enabled` | Whether to create a Kubernetes Service for `portaldb.host` or not. Set it to `true` if `portaldb.host` is an endpoint outside of the kubernetes cluster | `false` |
| `portaldb.service.fullNameOverride` | Override the service name for apollo portal db | `nil` |
| `portaldb.service.port` | The port for the service of apollo portal db | `3306` |
| `portaldb.service.type` | The service type of apollo portal db: `ClusterIP` or `ExternalName`. If the host is a DNS name, please specify `ExternalName` as the service type, e.g. `xxx.mysql.rds.aliyuncs.com` | `ClusterIP` |
##### 2.4.1.4.4 配置样例
###### 2.4.1.4.4.1 PortalDB的host是k8s集群外的IP
```yaml
portaldb:
host: 1.2.3.4
dbName: ApolloPortalDBName
userName: someUserName
password: somePassword
connectionStringProperties: characterEncoding=utf8&useSSL=false
service:
enabled: true
```
###### 2.4.1.4.4.2 PortalDB的host是k8s集群外的域名
```yaml
portaldb:
host: xxx.mysql.rds.aliyuncs.com
dbName: ApolloPortalDBName
userName: someUserName
password: somePassword
connectionStringProperties: characterEncoding=utf8&useSSL=false
service:
enabled: true
type: ExternalName
```
###### 2.4.1.4.4.3 PortalDB的host是k8s集群内的一个服务
```yaml
portaldb:
host: apollodb-mysql.mysql
dbName: ApolloPortalDBName
userName: someUserName
password: somePassword
connectionStringProperties: characterEncoding=utf8&useSSL=false
```
###### 2.4.1.4.4.4 配置环境信息
```yaml
config:
envs: dev,pro
metaServers:
dev: http://apollo-service-dev-apollo-configservice:8080
pro: http://apollo-service-pro-apollo-configservice:8080
```
###### 2.4.1.4.4.5 以Load Balancer形式暴露服务
```yaml
service:
type: LoadBalancer
```
###### 2.4.1.4.4.6 以Ingress形式暴露服务
```yaml
ingress:
enabled: true
hosts:
- paths:
- /
```
###### 2.4.1.4.4.7 以Ingress配置自定义路径`/apollo`形式暴露服务
```yaml
# use /apollo as root, should specify config.contextPath as /apollo
ingress:
enabled: true
hosts:
- paths:
- /apollo
config:
...
contextPath: /apollo
...
```
###### 2.4.1.4.4.8 以Ingress配置session affinity形式暴露服务
```yaml
ingress:
enabled: true
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/affinity: "cookie"
nginx.ingress.kubernetes.io/affinity-mode: "persistent"
nginx.ingress.kubernetes.io/session-cookie-conditional-samesite-none: "true"
nginx.ingress.kubernetes.io/session-cookie-expires: "172800"
nginx.ingress.kubernetes.io/session-cookie-max-age: "172800"
hosts:
- host: xxx.somedomain.com # host is required to make session affinity work
paths:
- /
```
###### 2.4.1.4.4.9 启用 LDAP 支持
```yaml
config:
...
profiles: github,ldap
...
files:
application-ldap.yml: |
spring:
ldap:
base: "dc=example,dc=org"
username: "cn=admin,dc=example,dc=org"
password: "password"
searchFilter: "(uid={0})"
urls:
- "ldap://xxx.somedomain.com:389"
ldap:
mapping:
objectClass: "inetOrgPerson"
loginId: "uid"
userDisplayName: "cn"
email: "mail"
```
#### 2.4.1.5 通过源码构建 Docker 镜像
如果修改了 apollo 服务端的代码,希望通过源码构建 Docker 镜像,可以参考[2.3.1.4 通过源码构建 Docker 镜像](#_2314-通过源码构建-docker-镜像)的步骤。
### 2.4.2 基于内置的Eureka服务发现
感谢[AiotCEO](https://github.com/AiotCEO)提供了k8s的部署支持,使用说明可以参考[apollo-on-kubernetes](https://github.com/ctripcorp/apollo/blob/master/scripts/apollo-on-kubernetes/README.md)。
感谢[qct](https://github.com/qct)提供的Helm Chart部署支持,使用说明可以参考[qct/apollo-helm](https://github.com/qct/apollo-helm)。
# 三、服务端配置说明
> 以下配置除了支持在数据库中配置以外,也支持通过-D参数、application.properties等配置,且-D参数、application.properties等优先级高于数据库中的配置
## 3.1 调整ApolloPortalDB配置
配置项统一存储在ApolloPortalDB.ServerConfig表中,也可以通过`管理员工具 - 系统参数`页面进行配置,无特殊说明则修改完一分钟实时生效。
### 3.1.1 apollo.portal.envs - 可支持的环境列表
默认值是dev,如果portal需要管理多个环境的话,以逗号分隔即可(大小写不敏感),如:
```
DEV,FAT,UAT,PRO
```
修改完需要重启生效。
>注1:一套Portal可以管理多个环境,但是每个环境都需要独立部署一套Config Service、Admin Service和ApolloConfigDB,具体请参考:[2.1.2 创建ApolloConfigDB](#_212-创建apolloconfigdb),[3.2 调整ApolloConfigDB配置](zh/deployment/distributed-deployment-guide?id=_32-调整apolloconfigdb配置),[2.2.1.1.2 配置数据库连接信息](#_22112-配置数据库连接信息),另外如果是为已经运行了一段时间的Apollo配置中心增加环境,别忘了参考[2.1.2.4 从别的环境导入ApolloConfigDB的项目数据](#_2124-从别的环境导入apolloconfigdb的项目数据)对新的环境做初始化。
>注2:只在数据库添加环境是不起作用的,还需要为apollo-portal添加新增环境对应的meta server地址,具体参考:[2.2.1.1.2.4 配置apollo-portal的meta service信息](#_221124-配置apollo-portal的meta-service信息)。apollo-client在新的环境下使用时也需要做好相应的配置,具体参考:[1.2.2 Apollo Meta Server](zh/usage/java-sdk-user-guide#_122-apollo-meta-server)。
>注3:如果希望添加自定义的环境名称,具体步骤可以参考[Portal如何增加环境](zh/faq/common-issues-in-deployment-and-development-phase?id=_4-portal如何增加环境?)。
>注4:1.1.0版本增加了系统信息页面(`管理员工具` -> `系统信息`),可以通过该页面检查配置是否正确
### 3.1.2 apollo.portal.meta.servers - 各环境Meta Service列表
> 适用于1.6.0及以上版本
Apollo Portal需要在不同的环境访问不同的meta service(apollo-configservice)地址,所以我们需要在配置中提供这些信息。默认情况下,meta service和config service是部署在同一个JVM进程,所以meta service的地址就是config service的地址。
样例如下:
```json
{
"DEV":"http://1.1.1.1:8080",
"FAT":"http://apollo.fat.xxx.com",
"UAT":"http://apollo.uat.xxx.com",
"PRO":"http://apollo.xxx.com"
}
```
修改完需要重启生效。
> 该配置优先级高于其它方式设置的Meta Service地址,更多信息可以参考[2.2.1.1.2.4 配置apollo-portal的meta service信息](#_221124-配置apollo-portal的meta-service信息)。
### 3.1.3 organizations - 部门列表
Portal中新建的App都需要选择部门,所以需要在这里配置可选的部门信息,样例如下:
```json
[{"orgId":"TEST1","orgName":"样例部门1"},{"orgId":"TEST2","orgName":"样例部门2"}]
```
### 3.1.4 superAdmin - Portal超级管理员
超级管理员拥有所有权限,需要谨慎设置。
如果没有接入自己公司的SSO系统的话,可以先暂时使用默认值apollo(默认用户)。等接入后,修改为实际使用的账号,多个账号以英文逗号分隔(,)。
### 3.1.5 consumer.token.salt - consumer token salt
如果会使用开放平台API的话,可以设置一个token salt。如果不使用,可以忽略。
### 3.1.6 wiki.address
portal上“帮助”链接的地址,默认是Apollo github的wiki首页,可自行设置。
### 3.1.7 admin.createPrivateNamespace.switch
是否允许项目管理员创建private namespace。设置为`true`允许创建,设置为`false`则项目管理员在页面上看不到创建private namespace的选项。[了解更多Namespace](zh/design/apollo-core-concept-namespace)
### 3.1.8 emergencyPublish.supported.envs
配置允许紧急发布的环境列表,多个env以英文逗号分隔。
当config service开启一次发布只能有一个人修改开关(`namespace.lock.switch`)后,一次配置发布只能是一个人修改,另一个发布。为了避免遇到紧急情况时(如非工作时间、节假日)无法发布配置,可以配置此项以允许某些环境可以操作紧急发布,即同一个人可以修改并发布配置。
### 3.1.9 configView.memberOnly.envs
只对项目成员显示配置信息的环境列表,多个env以英文逗号分隔。
对设定了只对项目成员显示配置信息的环境,只有该项目的管理员或拥有该namespace的编辑或发布权限的用户才能看到该私有namespace的配置信息和发布历史。公共namespace始终对所有用户可见。
> 从1.1.0版本开始支持,详见[PR 1531](https://github.com/ctripcorp/apollo/pull/1531)
### 3.1.10 role.create-application.enabled - 是否开启创建项目权限控制
> 适用于1.5.0及以上版本
默认为false,所有用户都可以创建项目
如果设置为true,那么只有超级管理员和拥有创建项目权限的帐号可以创建项目,超级管理员可以通过`管理员工具 - 系统权限管理`给用户分配创建项目权限
### 3.1.11 role.manage-app-master.enabled - 是否开启项目管理员分配权限控制
> 适用于1.5.0及以上版本
默认为false,所有项目的管理员可以为项目添加/删除管理员
如果设置为true,那么只有超级管理员和拥有项目管理员分配权限的帐号可以为特定项目添加/删除管理员,超级管理员可以通过`管理员工具 - 系统权限管理`给用户分配特定项目的管理员分配权限
### 3.1.12 admin-service.access.tokens - 设置apollo-portal访问各环境apollo-adminservice所需的access token
> 适用于1.7.1及以上版本
如果对应环境的apollo-adminservice开启了[访问控制](#_326-admin-serviceaccesscontrolenabled-配置apollo-adminservice是否开启访问控制),那么需要在此配置apollo-portal访问该环境apollo-adminservice所需的access token,否则会访问失败
格式为json,如下所示:
```json
{
"dev" : "098f6bcd4621d373cade4e832627b4f6",
"pro" : "ad0234829205b9033196ba818f7a872b"
}
```
## 3.2 调整ApolloConfigDB配置
配置项统一存储在ApolloConfigDB.ServerConfig表中,需要注意每个环境的ApolloConfigDB.ServerConfig都需要单独配置,修改完一分钟实时生效。
### 3.2.1 eureka.service.url - Eureka服务Url
> 不适用于基于Kubernetes原生服务发现场景
不管是apollo-configservice还是apollo-adminservice都需要向eureka服务注册,所以需要配置eureka服务地址。
按照目前的实现,apollo-configservice本身就是一个eureka服务,所以只需要填入apollo-configservice的地址即可,如有多个,用逗号分隔(注意不要忘了/eureka/后缀)。
需要注意的是每个环境只填入自己环境的eureka服务地址,比如FAT的apollo-configservice是1.1.1.1:8080和2.2.2.2:8080,UAT的apollo-configservice是3.3.3.3:8080和4.4.4.4:8080,PRO的apollo-configservice是5.5.5.5:8080和6.6.6.6:8080,那么:
1. 在FAT环境的ApolloConfigDB.ServerConfig表中设置eureka.service.url为:
```
http://1.1.1.1:8080/eureka/,http://2.2.2.2:8080/eureka/
```
2. 在UAT环境的ApolloConfigDB.ServerConfig表中设置eureka.service.url为:
```
http://3.3.3.3:8080/eureka/,http://4.4.4.4:8080/eureka/
```
3. 在PRO环境的ApolloConfigDB.ServerConfig表中设置eureka.service.url为:
```
http://5.5.5.5:8080/eureka/,http://6.6.6.6:8080/eureka/
```
>注1:这里需要填写本环境中全部的eureka服务地址,因为eureka需要互相复制注册信息
>注2:如果希望将Config Service和Admin Service注册到公司统一的Eureka上,可以参考[部署&开发遇到的常见问题 - 将Config Service和Admin Service注册到单独的Eureka Server上](zh/faq/common-issues-in-deployment-and-development-phase#_8-将config-service和admin-service注册到单独的eureka-server上)章节
>注3:在多机房部署时,往往希望config service和admin service只向同机房的eureka注册,要实现这个效果,需要利用`ServerConfig`表中的cluster字段,config service和admin service会读取所在机器的`/opt/settings/server.properties`(Mac/Linux)或`C:\opt\settings\server.properties`(Windows)中的idc属性,如果该idc有对应的eureka.service.url配置,那么就只会向该机房的eureka注册。比如config service和admin service会部署到`SHAOY`和`SHAJQ`两个IDC,那么为了实现这两个机房中的服务只向该机房注册,那么可以在`ServerConfig`表中新增两条记录,分别填入`SHAOY`和`SHAJQ`两个机房的eureka地址即可,`default` cluster的记录可以保留,如果有config service和admin service不是部署在`SHAOY`和`SHAJQ`这两个机房的,就会使用这条默认配置。
| Key |Cluster | Value | Comment |
|--------------------|-----------|-------------------------------|---------------------|
| eureka.service.url | default | http://1.1.1.1:8080/eureka/ | 默认的Eureka服务Url |
| eureka.service.url | SHAOY | http://2.2.2.2:8080/eureka/ | SHAOY的Eureka服务Url |
| eureka.service.url | SHAJQ | http://3.3.3.3:8080/eureka/ | SHAJQ的Eureka服务Url |
### 3.2.2 namespace.lock.switch - 一次发布只能有一个人修改开关,用于发布审核
这是一个功能开关,如果配置为true的话,那么一次配置发布只能是一个人修改,另一个发布。
> 生产环境建议开启此选项
### 3.2.3 config-service.cache.enabled - 是否开启配置缓存
这是一个功能开关,如果配置为true的话,config service会缓存加载过的配置信息,从而加快后续配置获取性能。
默认为false,开启前请先评估总配置大小并调整config service内存配置。
> 开启缓存后必须确保应用中配置的app.id大小写正确,否则将获取不到正确的配置
### 3.2.4 item.key.length.limit - 配置项 key 最大长度限制
默认配置是128。
### 3.2.5 item.value.length.limit - 配置项 value 最大长度限制
默认配置是20000。
### 3.2.6 admin-service.access.control.enabled - 配置apollo-adminservice是否开启访问控制
> 适用于1.7.1及以上版本
默认为false,如果配置为true,那么apollo-portal就需要[正确配置](#_3112-admin-serviceaccesstokens-设置apollo-portal访问各环境apollo-adminservice所需的access-token)访问该环境的access token,否则访问会被拒绝
### 3.2.7 admin-service.access.tokens - 配置允许访问apollo-adminservice的access token列表
> 适用于1.7.1及以上版本
如果该配置项为空,那么访问控制不会生效。如果允许多个token,token 之间以英文逗号分隔
样例:
```properties
admin-service.access.tokens=098f6bcd4621d373cade4e832627b4f6
admin-service.access.tokens=098f6bcd4621d373cade4e832627b4f6,ad0234829205b9033196ba818f7a872b
``` | 本文档介绍了如何按照分布式部署的方式编译、打包、部署Apollo配置中心,从而可以在开发、测试、生产等环境分别部署运行。
> 如果只是需要在本地快速部署试用Apollo的话,可以参考[Quick Start](zh/deployment/quick-start)
#
# 一、准备工作
## 1.1 运行时环境
### 1.1.1 OS
服务端基于Spring Boot,启动脚本理论上支持所有Linux发行版,建议[CentOS 7](https://www.centos.org/)。
### 1.1.2 Java
* Apollo服务端:1.8+
* Apollo客户端:1.7+
由于需要同时运行服务端和客户端,所以建议安装Java 1.8+。
>对于Apollo客户端,运行时环境只需要1.7+即可。
>注:对于Apollo客户端,如果有需要的话,可以做少量代码修改来降级到Java 1.6,详细信息可以参考[Issue 483](https://github.com/ctripcorp/apollo/issues/483)
在配置好后,可以通过如下命令检查:
```sh
java -version
```
样例输出:
```sh
java version "1.8.0_74"
Java(TM) SE Runtime Environment (build 1.8.0_74-b02)
Java HotSpot(TM) 64-Bit Server VM (build 25.74-b02, mixed mode)
```
## 1.2 MySQL
* 版本要求:5.6.5+
Apollo的表结构对`timestamp`使用了多个default声明,所以需要5.6.5以上版本。
连接上MySQL后,可以通过如下命令检查:
```sql
SHOW VARIABLES WHERE Variable_name = 'version';
```
| Variable_name | Value |
|---------------|--------|
| version | 5.7.11 |
> 注1:MySQL版本可以降级到5.5,详见[mysql 依赖降级讨论](https://github.com/ctripcorp/apollo/issues/481)。
> 注2:如果希望使用Oracle的话,可以参考[vanpersl](https://github.com/vanpersl)在Apollo 0.8.0基础上开发的[Oracle适配代码](https://github.com/ctripcorp/apollo/compare/v0.8.0...vanpersl:db-oracle),Oracle版本为10.2.0.1.0。
> 注3:如果希望使用Postgres的话,可以参考[oaksharks](https://github.com/oaksharks)在Apollo 0.9.1基础上开发的[Pg适配代码](https://github.com/oaksharks/apollo/compare/ac10768ee2e11c488523ca0e845984f6f71499ac...oaksharks:pg),Postgres的版本为9.3.20,也可以参考[xiao0yy](https://github.com/xiao0yy)在Apollo 0.10.2基础上开发的[Pg适配代码](https://github.com/ctripcorp/apollo/issues/1293),Postgres的版本为9.5。
## 1.3 环境
分布式部署需要事先确定部署的环境以及部署方式。
Apollo目前支持以下环境:
* DEV
* 开发环境
* FAT
* 测试环境,相当于alpha环境(功能测试)
* UAT
* 集成环境,相当于beta环境(回归测试)
* PRO
* 生产环境
> 如果希望添加自定义的环境名称,具体步骤可以参考[Portal如何增加环境](zh/faq/common-issues-in-deployment-and-development-phase?id=_4-portal如何增加环境?)
以ctrip为例,我们的部署策略如下:

* Portal部署在生产环境的机房,通过它来直接管理FAT、UAT、PRO等环境的配置
* Meta Server、Config Service和Admin Service在每个环境都单独部署,使用独立的数据库
* Meta Server、Config Service和Admin Service在生产环境部署在两个机房,实现双活
* Meta Server和Config Service部署在同一个JVM进程内,Admin Service部署在同一台服务器的另一个JVM进程内
另外也可以参考下[@lyliyongblue](https://github.com/lyliyongblue) 贡献的样例部署图(建议右键新窗口打开看大图):

## 1.4 网络策略
分布式部署的时候,`apollo-configservice`和`apollo-adminservice`需要把自己的IP和端口注册到Meta Server(apollo-configservice本身)。
Apollo客户端和Portal会从Meta Server获取服务的地址(IP+端口),然后通过服务地址直接访问。
需要注意的是,`apollo-configservice`和`apollo-adminservice`是基于内网可信网络设计的,所以出于安全考虑,**请不要将`apollo-configservice`和`apollo-adminservice`直接暴露在公网**。
所以如果实际部署的机器有多块网卡(如docker),或者存在某些网卡的IP是Apollo客户端和Portal无法访问的(如网络安全限制),那么我们就需要在`apollo-configservice`和`apollo-adminservice`中做相关配置来解决连通性问题。
### 1.4.1 忽略某些网卡
可以分别修改`apollo-configservice`和`apollo-adminservice`的startup.sh,通过JVM System Property传入-D参数,也可以通过OS Environment Variable传入,下面的例子会把`docker0`和`veth`开头的网卡在注册到Eureka时忽略掉。
JVM System Property示例:
```properties
-Dspring.cloud.inetutils.ignoredInterfaces[0]=docker0
-Dspring.cloud.inetutils.ignoredInterfaces[1]=veth.*
```
OS Environment Variable示例:
```properties
SPRING_CLOUD_INETUTILS_IGNORED_INTERFACES[0]=docker0
SPRING_CLOUD_INETUTILS_IGNORED_INTERFACES[1]=veth.*
```
### 1.4.2 指定要注册的IP
可以分别修改`apollo-configservice`和`apollo-adminservice`的startup.sh,通过JVM System Property传入-D参数,也可以通过OS Environment Variable传入,下面的例子会指定注册的IP为`1.2.3.4`。
JVM System Property示例:
```properties
-Deureka.instance.ip-address=1.2.3.4
```
OS Environment Variable示例:
```properties
EUREKA_INSTANCE_IP_ADDRESS=1.2.3.4
```
### 1.4.3 指定要注册的URL
可以分别修改`apollo-configservice`和`apollo-adminservice`的startup.sh,通过JVM System Property传入-D参数,也可以通过OS Environment Variable传入,下面的例子会指定注册的URL为`http://1.2.3.4:8080`。
JVM System Property示例:
```properties
-Deureka.instance.homePageUrl=http://1.2.3.4:8080
-Deureka.instance.preferIpAddress=false
```
OS Environment Variable示例:
```properties
EUREKA_INSTANCE_HOME_PAGE_URL=http://1.2.3.4:8080
EUREKA_INSTANCE_PREFER_IP_ADDRESS=false
```
### 1.4.4 直接指定apollo-configservice地址
如果Apollo部署在公有云上,本地开发环境无法连接,但又需要做开发测试的话,客户端可以升级到0.11.0版本及以上,然后配置[跳过Apollo Meta Server服务发现](zh/usage/java-sdk-user-guide#_1222-跳过apollo-meta-server服务发现)
# 二、部署步骤
部署步骤总体还是比较简单的,Apollo的唯一依赖是数据库,所以需要首先把数据库准备好,然后根据实际情况,选择不同的部署方式:
> [@lingjiaju](https://github.com/lingjiaju)录制了一系列Apollo快速上手视频,如果看文档觉得略繁琐的话,不妨可以先看一下他的[视频教程](https://pan.baidu.com/s/1blv87EOZS77NWT8Amkijkw#list/path=%2F)。
> 如果部署过程中遇到了问题,可以参考[部署&开发遇到的常见问题](zh/faq/common-issues-in-deployment-and-development-phase),一般都能找到答案。
## 2.1 创建数据库
Apollo服务端共需要两个数据库:`ApolloPortalDB`和`ApolloConfigDB`,我们把数据库、表的创建和样例数据都分别准备了sql文件,只需要导入数据库即可。
需要注意的是ApolloPortalDB只需要在生产环境部署一个即可,而ApolloConfigDB需要在每个环境部署一套,如fat、uat和pro分别部署3套ApolloConfigDB。
> 注意:如果你本地已经创建过Apollo数据库,请注意备份数据。我们准备的sql文件会清空Apollo相关的表。
### 2.1.1 创建ApolloPortalDB
可以根据实际情况选择通过手动导入SQL或是通过[Flyway](https://flywaydb.org/)自动导入SQL创建。
#### 2.1.1.1 手动导入SQL创建
通过各种MySQL客户端导入[apolloportaldb.sql](https://github.com/ctripcorp/apollo/blob/master/scripts/sql/apolloportaldb.sql)即可。
以MySQL原生客户端为例:
```sql
source /your_local_path/scripts/sql/apolloportaldb.sql
```
#### 2.1.1.2 通过Flyway导入SQL创建
> 需要1.3.0及以上版本
1. 根据实际情况修改[flyway-portaldb.properties](https://github.com/ctripcorp/apollo/blob/master/scripts/flyway/flyway-portaldb.properties)中的`flyway.user`、`flyway.password`和`flyway.url`配置
2. 在apollo项目根目录下执行`mvn -N -Pportaldb flyway:migrate`
#### 2.1.1.3 验证
导入成功后,可以通过执行以下sql语句来验证:
```sql
select `Id`, `Key`, `Value`, `Comment` from `ApolloPortalDB`.`ServerConfig` limit 1;
```
| Id | Key | Value | Comment |
|----|--------------------|-------|------------------|
| 1 | apollo.portal.envs | dev | 可支持的环境列表 |
> 注:ApolloPortalDB只需要在生产环境部署一个即可
### 2.1.2 创建ApolloConfigDB
可以根据实际情况选择通过手动导入SQL或是通过[Flyway](https://flywaydb.org/)自动导入SQL创建。
#### 2.1.2.1 手动导入SQL
通过各种MySQL客户端导入[apolloconfigdb.sql](https://github.com/ctripcorp/apollo/blob/master/scripts/sql/apolloconfigdb.sql)即可。
以MySQL原生客户端为例:
```sql
source /your_local_path/scripts/sql/apolloconfigdb.sql
```
#### 2.1.2.2 通过Flyway导入SQL
> 需要1.3.0及以上版本
1. 根据实际情况修改[flyway-configdb.properties](https://github.com/ctripcorp/apollo/blob/master/scripts/flyway/flyway-configdb.properties)中的`flyway.user`、`flyway.password`和`flyway.url`配置
2. 在apollo项目根目录下执行`mvn -N -Pconfigdb flyway:migrate`
#### 2.1.2.3 验证
导入成功后,可以通过执行以下sql语句来验证:
```sql
select `Id`, `Key`, `Value`, `Comment` from `ApolloConfigDB`.`ServerConfig` limit 1;
```
| Id | Key | Value | Comment |
|----|--------------------|-------------------------------|---------------|
| 1 | eureka.service.url | http://127.0.0.1:8080/eureka/ | Eureka服务Url |
> 注:ApolloConfigDB需要在每个环境部署一套,如fat、uat和pro分别部署3套ApolloConfigDB
#### 2.1.2.4 从别的环境导入ApolloConfigDB的项目数据
如果是全新部署的Apollo配置中心,请忽略此步。
如果不是全新部署的Apollo配置中心,比如已经使用了一段时间,这时在Apollo配置中心已经创建了不少项目以及namespace等,那么在新环境中的ApolloConfigDB中需要从其它正常运行的环境中导入必要的项目数据。
主要涉及ApolloConfigDB的下面4张表,下面同时附上需要导入的数据查询语句:
1. App
* 导入全部的App
* 如:insert into `新环境的ApolloConfigDB`.`App` select * from `其它环境的ApolloConfigDB`.`App` where `IsDeleted` = 0;
2. AppNamespace
* 导入全部的AppNamespace
* 如:insert into `新环境的ApolloConfigDB`.`AppNamespace` select * from `其它环境的ApolloConfigDB`.`AppNamespace` where `IsDeleted` = 0;
3. Cluster
* 导入默认的default集群
* 如:insert into `新环境的ApolloConfigDB`.`Cluster` select * from `其它环境的ApolloConfigDB`.`Cluster` where `Name` = 'default' and `IsDeleted` = 0;
4. Namespace
* 导入默认的default集群中的namespace
* 如:insert into `新环境的ApolloConfigDB`.`Namespace` select * from `其它环境的ApolloConfigDB`.`Namespace` where `ClusterName` = 'default' and `IsDeleted` = 0;
同时也别忘了通知用户在新的环境给自己的项目设置正确的配置信息,尤其是一些影响面比较大的公共namespace配置。
> 如果是为正在运行的环境迁移数据,建议迁移完重启一下config service,因为config service中有appnamespace的缓存数据
### 2.1.3 调整服务端配置
Apollo自身的一些配置是放在数据库里面的,所以需要针对实际情况做一些调整,具体参数说明请参考[三、服务端配置说明](#三、服务端配置说明)。
大部分配置可以先使用默认值,不过 [apollo.portal.envs](#_311-apolloportalenvs-可支持的环境列表) 和 [eureka.service.url](#_321-eurekaserviceurl-eureka服务url) 请务必配置正确后再进行下面的部署步骤。
## 2.2 虚拟机/物理机部署
### 2.2.1 获取安装包
可以通过两种方式获取安装包:
1. 直接下载安装包
* 从[GitHub Release](https://github.com/ctripcorp/apollo/releases)页面下载预先打好的安装包
* 如果对Apollo的代码没有定制需求,建议使用这种方式,可以省去本地打包的过程
2. 通过源码构建
* 从[GitHub Release](https://github.com/ctripcorp/apollo/releases)页面下载Source code包或直接clone[源码](https://github.com/ctripcorp/apollo)后在本地构建
* 如果需要对Apollo的做定制开发,需要使用这种方式
#### 2.2.1.1 直接下载安装包
##### 2.2.1.1.1 获取apollo-configservice、apollo-adminservice、apollo-portal安装包
从[GitHub Release](https://github.com/ctripcorp/apollo/releases)页面下载最新版本的`apollo-configservice-x.x.x-github.zip`、`apollo-adminservice-x.x.x-github.zip`和`apollo-portal-x.x.x-github.zip`即可。
##### 2.2.1.1.2 配置数据库连接信息
Apollo服务端需要知道如何连接到你前面创建的数据库,数据库连接串信息位于上一步下载的压缩包中的`config/application-github.properties`中。
###### 2.2.1.1.2.1 配置apollo-configservice的数据库连接信息
1. 解压`apollo-configservice-x.x.x-github.zip`
2. 用程序员专用编辑器(如vim,notepad++,sublime等)打开`config`目录下的`application-github.properties`文件
3. 填写正确的ApolloConfigDB数据库连接串信息,注意用户名和密码后面不要有空格!
4. 修改完的效果如下:
```properties
# DataSource
spring.datasource.url = jdbc:mysql://localhost:3306/ApolloConfigDB?useSSL=false&characterEncoding=utf8
spring.datasource.username = someuser
spring.datasource.password = somepwd
```
> 注:由于ApolloConfigDB在每个环境都有部署,所以对不同的环境config-service需要配置对应环境的数据库参数
###### 2.2.1.1.2.2 配置apollo-adminservice的数据库连接信息
1. 解压`apollo-adminservice-x.x.x-github.zip`
2. 用程序员专用编辑器(如vim,notepad++,sublime等)打开`config`目录下的`application-github.properties`文件
3. 填写正确的ApolloConfigDB数据库连接串信息,注意用户名和密码后面不要有空格!
4. 修改完的效果如下:
```properties
# DataSource
spring.datasource.url = jdbc:mysql://localhost:3306/ApolloConfigDB?useSSL=false&characterEncoding=utf8
spring.datasource.username = someuser
spring.datasource.password = somepwd
```
> 注:由于ApolloConfigDB在每个环境都有部署,所以对不同的环境admin-service需要配置对应环境的数据库参数
###### 2.2.1.1.2.3 配置apollo-portal的数据库连接信息
1. 解压`apollo-portal-x.x.x-github.zip`
2. 用程序员专用编辑器(如vim,notepad++,sublime等)打开`config`目录下的`application-github.properties`文件
3. 填写正确的ApolloPortalDB数据库连接串信息,注意用户名和密码后面不要有空格!
4. 修改完的效果如下:
```properties
# DataSource
spring.datasource.url = jdbc:mysql://localhost:3306/ApolloPortalDB?useSSL=false&characterEncoding=utf8
spring.datasource.username = someuser
spring.datasource.password = somepwd
```
###### 2.2.1.1.2.4 配置apollo-portal的meta service信息
Apollo Portal需要在不同的环境访问不同的meta service(apollo-configservice)地址,所以我们需要在配置中提供这些信息。默认情况下,meta service和config service是部署在同一个JVM进程,所以meta service的地址就是config service的地址。
> 对于1.6.0及以上版本,可以通过ApolloPortalDB.ServerConfig中的配置项来配置Meta Service地址,详见[apollo.portal.meta.servers - 各环境Meta Service列表](#_312-apolloportalmetaservers-各环境meta-service列表)
使用程序员专用编辑器(如vim,notepad++,sublime等)打开`apollo-portal-x.x.x-github.zip`中`config`目录下的`apollo-env.properties`文件。
假设DEV的apollo-configservice未绑定域名,地址是1.1.1.1:8080,FAT的apollo-configservice绑定了域名apollo.fat.xxx.com,UAT的apollo-configservice绑定了域名apollo.uat.xxx.com,PRO的apollo-configservice绑定了域名apollo.xxx.com,那么可以如下修改各环境meta service服务地址,格式为`${env}.meta=http://${config-service-url:port}`,如果某个环境不需要,也可以直接删除对应的配置项(如lpt.meta):
```sh
dev.meta=http://1.1.1.1:8080
fat.meta=http://apollo.fat.xxx.com
uat.meta=http://apollo.uat.xxx.com
pro.meta=http://apollo.xxx.com
```
除了通过`apollo-env.properties`方式配置meta service以外,apollo也支持在运行时指定meta service(优先级比`apollo-env.properties`高):
1. 通过Java System Property `${env}_meta`
* 可以通过Java的System Property `${env}_meta`来指定
* 如`java -Ddev_meta=http://config-service-url -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("dev_meta", "http://config-service-url");`
2. 通过操作系统的System Environment`${ENV}_META`
* 如`DEV_META=http://config-service-url`
* 注意key为全大写,且中间是`_`分隔
>注1: 为了实现meta service的高可用,推荐通过SLB(Software Load Balancer)做动态负载均衡
>注2: meta service地址也可以填入IP,0.11.0版本之前只支持填入一个IP。从0.11.0版本开始支持填入以逗号分隔的多个地址([PR #1214](https://github.com/ctripcorp/apollo/pull/1214)),如`http://1.1.1.1:8080,http://2.2.2.2:8080`,不过生产环境还是建议使用域名(走slb),因为机器扩容、缩容等都可能导致IP列表的变化。
#### 2.2.1.2 通过源码构建
##### 2.2.1.2.1 配置数据库连接信息
Apollo服务端需要知道如何连接到你前面创建的数据库,所以需要编辑[scripts/build.sh](https://github.com/ctripcorp/apollo/blob/master/scripts/build.sh),修改ApolloPortalDB和ApolloConfigDB相关的数据库连接串信息。
> 注意:填入的用户需要具备对ApolloPortalDB和ApolloConfigDB数据的读写权限。
```sh
#apollo config db info
apollo_config_db_url=jdbc:mysql://localhost:3306/ApolloConfigDB?useSSL=false&characterEncoding=utf8
apollo_config_db_username=用户名
apollo_config_db_password=密码(如果没有密码,留空即可)
# apollo portal db info
apollo_portal_db_url=jdbc:mysql://localhost:3306/ApolloPortalDB?useSSL=false&characterEncoding=utf8
apollo_portal_db_username=用户名
apollo_portal_db_password=密码(如果没有密码,留空即可)
```
> 注1:由于ApolloConfigDB在每个环境都有部署,所以对不同的环境config-service和admin-service需要使用不同的数据库参数打不同的包,portal只需要打一次包即可
> 注2:如果不想config-service和admin-service每个环境打一个包的话,也可以通过运行时传入数据库连接串信息实现,具体可以参考 [Issue 869](https://github.com/ctripcorp/apollo/issues/869)
> 注3:每个环境都需要独立部署一套config-service、admin-service和ApolloConfigDB
##### 2.2.1.2.2 配置各环境meta service地址
Apollo Portal需要在不同的环境访问不同的meta service(apollo-configservice)地址,所以需要在打包时提供这些信息。
假设DEV的apollo-configservice未绑定域名,地址是1.1.1.1:8080,FAT的apollo-configservice绑定了域名apollo.fat.xxx.com,UAT的apollo-configservice绑定了域名apollo.uat.xxx.com,PRO的apollo-configservice绑定了域名apollo.xxx.com,那么编辑[scripts/build.sh](https://github.com/ctripcorp/apollo/blob/master/scripts/build.sh),如下修改各环境meta service服务地址,格式为`${env}_meta=http://${config-service-url:port}`,如果某个环境不需要,也可以直接删除对应的配置项:
```sh
dev_meta=http://1.1.1.1:8080
fat_meta=http://apollo.fat.xxx.com
uat_meta=http://apollo.uat.xxx.com
pro_meta=http://apollo.xxx.com
META_SERVERS_OPTS="-Ddev_meta=$dev_meta -Dfat_meta=$fat_meta -Duat_meta=$uat_meta -Dpro_meta=$pro_meta"
```
除了在打包时配置meta service以外,apollo也支持在运行时指定meta service:
1. 通过Java System Property `${env}_meta`
* 可以通过Java的System Property `${env}_meta`来指定
* 如`java -Ddev_meta=http://config-service-url -jar xxx.jar`
* 也可以通过程序指定,如`System.setProperty("dev_meta", "http://config-service-url");`
2. 通过操作系统的System Environment`${ENV}_META`
* 如`DEV_META=http://config-service-url`
* 注意key为全大写,且中间是`_`分隔
>注1: 为了实现meta service的高可用,推荐通过SLB(Software Load Balancer)做动态负载均衡
>注2: meta service地址也可以填入IP,0.11.0版本之前只支持填入一个IP。从0.11.0版本开始支持填入以逗号分隔的多个地址([PR #1214](https://github.com/ctripcorp/apollo/pull/1214)),如`http://1.1.1.1:8080,http://2.2.2.2:8080`,不过生产环境还是建议使用域名(走slb),因为机器扩容、缩容等都可能导致IP列表的变化。
##### 2.2.1.2.3 执行编译、打包
做完上述配置后,就可以执行编译和打包了。
> 注:初次编译会从Maven中央仓库下载不少依赖,如果网络情况不佳时很容易出错,建议使用国内的Maven仓库源,比如[阿里云Maven镜像](http://www.cnblogs.com/geektown/p/5705405.html)
```sh
./build.sh
```
该脚本会依次打包apollo-configservice, apollo-adminservice, apollo-portal。
> 注:由于ApolloConfigDB在每个环境都有部署,所以对不同环境的config-service和admin-service需要使用不同的数据库连接信息打不同的包,portal只需要打一次包即可
##### 2.2.1.2.4 获取apollo-configservice安装包
位于`apollo-configservice/target/`目录下的`apollo-configservice-x.x.x-github.zip`
需要注意的是由于ApolloConfigDB在每个环境都有部署,所以对不同环境的config-service需要使用不同的数据库参数打不同的包后分别部署
##### 2.2.1.2.5 获取apollo-adminservice安装包
位于`apollo-adminservice/target/`目录下的`apollo-adminservice-x.x.x-github.zip`
需要注意的是由于ApolloConfigDB在每个环境都有部署,所以对不同环境的admin-service需要使用不同的数据库参数打不同的包后分别部署
##### 2.2.1.2.6 获取apollo-portal安装包
位于`apollo-portal/target/`目录下的`apollo-portal-x.x.x-github.zip`
##### 2.2.1.2.7 启用外部nacos服务注册中心替换内置eureka
1. 修改build.sh/build.bat,将config-service和admin-service的maven编译命令更改为
```shell
mvn clean package -Pgithub,nacos-discovery -DskipTests -pl apollo-configservice,apollo-adminservice -am -Dapollo_profile=github,nacos-discovery -Dspring_datasource_url=$apollo_config_db_url -Dspring_datasource_username=$apollo_config_db_username -Dspring_datasource_password=$apollo_config_db_password
```
2. 分别修改apollo-configservice和apollo-adminservice安装包中config目录下的application-github.properties,配置nacos服务器地址
```properties
nacos.discovery.server-addr=127.0.0.1:8848
# 更多 nacos 配置
nacos.discovery.access-key=
nacos.discovery.username=
nacos.discovery.password=
nacos.discovery.secret-key=
nacos.discovery.namespace=
nacos.discovery.context-path=
```
##### 2.2.1.2.8 启用外部Consul服务注册中心替换内置eureka
1. 修改build.sh/build.bat,将config-service和admin-service的maven编译命令更改为
```shell
mvn clean package -Pgithub -DskipTests -pl apollo-configservice,apollo-adminservice -am -Dapollo_profile=github,consul-discovery -Dspring_datasource_url=$apollo_config_db_url -Dspring_datasource_username=$apollo_config_db_username -Dspring_datasource_password=$apollo_config_db_password
```
2. 分别修改apollo-configservice和apollo-adminservice安装包中config目录下的application-github.properties,配置consul服务器地址
```properties
spring.cloud.consul.host=127.0.0.1
spring.cloud.consul.port=8500
```
### 2.2.2 部署Apollo服务端
#### 2.2.2.1 部署apollo-configservice
将对应环境的`apollo-configservice-x.x.x-github.zip`上传到服务器上,解压后执行scripts/startup.sh即可。如需停止服务,执行scripts/shutdown.sh.
记得在scripts/startup.sh中按照实际的环境设置一个JVM内存,以下是我们的默认设置,供参考:
```bash
export JAVA_OPTS="-server -Xms6144m -Xmx6144m -Xss256k -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=384m -XX:NewSize=4096m -XX:MaxNewSize=4096m -XX:SurvivorRatio=18"
```
> 注1:如果需要修改JVM参数,可以修改scripts/startup.sh的`JAVA_OPTS`部分。
> 注2:如要调整服务的日志输出路径,可以修改scripts/startup.sh和apollo-configservice.conf中的`LOG_DIR`。
> 注3:如要调整服务的监听端口,可以修改scripts/startup.sh中的`SERVER_PORT`。另外apollo-configservice同时承担meta server职责,如果要修改端口,注意要同时ApolloConfigDB.ServerConfig表中的`eureka.service.url`配置项以及apollo-portal和apollo-client中的使用到的meta server信息,详见:[2.2.1.1.2.4 配置apollo-portal的meta service信息](#_221124-配置apollo-portal的meta-service信息)和[1.2.2 Apollo Meta Server](zh/usage/java-sdk-user-guide#_122-apollo-meta-server)。
> 注4:如果ApolloConfigDB.ServerConfig的eureka.service.url只配了当前正在启动的机器的话,在启动apollo-configservice的过程中会在日志中输出eureka注册失败的信息,如`com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused`。需要注意的是,这个是预期的情况,因为apollo-configservice需要向Meta Server(它自己)注册服务,但是因为在启动过程中,自己还没起来,所以会报这个错。后面会进行重试的动作,所以等自己服务起来后就会注册正常了。
> 注5:如果你看到了这里,相信你一定是一个细心阅读文档的人,而且离成功就差一点点了,继续加油,应该很快就能完成Apollo的分布式部署了!不过你是否有感觉Apollo的分布式部署步骤有点繁琐?是否有啥建议想要和作者说?如果答案是肯定的话,请移步 [#1424](https://github.com/ctripcorp/apollo/issues/1424),期待你的建议!
#### 2.2.2.2 部署apollo-adminservice
将对应环境的`apollo-adminservice-x.x.x-github.zip`上传到服务器上,解压后执行scripts/startup.sh即可。如需停止服务,执行scripts/shutdown.sh.
记得在scripts/startup.sh中按照实际的环境设置一个JVM内存,以下是我们的默认设置,供参考:
```bash
export JAVA_OPTS="-server -Xms2560m -Xmx2560m -Xss256k -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=384m -XX:NewSize=1024m -XX:MaxNewSize=1024m -XX:SurvivorRatio=22"
```
> 注1:如果需要修改JVM参数,可以修改scripts/startup.sh的`JAVA_OPTS`部分。
> 注2:如要调整服务的日志输出路径,可以修改scripts/startup.sh和apollo-adminservice.conf中的`LOG_DIR`。
> 注3:如要调整服务的监听端口,可以修改scripts/startup.sh中的`SERVER_PORT`。
#### 2.2.2.3 部署apollo-portal
将`apollo-portal-x.x.x-github.zip`上传到服务器上,解压后执行scripts/startup.sh即可。如需停止服务,执行scripts/shutdown.sh.
记得在startup.sh中按照实际的环境设置一个JVM内存,以下是我们的默认设置,供参考:
```bash
export JAVA_OPTS="-server -Xms4096m -Xmx4096m -Xss256k -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=384m -XX:NewSize=1536m -XX:MaxNewSize=1536m -XX:SurvivorRatio=22"
```
> 注1:如果需要修改JVM参数,可以修改scripts/startup.sh的`JAVA_OPTS`部分。
> 注2:如要调整服务的日志输出路径,可以修改scripts/startup.sh和apollo-portal.conf中的`LOG_DIR`。
> 注3:如要调整服务的监听端口,可以修改scripts/startup.sh中的`SERVER_PORT`。
## 2.3 Docker部署
### 2.3.1 1.7.0及以上版本
Apollo 1.7.0版本开始会默认上传Docker镜像到[Docker Hub](https://hub.docker.com/u/apolloconfig),可以按照如下步骤获取
#### 2.3.1.1 Apollo Config Service
##### 2.3.1.1.1 获取镜像
```bash
docker pull apolloconfig/apollo-configservice:${version}
```
##### 2.3.1.1.2 运行镜像
示例:
```bash
docker run -p 8080:8080 \
-e SPRING_DATASOURCE_URL="jdbc:mysql://fill-in-the-correct-server:3306/ApolloConfigDB?characterEncoding=utf8" \
-e SPRING_DATASOURCE_USERNAME=FillInCorrectUser -e SPRING_DATASOURCE_PASSWORD=FillInCorrectPassword \
-d -v /tmp/logs:/opt/logs --name apollo-configservice apolloconfig/apollo-configservice:${version}
```
参数说明:
* SPRING_DATASOURCE_URL: 对应环境ApolloConfigDB的地址
* SPRING_DATASOURCE_USERNAME: 对应环境ApolloConfigDB的用户名
* SPRING_DATASOURCE_PASSWORD: 对应环境ApolloConfigDB的密码
#### 2.3.1.2 Apollo Admin Service
##### 2.3.1.2.1 获取镜像
```bash
docker pull apolloconfig/apollo-adminservice:${version}
```
##### 2.3.1.2.2 运行镜像
示例:
```bash
docker run -p 8090:8090 \
-e SPRING_DATASOURCE_URL="jdbc:mysql://fill-in-the-correct-server:3306/ApolloConfigDB?characterEncoding=utf8" \
-e SPRING_DATASOURCE_USERNAME=FillInCorrectUser -e SPRING_DATASOURCE_PASSWORD=FillInCorrectPassword \
-d -v /tmp/logs:/opt/logs --name apollo-adminservice apolloconfig/apollo-adminservice:${version}
```
参数说明:
* SPRING_DATASOURCE_URL: 对应环境ApolloConfigDB的地址
* SPRING_DATASOURCE_USERNAME: 对应环境ApolloConfigDB的用户名
* SPRING_DATASOURCE_PASSWORD: 对应环境ApolloConfigDB的密码
#### 2.3.1.3 Apollo Portal
##### 2.3.1.3.1 获取镜像
```bash
docker pull apolloconfig/apollo-portal:${version}
```
##### 2.3.1.3.2 运行镜像
示例:
```bash
docker run -p 8070:8070 \
-e SPRING_DATASOURCE_URL="jdbc:mysql://fill-in-the-correct-server:3306/ApolloPortalDB?characterEncoding=utf8" \
-e SPRING_DATASOURCE_USERNAME=FillInCorrectUser -e SPRING_DATASOURCE_PASSWORD=FillInCorrectPassword \
-e APOLLO_PORTAL_ENVS=dev,pro \
-e DEV_META=http://fill-in-dev-meta-server:8080 -e PRO_META=http://fill-in-pro-meta-server:8080 \
-d -v /tmp/logs:/opt/logs --name apollo-portal apolloconfig/apollo-portal:${version}
```
参数说明:
* SPRING_DATASOURCE_URL: 对应环境ApolloPortalDB的地址
* SPRING_DATASOURCE_USERNAME: 对应环境ApolloPortalDB的用户名
* SPRING_DATASOURCE_PASSWORD: 对应环境ApolloPortalDB的密码
* APOLLO_PORTAL_ENVS(可选): 对应ApolloPortalDB中的[apollo.portal.envs](#_311-apolloportalenvs-可支持的环境列表)配置项,如果没有在数据库中配置的话,可以通过此环境参数配置
* DEV_META/PRO_META(可选): 配置对应环境的Meta Service地址,以${ENV}_META命名,需要注意的是如果配置了ApolloPortalDB中的[apollo.portal.meta.servers](#_312-apolloportalmetaservers-各环境meta-service列表)配置,则以apollo.portal.meta.servers中的配置为准
#### 2.3.1.4 通过源码构建 Docker 镜像
如果修改了 apollo 服务端的代码,希望通过源码构建 Docker 镜像,可以参考下面的步骤:
1. 通过源码构建安装包:`./scripts/build.sh`
2. 构建 Docker 镜像:`mvn docker:build -pl apollo-configservice,apollo-adminservice,apollo-portal`
### 2.3.2 1.7.0之前的版本
Apollo项目已经自带了Docker file,可以参照[2.2.1 获取安装包](#_221-获取安装包)配置好安装包后通过下面的文件来打Docker镜像:
1. [apollo-configservice](https://github.com/ctripcorp/apollo/blob/master/apollo-configservice/src/main/docker/Dockerfile)
2. [apollo-adminservice](https://github.com/ctripcorp/apollo/blob/master/apollo-adminservice/src/main/docker/Dockerfile)
3. [apollo-portal](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/docker/Dockerfile)
也可以参考Apollo用户[@kulovecc](https://github.com/kulovecc)的[docker-apollo](https://github.com/kulovecc/docker-apollo)项目和[@idoop](https://github.com/idoop)的[docker-apollo](https://github.com/idoop/docker-apollo)项目。
## 2.4 Kubernetes部署
### 2.4.1 基于Kubernetes原生服务发现
Apollo 1.7.0版本增加了基于Kubernetes原生服务发现的部署模式,由于不再使用内置的Eureka,所以在整体部署上有很大简化,同时也提供了Helm Charts,便于部署。
> 更多设计说明可以参考[#3054](https://github.com/ctripcorp/apollo/issues/3054)。
#### 2.4.1.1 环境要求
- Kubernetes 1.10+
- Helm 3
#### 2.4.1.2 添加Apollo Helm Chart仓库
```bash
$ helm repo add apollo https://www.apolloconfig.com/charts
$ helm search repo apollo
```
#### 2.4.1.3 部署apollo-configservice和apollo-adminservice
##### 2.4.1.3.1 安装apollo-configservice和apollo-adminservice
需要在每个环境中安装apollo-configservice和apollo-adminservice,所以建议在release名称中加入环境信息,例如:`apollo-service-dev`
```bash
$ helm install apollo-service-dev \
--set configdb.host=1.2.3.4 \
--set configdb.userName=apollo \
--set configdb.password=apollo \
--set configdb.service.enabled=true \
--set configService.replicaCount=1 \
--set adminService.replicaCount=1 \
-n your-namespace \
apollo/apollo-service
```
一般部署建议通过 values.yaml 来配置:
```bash
$ helm install apollo-service-dev -f values.yaml -n your-namespace apollo/apollo-service
```
安装完成后会提示对应环境的Meta Server地址,需要记录下来,apollo-portal安装时需要用到:
```bash
Get meta service url for current release by running these commands:
echo http://apollo-service-dev-apollo-configservice:8080
```
> 更多配置项说明可以参考[2.4.1.3.3 配置项说明](#_24133-配置项说明)
##### 2.4.1.3.2 卸载apollo-configservice和apollo-adminservice
例如要卸载`apollo-service-dev`的部署:
```bash
$ helm uninstall -n your-namespace apollo-service-dev
```
##### 2.4.1.3.3 配置项说明
下表列出了apollo-service chart的可配置参数及其默认值:
| Parameter | Description | Default |
|----------------------|---------------------------------------------|---------------------|
| `configdb.host` | The host for apollo config db | `nil` |
| `configdb.port` | The port for apollo config db | `3306` |
| `configdb.dbName` | The database name for apollo config db | `ApolloConfigDB` |
| `configdb.userName` | The user name for apollo config db | `nil` |
| `configdb.password` | The password for apollo config db | `nil` |
| `configdb.connectionStringProperties` | The connection string properties for apollo config db | `characterEncoding=utf8` |
| `configdb.service.enabled` | Whether to create a Kubernetes Service for `configdb.host` or not. Set it to `true` if `configdb.host` is an endpoint outside of the kubernetes cluster | `false` |
| `configdb.service.fullNameOverride` | Override the service name for apollo config db | `nil` |
| `configdb.service.port` | The port for the service of apollo config db | `3306` |
| `configdb.service.type` | The service type of apollo config db: `ClusterIP` or `ExternalName`. If the host is a DNS name, please specify `ExternalName` as the service type, e.g. `xxx.mysql.rds.aliyuncs.com` | `ClusterIP` |
| `configService.fullNameOverride` | Override the deployment name for apollo-configservice | `nil` |
| `configService.replicaCount` | Replica count of apollo-configservice | `2` |
| `configService.containerPort` | Container port of apollo-configservice | `8080` |
| `configService.image.repository` | Image repository of apollo-configservice | `apolloconfig/apollo-configservice` |
| `configService.image.tag` | Image tag of apollo-configservice, e.g. `1.8.0`, leave it to `nil` to use the default version. _(chart version >= 0.2.0)_ | `nil` |
| `configService.image.pullPolicy` | Image pull policy of apollo-configservice | `IfNotPresent` |
| `configService.imagePullSecrets` | Image pull secrets of apollo-configservice | `[]` |
| `configService.service.fullNameOverride` | Override the service name for apollo-configservice | `nil` |
| `configService.service.port` | The port for the service of apollo-configservice | `8080` |
| `configService.service.targetPort` | The target port for the service of apollo-configservice | `8080` |
| `configService.service.type` | The service type of apollo-configservice | `ClusterIP` |
| `configService.ingress.enabled` | Whether to enable the ingress for config-service or not. _(chart version >= 0.2.0)_ | `false` |
| `configService.ingress.annotations` | The annotations of the ingress for config-service. _(chart version >= 0.2.0)_ | `{}` |
| `configService.ingress.hosts.host` | The host of the ingress for config-service. _(chart version >= 0.2.0)_ | `nil` |
| `configService.ingress.hosts.paths` | The paths of the ingress for config-service. _(chart version >= 0.2.0)_ | `[]` |
| `configService.ingress.tls` | The tls definition of the ingress for config-service. _(chart version >= 0.2.0)_ | `[]` |
| `configService.liveness.initialDelaySeconds` | The initial delay seconds of liveness probe | `100` |
| `configService.liveness.periodSeconds` | The period seconds of liveness probe | `10` |
| `configService.readiness.initialDelaySeconds` | The initial delay seconds of readiness probe | `30` |
| `configService.readiness.periodSeconds` | The period seconds of readiness probe | `5` |
| `configService.config.profiles` | specify the spring profiles to activate | `github,kubernetes` |
| `configService.config.configServiceUrlOverride` | Override `apollo.config-service.url`: config service url to be accessed by apollo-client, e.g. `http://apollo-config-service-dev:8080` | `nil` |
| `configService.config.adminServiceUrlOverride` | Override `apollo.admin-service.url`: admin service url to be accessed by apollo-portal, e.g. `http://apollo-admin-service-dev:8090` | `nil` |
| `configService.config.contextPath` | specify the context path, e.g. `/apollo`, then users could access config service via `http://{config_service_address}/apollo`. _(chart version >= 0.2.0)_ | `nil` |
| `configService.env` | Environment variables passed to the container, e.g. <br />`JAVA_OPTS: -Xss256k` | `{}` |
| `configService.strategy` | The deployment strategy of apollo-configservice | `{}` |
| `configService.resources` | The resources definition of apollo-configservice | `{}` |
| `configService.nodeSelector` | The node selector definition of apollo-configservice | `{}` |
| `configService.tolerations` | The tolerations definition of apollo-configservice | `[]` |
| `configService.affinity` | The affinity definition of apollo-configservice | `{}` |
| `adminService.fullNameOverride` | Override the deployment name for apollo-adminservice | `nil` |
| `adminService.replicaCount` | Replica count of apollo-adminservice | `2` |
| `adminService.containerPort` | Container port of apollo-adminservice | `8090` |
| `adminService.image.repository` | Image repository of apollo-adminservice | `apolloconfig/apollo-adminservice` |
| `adminService.image.tag` | Image tag of apollo-adminservice, e.g. `1.8.0`, leave it to `nil` to use the default version. _(chart version >= 0.2.0)_ | `nil` |
| `adminService.image.pullPolicy` | Image pull policy of apollo-adminservice | `IfNotPresent` |
| `adminService.imagePullSecrets` | Image pull secrets of apollo-adminservice | `[]` |
| `adminService.service.fullNameOverride` | Override the service name for apollo-adminservice | `nil` |
| `adminService.service.port` | The port for the service of apollo-adminservice | `8090` |
| `adminService.service.targetPort` | The target port for the service of apollo-adminservice | `8090` |
| `adminService.service.type` | The service type of apollo-adminservice | `ClusterIP` |
| `adminService.ingress.enabled` | Whether to enable the ingress for admin-service or not. _(chart version >= 0.2.0)_ | `false` |
| `adminService.ingress.annotations` | The annotations of the ingress for admin-service. _(chart version >= 0.2.0)_ | `{}` |
| `adminService.ingress.hosts.host` | The host of the ingress for admin-service. _(chart version >= 0.2.0)_ | `nil` |
| `adminService.ingress.hosts.paths` | The paths of the ingress for admin-service. _(chart version >= 0.2.0)_ | `[]` |
| `adminService.ingress.tls` | The tls definition of the ingress for admin-service. _(chart version >= 0.2.0)_ | `[]` |
| `adminService.liveness.initialDelaySeconds` | The initial delay seconds of liveness probe | `100` |
| `adminService.liveness.periodSeconds` | The period seconds of liveness probe | `10` |
| `adminService.readiness.initialDelaySeconds` | The initial delay seconds of readiness probe | `30` |
| `adminService.readiness.periodSeconds` | The period seconds of readiness probe | `5` |
| `adminService.config.profiles` | specify the spring profiles to activate | `github,kubernetes` |
| `adminService.config.contextPath` | specify the context path, e.g. `/apollo`, then users could access admin service via `http://{admin_service_address}/apollo`. _(chart version >= 0.2.0)_ | `nil` |
| `adminService.env` | Environment variables passed to the container, e.g. <br />`JAVA_OPTS: -Xss256k` | `{}` |
| `adminService.strategy` | The deployment strategy of apollo-adminservice | `{}` |
| `adminService.resources` | The resources definition of apollo-adminservice | `{}` |
| `adminService.nodeSelector` | The node selector definition of apollo-adminservice | `{}` |
| `adminService.tolerations` | The tolerations definition of apollo-adminservice | `[]` |
| `adminService.affinity` | The affinity definition of apollo-adminservice | `{}` |
##### 2.4.1.3.4 配置样例
###### 2.4.1.3.4.1 ConfigDB的host是k8s集群外的IP
```yaml
configdb:
host: 1.2.3.4
dbName: ApolloConfigDBName
userName: someUserName
password: somePassword
connectionStringProperties: characterEncoding=utf8&useSSL=false
service:
enabled: true
```
###### 2.4.1.3.4.2 ConfigDB的host是k8s集群外的域名
```yaml
configdb:
host: xxx.mysql.rds.aliyuncs.com
dbName: ApolloConfigDBName
userName: someUserName
password: somePassword
connectionStringProperties: characterEncoding=utf8&useSSL=false
service:
enabled: true
type: ExternalName
```
###### 2.4.1.3.4.3 ConfigDB的host是k8s集群内的一个服务
```yaml
configdb:
host: apollodb-mysql.mysql
dbName: ApolloConfigDBName
userName: someUserName
password: somePassword
connectionStringProperties: characterEncoding=utf8&useSSL=false
```
###### 2.4.1.3.4.4 指定Meta Server返回的apollo-configservice地址
如果apollo-client无法直接访问apollo-configservice的Service(比如不在同一个k8s集群),那么可以参照下面的示例指定Meta Server返回给apollo-client的地址(比如可以通过nodeport访问)
```yaml
configService:
config:
configServiceUrlOverride: http://1.2.3.4:12345
```
###### 2.4.1.3.4.5 指定Meta Server返回的apollo-adminservice地址
如果apollo-portal无法直接访问apollo-adminservice的Service(比如不在同一个k8s集群),那么可以参照下面的示例指定Meta Server返回给apollo-portal的地址(比如可以通过nodeport访问)
```yaml
configService:
config:
adminServiceUrlOverride: http://1.2.3.4:23456
```
###### 2.4.1.3.4.6 以Ingress配置自定义路径`/config`形式暴露apollo-configservice服务
```yaml
# use /config as root, should specify configService.config.contextPath as /config
configService:
config:
contextPath: /config
ingress:
enabled: true
hosts:
- paths:
- /config
```
###### 2.4.1.3.4.7 以Ingress配置自定义路径`/admin`形式暴露apollo-adminservice服务
```yaml
# use /admin as root, should specify adminService.config.contextPath as /admin
adminService:
config:
contextPath: /admin
ingress:
enabled: true
hosts:
- paths:
- /admin
```
#### 2.4.1.4 部署apollo-portal
##### 2.4.1.4.1 安装apollo-portal
假设有dev, pro两个环境,且meta server地址分别为`http://apollo-service-dev-apollo-configservice:8080`和`http://apollo-service-pro-apollo-configservice:8080`:
```bash
$ helm install apollo-portal \
--set portaldb.host=1.2.3.4 \
--set portaldb.userName=apollo \
--set portaldb.password=apollo \
--set portaldb.service.enabled=true \
--set config.envs="dev\,pro" \
--set config.metaServers.dev=http://apollo-service-dev-apollo-configservice:8080 \
--set config.metaServers.pro=http://apollo-service-pro-apollo-configservice:8080 \
--set replicaCount=1 \
-n your-namespace \
apollo/apollo-portal
```
一般部署建议通过 values.yaml 来配置:
```bash
$ helm install apollo-portal -f values.yaml -n your-namespace apollo/apollo-portal
```
> 更多配置项说明可以参考[2.4.1.4.3 配置项说明](#_24143-配置项说明)
##### 2.4.1.4.2 卸载apollo-portal
例如要卸载`apollo-portal`的部署:
```bash
$ helm uninstall -n your-namespace apollo-portal
```
##### 2.4.1.4.3 配置项说明
下表列出了apollo-portal chart的可配置参数及其默认值:
| Parameter | Description | Default |
|----------------------|---------------------------------------------|-----------------------|
| `fullNameOverride` | Override the deployment name for apollo-portal | `nil` |
| `replicaCount` | Replica count of apollo-portal | `2` |
| `containerPort` | Container port of apollo-portal | `8070` |
| `image.repository` | Image repository of apollo-portal | `apolloconfig/apollo-portal` |
| `image.tag` | Image tag of apollo-portal, e.g. `1.8.0`, leave it to `nil` to use the default version. _(chart version >= 0.2.0)_ | `nil` |
| `image.pullPolicy` | Image pull policy of apollo-portal | `IfNotPresent` |
| `imagePullSecrets` | Image pull secrets of apollo-portal | `[]` |
| `service.fullNameOverride` | Override the service name for apollo-portal | `nil` |
| `service.port` | The port for the service of apollo-portal | `8070` |
| `service.targetPort` | The target port for the service of apollo-portal | `8070` |
| `service.type` | The service type of apollo-portal | `ClusterIP` |
| `service.sessionAffinity` | The session affinity for the service of apollo-portal | `ClientIP` |
| `ingress.enabled` | Whether to enable the ingress or not | `false` |
| `ingress.annotations` | The annotations of the ingress | `{}` |
| `ingress.hosts.host` | The host of the ingress | `nil` |
| `ingress.hosts.paths` | The paths of the ingress | `[]` |
| `ingress.tls` | The tls definition of the ingress | `[]` |
| `liveness.initialDelaySeconds` | The initial delay seconds of liveness probe | `100` |
| `liveness.periodSeconds` | The period seconds of liveness probe | `10` |
| `readiness.initialDelaySeconds` | The initial delay seconds of readiness probe | `30` |
| `readiness.periodSeconds` | The period seconds of readiness probe | `5` |
| `env` | Environment variables passed to the container, e.g. <br />`JAVA_OPTS: -Xss256k` | `{}` |
| `strategy` | The deployment strategy of apollo-portal | `{}` |
| `resources` | The resources definition of apollo-portal | `{}` |
| `nodeSelector` | The node selector definition of apollo-portal | `{}` |
| `tolerations` | The tolerations definition of apollo-portal | `[]` |
| `affinity` | The affinity definition of apollo-portal | `{}` |
| `config.profiles` | specify the spring profiles to activate | `github,auth` |
| `config.envs` | specify the env names, e.g. `dev,pro` | `nil` |
| `config.contextPath` | specify the context path, e.g. `/apollo`, then users could access portal via `http://{portal_address}/apollo` | `nil` |
| `config.metaServers` | specify the meta servers, e.g.<br />`dev: http://apollo-configservice-dev:8080`<br />`pro: http://apollo-configservice-pro:8080` | `{}` |
| `config.files` | specify the extra config files for apollo-portal, e.g. `application-ldap.yml` | `{}` |
| `portaldb.host` | The host for apollo portal db | `nil` |
| `portaldb.port` | The port for apollo portal db | `3306` |
| `portaldb.dbName` | The database name for apollo portal db | `ApolloPortalDB` |
| `portaldb.userName` | The user name for apollo portal db | `nil` |
| `portaldb.password` | The password for apollo portal db | `nil` |
| `portaldb.connectionStringProperties` | The connection string properties for apollo portal db | `characterEncoding=utf8` |
| `portaldb.service.enabled` | Whether to create a Kubernetes Service for `portaldb.host` or not. Set it to `true` if `portaldb.host` is an endpoint outside of the kubernetes cluster | `false` |
| `portaldb.service.fullNameOverride` | Override the service name for apollo portal db | `nil` |
| `portaldb.service.port` | The port for the service of apollo portal db | `3306` |
| `portaldb.service.type` | The service type of apollo portal db: `ClusterIP` or `ExternalName`. If the host is a DNS name, please specify `ExternalName` as the service type, e.g. `xxx.mysql.rds.aliyuncs.com` | `ClusterIP` |
##### 2.4.1.4.4 配置样例
###### 2.4.1.4.4.1 PortalDB的host是k8s集群外的IP
```yaml
portaldb:
host: 1.2.3.4
dbName: ApolloPortalDBName
userName: someUserName
password: somePassword
connectionStringProperties: characterEncoding=utf8&useSSL=false
service:
enabled: true
```
###### 2.4.1.4.4.2 PortalDB的host是k8s集群外的域名
```yaml
portaldb:
host: xxx.mysql.rds.aliyuncs.com
dbName: ApolloPortalDBName
userName: someUserName
password: somePassword
connectionStringProperties: characterEncoding=utf8&useSSL=false
service:
enabled: true
type: ExternalName
```
###### 2.4.1.4.4.3 PortalDB的host是k8s集群内的一个服务
```yaml
portaldb:
host: apollodb-mysql.mysql
dbName: ApolloPortalDBName
userName: someUserName
password: somePassword
connectionStringProperties: characterEncoding=utf8&useSSL=false
```
###### 2.4.1.4.4.4 配置环境信息
```yaml
config:
envs: dev,pro
metaServers:
dev: http://apollo-service-dev-apollo-configservice:8080
pro: http://apollo-service-pro-apollo-configservice:8080
```
###### 2.4.1.4.4.5 以Load Balancer形式暴露服务
```yaml
service:
type: LoadBalancer
```
###### 2.4.1.4.4.6 以Ingress形式暴露服务
```yaml
ingress:
enabled: true
hosts:
- paths:
- /
```
###### 2.4.1.4.4.7 以Ingress配置自定义路径`/apollo`形式暴露服务
```yaml
# use /apollo as root, should specify config.contextPath as /apollo
ingress:
enabled: true
hosts:
- paths:
- /apollo
config:
...
contextPath: /apollo
...
```
###### 2.4.1.4.4.8 以Ingress配置session affinity形式暴露服务
```yaml
ingress:
enabled: true
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/affinity: "cookie"
nginx.ingress.kubernetes.io/affinity-mode: "persistent"
nginx.ingress.kubernetes.io/session-cookie-conditional-samesite-none: "true"
nginx.ingress.kubernetes.io/session-cookie-expires: "172800"
nginx.ingress.kubernetes.io/session-cookie-max-age: "172800"
hosts:
- host: xxx.somedomain.com # host is required to make session affinity work
paths:
- /
```
###### 2.4.1.4.4.9 启用 LDAP 支持
```yaml
config:
...
profiles: github,ldap
...
files:
application-ldap.yml: |
spring:
ldap:
base: "dc=example,dc=org"
username: "cn=admin,dc=example,dc=org"
password: "password"
searchFilter: "(uid={0})"
urls:
- "ldap://xxx.somedomain.com:389"
ldap:
mapping:
objectClass: "inetOrgPerson"
loginId: "uid"
userDisplayName: "cn"
email: "mail"
```
#### 2.4.1.5 通过源码构建 Docker 镜像
如果修改了 apollo 服务端的代码,希望通过源码构建 Docker 镜像,可以参考[2.3.1.4 通过源码构建 Docker 镜像](#_2314-通过源码构建-docker-镜像)的步骤。
### 2.4.2 基于内置的Eureka服务发现
感谢[AiotCEO](https://github.com/AiotCEO)提供了k8s的部署支持,使用说明可以参考[apollo-on-kubernetes](https://github.com/ctripcorp/apollo/blob/master/scripts/apollo-on-kubernetes/README.md)。
感谢[qct](https://github.com/qct)提供的Helm Chart部署支持,使用说明可以参考[qct/apollo-helm](https://github.com/qct/apollo-helm)。
# 三、服务端配置说明
> 以下配置除了支持在数据库中配置以外,也支持通过-D参数、application.properties等配置,且-D参数、application.properties等优先级高于数据库中的配置
## 3.1 调整ApolloPortalDB配置
配置项统一存储在ApolloPortalDB.ServerConfig表中,也可以通过`管理员工具 - 系统参数`页面进行配置,无特殊说明则修改完一分钟实时生效。
### 3.1.1 apollo.portal.envs - 可支持的环境列表
默认值是dev,如果portal需要管理多个环境的话,以逗号分隔即可(大小写不敏感),如:
```
DEV,FAT,UAT,PRO
```
修改完需要重启生效。
>注1:一套Portal可以管理多个环境,但是每个环境都需要独立部署一套Config Service、Admin Service和ApolloConfigDB,具体请参考:[2.1.2 创建ApolloConfigDB](#_212-创建apolloconfigdb),[3.2 调整ApolloConfigDB配置](zh/deployment/distributed-deployment-guide?id=_32-调整apolloconfigdb配置),[2.2.1.1.2 配置数据库连接信息](#_22112-配置数据库连接信息),另外如果是为已经运行了一段时间的Apollo配置中心增加环境,别忘了参考[2.1.2.4 从别的环境导入ApolloConfigDB的项目数据](#_2124-从别的环境导入apolloconfigdb的项目数据)对新的环境做初始化。
>注2:只在数据库添加环境是不起作用的,还需要为apollo-portal添加新增环境对应的meta server地址,具体参考:[2.2.1.1.2.4 配置apollo-portal的meta service信息](#_221124-配置apollo-portal的meta-service信息)。apollo-client在新的环境下使用时也需要做好相应的配置,具体参考:[1.2.2 Apollo Meta Server](zh/usage/java-sdk-user-guide#_122-apollo-meta-server)。
>注3:如果希望添加自定义的环境名称,具体步骤可以参考[Portal如何增加环境](zh/faq/common-issues-in-deployment-and-development-phase?id=_4-portal如何增加环境?)。
>注4:1.1.0版本增加了系统信息页面(`管理员工具` -> `系统信息`),可以通过该页面检查配置是否正确
### 3.1.2 apollo.portal.meta.servers - 各环境Meta Service列表
> 适用于1.6.0及以上版本
Apollo Portal需要在不同的环境访问不同的meta service(apollo-configservice)地址,所以我们需要在配置中提供这些信息。默认情况下,meta service和config service是部署在同一个JVM进程,所以meta service的地址就是config service的地址。
样例如下:
```json
{
"DEV":"http://1.1.1.1:8080",
"FAT":"http://apollo.fat.xxx.com",
"UAT":"http://apollo.uat.xxx.com",
"PRO":"http://apollo.xxx.com"
}
```
修改完需要重启生效。
> 该配置优先级高于其它方式设置的Meta Service地址,更多信息可以参考[2.2.1.1.2.4 配置apollo-portal的meta service信息](#_221124-配置apollo-portal的meta-service信息)。
### 3.1.3 organizations - 部门列表
Portal中新建的App都需要选择部门,所以需要在这里配置可选的部门信息,样例如下:
```json
[{"orgId":"TEST1","orgName":"样例部门1"},{"orgId":"TEST2","orgName":"样例部门2"}]
```
### 3.1.4 superAdmin - Portal超级管理员
超级管理员拥有所有权限,需要谨慎设置。
如果没有接入自己公司的SSO系统的话,可以先暂时使用默认值apollo(默认用户)。等接入后,修改为实际使用的账号,多个账号以英文逗号分隔(,)。
### 3.1.5 consumer.token.salt - consumer token salt
如果会使用开放平台API的话,可以设置一个token salt。如果不使用,可以忽略。
### 3.1.6 wiki.address
portal上“帮助”链接的地址,默认是Apollo github的wiki首页,可自行设置。
### 3.1.7 admin.createPrivateNamespace.switch
是否允许项目管理员创建private namespace。设置为`true`允许创建,设置为`false`则项目管理员在页面上看不到创建private namespace的选项。[了解更多Namespace](zh/design/apollo-core-concept-namespace)
### 3.1.8 emergencyPublish.supported.envs
配置允许紧急发布的环境列表,多个env以英文逗号分隔。
当config service开启一次发布只能有一个人修改开关(`namespace.lock.switch`)后,一次配置发布只能是一个人修改,另一个发布。为了避免遇到紧急情况时(如非工作时间、节假日)无法发布配置,可以配置此项以允许某些环境可以操作紧急发布,即同一个人可以修改并发布配置。
### 3.1.9 configView.memberOnly.envs
只对项目成员显示配置信息的环境列表,多个env以英文逗号分隔。
对设定了只对项目成员显示配置信息的环境,只有该项目的管理员或拥有该namespace的编辑或发布权限的用户才能看到该私有namespace的配置信息和发布历史。公共namespace始终对所有用户可见。
> 从1.1.0版本开始支持,详见[PR 1531](https://github.com/ctripcorp/apollo/pull/1531)
### 3.1.10 role.create-application.enabled - 是否开启创建项目权限控制
> 适用于1.5.0及以上版本
默认为false,所有用户都可以创建项目
如果设置为true,那么只有超级管理员和拥有创建项目权限的帐号可以创建项目,超级管理员可以通过`管理员工具 - 系统权限管理`给用户分配创建项目权限
### 3.1.11 role.manage-app-master.enabled - 是否开启项目管理员分配权限控制
> 适用于1.5.0及以上版本
默认为false,所有项目的管理员可以为项目添加/删除管理员
如果设置为true,那么只有超级管理员和拥有项目管理员分配权限的帐号可以为特定项目添加/删除管理员,超级管理员可以通过`管理员工具 - 系统权限管理`给用户分配特定项目的管理员分配权限
### 3.1.12 admin-service.access.tokens - 设置apollo-portal访问各环境apollo-adminservice所需的access token
> 适用于1.7.1及以上版本
如果对应环境的apollo-adminservice开启了[访问控制](#_326-admin-serviceaccesscontrolenabled-配置apollo-adminservice是否开启访问控制),那么需要在此配置apollo-portal访问该环境apollo-adminservice所需的access token,否则会访问失败
格式为json,如下所示:
```json
{
"dev" : "098f6bcd4621d373cade4e832627b4f6",
"pro" : "ad0234829205b9033196ba818f7a872b"
}
```
## 3.2 调整ApolloConfigDB配置
配置项统一存储在ApolloConfigDB.ServerConfig表中,需要注意每个环境的ApolloConfigDB.ServerConfig都需要单独配置,修改完一分钟实时生效。
### 3.2.1 eureka.service.url - Eureka服务Url
> 不适用于基于Kubernetes原生服务发现场景
不管是apollo-configservice还是apollo-adminservice都需要向eureka服务注册,所以需要配置eureka服务地址。
按照目前的实现,apollo-configservice本身就是一个eureka服务,所以只需要填入apollo-configservice的地址即可,如有多个,用逗号分隔(注意不要忘了/eureka/后缀)。
需要注意的是每个环境只填入自己环境的eureka服务地址,比如FAT的apollo-configservice是1.1.1.1:8080和2.2.2.2:8080,UAT的apollo-configservice是3.3.3.3:8080和4.4.4.4:8080,PRO的apollo-configservice是5.5.5.5:8080和6.6.6.6:8080,那么:
1. 在FAT环境的ApolloConfigDB.ServerConfig表中设置eureka.service.url为:
```
http://1.1.1.1:8080/eureka/,http://2.2.2.2:8080/eureka/
```
2. 在UAT环境的ApolloConfigDB.ServerConfig表中设置eureka.service.url为:
```
http://3.3.3.3:8080/eureka/,http://4.4.4.4:8080/eureka/
```
3. 在PRO环境的ApolloConfigDB.ServerConfig表中设置eureka.service.url为:
```
http://5.5.5.5:8080/eureka/,http://6.6.6.6:8080/eureka/
```
>注1:这里需要填写本环境中全部的eureka服务地址,因为eureka需要互相复制注册信息
>注2:如果希望将Config Service和Admin Service注册到公司统一的Eureka上,可以参考[部署&开发遇到的常见问题 - 将Config Service和Admin Service注册到单独的Eureka Server上](zh/faq/common-issues-in-deployment-and-development-phase#_8-将config-service和admin-service注册到单独的eureka-server上)章节
>注3:在多机房部署时,往往希望config service和admin service只向同机房的eureka注册,要实现这个效果,需要利用`ServerConfig`表中的cluster字段,config service和admin service会读取所在机器的`/opt/settings/server.properties`(Mac/Linux)或`C:\opt\settings\server.properties`(Windows)中的idc属性,如果该idc有对应的eureka.service.url配置,那么就只会向该机房的eureka注册。比如config service和admin service会部署到`SHAOY`和`SHAJQ`两个IDC,那么为了实现这两个机房中的服务只向该机房注册,那么可以在`ServerConfig`表中新增两条记录,分别填入`SHAOY`和`SHAJQ`两个机房的eureka地址即可,`default` cluster的记录可以保留,如果有config service和admin service不是部署在`SHAOY`和`SHAJQ`这两个机房的,就会使用这条默认配置。
| Key |Cluster | Value | Comment |
|--------------------|-----------|-------------------------------|---------------------|
| eureka.service.url | default | http://1.1.1.1:8080/eureka/ | 默认的Eureka服务Url |
| eureka.service.url | SHAOY | http://2.2.2.2:8080/eureka/ | SHAOY的Eureka服务Url |
| eureka.service.url | SHAJQ | http://3.3.3.3:8080/eureka/ | SHAJQ的Eureka服务Url |
### 3.2.2 namespace.lock.switch - 一次发布只能有一个人修改开关,用于发布审核
这是一个功能开关,如果配置为true的话,那么一次配置发布只能是一个人修改,另一个发布。
> 生产环境建议开启此选项
### 3.2.3 config-service.cache.enabled - 是否开启配置缓存
这是一个功能开关,如果配置为true的话,config service会缓存加载过的配置信息,从而加快后续配置获取性能。
默认为false,开启前请先评估总配置大小并调整config service内存配置。
> 开启缓存后必须确保应用中配置的app.id大小写正确,否则将获取不到正确的配置
### 3.2.4 item.key.length.limit - 配置项 key 最大长度限制
默认配置是128。
### 3.2.5 item.value.length.limit - 配置项 value 最大长度限制
默认配置是20000。
### 3.2.6 admin-service.access.control.enabled - 配置apollo-adminservice是否开启访问控制
> 适用于1.7.1及以上版本
默认为false,如果配置为true,那么apollo-portal就需要[正确配置](#_3112-admin-serviceaccesstokens-设置apollo-portal访问各环境apollo-adminservice所需的access-token)访问该环境的access token,否则访问会被拒绝
### 3.2.7 admin-service.access.tokens - 配置允许访问apollo-adminservice的access token列表
> 适用于1.7.1及以上版本
如果该配置项为空,那么访问控制不会生效。如果允许多个token,token 之间以英文逗号分隔
样例:
```properties
admin-service.access.tokens=098f6bcd4621d373cade4e832627b4f6
admin-service.access.tokens=098f6bcd4621d373cade4e832627b4f6,ad0234829205b9033196ba818f7a872b
``` | -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenNamespaceLockDTO.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.openapi.dto;
public class OpenNamespaceLockDTO {
private String namespaceName;
private boolean isLocked;
private String lockedBy;
public String getNamespaceName() {
return namespaceName;
}
public void setNamespaceName(String namespaceName) {
this.namespaceName = namespaceName;
}
public boolean isLocked() {
return isLocked;
}
public void setLocked(boolean locked) {
isLocked = locked;
}
public String getLockedBy() {
return lockedBy;
}
public void setLockedBy(String lockedBy) {
this.lockedBy = lockedBy;
}
@Override
public String toString() {
return "OpenNamespaceLockDTO{" +
"namespaceName='" + namespaceName + '\'' +
", isLocked=" + isLocked +
", lockedBy='" + lockedBy + '\'' +
'}';
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.openapi.dto;
public class OpenNamespaceLockDTO {
private String namespaceName;
private boolean isLocked;
private String lockedBy;
public String getNamespaceName() {
return namespaceName;
}
public void setNamespaceName(String namespaceName) {
this.namespaceName = namespaceName;
}
public boolean isLocked() {
return isLocked;
}
public void setLocked(boolean locked) {
isLocked = locked;
}
public String getLockedBy() {
return lockedBy;
}
public void setLockedBy(String lockedBy) {
this.lockedBy = lockedBy;
}
@Override
public String toString() {
return "OpenNamespaceLockDTO{" +
"namespaceName='" + namespaceName + '\'' +
", isLocked=" + isLocked +
", lockedBy='" + lockedBy + '\'' +
'}';
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-mockserver/src/test/java/com/ctrip/framework/apollo/mockserver/ApolloMockServerApiTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.mockserver;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.google.common.util.concurrent.SettableFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import org.junit.ClassRule;
import org.junit.Test;
public class ApolloMockServerApiTest {
private static final String anotherNamespace = "anotherNamespace";
@ClassRule
public static EmbeddedApollo embeddedApollo = new EmbeddedApollo();
@Test
public void testGetProperty() throws Exception {
Config applicationConfig = ConfigService.getAppConfig();
assertEquals("value1", applicationConfig.getProperty("key1", null));
assertEquals("value2", applicationConfig.getProperty("key2", null));
}
@Test
public void testUpdateProperties() throws Exception {
String someNewValue = "someNewValue";
Config otherConfig = ConfigService.getConfig(anotherNamespace);
final SettableFuture<ConfigChangeEvent> future = SettableFuture.create();
otherConfig.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
future.set(changeEvent);
}
});
assertEquals("otherValue1", otherConfig.getProperty("key1", null));
assertEquals("otherValue2", otherConfig.getProperty("key2", null));
embeddedApollo.addOrModifyProperty(anotherNamespace, "key1", someNewValue);
ConfigChangeEvent changeEvent = future.get(5, TimeUnit.SECONDS);
assertEquals(someNewValue, otherConfig.getProperty("key1", null));
assertEquals("otherValue2", otherConfig.getProperty("key2", null));
assertTrue(changeEvent.isChanged("key1"));
}
@Test
public void testUpdateSamePropertyTwice() throws Exception {
String someNewValue = "someNewValue";
Config otherConfig = ConfigService.getConfig(anotherNamespace);
final Semaphore changes = new Semaphore(0);
otherConfig.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
changes.release();
}
});
assertEquals("otherValue3", otherConfig.getProperty("key3", null));
embeddedApollo.addOrModifyProperty(anotherNamespace, "key3", someNewValue);
embeddedApollo.addOrModifyProperty(anotherNamespace, "key3", someNewValue);
assertTrue(changes.tryAcquire(5, TimeUnit.SECONDS));
assertEquals(someNewValue, otherConfig.getProperty("key3", null));
assertEquals(0, changes.availablePermits());
}
@Test
public void testDeleteProperties() throws Exception {
Config otherConfig = ConfigService.getConfig(anotherNamespace);
final SettableFuture<ConfigChangeEvent> future = SettableFuture.create();
otherConfig.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
future.set(changeEvent);
}
});
assertEquals("otherValue4", otherConfig.getProperty("key4", null));
assertEquals("otherValue5", otherConfig.getProperty("key5", null));
embeddedApollo.deleteProperty(anotherNamespace, "key4");
ConfigChangeEvent changeEvent = future.get(5, TimeUnit.SECONDS);
assertNull(otherConfig.getProperty("key4", null));
assertEquals("otherValue5", otherConfig.getProperty("key5", null));
assertTrue(changeEvent.isChanged("key4"));
}
@Test
public void testDeleteSamePropertyTwice() throws Exception {
Config otherConfig = ConfigService.getConfig(anotherNamespace);
final Semaphore changes = new Semaphore(0);
otherConfig.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
changes.release();
}
});
assertEquals("otherValue6", otherConfig.getProperty("key6", null));
embeddedApollo.deleteProperty(anotherNamespace, "key6");
embeddedApollo.deleteProperty(anotherNamespace, "key6");
assertTrue(changes.tryAcquire(5, TimeUnit.SECONDS));
assertNull(otherConfig.getProperty("key6", null));
assertEquals(0, changes.availablePermits());
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.mockserver;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.google.common.util.concurrent.SettableFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import org.junit.ClassRule;
import org.junit.Test;
public class ApolloMockServerApiTest {
private static final String anotherNamespace = "anotherNamespace";
@ClassRule
public static EmbeddedApollo embeddedApollo = new EmbeddedApollo();
@Test
public void testGetProperty() throws Exception {
Config applicationConfig = ConfigService.getAppConfig();
assertEquals("value1", applicationConfig.getProperty("key1", null));
assertEquals("value2", applicationConfig.getProperty("key2", null));
}
@Test
public void testUpdateProperties() throws Exception {
String someNewValue = "someNewValue";
Config otherConfig = ConfigService.getConfig(anotherNamespace);
final SettableFuture<ConfigChangeEvent> future = SettableFuture.create();
otherConfig.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
future.set(changeEvent);
}
});
assertEquals("otherValue1", otherConfig.getProperty("key1", null));
assertEquals("otherValue2", otherConfig.getProperty("key2", null));
embeddedApollo.addOrModifyProperty(anotherNamespace, "key1", someNewValue);
ConfigChangeEvent changeEvent = future.get(5, TimeUnit.SECONDS);
assertEquals(someNewValue, otherConfig.getProperty("key1", null));
assertEquals("otherValue2", otherConfig.getProperty("key2", null));
assertTrue(changeEvent.isChanged("key1"));
}
@Test
public void testUpdateSamePropertyTwice() throws Exception {
String someNewValue = "someNewValue";
Config otherConfig = ConfigService.getConfig(anotherNamespace);
final Semaphore changes = new Semaphore(0);
otherConfig.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
changes.release();
}
});
assertEquals("otherValue3", otherConfig.getProperty("key3", null));
embeddedApollo.addOrModifyProperty(anotherNamespace, "key3", someNewValue);
embeddedApollo.addOrModifyProperty(anotherNamespace, "key3", someNewValue);
assertTrue(changes.tryAcquire(5, TimeUnit.SECONDS));
assertEquals(someNewValue, otherConfig.getProperty("key3", null));
assertEquals(0, changes.availablePermits());
}
@Test
public void testDeleteProperties() throws Exception {
Config otherConfig = ConfigService.getConfig(anotherNamespace);
final SettableFuture<ConfigChangeEvent> future = SettableFuture.create();
otherConfig.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
future.set(changeEvent);
}
});
assertEquals("otherValue4", otherConfig.getProperty("key4", null));
assertEquals("otherValue5", otherConfig.getProperty("key5", null));
embeddedApollo.deleteProperty(anotherNamespace, "key4");
ConfigChangeEvent changeEvent = future.get(5, TimeUnit.SECONDS);
assertNull(otherConfig.getProperty("key4", null));
assertEquals("otherValue5", otherConfig.getProperty("key5", null));
assertTrue(changeEvent.isChanged("key4"));
}
@Test
public void testDeleteSamePropertyTwice() throws Exception {
Config otherConfig = ConfigService.getConfig(anotherNamespace);
final Semaphore changes = new Semaphore(0);
otherConfig.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
changes.release();
}
});
assertEquals("otherValue6", otherConfig.getProperty("key6", null));
embeddedApollo.deleteProperty(anotherNamespace, "key6");
embeddedApollo.deleteProperty(anotherNamespace, "key6");
assertTrue(changes.tryAcquire(5, TimeUnit.SECONDS));
assertNull(otherConfig.getProperty("key6", null));
assertEquals(0, changes.availablePermits());
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-biz/src/test/java/com/ctrip/framework/apollo/biz/service/InstanceServiceTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.service;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.ctrip.framework.apollo.biz.AbstractIntegrationTest;
import com.ctrip.framework.apollo.biz.entity.Instance;
import com.ctrip.framework.apollo.biz.entity.InstanceConfig;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.annotation.Rollback;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class InstanceServiceTest extends AbstractIntegrationTest {
@Autowired
private InstanceService instanceService;
@Test
@Rollback
public void testCreateAndFindInstance() throws Exception {
String someAppId = "someAppId";
String someClusterName = "someClusterName";
String someDataCenter = "someDataCenter";
String someIp = "someIp";
Instance instance = instanceService.findInstance(someAppId, someClusterName, someDataCenter,
someIp);
assertNull(instance);
instanceService.createInstance(assembleInstance(someAppId, someClusterName, someDataCenter,
someIp));
instance = instanceService.findInstance(someAppId, someClusterName, someDataCenter,
someIp);
assertNotEquals(0, instance.getId());
}
@Test
@Rollback
public void testFindInstancesByIds() throws Exception {
String someAppId = "someAppId";
String someClusterName = "someClusterName";
String someDataCenter = "someDataCenter";
String someIp = "someIp";
String anotherIp = "anotherIp";
Instance someInstance = instanceService.createInstance(assembleInstance(someAppId,
someClusterName, someDataCenter, someIp));
Instance anotherInstance = instanceService.createInstance(assembleInstance(someAppId,
someClusterName, someDataCenter, anotherIp));
List<Instance> instances = instanceService.findInstancesByIds(Sets.newHashSet(someInstance
.getId(), anotherInstance.getId()));
Set<String> ips = instances.stream().map(Instance::getIp).collect(Collectors.toSet());
assertEquals(2, instances.size());
assertEquals(Sets.newHashSet(someIp, anotherIp), ips);
}
@Test
@Rollback
public void testCreateAndFindInstanceConfig() throws Exception {
long someInstanceId = 1;
String someConfigAppId = "someConfigAppId";
String someConfigClusterName = "someConfigClusterName";
String someConfigNamespaceName = "someConfigNamespaceName";
String someReleaseKey = "someReleaseKey";
String anotherReleaseKey = "anotherReleaseKey";
InstanceConfig instanceConfig = instanceService.findInstanceConfig(someInstanceId,
someConfigAppId, someConfigNamespaceName);
assertNull(instanceConfig);
instanceService.createInstanceConfig(assembleInstanceConfig(someInstanceId, someConfigAppId,
someConfigClusterName, someConfigNamespaceName, someReleaseKey));
instanceConfig = instanceService.findInstanceConfig(someInstanceId, someConfigAppId,
someConfigNamespaceName);
assertNotEquals(0, instanceConfig.getId());
assertEquals(someReleaseKey, instanceConfig.getReleaseKey());
instanceConfig.setReleaseKey(anotherReleaseKey);
instanceService.updateInstanceConfig(instanceConfig);
InstanceConfig updated = instanceService.findInstanceConfig(someInstanceId, someConfigAppId,
someConfigNamespaceName);
assertEquals(instanceConfig.getId(), updated.getId());
assertEquals(anotherReleaseKey, updated.getReleaseKey());
}
@Test
@Rollback
public void testFindActiveInstanceConfigs() throws Exception {
long someInstanceId = 1;
long anotherInstanceId = 2;
String someConfigAppId = "someConfigAppId";
String someConfigClusterName = "someConfigClusterName";
String someConfigNamespaceName = "someConfigNamespaceName";
Date someValidDate = new Date();
Pageable pageable = PageRequest.of(0, 10);
String someReleaseKey = "someReleaseKey";
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -2);
Date someInvalidDate = calendar.getTime();
prepareInstanceConfigForInstance(someInstanceId, someConfigAppId, someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
prepareInstanceConfigForInstance(anotherInstanceId, someConfigAppId, someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someInvalidDate);
Page<InstanceConfig> validInstanceConfigs = instanceService
.findActiveInstanceConfigsByReleaseKey(someReleaseKey, pageable);
assertEquals(1, validInstanceConfigs.getContent().size());
assertEquals(someInstanceId, validInstanceConfigs.getContent().get(0).getInstanceId());
}
@Test
@Rollback
public void testFindInstancesByNamespace() throws Exception {
String someConfigAppId = "someConfigAppId";
String someConfigClusterName = "someConfigClusterName";
String someConfigNamespaceName = "someConfigNamespaceName";
String someReleaseKey = "someReleaseKey";
Date someValidDate = new Date();
String someAppId = "someAppId";
String someClusterName = "someClusterName";
String someDataCenter = "someDataCenter";
String someIp = "someIp";
String anotherIp = "anotherIp";
Instance someInstance = instanceService.createInstance(assembleInstance(someAppId,
someClusterName, someDataCenter, someIp));
Instance anotherInstance = instanceService.createInstance(assembleInstance(someAppId,
someClusterName, someDataCenter, anotherIp));
prepareInstanceConfigForInstance(someInstance.getId(), someConfigAppId, someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
prepareInstanceConfigForInstance(anotherInstance.getId(), someConfigAppId,
someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
Page<Instance> result = instanceService.findInstancesByNamespace(someConfigAppId,
someConfigClusterName, someConfigNamespaceName, PageRequest.of(0, 10));
assertEquals(Lists.newArrayList(someInstance, anotherInstance), result.getContent());
}
@Test
@Rollback
public void testFindInstancesByNamespaceAndInstanceAppId() throws Exception {
String someConfigAppId = "someConfigAppId";
String someConfigClusterName = "someConfigClusterName";
String someConfigNamespaceName = "someConfigNamespaceName";
String someReleaseKey = "someReleaseKey";
Date someValidDate = new Date();
String someAppId = "someAppId";
String anotherAppId = "anotherAppId";
String someClusterName = "someClusterName";
String someDataCenter = "someDataCenter";
String someIp = "someIp";
Instance someInstance = instanceService.createInstance(assembleInstance(someAppId,
someClusterName, someDataCenter, someIp));
Instance anotherInstance = instanceService.createInstance(assembleInstance(anotherAppId,
someClusterName, someDataCenter, someIp));
prepareInstanceConfigForInstance(someInstance.getId(), someConfigAppId, someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
prepareInstanceConfigForInstance(anotherInstance.getId(), someConfigAppId,
someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
Page<Instance> result = instanceService.findInstancesByNamespaceAndInstanceAppId(someAppId,
someConfigAppId, someConfigClusterName, someConfigNamespaceName, PageRequest.of(0, 10));
Page<Instance> anotherResult = instanceService.findInstancesByNamespaceAndInstanceAppId(anotherAppId,
someConfigAppId, someConfigClusterName, someConfigNamespaceName, PageRequest.of(0, 10));
assertEquals(Lists.newArrayList(someInstance), result.getContent());
assertEquals(Lists.newArrayList(anotherInstance), anotherResult.getContent());
}
@Test
@Rollback
public void testFindInstanceConfigsByNamespaceWithReleaseKeysNotIn() throws Exception {
long someInstanceId = 1;
long anotherInstanceId = 2;
long yetAnotherInstanceId = 3;
String someConfigAppId = "someConfigAppId";
String someConfigClusterName = "someConfigClusterName";
String someConfigNamespaceName = "someConfigNamespaceName";
Date someValidDate = new Date();
String someReleaseKey = "someReleaseKey";
String anotherReleaseKey = "anotherReleaseKey";
String yetAnotherReleaseKey = "yetAnotherReleaseKey";
InstanceConfig someInstanceConfig = prepareInstanceConfigForInstance(someInstanceId,
someConfigAppId, someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
InstanceConfig anotherInstanceConfig = prepareInstanceConfigForInstance(anotherInstanceId,
someConfigAppId, someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
prepareInstanceConfigForInstance(yetAnotherInstanceId, someConfigAppId, someConfigClusterName,
someConfigNamespaceName, anotherReleaseKey, someValidDate);
List<InstanceConfig> instanceConfigs = instanceService
.findInstanceConfigsByNamespaceWithReleaseKeysNotIn(someConfigAppId,
someConfigClusterName, someConfigNamespaceName, Sets.newHashSet(anotherReleaseKey,
yetAnotherReleaseKey));
assertEquals(Lists.newArrayList(someInstanceConfig, anotherInstanceConfig), instanceConfigs);
}
private InstanceConfig prepareInstanceConfigForInstance(long instanceId, String configAppId,
String configClusterName, String
configNamespace, String releaseKey,
Date lastModifiedTime) {
InstanceConfig someConfig = assembleInstanceConfig(instanceId, configAppId, configClusterName,
configNamespace, releaseKey);
someConfig.setDataChangeCreatedTime(lastModifiedTime);
someConfig.setDataChangeLastModifiedTime(lastModifiedTime);
return instanceService.createInstanceConfig(someConfig);
}
private Instance assembleInstance(String appId, String clusterName, String dataCenter, String
ip) {
Instance instance = new Instance();
instance.setAppId(appId);
instance.setIp(ip);
instance.setClusterName(clusterName);
instance.setDataCenter(dataCenter);
return instance;
}
private InstanceConfig assembleInstanceConfig(long instanceId, String configAppId, String
configClusterName, String configNamespaceName, String releaseKey) {
InstanceConfig instanceConfig = new InstanceConfig();
instanceConfig.setInstanceId(instanceId);
instanceConfig.setConfigAppId(configAppId);
instanceConfig.setConfigClusterName(configClusterName);
instanceConfig.setConfigNamespaceName(configNamespaceName);
instanceConfig.setReleaseKey(releaseKey);
return instanceConfig;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.service;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.ctrip.framework.apollo.biz.AbstractIntegrationTest;
import com.ctrip.framework.apollo.biz.entity.Instance;
import com.ctrip.framework.apollo.biz.entity.InstanceConfig;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.annotation.Rollback;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class InstanceServiceTest extends AbstractIntegrationTest {
@Autowired
private InstanceService instanceService;
@Test
@Rollback
public void testCreateAndFindInstance() throws Exception {
String someAppId = "someAppId";
String someClusterName = "someClusterName";
String someDataCenter = "someDataCenter";
String someIp = "someIp";
Instance instance = instanceService.findInstance(someAppId, someClusterName, someDataCenter,
someIp);
assertNull(instance);
instanceService.createInstance(assembleInstance(someAppId, someClusterName, someDataCenter,
someIp));
instance = instanceService.findInstance(someAppId, someClusterName, someDataCenter,
someIp);
assertNotEquals(0, instance.getId());
}
@Test
@Rollback
public void testFindInstancesByIds() throws Exception {
String someAppId = "someAppId";
String someClusterName = "someClusterName";
String someDataCenter = "someDataCenter";
String someIp = "someIp";
String anotherIp = "anotherIp";
Instance someInstance = instanceService.createInstance(assembleInstance(someAppId,
someClusterName, someDataCenter, someIp));
Instance anotherInstance = instanceService.createInstance(assembleInstance(someAppId,
someClusterName, someDataCenter, anotherIp));
List<Instance> instances = instanceService.findInstancesByIds(Sets.newHashSet(someInstance
.getId(), anotherInstance.getId()));
Set<String> ips = instances.stream().map(Instance::getIp).collect(Collectors.toSet());
assertEquals(2, instances.size());
assertEquals(Sets.newHashSet(someIp, anotherIp), ips);
}
@Test
@Rollback
public void testCreateAndFindInstanceConfig() throws Exception {
long someInstanceId = 1;
String someConfigAppId = "someConfigAppId";
String someConfigClusterName = "someConfigClusterName";
String someConfigNamespaceName = "someConfigNamespaceName";
String someReleaseKey = "someReleaseKey";
String anotherReleaseKey = "anotherReleaseKey";
InstanceConfig instanceConfig = instanceService.findInstanceConfig(someInstanceId,
someConfigAppId, someConfigNamespaceName);
assertNull(instanceConfig);
instanceService.createInstanceConfig(assembleInstanceConfig(someInstanceId, someConfigAppId,
someConfigClusterName, someConfigNamespaceName, someReleaseKey));
instanceConfig = instanceService.findInstanceConfig(someInstanceId, someConfigAppId,
someConfigNamespaceName);
assertNotEquals(0, instanceConfig.getId());
assertEquals(someReleaseKey, instanceConfig.getReleaseKey());
instanceConfig.setReleaseKey(anotherReleaseKey);
instanceService.updateInstanceConfig(instanceConfig);
InstanceConfig updated = instanceService.findInstanceConfig(someInstanceId, someConfigAppId,
someConfigNamespaceName);
assertEquals(instanceConfig.getId(), updated.getId());
assertEquals(anotherReleaseKey, updated.getReleaseKey());
}
@Test
@Rollback
public void testFindActiveInstanceConfigs() throws Exception {
long someInstanceId = 1;
long anotherInstanceId = 2;
String someConfigAppId = "someConfigAppId";
String someConfigClusterName = "someConfigClusterName";
String someConfigNamespaceName = "someConfigNamespaceName";
Date someValidDate = new Date();
Pageable pageable = PageRequest.of(0, 10);
String someReleaseKey = "someReleaseKey";
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -2);
Date someInvalidDate = calendar.getTime();
prepareInstanceConfigForInstance(someInstanceId, someConfigAppId, someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
prepareInstanceConfigForInstance(anotherInstanceId, someConfigAppId, someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someInvalidDate);
Page<InstanceConfig> validInstanceConfigs = instanceService
.findActiveInstanceConfigsByReleaseKey(someReleaseKey, pageable);
assertEquals(1, validInstanceConfigs.getContent().size());
assertEquals(someInstanceId, validInstanceConfigs.getContent().get(0).getInstanceId());
}
@Test
@Rollback
public void testFindInstancesByNamespace() throws Exception {
String someConfigAppId = "someConfigAppId";
String someConfigClusterName = "someConfigClusterName";
String someConfigNamespaceName = "someConfigNamespaceName";
String someReleaseKey = "someReleaseKey";
Date someValidDate = new Date();
String someAppId = "someAppId";
String someClusterName = "someClusterName";
String someDataCenter = "someDataCenter";
String someIp = "someIp";
String anotherIp = "anotherIp";
Instance someInstance = instanceService.createInstance(assembleInstance(someAppId,
someClusterName, someDataCenter, someIp));
Instance anotherInstance = instanceService.createInstance(assembleInstance(someAppId,
someClusterName, someDataCenter, anotherIp));
prepareInstanceConfigForInstance(someInstance.getId(), someConfigAppId, someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
prepareInstanceConfigForInstance(anotherInstance.getId(), someConfigAppId,
someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
Page<Instance> result = instanceService.findInstancesByNamespace(someConfigAppId,
someConfigClusterName, someConfigNamespaceName, PageRequest.of(0, 10));
assertEquals(Lists.newArrayList(someInstance, anotherInstance), result.getContent());
}
@Test
@Rollback
public void testFindInstancesByNamespaceAndInstanceAppId() throws Exception {
String someConfigAppId = "someConfigAppId";
String someConfigClusterName = "someConfigClusterName";
String someConfigNamespaceName = "someConfigNamespaceName";
String someReleaseKey = "someReleaseKey";
Date someValidDate = new Date();
String someAppId = "someAppId";
String anotherAppId = "anotherAppId";
String someClusterName = "someClusterName";
String someDataCenter = "someDataCenter";
String someIp = "someIp";
Instance someInstance = instanceService.createInstance(assembleInstance(someAppId,
someClusterName, someDataCenter, someIp));
Instance anotherInstance = instanceService.createInstance(assembleInstance(anotherAppId,
someClusterName, someDataCenter, someIp));
prepareInstanceConfigForInstance(someInstance.getId(), someConfigAppId, someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
prepareInstanceConfigForInstance(anotherInstance.getId(), someConfigAppId,
someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
Page<Instance> result = instanceService.findInstancesByNamespaceAndInstanceAppId(someAppId,
someConfigAppId, someConfigClusterName, someConfigNamespaceName, PageRequest.of(0, 10));
Page<Instance> anotherResult = instanceService.findInstancesByNamespaceAndInstanceAppId(anotherAppId,
someConfigAppId, someConfigClusterName, someConfigNamespaceName, PageRequest.of(0, 10));
assertEquals(Lists.newArrayList(someInstance), result.getContent());
assertEquals(Lists.newArrayList(anotherInstance), anotherResult.getContent());
}
@Test
@Rollback
public void testFindInstanceConfigsByNamespaceWithReleaseKeysNotIn() throws Exception {
long someInstanceId = 1;
long anotherInstanceId = 2;
long yetAnotherInstanceId = 3;
String someConfigAppId = "someConfigAppId";
String someConfigClusterName = "someConfigClusterName";
String someConfigNamespaceName = "someConfigNamespaceName";
Date someValidDate = new Date();
String someReleaseKey = "someReleaseKey";
String anotherReleaseKey = "anotherReleaseKey";
String yetAnotherReleaseKey = "yetAnotherReleaseKey";
InstanceConfig someInstanceConfig = prepareInstanceConfigForInstance(someInstanceId,
someConfigAppId, someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
InstanceConfig anotherInstanceConfig = prepareInstanceConfigForInstance(anotherInstanceId,
someConfigAppId, someConfigClusterName,
someConfigNamespaceName, someReleaseKey, someValidDate);
prepareInstanceConfigForInstance(yetAnotherInstanceId, someConfigAppId, someConfigClusterName,
someConfigNamespaceName, anotherReleaseKey, someValidDate);
List<InstanceConfig> instanceConfigs = instanceService
.findInstanceConfigsByNamespaceWithReleaseKeysNotIn(someConfigAppId,
someConfigClusterName, someConfigNamespaceName, Sets.newHashSet(anotherReleaseKey,
yetAnotherReleaseKey));
assertEquals(Lists.newArrayList(someInstanceConfig, anotherInstanceConfig), instanceConfigs);
}
private InstanceConfig prepareInstanceConfigForInstance(long instanceId, String configAppId,
String configClusterName, String
configNamespace, String releaseKey,
Date lastModifiedTime) {
InstanceConfig someConfig = assembleInstanceConfig(instanceId, configAppId, configClusterName,
configNamespace, releaseKey);
someConfig.setDataChangeCreatedTime(lastModifiedTime);
someConfig.setDataChangeLastModifiedTime(lastModifiedTime);
return instanceService.createInstanceConfig(someConfig);
}
private Instance assembleInstance(String appId, String clusterName, String dataCenter, String
ip) {
Instance instance = new Instance();
instance.setAppId(appId);
instance.setIp(ip);
instance.setClusterName(clusterName);
instance.setDataCenter(dataCenter);
return instance;
}
private InstanceConfig assembleInstanceConfig(long instanceId, String configAppId, String
configClusterName, String configNamespaceName, String releaseKey) {
InstanceConfig instanceConfig = new InstanceConfig();
instanceConfig.setInstanceId(instanceId);
instanceConfig.setConfigAppId(configAppId);
instanceConfig.setConfigClusterName(configClusterName);
instanceConfig.setConfigNamespaceName(configNamespaceName);
instanceConfig.setReleaseKey(releaseKey);
return instanceConfig;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-core/src/main/java/com/ctrip/framework/apollo/core/ServiceNameConsts.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.core;
public interface ServiceNameConsts {
String APOLLO_METASERVICE = "apollo-metaservice";
String APOLLO_CONFIGSERVICE = "apollo-configservice";
String APOLLO_ADMINSERVICE = "apollo-adminservice";
String APOLLO_PORTAL = "apollo-portal";
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.core;
public interface ServiceNameConsts {
String APOLLO_METASERVICE = "apollo-metaservice";
String APOLLO_CONFIGSERVICE = "apollo-configservice";
String APOLLO_ADMINSERVICE = "apollo-adminservice";
String APOLLO_PORTAL = "apollo-portal";
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-adminservice/src/test/java/com/ctrip/framework/apollo/AdminServiceTestConfiguration.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo;
import com.ctrip.framework.apollo.adminservice.AdminServiceApplication;
import com.ctrip.framework.apollo.common.controller.HttpMessageConverterConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
@Configuration
@ComponentScan(excludeFilters = {@Filter(type = FilterType.ASSIGNABLE_TYPE, value = {
LocalAdminServiceApplication.class, AdminServiceApplication.class,
HttpMessageConverterConfiguration.class})})
@EnableAutoConfiguration
public class AdminServiceTestConfiguration {
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo;
import com.ctrip.framework.apollo.adminservice.AdminServiceApplication;
import com.ctrip.framework.apollo.common.controller.HttpMessageConverterConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
@Configuration
@ComponentScan(excludeFilters = {@Filter(type = FilterType.ASSIGNABLE_TYPE, value = {
LocalAdminServiceApplication.class, AdminServiceApplication.class,
HttpMessageConverterConfiguration.class})})
@EnableAutoConfiguration
public class AdminServiceTestConfiguration {
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-adminservice/src/test/java/com/ctrip/framework/apollo/adminservice/controller/ControllerExceptionTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.adminservice.controller;
import com.ctrip.framework.apollo.biz.service.AdminService;
import com.ctrip.framework.apollo.biz.service.AppService;
import com.ctrip.framework.apollo.common.dto.AppDTO;
import com.ctrip.framework.apollo.common.entity.App;
import com.ctrip.framework.apollo.common.exception.NotFoundException;
import com.ctrip.framework.apollo.common.exception.ServiceException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ControllerExceptionTest {
private AppController appController;
@Mock
private AppService appService;
@Mock
private AdminService adminService;
@Before
public void setUp() {
appController = new AppController(appService, adminService);
}
@Test(expected = NotFoundException.class)
public void testFindNotExists() {
when(appService.findOne(any(String.class))).thenReturn(null);
appController.get("unexist");
}
@Test(expected = NotFoundException.class)
public void testDeleteNotExists() {
when(appService.findOne(any(String.class))).thenReturn(null);
appController.delete("unexist", null);
}
@Test
public void testFindEmpty() {
when(appService.findAll(any(Pageable.class))).thenReturn(new ArrayList<>());
Pageable pageable = PageRequest.of(0, 10);
List<AppDTO> appDTOs = appController.find(null, pageable);
Assert.assertNotNull(appDTOs);
Assert.assertEquals(0, appDTOs.size());
appDTOs = appController.find("", pageable);
Assert.assertNotNull(appDTOs);
Assert.assertEquals(0, appDTOs.size());
}
@Test
public void testFindByName() {
Pageable pageable = PageRequest.of(0, 10);
List<AppDTO> appDTOs = appController.find("unexist", pageable);
Assert.assertNotNull(appDTOs);
Assert.assertEquals(0, appDTOs.size());
}
@Test(expected = ServiceException.class)
public void createFailed() {
AppDTO dto = generateSampleDTOData();
when(appService.findOne(any(String.class))).thenReturn(null);
when(adminService.createNewApp(any(App.class)))
.thenThrow(new ServiceException("create app failed"));
appController.create(dto);
}
private AppDTO generateSampleDTOData() {
AppDTO dto = new AppDTO();
dto.setAppId("someAppId");
dto.setName("someName");
dto.setOwnerName("someOwner");
dto.setOwnerEmail("someOwner@ctrip.com");
dto.setDataChangeLastModifiedBy("test");
dto.setDataChangeCreatedBy("test");
return dto;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.adminservice.controller;
import com.ctrip.framework.apollo.biz.service.AdminService;
import com.ctrip.framework.apollo.biz.service.AppService;
import com.ctrip.framework.apollo.common.dto.AppDTO;
import com.ctrip.framework.apollo.common.entity.App;
import com.ctrip.framework.apollo.common.exception.NotFoundException;
import com.ctrip.framework.apollo.common.exception.ServiceException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ControllerExceptionTest {
private AppController appController;
@Mock
private AppService appService;
@Mock
private AdminService adminService;
@Before
public void setUp() {
appController = new AppController(appService, adminService);
}
@Test(expected = NotFoundException.class)
public void testFindNotExists() {
when(appService.findOne(any(String.class))).thenReturn(null);
appController.get("unexist");
}
@Test(expected = NotFoundException.class)
public void testDeleteNotExists() {
when(appService.findOne(any(String.class))).thenReturn(null);
appController.delete("unexist", null);
}
@Test
public void testFindEmpty() {
when(appService.findAll(any(Pageable.class))).thenReturn(new ArrayList<>());
Pageable pageable = PageRequest.of(0, 10);
List<AppDTO> appDTOs = appController.find(null, pageable);
Assert.assertNotNull(appDTOs);
Assert.assertEquals(0, appDTOs.size());
appDTOs = appController.find("", pageable);
Assert.assertNotNull(appDTOs);
Assert.assertEquals(0, appDTOs.size());
}
@Test
public void testFindByName() {
Pageable pageable = PageRequest.of(0, 10);
List<AppDTO> appDTOs = appController.find("unexist", pageable);
Assert.assertNotNull(appDTOs);
Assert.assertEquals(0, appDTOs.size());
}
@Test(expected = ServiceException.class)
public void createFailed() {
AppDTO dto = generateSampleDTOData();
when(appService.findOne(any(String.class))).thenReturn(null);
when(adminService.createNewApp(any(App.class)))
.thenThrow(new ServiceException("create app failed"));
appController.create(dto);
}
private AppDTO generateSampleDTOData() {
AppDTO dto = new AppDTO();
dto.setAppId("someAppId");
dto.setName("someName");
dto.setOwnerName("someOwner");
dto.setOwnerEmail("someOwner@ctrip.com");
dto.setDataChangeLastModifiedBy("test");
dto.setDataChangeCreatedBy("test");
return dto;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-configservice/src/test/java/com/ctrip/framework/apollo/configservice/controller/TestWebSecurityConfig.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@Order(99)
public class TestWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic();
http.csrf().disable();
http.authorizeRequests().antMatchers("/").permitAll().and()
.authorizeRequests().antMatchers("/console/**").permitAll();
http.headers().frameOptions().disable();
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.controller;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@Order(99)
public class TestWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic();
http.csrf().disable();
http.authorizeRequests().antMatchers("/").permitAll().and()
.authorizeRequests().antMatchers("/console/**").permitAll();
http.headers().frameOptions().disable();
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import java.util.Map;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.spi.ConfigFactory;
import com.ctrip.framework.apollo.spi.ConfigFactoryManager;
import com.google.common.collect.Maps;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class DefaultConfigManager implements ConfigManager {
private ConfigFactoryManager m_factoryManager;
private Map<String, Config> m_configs = Maps.newConcurrentMap();
private Map<String, ConfigFile> m_configFiles = Maps.newConcurrentMap();
public DefaultConfigManager() {
m_factoryManager = ApolloInjector.getInstance(ConfigFactoryManager.class);
}
@Override
public Config getConfig(String namespace) {
Config config = m_configs.get(namespace);
if (config == null) {
synchronized (this) {
config = m_configs.get(namespace);
if (config == null) {
ConfigFactory factory = m_factoryManager.getFactory(namespace);
config = factory.create(namespace);
m_configs.put(namespace, config);
}
}
}
return config;
}
@Override
public ConfigFile getConfigFile(String namespace, ConfigFileFormat configFileFormat) {
String namespaceFileName = String.format("%s.%s", namespace, configFileFormat.getValue());
ConfigFile configFile = m_configFiles.get(namespaceFileName);
if (configFile == null) {
synchronized (this) {
configFile = m_configFiles.get(namespaceFileName);
if (configFile == null) {
ConfigFactory factory = m_factoryManager.getFactory(namespaceFileName);
configFile = factory.createConfigFile(namespaceFileName, configFileFormat);
m_configFiles.put(namespaceFileName, configFile);
}
}
}
return configFile;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import java.util.Map;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.spi.ConfigFactory;
import com.ctrip.framework.apollo.spi.ConfigFactoryManager;
import com.google.common.collect.Maps;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class DefaultConfigManager implements ConfigManager {
private ConfigFactoryManager m_factoryManager;
private Map<String, Config> m_configs = Maps.newConcurrentMap();
private Map<String, ConfigFile> m_configFiles = Maps.newConcurrentMap();
public DefaultConfigManager() {
m_factoryManager = ApolloInjector.getInstance(ConfigFactoryManager.class);
}
@Override
public Config getConfig(String namespace) {
Config config = m_configs.get(namespace);
if (config == null) {
synchronized (this) {
config = m_configs.get(namespace);
if (config == null) {
ConfigFactory factory = m_factoryManager.getFactory(namespace);
config = factory.create(namespace);
m_configs.put(namespace, config);
}
}
}
return config;
}
@Override
public ConfigFile getConfigFile(String namespace, ConfigFileFormat configFileFormat) {
String namespaceFileName = String.format("%s.%s", namespace, configFileFormat.getValue());
ConfigFile configFile = m_configFiles.get(namespaceFileName);
if (configFile == null) {
synchronized (this) {
configFile = m_configFiles.get(namespaceFileName);
if (configFile == null) {
ConfigFactory factory = m_factoryManager.getFactory(namespaceFileName);
configFile = factory.createConfigFile(namespaceFileName, configFileFormat);
m_configFiles.put(namespaceFileName, configFile);
}
}
}
return configFile;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/configuration/MQConfiguration.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi.configuration;
import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripMQService;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultMQService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class MQConfiguration {
@Configuration
@Profile("ctrip")
public static class CtripMQConfiguration {
@Bean
public CtripMQService mqService() {
return new CtripMQService();
}
}
/**
* spring.profiles.active != ctrip
*/
@Configuration
@ConditionalOnMissingProfile({"ctrip"})
public static class DefaultMQConfiguration {
@Bean
public DefaultMQService mqService() {
return new DefaultMQService();
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi.configuration;
import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripMQService;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultMQService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class MQConfiguration {
@Configuration
@Profile("ctrip")
public static class CtripMQConfiguration {
@Bean
public CtripMQService mqService() {
return new CtripMQService();
}
}
/**
* spring.profiles.active != ctrip
*/
@Configuration
@ConditionalOnMissingProfile({"ctrip"})
public static class DefaultMQConfiguration {
@Bean
public DefaultMQService mqService() {
return new DefaultMQService();
}
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/dto/ClusterDTO.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.dto;
import com.ctrip.framework.apollo.common.utils.InputValidator;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
public class ClusterDTO extends BaseDTO{
private long id;
@NotBlank(message = "cluster name cannot be blank")
@Pattern(
regexp = InputValidator.CLUSTER_NAMESPACE_VALIDATOR,
message = "Invalid Cluster format: " + InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE
)
private String name;
@NotBlank(message = "appId cannot be blank")
private String appId;
private long parentClusterId;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public long getParentClusterId() {
return parentClusterId;
}
public void setParentClusterId(long parentClusterId) {
this.parentClusterId = parentClusterId;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.dto;
import com.ctrip.framework.apollo.common.utils.InputValidator;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
public class ClusterDTO extends BaseDTO{
private long id;
@NotBlank(message = "cluster name cannot be blank")
@Pattern(
regexp = InputValidator.CLUSTER_NAMESPACE_VALIDATOR,
message = "Invalid Cluster format: " + InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE
)
private String name;
@NotBlank(message = "appId cannot be blank")
private String appId;
private long parentClusterId;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public long getParentClusterId() {
return parentClusterId;
}
public void setParentClusterId(long parentClusterId) {
this.parentClusterId = parentClusterId;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/NamespaceBranchController.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.common.dto.GrayReleaseRuleDTO;
import com.ctrip.framework.apollo.common.dto.NamespaceDTO;
import com.ctrip.framework.apollo.common.dto.ReleaseDTO;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.component.PermissionValidator;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.entity.bo.NamespaceBO;
import com.ctrip.framework.apollo.portal.entity.model.NamespaceReleaseModel;
import com.ctrip.framework.apollo.portal.listener.ConfigPublishEvent;
import com.ctrip.framework.apollo.portal.service.NamespaceBranchService;
import com.ctrip.framework.apollo.portal.service.ReleaseService;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class NamespaceBranchController {
private final PermissionValidator permissionValidator;
private final ReleaseService releaseService;
private final NamespaceBranchService namespaceBranchService;
private final ApplicationEventPublisher publisher;
private final PortalConfig portalConfig;
public NamespaceBranchController(
final PermissionValidator permissionValidator,
final ReleaseService releaseService,
final NamespaceBranchService namespaceBranchService,
final ApplicationEventPublisher publisher,
final PortalConfig portalConfig) {
this.permissionValidator = permissionValidator;
this.releaseService = releaseService;
this.namespaceBranchService = namespaceBranchService;
this.publisher = publisher;
this.portalConfig = portalConfig;
}
@GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/branches")
public NamespaceBO findBranch(@PathVariable String appId,
@PathVariable String env,
@PathVariable String clusterName,
@PathVariable String namespaceName) {
NamespaceBO namespaceBO = namespaceBranchService.findBranch(appId, Env.valueOf(env), clusterName, namespaceName);
if (namespaceBO != null && permissionValidator.shouldHideConfigToCurrentUser(appId, env, namespaceName)) {
namespaceBO.hideItems();
}
return namespaceBO;
}
@PreAuthorize(value = "@permissionValidator.hasModifyNamespacePermission(#appId, #namespaceName, #env)")
@PostMapping(value = "/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/branches")
public NamespaceDTO createBranch(@PathVariable String appId,
@PathVariable String env,
@PathVariable String clusterName,
@PathVariable String namespaceName) {
return namespaceBranchService.createBranch(appId, Env.valueOf(env), clusterName, namespaceName);
}
@DeleteMapping(value = "/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}")
public void deleteBranch(@PathVariable String appId,
@PathVariable String env,
@PathVariable String clusterName,
@PathVariable String namespaceName,
@PathVariable String branchName) {
boolean canDelete = permissionValidator.hasReleaseNamespacePermission(appId, namespaceName, env) ||
(permissionValidator.hasModifyNamespacePermission(appId, namespaceName, env) &&
releaseService.loadLatestRelease(appId, Env.valueOf(env), branchName, namespaceName) == null);
if (!canDelete) {
throw new AccessDeniedException("Forbidden operation. "
+ "Caused by: 1.you don't have release permission "
+ "or 2. you don't have modification permission "
+ "or 3. you have modification permission but branch has been released");
}
namespaceBranchService.deleteBranch(appId, Env.valueOf(env), clusterName, namespaceName, branchName);
}
@PreAuthorize(value = "@permissionValidator.hasReleaseNamespacePermission(#appId, #namespaceName, #env)")
@PostMapping(value = "/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}/merge")
public ReleaseDTO merge(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName, @PathVariable String namespaceName,
@PathVariable String branchName, @RequestParam(value = "deleteBranch", defaultValue = "true") boolean deleteBranch,
@RequestBody NamespaceReleaseModel model) {
if (model.isEmergencyPublish() && !portalConfig.isEmergencyPublishAllowed(Env.valueOf(env))) {
throw new BadRequestException(String.format("Env: %s is not supported emergency publish now", env));
}
ReleaseDTO createdRelease = namespaceBranchService.merge(appId, Env.valueOf(env), clusterName, namespaceName, branchName,
model.getReleaseTitle(), model.getReleaseComment(),
model.isEmergencyPublish(), deleteBranch);
ConfigPublishEvent event = ConfigPublishEvent.instance();
event.withAppId(appId)
.withCluster(clusterName)
.withNamespace(namespaceName)
.withReleaseId(createdRelease.getId())
.setMergeEvent(true)
.setEnv(Env.valueOf(env));
publisher.publishEvent(event);
return createdRelease;
}
@GetMapping(value = "/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}/rules")
public GrayReleaseRuleDTO getBranchGrayRules(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName,
@PathVariable String namespaceName,
@PathVariable String branchName) {
return namespaceBranchService.findBranchGrayRules(appId, Env.valueOf(env), clusterName, namespaceName, branchName);
}
@PreAuthorize(value = "@permissionValidator.hasOperateNamespacePermission(#appId, #namespaceName, #env)")
@PutMapping(value = "/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}/rules")
public void updateBranchRules(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName, @PathVariable String namespaceName,
@PathVariable String branchName, @RequestBody GrayReleaseRuleDTO rules) {
namespaceBranchService
.updateBranchGrayRules(appId, Env.valueOf(env), clusterName, namespaceName, branchName, rules);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.common.dto.GrayReleaseRuleDTO;
import com.ctrip.framework.apollo.common.dto.NamespaceDTO;
import com.ctrip.framework.apollo.common.dto.ReleaseDTO;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.component.PermissionValidator;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.entity.bo.NamespaceBO;
import com.ctrip.framework.apollo.portal.entity.model.NamespaceReleaseModel;
import com.ctrip.framework.apollo.portal.listener.ConfigPublishEvent;
import com.ctrip.framework.apollo.portal.service.NamespaceBranchService;
import com.ctrip.framework.apollo.portal.service.ReleaseService;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class NamespaceBranchController {
private final PermissionValidator permissionValidator;
private final ReleaseService releaseService;
private final NamespaceBranchService namespaceBranchService;
private final ApplicationEventPublisher publisher;
private final PortalConfig portalConfig;
public NamespaceBranchController(
final PermissionValidator permissionValidator,
final ReleaseService releaseService,
final NamespaceBranchService namespaceBranchService,
final ApplicationEventPublisher publisher,
final PortalConfig portalConfig) {
this.permissionValidator = permissionValidator;
this.releaseService = releaseService;
this.namespaceBranchService = namespaceBranchService;
this.publisher = publisher;
this.portalConfig = portalConfig;
}
@GetMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/branches")
public NamespaceBO findBranch(@PathVariable String appId,
@PathVariable String env,
@PathVariable String clusterName,
@PathVariable String namespaceName) {
NamespaceBO namespaceBO = namespaceBranchService.findBranch(appId, Env.valueOf(env), clusterName, namespaceName);
if (namespaceBO != null && permissionValidator.shouldHideConfigToCurrentUser(appId, env, namespaceName)) {
namespaceBO.hideItems();
}
return namespaceBO;
}
@PreAuthorize(value = "@permissionValidator.hasModifyNamespacePermission(#appId, #namespaceName, #env)")
@PostMapping(value = "/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/branches")
public NamespaceDTO createBranch(@PathVariable String appId,
@PathVariable String env,
@PathVariable String clusterName,
@PathVariable String namespaceName) {
return namespaceBranchService.createBranch(appId, Env.valueOf(env), clusterName, namespaceName);
}
@DeleteMapping(value = "/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}")
public void deleteBranch(@PathVariable String appId,
@PathVariable String env,
@PathVariable String clusterName,
@PathVariable String namespaceName,
@PathVariable String branchName) {
boolean canDelete = permissionValidator.hasReleaseNamespacePermission(appId, namespaceName, env) ||
(permissionValidator.hasModifyNamespacePermission(appId, namespaceName, env) &&
releaseService.loadLatestRelease(appId, Env.valueOf(env), branchName, namespaceName) == null);
if (!canDelete) {
throw new AccessDeniedException("Forbidden operation. "
+ "Caused by: 1.you don't have release permission "
+ "or 2. you don't have modification permission "
+ "or 3. you have modification permission but branch has been released");
}
namespaceBranchService.deleteBranch(appId, Env.valueOf(env), clusterName, namespaceName, branchName);
}
@PreAuthorize(value = "@permissionValidator.hasReleaseNamespacePermission(#appId, #namespaceName, #env)")
@PostMapping(value = "/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}/merge")
public ReleaseDTO merge(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName, @PathVariable String namespaceName,
@PathVariable String branchName, @RequestParam(value = "deleteBranch", defaultValue = "true") boolean deleteBranch,
@RequestBody NamespaceReleaseModel model) {
if (model.isEmergencyPublish() && !portalConfig.isEmergencyPublishAllowed(Env.valueOf(env))) {
throw new BadRequestException(String.format("Env: %s is not supported emergency publish now", env));
}
ReleaseDTO createdRelease = namespaceBranchService.merge(appId, Env.valueOf(env), clusterName, namespaceName, branchName,
model.getReleaseTitle(), model.getReleaseComment(),
model.isEmergencyPublish(), deleteBranch);
ConfigPublishEvent event = ConfigPublishEvent.instance();
event.withAppId(appId)
.withCluster(clusterName)
.withNamespace(namespaceName)
.withReleaseId(createdRelease.getId())
.setMergeEvent(true)
.setEnv(Env.valueOf(env));
publisher.publishEvent(event);
return createdRelease;
}
@GetMapping(value = "/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}/rules")
public GrayReleaseRuleDTO getBranchGrayRules(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName,
@PathVariable String namespaceName,
@PathVariable String branchName) {
return namespaceBranchService.findBranchGrayRules(appId, Env.valueOf(env), clusterName, namespaceName, branchName);
}
@PreAuthorize(value = "@permissionValidator.hasOperateNamespacePermission(#appId, #namespaceName, #env)")
@PutMapping(value = "/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces/{namespaceName}/branches/{branchName}/rules")
public void updateBranchRules(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName, @PathVariable String namespaceName,
@PathVariable String branchName, @RequestBody GrayReleaseRuleDTO rules) {
namespaceBranchService
.updateBranchGrayRules(appId, Env.valueOf(env), clusterName, namespaceName, branchName, rules);
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/pom.xml | <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo</artifactId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>apollo-portal</artifactId>
<name>Apollo Portal</name>
<properties>
<github.path>${project.artifactId}</github.path>
<maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
</dependency>
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-common</artifactId>
</dependency>
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-openapi</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<!-- yml processing -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</dependency>
<!-- end of yml processing -->
<!-- JDK 1.8+ -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
</dependency>
<!-- end of JDK 1.8+ -->
<!-- JDK 11+ -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</dependency>
<!-- end of JDK 11+ -->
<!-- test -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<scope>test</scope>
</dependency>
<!-- end of test -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>${project.artifactId}-${project.version}-${package.environment}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/assembly-descriptor.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>1.2.2</version>
<configuration>
<imageName>apolloconfig/${project.artifactId}</imageName>
<imageTags>
<imageTag>${project.version}</imageTag>
<imageTag>latest</imageTag>
</imageTags>
<dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
<serverId>docker-hub</serverId>
<buildArgs>
<VERSION>${project.version}</VERSION>
</buildArgs>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>*.zip</include>
</resource>
</resources>
</configuration>
</plugin>
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.3</version>
<executions>
<execution>
<phase>prepare-package</phase>
<goals>
<goal>replace</goal>
</goals>
</execution>
</executions>
<configuration>
<basedir>${project.build.directory}</basedir>
<includes>
<include>classes/static/*.html</include>
<include>classes/static/**/*.html</include>
</includes>
<replacements>
<replacement>
<token>\.css\"</token>
<value>.css?v=${maven.build.timestamp}\"</value>
</replacement>
<replacement>
<token>\.js\"</token>
<value>.js?v=${maven.build.timestamp}\"</value>
</replacement>
</replacements>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>ctrip</id>
<dependencies>
<dependency>
<groupId>com.ctrip.framework.apollo-sso</groupId>
<artifactId>apollo-sso-ctrip</artifactId>
</dependency>
<dependency>
<groupId>com.ctrip.framework.apollo-ctrip-service</groupId>
<artifactId>apollo-email-service</artifactId>
</dependency>
</dependencies>
</profile>
</profiles>
</project>
| <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo</artifactId>
<version>${revision}</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>apollo-portal</artifactId>
<name>Apollo Portal</name>
<properties>
<github.path>${project.artifactId}</github.path>
<maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
</dependency>
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-common</artifactId>
</dependency>
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-openapi</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<!-- yml processing -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</dependency>
<!-- end of yml processing -->
<!-- JDK 1.8+ -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
</dependency>
<!-- end of JDK 1.8+ -->
<!-- JDK 11+ -->
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</dependency>
<!-- end of JDK 11+ -->
<!-- test -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<scope>test</scope>
</dependency>
<!-- end of test -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<finalName>${project.artifactId}-${project.version}-${package.environment}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/assembly-descriptor.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>1.2.2</version>
<configuration>
<imageName>apolloconfig/${project.artifactId}</imageName>
<imageTags>
<imageTag>${project.version}</imageTag>
<imageTag>latest</imageTag>
</imageTags>
<dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
<serverId>docker-hub</serverId>
<buildArgs>
<VERSION>${project.version}</VERSION>
</buildArgs>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>*.zip</include>
</resource>
</resources>
</configuration>
</plugin>
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.3</version>
<executions>
<execution>
<phase>prepare-package</phase>
<goals>
<goal>replace</goal>
</goals>
</execution>
</executions>
<configuration>
<basedir>${project.build.directory}</basedir>
<includes>
<include>classes/static/*.html</include>
<include>classes/static/**/*.html</include>
</includes>
<replacements>
<replacement>
<token>\.css\"</token>
<value>.css?v=${maven.build.timestamp}\"</value>
</replacement>
<replacement>
<token>\.js\"</token>
<value>.js?v=${maven.build.timestamp}\"</value>
</replacement>
</replacements>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>ctrip</id>
<dependencies>
<dependency>
<groupId>com.ctrip.framework.apollo-sso</groupId>
<artifactId>apollo-sso-ctrip</artifactId>
</dependency>
<dependency>
<groupId>com.ctrip.framework.apollo-ctrip-service</groupId>
<artifactId>apollo-email-service</artifactId>
</dependency>
</dependencies>
</profile>
</profiles>
</project>
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpUtil.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.util.http;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import java.lang.reflect.Type;
/**
* @author Jason Song(song_s@ctrip.com)
* @deprecated in favor of the interface {@link HttpClient} and it's default implementation {@link
* DefaultHttpClient}
*/
@Deprecated
public class HttpUtil implements HttpClient {
private HttpClient m_httpClient;
/**
* Constructor.
*/
public HttpUtil() {
m_httpClient = new DefaultHttpClient();
}
/**
* Do get operation for the http request.
*
* @param httpRequest the request
* @param responseType the response type
* @return the response
* @throws ApolloConfigException if any error happened or response code is neither 200 nor 304
*/
@Override
public <T> HttpResponse<T> doGet(HttpRequest httpRequest, final Class<T> responseType) {
return m_httpClient.doGet(httpRequest, responseType);
}
/**
* Do get operation for the http request.
*
* @param httpRequest the request
* @param responseType the response type
* @return the response
* @throws ApolloConfigException if any error happened or response code is neither 200 nor 304
*/
@Override
public <T> HttpResponse<T> doGet(HttpRequest httpRequest, final Type responseType) {
return m_httpClient.doGet(httpRequest, responseType);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.util.http;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import java.lang.reflect.Type;
/**
* @author Jason Song(song_s@ctrip.com)
* @deprecated in favor of the interface {@link HttpClient} and it's default implementation {@link
* DefaultHttpClient}
*/
@Deprecated
public class HttpUtil implements HttpClient {
private HttpClient m_httpClient;
/**
* Constructor.
*/
public HttpUtil() {
m_httpClient = new DefaultHttpClient();
}
/**
* Do get operation for the http request.
*
* @param httpRequest the request
* @param responseType the response type
* @return the response
* @throws ApolloConfigException if any error happened or response code is neither 200 nor 304
*/
@Override
public <T> HttpResponse<T> doGet(HttpRequest httpRequest, final Class<T> responseType) {
return m_httpClient.doGet(httpRequest, responseType);
}
/**
* Do get operation for the http request.
*
* @param httpRequest the request
* @param responseType the response type
* @return the response
* @throws ApolloConfigException if any error happened or response code is neither 200 nor 304
*/
@Override
public <T> HttpResponse<T> doGet(HttpRequest httpRequest, final Type responseType) {
return m_httpClient.doGet(httpRequest, responseType);
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/vo/LockInfo.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.entity.vo;
public class LockInfo {
private String lockOwner;
private boolean isEmergencyPublishAllowed;
public String getLockOwner() {
return lockOwner;
}
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
public boolean isEmergencyPublishAllowed() {
return isEmergencyPublishAllowed;
}
public void setEmergencyPublishAllowed(boolean emergencyPublishAllowed) {
isEmergencyPublishAllowed = emergencyPublishAllowed;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.entity.vo;
public class LockInfo {
private String lockOwner;
private boolean isEmergencyPublishAllowed;
public String getLockOwner() {
return lockOwner;
}
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
public boolean isEmergencyPublishAllowed() {
return isEmergencyPublishAllowed;
}
public void setEmergencyPublishAllowed(boolean emergencyPublishAllowed) {
isEmergencyPublishAllowed = emergencyPublishAllowed;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/ApolloOpenApiClientTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.openapi.client;
import static org.junit.Assert.*;
import org.junit.Test;
public class ApolloOpenApiClientTest {
@Test
public void testCreate() {
String someUrl = "http://someUrl";
String someToken = "someToken";
ApolloOpenApiClient client = ApolloOpenApiClient.newBuilder().withPortalUrl(someUrl).withToken(someToken).build();
assertEquals(someUrl, client.getPortalUrl());
assertEquals(someToken, client.getToken());
}
@Test(expected = IllegalArgumentException.class)
public void testCreateWithInvalidUrl() {
String someInvalidUrl = "someInvalidUrl";
String someToken = "someToken";
ApolloOpenApiClient.newBuilder().withPortalUrl(someInvalidUrl).withToken(someToken).build();
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.openapi.client;
import static org.junit.Assert.*;
import org.junit.Test;
public class ApolloOpenApiClientTest {
@Test
public void testCreate() {
String someUrl = "http://someUrl";
String someToken = "someToken";
ApolloOpenApiClient client = ApolloOpenApiClient.newBuilder().withPortalUrl(someUrl).withToken(someToken).build();
assertEquals(someUrl, client.getPortalUrl());
assertEquals(someToken, client.getToken());
}
@Test(expected = IllegalArgumentException.class)
public void testCreateWithInvalidUrl() {
String someInvalidUrl = "someInvalidUrl";
String someToken = "someToken";
ApolloOpenApiClient.newBuilder().withPortalUrl(someInvalidUrl).withToken(someToken).build();
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-demo/src/main/java/com/ctrip/framework/apollo/demo/spring/springBootDemo/refresh/SpringBootApolloRefreshConfig.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.demo.spring.springBootDemo.refresh;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.demo.spring.springBootDemo.config.SampleRedisConfig;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.stereotype.Component;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@ConditionalOnProperty("redis.cache.enabled")
@Component
public class SpringBootApolloRefreshConfig {
private static final Logger logger = LoggerFactory.getLogger(SpringBootApolloRefreshConfig.class);
private final SampleRedisConfig sampleRedisConfig;
private final RefreshScope refreshScope;
public SpringBootApolloRefreshConfig(
final SampleRedisConfig sampleRedisConfig,
final RefreshScope refreshScope) {
this.sampleRedisConfig = sampleRedisConfig;
this.refreshScope = refreshScope;
}
@ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, "TEST1.apollo", "application.yaml"},
interestedKeyPrefixes = {"redis.cache."})
public void onChange(ConfigChangeEvent changeEvent) {
logger.info("before refresh {}", sampleRedisConfig.toString());
refreshScope.refresh("sampleRedisConfig");
logger.info("after refresh {}", sampleRedisConfig.toString());
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.demo.spring.springBootDemo.refresh;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.demo.spring.springBootDemo.config.SampleRedisConfig;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.stereotype.Component;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@ConditionalOnProperty("redis.cache.enabled")
@Component
public class SpringBootApolloRefreshConfig {
private static final Logger logger = LoggerFactory.getLogger(SpringBootApolloRefreshConfig.class);
private final SampleRedisConfig sampleRedisConfig;
private final RefreshScope refreshScope;
public SpringBootApolloRefreshConfig(
final SampleRedisConfig sampleRedisConfig,
final RefreshScope refreshScope) {
this.sampleRedisConfig = sampleRedisConfig;
this.refreshScope = refreshScope;
}
@ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, "TEST1.apollo", "application.yaml"},
interestedKeyPrefixes = {"redis.cache."})
public void onChange(ConfigChangeEvent changeEvent) {
logger.info("before refresh {}", sampleRedisConfig.toString());
refreshScope.refresh("sampleRedisConfig");
logger.info("after refresh {}", sampleRedisConfig.toString());
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-core/src/test/java/com/ctrip/framework/foundation/FoundationTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.foundation;
import static org.junit.Assert.assertTrue;
import com.ctrip.framework.foundation.Foundation;
import com.ctrip.framework.foundation.internals.provider.DefaultApplicationProvider;
import com.ctrip.framework.foundation.internals.provider.DefaultServerProvider;
import org.junit.Assert;
import org.junit.Test;
public class FoundationTest {
@Test
public void testApp() {
assertTrue(Foundation.app() instanceof DefaultApplicationProvider);
}
@Test
public void testServer() {
assertTrue(Foundation.server() instanceof DefaultServerProvider);
}
@Test
public void testNet() {
// 获取本机IP和HostName
String hostAddress = Foundation.net().getHostAddress();
String hostName = Foundation.net().getHostName();
Assert.assertNotNull("No host address detected.", hostAddress);
Assert.assertNotNull("No host name resolved.", hostName);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.foundation;
import static org.junit.Assert.assertTrue;
import com.ctrip.framework.foundation.Foundation;
import com.ctrip.framework.foundation.internals.provider.DefaultApplicationProvider;
import com.ctrip.framework.foundation.internals.provider.DefaultServerProvider;
import org.junit.Assert;
import org.junit.Test;
public class FoundationTest {
@Test
public void testApp() {
assertTrue(Foundation.app() instanceof DefaultApplicationProvider);
}
@Test
public void testServer() {
assertTrue(Foundation.server() instanceof DefaultServerProvider);
}
@Test
public void testNet() {
// 获取本机IP和HostName
String hostAddress = Foundation.net().getHostAddress();
String hostName = Foundation.net().getHostName();
Assert.assertNotNull("No host address detected.", hostAddress);
Assert.assertNotNull("No host name resolved.", hostName);
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-core/src/main/java/com/ctrip/framework/apollo/core/enums/Env.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.core.enums;
import com.google.common.base.Preconditions;
/**
* Here is the brief description for all the predefined environments:
* <ul>
* <li>LOCAL: Local Development environment, assume you are working at the beach with no network access</li>
* <li>DEV: Development environment</li>
* <li>FWS: Feature Web Service Test environment</li>
* <li>FAT: Feature Acceptance Test environment</li>
* <li>UAT: User Acceptance Test environment</li>
* <li>LPT: Load and Performance Test environment</li>
* <li>PRO: Production environment</li>
* <li>TOOLS: Tooling environment, a special area in production environment which allows
* access to test environment, e.g. Apollo Portal should be deployed in tools environment</li>
* </ul>
*
* @author Jason Song(song_s@ctrip.com)
*/
public enum Env{
LOCAL, DEV, FWS, FAT, UAT, LPT, PRO, TOOLS, UNKNOWN;
public static Env fromString(String env) {
Env environment = EnvUtils.transformEnv(env);
Preconditions.checkArgument(environment != UNKNOWN, String.format("Env %s is invalid", env));
return environment;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.core.enums;
import com.google.common.base.Preconditions;
/**
* Here is the brief description for all the predefined environments:
* <ul>
* <li>LOCAL: Local Development environment, assume you are working at the beach with no network access</li>
* <li>DEV: Development environment</li>
* <li>FWS: Feature Web Service Test environment</li>
* <li>FAT: Feature Acceptance Test environment</li>
* <li>UAT: User Acceptance Test environment</li>
* <li>LPT: Load and Performance Test environment</li>
* <li>PRO: Production environment</li>
* <li>TOOLS: Tooling environment, a special area in production environment which allows
* access to test environment, e.g. Apollo Portal should be deployed in tools environment</li>
* </ul>
*
* @author Jason Song(song_s@ctrip.com)
*/
public enum Env{
LOCAL, DEV, FWS, FAT, UAT, LPT, PRO, TOOLS, UNKNOWN;
public static Env fromString(String env) {
Env environment = EnvUtils.transformEnv(env);
Preconditions.checkArgument(environment != UNKNOWN, String.format("Env %s is invalid", env));
return environment;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/test/java/com/ctrip/framework/apollo/spring/JavaConfigPlaceholderAutoUpdateTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.internals.SimpleConfig;
import com.ctrip.framework.apollo.internals.YamlConfigFile;
import com.ctrip.framework.apollo.spring.JavaConfigPlaceholderTest.JsonBean;
import com.ctrip.framework.apollo.spring.XmlConfigPlaceholderTest.TestXmlBean;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.google.common.primitives.Ints;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Component;
public class JavaConfigPlaceholderAutoUpdateTest extends AbstractSpringIntegrationTest {
private static final String TIMEOUT_PROPERTY = "timeout";
private static final int DEFAULT_TIMEOUT = 100;
private static final String BATCH_PROPERTY = "batch";
private static final int DEFAULT_BATCH = 200;
private static final String FX_APOLLO_NAMESPACE = "FX.apollo";
private static final String SOME_KEY_PROPERTY = "someKey";
private static final String ANOTHER_KEY_PROPERTY = "anotherKey";
@Test
public void testAutoUpdateWithOneNamespace() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithOneYamlFile() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
YamlConfigFile configFile = prepareYamlConfigFile("application.yaml",
readYamlContentAsConfigFileProperties("case1.yaml"));
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig12.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case1-new.yaml"));
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithValueAndXmlProperty() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig8.class);
TestJavaConfigBean javaConfigBean = context.getBean(TestJavaConfigBean.class);
TestXmlBean xmlBean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, javaConfigBean.getTimeout());
assertEquals(initialBatch, javaConfigBean.getBatch());
assertEquals(initialTimeout, xmlBean.getTimeout());
assertEquals(initialBatch, xmlBean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, javaConfigBean.getTimeout());
assertEquals(newBatch, javaConfigBean.getBatch());
assertEquals(newTimeout, xmlBean.getTimeout());
assertEquals(newBatch, xmlBean.getBatch());
}
@Test
public void testAutoUpdateWithYamlFileWithValueAndXmlProperty() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
YamlConfigFile configFile = prepareYamlConfigFile("application.yaml",
readYamlContentAsConfigFileProperties("case1.yaml"));
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig13.class);
TestJavaConfigBean javaConfigBean = context.getBean(TestJavaConfigBean.class);
TestXmlBean xmlBean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, javaConfigBean.getTimeout());
assertEquals(initialBatch, javaConfigBean.getBatch());
assertEquals(initialTimeout, xmlBean.getTimeout());
assertEquals(initialBatch, xmlBean.getBatch());
configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case1-new.yaml"));
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, javaConfigBean.getTimeout());
assertEquals(newBatch, javaConfigBean.getBatch());
assertEquals(newTimeout, xmlBean.getTimeout());
assertEquals(newBatch, xmlBean.getBatch());
}
@Test
public void testAutoUpdateDisabled() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
MockConfigUtil mockConfigUtil = new MockConfigUtil();
mockConfigUtil.setAutoUpdateInjectedSpringProperties(false);
MockInjector.setInstance(ConfigUtil.class, mockConfigUtil);
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespaces() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout));
Properties fxApolloProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties);
SimpleConfig fxApolloConfig = prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig2.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout));
applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newFxApolloProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(newBatch));
fxApolloConfig.onRepositoryChange(FX_APOLLO_NAMESPACE, newFxApolloProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespacesWithSameProperties() throws Exception {
int someTimeout = 1000;
int someBatch = 2000;
int anotherBatch = 3000;
int someNewTimeout = 1001;
int someNewBatch = 2001;
Properties applicationProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(someBatch));
Properties fxApolloProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch));
prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties);
SimpleConfig fxApolloConfig = prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig2.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
Properties newFxApolloProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(someNewTimeout),
BATCH_PROPERTY, String.valueOf(someNewBatch));
fxApolloConfig.onRepositoryChange(FX_APOLLO_NAMESPACE, newFxApolloProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespacesWithSamePropertiesWithYamlFile() throws Exception {
int someTimeout = 1000;
int someBatch = 2000;
int anotherBatch = 3000;
int someNewBatch = 2001;
YamlConfigFile configFile = prepareYamlConfigFile("application.yml",
readYamlContentAsConfigFileProperties("case2.yml"));
Properties fxApolloProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch));
prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig14.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
configFile.onRepositoryChange("application.yml", readYamlContentAsConfigFileProperties("case2-new.yml"));
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(someNewBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithNewProperties() throws Exception {
int initialTimeout = 1000;
int newTimeout = 1001;
int newBatch = 2001;
Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout));
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
Properties newApplicationProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithNewPropertiesWithYamlFile() throws Exception {
int initialTimeout = 1000;
int newTimeout = 1001;
int newBatch = 2001;
YamlConfigFile configFile = prepareYamlConfigFile("application.yaml",
readYamlContentAsConfigFileProperties("case3.yaml"));
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig12.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case3-new.yaml"));
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithIrrelevantProperties() throws Exception {
int initialTimeout = 1000;
String someIrrelevantKey = "someIrrelevantKey";
String someIrrelevantValue = "someIrrelevantValue";
String anotherIrrelevantKey = "anotherIrrelevantKey";
String anotherIrrelevantValue = "anotherIrrelevantValue";
Properties applicationProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), someIrrelevantKey, someIrrelevantValue);
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
anotherIrrelevantKey, anotherIrrelevantValue);
applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
}
@Test
public void testAutoUpdateWithDeletedProperties() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = new Properties();
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(DEFAULT_TIMEOUT, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
}
@Test
public void testAutoUpdateWithDeletedPropertiesWithYamlFile() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
YamlConfigFile configFile = prepareYamlConfigFile("application.yaml",
readYamlContentAsConfigFileProperties("case4.yaml"));
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig12.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case4-new.yaml"));
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(DEFAULT_TIMEOUT, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespacesWithSamePropertiesDeleted() throws Exception {
int someTimeout = 1000;
int someBatch = 2000;
int anotherBatch = 3000;
Properties applicationProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(someBatch));
Properties fxApolloProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch));
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties);
prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig2.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
Properties newProperties = new Properties();
applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(anotherBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithDeletedPropertiesWithNoDefaultValue() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig6.class);
TestJavaConfigBean5 bean = context.getBean(TestJavaConfigBean5.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(300);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithTypeMismatch() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
String newBatch = "newBatch";
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, newBatch);
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(300);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithTypeMismatchWithYamlFile() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
YamlConfigFile configFile = prepareYamlConfigFile("application.yaml",
readYamlContentAsConfigFileProperties("case5.yaml"));
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig12.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case5-new.yaml"));
TimeUnit.MILLISECONDS.sleep(300);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithValueInjectedAsParameter() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig3.class);
TestJavaConfigBean2 bean = context.getBean(TestJavaConfigBean2.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
// Does not support this scenario
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testApplicationPropertySourceWithValueInjectedInConfiguration() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig7.class);
TestJavaConfigBean2 bean = context.getBean(TestJavaConfigBean2.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
// Does not support this scenario
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithValueInjectedAsConstructorArgs() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig4.class);
TestJavaConfigBean3 bean = context.getBean(TestJavaConfigBean3.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
// Does not support this scenario
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithInvalidSetter() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig5.class);
TestJavaConfigBean4 bean = context.getBean(TestJavaConfigBean4.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
// Does not support this scenario
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithNestedProperty() throws Exception {
String someKeyValue = "someKeyValue";
String anotherKeyValue = "anotherKeyValue";
String newKeyValue = "newKeyValue";
int someValue = 1234;
int someNewValue = 2345;
Properties properties = assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY, anotherKeyValue,
String.format("%s.%s", someKeyValue, anotherKeyValue), String.valueOf(someValue));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig1.class);
TestNestedPropertyBean bean = context.getBean(TestNestedPropertyBean.class);
assertEquals(someValue, bean.getNestedProperty());
Properties newProperties = assembleProperties(SOME_KEY_PROPERTY, newKeyValue, ANOTHER_KEY_PROPERTY, anotherKeyValue,
String.format("%s.%s", newKeyValue, anotherKeyValue), String.valueOf(someNewValue));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewValue, bean.getNestedProperty());
}
@Test
public void testAutoUpdateWithNotSupportedNestedProperty() throws Exception {
String someKeyValue = "someKeyValue";
String anotherKeyValue = "anotherKeyValue";
int someValue = 1234;
int someNewValue = 2345;
Properties properties = assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY, anotherKeyValue,
String.format("%s.%s", someKeyValue, anotherKeyValue), String.valueOf(someValue));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig1.class);
TestNestedPropertyBean bean = context.getBean(TestNestedPropertyBean.class);
assertEquals(someValue, bean.getNestedProperty());
Properties newProperties = assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY,
anotherKeyValue, String.format("%s.%s", someKeyValue, anotherKeyValue), String.valueOf(someNewValue));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
// Does not support this scenario
assertEquals(someValue, bean.getNestedProperty());
}
@Test
public void testAutoUpdateWithNestedPropertyWithDefaultValue() throws Exception {
String someKeyValue = "someKeyValue";
String someNewKeyValue = "someNewKeyValue";
int someValue = 1234;
int someNewValue = 2345;
Properties properties =
assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY, String.valueOf(someValue));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig2.class);
TestNestedPropertyBeanWithDefaultValue bean = context.getBean(TestNestedPropertyBeanWithDefaultValue.class);
assertEquals(someValue, bean.getNestedProperty());
Properties newProperties = assembleProperties(SOME_KEY_PROPERTY, someNewKeyValue, ANOTHER_KEY_PROPERTY,
String.valueOf(someValue), someNewKeyValue, String.valueOf(someNewValue));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewValue, bean.getNestedProperty());
}
@Test
public void testAutoUpdateWithMultipleNestedProperty() throws Exception {
String someKeyValue = "someKeyValue";
String someNewKeyValue = "someNewKeyValue";
String anotherKeyValue = "anotherKeyValue";
String someNestedKey = "someNestedKey";
String someNestedPlaceholder = String.format("${%s}", someNestedKey);
String anotherNestedKey = "anotherNestedKey";
String anotherNestedPlaceholder = String.format("${%s}", anotherNestedKey);
int someValue = 1234;
int someNewValue = 2345;
Properties properties = assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY, anotherKeyValue,
someKeyValue, someNestedPlaceholder);
properties.setProperty(someNestedKey, String.valueOf(someValue));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig2.class);
TestNestedPropertyBeanWithDefaultValue bean = context.getBean(TestNestedPropertyBeanWithDefaultValue.class);
assertEquals(someValue, bean.getNestedProperty());
Properties newProperties = assembleProperties(SOME_KEY_PROPERTY, someNewKeyValue, ANOTHER_KEY_PROPERTY,
anotherKeyValue, someNewKeyValue, anotherNestedPlaceholder);
newProperties.setProperty(anotherNestedKey, String.valueOf(someNewValue));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewValue, bean.getNestedProperty());
}
@Test
public void testAutoUpdateWithAllKindsOfDataTypes() throws Exception {
int someInt = 1000;
int someNewInt = 1001;
int[] someIntArray = {1, 2, 3, 4};
int[] someNewIntArray = {5, 6, 7, 8};
long someLong = 2000L;
long someNewLong = 2001L;
short someShort = 3000;
short someNewShort = 3001;
float someFloat = 1.2F;
float someNewFloat = 2.2F;
double someDouble = 3.10D;
double someNewDouble = 4.10D;
byte someByte = 123;
byte someNewByte = 124;
boolean someBoolean = true;
boolean someNewBoolean = !someBoolean;
String someString = "someString";
String someNewString = "someNewString";
String someJsonProperty = "[{\"a\":\"astring\", \"b\":10},{\"a\":\"astring2\", \"b\":20}]";
String someNewJsonProperty = "[{\"a\":\"newString\", \"b\":20},{\"a\":\"astring2\", \"b\":20}]";
String someDateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
Date someDate = assembleDate(2018, 2, 23, 20, 1, 2, 123);
Date someNewDate = assembleDate(2018, 2, 23, 21, 2, 3, 345);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(someDateFormat, Locale.US);
Properties properties = new Properties();
properties.setProperty("intProperty", String.valueOf(someInt));
properties.setProperty("intArrayProperty", Ints.join(", ", someIntArray));
properties.setProperty("longProperty", String.valueOf(someLong));
properties.setProperty("shortProperty", String.valueOf(someShort));
properties.setProperty("floatProperty", String.valueOf(someFloat));
properties.setProperty("doubleProperty", String.valueOf(someDouble));
properties.setProperty("byteProperty", String.valueOf(someByte));
properties.setProperty("booleanProperty", String.valueOf(someBoolean));
properties.setProperty("stringProperty", someString);
properties.setProperty("dateFormat", someDateFormat);
properties.setProperty("dateProperty", simpleDateFormat.format(someDate));
properties.setProperty("jsonProperty", someJsonProperty);
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig9.class);
TestAllKindsOfDataTypesBean bean = context.getBean(TestAllKindsOfDataTypesBean.class);
assertEquals(someInt, bean.getIntProperty());
assertArrayEquals(someIntArray, bean.getIntArrayProperty());
assertEquals(someLong, bean.getLongProperty());
assertEquals(someShort, bean.getShortProperty());
assertEquals(someFloat, bean.getFloatProperty(), 0.001F);
assertEquals(someDouble, bean.getDoubleProperty(), 0.001D);
assertEquals(someByte, bean.getByteProperty());
assertEquals(someBoolean, bean.getBooleanProperty());
assertEquals(someString, bean.getStringProperty());
assertEquals(someDate, bean.getDateProperty());
assertEquals("astring", bean.getJsonBeanList().get(0).getA());
assertEquals(10, bean.getJsonBeanList().get(0).getB());
Properties newProperties = new Properties();
newProperties.setProperty("intProperty", String.valueOf(someNewInt));
newProperties.setProperty("intArrayProperty", Ints.join(", ", someNewIntArray));
newProperties.setProperty("longProperty", String.valueOf(someNewLong));
newProperties.setProperty("shortProperty", String.valueOf(someNewShort));
newProperties.setProperty("floatProperty", String.valueOf(someNewFloat));
newProperties.setProperty("doubleProperty", String.valueOf(someNewDouble));
newProperties.setProperty("byteProperty", String.valueOf(someNewByte));
newProperties.setProperty("booleanProperty", String.valueOf(someNewBoolean));
newProperties.setProperty("stringProperty", someNewString);
newProperties.setProperty("dateFormat", someDateFormat);
newProperties.setProperty("dateProperty", simpleDateFormat.format(someNewDate));
newProperties.setProperty("jsonProperty", someNewJsonProperty);
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewInt, bean.getIntProperty());
assertArrayEquals(someNewIntArray, bean.getIntArrayProperty());
assertEquals(someNewLong, bean.getLongProperty());
assertEquals(someNewShort, bean.getShortProperty());
assertEquals(someNewFloat, bean.getFloatProperty(), 0.001F);
assertEquals(someNewDouble, bean.getDoubleProperty(), 0.001D);
assertEquals(someNewByte, bean.getByteProperty());
assertEquals(someNewBoolean, bean.getBooleanProperty());
assertEquals(someNewString, bean.getStringProperty());
assertEquals(someNewDate, bean.getDateProperty());
assertEquals("newString", bean.getJsonBeanList().get(0).getA());
assertEquals(20, bean.getJsonBeanList().get(0).getB());
}
@Test
public void testAutoUpdateJsonValueWithInvalidValue() throws Exception {
String someValidValue = "{\"a\":\"someString\", \"b\":10}";
String someInvalidValue = "someInvalidValue";
Properties properties = assembleProperties("jsonProperty", someValidValue);
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig10.class);
TestApolloJsonValue bean = context.getBean(TestApolloJsonValue.class);
JsonBean jsonBean = bean.getJsonBean();
assertEquals("someString", jsonBean.getA());
assertEquals(10, jsonBean.getB());
Properties newProperties = assembleProperties("jsonProperty", someInvalidValue);
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(300);
// should not change anything
assertTrue(jsonBean == bean.getJsonBean());
}
@Test
public void testAutoUpdateJsonValueWithNoValueAndNoDefaultValue() throws Exception {
String someValidValue = "{\"a\":\"someString\", \"b\":10}";
Properties properties = assembleProperties("jsonProperty", someValidValue);
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig10.class);
TestApolloJsonValue bean = context.getBean(TestApolloJsonValue.class);
JsonBean jsonBean = bean.getJsonBean();
assertEquals("someString", jsonBean.getA());
assertEquals(10, jsonBean.getB());
Properties newProperties = new Properties();
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(300);
// should not change anything
assertTrue(jsonBean == bean.getJsonBean());
}
@Test
public void testAutoUpdateJsonValueWithNoValueAndDefaultValue() throws Exception {
String someValidValue = "{\"a\":\"someString\", \"b\":10}";
Properties properties = assembleProperties("jsonProperty", someValidValue);
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig11.class);
TestApolloJsonValueWithDefaultValue bean = context.getBean(TestApolloJsonValueWithDefaultValue.class);
JsonBean jsonBean = bean.getJsonBean();
assertEquals("someString", jsonBean.getA());
assertEquals(10, jsonBean.getB());
Properties newProperties = new Properties();
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
JsonBean newJsonBean = bean.getJsonBean();
assertEquals("defaultString", newJsonBean.getA());
assertEquals(1, newJsonBean.getB());
}
@Configuration
@EnableApolloConfig
static class AppConfig1 {
@Bean
TestJavaConfigBean testJavaConfigBean() {
return new TestJavaConfigBean();
}
}
@Configuration
@EnableApolloConfig({"application", "FX.apollo"})
static class AppConfig2 {
@Bean
TestJavaConfigBean testJavaConfigBean() {
return new TestJavaConfigBean();
}
}
@Configuration
@EnableApolloConfig
static class AppConfig3 {
/**
* This case won't get auto updated
*/
@Bean
TestJavaConfigBean2 testJavaConfigBean2(@Value("${timeout:100}") int timeout, @Value("${batch:200}") int batch) {
TestJavaConfigBean2 bean = new TestJavaConfigBean2();
bean.setTimeout(timeout);
bean.setBatch(batch);
return bean;
}
}
@Configuration
@ComponentScan(includeFilters = {@Filter(type = FilterType.ANNOTATION, value = {Component.class})},
excludeFilters = {@Filter(type = FilterType.ANNOTATION, value = {Configuration.class})})
@EnableApolloConfig
static class AppConfig4 {
}
@Configuration
@EnableApolloConfig
static class AppConfig5 {
@Bean
TestJavaConfigBean4 testJavaConfigBean() {
return new TestJavaConfigBean4();
}
}
@Configuration
@EnableApolloConfig
static class AppConfig6 {
@Bean
TestJavaConfigBean5 testJavaConfigBean() {
return new TestJavaConfigBean5();
}
}
@Configuration
@EnableApolloConfig
static class AppConfig7 {
@Value("${batch}")
private int batch;
@Bean
@Value("${timeout}")
TestJavaConfigBean2 testJavaConfigBean2(int timeout) {
TestJavaConfigBean2 bean = new TestJavaConfigBean2();
bean.setTimeout(timeout);
bean.setBatch(batch);
return bean;
}
}
@Configuration
@EnableApolloConfig
@ImportResource("spring/XmlConfigPlaceholderTest1.xml")
static class AppConfig8 {
@Bean
TestJavaConfigBean testJavaConfigBean() {
return new TestJavaConfigBean();
}
}
@Configuration
@EnableApolloConfig
static class AppConfig9 {
@Bean
TestAllKindsOfDataTypesBean testAllKindsOfDataTypesBean() {
return new TestAllKindsOfDataTypesBean();
}
}
@Configuration
@EnableApolloConfig
static class NestedPropertyConfig1 {
@Bean
TestNestedPropertyBean testNestedPropertyBean() {
return new TestNestedPropertyBean();
}
}
@Configuration
@EnableApolloConfig
static class NestedPropertyConfig2 {
@Bean
TestNestedPropertyBeanWithDefaultValue testNestedPropertyBean() {
return new TestNestedPropertyBeanWithDefaultValue();
}
}
@Configuration
@EnableApolloConfig
static class AppConfig10 {
@Bean
TestApolloJsonValue testApolloJsonValue() {
return new TestApolloJsonValue();
}
}
@Configuration
@EnableApolloConfig
static class AppConfig11 {
@Bean
TestApolloJsonValueWithDefaultValue testApolloJsonValue() {
return new TestApolloJsonValueWithDefaultValue();
}
}
@Configuration
@EnableApolloConfig("application.yaMl")
static class AppConfig12 {
@Bean
TestJavaConfigBean testJavaConfigBean() {
return new TestJavaConfigBean();
}
}
@Configuration
@EnableApolloConfig("application.yaml")
@ImportResource("spring/XmlConfigPlaceholderTest11.xml")
static class AppConfig13 {
@Bean
TestJavaConfigBean testJavaConfigBean() {
return new TestJavaConfigBean();
}
}
@Configuration
@EnableApolloConfig({"application.yml", "FX.apollo"})
static class AppConfig14 {
@Bean
TestJavaConfigBean testJavaConfigBean() {
return new TestJavaConfigBean();
}
}
static class TestJavaConfigBean {
@Value("${timeout:100}")
private int timeout;
private int batch;
@Value("${batch:200}")
public void setBatch(int batch) {
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
static class TestJavaConfigBean2 {
private int timeout;
private int batch;
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public int getBatch() {
return batch;
}
public void setBatch(int batch) {
this.batch = batch;
}
}
/**
* This case won't get auto updated
*/
@Component
static class TestJavaConfigBean3 {
private final int timeout;
private final int batch;
@Autowired
public TestJavaConfigBean3(@Value("${timeout:100}") int timeout, @Value("${batch:200}") int batch) {
this.timeout = timeout;
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
/**
* This case won't get auto updated
*/
static class TestJavaConfigBean4 {
private int timeout;
private int batch;
@Value("${batch:200}")
public void setValues(int batch, @Value("${timeout:100}") int timeout) {
this.batch = batch;
this.timeout = timeout;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
static class TestJavaConfigBean5 {
@Value("${timeout}")
private int timeout;
private int batch;
@Value("${batch}")
public void setBatch(int batch) {
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
static class TestNestedPropertyBean {
@Value("${${someKey}.${anotherKey}}")
private int nestedProperty;
public int getNestedProperty() {
return nestedProperty;
}
}
static class TestNestedPropertyBeanWithDefaultValue {
@Value("${${someKey}:${anotherKey}}")
private int nestedProperty;
public int getNestedProperty() {
return nestedProperty;
}
}
static class TestAllKindsOfDataTypesBean {
@Value("${intProperty}")
private int intProperty;
@Value("${intArrayProperty}")
private int[] intArrayProperty;
@Value("${longProperty}")
private long longProperty;
@Value("${shortProperty}")
private short shortProperty;
@Value("${floatProperty}")
private float floatProperty;
@Value("${doubleProperty}")
private double doubleProperty;
@Value("${byteProperty}")
private byte byteProperty;
@Value("${booleanProperty}")
private boolean booleanProperty;
@Value("${stringProperty}")
private String stringProperty;
@Value("#{new java.text.SimpleDateFormat('${dateFormat}').parse('${dateProperty}')}")
private Date dateProperty;
@ApolloJsonValue("${jsonProperty}")
private List<JsonBean> jsonBeanList;
public int getIntProperty() {
return intProperty;
}
public int[] getIntArrayProperty() {
return intArrayProperty;
}
public long getLongProperty() {
return longProperty;
}
public short getShortProperty() {
return shortProperty;
}
public float getFloatProperty() {
return floatProperty;
}
public double getDoubleProperty() {
return doubleProperty;
}
public byte getByteProperty() {
return byteProperty;
}
public boolean getBooleanProperty() {
return booleanProperty;
}
public String getStringProperty() {
return stringProperty;
}
public Date getDateProperty() {
return dateProperty;
}
public List<JsonBean> getJsonBeanList() {
return jsonBeanList;
}
}
static class TestApolloJsonValue {
@ApolloJsonValue("${jsonProperty}")
private JsonBean jsonBean;
public JsonBean getJsonBean() {
return jsonBean;
}
}
static class TestApolloJsonValueWithDefaultValue {
@ApolloJsonValue("${jsonProperty:{\"a\":\"defaultString\", \"b\":1}}")
private JsonBean jsonBean;
public JsonBean getJsonBean() {
return jsonBean;
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.internals.SimpleConfig;
import com.ctrip.framework.apollo.internals.YamlConfigFile;
import com.ctrip.framework.apollo.spring.JavaConfigPlaceholderTest.JsonBean;
import com.ctrip.framework.apollo.spring.XmlConfigPlaceholderTest.TestXmlBean;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.google.common.primitives.Ints;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Component;
public class JavaConfigPlaceholderAutoUpdateTest extends AbstractSpringIntegrationTest {
private static final String TIMEOUT_PROPERTY = "timeout";
private static final int DEFAULT_TIMEOUT = 100;
private static final String BATCH_PROPERTY = "batch";
private static final int DEFAULT_BATCH = 200;
private static final String FX_APOLLO_NAMESPACE = "FX.apollo";
private static final String SOME_KEY_PROPERTY = "someKey";
private static final String ANOTHER_KEY_PROPERTY = "anotherKey";
@Test
public void testAutoUpdateWithOneNamespace() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithOneYamlFile() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
YamlConfigFile configFile = prepareYamlConfigFile("application.yaml",
readYamlContentAsConfigFileProperties("case1.yaml"));
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig12.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case1-new.yaml"));
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithValueAndXmlProperty() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig8.class);
TestJavaConfigBean javaConfigBean = context.getBean(TestJavaConfigBean.class);
TestXmlBean xmlBean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, javaConfigBean.getTimeout());
assertEquals(initialBatch, javaConfigBean.getBatch());
assertEquals(initialTimeout, xmlBean.getTimeout());
assertEquals(initialBatch, xmlBean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, javaConfigBean.getTimeout());
assertEquals(newBatch, javaConfigBean.getBatch());
assertEquals(newTimeout, xmlBean.getTimeout());
assertEquals(newBatch, xmlBean.getBatch());
}
@Test
public void testAutoUpdateWithYamlFileWithValueAndXmlProperty() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
YamlConfigFile configFile = prepareYamlConfigFile("application.yaml",
readYamlContentAsConfigFileProperties("case1.yaml"));
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig13.class);
TestJavaConfigBean javaConfigBean = context.getBean(TestJavaConfigBean.class);
TestXmlBean xmlBean = context.getBean(TestXmlBean.class);
assertEquals(initialTimeout, javaConfigBean.getTimeout());
assertEquals(initialBatch, javaConfigBean.getBatch());
assertEquals(initialTimeout, xmlBean.getTimeout());
assertEquals(initialBatch, xmlBean.getBatch());
configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case1-new.yaml"));
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, javaConfigBean.getTimeout());
assertEquals(newBatch, javaConfigBean.getBatch());
assertEquals(newTimeout, xmlBean.getTimeout());
assertEquals(newBatch, xmlBean.getBatch());
}
@Test
public void testAutoUpdateDisabled() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
MockConfigUtil mockConfigUtil = new MockConfigUtil();
mockConfigUtil.setAutoUpdateInjectedSpringProperties(false);
MockInjector.setInstance(ConfigUtil.class, mockConfigUtil);
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespaces() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout));
Properties fxApolloProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(initialBatch));
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties);
SimpleConfig fxApolloConfig = prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig2.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout));
applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newFxApolloProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(newBatch));
fxApolloConfig.onRepositoryChange(FX_APOLLO_NAMESPACE, newFxApolloProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespacesWithSameProperties() throws Exception {
int someTimeout = 1000;
int someBatch = 2000;
int anotherBatch = 3000;
int someNewTimeout = 1001;
int someNewBatch = 2001;
Properties applicationProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(someBatch));
Properties fxApolloProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch));
prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties);
SimpleConfig fxApolloConfig = prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig2.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
Properties newFxApolloProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(someNewTimeout),
BATCH_PROPERTY, String.valueOf(someNewBatch));
fxApolloConfig.onRepositoryChange(FX_APOLLO_NAMESPACE, newFxApolloProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespacesWithSamePropertiesWithYamlFile() throws Exception {
int someTimeout = 1000;
int someBatch = 2000;
int anotherBatch = 3000;
int someNewBatch = 2001;
YamlConfigFile configFile = prepareYamlConfigFile("application.yml",
readYamlContentAsConfigFileProperties("case2.yml"));
Properties fxApolloProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch));
prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig14.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
configFile.onRepositoryChange("application.yml", readYamlContentAsConfigFileProperties("case2-new.yml"));
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(someNewBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithNewProperties() throws Exception {
int initialTimeout = 1000;
int newTimeout = 1001;
int newBatch = 2001;
Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout));
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
Properties newApplicationProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithNewPropertiesWithYamlFile() throws Exception {
int initialTimeout = 1000;
int newTimeout = 1001;
int newBatch = 2001;
YamlConfigFile configFile = prepareYamlConfigFile("application.yaml",
readYamlContentAsConfigFileProperties("case3.yaml"));
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig12.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case3-new.yaml"));
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(newBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithIrrelevantProperties() throws Exception {
int initialTimeout = 1000;
String someIrrelevantKey = "someIrrelevantKey";
String someIrrelevantValue = "someIrrelevantValue";
String anotherIrrelevantKey = "anotherIrrelevantKey";
String anotherIrrelevantValue = "anotherIrrelevantValue";
Properties applicationProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), someIrrelevantKey, someIrrelevantValue);
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout),
anotherIrrelevantKey, anotherIrrelevantValue);
applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
}
@Test
public void testAutoUpdateWithDeletedProperties() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = new Properties();
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(DEFAULT_TIMEOUT, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
}
@Test
public void testAutoUpdateWithDeletedPropertiesWithYamlFile() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
YamlConfigFile configFile = prepareYamlConfigFile("application.yaml",
readYamlContentAsConfigFileProperties("case4.yaml"));
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig12.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case4-new.yaml"));
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(DEFAULT_TIMEOUT, bean.getTimeout());
assertEquals(DEFAULT_BATCH, bean.getBatch());
}
@Test
public void testAutoUpdateWithMultipleNamespacesWithSamePropertiesDeleted() throws Exception {
int someTimeout = 1000;
int someBatch = 2000;
int anotherBatch = 3000;
Properties applicationProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(someBatch));
Properties fxApolloProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch));
SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties);
prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig2.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(someBatch, bean.getBatch());
Properties newProperties = new Properties();
applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someTimeout, bean.getTimeout());
assertEquals(anotherBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithDeletedPropertiesWithNoDefaultValue() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig6.class);
TestJavaConfigBean5 bean = context.getBean(TestJavaConfigBean5.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(300);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithTypeMismatch() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
String newBatch = "newBatch";
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, newBatch);
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(300);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithTypeMismatchWithYamlFile() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
YamlConfigFile configFile = prepareYamlConfigFile("application.yaml",
readYamlContentAsConfigFileProperties("case5.yaml"));
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig12.class);
TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case5-new.yaml"));
TimeUnit.MILLISECONDS.sleep(300);
assertEquals(newTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithValueInjectedAsParameter() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig3.class);
TestJavaConfigBean2 bean = context.getBean(TestJavaConfigBean2.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
// Does not support this scenario
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testApplicationPropertySourceWithValueInjectedInConfiguration() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig7.class);
TestJavaConfigBean2 bean = context.getBean(TestJavaConfigBean2.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
// Does not support this scenario
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithValueInjectedAsConstructorArgs() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig4.class);
TestJavaConfigBean3 bean = context.getBean(TestJavaConfigBean3.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
// Does not support this scenario
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithInvalidSetter() throws Exception {
int initialTimeout = 1000;
int initialBatch = 2000;
int newTimeout = 1001;
int newBatch = 2001;
Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY,
String.valueOf(initialBatch));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig5.class);
TestJavaConfigBean4 bean = context.getBean(TestJavaConfigBean4.class);
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
Properties newProperties =
assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
// Does not support this scenario
assertEquals(initialTimeout, bean.getTimeout());
assertEquals(initialBatch, bean.getBatch());
}
@Test
public void testAutoUpdateWithNestedProperty() throws Exception {
String someKeyValue = "someKeyValue";
String anotherKeyValue = "anotherKeyValue";
String newKeyValue = "newKeyValue";
int someValue = 1234;
int someNewValue = 2345;
Properties properties = assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY, anotherKeyValue,
String.format("%s.%s", someKeyValue, anotherKeyValue), String.valueOf(someValue));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig1.class);
TestNestedPropertyBean bean = context.getBean(TestNestedPropertyBean.class);
assertEquals(someValue, bean.getNestedProperty());
Properties newProperties = assembleProperties(SOME_KEY_PROPERTY, newKeyValue, ANOTHER_KEY_PROPERTY, anotherKeyValue,
String.format("%s.%s", newKeyValue, anotherKeyValue), String.valueOf(someNewValue));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewValue, bean.getNestedProperty());
}
@Test
public void testAutoUpdateWithNotSupportedNestedProperty() throws Exception {
String someKeyValue = "someKeyValue";
String anotherKeyValue = "anotherKeyValue";
int someValue = 1234;
int someNewValue = 2345;
Properties properties = assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY, anotherKeyValue,
String.format("%s.%s", someKeyValue, anotherKeyValue), String.valueOf(someValue));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig1.class);
TestNestedPropertyBean bean = context.getBean(TestNestedPropertyBean.class);
assertEquals(someValue, bean.getNestedProperty());
Properties newProperties = assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY,
anotherKeyValue, String.format("%s.%s", someKeyValue, anotherKeyValue), String.valueOf(someNewValue));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
// Does not support this scenario
assertEquals(someValue, bean.getNestedProperty());
}
@Test
public void testAutoUpdateWithNestedPropertyWithDefaultValue() throws Exception {
String someKeyValue = "someKeyValue";
String someNewKeyValue = "someNewKeyValue";
int someValue = 1234;
int someNewValue = 2345;
Properties properties =
assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY, String.valueOf(someValue));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig2.class);
TestNestedPropertyBeanWithDefaultValue bean = context.getBean(TestNestedPropertyBeanWithDefaultValue.class);
assertEquals(someValue, bean.getNestedProperty());
Properties newProperties = assembleProperties(SOME_KEY_PROPERTY, someNewKeyValue, ANOTHER_KEY_PROPERTY,
String.valueOf(someValue), someNewKeyValue, String.valueOf(someNewValue));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewValue, bean.getNestedProperty());
}
@Test
public void testAutoUpdateWithMultipleNestedProperty() throws Exception {
String someKeyValue = "someKeyValue";
String someNewKeyValue = "someNewKeyValue";
String anotherKeyValue = "anotherKeyValue";
String someNestedKey = "someNestedKey";
String someNestedPlaceholder = String.format("${%s}", someNestedKey);
String anotherNestedKey = "anotherNestedKey";
String anotherNestedPlaceholder = String.format("${%s}", anotherNestedKey);
int someValue = 1234;
int someNewValue = 2345;
Properties properties = assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY, anotherKeyValue,
someKeyValue, someNestedPlaceholder);
properties.setProperty(someNestedKey, String.valueOf(someValue));
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig2.class);
TestNestedPropertyBeanWithDefaultValue bean = context.getBean(TestNestedPropertyBeanWithDefaultValue.class);
assertEquals(someValue, bean.getNestedProperty());
Properties newProperties = assembleProperties(SOME_KEY_PROPERTY, someNewKeyValue, ANOTHER_KEY_PROPERTY,
anotherKeyValue, someNewKeyValue, anotherNestedPlaceholder);
newProperties.setProperty(anotherNestedKey, String.valueOf(someNewValue));
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewValue, bean.getNestedProperty());
}
@Test
public void testAutoUpdateWithAllKindsOfDataTypes() throws Exception {
int someInt = 1000;
int someNewInt = 1001;
int[] someIntArray = {1, 2, 3, 4};
int[] someNewIntArray = {5, 6, 7, 8};
long someLong = 2000L;
long someNewLong = 2001L;
short someShort = 3000;
short someNewShort = 3001;
float someFloat = 1.2F;
float someNewFloat = 2.2F;
double someDouble = 3.10D;
double someNewDouble = 4.10D;
byte someByte = 123;
byte someNewByte = 124;
boolean someBoolean = true;
boolean someNewBoolean = !someBoolean;
String someString = "someString";
String someNewString = "someNewString";
String someJsonProperty = "[{\"a\":\"astring\", \"b\":10},{\"a\":\"astring2\", \"b\":20}]";
String someNewJsonProperty = "[{\"a\":\"newString\", \"b\":20},{\"a\":\"astring2\", \"b\":20}]";
String someDateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
Date someDate = assembleDate(2018, 2, 23, 20, 1, 2, 123);
Date someNewDate = assembleDate(2018, 2, 23, 21, 2, 3, 345);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(someDateFormat, Locale.US);
Properties properties = new Properties();
properties.setProperty("intProperty", String.valueOf(someInt));
properties.setProperty("intArrayProperty", Ints.join(", ", someIntArray));
properties.setProperty("longProperty", String.valueOf(someLong));
properties.setProperty("shortProperty", String.valueOf(someShort));
properties.setProperty("floatProperty", String.valueOf(someFloat));
properties.setProperty("doubleProperty", String.valueOf(someDouble));
properties.setProperty("byteProperty", String.valueOf(someByte));
properties.setProperty("booleanProperty", String.valueOf(someBoolean));
properties.setProperty("stringProperty", someString);
properties.setProperty("dateFormat", someDateFormat);
properties.setProperty("dateProperty", simpleDateFormat.format(someDate));
properties.setProperty("jsonProperty", someJsonProperty);
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig9.class);
TestAllKindsOfDataTypesBean bean = context.getBean(TestAllKindsOfDataTypesBean.class);
assertEquals(someInt, bean.getIntProperty());
assertArrayEquals(someIntArray, bean.getIntArrayProperty());
assertEquals(someLong, bean.getLongProperty());
assertEquals(someShort, bean.getShortProperty());
assertEquals(someFloat, bean.getFloatProperty(), 0.001F);
assertEquals(someDouble, bean.getDoubleProperty(), 0.001D);
assertEquals(someByte, bean.getByteProperty());
assertEquals(someBoolean, bean.getBooleanProperty());
assertEquals(someString, bean.getStringProperty());
assertEquals(someDate, bean.getDateProperty());
assertEquals("astring", bean.getJsonBeanList().get(0).getA());
assertEquals(10, bean.getJsonBeanList().get(0).getB());
Properties newProperties = new Properties();
newProperties.setProperty("intProperty", String.valueOf(someNewInt));
newProperties.setProperty("intArrayProperty", Ints.join(", ", someNewIntArray));
newProperties.setProperty("longProperty", String.valueOf(someNewLong));
newProperties.setProperty("shortProperty", String.valueOf(someNewShort));
newProperties.setProperty("floatProperty", String.valueOf(someNewFloat));
newProperties.setProperty("doubleProperty", String.valueOf(someNewDouble));
newProperties.setProperty("byteProperty", String.valueOf(someNewByte));
newProperties.setProperty("booleanProperty", String.valueOf(someNewBoolean));
newProperties.setProperty("stringProperty", someNewString);
newProperties.setProperty("dateFormat", someDateFormat);
newProperties.setProperty("dateProperty", simpleDateFormat.format(someNewDate));
newProperties.setProperty("jsonProperty", someNewJsonProperty);
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
assertEquals(someNewInt, bean.getIntProperty());
assertArrayEquals(someNewIntArray, bean.getIntArrayProperty());
assertEquals(someNewLong, bean.getLongProperty());
assertEquals(someNewShort, bean.getShortProperty());
assertEquals(someNewFloat, bean.getFloatProperty(), 0.001F);
assertEquals(someNewDouble, bean.getDoubleProperty(), 0.001D);
assertEquals(someNewByte, bean.getByteProperty());
assertEquals(someNewBoolean, bean.getBooleanProperty());
assertEquals(someNewString, bean.getStringProperty());
assertEquals(someNewDate, bean.getDateProperty());
assertEquals("newString", bean.getJsonBeanList().get(0).getA());
assertEquals(20, bean.getJsonBeanList().get(0).getB());
}
@Test
public void testAutoUpdateJsonValueWithInvalidValue() throws Exception {
String someValidValue = "{\"a\":\"someString\", \"b\":10}";
String someInvalidValue = "someInvalidValue";
Properties properties = assembleProperties("jsonProperty", someValidValue);
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig10.class);
TestApolloJsonValue bean = context.getBean(TestApolloJsonValue.class);
JsonBean jsonBean = bean.getJsonBean();
assertEquals("someString", jsonBean.getA());
assertEquals(10, jsonBean.getB());
Properties newProperties = assembleProperties("jsonProperty", someInvalidValue);
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(300);
// should not change anything
assertTrue(jsonBean == bean.getJsonBean());
}
@Test
public void testAutoUpdateJsonValueWithNoValueAndNoDefaultValue() throws Exception {
String someValidValue = "{\"a\":\"someString\", \"b\":10}";
Properties properties = assembleProperties("jsonProperty", someValidValue);
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig10.class);
TestApolloJsonValue bean = context.getBean(TestApolloJsonValue.class);
JsonBean jsonBean = bean.getJsonBean();
assertEquals("someString", jsonBean.getA());
assertEquals(10, jsonBean.getB());
Properties newProperties = new Properties();
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(300);
// should not change anything
assertTrue(jsonBean == bean.getJsonBean());
}
@Test
public void testAutoUpdateJsonValueWithNoValueAndDefaultValue() throws Exception {
String someValidValue = "{\"a\":\"someString\", \"b\":10}";
Properties properties = assembleProperties("jsonProperty", someValidValue);
SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig11.class);
TestApolloJsonValueWithDefaultValue bean = context.getBean(TestApolloJsonValueWithDefaultValue.class);
JsonBean jsonBean = bean.getJsonBean();
assertEquals("someString", jsonBean.getA());
assertEquals(10, jsonBean.getB());
Properties newProperties = new Properties();
config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties);
TimeUnit.MILLISECONDS.sleep(100);
JsonBean newJsonBean = bean.getJsonBean();
assertEquals("defaultString", newJsonBean.getA());
assertEquals(1, newJsonBean.getB());
}
@Configuration
@EnableApolloConfig
static class AppConfig1 {
@Bean
TestJavaConfigBean testJavaConfigBean() {
return new TestJavaConfigBean();
}
}
@Configuration
@EnableApolloConfig({"application", "FX.apollo"})
static class AppConfig2 {
@Bean
TestJavaConfigBean testJavaConfigBean() {
return new TestJavaConfigBean();
}
}
@Configuration
@EnableApolloConfig
static class AppConfig3 {
/**
* This case won't get auto updated
*/
@Bean
TestJavaConfigBean2 testJavaConfigBean2(@Value("${timeout:100}") int timeout, @Value("${batch:200}") int batch) {
TestJavaConfigBean2 bean = new TestJavaConfigBean2();
bean.setTimeout(timeout);
bean.setBatch(batch);
return bean;
}
}
@Configuration
@ComponentScan(includeFilters = {@Filter(type = FilterType.ANNOTATION, value = {Component.class})},
excludeFilters = {@Filter(type = FilterType.ANNOTATION, value = {Configuration.class})})
@EnableApolloConfig
static class AppConfig4 {
}
@Configuration
@EnableApolloConfig
static class AppConfig5 {
@Bean
TestJavaConfigBean4 testJavaConfigBean() {
return new TestJavaConfigBean4();
}
}
@Configuration
@EnableApolloConfig
static class AppConfig6 {
@Bean
TestJavaConfigBean5 testJavaConfigBean() {
return new TestJavaConfigBean5();
}
}
@Configuration
@EnableApolloConfig
static class AppConfig7 {
@Value("${batch}")
private int batch;
@Bean
@Value("${timeout}")
TestJavaConfigBean2 testJavaConfigBean2(int timeout) {
TestJavaConfigBean2 bean = new TestJavaConfigBean2();
bean.setTimeout(timeout);
bean.setBatch(batch);
return bean;
}
}
@Configuration
@EnableApolloConfig
@ImportResource("spring/XmlConfigPlaceholderTest1.xml")
static class AppConfig8 {
@Bean
TestJavaConfigBean testJavaConfigBean() {
return new TestJavaConfigBean();
}
}
@Configuration
@EnableApolloConfig
static class AppConfig9 {
@Bean
TestAllKindsOfDataTypesBean testAllKindsOfDataTypesBean() {
return new TestAllKindsOfDataTypesBean();
}
}
@Configuration
@EnableApolloConfig
static class NestedPropertyConfig1 {
@Bean
TestNestedPropertyBean testNestedPropertyBean() {
return new TestNestedPropertyBean();
}
}
@Configuration
@EnableApolloConfig
static class NestedPropertyConfig2 {
@Bean
TestNestedPropertyBeanWithDefaultValue testNestedPropertyBean() {
return new TestNestedPropertyBeanWithDefaultValue();
}
}
@Configuration
@EnableApolloConfig
static class AppConfig10 {
@Bean
TestApolloJsonValue testApolloJsonValue() {
return new TestApolloJsonValue();
}
}
@Configuration
@EnableApolloConfig
static class AppConfig11 {
@Bean
TestApolloJsonValueWithDefaultValue testApolloJsonValue() {
return new TestApolloJsonValueWithDefaultValue();
}
}
@Configuration
@EnableApolloConfig("application.yaMl")
static class AppConfig12 {
@Bean
TestJavaConfigBean testJavaConfigBean() {
return new TestJavaConfigBean();
}
}
@Configuration
@EnableApolloConfig("application.yaml")
@ImportResource("spring/XmlConfigPlaceholderTest11.xml")
static class AppConfig13 {
@Bean
TestJavaConfigBean testJavaConfigBean() {
return new TestJavaConfigBean();
}
}
@Configuration
@EnableApolloConfig({"application.yml", "FX.apollo"})
static class AppConfig14 {
@Bean
TestJavaConfigBean testJavaConfigBean() {
return new TestJavaConfigBean();
}
}
static class TestJavaConfigBean {
@Value("${timeout:100}")
private int timeout;
private int batch;
@Value("${batch:200}")
public void setBatch(int batch) {
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
static class TestJavaConfigBean2 {
private int timeout;
private int batch;
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public int getBatch() {
return batch;
}
public void setBatch(int batch) {
this.batch = batch;
}
}
/**
* This case won't get auto updated
*/
@Component
static class TestJavaConfigBean3 {
private final int timeout;
private final int batch;
@Autowired
public TestJavaConfigBean3(@Value("${timeout:100}") int timeout, @Value("${batch:200}") int batch) {
this.timeout = timeout;
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
/**
* This case won't get auto updated
*/
static class TestJavaConfigBean4 {
private int timeout;
private int batch;
@Value("${batch:200}")
public void setValues(int batch, @Value("${timeout:100}") int timeout) {
this.batch = batch;
this.timeout = timeout;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
static class TestJavaConfigBean5 {
@Value("${timeout}")
private int timeout;
private int batch;
@Value("${batch}")
public void setBatch(int batch) {
this.batch = batch;
}
public int getTimeout() {
return timeout;
}
public int getBatch() {
return batch;
}
}
static class TestNestedPropertyBean {
@Value("${${someKey}.${anotherKey}}")
private int nestedProperty;
public int getNestedProperty() {
return nestedProperty;
}
}
static class TestNestedPropertyBeanWithDefaultValue {
@Value("${${someKey}:${anotherKey}}")
private int nestedProperty;
public int getNestedProperty() {
return nestedProperty;
}
}
static class TestAllKindsOfDataTypesBean {
@Value("${intProperty}")
private int intProperty;
@Value("${intArrayProperty}")
private int[] intArrayProperty;
@Value("${longProperty}")
private long longProperty;
@Value("${shortProperty}")
private short shortProperty;
@Value("${floatProperty}")
private float floatProperty;
@Value("${doubleProperty}")
private double doubleProperty;
@Value("${byteProperty}")
private byte byteProperty;
@Value("${booleanProperty}")
private boolean booleanProperty;
@Value("${stringProperty}")
private String stringProperty;
@Value("#{new java.text.SimpleDateFormat('${dateFormat}').parse('${dateProperty}')}")
private Date dateProperty;
@ApolloJsonValue("${jsonProperty}")
private List<JsonBean> jsonBeanList;
public int getIntProperty() {
return intProperty;
}
public int[] getIntArrayProperty() {
return intArrayProperty;
}
public long getLongProperty() {
return longProperty;
}
public short getShortProperty() {
return shortProperty;
}
public float getFloatProperty() {
return floatProperty;
}
public double getDoubleProperty() {
return doubleProperty;
}
public byte getByteProperty() {
return byteProperty;
}
public boolean getBooleanProperty() {
return booleanProperty;
}
public String getStringProperty() {
return stringProperty;
}
public Date getDateProperty() {
return dateProperty;
}
public List<JsonBean> getJsonBeanList() {
return jsonBeanList;
}
}
static class TestApolloJsonValue {
@ApolloJsonValue("${jsonProperty}")
private JsonBean jsonBean;
public JsonBean getJsonBean() {
return jsonBean;
}
}
static class TestApolloJsonValueWithDefaultValue {
@ApolloJsonValue("${jsonProperty:{\"a\":\"defaultString\", \"b\":1}}")
private JsonBean jsonBean;
public JsonBean getJsonBean() {
return jsonBean;
}
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-configservice/src/main/java/com/ctrip/framework/apollo/configservice/service/ReleaseMessageServiceWithCache.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.service;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import com.ctrip.framework.apollo.biz.entity.ReleaseMessage;
import com.ctrip.framework.apollo.biz.message.ReleaseMessageListener;
import com.ctrip.framework.apollo.biz.message.Topics;
import com.ctrip.framework.apollo.biz.repository.ReleaseMessageRepository;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@Service
public class ReleaseMessageServiceWithCache implements ReleaseMessageListener, InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(ReleaseMessageServiceWithCache
.class);
private final ReleaseMessageRepository releaseMessageRepository;
private final BizConfig bizConfig;
private int scanInterval;
private TimeUnit scanIntervalTimeUnit;
private volatile long maxIdScanned;
private ConcurrentMap<String, ReleaseMessage> releaseMessageCache;
private AtomicBoolean doScan;
private ExecutorService executorService;
public ReleaseMessageServiceWithCache(
final ReleaseMessageRepository releaseMessageRepository,
final BizConfig bizConfig) {
this.releaseMessageRepository = releaseMessageRepository;
this.bizConfig = bizConfig;
initialize();
}
private void initialize() {
releaseMessageCache = Maps.newConcurrentMap();
doScan = new AtomicBoolean(true);
executorService = Executors.newSingleThreadExecutor(ApolloThreadFactory
.create("ReleaseMessageServiceWithCache", true));
}
public ReleaseMessage findLatestReleaseMessageForMessages(Set<String> messages) {
if (CollectionUtils.isEmpty(messages)) {
return null;
}
long maxReleaseMessageId = 0;
ReleaseMessage result = null;
for (String message : messages) {
ReleaseMessage releaseMessage = releaseMessageCache.get(message);
if (releaseMessage != null && releaseMessage.getId() > maxReleaseMessageId) {
maxReleaseMessageId = releaseMessage.getId();
result = releaseMessage;
}
}
return result;
}
public List<ReleaseMessage> findLatestReleaseMessagesGroupByMessages(Set<String> messages) {
if (CollectionUtils.isEmpty(messages)) {
return Collections.emptyList();
}
List<ReleaseMessage> releaseMessages = Lists.newArrayList();
for (String message : messages) {
ReleaseMessage releaseMessage = releaseMessageCache.get(message);
if (releaseMessage != null) {
releaseMessages.add(releaseMessage);
}
}
return releaseMessages;
}
@Override
public void handleMessage(ReleaseMessage message, String channel) {
//Could stop once the ReleaseMessageScanner starts to work
doScan.set(false);
logger.info("message received - channel: {}, message: {}", channel, message);
String content = message.getMessage();
Tracer.logEvent("Apollo.ReleaseMessageService.UpdateCache", String.valueOf(message.getId()));
if (!Topics.APOLLO_RELEASE_TOPIC.equals(channel) || Strings.isNullOrEmpty(content)) {
return;
}
long gap = message.getId() - maxIdScanned;
if (gap == 1) {
mergeReleaseMessage(message);
} else if (gap > 1) {
//gap found!
loadReleaseMessages(maxIdScanned);
}
}
@Override
public void afterPropertiesSet() throws Exception {
populateDataBaseInterval();
//block the startup process until load finished
//this should happen before ReleaseMessageScanner due to autowire
loadReleaseMessages(0);
executorService.submit(() -> {
while (doScan.get() && !Thread.currentThread().isInterrupted()) {
Transaction transaction = Tracer.newTransaction("Apollo.ReleaseMessageServiceWithCache",
"scanNewReleaseMessages");
try {
loadReleaseMessages(maxIdScanned);
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
logger.error("Scan new release messages failed", ex);
} finally {
transaction.complete();
}
try {
scanIntervalTimeUnit.sleep(scanInterval);
} catch (InterruptedException e) {
//ignore
}
}
});
}
private synchronized void mergeReleaseMessage(ReleaseMessage releaseMessage) {
ReleaseMessage old = releaseMessageCache.get(releaseMessage.getMessage());
if (old == null || releaseMessage.getId() > old.getId()) {
releaseMessageCache.put(releaseMessage.getMessage(), releaseMessage);
maxIdScanned = releaseMessage.getId();
}
}
private void loadReleaseMessages(long startId) {
boolean hasMore = true;
while (hasMore && !Thread.currentThread().isInterrupted()) {
//current batch is 500
List<ReleaseMessage> releaseMessages = releaseMessageRepository
.findFirst500ByIdGreaterThanOrderByIdAsc(startId);
if (CollectionUtils.isEmpty(releaseMessages)) {
break;
}
releaseMessages.forEach(this::mergeReleaseMessage);
int scanned = releaseMessages.size();
startId = releaseMessages.get(scanned - 1).getId();
hasMore = scanned == 500;
logger.info("Loaded {} release messages with startId {}", scanned, startId);
}
}
private void populateDataBaseInterval() {
scanInterval = bizConfig.releaseMessageCacheScanInterval();
scanIntervalTimeUnit = bizConfig.releaseMessageCacheScanIntervalTimeUnit();
}
//only for test use
private void reset() throws Exception {
executorService.shutdownNow();
initialize();
afterPropertiesSet();
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.service;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import com.ctrip.framework.apollo.biz.entity.ReleaseMessage;
import com.ctrip.framework.apollo.biz.message.ReleaseMessageListener;
import com.ctrip.framework.apollo.biz.message.Topics;
import com.ctrip.framework.apollo.biz.repository.ReleaseMessageRepository;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@Service
public class ReleaseMessageServiceWithCache implements ReleaseMessageListener, InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(ReleaseMessageServiceWithCache
.class);
private final ReleaseMessageRepository releaseMessageRepository;
private final BizConfig bizConfig;
private int scanInterval;
private TimeUnit scanIntervalTimeUnit;
private volatile long maxIdScanned;
private ConcurrentMap<String, ReleaseMessage> releaseMessageCache;
private AtomicBoolean doScan;
private ExecutorService executorService;
public ReleaseMessageServiceWithCache(
final ReleaseMessageRepository releaseMessageRepository,
final BizConfig bizConfig) {
this.releaseMessageRepository = releaseMessageRepository;
this.bizConfig = bizConfig;
initialize();
}
private void initialize() {
releaseMessageCache = Maps.newConcurrentMap();
doScan = new AtomicBoolean(true);
executorService = Executors.newSingleThreadExecutor(ApolloThreadFactory
.create("ReleaseMessageServiceWithCache", true));
}
public ReleaseMessage findLatestReleaseMessageForMessages(Set<String> messages) {
if (CollectionUtils.isEmpty(messages)) {
return null;
}
long maxReleaseMessageId = 0;
ReleaseMessage result = null;
for (String message : messages) {
ReleaseMessage releaseMessage = releaseMessageCache.get(message);
if (releaseMessage != null && releaseMessage.getId() > maxReleaseMessageId) {
maxReleaseMessageId = releaseMessage.getId();
result = releaseMessage;
}
}
return result;
}
public List<ReleaseMessage> findLatestReleaseMessagesGroupByMessages(Set<String> messages) {
if (CollectionUtils.isEmpty(messages)) {
return Collections.emptyList();
}
List<ReleaseMessage> releaseMessages = Lists.newArrayList();
for (String message : messages) {
ReleaseMessage releaseMessage = releaseMessageCache.get(message);
if (releaseMessage != null) {
releaseMessages.add(releaseMessage);
}
}
return releaseMessages;
}
@Override
public void handleMessage(ReleaseMessage message, String channel) {
//Could stop once the ReleaseMessageScanner starts to work
doScan.set(false);
logger.info("message received - channel: {}, message: {}", channel, message);
String content = message.getMessage();
Tracer.logEvent("Apollo.ReleaseMessageService.UpdateCache", String.valueOf(message.getId()));
if (!Topics.APOLLO_RELEASE_TOPIC.equals(channel) || Strings.isNullOrEmpty(content)) {
return;
}
long gap = message.getId() - maxIdScanned;
if (gap == 1) {
mergeReleaseMessage(message);
} else if (gap > 1) {
//gap found!
loadReleaseMessages(maxIdScanned);
}
}
@Override
public void afterPropertiesSet() throws Exception {
populateDataBaseInterval();
//block the startup process until load finished
//this should happen before ReleaseMessageScanner due to autowire
loadReleaseMessages(0);
executorService.submit(() -> {
while (doScan.get() && !Thread.currentThread().isInterrupted()) {
Transaction transaction = Tracer.newTransaction("Apollo.ReleaseMessageServiceWithCache",
"scanNewReleaseMessages");
try {
loadReleaseMessages(maxIdScanned);
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
logger.error("Scan new release messages failed", ex);
} finally {
transaction.complete();
}
try {
scanIntervalTimeUnit.sleep(scanInterval);
} catch (InterruptedException e) {
//ignore
}
}
});
}
private synchronized void mergeReleaseMessage(ReleaseMessage releaseMessage) {
ReleaseMessage old = releaseMessageCache.get(releaseMessage.getMessage());
if (old == null || releaseMessage.getId() > old.getId()) {
releaseMessageCache.put(releaseMessage.getMessage(), releaseMessage);
maxIdScanned = releaseMessage.getId();
}
}
private void loadReleaseMessages(long startId) {
boolean hasMore = true;
while (hasMore && !Thread.currentThread().isInterrupted()) {
//current batch is 500
List<ReleaseMessage> releaseMessages = releaseMessageRepository
.findFirst500ByIdGreaterThanOrderByIdAsc(startId);
if (CollectionUtils.isEmpty(releaseMessages)) {
break;
}
releaseMessages.forEach(this::mergeReleaseMessage);
int scanned = releaseMessages.size();
startId = releaseMessages.get(scanned - 1).getId();
hasMore = scanned == 500;
logger.info("Loaded {} release messages with startId {}", scanned, startId);
}
}
private void populateDataBaseInterval() {
scanInterval = bizConfig.releaseMessageCacheScanInterval();
scanIntervalTimeUnit = bizConfig.releaseMessageCacheScanIntervalTimeUnit();
}
//only for test use
private void reset() throws Exception {
executorService.shutdownNow();
initialize();
afterPropertiesSet();
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-configservice/src/main/java/com/ctrip/framework/apollo/configservice/controller/ConfigFileController.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.controller;
import com.ctrip.framework.apollo.biz.entity.ReleaseMessage;
import com.ctrip.framework.apollo.biz.grayReleaseRule.GrayReleaseRulesHolder;
import com.ctrip.framework.apollo.biz.message.ReleaseMessageListener;
import com.ctrip.framework.apollo.biz.message.Topics;
import com.ctrip.framework.apollo.configservice.util.NamespaceUtil;
import com.ctrip.framework.apollo.configservice.util.WatchKeysUtil;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.ctrip.framework.apollo.core.utils.PropertiesUtil;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.Weigher;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@RestController
@RequestMapping("/configfiles")
public class ConfigFileController implements ReleaseMessageListener {
private static final Logger logger = LoggerFactory.getLogger(ConfigFileController.class);
private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR);
private static final Splitter X_FORWARDED_FOR_SPLITTER = Splitter.on(",").omitEmptyStrings()
.trimResults();
private static final long MAX_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
private static final long EXPIRE_AFTER_WRITE = 30;
private final HttpHeaders propertiesResponseHeaders;
private final HttpHeaders jsonResponseHeaders;
private final ResponseEntity<String> NOT_FOUND_RESPONSE;
private Cache<String, String> localCache;
private final Multimap<String, String>
watchedKeys2CacheKey = Multimaps.synchronizedSetMultimap(HashMultimap.create());
private final Multimap<String, String>
cacheKey2WatchedKeys = Multimaps.synchronizedSetMultimap(HashMultimap.create());
private static final Gson GSON = new Gson();
private final ConfigController configController;
private final NamespaceUtil namespaceUtil;
private final WatchKeysUtil watchKeysUtil;
private final GrayReleaseRulesHolder grayReleaseRulesHolder;
public ConfigFileController(
final ConfigController configController,
final NamespaceUtil namespaceUtil,
final WatchKeysUtil watchKeysUtil,
final GrayReleaseRulesHolder grayReleaseRulesHolder) {
localCache = CacheBuilder.newBuilder()
.expireAfterWrite(EXPIRE_AFTER_WRITE, TimeUnit.MINUTES)
.weigher((Weigher<String, String>) (key, value) -> value == null ? 0 : value.length())
.maximumWeight(MAX_CACHE_SIZE)
.removalListener(notification -> {
String cacheKey = notification.getKey();
logger.debug("removing cache key: {}", cacheKey);
if (!cacheKey2WatchedKeys.containsKey(cacheKey)) {
return;
}
//create a new list to avoid ConcurrentModificationException
List<String> watchedKeys = new ArrayList<>(cacheKey2WatchedKeys.get(cacheKey));
for (String watchedKey : watchedKeys) {
watchedKeys2CacheKey.remove(watchedKey, cacheKey);
}
cacheKey2WatchedKeys.removeAll(cacheKey);
logger.debug("removed cache key: {}", cacheKey);
})
.build();
propertiesResponseHeaders = new HttpHeaders();
propertiesResponseHeaders.add("Content-Type", "text/plain;charset=UTF-8");
jsonResponseHeaders = new HttpHeaders();
jsonResponseHeaders.add("Content-Type", "application/json;charset=UTF-8");
NOT_FOUND_RESPONSE = new ResponseEntity<>(HttpStatus.NOT_FOUND);
this.configController = configController;
this.namespaceUtil = namespaceUtil;
this.watchKeysUtil = watchKeysUtil;
this.grayReleaseRulesHolder = grayReleaseRulesHolder;
}
@GetMapping(value = "/{appId}/{clusterName}/{namespace:.+}")
public ResponseEntity<String> queryConfigAsProperties(@PathVariable String appId,
@PathVariable String clusterName,
@PathVariable String namespace,
@RequestParam(value = "dataCenter", required = false) String dataCenter,
@RequestParam(value = "ip", required = false) String clientIp,
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
String result =
queryConfig(ConfigFileOutputFormat.PROPERTIES, appId, clusterName, namespace, dataCenter,
clientIp, request, response);
if (result == null) {
return NOT_FOUND_RESPONSE;
}
return new ResponseEntity<>(result, propertiesResponseHeaders, HttpStatus.OK);
}
@GetMapping(value = "/json/{appId}/{clusterName}/{namespace:.+}")
public ResponseEntity<String> queryConfigAsJson(@PathVariable String appId,
@PathVariable String clusterName,
@PathVariable String namespace,
@RequestParam(value = "dataCenter", required = false) String dataCenter,
@RequestParam(value = "ip", required = false) String clientIp,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
String result =
queryConfig(ConfigFileOutputFormat.JSON, appId, clusterName, namespace, dataCenter,
clientIp, request, response);
if (result == null) {
return NOT_FOUND_RESPONSE;
}
return new ResponseEntity<>(result, jsonResponseHeaders, HttpStatus.OK);
}
String queryConfig(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
String namespace, String dataCenter, String clientIp,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
//strip out .properties suffix
namespace = namespaceUtil.filterNamespaceName(namespace);
//fix the character case issue, such as FX.apollo <-> fx.apollo
namespace = namespaceUtil.normalizeNamespace(appId, namespace);
if (Strings.isNullOrEmpty(clientIp)) {
clientIp = tryToGetClientIp(request);
}
//1. check whether this client has gray release rules
boolean hasGrayReleaseRule = grayReleaseRulesHolder.hasGrayReleaseRule(appId, clientIp,
namespace);
String cacheKey = assembleCacheKey(outputFormat, appId, clusterName, namespace, dataCenter);
//2. try to load gray release and return
if (hasGrayReleaseRule) {
Tracer.logEvent("ConfigFile.Cache.GrayRelease", cacheKey);
return loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
request, response);
}
//3. if not gray release, check weather cache exists, if exists, return
String result = localCache.getIfPresent(cacheKey);
//4. if not exists, load from ConfigController
if (Strings.isNullOrEmpty(result)) {
Tracer.logEvent("ConfigFile.Cache.Miss", cacheKey);
result = loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
request, response);
if (result == null) {
return null;
}
//5. Double check if this client needs to load gray release, if yes, load from db again
//This step is mainly to avoid cache pollution
if (grayReleaseRulesHolder.hasGrayReleaseRule(appId, clientIp, namespace)) {
Tracer.logEvent("ConfigFile.Cache.GrayReleaseConflict", cacheKey);
return loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
request, response);
}
localCache.put(cacheKey, result);
logger.debug("adding cache for key: {}", cacheKey);
Set<String> watchedKeys =
watchKeysUtil.assembleAllWatchKeys(appId, clusterName, namespace, dataCenter);
for (String watchedKey : watchedKeys) {
watchedKeys2CacheKey.put(watchedKey, cacheKey);
}
cacheKey2WatchedKeys.putAll(cacheKey, watchedKeys);
logger.debug("added cache for key: {}", cacheKey);
} else {
Tracer.logEvent("ConfigFile.Cache.Hit", cacheKey);
}
return result;
}
private String loadConfig(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
String namespace, String dataCenter, String clientIp,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
ApolloConfig apolloConfig = configController.queryConfig(appId, clusterName, namespace,
dataCenter, "-1", clientIp, null, request, response);
if (apolloConfig == null || apolloConfig.getConfigurations() == null) {
return null;
}
String result = null;
switch (outputFormat) {
case PROPERTIES:
Properties properties = new Properties();
properties.putAll(apolloConfig.getConfigurations());
result = PropertiesUtil.toString(properties);
break;
case JSON:
result = GSON.toJson(apolloConfig.getConfigurations());
break;
}
return result;
}
String assembleCacheKey(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
String namespace,
String dataCenter) {
List<String> keyParts =
Lists.newArrayList(outputFormat.getValue(), appId, clusterName, namespace);
if (!Strings.isNullOrEmpty(dataCenter)) {
keyParts.add(dataCenter);
}
return STRING_JOINER.join(keyParts);
}
@Override
public void handleMessage(ReleaseMessage message, String channel) {
logger.info("message received - channel: {}, message: {}", channel, message);
String content = message.getMessage();
if (!Topics.APOLLO_RELEASE_TOPIC.equals(channel) || Strings.isNullOrEmpty(content)) {
return;
}
if (!watchedKeys2CacheKey.containsKey(content)) {
return;
}
//create a new list to avoid ConcurrentModificationException
List<String> cacheKeys = new ArrayList<>(watchedKeys2CacheKey.get(content));
for (String cacheKey : cacheKeys) {
logger.debug("invalidate cache key: {}", cacheKey);
localCache.invalidate(cacheKey);
}
}
enum ConfigFileOutputFormat {
PROPERTIES("properties"), JSON("json");
private String value;
ConfigFileOutputFormat(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
private String tryToGetClientIp(HttpServletRequest request) {
String forwardedFor = request.getHeader("X-FORWARDED-FOR");
if (!Strings.isNullOrEmpty(forwardedFor)) {
return X_FORWARDED_FOR_SPLITTER.splitToList(forwardedFor).get(0);
}
return request.getRemoteAddr();
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.controller;
import com.ctrip.framework.apollo.biz.entity.ReleaseMessage;
import com.ctrip.framework.apollo.biz.grayReleaseRule.GrayReleaseRulesHolder;
import com.ctrip.framework.apollo.biz.message.ReleaseMessageListener;
import com.ctrip.framework.apollo.biz.message.Topics;
import com.ctrip.framework.apollo.configservice.util.NamespaceUtil;
import com.ctrip.framework.apollo.configservice.util.WatchKeysUtil;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.ctrip.framework.apollo.core.utils.PropertiesUtil;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.Weigher;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author Jason Song(song_s@ctrip.com)
*/
@RestController
@RequestMapping("/configfiles")
public class ConfigFileController implements ReleaseMessageListener {
private static final Logger logger = LoggerFactory.getLogger(ConfigFileController.class);
private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR);
private static final Splitter X_FORWARDED_FOR_SPLITTER = Splitter.on(",").omitEmptyStrings()
.trimResults();
private static final long MAX_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
private static final long EXPIRE_AFTER_WRITE = 30;
private final HttpHeaders propertiesResponseHeaders;
private final HttpHeaders jsonResponseHeaders;
private final ResponseEntity<String> NOT_FOUND_RESPONSE;
private Cache<String, String> localCache;
private final Multimap<String, String>
watchedKeys2CacheKey = Multimaps.synchronizedSetMultimap(HashMultimap.create());
private final Multimap<String, String>
cacheKey2WatchedKeys = Multimaps.synchronizedSetMultimap(HashMultimap.create());
private static final Gson GSON = new Gson();
private final ConfigController configController;
private final NamespaceUtil namespaceUtil;
private final WatchKeysUtil watchKeysUtil;
private final GrayReleaseRulesHolder grayReleaseRulesHolder;
public ConfigFileController(
final ConfigController configController,
final NamespaceUtil namespaceUtil,
final WatchKeysUtil watchKeysUtil,
final GrayReleaseRulesHolder grayReleaseRulesHolder) {
localCache = CacheBuilder.newBuilder()
.expireAfterWrite(EXPIRE_AFTER_WRITE, TimeUnit.MINUTES)
.weigher((Weigher<String, String>) (key, value) -> value == null ? 0 : value.length())
.maximumWeight(MAX_CACHE_SIZE)
.removalListener(notification -> {
String cacheKey = notification.getKey();
logger.debug("removing cache key: {}", cacheKey);
if (!cacheKey2WatchedKeys.containsKey(cacheKey)) {
return;
}
//create a new list to avoid ConcurrentModificationException
List<String> watchedKeys = new ArrayList<>(cacheKey2WatchedKeys.get(cacheKey));
for (String watchedKey : watchedKeys) {
watchedKeys2CacheKey.remove(watchedKey, cacheKey);
}
cacheKey2WatchedKeys.removeAll(cacheKey);
logger.debug("removed cache key: {}", cacheKey);
})
.build();
propertiesResponseHeaders = new HttpHeaders();
propertiesResponseHeaders.add("Content-Type", "text/plain;charset=UTF-8");
jsonResponseHeaders = new HttpHeaders();
jsonResponseHeaders.add("Content-Type", "application/json;charset=UTF-8");
NOT_FOUND_RESPONSE = new ResponseEntity<>(HttpStatus.NOT_FOUND);
this.configController = configController;
this.namespaceUtil = namespaceUtil;
this.watchKeysUtil = watchKeysUtil;
this.grayReleaseRulesHolder = grayReleaseRulesHolder;
}
@GetMapping(value = "/{appId}/{clusterName}/{namespace:.+}")
public ResponseEntity<String> queryConfigAsProperties(@PathVariable String appId,
@PathVariable String clusterName,
@PathVariable String namespace,
@RequestParam(value = "dataCenter", required = false) String dataCenter,
@RequestParam(value = "ip", required = false) String clientIp,
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
String result =
queryConfig(ConfigFileOutputFormat.PROPERTIES, appId, clusterName, namespace, dataCenter,
clientIp, request, response);
if (result == null) {
return NOT_FOUND_RESPONSE;
}
return new ResponseEntity<>(result, propertiesResponseHeaders, HttpStatus.OK);
}
@GetMapping(value = "/json/{appId}/{clusterName}/{namespace:.+}")
public ResponseEntity<String> queryConfigAsJson(@PathVariable String appId,
@PathVariable String clusterName,
@PathVariable String namespace,
@RequestParam(value = "dataCenter", required = false) String dataCenter,
@RequestParam(value = "ip", required = false) String clientIp,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
String result =
queryConfig(ConfigFileOutputFormat.JSON, appId, clusterName, namespace, dataCenter,
clientIp, request, response);
if (result == null) {
return NOT_FOUND_RESPONSE;
}
return new ResponseEntity<>(result, jsonResponseHeaders, HttpStatus.OK);
}
String queryConfig(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
String namespace, String dataCenter, String clientIp,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
//strip out .properties suffix
namespace = namespaceUtil.filterNamespaceName(namespace);
//fix the character case issue, such as FX.apollo <-> fx.apollo
namespace = namespaceUtil.normalizeNamespace(appId, namespace);
if (Strings.isNullOrEmpty(clientIp)) {
clientIp = tryToGetClientIp(request);
}
//1. check whether this client has gray release rules
boolean hasGrayReleaseRule = grayReleaseRulesHolder.hasGrayReleaseRule(appId, clientIp,
namespace);
String cacheKey = assembleCacheKey(outputFormat, appId, clusterName, namespace, dataCenter);
//2. try to load gray release and return
if (hasGrayReleaseRule) {
Tracer.logEvent("ConfigFile.Cache.GrayRelease", cacheKey);
return loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
request, response);
}
//3. if not gray release, check weather cache exists, if exists, return
String result = localCache.getIfPresent(cacheKey);
//4. if not exists, load from ConfigController
if (Strings.isNullOrEmpty(result)) {
Tracer.logEvent("ConfigFile.Cache.Miss", cacheKey);
result = loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
request, response);
if (result == null) {
return null;
}
//5. Double check if this client needs to load gray release, if yes, load from db again
//This step is mainly to avoid cache pollution
if (grayReleaseRulesHolder.hasGrayReleaseRule(appId, clientIp, namespace)) {
Tracer.logEvent("ConfigFile.Cache.GrayReleaseConflict", cacheKey);
return loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
request, response);
}
localCache.put(cacheKey, result);
logger.debug("adding cache for key: {}", cacheKey);
Set<String> watchedKeys =
watchKeysUtil.assembleAllWatchKeys(appId, clusterName, namespace, dataCenter);
for (String watchedKey : watchedKeys) {
watchedKeys2CacheKey.put(watchedKey, cacheKey);
}
cacheKey2WatchedKeys.putAll(cacheKey, watchedKeys);
logger.debug("added cache for key: {}", cacheKey);
} else {
Tracer.logEvent("ConfigFile.Cache.Hit", cacheKey);
}
return result;
}
private String loadConfig(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
String namespace, String dataCenter, String clientIp,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
ApolloConfig apolloConfig = configController.queryConfig(appId, clusterName, namespace,
dataCenter, "-1", clientIp, null, request, response);
if (apolloConfig == null || apolloConfig.getConfigurations() == null) {
return null;
}
String result = null;
switch (outputFormat) {
case PROPERTIES:
Properties properties = new Properties();
properties.putAll(apolloConfig.getConfigurations());
result = PropertiesUtil.toString(properties);
break;
case JSON:
result = GSON.toJson(apolloConfig.getConfigurations());
break;
}
return result;
}
String assembleCacheKey(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
String namespace,
String dataCenter) {
List<String> keyParts =
Lists.newArrayList(outputFormat.getValue(), appId, clusterName, namespace);
if (!Strings.isNullOrEmpty(dataCenter)) {
keyParts.add(dataCenter);
}
return STRING_JOINER.join(keyParts);
}
@Override
public void handleMessage(ReleaseMessage message, String channel) {
logger.info("message received - channel: {}, message: {}", channel, message);
String content = message.getMessage();
if (!Topics.APOLLO_RELEASE_TOPIC.equals(channel) || Strings.isNullOrEmpty(content)) {
return;
}
if (!watchedKeys2CacheKey.containsKey(content)) {
return;
}
//create a new list to avoid ConcurrentModificationException
List<String> cacheKeys = new ArrayList<>(watchedKeys2CacheKey.get(content));
for (String cacheKey : cacheKeys) {
logger.debug("invalidate cache key: {}", cacheKey);
localCache.invalidate(cacheKey);
}
}
enum ConfigFileOutputFormat {
PROPERTIES("properties"), JSON("json");
private String value;
ConfigFileOutputFormat(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
private String tryToGetClientIp(HttpServletRequest request) {
String forwardedFor = request.getHeader("X-FORWARDED-FOR");
if (!Strings.isNullOrEmpty(forwardedFor)) {
return X_FORWARDED_FOR_SPLITTER.splitToList(forwardedFor).get(0);
}
return request.getRemoteAddr();
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducerManager.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.tracer.spi;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public interface MessageProducerManager {
/**
* @return the message producer
*/
MessageProducer getProducer();
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.tracer.spi;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public interface MessageProducerManager {
/**
* @return the message producer
*/
MessageProducer getProducer();
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/build/ApolloInjector.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.build;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.internals.Injector;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.foundation.internals.ServiceBootstrap;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class ApolloInjector {
private static volatile Injector s_injector;
private static final Object lock = new Object();
private static Injector getInjector() {
if (s_injector == null) {
synchronized (lock) {
if (s_injector == null) {
try {
s_injector = ServiceBootstrap.loadFirst(Injector.class);
} catch (Throwable ex) {
ApolloConfigException exception = new ApolloConfigException("Unable to initialize Apollo Injector!", ex);
Tracer.logError(exception);
throw exception;
}
}
}
}
return s_injector;
}
public static <T> T getInstance(Class<T> clazz) {
try {
return getInjector().getInstance(clazz);
} catch (Throwable ex) {
Tracer.logError(ex);
throw new ApolloConfigException(String.format("Unable to load instance for type %s!", clazz.getName()), ex);
}
}
public static <T> T getInstance(Class<T> clazz, String name) {
try {
return getInjector().getInstance(clazz, name);
} catch (Throwable ex) {
Tracer.logError(ex);
throw new ApolloConfigException(
String.format("Unable to load instance for type %s and name %s !", clazz.getName(), name), ex);
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.build;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.internals.Injector;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.foundation.internals.ServiceBootstrap;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class ApolloInjector {
private static volatile Injector s_injector;
private static final Object lock = new Object();
private static Injector getInjector() {
if (s_injector == null) {
synchronized (lock) {
if (s_injector == null) {
try {
s_injector = ServiceBootstrap.loadFirst(Injector.class);
} catch (Throwable ex) {
ApolloConfigException exception = new ApolloConfigException("Unable to initialize Apollo Injector!", ex);
Tracer.logError(exception);
throw exception;
}
}
}
}
return s_injector;
}
public static <T> T getInstance(Class<T> clazz) {
try {
return getInjector().getInstance(clazz);
} catch (Throwable ex) {
Tracer.logError(ex);
throw new ApolloConfigException(String.format("Unable to load instance for type %s!", clazz.getName()), ex);
}
}
public static <T> T getInstance(Class<T> clazz, String name) {
try {
return getInjector().getInstance(clazz, name);
} catch (Throwable ex) {
Tracer.logError(ex);
throw new ApolloConfigException(
String.format("Unable to load instance for type %s and name %s !", clazz.getName(), name), ex);
}
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/bo/KVEntity.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.entity.bo;
public class KVEntity {
private String key;
private String value;
public KVEntity(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.entity.bo;
public class KVEntity {
private String key;
private String value;
public KVEntity(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-biz/src/test/java/com/ctrip/framework/apollo/biz/utils/ConfigChangeContentBuilderTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.utils;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.ctrip.framework.apollo.biz.MockBeanFactory;
import com.ctrip.framework.apollo.biz.entity.Item;
import org.junit.Before;
import org.junit.Test;
/**
* @author jian.tan
*/
public class ConfigChangeContentBuilderTest {
private final ConfigChangeContentBuilder configChangeContentBuilder = new ConfigChangeContentBuilder();
private String configString;
@Before
public void initConfig() {
Item createdItem = MockBeanFactory.mockItem(1, 1, "timeout", "100", 1);
Item updatedItem = MockBeanFactory.mockItem(1, 1, "timeout", "1001", 1);
configChangeContentBuilder.createItem(createdItem);
configChangeContentBuilder.updateItem(createdItem, updatedItem);
configChangeContentBuilder.deleteItem(updatedItem);
configString = configChangeContentBuilder.build();
}
@Test
public void testHasContent() {
assertTrue(configChangeContentBuilder.hasContent());
}
@Test
public void testConvertJsonString() {
ConfigChangeContentBuilder contentBuilder = ConfigChangeContentBuilder
.convertJsonString(configString);
assertNotNull(contentBuilder.getCreateItems());
assertNotNull(contentBuilder.getUpdateItems().get(0).oldItem);
assertNotNull(contentBuilder.getUpdateItems().get(0).newItem);
assertNotNull(contentBuilder.getDeleteItems());
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.utils;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.ctrip.framework.apollo.biz.MockBeanFactory;
import com.ctrip.framework.apollo.biz.entity.Item;
import org.junit.Before;
import org.junit.Test;
/**
* @author jian.tan
*/
public class ConfigChangeContentBuilderTest {
private final ConfigChangeContentBuilder configChangeContentBuilder = new ConfigChangeContentBuilder();
private String configString;
@Before
public void initConfig() {
Item createdItem = MockBeanFactory.mockItem(1, 1, "timeout", "100", 1);
Item updatedItem = MockBeanFactory.mockItem(1, 1, "timeout", "1001", 1);
configChangeContentBuilder.createItem(createdItem);
configChangeContentBuilder.updateItem(createdItem, updatedItem);
configChangeContentBuilder.deleteItem(updatedItem);
configString = configChangeContentBuilder.build();
}
@Test
public void testHasContent() {
assertTrue(configChangeContentBuilder.hasContent());
}
@Test
public void testConvertJsonString() {
ConfigChangeContentBuilder contentBuilder = ConfigChangeContentBuilder
.convertJsonString(configString);
assertNotNull(contentBuilder.getCreateItems());
assertNotNull(contentBuilder.getUpdateItems().get(0).oldItem);
assertNotNull(contentBuilder.getUpdateItems().get(0).newItem);
assertNotNull(contentBuilder.getDeleteItems());
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/dto/ReleaseDTO.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.dto;
public class ReleaseDTO extends BaseDTO{
private long id;
private String releaseKey;
private String name;
private String appId;
private String clusterName;
private String namespaceName;
private String configurations;
private String comment;
private boolean isAbandoned;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getReleaseKey() {
return releaseKey;
}
public void setReleaseKey(String releaseKey) {
this.releaseKey = releaseKey;
}
public String getAppId() {
return appId;
}
public String getClusterName() {
return clusterName;
}
public String getComment() {
return comment;
}
public String getConfigurations() {
return configurations;
}
public String getName() {
return name;
}
public String getNamespaceName() {
return namespaceName;
}
public void setAppId(String appId) {
this.appId = appId;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setConfigurations(String configurations) {
this.configurations = configurations;
}
public void setName(String name) {
this.name = name;
}
public void setNamespaceName(String namespaceName) {
this.namespaceName = namespaceName;
}
public boolean isAbandoned() {
return isAbandoned;
}
public void setAbandoned(boolean abandoned) {
isAbandoned = abandoned;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.dto;
public class ReleaseDTO extends BaseDTO{
private long id;
private String releaseKey;
private String name;
private String appId;
private String clusterName;
private String namespaceName;
private String configurations;
private String comment;
private boolean isAbandoned;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getReleaseKey() {
return releaseKey;
}
public void setReleaseKey(String releaseKey) {
this.releaseKey = releaseKey;
}
public String getAppId() {
return appId;
}
public String getClusterName() {
return clusterName;
}
public String getComment() {
return comment;
}
public String getConfigurations() {
return configurations;
}
public String getName() {
return name;
}
public String getNamespaceName() {
return namespaceName;
}
public void setAppId(String appId) {
this.appId = appId;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setConfigurations(String configurations) {
this.configurations = configurations;
}
public void setName(String name) {
this.name = name;
}
public void setNamespaceName(String namespaceName) {
this.namespaceName = namespaceName;
}
public boolean isAbandoned() {
return isAbandoned;
}
public void setAbandoned(boolean abandoned) {
isAbandoned = abandoned;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/customize/package-info.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.customize;
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.customize;
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./docs/_navbar.md | - Translations
- [:uk: English](/en/)
- [:cn: 中文](/zh/) | - Translations
- [:uk: English](/en/)
- [:cn: 中文](/zh/) | -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./docs/en/README.md | <img src="https://raw.githubusercontent.com/ctripcorp/apollo/master/doc/images/logo/logo-simple.png" alt="apollo-logo" width="40%">
# Introduction
Apollo is a reliable configuration management system. It can centrally manage the configurations of different applications and different clusters. It is suitable for microservice configuration management scenarios.
The server side is developed based on Spring Boot and Spring Cloud, which can simply run without the need to install additional application containers such as Tomcat.
The Java SDK does not rely on any framework and can run in all Java runtime environments. It also has good support for Spring/Spring Boot environments.
The .Net SDK does not rely on any framework and can run in all .Net runtime environments.
For more details of the product introduction, please refer [Introduction to Apollo Configuration Center](zh/design/apollo-introduction).
For local demo purpose, please refer [Quick Start](zh/deployment/quick-start).
Demo Environment:
- [http://106.54.227.205](http://106.54.227.205/)
- User/Password: apollo/admin
# Screenshots

# Features
* **Unified management of the configurations of different environments and different clusters**
* Apollo provides a unified interface to centrally manage the configurations of different environments, different clusters, and different namespaces
* The same codebase could have different configurations when deployed in different clusters
* With the namespace concept, it is easy to support multiple applications to share the same configurations, while also allowing them to customize the configurations
* Multiple languages is provided in user interface(currently Chinese and English)
* **Configuration changes takes effect in real time (hot release)**
* After the user modified the configuration and released it in Apollo, the sdk will receive the latest configurations in real time (1 second) and notify the application
* **Release version management**
* Every configuration releases are versioned, which is friendly to support configuration rollback
* **Grayscale release**
* Support grayscale configuration release, for example, after clicking release, it will only take effect for some application instances. After a period of observation, we could push the configurations to all application instances if there is no problem
* **Authorization management, release approval and operation audit**
* Great authorization mechanism is designed for applications and configurations management, and the management of configurations is divided into two operations: editing and publishing, therefore greatly reducing human errors
* All operations have audit logs for easy tracking of problems
* **Client side configuration information monitoring**
* It's very easy to see which instances are using the configurations and what versions they are using
* **Rich SDKs available**
* Provides native sdks of Java and .Net to facilitate application integration
* Support Spring Placeholder, Annotation and Spring Boot ConfigurationProperties for easy application use (requires Spring 3.1.1+)
* Http APIs are provided, so non-Java and .Net applications can integrate conveniently
* Rich third party sdks are also available, e.g. Golang, Python, NodeJS, PHP, C, etc
* **Open platform API**
* Apollo itself provides a unified configuration management interface, which supports features such as multi-environment, multi-data center configuration management, permissions, and process governance
* However, for the sake of versatility, Apollo will not put too many restrictions on the modification of the configuration, as long as it conforms to the basic format, it can be saved.
* In our research, we found that for some users, their configurations may have more complicated formats, such as xml, json, and the format needs to be verified
* There are also some users such as DAL, which not only have a specific format, but also need to verify the entered value before saving, such as checking whether the database, username and password match
* For this type of application, Apollo allows the application to modify and release configurations through open APIs, which has great authorization and permission control mechanism built in
* **Simple deployment**
* As an infrastructure service, the configuration center has very high availability requirements, which forces Apollo to rely on external dependencies as little as possible
* Currently, the only external dependency is MySQL, so the deployment is very simple. Apollo can run as long as Java and MySQL are installed
* Apollo also provides a packaging script, which can generate all required installation packages with just one click, and supports customization of runtime parameters
# Usage
1. [Apollo User Guide](zh/usage/apollo-user-guide)
2. [Java SDK User Guide](zh/usage/java-sdk-user-guide)
3. [.Net SDK user Guide](zh/usage/dotnet-sdk-user-guide)
4. [Third Party SDK User Guide](zh/usage/third-party-sdks-user-guide)
5. [Other Language Client User Guide](zh/usage/other-language-client-user-guide)
6. [Apollo Open APIs](zh/usage/apollo-open-api-platform)
7. [Apollo Use Cases](https://github.com/ctripcorp/apollo-use-cases)
8. [Apollo User Practices](zh/usage/apollo-user-practices)
9. [Apollo Security Best Practices](zh/usage/apollo-user-guide?id=_71-%e5%ae%89%e5%85%a8%e7%9b%b8%e5%85%b3)
# Design
* [Apollo Design](zh/design/apollo-design)
* [Apollo Core Concept - Namespace](zh/design/apollo-core-concept-namespace)
* [Apollo Architecture Analysis](https://mp.weixin.qq.com/s/-hUaQPzfsl9Lm3IqQW3VDQ)
* [Apollo Source Code Explanation](http://www.iocoder.cn/categories/Apollo/)
# Development
* [Apollo Development Guide](zh/development/apollo-development-guide)
* Code Styles
* [Eclipse Code Style](https://github.com/ctripcorp/apollo/blob/master/apollo-buildtools/style/eclipse-java-google-style.xml)
* [Intellij Code Style](https://github.com/ctripcorp/apollo/blob/master/apollo-buildtools/style/intellij-java-google-style.xml)
# Deployment
* [Quick Start](zh/deployment/quick-start)
* [Distributed Deployment Guide](zh/deployment/distributed-deployment-guide)
# Release Notes
* [Releases](https://github.com/ctripcorp/apollo/releases)
# FAQ
* [FAQ](zh/faq/faq)
* [Common Issues in Deployment & Development Phase](zh/faq/common-issues-in-deployment-and-development-phase)
# Presentation
* [Design and Implementation Details of Apollo](http://www.itdks.com/dakalive/detail/3420)
* [Slides](https://myslide.cn/slides/10168)
* [Configuration Center Makes Microservices Smart](https://2018.qconshanghai.com/presentation/799)
* [Slides](https://myslide.cn/slides/10035)
# Publication
* [Design and Implementation Details of Apollo](https://www.infoq.cn/article/open-source-configuration-center-apollo)
* [Configuration Center Makes Microservices Smart](https://mp.weixin.qq.com/s/iDmYJre_ULEIxuliu1EbIQ)
# Contribution
Please make sure to read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making a pull request.
Thanks for all the people who contributed to Apollo!
<a href="https://github.com/ctripcorp/apollo/graphs/contributors"><img src="https://opencollective.com/apollo/contributors.svg?width=880&button=false" /></a>
# License
The project is licensed under the [Apache 2 license](https://github.com/ctripcorp/apollo/blob/master/LICENSE).
| <img src="https://raw.githubusercontent.com/ctripcorp/apollo/master/doc/images/logo/logo-simple.png" alt="apollo-logo" width="40%">
# Introduction
Apollo is a reliable configuration management system. It can centrally manage the configurations of different applications and different clusters. It is suitable for microservice configuration management scenarios.
The server side is developed based on Spring Boot and Spring Cloud, which can simply run without the need to install additional application containers such as Tomcat.
The Java SDK does not rely on any framework and can run in all Java runtime environments. It also has good support for Spring/Spring Boot environments.
The .Net SDK does not rely on any framework and can run in all .Net runtime environments.
For more details of the product introduction, please refer [Introduction to Apollo Configuration Center](zh/design/apollo-introduction).
For local demo purpose, please refer [Quick Start](zh/deployment/quick-start).
Demo Environment:
- [http://106.54.227.205](http://106.54.227.205/)
- User/Password: apollo/admin
# Screenshots

# Features
* **Unified management of the configurations of different environments and different clusters**
* Apollo provides a unified interface to centrally manage the configurations of different environments, different clusters, and different namespaces
* The same codebase could have different configurations when deployed in different clusters
* With the namespace concept, it is easy to support multiple applications to share the same configurations, while also allowing them to customize the configurations
* Multiple languages is provided in user interface(currently Chinese and English)
* **Configuration changes takes effect in real time (hot release)**
* After the user modified the configuration and released it in Apollo, the sdk will receive the latest configurations in real time (1 second) and notify the application
* **Release version management**
* Every configuration releases are versioned, which is friendly to support configuration rollback
* **Grayscale release**
* Support grayscale configuration release, for example, after clicking release, it will only take effect for some application instances. After a period of observation, we could push the configurations to all application instances if there is no problem
* **Authorization management, release approval and operation audit**
* Great authorization mechanism is designed for applications and configurations management, and the management of configurations is divided into two operations: editing and publishing, therefore greatly reducing human errors
* All operations have audit logs for easy tracking of problems
* **Client side configuration information monitoring**
* It's very easy to see which instances are using the configurations and what versions they are using
* **Rich SDKs available**
* Provides native sdks of Java and .Net to facilitate application integration
* Support Spring Placeholder, Annotation and Spring Boot ConfigurationProperties for easy application use (requires Spring 3.1.1+)
* Http APIs are provided, so non-Java and .Net applications can integrate conveniently
* Rich third party sdks are also available, e.g. Golang, Python, NodeJS, PHP, C, etc
* **Open platform API**
* Apollo itself provides a unified configuration management interface, which supports features such as multi-environment, multi-data center configuration management, permissions, and process governance
* However, for the sake of versatility, Apollo will not put too many restrictions on the modification of the configuration, as long as it conforms to the basic format, it can be saved.
* In our research, we found that for some users, their configurations may have more complicated formats, such as xml, json, and the format needs to be verified
* There are also some users such as DAL, which not only have a specific format, but also need to verify the entered value before saving, such as checking whether the database, username and password match
* For this type of application, Apollo allows the application to modify and release configurations through open APIs, which has great authorization and permission control mechanism built in
* **Simple deployment**
* As an infrastructure service, the configuration center has very high availability requirements, which forces Apollo to rely on external dependencies as little as possible
* Currently, the only external dependency is MySQL, so the deployment is very simple. Apollo can run as long as Java and MySQL are installed
* Apollo also provides a packaging script, which can generate all required installation packages with just one click, and supports customization of runtime parameters
# Usage
1. [Apollo User Guide](zh/usage/apollo-user-guide)
2. [Java SDK User Guide](zh/usage/java-sdk-user-guide)
3. [.Net SDK user Guide](zh/usage/dotnet-sdk-user-guide)
4. [Third Party SDK User Guide](zh/usage/third-party-sdks-user-guide)
5. [Other Language Client User Guide](zh/usage/other-language-client-user-guide)
6. [Apollo Open APIs](zh/usage/apollo-open-api-platform)
7. [Apollo Use Cases](https://github.com/ctripcorp/apollo-use-cases)
8. [Apollo User Practices](zh/usage/apollo-user-practices)
9. [Apollo Security Best Practices](zh/usage/apollo-user-guide?id=_71-%e5%ae%89%e5%85%a8%e7%9b%b8%e5%85%b3)
# Design
* [Apollo Design](zh/design/apollo-design)
* [Apollo Core Concept - Namespace](zh/design/apollo-core-concept-namespace)
* [Apollo Architecture Analysis](https://mp.weixin.qq.com/s/-hUaQPzfsl9Lm3IqQW3VDQ)
* [Apollo Source Code Explanation](http://www.iocoder.cn/categories/Apollo/)
# Development
* [Apollo Development Guide](zh/development/apollo-development-guide)
* Code Styles
* [Eclipse Code Style](https://github.com/ctripcorp/apollo/blob/master/apollo-buildtools/style/eclipse-java-google-style.xml)
* [Intellij Code Style](https://github.com/ctripcorp/apollo/blob/master/apollo-buildtools/style/intellij-java-google-style.xml)
# Deployment
* [Quick Start](zh/deployment/quick-start)
* [Distributed Deployment Guide](zh/deployment/distributed-deployment-guide)
# Release Notes
* [Releases](https://github.com/ctripcorp/apollo/releases)
# FAQ
* [FAQ](zh/faq/faq)
* [Common Issues in Deployment & Development Phase](zh/faq/common-issues-in-deployment-and-development-phase)
# Presentation
* [Design and Implementation Details of Apollo](http://www.itdks.com/dakalive/detail/3420)
* [Slides](https://myslide.cn/slides/10168)
* [Configuration Center Makes Microservices Smart](https://2018.qconshanghai.com/presentation/799)
* [Slides](https://myslide.cn/slides/10035)
# Publication
* [Design and Implementation Details of Apollo](https://www.infoq.cn/article/open-source-configuration-center-apollo)
* [Configuration Center Makes Microservices Smart](https://mp.weixin.qq.com/s/iDmYJre_ULEIxuliu1EbIQ)
# Contribution
Please make sure to read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making a pull request.
Thanks for all the people who contributed to Apollo!
<a href="https://github.com/ctripcorp/apollo/graphs/contributors"><img src="https://opencollective.com/apollo/contributors.svg?width=880&button=false" /></a>
# License
The project is licensed under the [Apache 2 license](https://github.com/ctripcorp/apollo/blob/master/LICENSE).
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/test/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepositoryTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.io.Files;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* Created by Jason on 4/9/16.
*/
public class LocalFileConfigRepositoryTest {
private File someBaseDir;
private String someNamespace;
private ConfigRepository upstreamRepo;
private Properties someProperties;
private static String someAppId = "someApp";
private static String someCluster = "someCluster";
private String defaultKey;
private String defaultValue;
private ConfigSourceType someSourceType;
@Before
public void setUp() throws Exception {
someBaseDir = new File("src/test/resources/config-cache");
someBaseDir.mkdir();
someNamespace = "someName";
someProperties = new Properties();
defaultKey = "defaultKey";
defaultValue = "defaultValue";
someProperties.setProperty(defaultKey, defaultValue);
someSourceType = ConfigSourceType.REMOTE;
upstreamRepo = mock(ConfigRepository.class);
when(upstreamRepo.getConfig()).thenReturn(someProperties);
when(upstreamRepo.getSourceType()).thenReturn(someSourceType);
MockInjector.setInstance(ConfigUtil.class, new MockConfigUtil());
PropertiesFactory propertiesFactory = mock(PropertiesFactory.class);
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new Properties();
}
});
MockInjector.setInstance(PropertiesFactory.class, propertiesFactory);
}
@After
public void tearDown() throws Exception {
MockInjector.reset();
recursiveDelete(someBaseDir);
}
//helper method to clean created files
private void recursiveDelete(File file) {
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
for (File f : file.listFiles()) {
recursiveDelete(f);
}
}
file.delete();
}
private String assembleLocalCacheFileName() {
return String.format("%s.properties", Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR)
.join(someAppId, someCluster, someNamespace));
}
@Test
public void testLoadConfigWithLocalFile() throws Exception {
String someKey = "someKey";
String someValue = "someValue\nxxx\nyyy";
Properties someProperties = new Properties();
someProperties.setProperty(someKey, someValue);
createLocalCachePropertyFile(someProperties);
LocalFileConfigRepository localRepo = new LocalFileConfigRepository(someNamespace);
localRepo.setLocalCacheDir(someBaseDir, true);
Properties properties = localRepo.getConfig();
assertEquals(someValue, properties.getProperty(someKey));
assertEquals(ConfigSourceType.LOCAL, localRepo.getSourceType());
}
@Test
public void testLoadConfigWithLocalFileAndFallbackRepo() throws Exception {
File file = new File(someBaseDir, assembleLocalCacheFileName());
String someValue = "someValue";
Files.write(defaultKey + "=" + someValue, file, Charsets.UTF_8);
LocalFileConfigRepository localRepo = new LocalFileConfigRepository(someNamespace, upstreamRepo);
localRepo.setLocalCacheDir(someBaseDir, true);
Properties properties = localRepo.getConfig();
assertEquals(defaultValue, properties.getProperty(defaultKey));
assertEquals(someSourceType, localRepo.getSourceType());
}
@Test
public void testLoadConfigWithNoLocalFile() throws Exception {
LocalFileConfigRepository localFileConfigRepository =
new LocalFileConfigRepository(someNamespace, upstreamRepo);
localFileConfigRepository.setLocalCacheDir(someBaseDir, true);
Properties result = localFileConfigRepository.getConfig();
assertEquals(
"LocalFileConfigRepository's properties should be the same as fallback repo's when there is no local cache",
result, someProperties);
assertEquals(someSourceType, localFileConfigRepository.getSourceType());
}
@Test
public void testLoadConfigWithNoLocalFileMultipleTimes() throws Exception {
LocalFileConfigRepository localRepo =
new LocalFileConfigRepository(someNamespace, upstreamRepo);
localRepo.setLocalCacheDir(someBaseDir, true);
Properties someProperties = localRepo.getConfig();
LocalFileConfigRepository
anotherLocalRepoWithNoFallback =
new LocalFileConfigRepository(someNamespace);
anotherLocalRepoWithNoFallback.setLocalCacheDir(someBaseDir, true);
Properties anotherProperties = anotherLocalRepoWithNoFallback.getConfig();
assertEquals(
"LocalFileConfigRepository should persist local cache files and return that afterwards",
someProperties, anotherProperties);
assertEquals(someSourceType, localRepo.getSourceType());
}
@Test
public void testOnRepositoryChange() throws Exception {
RepositoryChangeListener someListener = mock(RepositoryChangeListener.class);
LocalFileConfigRepository localFileConfigRepository =
new LocalFileConfigRepository(someNamespace, upstreamRepo);
assertEquals(someSourceType, localFileConfigRepository.getSourceType());
localFileConfigRepository.setLocalCacheDir(someBaseDir, true);
localFileConfigRepository.addChangeListener(someListener);
localFileConfigRepository.getConfig();
Properties anotherProperties = new Properties();
anotherProperties.put("anotherKey", "anotherValue");
ConfigSourceType anotherSourceType = ConfigSourceType.NONE;
when(upstreamRepo.getSourceType()).thenReturn(anotherSourceType);
localFileConfigRepository.onRepositoryChange(someNamespace, anotherProperties);
final ArgumentCaptor<Properties> captor = ArgumentCaptor.forClass(Properties.class);
verify(someListener, times(1)).onRepositoryChange(eq(someNamespace), captor.capture());
assertEquals(anotherProperties, captor.getValue());
assertEquals(anotherSourceType, localFileConfigRepository.getSourceType());
}
public static class MockConfigUtil extends ConfigUtil {
@Override
public String getAppId() {
return someAppId;
}
@Override
public String getCluster() {
return someCluster;
}
}
private File createLocalCachePropertyFile(Properties properties) throws IOException {
File file = new File(someBaseDir, assembleLocalCacheFileName());
FileOutputStream in = null;
try {
in = new FileOutputStream(file);
properties.store(in, "Persisted by LocalFileConfigRepositoryTest");
} finally {
if (in != null) {
in.close();
}
}
return file;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.io.Files;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* Created by Jason on 4/9/16.
*/
public class LocalFileConfigRepositoryTest {
private File someBaseDir;
private String someNamespace;
private ConfigRepository upstreamRepo;
private Properties someProperties;
private static String someAppId = "someApp";
private static String someCluster = "someCluster";
private String defaultKey;
private String defaultValue;
private ConfigSourceType someSourceType;
@Before
public void setUp() throws Exception {
someBaseDir = new File("src/test/resources/config-cache");
someBaseDir.mkdir();
someNamespace = "someName";
someProperties = new Properties();
defaultKey = "defaultKey";
defaultValue = "defaultValue";
someProperties.setProperty(defaultKey, defaultValue);
someSourceType = ConfigSourceType.REMOTE;
upstreamRepo = mock(ConfigRepository.class);
when(upstreamRepo.getConfig()).thenReturn(someProperties);
when(upstreamRepo.getSourceType()).thenReturn(someSourceType);
MockInjector.setInstance(ConfigUtil.class, new MockConfigUtil());
PropertiesFactory propertiesFactory = mock(PropertiesFactory.class);
when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() {
@Override
public Properties answer(InvocationOnMock invocation) {
return new Properties();
}
});
MockInjector.setInstance(PropertiesFactory.class, propertiesFactory);
}
@After
public void tearDown() throws Exception {
MockInjector.reset();
recursiveDelete(someBaseDir);
}
//helper method to clean created files
private void recursiveDelete(File file) {
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
for (File f : file.listFiles()) {
recursiveDelete(f);
}
}
file.delete();
}
private String assembleLocalCacheFileName() {
return String.format("%s.properties", Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR)
.join(someAppId, someCluster, someNamespace));
}
@Test
public void testLoadConfigWithLocalFile() throws Exception {
String someKey = "someKey";
String someValue = "someValue\nxxx\nyyy";
Properties someProperties = new Properties();
someProperties.setProperty(someKey, someValue);
createLocalCachePropertyFile(someProperties);
LocalFileConfigRepository localRepo = new LocalFileConfigRepository(someNamespace);
localRepo.setLocalCacheDir(someBaseDir, true);
Properties properties = localRepo.getConfig();
assertEquals(someValue, properties.getProperty(someKey));
assertEquals(ConfigSourceType.LOCAL, localRepo.getSourceType());
}
@Test
public void testLoadConfigWithLocalFileAndFallbackRepo() throws Exception {
File file = new File(someBaseDir, assembleLocalCacheFileName());
String someValue = "someValue";
Files.write(defaultKey + "=" + someValue, file, Charsets.UTF_8);
LocalFileConfigRepository localRepo = new LocalFileConfigRepository(someNamespace, upstreamRepo);
localRepo.setLocalCacheDir(someBaseDir, true);
Properties properties = localRepo.getConfig();
assertEquals(defaultValue, properties.getProperty(defaultKey));
assertEquals(someSourceType, localRepo.getSourceType());
}
@Test
public void testLoadConfigWithNoLocalFile() throws Exception {
LocalFileConfigRepository localFileConfigRepository =
new LocalFileConfigRepository(someNamespace, upstreamRepo);
localFileConfigRepository.setLocalCacheDir(someBaseDir, true);
Properties result = localFileConfigRepository.getConfig();
assertEquals(
"LocalFileConfigRepository's properties should be the same as fallback repo's when there is no local cache",
result, someProperties);
assertEquals(someSourceType, localFileConfigRepository.getSourceType());
}
@Test
public void testLoadConfigWithNoLocalFileMultipleTimes() throws Exception {
LocalFileConfigRepository localRepo =
new LocalFileConfigRepository(someNamespace, upstreamRepo);
localRepo.setLocalCacheDir(someBaseDir, true);
Properties someProperties = localRepo.getConfig();
LocalFileConfigRepository
anotherLocalRepoWithNoFallback =
new LocalFileConfigRepository(someNamespace);
anotherLocalRepoWithNoFallback.setLocalCacheDir(someBaseDir, true);
Properties anotherProperties = anotherLocalRepoWithNoFallback.getConfig();
assertEquals(
"LocalFileConfigRepository should persist local cache files and return that afterwards",
someProperties, anotherProperties);
assertEquals(someSourceType, localRepo.getSourceType());
}
@Test
public void testOnRepositoryChange() throws Exception {
RepositoryChangeListener someListener = mock(RepositoryChangeListener.class);
LocalFileConfigRepository localFileConfigRepository =
new LocalFileConfigRepository(someNamespace, upstreamRepo);
assertEquals(someSourceType, localFileConfigRepository.getSourceType());
localFileConfigRepository.setLocalCacheDir(someBaseDir, true);
localFileConfigRepository.addChangeListener(someListener);
localFileConfigRepository.getConfig();
Properties anotherProperties = new Properties();
anotherProperties.put("anotherKey", "anotherValue");
ConfigSourceType anotherSourceType = ConfigSourceType.NONE;
when(upstreamRepo.getSourceType()).thenReturn(anotherSourceType);
localFileConfigRepository.onRepositoryChange(someNamespace, anotherProperties);
final ArgumentCaptor<Properties> captor = ArgumentCaptor.forClass(Properties.class);
verify(someListener, times(1)).onRepositoryChange(eq(someNamespace), captor.capture());
assertEquals(anotherProperties, captor.getValue());
assertEquals(anotherSourceType, localFileConfigRepository.getSourceType());
}
public static class MockConfigUtil extends ConfigUtil {
@Override
public String getAppId() {
return someAppId;
}
@Override
public String getCluster() {
return someCluster;
}
}
private File createLocalCachePropertyFile(Properties properties) throws IOException {
File file = new File(someBaseDir, assembleLocalCacheFileName());
FileOutputStream in = null;
try {
in = new FileOutputStream(file);
properties.store(in, "Persisted by LocalFileConfigRepositoryTest");
} finally {
if (in != null) {
in.close();
}
}
return file;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-configservice/src/test/java/com/ctrip/framework/apollo/metaservice/service/NacosDiscoveryServiceTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.metaservice.service;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author kl (http://kailing.pub)
* @since 2020/12/21
*/
@RunWith(MockitoJUnitRunner.class)
public class NacosDiscoveryServiceTest {
private NacosDiscoveryService nacosDiscoveryService;
@Mock
private NamingService nacosNamingService;
private String someServiceId;
@Before
public void setUp() throws Exception {
nacosDiscoveryService = new NacosDiscoveryService();
nacosDiscoveryService.setNamingService(nacosNamingService);
someServiceId = "someServiceId";
}
@Test
public void testGetServiceInstancesWithEmptyInstances() throws Exception {
assertTrue(nacosNamingService.selectInstances(someServiceId, true).isEmpty());
}
@Test
public void testGetServiceInstancesWithInvalidServiceId() {
assertTrue(nacosDiscoveryService.getServiceInstances(someServiceId).isEmpty());
}
@Test
public void testGetServiceInstances() throws Exception {
String someIp = "1.2.3.4";
int somePort = 8080;
String someInstanceId = "someInstanceId";
Instance someServiceInstance = mockServiceInstance(someInstanceId, someIp, somePort);
when(nacosNamingService.selectInstances(someServiceId, true)).thenReturn(
Lists.newArrayList(someServiceInstance));
List<ServiceDTO> serviceDTOList = nacosDiscoveryService.getServiceInstances(someServiceId);
ServiceDTO serviceDTO = serviceDTOList.get(0);
assertEquals(1, serviceDTOList.size());
assertEquals(someServiceId, serviceDTO.getAppName());
assertEquals("http://1.2.3.4:8080/", serviceDTO.getHomepageUrl());
}
private Instance mockServiceInstance(String instanceId, String ip, int port) {
Instance serviceInstance = mock(Instance.class);
when(serviceInstance.getInstanceId()).thenReturn(instanceId);
when(serviceInstance.getIp()).thenReturn(ip);
when(serviceInstance.getPort()).thenReturn(port);
return serviceInstance;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.metaservice.service;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author kl (http://kailing.pub)
* @since 2020/12/21
*/
@RunWith(MockitoJUnitRunner.class)
public class NacosDiscoveryServiceTest {
private NacosDiscoveryService nacosDiscoveryService;
@Mock
private NamingService nacosNamingService;
private String someServiceId;
@Before
public void setUp() throws Exception {
nacosDiscoveryService = new NacosDiscoveryService();
nacosDiscoveryService.setNamingService(nacosNamingService);
someServiceId = "someServiceId";
}
@Test
public void testGetServiceInstancesWithEmptyInstances() throws Exception {
assertTrue(nacosNamingService.selectInstances(someServiceId, true).isEmpty());
}
@Test
public void testGetServiceInstancesWithInvalidServiceId() {
assertTrue(nacosDiscoveryService.getServiceInstances(someServiceId).isEmpty());
}
@Test
public void testGetServiceInstances() throws Exception {
String someIp = "1.2.3.4";
int somePort = 8080;
String someInstanceId = "someInstanceId";
Instance someServiceInstance = mockServiceInstance(someInstanceId, someIp, somePort);
when(nacosNamingService.selectInstances(someServiceId, true)).thenReturn(
Lists.newArrayList(someServiceInstance));
List<ServiceDTO> serviceDTOList = nacosDiscoveryService.getServiceInstances(someServiceId);
ServiceDTO serviceDTO = serviceDTOList.get(0);
assertEquals(1, serviceDTOList.size());
assertEquals(someServiceId, serviceDTO.getAppName());
assertEquals("http://1.2.3.4:8080/", serviceDTO.getHomepageUrl());
}
private Instance mockServiceInstance(String instanceId, String ip, int port) {
Instance serviceInstance = mock(Instance.class);
when(serviceInstance.getInstanceId()).thenReturn(instanceId);
when(serviceInstance.getIp()).thenReturn(ip);
when(serviceInstance.getPort()).thenReturn(port);
return serviceInstance;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/txtresolver/PropertyResolver.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.component.txtresolver;
import com.ctrip.framework.apollo.common.dto.ItemChangeSets;
import com.ctrip.framework.apollo.common.dto.ItemDTO;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.common.utils.BeanUtils;
import com.google.common.base.Strings;
import org.springframework.stereotype.Component;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* normal property file resolver.
* update comment and blank item implement by create new item and delete old item.
* update normal key/value item implement by update.
*/
@Component("propertyResolver")
public class PropertyResolver implements ConfigTextResolver {
private static final String KV_SEPARATOR = "=";
private static final String ITEM_SEPARATOR = "\n";
@Override
public ItemChangeSets resolve(long namespaceId, String configText, List<ItemDTO> baseItems) {
Map<Integer, ItemDTO> oldLineNumMapItem = BeanUtils.mapByKey("lineNum", baseItems);
Map<String, ItemDTO> oldKeyMapItem = BeanUtils.mapByKey("key", baseItems);
//remove comment and blank item map.
oldKeyMapItem.remove("");
String[] newItems = configText.split(ITEM_SEPARATOR);
Set<String> repeatKeys = new HashSet<>();
if (isHasRepeatKey(newItems, repeatKeys)) {
throw new BadRequestException(String.format("Config text has repeated keys: %s, please check your input.", repeatKeys.toString()));
}
ItemChangeSets changeSets = new ItemChangeSets();
Map<Integer, String> newLineNumMapItem = new HashMap<>();//use for delete blank and comment item
int lineCounter = 1;
for (String newItem : newItems) {
newItem = newItem.trim();
newLineNumMapItem.put(lineCounter, newItem);
ItemDTO oldItemByLine = oldLineNumMapItem.get(lineCounter);
//comment item
if (isCommentItem(newItem)) {
handleCommentLine(namespaceId, oldItemByLine, newItem, lineCounter, changeSets);
//blank item
} else if (isBlankItem(newItem)) {
handleBlankLine(namespaceId, oldItemByLine, lineCounter, changeSets);
//normal item
} else {
handleNormalLine(namespaceId, oldKeyMapItem, newItem, lineCounter, changeSets);
}
lineCounter++;
}
deleteCommentAndBlankItem(oldLineNumMapItem, newLineNumMapItem, changeSets);
deleteNormalKVItem(oldKeyMapItem, changeSets);
return changeSets;
}
private boolean isHasRepeatKey(String[] newItems, @NotNull Set<String> repeatKeys) {
Set<String> keys = new HashSet<>();
int lineCounter = 1;
for (String item : newItems) {
if (!isCommentItem(item) && !isBlankItem(item)) {
String[] kv = parseKeyValueFromItem(item);
if (kv != null) {
String key = kv[0].toLowerCase();
if(!keys.add(key)){
repeatKeys.add(key);
}
} else {
throw new BadRequestException("line:" + lineCounter + " key value must separate by '='");
}
}
lineCounter++;
}
return !repeatKeys.isEmpty();
}
private String[] parseKeyValueFromItem(String item) {
int kvSeparator = item.indexOf(KV_SEPARATOR);
if (kvSeparator == -1) {
return null;
}
String[] kv = new String[2];
kv[0] = item.substring(0, kvSeparator).trim();
kv[1] = item.substring(kvSeparator + 1).trim();
return kv;
}
private void handleCommentLine(Long namespaceId, ItemDTO oldItemByLine, String newItem, int lineCounter, ItemChangeSets changeSets) {
String oldComment = oldItemByLine == null ? "" : oldItemByLine.getComment();
//create comment. implement update comment by delete old comment and create new comment
if (!(isCommentItem(oldItemByLine) && newItem.equals(oldComment))) {
changeSets.addCreateItem(buildCommentItem(0L, namespaceId, newItem, lineCounter));
}
}
private void handleBlankLine(Long namespaceId, ItemDTO oldItem, int lineCounter, ItemChangeSets changeSets) {
if (!isBlankItem(oldItem)) {
changeSets.addCreateItem(buildBlankItem(0L, namespaceId, lineCounter));
}
}
private void handleNormalLine(Long namespaceId, Map<String, ItemDTO> keyMapOldItem, String newItem,
int lineCounter, ItemChangeSets changeSets) {
String[] kv = parseKeyValueFromItem(newItem);
if (kv == null) {
throw new BadRequestException("line:" + lineCounter + " key value must separate by '='");
}
String newKey = kv[0];
String newValue = kv[1].replace("\\n", "\n"); //handle user input \n
ItemDTO oldItem = keyMapOldItem.get(newKey);
if (oldItem == null) {//new item
changeSets.addCreateItem(buildNormalItem(0L, namespaceId, newKey, newValue, "", lineCounter));
} else if (!newValue.equals(oldItem.getValue()) || lineCounter != oldItem.getLineNum()) {//update item
changeSets.addUpdateItem(
buildNormalItem(oldItem.getId(), namespaceId, newKey, newValue, oldItem.getComment(),
lineCounter));
}
keyMapOldItem.remove(newKey);
}
private boolean isCommentItem(ItemDTO item) {
return item != null && "".equals(item.getKey())
&& (item.getComment().startsWith("#") || item.getComment().startsWith("!"));
}
private boolean isCommentItem(String line) {
return line != null && (line.startsWith("#") || line.startsWith("!"));
}
private boolean isBlankItem(ItemDTO item) {
return item != null && "".equals(item.getKey()) && "".equals(item.getComment());
}
private boolean isBlankItem(String line) {
return Strings.nullToEmpty(line).trim().isEmpty();
}
private void deleteNormalKVItem(Map<String, ItemDTO> baseKeyMapItem, ItemChangeSets changeSets) {
//surplus item is to be deleted
for (Map.Entry<String, ItemDTO> entry : baseKeyMapItem.entrySet()) {
changeSets.addDeleteItem(entry.getValue());
}
}
private void deleteCommentAndBlankItem(Map<Integer, ItemDTO> oldLineNumMapItem,
Map<Integer, String> newLineNumMapItem,
ItemChangeSets changeSets) {
for (Map.Entry<Integer, ItemDTO> entry : oldLineNumMapItem.entrySet()) {
int lineNum = entry.getKey();
ItemDTO oldItem = entry.getValue();
String newItem = newLineNumMapItem.get(lineNum);
//1. old is blank by now is not
//2.old is comment by now is not exist or modified
if ((isBlankItem(oldItem) && !isBlankItem(newItem))
|| isCommentItem(oldItem) && (newItem == null || !newItem.equals(oldItem.getComment()))) {
changeSets.addDeleteItem(oldItem);
}
}
}
private ItemDTO buildCommentItem(Long id, Long namespaceId, String comment, int lineNum) {
return buildNormalItem(id, namespaceId, "", "", comment, lineNum);
}
private ItemDTO buildBlankItem(Long id, Long namespaceId, int lineNum) {
return buildNormalItem(id, namespaceId, "", "", "", lineNum);
}
private ItemDTO buildNormalItem(Long id, Long namespaceId, String key, String value, String comment, int lineNum) {
ItemDTO item = new ItemDTO(key, value, comment, lineNum);
item.setId(id);
item.setNamespaceId(namespaceId);
return item;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.component.txtresolver;
import com.ctrip.framework.apollo.common.dto.ItemChangeSets;
import com.ctrip.framework.apollo.common.dto.ItemDTO;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.common.utils.BeanUtils;
import com.google.common.base.Strings;
import org.springframework.stereotype.Component;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* normal property file resolver.
* update comment and blank item implement by create new item and delete old item.
* update normal key/value item implement by update.
*/
@Component("propertyResolver")
public class PropertyResolver implements ConfigTextResolver {
private static final String KV_SEPARATOR = "=";
private static final String ITEM_SEPARATOR = "\n";
@Override
public ItemChangeSets resolve(long namespaceId, String configText, List<ItemDTO> baseItems) {
Map<Integer, ItemDTO> oldLineNumMapItem = BeanUtils.mapByKey("lineNum", baseItems);
Map<String, ItemDTO> oldKeyMapItem = BeanUtils.mapByKey("key", baseItems);
//remove comment and blank item map.
oldKeyMapItem.remove("");
String[] newItems = configText.split(ITEM_SEPARATOR);
Set<String> repeatKeys = new HashSet<>();
if (isHasRepeatKey(newItems, repeatKeys)) {
throw new BadRequestException(String.format("Config text has repeated keys: %s, please check your input.", repeatKeys.toString()));
}
ItemChangeSets changeSets = new ItemChangeSets();
Map<Integer, String> newLineNumMapItem = new HashMap<>();//use for delete blank and comment item
int lineCounter = 1;
for (String newItem : newItems) {
newItem = newItem.trim();
newLineNumMapItem.put(lineCounter, newItem);
ItemDTO oldItemByLine = oldLineNumMapItem.get(lineCounter);
//comment item
if (isCommentItem(newItem)) {
handleCommentLine(namespaceId, oldItemByLine, newItem, lineCounter, changeSets);
//blank item
} else if (isBlankItem(newItem)) {
handleBlankLine(namespaceId, oldItemByLine, lineCounter, changeSets);
//normal item
} else {
handleNormalLine(namespaceId, oldKeyMapItem, newItem, lineCounter, changeSets);
}
lineCounter++;
}
deleteCommentAndBlankItem(oldLineNumMapItem, newLineNumMapItem, changeSets);
deleteNormalKVItem(oldKeyMapItem, changeSets);
return changeSets;
}
private boolean isHasRepeatKey(String[] newItems, @NotNull Set<String> repeatKeys) {
Set<String> keys = new HashSet<>();
int lineCounter = 1;
for (String item : newItems) {
if (!isCommentItem(item) && !isBlankItem(item)) {
String[] kv = parseKeyValueFromItem(item);
if (kv != null) {
String key = kv[0].toLowerCase();
if(!keys.add(key)){
repeatKeys.add(key);
}
} else {
throw new BadRequestException("line:" + lineCounter + " key value must separate by '='");
}
}
lineCounter++;
}
return !repeatKeys.isEmpty();
}
private String[] parseKeyValueFromItem(String item) {
int kvSeparator = item.indexOf(KV_SEPARATOR);
if (kvSeparator == -1) {
return null;
}
String[] kv = new String[2];
kv[0] = item.substring(0, kvSeparator).trim();
kv[1] = item.substring(kvSeparator + 1).trim();
return kv;
}
private void handleCommentLine(Long namespaceId, ItemDTO oldItemByLine, String newItem, int lineCounter, ItemChangeSets changeSets) {
String oldComment = oldItemByLine == null ? "" : oldItemByLine.getComment();
//create comment. implement update comment by delete old comment and create new comment
if (!(isCommentItem(oldItemByLine) && newItem.equals(oldComment))) {
changeSets.addCreateItem(buildCommentItem(0L, namespaceId, newItem, lineCounter));
}
}
private void handleBlankLine(Long namespaceId, ItemDTO oldItem, int lineCounter, ItemChangeSets changeSets) {
if (!isBlankItem(oldItem)) {
changeSets.addCreateItem(buildBlankItem(0L, namespaceId, lineCounter));
}
}
private void handleNormalLine(Long namespaceId, Map<String, ItemDTO> keyMapOldItem, String newItem,
int lineCounter, ItemChangeSets changeSets) {
String[] kv = parseKeyValueFromItem(newItem);
if (kv == null) {
throw new BadRequestException("line:" + lineCounter + " key value must separate by '='");
}
String newKey = kv[0];
String newValue = kv[1].replace("\\n", "\n"); //handle user input \n
ItemDTO oldItem = keyMapOldItem.get(newKey);
if (oldItem == null) {//new item
changeSets.addCreateItem(buildNormalItem(0L, namespaceId, newKey, newValue, "", lineCounter));
} else if (!newValue.equals(oldItem.getValue()) || lineCounter != oldItem.getLineNum()) {//update item
changeSets.addUpdateItem(
buildNormalItem(oldItem.getId(), namespaceId, newKey, newValue, oldItem.getComment(),
lineCounter));
}
keyMapOldItem.remove(newKey);
}
private boolean isCommentItem(ItemDTO item) {
return item != null && "".equals(item.getKey())
&& (item.getComment().startsWith("#") || item.getComment().startsWith("!"));
}
private boolean isCommentItem(String line) {
return line != null && (line.startsWith("#") || line.startsWith("!"));
}
private boolean isBlankItem(ItemDTO item) {
return item != null && "".equals(item.getKey()) && "".equals(item.getComment());
}
private boolean isBlankItem(String line) {
return Strings.nullToEmpty(line).trim().isEmpty();
}
private void deleteNormalKVItem(Map<String, ItemDTO> baseKeyMapItem, ItemChangeSets changeSets) {
//surplus item is to be deleted
for (Map.Entry<String, ItemDTO> entry : baseKeyMapItem.entrySet()) {
changeSets.addDeleteItem(entry.getValue());
}
}
private void deleteCommentAndBlankItem(Map<Integer, ItemDTO> oldLineNumMapItem,
Map<Integer, String> newLineNumMapItem,
ItemChangeSets changeSets) {
for (Map.Entry<Integer, ItemDTO> entry : oldLineNumMapItem.entrySet()) {
int lineNum = entry.getKey();
ItemDTO oldItem = entry.getValue();
String newItem = newLineNumMapItem.get(lineNum);
//1. old is blank by now is not
//2.old is comment by now is not exist or modified
if ((isBlankItem(oldItem) && !isBlankItem(newItem))
|| isCommentItem(oldItem) && (newItem == null || !newItem.equals(oldItem.getComment()))) {
changeSets.addDeleteItem(oldItem);
}
}
}
private ItemDTO buildCommentItem(Long id, Long namespaceId, String comment, int lineNum) {
return buildNormalItem(id, namespaceId, "", "", comment, lineNum);
}
private ItemDTO buildBlankItem(Long id, Long namespaceId, int lineNum) {
return buildNormalItem(id, namespaceId, "", "", "", lineNum);
}
private ItemDTO buildNormalItem(Long id, Long namespaceId, String key, String value, String comment, int lineNum) {
ItemDTO item = new ItemDTO(key, value, comment, lineNum);
item.setId(id);
item.setNamespaceId(namespaceId);
return item;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./docs/zh/usage/other-language-client-user-guide.md | 目前Apollo团队由于人力所限,只提供了Java和.Net的客户端,对于其它语言的应用,可以通过本文的介绍来直接通过Http接口获取配置。
另外,如果有团队/个人有兴趣的话,也欢迎帮助我们来实现其它语言的客户端,具体细节可以联系@nobodyiam和@lepdou。
>注:目前已有热心用户贡献了Go、Python、NodeJS、PHP、C++的客户端,更多信息可以参考[Go、Python、NodeJS、PHP等客户端使用指南](zh/usage/third-party-sdks-user-guide)
## 1.1 应用接入Apollo
首先需要在Apollo中接入你的应用,具体步骤可以参考[应用接入文档](zh/usage/apollo-user-guide?id=一、普通应用接入指南)。
## 1.2 通过带缓存的Http接口从Apollo读取配置
该接口会从缓存中获取配置,适合频率较高的配置拉取请求,如简单的每30秒轮询一次配置。
由于缓存最多会有一秒的延时,所以如果需要配合配置推送通知实现实时更新配置的话,请参考[1.3 通过不带缓存的Http接口从Apollo读取配置](#_13-%E9%80%9A%E8%BF%87%E4%B8%8D%E5%B8%A6%E7%BC%93%E5%AD%98%E7%9A%84http%E6%8E%A5%E5%8F%A3%E4%BB%8Eapollo%E8%AF%BB%E5%8F%96%E9%85%8D%E7%BD%AE)。
### 1.2.1 Http接口说明
**URL**: {config_server_url}/configfiles/json/{appId}/{clusterName}/{namespaceName}?ip={clientIp}
**Method**: GET
**参数说明**:
| 参数名 | 是否必须 | 参数值 | 备注 |
|-------------------|----------|----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| config_server_url | 是 | Apollo配置服务的地址 | |
| appId | 是 | 应用的appId | |
| clusterName | 是 | 集群名 | 一般情况下传入 default 即可。 如果希望配置按集群划分,可以参考[集群独立配置说明](zh/usage/apollo-user-guide?id=三、集群独立配置说明)做相关配置,然后在这里填入对应的集群名。 |
| namespaceName | 是 | Namespace的名字 | 如果没有新建过Namespace的话,传入application即可。 如果创建了Namespace,并且需要使用该Namespace的配置,则传入对应的Namespace名字。**需要注意的是对于properties类型的namespace,只需要传入namespace的名字即可,如application。对于其它类型的namespace,需要传入namespace的名字加上后缀名,如datasources.json** |
| ip | 否 | 应用部署的机器ip | 这个参数是可选的,用来实现灰度发布。 如果不想传这个参数,请注意URL中从?号开始的query parameters整个都不要出现。 |
### 1.2.2 Http接口返回格式
该Http接口返回的是JSON格式、UTF-8编码,包含了对应namespace中所有的配置项。
返回内容Sample如下:
```json
{
"portal.elastic.document.type":"biz",
"portal.elastic.cluster.name":"hermes-es-fws"
}
```
> 通过`{config_server_url}/configfiles/{appId}/{clusterName}/{namespaceName}?ip={clientIp}`可以获取到properties形式的配置
### 1.2.3 测试
由于是Http接口,所以在URL组装OK之后,直接通过浏览器、或者相关的http接口测试工具访问即可。
## 1.3 通过不带缓存的Http接口从Apollo读取配置
该接口会直接从数据库中获取配置,可以配合配置推送通知实现实时更新配置。
### 1.3.1 Http接口说明
**URL**: {config_server_url}/configs/{appId}/{clusterName}/{namespaceName}?releaseKey={releaseKey}&ip={clientIp}
**Method**: GET
**参数说明**:
| 参数名 | 是否必须 | 参数值 | 备注 |
|-------------------|----------|----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| config_server_url | 是 | Apollo配置服务的地址 | |
| appId | 是 | 应用的appId | |
| clusterName | 是 | 集群名 | 一般情况下传入 default 即可。 如果希望配置按集群划分,可以参考[集群独立配置说明](zh/usage/apollo-user-guide?id=三、集群独立配置说明)做相关配置,然后在这里填入对应的集群名。 |
| namespaceName | 是 | Namespace的名字 | 如果没有新建过Namespace的话,传入application即可。 如果创建了Namespace,并且需要使用该Namespace的配置,则传入对应的Namespace名字。**需要注意的是对于properties类型的namespace,只需要传入namespace的名字即可,如application。对于其它类型的namespace,需要传入namespace的名字加上后缀名,如datasources.json** |
| releaseKey | 否 | 上一次的releaseKey | 将上一次返回对象中的releaseKey传入即可,用来给服务端比较版本,如果版本比下来没有变化,则服务端直接返回304以节省流量和运算 |
| ip | 否 | 应用部署的机器ip | 这个参数是可选的,用来实现灰度发布。 |
### 1.3.2 Http接口返回格式
该Http接口返回的是JSON格式、UTF-8编码。
如果配置没有变化(传入的releaseKey和服务端的相等),则返回HttpStatus 304,response body为空。
如果配置有变化,则会返回HttpStatus 200,response body为对应namespace的meta信息以及其中所有的配置项。
返回内容Sample如下:
```json
{
"appId": "100004458",
"cluster": "default",
"namespaceName": "application",
"configurations": {
"portal.elastic.document.type":"biz",
"portal.elastic.cluster.name":"hermes-es-fws"
},
"releaseKey": "20170430092936-dee2d58e74515ff3"
}
```
### 1.3.3 测试
由于是Http接口,所以在URL组装OK之后,直接通过浏览器、或者相关的http接口测试工具访问即可。
## 1.4 应用感知配置更新
Apollo提供了基于Http long polling的配置更新推送通知,第三方客户端可以看自己实际的需求决定是否需要使用这个功能。
如果对配置更新时间不是那么敏感的话,可以通过定时刷新来感知配置更新,刷新频率可以视应用自身情况来定,建议在30秒以上。
如果需要做到实时感知配置更新(1秒)的话,可以参考下面的文档实现配置更新推送的功能。
### 1.4.1 配置更新推送实现思路
这里建议大家可以参考Apollo的Java实现:[RemoteConfigLongPollService.java](https://github.com/ctripcorp/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java),代码量200多行,总体上还是比较简单的。
#### 1.4.1.1 初始化
首先需要确定哪些namespace需要配置更新推送,Apollo的实现方式是程序第一次获取某个namespace的配置时就会来注册一下,我们就知道有哪些namespace需要配置更新推送了。
初始化后的结果就是得到一个notifications的Map,内容是namespaceName -> notificationId(初始值为-1)。
运行过程中如果发现有新的namespace需要配置更新推送,直接塞到notifications这个Map里面即可。
#### 1.4.1.2 请求服务
有了notifications这个Map之后,就可以请求服务了。这里先描述一下请求服务的逻辑,具体的URL参数和说明请参见后面的接口说明。
1. 请求远端服务,带上自己的应用信息以及notifications信息
2. 服务端针对传过来的每一个namespace和对应的notificationId,检查notificationId是否是最新的
3. 如果都是最新的,则保持住请求60秒,如果60秒内没有配置变化,则返回HttpStatus 304。如果60秒内有配置变化,则返回对应namespace的最新notificationId, HttpStatus 200。
4. 如果传过来的notifications信息中发现有notificationId比服务端老,则直接返回对应namespace的最新notificationId, HttpStatus 200。
5. 客户端拿到服务端返回后,判断返回的HttpStatus
6. 如果返回的HttpStatus是304,说明配置没有变化,重新执行第1步
7. 如果返回的HttpStauts是200,说明配置有变化,针对变化的namespace重新去服务端拉取配置,参见[1.3 通过不带缓存的Http接口从Apollo读取配置](#_13-%E9%80%9A%E8%BF%87%E4%B8%8D%E5%B8%A6%E7%BC%93%E5%AD%98%E7%9A%84http%E6%8E%A5%E5%8F%A3%E4%BB%8Eapollo%E8%AF%BB%E5%8F%96%E9%85%8D%E7%BD%AE)。同时更新notifications map中的notificationId。重新执行第1步。
### 1.4.2 Http接口说明
**URL**: {config_server_url}/notifications/v2?appId={appId}&cluster={clusterName}¬ifications={notifications}
**Method**: GET
**参数说明**:
| 参数名 | 是否必须 | 参数值 | 备注 |
|-------------------|----------|----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| config_server_url | 是 | Apollo配置服务的地址 | |
| appId | 是 | 应用的appId | |
| clusterName | 是 | 集群名 | 一般情况下传入 default 即可。 如果希望配置按集群划分,可以参考[集群独立配置说明](zh/usage/apollo-user-guide?id=三、集群独立配置说明)做相关配置,然后在这里填入对应的集群名。 |
| notifications | 是 | notifications信息 | 传入本地的notifications信息,注意这里需要以array形式转为json传入,如:[{"namespaceName": "application", "notificationId": 100}, {"namespaceName": "FX.apollo", "notificationId": 200}]。**需要注意的是对于properties类型的namespace,只需要传入namespace的名字即可,如application。对于其它类型的namespace,需要传入namespace的名字加上后缀名,如datasources.json** |
> 注1:由于服务端会hold住请求60秒,所以请确保客户端访问服务端的超时时间要大于60秒。
> 注2:别忘了对参数进行[url encode](https://en.wikipedia.org/wiki/Percent-encoding)
### 1.4.3 Http接口返回格式
该Http接口返回的是JSON格式、UTF-8编码,包含了有变化的namespace和最新的notificationId。
返回内容Sample如下:
```json
[
{
"namespaceName": "application",
"notificationId": 101
}
]
```
### 1.4.4 测试
由于是Http接口,所以在URL组装OK之后,直接通过浏览器、或者相关的http接口测试工具访问即可。
## 1.5 配置访问密钥
Apollo从1.6.0版本开始增加访问密钥机制,从而只有经过身份验证的客户端才能访问敏感配置。如果应用开启了访问密钥,客户端发出请求时需要增加签名,否则无法获取配置。
需要设置的Header信息:
| Header | Value | 备注 |
|---------------|------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Authorization | Apollo ${appId}:${signature} | appId: 应用的appId,signature:使用访问密钥对当前时间以及所访问的URL加签后的值,具体实现可以参考[Signature.signature](https://github.com/ctripcorp/apollo/blob/aa184a2e11d6e7e3f519d860d69f3cf30ccfcf9c/apollo-core/src/main/java/com/ctrip/framework/apollo/core/signature/Signature.java#L22) |
| Timestamp | 从`1970-1-1 00:00:00 UTC+0`到现在所经过的毫秒数 | 可以参考[System.currentTimeMillis](https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis()) |
## 1.6 错误码说明
正常情况下,接口返回的Http状态码是200,下面列举了Apollo会返回的非200错误码说明。
### 1.6.1 400 - Bad Request
客户端传入参数的错误,如必选参数没有传入等,客户端需要根据提示信息检查对应的参数是否正确。
### 1.6.2 401 - Unauthorized
客户端未授权,如服务端配置了访问密钥,客户端未配置或配置错误。
### 1.6.3 404 - Not Found
接口要访问的资源不存在,一般是URL或URL的参数错误,或者是对应的namespace还没有发布过配置。
### 1.6.4 405 - Method Not Allowed
接口访问的Method不正确,比如应该使用GET的接口使用了POST访问等,客户端需要检查接口访问方式是否正确。
### 1.6.5 500 - Internal Server Error
其它类型的错误默认都会返回500,对这类错误如果应用无法根据提示信息找到原因的话,可以尝试查看服务端日志来排查问题。 | 目前Apollo团队由于人力所限,只提供了Java和.Net的客户端,对于其它语言的应用,可以通过本文的介绍来直接通过Http接口获取配置。
另外,如果有团队/个人有兴趣的话,也欢迎帮助我们来实现其它语言的客户端,具体细节可以联系@nobodyiam和@lepdou。
>注:目前已有热心用户贡献了Go、Python、NodeJS、PHP、C++的客户端,更多信息可以参考[Go、Python、NodeJS、PHP等客户端使用指南](zh/usage/third-party-sdks-user-guide)
## 1.1 应用接入Apollo
首先需要在Apollo中接入你的应用,具体步骤可以参考[应用接入文档](zh/usage/apollo-user-guide?id=一、普通应用接入指南)。
## 1.2 通过带缓存的Http接口从Apollo读取配置
该接口会从缓存中获取配置,适合频率较高的配置拉取请求,如简单的每30秒轮询一次配置。
由于缓存最多会有一秒的延时,所以如果需要配合配置推送通知实现实时更新配置的话,请参考[1.3 通过不带缓存的Http接口从Apollo读取配置](#_13-%E9%80%9A%E8%BF%87%E4%B8%8D%E5%B8%A6%E7%BC%93%E5%AD%98%E7%9A%84http%E6%8E%A5%E5%8F%A3%E4%BB%8Eapollo%E8%AF%BB%E5%8F%96%E9%85%8D%E7%BD%AE)。
### 1.2.1 Http接口说明
**URL**: {config_server_url}/configfiles/json/{appId}/{clusterName}/{namespaceName}?ip={clientIp}
**Method**: GET
**参数说明**:
| 参数名 | 是否必须 | 参数值 | 备注 |
|-------------------|----------|----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| config_server_url | 是 | Apollo配置服务的地址 | |
| appId | 是 | 应用的appId | |
| clusterName | 是 | 集群名 | 一般情况下传入 default 即可。 如果希望配置按集群划分,可以参考[集群独立配置说明](zh/usage/apollo-user-guide?id=三、集群独立配置说明)做相关配置,然后在这里填入对应的集群名。 |
| namespaceName | 是 | Namespace的名字 | 如果没有新建过Namespace的话,传入application即可。 如果创建了Namespace,并且需要使用该Namespace的配置,则传入对应的Namespace名字。**需要注意的是对于properties类型的namespace,只需要传入namespace的名字即可,如application。对于其它类型的namespace,需要传入namespace的名字加上后缀名,如datasources.json** |
| ip | 否 | 应用部署的机器ip | 这个参数是可选的,用来实现灰度发布。 如果不想传这个参数,请注意URL中从?号开始的query parameters整个都不要出现。 |
### 1.2.2 Http接口返回格式
该Http接口返回的是JSON格式、UTF-8编码,包含了对应namespace中所有的配置项。
返回内容Sample如下:
```json
{
"portal.elastic.document.type":"biz",
"portal.elastic.cluster.name":"hermes-es-fws"
}
```
> 通过`{config_server_url}/configfiles/{appId}/{clusterName}/{namespaceName}?ip={clientIp}`可以获取到properties形式的配置
### 1.2.3 测试
由于是Http接口,所以在URL组装OK之后,直接通过浏览器、或者相关的http接口测试工具访问即可。
## 1.3 通过不带缓存的Http接口从Apollo读取配置
该接口会直接从数据库中获取配置,可以配合配置推送通知实现实时更新配置。
### 1.3.1 Http接口说明
**URL**: {config_server_url}/configs/{appId}/{clusterName}/{namespaceName}?releaseKey={releaseKey}&ip={clientIp}
**Method**: GET
**参数说明**:
| 参数名 | 是否必须 | 参数值 | 备注 |
|-------------------|----------|----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| config_server_url | 是 | Apollo配置服务的地址 | |
| appId | 是 | 应用的appId | |
| clusterName | 是 | 集群名 | 一般情况下传入 default 即可。 如果希望配置按集群划分,可以参考[集群独立配置说明](zh/usage/apollo-user-guide?id=三、集群独立配置说明)做相关配置,然后在这里填入对应的集群名。 |
| namespaceName | 是 | Namespace的名字 | 如果没有新建过Namespace的话,传入application即可。 如果创建了Namespace,并且需要使用该Namespace的配置,则传入对应的Namespace名字。**需要注意的是对于properties类型的namespace,只需要传入namespace的名字即可,如application。对于其它类型的namespace,需要传入namespace的名字加上后缀名,如datasources.json** |
| releaseKey | 否 | 上一次的releaseKey | 将上一次返回对象中的releaseKey传入即可,用来给服务端比较版本,如果版本比下来没有变化,则服务端直接返回304以节省流量和运算 |
| ip | 否 | 应用部署的机器ip | 这个参数是可选的,用来实现灰度发布。 |
### 1.3.2 Http接口返回格式
该Http接口返回的是JSON格式、UTF-8编码。
如果配置没有变化(传入的releaseKey和服务端的相等),则返回HttpStatus 304,response body为空。
如果配置有变化,则会返回HttpStatus 200,response body为对应namespace的meta信息以及其中所有的配置项。
返回内容Sample如下:
```json
{
"appId": "100004458",
"cluster": "default",
"namespaceName": "application",
"configurations": {
"portal.elastic.document.type":"biz",
"portal.elastic.cluster.name":"hermes-es-fws"
},
"releaseKey": "20170430092936-dee2d58e74515ff3"
}
```
### 1.3.3 测试
由于是Http接口,所以在URL组装OK之后,直接通过浏览器、或者相关的http接口测试工具访问即可。
## 1.4 应用感知配置更新
Apollo提供了基于Http long polling的配置更新推送通知,第三方客户端可以看自己实际的需求决定是否需要使用这个功能。
如果对配置更新时间不是那么敏感的话,可以通过定时刷新来感知配置更新,刷新频率可以视应用自身情况来定,建议在30秒以上。
如果需要做到实时感知配置更新(1秒)的话,可以参考下面的文档实现配置更新推送的功能。
### 1.4.1 配置更新推送实现思路
这里建议大家可以参考Apollo的Java实现:[RemoteConfigLongPollService.java](https://github.com/ctripcorp/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java),代码量200多行,总体上还是比较简单的。
#### 1.4.1.1 初始化
首先需要确定哪些namespace需要配置更新推送,Apollo的实现方式是程序第一次获取某个namespace的配置时就会来注册一下,我们就知道有哪些namespace需要配置更新推送了。
初始化后的结果就是得到一个notifications的Map,内容是namespaceName -> notificationId(初始值为-1)。
运行过程中如果发现有新的namespace需要配置更新推送,直接塞到notifications这个Map里面即可。
#### 1.4.1.2 请求服务
有了notifications这个Map之后,就可以请求服务了。这里先描述一下请求服务的逻辑,具体的URL参数和说明请参见后面的接口说明。
1. 请求远端服务,带上自己的应用信息以及notifications信息
2. 服务端针对传过来的每一个namespace和对应的notificationId,检查notificationId是否是最新的
3. 如果都是最新的,则保持住请求60秒,如果60秒内没有配置变化,则返回HttpStatus 304。如果60秒内有配置变化,则返回对应namespace的最新notificationId, HttpStatus 200。
4. 如果传过来的notifications信息中发现有notificationId比服务端老,则直接返回对应namespace的最新notificationId, HttpStatus 200。
5. 客户端拿到服务端返回后,判断返回的HttpStatus
6. 如果返回的HttpStatus是304,说明配置没有变化,重新执行第1步
7. 如果返回的HttpStauts是200,说明配置有变化,针对变化的namespace重新去服务端拉取配置,参见[1.3 通过不带缓存的Http接口从Apollo读取配置](#_13-%E9%80%9A%E8%BF%87%E4%B8%8D%E5%B8%A6%E7%BC%93%E5%AD%98%E7%9A%84http%E6%8E%A5%E5%8F%A3%E4%BB%8Eapollo%E8%AF%BB%E5%8F%96%E9%85%8D%E7%BD%AE)。同时更新notifications map中的notificationId。重新执行第1步。
### 1.4.2 Http接口说明
**URL**: {config_server_url}/notifications/v2?appId={appId}&cluster={clusterName}¬ifications={notifications}
**Method**: GET
**参数说明**:
| 参数名 | 是否必须 | 参数值 | 备注 |
|-------------------|----------|----------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| config_server_url | 是 | Apollo配置服务的地址 | |
| appId | 是 | 应用的appId | |
| clusterName | 是 | 集群名 | 一般情况下传入 default 即可。 如果希望配置按集群划分,可以参考[集群独立配置说明](zh/usage/apollo-user-guide?id=三、集群独立配置说明)做相关配置,然后在这里填入对应的集群名。 |
| notifications | 是 | notifications信息 | 传入本地的notifications信息,注意这里需要以array形式转为json传入,如:[{"namespaceName": "application", "notificationId": 100}, {"namespaceName": "FX.apollo", "notificationId": 200}]。**需要注意的是对于properties类型的namespace,只需要传入namespace的名字即可,如application。对于其它类型的namespace,需要传入namespace的名字加上后缀名,如datasources.json** |
> 注1:由于服务端会hold住请求60秒,所以请确保客户端访问服务端的超时时间要大于60秒。
> 注2:别忘了对参数进行[url encode](https://en.wikipedia.org/wiki/Percent-encoding)
### 1.4.3 Http接口返回格式
该Http接口返回的是JSON格式、UTF-8编码,包含了有变化的namespace和最新的notificationId。
返回内容Sample如下:
```json
[
{
"namespaceName": "application",
"notificationId": 101
}
]
```
### 1.4.4 测试
由于是Http接口,所以在URL组装OK之后,直接通过浏览器、或者相关的http接口测试工具访问即可。
## 1.5 配置访问密钥
Apollo从1.6.0版本开始增加访问密钥机制,从而只有经过身份验证的客户端才能访问敏感配置。如果应用开启了访问密钥,客户端发出请求时需要增加签名,否则无法获取配置。
需要设置的Header信息:
| Header | Value | 备注 |
|---------------|------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Authorization | Apollo ${appId}:${signature} | appId: 应用的appId,signature:使用访问密钥对当前时间以及所访问的URL加签后的值,具体实现可以参考[Signature.signature](https://github.com/ctripcorp/apollo/blob/aa184a2e11d6e7e3f519d860d69f3cf30ccfcf9c/apollo-core/src/main/java/com/ctrip/framework/apollo/core/signature/Signature.java#L22) |
| Timestamp | 从`1970-1-1 00:00:00 UTC+0`到现在所经过的毫秒数 | 可以参考[System.currentTimeMillis](https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis()) |
## 1.6 错误码说明
正常情况下,接口返回的Http状态码是200,下面列举了Apollo会返回的非200错误码说明。
### 1.6.1 400 - Bad Request
客户端传入参数的错误,如必选参数没有传入等,客户端需要根据提示信息检查对应的参数是否正确。
### 1.6.2 401 - Unauthorized
客户端未授权,如服务端配置了访问密钥,客户端未配置或配置错误。
### 1.6.3 404 - Not Found
接口要访问的资源不存在,一般是URL或URL的参数错误,或者是对应的namespace还没有发布过配置。
### 1.6.4 405 - Method Not Allowed
接口访问的Method不正确,比如应该使用GET的接口使用了POST访问等,客户端需要检查接口访问方式是否正确。
### 1.6.5 500 - Internal Server Error
其它类型的错误默认都会返回500,对这类错误如果应用无法根据提示信息找到原因的话,可以尝试查看服务端日志来排查问题。 | -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/SpringValue.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.property;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import org.springframework.core.MethodParameter;
/**
* Spring @Value method info
*
* @author github.com/zhegexiaohuozi seimimaster@gmail.com
* @since 2018/2/6.
*/
public class SpringValue {
private MethodParameter methodParameter;
private Field field;
private WeakReference<Object> beanRef;
private String beanName;
private String key;
private String placeholder;
private Class<?> targetType;
private Type genericType;
private boolean isJson;
public SpringValue(String key, String placeholder, Object bean, String beanName, Field field, boolean isJson) {
this.beanRef = new WeakReference<>(bean);
this.beanName = beanName;
this.field = field;
this.key = key;
this.placeholder = placeholder;
this.targetType = field.getType();
this.isJson = isJson;
if(isJson){
this.genericType = field.getGenericType();
}
}
public SpringValue(String key, String placeholder, Object bean, String beanName, Method method, boolean isJson) {
this.beanRef = new WeakReference<>(bean);
this.beanName = beanName;
this.methodParameter = new MethodParameter(method, 0);
this.key = key;
this.placeholder = placeholder;
Class<?>[] paramTps = method.getParameterTypes();
this.targetType = paramTps[0];
this.isJson = isJson;
if(isJson){
this.genericType = method.getGenericParameterTypes()[0];
}
}
public void update(Object newVal) throws IllegalAccessException, InvocationTargetException {
if (isField()) {
injectField(newVal);
} else {
injectMethod(newVal);
}
}
private void injectField(Object newVal) throws IllegalAccessException {
Object bean = beanRef.get();
if (bean == null) {
return;
}
boolean accessible = field.isAccessible();
field.setAccessible(true);
field.set(bean, newVal);
field.setAccessible(accessible);
}
private void injectMethod(Object newVal)
throws InvocationTargetException, IllegalAccessException {
Object bean = beanRef.get();
if (bean == null) {
return;
}
methodParameter.getMethod().invoke(bean, newVal);
}
public String getBeanName() {
return beanName;
}
public Class<?> getTargetType() {
return targetType;
}
public String getPlaceholder() {
return this.placeholder;
}
public MethodParameter getMethodParameter() {
return methodParameter;
}
public boolean isField() {
return this.field != null;
}
public Field getField() {
return field;
}
public Type getGenericType() {
return genericType;
}
public boolean isJson() {
return isJson;
}
boolean isTargetBeanValid() {
return beanRef.get() != null;
}
@Override
public String toString() {
Object bean = beanRef.get();
if (bean == null) {
return "";
}
if (isField()) {
return String
.format("key: %s, beanName: %s, field: %s.%s", key, beanName, bean.getClass().getName(), field.getName());
}
return String.format("key: %s, beanName: %s, method: %s.%s", key, beanName, bean.getClass().getName(),
methodParameter.getMethod().getName());
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.property;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import org.springframework.core.MethodParameter;
/**
* Spring @Value method info
*
* @author github.com/zhegexiaohuozi seimimaster@gmail.com
* @since 2018/2/6.
*/
public class SpringValue {
private MethodParameter methodParameter;
private Field field;
private WeakReference<Object> beanRef;
private String beanName;
private String key;
private String placeholder;
private Class<?> targetType;
private Type genericType;
private boolean isJson;
public SpringValue(String key, String placeholder, Object bean, String beanName, Field field, boolean isJson) {
this.beanRef = new WeakReference<>(bean);
this.beanName = beanName;
this.field = field;
this.key = key;
this.placeholder = placeholder;
this.targetType = field.getType();
this.isJson = isJson;
if(isJson){
this.genericType = field.getGenericType();
}
}
public SpringValue(String key, String placeholder, Object bean, String beanName, Method method, boolean isJson) {
this.beanRef = new WeakReference<>(bean);
this.beanName = beanName;
this.methodParameter = new MethodParameter(method, 0);
this.key = key;
this.placeholder = placeholder;
Class<?>[] paramTps = method.getParameterTypes();
this.targetType = paramTps[0];
this.isJson = isJson;
if(isJson){
this.genericType = method.getGenericParameterTypes()[0];
}
}
public void update(Object newVal) throws IllegalAccessException, InvocationTargetException {
if (isField()) {
injectField(newVal);
} else {
injectMethod(newVal);
}
}
private void injectField(Object newVal) throws IllegalAccessException {
Object bean = beanRef.get();
if (bean == null) {
return;
}
boolean accessible = field.isAccessible();
field.setAccessible(true);
field.set(bean, newVal);
field.setAccessible(accessible);
}
private void injectMethod(Object newVal)
throws InvocationTargetException, IllegalAccessException {
Object bean = beanRef.get();
if (bean == null) {
return;
}
methodParameter.getMethod().invoke(bean, newVal);
}
public String getBeanName() {
return beanName;
}
public Class<?> getTargetType() {
return targetType;
}
public String getPlaceholder() {
return this.placeholder;
}
public MethodParameter getMethodParameter() {
return methodParameter;
}
public boolean isField() {
return this.field != null;
}
public Field getField() {
return field;
}
public Type getGenericType() {
return genericType;
}
public boolean isJson() {
return isJson;
}
boolean isTargetBeanValid() {
return beanRef.get() != null;
}
@Override
public String toString() {
Object bean = beanRef.get();
if (bean == null) {
return "";
}
if (isField()) {
return String
.format("key: %s, beanName: %s, field: %s.%s", key, beanName, bean.getClass().getName(), field.getName());
}
return String.format("key: %s, beanName: %s, method: %s.%s", key, beanName, bean.getClass().getName(),
methodParameter.getMethod().getName());
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/MachineUtil.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.core.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.NetworkInterface;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.Enumeration;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class MachineUtil {
private static final Logger logger = LoggerFactory.getLogger(MachineUtil.class);
private static final int MACHINE_IDENTIFIER = createMachineIdentifier();
public static int getMachineIdentifier() {
return MACHINE_IDENTIFIER;
}
/**
* Get the machine identifier from mac address
*
* @see <a href=https://github.com/mongodb/mongo-java-driver/blob/master/bson/src/main/org/bson/types/ObjectId.java>ObjectId.java</a>
*/
private static int createMachineIdentifier() {
// build a 2-byte machine piece based on NICs info
int machinePiece;
try {
StringBuilder sb = new StringBuilder();
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
if (e != null){
while (e.hasMoreElements()) {
NetworkInterface ni = e.nextElement();
sb.append(ni.toString());
byte[] mac = ni.getHardwareAddress();
if (mac != null) {
ByteBuffer bb = ByteBuffer.wrap(mac);
try {
sb.append(bb.getChar());
sb.append(bb.getChar());
sb.append(bb.getChar());
} catch (BufferUnderflowException shortHardwareAddressException) { //NOPMD
// mac with less than 6 bytes. continue
}
}
}
}
machinePiece = sb.toString().hashCode();
} catch (Throwable ex) {
// exception sometimes happens with IBM JVM, use random
machinePiece = (new SecureRandom().nextInt());
logger.warn(
"Failed to get machine identifier from network interface, using random number instead",
ex);
}
return machinePiece;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.core.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.NetworkInterface;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.Enumeration;
/**
* @author Jason Song(song_s@ctrip.com)
*/
public class MachineUtil {
private static final Logger logger = LoggerFactory.getLogger(MachineUtil.class);
private static final int MACHINE_IDENTIFIER = createMachineIdentifier();
public static int getMachineIdentifier() {
return MACHINE_IDENTIFIER;
}
/**
* Get the machine identifier from mac address
*
* @see <a href=https://github.com/mongodb/mongo-java-driver/blob/master/bson/src/main/org/bson/types/ObjectId.java>ObjectId.java</a>
*/
private static int createMachineIdentifier() {
// build a 2-byte machine piece based on NICs info
int machinePiece;
try {
StringBuilder sb = new StringBuilder();
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
if (e != null){
while (e.hasMoreElements()) {
NetworkInterface ni = e.nextElement();
sb.append(ni.toString());
byte[] mac = ni.getHardwareAddress();
if (mac != null) {
ByteBuffer bb = ByteBuffer.wrap(mac);
try {
sb.append(bb.getChar());
sb.append(bb.getChar());
sb.append(bb.getChar());
} catch (BufferUnderflowException shortHardwareAddressException) { //NOPMD
// mac with less than 6 bytes. continue
}
}
}
}
machinePiece = sb.toString().hashCode();
} catch (Throwable ex) {
// exception sometimes happens with IBM JVM, use random
machinePiece = (new SecureRandom().nextInt());
logger.warn(
"Failed to get machine identifier from network interface, using random number instead",
ex);
}
return machinePiece;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/test/java/com/ctrip/framework/apollo/openapi/service/ConsumerServiceTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.openapi.service;
import com.ctrip.framework.apollo.openapi.entity.Consumer;
import com.ctrip.framework.apollo.openapi.entity.ConsumerRole;
import com.ctrip.framework.apollo.openapi.entity.ConsumerToken;
import com.ctrip.framework.apollo.openapi.repository.ConsumerRepository;
import com.ctrip.framework.apollo.openapi.repository.ConsumerRoleRepository;
import com.ctrip.framework.apollo.openapi.repository.ConsumerTokenRepository;
import com.ctrip.framework.apollo.portal.AbstractUnitTest;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import com.ctrip.framework.apollo.portal.entity.po.Role;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.service.RolePermissionService;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.UserService;
import com.ctrip.framework.apollo.portal.util.RoleUtils;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.*;
public class ConsumerServiceTest extends AbstractUnitTest {
@Mock
private ConsumerTokenRepository consumerTokenRepository;
@Mock
private ConsumerRepository consumerRepository;
@Mock
private PortalConfig portalConfig;
@Mock
private UserService userService;
@Mock
private UserInfoHolder userInfoHolder;
@Mock
private ConsumerRoleRepository consumerRoleRepository;
@Mock
private RolePermissionService rolePermissionService;
@Spy
@InjectMocks
private ConsumerService consumerService;
private String someTokenSalt = "someTokenSalt";
private String testAppId = "testAppId";
private String testConsumerName = "testConsumerName";
private String testOwner = "testOwner";
@Before
public void setUp() throws Exception {
when(portalConfig.consumerTokenSalt()).thenReturn(someTokenSalt);
}
@Test
public void testGetConsumerId() throws Exception {
String someToken = "someToken";
long someConsumerId = 1;
ConsumerToken someConsumerToken = new ConsumerToken();
someConsumerToken.setConsumerId(someConsumerId);
when(consumerTokenRepository.findTopByTokenAndExpiresAfter(eq(someToken), any(Date.class)))
.thenReturn(someConsumerToken);
assertEquals(someConsumerId, consumerService.getConsumerIdByToken(someToken).longValue());
}
@Test
public void testGetConsumerIdWithNullToken() throws Exception {
Long consumerId = consumerService.getConsumerIdByToken(null);
assertNull(consumerId);
verify(consumerTokenRepository, never()).findTopByTokenAndExpiresAfter(anyString(), any(Date
.class));
}
@Test
public void testGetConsumerByConsumerId() throws Exception {
long someConsumerId = 1;
Consumer someConsumer = mock(Consumer.class);
when(consumerRepository.findById(someConsumerId)).thenReturn(Optional.of(someConsumer));
assertEquals(someConsumer, consumerService.getConsumerByConsumerId(someConsumerId));
verify(consumerRepository, times(1)).findById(someConsumerId);
}
@Test
public void testCreateConsumerToken() throws Exception {
ConsumerToken someConsumerToken = mock(ConsumerToken.class);
ConsumerToken savedConsumerToken = mock(ConsumerToken.class);
when(consumerTokenRepository.save(someConsumerToken)).thenReturn(savedConsumerToken);
assertEquals(savedConsumerToken, consumerService.createConsumerToken(someConsumerToken));
}
@Test
public void testGenerateConsumerToken() throws Exception {
String someConsumerAppId = "100003171";
Date generationTime = new GregorianCalendar(2016, Calendar.AUGUST, 9, 12, 10, 50).getTime();
String tokenSalt = "apollo";
assertEquals("d0da35292dd5079eeb73cc3a5f7c0759afabd806", consumerService
.generateToken(someConsumerAppId, generationTime, tokenSalt));
}
@Test
public void testGenerateAndEnrichConsumerToken() throws Exception {
String someConsumerAppId = "someAppId";
long someConsumerId = 1;
String someToken = "someToken";
Date generationTime = new Date();
Consumer consumer = mock(Consumer.class);
when(consumerRepository.findById(someConsumerId)).thenReturn(Optional.of(consumer));
when(consumer.getAppId()).thenReturn(someConsumerAppId);
when(consumerService.generateToken(someConsumerAppId, generationTime, someTokenSalt))
.thenReturn(someToken);
ConsumerToken consumerToken = new ConsumerToken();
consumerToken.setConsumerId(someConsumerId);
consumerToken.setDataChangeCreatedTime(generationTime);
consumerService.generateAndEnrichToken(consumer, consumerToken);
assertEquals(someToken, consumerToken.getToken());
}
@Test(expected = IllegalArgumentException.class)
public void testGenerateAndEnrichConsumerTokenWithConsumerNotFound() throws Exception {
long someConsumerIdNotExist = 1;
ConsumerToken consumerToken = new ConsumerToken();
consumerToken.setConsumerId(someConsumerIdNotExist);
consumerService.generateAndEnrichToken(null, consumerToken);
}
@Test
public void testCreateConsumer() {
Consumer consumer = createConsumer(testConsumerName, testAppId, testOwner);
UserInfo owner = createUser(testOwner);
when(consumerRepository.findByAppId(testAppId)).thenReturn(null);
when(userService.findByUserId(testOwner)).thenReturn(owner);
when(userInfoHolder.getUser()).thenReturn(owner);
consumerService.createConsumer(consumer);
verify(consumerRepository).save(consumer);
}
@Test
public void testAssignNamespaceRoleToConsumer() {
Long consumerId = 1L;
String token = "token";
doReturn(consumerId).when(consumerService).getConsumerIdByToken(token);
String testNamespace = "namespace";
String modifyRoleName = RoleUtils.buildModifyNamespaceRoleName(testAppId, testNamespace);
String releaseRoleName = RoleUtils.buildReleaseNamespaceRoleName(testAppId, testNamespace);
String envModifyRoleName = RoleUtils.buildModifyNamespaceRoleName(testAppId, testNamespace, Env.DEV.toString());
String envReleaseRoleName = RoleUtils.buildReleaseNamespaceRoleName(testAppId, testNamespace, Env.DEV.toString());
long modifyRoleId = 1;
long releaseRoleId = 2;
long envModifyRoleId = 3;
long envReleaseRoleId = 4;
Role modifyRole = createRole(modifyRoleId, modifyRoleName);
Role releaseRole = createRole(releaseRoleId, releaseRoleName);
Role envModifyRole = createRole(envModifyRoleId, modifyRoleName);
Role envReleaseRole = createRole(envReleaseRoleId, releaseRoleName);
when(rolePermissionService.findRoleByRoleName(modifyRoleName)).thenReturn(modifyRole);
when(rolePermissionService.findRoleByRoleName(releaseRoleName)).thenReturn(releaseRole);
when(rolePermissionService.findRoleByRoleName(envModifyRoleName)).thenReturn(envModifyRole);
when(rolePermissionService.findRoleByRoleName(envReleaseRoleName)).thenReturn(envReleaseRole);
when(consumerRoleRepository.findByConsumerIdAndRoleId(consumerId, modifyRoleId)).thenReturn(null);
UserInfo owner = createUser(testOwner);
when(userInfoHolder.getUser()).thenReturn(owner);
ConsumerRole namespaceModifyConsumerRole = createConsumerRole(consumerId, modifyRoleId);
ConsumerRole namespaceEnvModifyConsumerRole = createConsumerRole(consumerId, envModifyRoleId);
ConsumerRole namespaceReleaseConsumerRole = createConsumerRole(consumerId, releaseRoleId);
ConsumerRole namespaceEnvReleaseConsumerRole = createConsumerRole(consumerId, envReleaseRoleId);
doReturn(namespaceModifyConsumerRole).when(consumerService).createConsumerRole(consumerId, modifyRoleId, testOwner);
doReturn(namespaceEnvModifyConsumerRole).when(consumerService).createConsumerRole(consumerId, envModifyRoleId, testOwner);
doReturn(namespaceReleaseConsumerRole).when(consumerService).createConsumerRole(consumerId, releaseRoleId, testOwner);
doReturn(namespaceEnvReleaseConsumerRole).when(consumerService).createConsumerRole(consumerId, envReleaseRoleId, testOwner);
consumerService.assignNamespaceRoleToConsumer(token, testAppId, testNamespace);
consumerService.assignNamespaceRoleToConsumer(token, testAppId, testNamespace, Env.DEV.toString());
verify(consumerRoleRepository).save(namespaceModifyConsumerRole);
verify(consumerRoleRepository).save(namespaceEnvModifyConsumerRole);
verify(consumerRoleRepository).save(namespaceReleaseConsumerRole);
verify(consumerRoleRepository).save(namespaceEnvReleaseConsumerRole);
}
private Consumer createConsumer(String name, String appId, String ownerName) {
Consumer consumer = new Consumer();
consumer.setName(name);
consumer.setAppId(appId);
consumer.setOwnerName(ownerName);
return consumer;
}
private Role createRole(long roleId, String roleName) {
Role role = new Role();
role.setId(roleId);
role.setRoleName(roleName);
return role;
}
private ConsumerRole createConsumerRole(long consumerId, long roleId) {
ConsumerRole consumerRole = new ConsumerRole();
consumerRole.setConsumerId(consumerId);
consumerRole.setRoleId(roleId);
return consumerRole;
}
private UserInfo createUser(String userId) {
UserInfo userInfo = new UserInfo();
userInfo.setUserId(userId);
return userInfo;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.openapi.service;
import com.ctrip.framework.apollo.openapi.entity.Consumer;
import com.ctrip.framework.apollo.openapi.entity.ConsumerRole;
import com.ctrip.framework.apollo.openapi.entity.ConsumerToken;
import com.ctrip.framework.apollo.openapi.repository.ConsumerRepository;
import com.ctrip.framework.apollo.openapi.repository.ConsumerRoleRepository;
import com.ctrip.framework.apollo.openapi.repository.ConsumerTokenRepository;
import com.ctrip.framework.apollo.portal.AbstractUnitTest;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import com.ctrip.framework.apollo.portal.entity.po.Role;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.service.RolePermissionService;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.UserService;
import com.ctrip.framework.apollo.portal.util.RoleUtils;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.*;
public class ConsumerServiceTest extends AbstractUnitTest {
@Mock
private ConsumerTokenRepository consumerTokenRepository;
@Mock
private ConsumerRepository consumerRepository;
@Mock
private PortalConfig portalConfig;
@Mock
private UserService userService;
@Mock
private UserInfoHolder userInfoHolder;
@Mock
private ConsumerRoleRepository consumerRoleRepository;
@Mock
private RolePermissionService rolePermissionService;
@Spy
@InjectMocks
private ConsumerService consumerService;
private String someTokenSalt = "someTokenSalt";
private String testAppId = "testAppId";
private String testConsumerName = "testConsumerName";
private String testOwner = "testOwner";
@Before
public void setUp() throws Exception {
when(portalConfig.consumerTokenSalt()).thenReturn(someTokenSalt);
}
@Test
public void testGetConsumerId() throws Exception {
String someToken = "someToken";
long someConsumerId = 1;
ConsumerToken someConsumerToken = new ConsumerToken();
someConsumerToken.setConsumerId(someConsumerId);
when(consumerTokenRepository.findTopByTokenAndExpiresAfter(eq(someToken), any(Date.class)))
.thenReturn(someConsumerToken);
assertEquals(someConsumerId, consumerService.getConsumerIdByToken(someToken).longValue());
}
@Test
public void testGetConsumerIdWithNullToken() throws Exception {
Long consumerId = consumerService.getConsumerIdByToken(null);
assertNull(consumerId);
verify(consumerTokenRepository, never()).findTopByTokenAndExpiresAfter(anyString(), any(Date
.class));
}
@Test
public void testGetConsumerByConsumerId() throws Exception {
long someConsumerId = 1;
Consumer someConsumer = mock(Consumer.class);
when(consumerRepository.findById(someConsumerId)).thenReturn(Optional.of(someConsumer));
assertEquals(someConsumer, consumerService.getConsumerByConsumerId(someConsumerId));
verify(consumerRepository, times(1)).findById(someConsumerId);
}
@Test
public void testCreateConsumerToken() throws Exception {
ConsumerToken someConsumerToken = mock(ConsumerToken.class);
ConsumerToken savedConsumerToken = mock(ConsumerToken.class);
when(consumerTokenRepository.save(someConsumerToken)).thenReturn(savedConsumerToken);
assertEquals(savedConsumerToken, consumerService.createConsumerToken(someConsumerToken));
}
@Test
public void testGenerateConsumerToken() throws Exception {
String someConsumerAppId = "100003171";
Date generationTime = new GregorianCalendar(2016, Calendar.AUGUST, 9, 12, 10, 50).getTime();
String tokenSalt = "apollo";
assertEquals("d0da35292dd5079eeb73cc3a5f7c0759afabd806", consumerService
.generateToken(someConsumerAppId, generationTime, tokenSalt));
}
@Test
public void testGenerateAndEnrichConsumerToken() throws Exception {
String someConsumerAppId = "someAppId";
long someConsumerId = 1;
String someToken = "someToken";
Date generationTime = new Date();
Consumer consumer = mock(Consumer.class);
when(consumerRepository.findById(someConsumerId)).thenReturn(Optional.of(consumer));
when(consumer.getAppId()).thenReturn(someConsumerAppId);
when(consumerService.generateToken(someConsumerAppId, generationTime, someTokenSalt))
.thenReturn(someToken);
ConsumerToken consumerToken = new ConsumerToken();
consumerToken.setConsumerId(someConsumerId);
consumerToken.setDataChangeCreatedTime(generationTime);
consumerService.generateAndEnrichToken(consumer, consumerToken);
assertEquals(someToken, consumerToken.getToken());
}
@Test(expected = IllegalArgumentException.class)
public void testGenerateAndEnrichConsumerTokenWithConsumerNotFound() throws Exception {
long someConsumerIdNotExist = 1;
ConsumerToken consumerToken = new ConsumerToken();
consumerToken.setConsumerId(someConsumerIdNotExist);
consumerService.generateAndEnrichToken(null, consumerToken);
}
@Test
public void testCreateConsumer() {
Consumer consumer = createConsumer(testConsumerName, testAppId, testOwner);
UserInfo owner = createUser(testOwner);
when(consumerRepository.findByAppId(testAppId)).thenReturn(null);
when(userService.findByUserId(testOwner)).thenReturn(owner);
when(userInfoHolder.getUser()).thenReturn(owner);
consumerService.createConsumer(consumer);
verify(consumerRepository).save(consumer);
}
@Test
public void testAssignNamespaceRoleToConsumer() {
Long consumerId = 1L;
String token = "token";
doReturn(consumerId).when(consumerService).getConsumerIdByToken(token);
String testNamespace = "namespace";
String modifyRoleName = RoleUtils.buildModifyNamespaceRoleName(testAppId, testNamespace);
String releaseRoleName = RoleUtils.buildReleaseNamespaceRoleName(testAppId, testNamespace);
String envModifyRoleName = RoleUtils.buildModifyNamespaceRoleName(testAppId, testNamespace, Env.DEV.toString());
String envReleaseRoleName = RoleUtils.buildReleaseNamespaceRoleName(testAppId, testNamespace, Env.DEV.toString());
long modifyRoleId = 1;
long releaseRoleId = 2;
long envModifyRoleId = 3;
long envReleaseRoleId = 4;
Role modifyRole = createRole(modifyRoleId, modifyRoleName);
Role releaseRole = createRole(releaseRoleId, releaseRoleName);
Role envModifyRole = createRole(envModifyRoleId, modifyRoleName);
Role envReleaseRole = createRole(envReleaseRoleId, releaseRoleName);
when(rolePermissionService.findRoleByRoleName(modifyRoleName)).thenReturn(modifyRole);
when(rolePermissionService.findRoleByRoleName(releaseRoleName)).thenReturn(releaseRole);
when(rolePermissionService.findRoleByRoleName(envModifyRoleName)).thenReturn(envModifyRole);
when(rolePermissionService.findRoleByRoleName(envReleaseRoleName)).thenReturn(envReleaseRole);
when(consumerRoleRepository.findByConsumerIdAndRoleId(consumerId, modifyRoleId)).thenReturn(null);
UserInfo owner = createUser(testOwner);
when(userInfoHolder.getUser()).thenReturn(owner);
ConsumerRole namespaceModifyConsumerRole = createConsumerRole(consumerId, modifyRoleId);
ConsumerRole namespaceEnvModifyConsumerRole = createConsumerRole(consumerId, envModifyRoleId);
ConsumerRole namespaceReleaseConsumerRole = createConsumerRole(consumerId, releaseRoleId);
ConsumerRole namespaceEnvReleaseConsumerRole = createConsumerRole(consumerId, envReleaseRoleId);
doReturn(namespaceModifyConsumerRole).when(consumerService).createConsumerRole(consumerId, modifyRoleId, testOwner);
doReturn(namespaceEnvModifyConsumerRole).when(consumerService).createConsumerRole(consumerId, envModifyRoleId, testOwner);
doReturn(namespaceReleaseConsumerRole).when(consumerService).createConsumerRole(consumerId, releaseRoleId, testOwner);
doReturn(namespaceEnvReleaseConsumerRole).when(consumerService).createConsumerRole(consumerId, envReleaseRoleId, testOwner);
consumerService.assignNamespaceRoleToConsumer(token, testAppId, testNamespace);
consumerService.assignNamespaceRoleToConsumer(token, testAppId, testNamespace, Env.DEV.toString());
verify(consumerRoleRepository).save(namespaceModifyConsumerRole);
verify(consumerRoleRepository).save(namespaceEnvModifyConsumerRole);
verify(consumerRoleRepository).save(namespaceReleaseConsumerRole);
verify(consumerRoleRepository).save(namespaceEnvReleaseConsumerRole);
}
private Consumer createConsumer(String name, String appId, String ownerName) {
Consumer consumer = new Consumer();
consumer.setName(name);
consumer.setAppId(appId);
consumer.setOwnerName(ownerName);
return consumer;
}
private Role createRole(long roleId, String roleName) {
Role role = new Role();
role.setId(roleId);
role.setRoleName(roleName);
return role;
}
private ConsumerRole createConsumerRole(long consumerId, long roleId) {
ConsumerRole consumerRole = new ConsumerRole();
consumerRole.setConsumerId(consumerId);
consumerRole.setRoleId(roleId);
return consumerRole;
}
private UserInfo createUser(String userId) {
UserInfo userInfo = new UserInfo();
userInfo.setUserId(userId);
return userInfo;
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest2.xml | <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<apollo:config namespaces="application"/>
<bean class="com.ctrip.framework.apollo.spring.XmlConfigPlaceholderTest.TestXmlBean">
<property name="timeout" value="${timeout:100}"/>
<property name="batch" value="${batch:200}"/>
</bean>
</beans>
| <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:apollo="http://www.ctrip.com/schema/apollo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.ctrip.com/schema/apollo http://www.ctrip.com/schema/apollo.xsd">
<apollo:config namespaces="application"/>
<bean class="com.ctrip.framework.apollo.spring.XmlConfigPlaceholderTest.TestXmlBean">
<property name="timeout" value="${timeout:100}"/>
<property name="batch" value="${batch:200}"/>
</bean>
</beans>
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/repository/GrayReleaseRuleRepository.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.biz.entity.GrayReleaseRule;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface GrayReleaseRuleRepository extends PagingAndSortingRepository<GrayReleaseRule, Long> {
GrayReleaseRule findTopByAppIdAndClusterNameAndNamespaceNameAndBranchNameOrderByIdDesc(String appId, String clusterName,
String namespaceName, String branchName);
List<GrayReleaseRule> findByAppIdAndClusterNameAndNamespaceName(String appId,
String clusterName, String namespaceName);
List<GrayReleaseRule> findFirst500ByIdGreaterThanOrderByIdAsc(Long id);
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.biz.entity.GrayReleaseRule;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface GrayReleaseRuleRepository extends PagingAndSortingRepository<GrayReleaseRule, Long> {
GrayReleaseRule findTopByAppIdAndClusterNameAndNamespaceNameAndBranchNameOrderByIdDesc(String appId, String clusterName,
String namespaceName, String branchName);
List<GrayReleaseRule> findByAppIdAndClusterNameAndNamespaceName(String appId,
String clusterName, String namespaceName);
List<GrayReleaseRule> findFirst500ByIdGreaterThanOrderByIdAsc(Long id);
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/datasource/TitanSettings.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.datasource;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.core.enums.EnvUtils;
import com.ctrip.framework.foundation.Foundation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class TitanSettings {
@Value("${fat.titan.url:}")
private String fatTitanUrl;
@Value("${uat.titan.url:}")
private String uatTitanUrl;
@Value("${pro.titan.url:}")
private String proTitanUrl;
@Value("${fat.titan.dbname:}")
private String fatTitanDbname;
@Value("${uat.titan.dbname:}")
private String uatTitanDbname;
@Value("${pro.titan.dbname:}")
private String proTitanDbname;
public String getTitanUrl() {
Env env = EnvUtils.transformEnv(Foundation.server().getEnvType());
switch (env) {
case FAT:
case FWS:
return fatTitanUrl;
case UAT:
return uatTitanUrl;
case TOOLS:
case PRO:
return proTitanUrl;
default:
return "";
}
}
public String getTitanDbname() {
Env env = EnvUtils.transformEnv(Foundation.server().getEnvType());
switch (env) {
case FAT:
case FWS:
return fatTitanDbname;
case UAT:
return uatTitanDbname;
case TOOLS:
case PRO:
return proTitanDbname;
default:
return "";
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.datasource;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.core.enums.EnvUtils;
import com.ctrip.framework.foundation.Foundation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class TitanSettings {
@Value("${fat.titan.url:}")
private String fatTitanUrl;
@Value("${uat.titan.url:}")
private String uatTitanUrl;
@Value("${pro.titan.url:}")
private String proTitanUrl;
@Value("${fat.titan.dbname:}")
private String fatTitanDbname;
@Value("${uat.titan.dbname:}")
private String uatTitanDbname;
@Value("${pro.titan.dbname:}")
private String proTitanDbname;
public String getTitanUrl() {
Env env = EnvUtils.transformEnv(Foundation.server().getEnvType());
switch (env) {
case FAT:
case FWS:
return fatTitanUrl;
case UAT:
return uatTitanUrl;
case TOOLS:
case PRO:
return proTitanUrl;
default:
return "";
}
}
public String getTitanDbname() {
Env env = EnvUtils.transformEnv(Foundation.server().getEnvType());
switch (env) {
case FAT:
case FWS:
return fatTitanDbname;
case UAT:
return uatTitanDbname;
case TOOLS:
case PRO:
return proTitanDbname;
default:
return "";
}
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/ConfigsExportService.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.service;
import com.ctrip.framework.apollo.common.dto.ClusterDTO;
import com.ctrip.framework.apollo.common.entity.App;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.portal.component.PermissionValidator;
import com.ctrip.framework.apollo.portal.component.PortalSettings;
import com.ctrip.framework.apollo.portal.entity.bo.ConfigBO;
import com.ctrip.framework.apollo.portal.entity.bo.NamespaceBO;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.util.ConfigFileUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@Service
public class ConfigsExportService {
private static final Logger logger = LoggerFactory.getLogger(ConfigsExportService.class);
private final AppService appService;
private final ClusterService clusterService;
private final NamespaceService namespaceService;
private final PortalSettings portalSettings;
private final PermissionValidator permissionValidator;
public ConfigsExportService(
AppService appService,
ClusterService clusterService,
final @Lazy NamespaceService namespaceService,
PortalSettings portalSettings,
PermissionValidator permissionValidator) {
this.appService = appService;
this.clusterService = clusterService;
this.namespaceService = namespaceService;
this.portalSettings = portalSettings;
this.permissionValidator = permissionValidator;
}
/**
* write multiple namespace to a zip. use {@link Stream#reduce(Object, BiFunction,
* BinaryOperator)} to forbid concurrent write.
*
* @param configBOStream namespace's stream
* @param outputStream receive zip file output stream
* @throws IOException if happen write problem
*/
private static void writeAsZipOutputStream(
Stream<ConfigBO> configBOStream, OutputStream outputStream) throws IOException {
try (final ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
final Consumer<ConfigBO> configBOConsumer =
configBO -> {
try {
// TODO, Stream.reduce will cause some problems. Is There other way to speed up the
// downloading?
synchronized (zipOutputStream) {
write2ZipOutputStream(zipOutputStream, configBO);
}
} catch (IOException e) {
logger.error("Write error. {}", configBO);
throw new IllegalStateException(e);
}
};
configBOStream.forEach(configBOConsumer);
}
}
/**
* write {@link ConfigBO} as file to {@link ZipOutputStream}. Watch out the concurrent problem!
* zip output stream is same like cannot write concurrently! the name of file is determined by
* {@link ConfigFileUtils#toFilename(String, String, String, ConfigFileFormat)}. the path of file
* is determined by {@link ConfigFileUtils#toFilePath(String, String, Env, String)}.
*
* @param zipOutputStream zip file output stream
* @param configBO a namespace represent
* @return zip file output stream same as parameter zipOutputStream
*/
private static ZipOutputStream write2ZipOutputStream(
final ZipOutputStream zipOutputStream, final ConfigBO configBO) throws IOException {
final Env env = configBO.getEnv();
final String ownerName = configBO.getOwnerName();
final String appId = configBO.getAppId();
final String clusterName = configBO.getClusterName();
final String namespace = configBO.getNamespace();
final String configFileContent = configBO.getConfigFileContent();
final ConfigFileFormat configFileFormat = configBO.getFormat();
final String configFilename =
ConfigFileUtils.toFilename(appId, clusterName, namespace, configFileFormat);
final String filePath = ConfigFileUtils.toFilePath(ownerName, appId, env, configFilename);
final ZipEntry zipEntry = new ZipEntry(filePath);
try {
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write(configFileContent.getBytes());
zipOutputStream.closeEntry();
} catch (IOException e) {
logger.error("config export failed. {}", configBO);
throw new IOException("config export failed", e);
}
return zipOutputStream;
}
/** @return the namespaces current user exists */
private Stream<ConfigBO> makeStreamBy(
final Env env, final String ownerName, final String appId, final String clusterName) {
final List<NamespaceBO> namespaceBOS =
namespaceService.findNamespaceBOs(appId, env, clusterName);
final Function<NamespaceBO, ConfigBO> function =
namespaceBO -> new ConfigBO(env, ownerName, appId, clusterName, namespaceBO);
return namespaceBOS.parallelStream().map(function);
}
private Stream<ConfigBO> makeStreamBy(final Env env, final String ownerName, final String appId) {
final List<ClusterDTO> clusterDTOS = clusterService.findClusters(env, appId);
final Function<ClusterDTO, Stream<ConfigBO>> function =
clusterDTO -> this.makeStreamBy(env, ownerName, appId, clusterDTO.getName());
return clusterDTOS.parallelStream().flatMap(function);
}
private Stream<ConfigBO> makeStreamBy(final Env env, final List<App> apps) {
final Function<App, Stream<ConfigBO>> function =
app -> this.makeStreamBy(env, app.getOwnerName(), app.getAppId());
return apps.parallelStream().flatMap(function);
}
private Stream<ConfigBO> makeStreamBy(final Collection<Env> envs) {
// get all apps
final List<App> apps = appService.findAll();
// permission check
final Predicate<App> isAppAdmin =
app -> {
try {
return permissionValidator.isAppAdmin(app.getAppId());
} catch (Exception e) {
logger.error("app = {}", app);
logger.error(app.getAppId());
}
return false;
};
// app admin permission filter
final List<App> appsExistPermission =
apps.stream().filter(isAppAdmin).collect(Collectors.toList());
return envs.parallelStream().flatMap(env -> this.makeStreamBy(env, appsExistPermission));
}
/**
* Export all projects which current user own them. Permission check by {@link
* PermissionValidator#isAppAdmin(java.lang.String)}
*
* @param outputStream network file download stream to user
* @throws IOException if happen write problem
*/
public void exportAllTo(OutputStream outputStream) throws IOException {
final List<Env> activeEnvs = portalSettings.getActiveEnvs();
final Stream<ConfigBO> configBOStream = this.makeStreamBy(activeEnvs);
writeAsZipOutputStream(configBOStream, outputStream);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.service;
import com.ctrip.framework.apollo.common.dto.ClusterDTO;
import com.ctrip.framework.apollo.common.entity.App;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.portal.component.PermissionValidator;
import com.ctrip.framework.apollo.portal.component.PortalSettings;
import com.ctrip.framework.apollo.portal.entity.bo.ConfigBO;
import com.ctrip.framework.apollo.portal.entity.bo.NamespaceBO;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.util.ConfigFileUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@Service
public class ConfigsExportService {
private static final Logger logger = LoggerFactory.getLogger(ConfigsExportService.class);
private final AppService appService;
private final ClusterService clusterService;
private final NamespaceService namespaceService;
private final PortalSettings portalSettings;
private final PermissionValidator permissionValidator;
public ConfigsExportService(
AppService appService,
ClusterService clusterService,
final @Lazy NamespaceService namespaceService,
PortalSettings portalSettings,
PermissionValidator permissionValidator) {
this.appService = appService;
this.clusterService = clusterService;
this.namespaceService = namespaceService;
this.portalSettings = portalSettings;
this.permissionValidator = permissionValidator;
}
/**
* write multiple namespace to a zip. use {@link Stream#reduce(Object, BiFunction,
* BinaryOperator)} to forbid concurrent write.
*
* @param configBOStream namespace's stream
* @param outputStream receive zip file output stream
* @throws IOException if happen write problem
*/
private static void writeAsZipOutputStream(
Stream<ConfigBO> configBOStream, OutputStream outputStream) throws IOException {
try (final ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
final Consumer<ConfigBO> configBOConsumer =
configBO -> {
try {
// TODO, Stream.reduce will cause some problems. Is There other way to speed up the
// downloading?
synchronized (zipOutputStream) {
write2ZipOutputStream(zipOutputStream, configBO);
}
} catch (IOException e) {
logger.error("Write error. {}", configBO);
throw new IllegalStateException(e);
}
};
configBOStream.forEach(configBOConsumer);
}
}
/**
* write {@link ConfigBO} as file to {@link ZipOutputStream}. Watch out the concurrent problem!
* zip output stream is same like cannot write concurrently! the name of file is determined by
* {@link ConfigFileUtils#toFilename(String, String, String, ConfigFileFormat)}. the path of file
* is determined by {@link ConfigFileUtils#toFilePath(String, String, Env, String)}.
*
* @param zipOutputStream zip file output stream
* @param configBO a namespace represent
* @return zip file output stream same as parameter zipOutputStream
*/
private static ZipOutputStream write2ZipOutputStream(
final ZipOutputStream zipOutputStream, final ConfigBO configBO) throws IOException {
final Env env = configBO.getEnv();
final String ownerName = configBO.getOwnerName();
final String appId = configBO.getAppId();
final String clusterName = configBO.getClusterName();
final String namespace = configBO.getNamespace();
final String configFileContent = configBO.getConfigFileContent();
final ConfigFileFormat configFileFormat = configBO.getFormat();
final String configFilename =
ConfigFileUtils.toFilename(appId, clusterName, namespace, configFileFormat);
final String filePath = ConfigFileUtils.toFilePath(ownerName, appId, env, configFilename);
final ZipEntry zipEntry = new ZipEntry(filePath);
try {
zipOutputStream.putNextEntry(zipEntry);
zipOutputStream.write(configFileContent.getBytes());
zipOutputStream.closeEntry();
} catch (IOException e) {
logger.error("config export failed. {}", configBO);
throw new IOException("config export failed", e);
}
return zipOutputStream;
}
/** @return the namespaces current user exists */
private Stream<ConfigBO> makeStreamBy(
final Env env, final String ownerName, final String appId, final String clusterName) {
final List<NamespaceBO> namespaceBOS =
namespaceService.findNamespaceBOs(appId, env, clusterName);
final Function<NamespaceBO, ConfigBO> function =
namespaceBO -> new ConfigBO(env, ownerName, appId, clusterName, namespaceBO);
return namespaceBOS.parallelStream().map(function);
}
private Stream<ConfigBO> makeStreamBy(final Env env, final String ownerName, final String appId) {
final List<ClusterDTO> clusterDTOS = clusterService.findClusters(env, appId);
final Function<ClusterDTO, Stream<ConfigBO>> function =
clusterDTO -> this.makeStreamBy(env, ownerName, appId, clusterDTO.getName());
return clusterDTOS.parallelStream().flatMap(function);
}
private Stream<ConfigBO> makeStreamBy(final Env env, final List<App> apps) {
final Function<App, Stream<ConfigBO>> function =
app -> this.makeStreamBy(env, app.getOwnerName(), app.getAppId());
return apps.parallelStream().flatMap(function);
}
private Stream<ConfigBO> makeStreamBy(final Collection<Env> envs) {
// get all apps
final List<App> apps = appService.findAll();
// permission check
final Predicate<App> isAppAdmin =
app -> {
try {
return permissionValidator.isAppAdmin(app.getAppId());
} catch (Exception e) {
logger.error("app = {}", app);
logger.error(app.getAppId());
}
return false;
};
// app admin permission filter
final List<App> appsExistPermission =
apps.stream().filter(isAppAdmin).collect(Collectors.toList());
return envs.parallelStream().flatMap(env -> this.makeStreamBy(env, appsExistPermission));
}
/**
* Export all projects which current user own them. Permission check by {@link
* PermissionValidator#isAppAdmin(java.lang.String)}
*
* @param outputStream network file download stream to user
* @throws IOException if happen write problem
*/
public void exportAllTo(OutputStream outputStream) throws IOException {
final List<Env> activeEnvs = portalSettings.getActiveEnvs();
final Stream<ConfigBO> configBOStream = this.makeStreamBy(activeEnvs);
writeAsZipOutputStream(configBOStream, outputStream);
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./apollo-adminservice/src/main/java/com/ctrip/framework/apollo/adminservice/controller/ItemSetController.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.adminservice.controller;
import com.ctrip.framework.apollo.adminservice.aop.PreAcquireNamespaceLock;
import com.ctrip.framework.apollo.biz.service.ItemSetService;
import com.ctrip.framework.apollo.common.dto.ItemChangeSets;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ItemSetController {
private final ItemSetService itemSetService;
public ItemSetController(final ItemSetService itemSetService) {
this.itemSetService = itemSetService;
}
@PreAcquireNamespaceLock
@PostMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/itemset")
public ResponseEntity<Void> create(@PathVariable String appId, @PathVariable String clusterName,
@PathVariable String namespaceName, @RequestBody ItemChangeSets changeSet) {
itemSetService.updateSet(appId, clusterName, namespaceName, changeSet);
return ResponseEntity.status(HttpStatus.OK).build();
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.adminservice.controller;
import com.ctrip.framework.apollo.adminservice.aop.PreAcquireNamespaceLock;
import com.ctrip.framework.apollo.biz.service.ItemSetService;
import com.ctrip.framework.apollo.common.dto.ItemChangeSets;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ItemSetController {
private final ItemSetService itemSetService;
public ItemSetController(final ItemSetService itemSetService) {
this.itemSetService = itemSetService;
}
@PreAcquireNamespaceLock
@PostMapping("/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/itemset")
public ResponseEntity<Void> create(@PathVariable String appId, @PathVariable String clusterName,
@PathVariable String namespaceName, @RequestBody ItemChangeSets changeSet) {
itemSetService.updateSet(appId, clusterName, namespaceName, changeSet);
return ResponseEntity.status(HttpStatus.OK).build();
}
}
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./scripts/flyway/configdb/V1.1.2__extend_username.sql | --
-- Copyright 2021 Apollo 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.
--
# delta schema to upgrade apollo config db from v1.7.0 to v1.8.0
Use ApolloConfigDB;
ALTER TABLE `App`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `AppNamespace`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `Audit`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `Cluster`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `Commit`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `GrayReleaseRule`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `Item`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `Namespace`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `NamespaceLock`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `Release`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `ReleaseHistory`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `ServerConfig`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `AccessKey`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
| --
-- Copyright 2021 Apollo 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.
--
# delta schema to upgrade apollo config db from v1.7.0 to v1.8.0
Use ApolloConfigDB;
ALTER TABLE `App`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `AppNamespace`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `Audit`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `Cluster`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `Commit`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `GrayReleaseRule`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `Item`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `Namespace`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `NamespaceLock`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `Release`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `ReleaseHistory`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `ServerConfig`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
ALTER TABLE `AccessKey`
MODIFY COLUMN `DataChange_CreatedBy` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '创建人邮箱前缀',
MODIFY COLUMN `DataChange_LastModifiedBy` VARCHAR(64) DEFAULT '' COMMENT '最后修改人邮箱前缀';
| -1 |
apolloconfig/apollo | 3,677 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题 | ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | klboke | 2021-05-11T09:35:40Z | 2021-05-23T11:44:16Z | f41a73b92d19383bbb542c51b0f6d062e9e80e3b | dc41c934349af28631cc5b2d9b2bdf75eac9d1f3 | 解决日志系统未初始化完成时,apollo 的加载日志没法输出问题. ## What's the purpose of this PR
> 解决问题:
解决 spring boot 方式集成时,配置 `apollo.bootstrap.eagerLoad.enabled` 情况下,apollo 的加载日志没法输出问题。
> 设计原理:
封装一个基于 guava-cache 的日志输出内容存储容器 `DeferredLogUtil`,将 apollo 初始化时的日志信息,添加到延迟输出的日志容器。在日志系统加载完成也就是 EnvironmentPostProcessor 事件立刻回放,最终实现的效果和不开启 `apollo.bootstrap.eagerLoad.enabled` 是一样的,设计过程参考了 [spring-boot#DeferredLog](https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/logging/DeferredLog.java) | ./doc/images/text-mode-config-submit.png | PNG
IHDR $ D ) iCCPICC Profile HWTZ ҫ.H! J A^\`EWElkdQQ,,AEEY6T$tWλ߹wg e'@ /Ƅ3S$ @`Z # @UiWQpEl h8"v. a 7Q !A d)ΐc])Nc;M\L ā ,0 %i|f!;Q@lo؛@,xlnnT-Ҿi1YQ,E&@HÚNFP31ҜbiEFAGf/w2š}lQ 3p9p\qv0v` e
4a^p|1gY&7lo劂bGlyaÝ+ʌKD[
y +A!ʎ
}P9b#H9@6]#4sE#yall,M}2BXW1
s8\~07.abAN=#g차0vķ n0<`Xw897 &Ò@/yO0`! \`3Haqh_PeT+m@P
@k'k_Xp7}ď<2*1H%-Gy!Xot\#9|GxB$<$\'HAx,2l5Hs&$0Zpvi0f
nY;\N0?3r6?'e}>z%+%ai+0jc-eQ;]:NcXvRGwcN-F-}aBz22~eٶcv. H쿍0.}7^t,c N<5<^8:\Z (Ó199 |A @Hg\zbP
V
l;^p uepoBGF7 B"$IE2>"F Rd-R@_"҉F^5 P*f8
C8t*Et%ZVZzJ 0Eb6Ea)X:&a%XVZ_$X'tl<+x-ނ_Ż~+F%X<a$BaPFM8N8NHd͉l&+[MN# D"YHQ$TLDO:M">dr09'/"OOɃ
*
Q
Y
v)4(\QQR)^8Je!rrrFQQH]q"Oqba݊jT+j u
UL]ICmަhf4_Z
VM;K{@DWU
S(WTURzl<MHL>3 <J*7UTQ+T^T}FR3SR-Q۩vVlb.9z:Q\=L=KTzzFLJ0c1rG7|1]ckhjr5K4i^
ZUu_Ҟ=C{9>uON;nlݝmzz!zMzgYO
x
N<gj09rfP0Plðp(h!c7t&&MԘ1U0u34hj,lY3sM0"{4|*kDK7l-VUUkŚgźs,aXت7m6~6656ݶEu/ǙKf\븯vv9vګO_d`ʁPp͑8߱i-gD_\\].]z]M\S]7tSwv[v>߽G<m<=y>o>;~G^F^,^owvo˧硯/wS?K,~/x
h
CKۃԂ*g8i
% :apjxlxEaDDt℉&ދ4GEuQͣD=rғ91bǭo/oNPNP>10qm$i\ܤɼRJBA7L<xʍSgN8M{ZδӕM%&K̊bU6/8^w-iWg^2z3}22x
ޫЬmYﳣd$%-yy3:ւb$#C~0\[UMl!I]]XYaF3UggͲ|Ӣ_fٳY8{yi_2gAȂ)nEo'.nXdG?TST,,se27-Z)TjWZVy{ť.yheU.&毾gk>Z7q]zo7Lp̩lFFFIyDy&M7}Ȭ^_yhol6m>mm#dGmYUNOv%jڻKw#ڵzU5hw9PapX|8~уLm>N?^RΪˬ'wpoi4l<qr)ʩ%Nh48yzݳIgLji?~g[ZO_xKn.\msn;]k^phy˧篅]|=znN)ŹvWw
]ppEr;aû؏^<=ܳ IS5v<`_n~i_'z֛=o6D<xn}{?}lϤ_,4|
zo(whHdW4={ %û|Q/ 7o4_ ([a1
[;eXDXT!|z /¡-CC_vAhʗBwRF?ʿ <9lXA%'Y @ IDATx|VE5H :
"v\{ǾEײo{w[\]ꢮ`EY+EzKHw>7>- ϓ>sgݹsߜslڼ}("("("("("("(@
OSE@PE@PE@PE@PE@PE@P,JDiGPE@PE@PE@PE@PE@PE@XRE@PE@PE@PE@PE@PE@P`m
[EΝ[WE@PE@PE@PE@PE@PE@,Xy \QwN IPE@PE@PE@PE@PE@PE (G2=H́UDPE@PE@PE@PE@PE@PE Q(e"
Ҏ("("("("("(@C Q(e"*QAg("("("("("(@F Q(e"fçg("("("("("("P^*/Z^PE@PE@PE@PE@PE@PE %aDE@PE@PE@PE@PE@PE@P"DTy"("("("("("((&*"("("("("("%ʋWE@PE@PE@PE@PE@PE@D@@X4QPE@PE@PE@PE@PE@PE(U^"("("("("("(@ JD¢"("("("("("(E@"E@PE@PE@PE@PE@PE@PP"*MTE@PE@PE@PE@PE@PE@(/JDA-("("("("("("Qh"("("("("("(@yP"jyE@PE@PE@PE@PE@PE@P@
EE@PE@PE@PE@PE@PE@Pʋ@VE@PE@PE@Pj͖o~#RP8~l!}ztF֭>RRRRZj P^=̔f͚O*
jZ"~ڣ!Q}?Tk-/@E粵W~JMN0v>7;wJ5ZFPE@PE@PE!PTR${Mn^ZZM@2hI/4|ٲeKB5SB ++Kt"(y5c>f]~6m9-nݺ~%bE@PE@PE@Px- g
nP5k.)YlBF㜄`ܹjڴlZ$JZ$t ʹ_X\blݺUPru=vhH&ʹHivHԌo5:Y"P\8&KDCEu)"("("PPP
ҕ"^KsM\x*!PX@X( 걟k٣Giܸ\x!B_#J?vm쐨9jε3;J9]UpS"\ m"("("(UGR` Rp]XgvZK(@۶m퉹k,]P}dkgDPim>TK}"("("Tn/% _5`I4]Swcݾ}*s@ff=1wcˣ!Jo L?v쐨yj5gJx)_PE@PE@Pj@jRmf$rKJJR^UDu"yik3kcwڟ5[CͻR/%+"("("("("("PCP"^X=-E@PE@PE@PE@PE@PE@P7JD+WE@PE@PE@PE@PE@PE"Pv-͓;vDaR~}ڵԭEN:UܨC1-WZSPE@PE@PE@PE@PEP"bSO=%vjY:u䦛nH:ĉe4ѪUZID)&"("("("("("<JD%Y*Q^=k'8 (4lПdSOMs_-X9ٹs:Tڶm뒢k:&Q'?E@PE@PE@PE@PE@P
D`6+ժ9sdeשSP"LfMPE@PE@PE@PE@PE@PP"*!4SMA@w%/pa*ҵ:%tnB4SD`=jY+"("("("PM[Mۭͮ$pS$An4Ť&^U='E@PE@PE@PE@PE@P}ZD1 ~ˎ;ʴ8;;LZmHPLjUsTE@PE@PE@PE@PE@,j4yfYnl߾=_ZZ4o\4iI+FqqZJ
mUUV^ު#ׯ_oe6-77מG$Cmdff-[ڵk#cQD֬Y#,ի'M6f͚Iu|
4=$??_-[&6l1[h!pp=+R8}^71*OVd{.E@PE@PE*#0Pٱk,XV4A6=ƠVdێm*Ūb
ٵktN-B l2J/xEx>##CX\폫F?F/n%L'?U[^1QF)_gki&(AlܸHT_PKKL{_ΛN{ɜ9s"
CO"[b-z!t,B*W\qlݺU^uowMF-999IOe2A]tEҥK:u[s8餓d䔷(;V/^lvў;Oz|?ɰ'裏'4?Yz^P\?\(uF{={L2Ş˻+3g/-pb_|/ &CÇi˗/~Z ;'
$sI&AҩS'9$9h)"("(#)6[7뾱Pl%5?H֩+2;ޑrF3$aY?G&-2l}(mRKV}kyw'?I~vmva!exoT?,X@X ܵkW3A}QygwL=J3Au'luA+Ro[.rmM
z0gs}~B~yX@.J,f%K{モo]N=@&M$7t\z,0&_0 :;}w`( ~_ɴi"}1,|<ʒm۶JYy
۴i<V=5e_" -^~儮
r%\R l
4O<r["M]+ ,MnS^.7_2LX◠4r0@/Zr
cǎYyP\re~"ëj⋣&{OHoΛ'xbd*ny$"<!>#kWP9&
?DbG1bDv"PlXO~z\wY@*_[W<yeR)(~N>lC:̕KZV%])"(@nMKnZnj%unj[sGNKB+`\wuoZjBϨ{ /)"Vgu]go<䓑}N)=ɞ={ڟ% 82XR@C}kQ,DPCBO#<K}≮l9Hӿ*B=O>G
'Z^U,z8}5YaqH;WO}˼yZpo1VɶSEkA TҡCtzQβ
WH2PJ~zL#o.rM*~0l-/FAui@-J1D,P
Db+@AL,ubo=Xzd~vIZ讻
;
:2$@$0.~4'&k0
Cz\"ߋw;s-
Un%ꫯC&L`-Gw(5
,)%w,̏2&r2{Xrkⷫ翎Iu ʃ_KNoR(aU0#'?Wdr?5,\re-{likΛW_irC]Yޜ|[ez"("PQzXmyymd(PX2#,azuIΧ^s9i9ҸAٕO&-3KWocF[+tҰ]^NpɊ8A"Ϋ*?|yG{&:nƨ4Q`3-P;9^`aÂX>ĕs,z[J:}cxU[Qcz5t<8ʻ?^QTzV(q% H|ڷoo=|MF_cXB?ΰV;"ʸ&[X oTA^ 'C^14Q=o^ְu?8.!3f̐/7~ñkσ$ӟ*%w 訩PboҥvPuigI^^T;_e,*<uT*fBBvP/V2EWTH$1BZ:r-I282IHTXǪ*
&rOs"a~:bth)K(=밽i
ɝgt;Jw/δaݚ~Tn#P&ϟbӿcS$Ut-C<yρml!sybvyߊ"(B3J&RlIiѦEfٹk%6|'6ȩO5n''$o-ze#ڏMQ;|? .u/5'ճ?)W*UH۶m-TJlC;nܸQk7U߹sZP,EPW@:(kl/,./1whrR^]ܱt^23ғ+lrNuqګ@y9yd~
<+o]TM~gO"rg7\Fb
X˄BcAN>n#Lze|^q>K'<@vَ{1c|A;.qdkX"of[oUnKF k0[)ٵ Ku}uI}a\KU`BmtXay&,`}X{瞰e;Ru Da3'8)˳6r)uDŽxӔsڷo_KDwF(+D#P#ӧT(097|53:k2
WxV92Yf ;fe~CdÁ
6;)& a¤#!YpYV&-gއ+ ×v>lptþHRG[7-N**ze Lj}L[hU͐6p [wNY&'"Y&B\={$kh ԵU|pˈ
EjjJbx
ޙlc E)'i^7Y[Rqz}mP9v)kF]Z?~EO9˷K;o`J6,8 9ϐR7&+7nO
ͯ(" T#Cشt$/:4v0$Ϣ-"6dhl,IgcujygZu˾b[%~SXKTy#/A'*x%
މ1i$9rdD_F?^).!c_~G~I3
dIQ4
;E>edZ>&dBeo)#GgD^AS?HQ֓6OXo@xv
1Gh$SƟ_mA?-6:%
~L*^:2o<pҞJaÆ u}ѭkÊ paF_;oֆtԨQ:i?B|4
ȗfˇO,u6Yaҽs:6nS{\d%2A")Br<Z{\<t$:Loq{/?7 m'˪BԳgl9X?+Q,nqw\|a=ì^=sw!]bPM|Ax`?ߤo&0F
bc
~gɛ#֬Y8A\P\#&?~1;̰ADYgau%bR4LXƋ6<_ykTnt&2sʵW{'ɠ .vB ڽ憘0_,k5l!HhhƄgep'xM
a@lԁevjJs-d~I=RPXL9VD!f)iGCLNoQ7.}~$cʰzڡ4_2_PE@H x*9t1鲽dl.JȦ{'h*od˳ߛ*EQx4h(
}K,SLWe*,)m7ku/%Ұ^C_'|NsNkPyo)**F1xc*(^c (\8p#
w zX=7X]XǪ6m&/9IubeؗޕHF;4)"N⋈7SzH˻<VP(QO8;8.s8aA,epH Ý">C\Y
DB?.OG6p@Fo{ XYcj~lyoҗ2):yՕZɉ#ʰf9MLGX+\~s[(\3ƺ)U).FQC"Xrz"tO~!9{0$k,OD7D5x(k*57[/oL5j+{w-^یRsUǾ&}mģ帣4ׂ-ܷDqt<7zb>zrrUWɉ'hux
髌A
߶Eb$Щ
sJ客ixArgDPe@reE hӦ]%k6 a(VLc6Z%H0c&6Ay*"
Yp{&9X
c+Vغ8O a@4Ț_.
(&\y!a0
gm->S.$ty"C2L cgB5O!^%2-B$-mO;b=T)En%`%gqFG}.zk+K>Z`e)bՄSܵ%M5cV^붘cIReuTrN 5%*P_18(?X1UsA1HWs()":buRtl':K"߾, ~om'pӉxNyybe;ewiR_{ ΐu+>ۣ,~xɦìYApQmk.?
k[卥
(ֻ8gϾ:EX` Uĭ>o^AM/u {wq!d
;g
6ݻ_n;&fkvn E!p/,K\{,GP\Z \un+-!i+_E!Jy" h?[H[SaRӯX=CJ~b׳oEINw7\A<iw;tdZs9ZAg,f@0Vނ0wB,P.'w"kCUvϺg
/nyrep^_̘=W|c),X\=8ԾyFE"9o euxmd~?zKB d~A`IѠ:X$!~s5Uǎ]rZU#8a =dSҗ 0%{sy˻m,xf./1ǻp!^D^0xU`0\h2ŸD0AF^L/{A$?_e?[ c0x*XRo^ [EċT<2х%{(Li7.%r3ӌ体7s??"&ȸ1ɳ~k͏B^ҽh[2B,%m,!
U{;Xc4~J.k|ϫ<\SiDAKS;>,Vơ@Ax{n=}_>U7}~`"(@4SjվQ{ク%.O
vX+%!l7jPj
6VLn_թ'w[](]"MTrd&Ks)7qA+,OXu xN!{'ӏ~#[
dJ[\a-
kCldʰ=<,-1YlܴU>%bGvV#@iג~am߮V\;"/Yx>LVZqF)=9~bd9xT%^z^n -])w"iπ
__ޞqÖ+gt4n|g>\
16}BcokZR"I&<x{ ǽڵkgcKV*gn[s̙3-/ {ߵP< N:v\x(iJۋC!=Y^7A^~!ulqxzw11}p'xyEglfHy+#Vv,#HTcHۭSy&b*ɍk2X`Ox~vI S[Ap`mÍf$MeZ' )Ipyo~6M%dۂHw|
Nb`13fL2q&<-AHRU\t&CI$qx5UwewO.Lf̃)*XnlDJxؘ|zBιVߦm2dĕUфّ)ƒҭIg&
WkynL8#[7Zx@$v.R,_&0ggt/jH
qp!ԸA]oMI>o2/A1i-̹vk!$&=Ӎ5W-д5C*#msٶbrV`pKJXC~q5;vkc&m3g,p/KvPKK
ݸTX?^U'r~;w}KMЬ?><W!|~BN1DwkSƲzCX֭qb<"#XߴpO]oX!8xm.Xu*H(~ml uCF]HYа2("! I [dTV]c斥RZ[$;k,㕌rAҼ[(uiEiy22-3gm[M=whC¢OXĔG/qH +!)vObFmݵ
D]gQ^kuX(}d:z XvFn&yfX:fQ
z7z藘ctꩧZ}D##,nן"ܠ^ܤA*-Я ė#]ͅ= /(cIo/-]Z>r7d)#rfY'cUYr
ٵcPUI9$m* #(xY!
= BBdX`3Ą+oOF%W^`b!"c.Eg`tbIx-dB.YPネeN\:
XA3iI_d?VR/ E_{wGy(,Bui
R>z.?fJOI ٦Nj?qIX3
"\G9ɳz2Y *S ]V0I M<dbc?IoRf`'?7//#^ewo{RaGIC0.JU-dQa*UNhD:x\hH#b'A 9Z}[A9fÇvp9jk~)o/$,VnF82moB땑'^n(m@1Sk6Ԭܐ_ȈYr~f&.a<\|9h"gwʱVieouA崁cRWM';
K'68
XvU#JCP21˪Me'|smd6Ҭ^= Wl(lKR.,I?}e\v3c9myXMWE@PB_MMFI60~
SPvZ|vlC+[,k
HF
0LZeFDݿE8N8iZSA?vɑo8O/I'_xKƛx)砨[tu4ɶss-QSN9
-DW(.q,ޛ_XO.(dQO_nƸ$++*
DPt;@9GKBĜY{{q"kChaAP'N/.}K:3o,eq/ +XD]8+s?Jcvmw+H7ࠞQ$âyңKyXࢴč({l~;&RY9q
B]ZХc5)H%//O-Z$SL,뭷~\qg aYe{c|p/Km\oia]9QZ2<˼zlG;'l1>uF[;NAH!,O|{~]-ī?y31wǬ-DOЎEUf3qbI
IGeDb'aJjxuU~J~tI*u2`A277ן\ׇwgda}[iW " BɑQRoac%a7eFwljv˫7]$+N4.\{iEb^8EV7xvlQ|A$%*KE
ـGYeEEVSX1\\}K?c[FK-;u.1Wg#75z{! _HhX+Wn<Jh; \XP?4ϼȚ>jCɋ"w0=\5cuy6Y,aRG Q^+WUE@eK ֆ
_fR *Y 7JvnYP%TҹIH>Xh<3Y7n/FݝK~;RʛVQqG#(knDꎛc8̯b͒WՊSzs;E7-6np[Ś,4E5 q!q]w4qFurѭyr,a6{rx/:* e)NA<REM' A}ӛ~JÎC1} ;O%;]}xWhbԫKp=cwyGN1bqBDAݱeL. izPH&d]t0AZ}і9_uՌ9
Fk Xq&+23m|9mƂ']?}6Mn7,10>q\7=/3. DdiSO==deH b?E`joZbF}%%
GyDWX%{"ŰIWLD{҉Bɱ7~f>zU9^~y!2~S79}BX2yc6pqc1FWm)[w~Mޖ}yg&9^K-Rf}QXl߸;yLY}|)ibܺye!57mo^3mjh0jw0dԭS˩
gbL#)kwo!ḙR$ڒ6_ |N1T֪\{.Yi/KTh⯾Ɔ8Zw0ۣ
%+M3ʉM K>G`˹Dd`\WX_]YqU8"(cC 99Ou^"gsfYSZgIf̈-1R9=%apP'H 5堈b6qjr$XtkOrr/W}*U"[6AQi(ZnfI#9!>PjhXC`KVKDQ(r|M}W A&SN6,@Xn;gbmk|CT`tYcƌX'uB1p+: q+"BX,tܮdeA5YxwT(k'4wudkZ+QE+ /[i7-XEŲrZ>d}duvv>͏%&X'AijF"/ו(Ŧ_چ^b@gذaٴiӬ?E1au
^c㖯uq_o- _yg#'}XDד{ y=,3P{MLVL=Xb]u'GώoABP ~wxԹs뮋QG<mdAejSZ69XÖgǎFxlfuNʆݔ/s/?*[8YP"$(ןV/DVx<T!~o\|{'TDz'"ng&FvSvrq)
zzZOT}]2Q3ˮA}w&&S]i{H9Z42cȞZj_p8m;aD|+鉹ker6.䘍S'rf9ϟn|smUⰖgȜ?ee9~ϏVMITdȼg,!dfC\Zɦ=o^[ZS^A^rۧuĩjb9jqQ);{?H̼ZQAaM)Eng^=gyX+bȃo͉E)"b i cZe6.TZ3P$xqMٲ
aEPEQ}5cO8(w{G;Hː6C=|rcJhFcWn/7ZH@@
l5P.sc_O&0/;tNO|"k9CAcJر4 kXek\[<cr!O<
@|&ņ\D>+O{B\y ppuq_\%W3<xuO.&4
~Sr3z0ҥK<`-$wq~`{H[*?_סm+i۪fJݥ[q>9l:E*[EC+Xknȑ2fk<yސ[H/9V!a:
:˦<HEh]ҧGkɔJ7l"ϖ"Cʠ~ryG;Moz"XZp$,';XIaAu;}*.7X[aa裏,~},c+~W*Wo7|Tʇ@'4H0'2wXaB2.l5u3o[@
s`01gɱkMȽs<#ܾHz~Fe[, sC$-XB2
s
=>\!0sr,X+SߑPiy﵌:w[vqg lޱKB>b1:)!Ȼl[!ϲ%X`m()5#>x!/WAx{ɰҔ;Or\k
rF^) `;,as!qɖ]b 6ַ7%`SeI(bBk!*!⦝yLJ. ߬G/bGGY6*VޟP\1sKƽڭE2evM}A!]Y&<C^7_뎔6n6\nAՖIʛ;1*1mE@Pځ@N\K@lkHҠNYعڢdb*CZf21Ӣ ">Զ[ܧ=*csfg˿c#/{9Ȏ#ܪ=7G.z7mI{ߓ#iwSlX;tlo >jv˓k.=3a {eYh%.'##(xu~qJ|
|7bقP?1$qnP<j3],[kצ\sYf!hlGtt()8Qs$J]{F(멓U@SoY*Ɉgp&X ~x}
.nyto[n9^Or<ur1˳_|["ufvXldY-r$zk4kƣr$B?o\m;6H`}w+ zÇw?k'̌ǩZY'zvki)MU vg!mޛ'hJq{Ƙ4aF<evmLEN=T[?c7EưH,b8 @ IDATt?x(W|M_퉨0Vk %pbZ9iб̢n=V`EB2 0͛71
d/`C)t9YYC=w_fȝ:ujjP8o?hoʾc-W6{lm<<7 Ey:H1j`ƝWh+uREWf01\AeUo݊}aX\`sqR%JX! -. #Ȗ9kt^
SP&:BXra a&FU#I#YYlBqK7Q᷿ƦW*9ސ\ӖwIcEXJDpqۡSE@:d3.w6ڙG+34n6$nY,*,[g)ćx\zs2PiZ?wmɝN솥1ee ]}|ciԠL]3~MF e䪋N7ʰREypOu.+2A22ChABjB_}4"xv >h].JT֞N]c,aQO|p`297ް1UxqO>H~Wxɻ>qs ڑw~~"K/f\^Cĝ4is=!Q{ #6TWc$K&|<Ef6B
פ+V˦-dä\MElݡ^kO2G%NЌ37MTcCXzr½baٽ{wA,|샌 e?r! ғtHCfW 1ݳ0WՃٻf;餓]2XQ'n+L<f9<//ώAO璒%s϶dTXksz!Rt0@.Xg/M7xV@۷Oh@`bWa qƕI'ɘ3u
PɉMXcF0)2~a z V hi%|h? "61/ aUy AeۢڳȐ!=uVbyʤ<U&AА^jk!{ݟ6>Ay*3/#m`
1nZeM[Ueo4y#m̥?bEd1#?@"ٳtR"̺3WaB\yI(Z0\SWL\'_O~y9A`0ǣȾÐq*"(oJ0o+KDؽú~k 9(չp]Jp%g嶕|rp\)/;ON|યCV{8\w2m_xR&&D=sY'Bd>ζVHy'LMW^pyEeve/;36taݚtܝ>)@`W_?nl#j $}r:z[oc}uGz,܅HD⏅m]9{(P !Do_9}q[>pنލ8@ΪKh|_>"6E=:[);+Ӻlnc͚3Oy=9iPݽ^e5G"wa-ڴic!_^t'z\W_}U?~{ud@HT|0&rg]ޚ?/-Y2kKΐ~tz|,[ZƜcd5JW6$\|rcM9¨0 0
yHNʌIA;.DTY^z%R>=va1P^f_|qk_FV#OfpM- 8$Ee
AM駟gQ7/!
\ j4X6#^u\!+QFE=DeXF_O 0S
09ꨣvU4b*Wrw
(Ki;
iq{2kT0a[j2&אpsk;}~k֩e[4y?}jUE텙r]cKW3]b@a\i!bD21ʝ̒:4ƒC4Ka<gY?[ym2W}RovQ-
rg>Y~"("P-(Uh-$X5ilf,s,X7-۶X5S]ƑZƻ%䉨>H쎶}hn]e]kJKͅo7<#;tB`nѣɦo/BΉJP:=?M~cҩS'6;UW]e߳ e6~I@
%TQ3%&O!V9>V;c(T?!`nWU(HT))XQYeDbIe]~2XDNA~0rk71ޛhtPխ6q23Ӎ$c&YdAf2!:k%V?v=}.6Dޛ5 })//Ͽ+7 Yq?Af9WoMԜZ"Iƍ-#NZ/a?w,+H(,П<yD53^g3dXA~HRzq,Fx.]KDTPG`։7F+W{/(LX]VrcB~`
2 yc6jX7pC틉 9ĚhL!.\t4= .L ڊd(هl?ua*9&
XG\3caVai7][қwo
juPZaHD'#ۃozxIA C[4F{ܝ}b'KyRr"O}]@{+
ar+IrzǦ=3o@[ilbAm pꓓ)|.漱*?])BBӡYcK7-}H((ê-*tr/p}ek 1n:@Yfl,UXTNSETB}m5we{DۨE@PjEdMiXYhdT]Ym'}sI#TCl%C1G)Oʟ%>On]j7v[XRh%#O3- lw;\VٗKTڄK7{.dzY:bĈ1VI(0jeWXr/8W,EayF[(Qc{ӆ(L ׀uɒ%AYۿ9s}zhTCn"XLG!?S
S>t"Ǐ1Q
"bs>2K{}iߦwHe,2|n {v͓A閄,b]w)X>q\<aV-,wzcC"OY`uxByWī=t6: |%=tR9s̓1qu_ǽS>N vR?q{X/}g1Cjy䑱aӌu8c(AJoy5Ok/m_(rN81/0DA&
nċJDb|U8lb-
a<8)@85777!\2l2vnx`5Dɮߜ~Bǰ '}%!v4Cܷ<;Y=Z"W0DNXO+yu[EP3Zo#ϘuNsL4#Xo3r2u\ֽq-hoj͔a,mlC(3M.'L<!pb9''`s`5qrn\2gc@Qw0Z4+U܇&-:1uY 1c?}P{7fQT=Ok6uy26A*n_Q[
`w("*eSz
@T4̵%Ҩ^@h}z&gMF9ӉRN#vG Bӻ.kV%7/g
4H0$mZ_ERI?r*y{?o%([nEN893"M'CFLG2W: *IvJo
أw1lP{o^Qnb)8ecw\zv%?CυK%'$( t~4./
X(PG2|XAxI(Q.B.ިkG^}5P<]@ǝEWޓ3N:ZzthbG?'\dgXEݻwh[e#s}Btg}54n){!Ae XO}$dd2nǒn%rPDPr+Ju֣Au
Y*R&x,p3G%W0WȏE,ORqgM-<yQyyyj
.hxpY:>àxO$6'K$s^fΜHN*דxˤ/Vs
sUhauT*-{= WM>9Qda"@ZLyݣIiRkrE!r.Wl{:)
r,Ciێ`S/l3O;2
)a(|؏|s>
iB!3_G 89
1/GkުkK6ƀ5HɜU}m2Xȹ8HgsJKӯpY> 17}[FHSd_3_ҫT~>l7Y/T$\KQ}KPjy4KVbN&vSj\Zd4S#CDHidǑ yX%>hK@.3eerD#{@5h.'`O[d2y6ԫ[:`ށ?مA, f* =X|Yт}+@$@wmj'XO
88묳l1cXj_*X bpҤIy`Gyz9qmǣ ;"qq&ta!(NB_QJW R~F.p焘(w?%PJLDPi(!P>V_a cѣ= }MYSwFuӏ/IBqfLgyz7%Fi(<</6G?}ǯ?EO
3x3DQ3"&[~'!C؟<qGXHܚ<hf4٧8L[[3֞'t
a2s>~5W³)?|2vبCwuWi!t|u0ָr_dÎ<!Q,>JfA
+X>_U5g'$< y3xxu:#V;0~ko]mLy&#Ą1l. ֚ _ho.AAi:o0|D2ϊwib`p.=RLVx2Wys5&wqR%0QfIEJP]k~H",x,&,ǵˎ;;X+!{`I(}m +'9w,z!-^Ȣ}VA@Y_\!TRiieY4T7YX:)920LC-C8eDA:-]W`-hj.ҞJߚB~!gu="D.$8\rǙIۙgUiq}9omH|jo2.0pAA]-
M[ViukŊ"(5\5Ko&6eo˲^76T㲯};MLDYF3iXTWTR$] [*N%[#s?'5;Ho]R W^Ź/Qeٖg_&awc5
#ҔO;'P.K%pyy>|-
J.ʣ;cd=}e=1(ı.eJG
uGBGE>(krE(
Z${m QXQsWHᇣ_@A&tX+[. &Xdq-E|do
y0ᣯ$}9~~?̒O0d˶Smk &;.q}'㎳w\L"X+=r~r뭷t
BxE6,p@|BHM20J-ZzxVmH,VKoMrq2j[vyq}zql
(~\{\b^w͚RZO?_˗/^osd*ú2 qu<myu(mel=AIFɳ;~d yjYab̤?N:9cWd2(>,M uryvgPx%+0`:'f[5B:%/7F u\6Y:t=,ُ.nߛAD-Q2 @=npƃDU@YkFްtWO9+W7zsbjo^nMӆTY^P,ˡ7v+ẼVGbSCܪfZ˿(CRguʑDs0m}ߜ.$z>. ?hǏ SK(C]bu6 YfᏦ.F*xeP㜫x-9@j`Mcsw{rr!RQ&>a<oW8vI6ezٶǯ8TZx\qKkYuÉ=傡y
ȨkFvC7de(QAWBE@P!PǼ4PL쨕VȦh6KھZ2iՉuQ|PG6/[l=X@-ߺ\&.h\JpnS6+[Xn۾.=Oʌ;w:Ldk%VS˻<¢SG]7)(k;(4z/L{5kOcV^aӖm2)l9?;Ə4Yb?Pnn|)(Y@x%\b]=C`rX"=>~|QF^!^w}ԇbٝ6AhYH:puq7Ve|ݸqB|07.Ou^~,_F>HX9!4EӓFӺĥq,0[h۶40+/r
^awY@躐0kLw_
d@-~
裏P;~ *_]Ӛ4qho| _h.|ibIyxz3_ƽ|5ctsqҦyNxmcI$Sݛ EAz_e+(_mfcwfg2c=ZI~sO$uP5!Φۓ|6J~>7(ѫ0!FGbcV1X$:BHo9E'`>b,){={f}: ps={la9n/?~3,\ܐ| &&Lּ7}vr 3o0~&4`KKcP? tǡȠ 酩3PpaZX+tK5fGB2F4^6KEv6R!i-O4, ϿX+gRagxa!&*ܾt0qo!3AyWti#cIZTG6\J,O&~aUY& v}CV,5v7Ub"r-.$/DӸ_
&%=QTz잳Y,[Mc7ab=x kTcO"`_40bBi!|k79j_Wf \gw^+|~{yEz~e}Xo61~4ȳ;"W5EXeKD^xy9m/qT)[)"T2|=BfZUx%V_h $OU+|2=3sxT<). *,(KotSx '_2.qv/~rRubҠ3H10BkyߏuN4_1IaRok.=K>\/]!z{N9?,h#'s|9}QΓ"L7:yOw ;K/yGis@oĂD躸ָKD([)tbY(g0]zӰ*Ω(A?2N ._d'ۮf|+Q'Ȩ¡O6OLL}G\%z|u/0b\dp.~a} OX!hG1ZђM6EǾzWd<䀶-"gol, y1Cd![lt0tEѱ&HvzMΕ1"C}>\an3rlj^Xn_ϰsC洴(^_J:;ZLgaB
tSU囇 d'daNJU77aM~@>)<aҽ~+xաne]TDS/ \p[tS2Bᓊ,2 Ւ,j44N/__'A䵄"wx
L00uz-Ĉj ^)T]Ts0ɐK~ڐoXa]ormL*o^bN7.<m,C{,oU1x:Lb<$Tu"(@@xW,۶D4
$S%M,yre$N]:ݿ'YxPT)n<@"W<[ؗߑsCʪ57ޗ۲:R-oOL~?!=Rڷke`R^Iryt%X_wo8<%uQRT0çu3{_K7<7Ǹ
dō[fM}3$3Pb%'{d }ⰿQn+gtW>̔?&g;K#CvlZ8h9t@o`,C|Ku<xND*#"Fq<CT=jU )"/
OLܬ,nզc5.7Ӭ.ebƽd\݅2CPM_ޒ<~,btxeg>]($AR~*&g ;YQ(BU_<cs-CʹoV0M8ћw+3("@lRp)h֩j.B=ilj.Z4ojGz,;wܦrȆ@zBsұC$q#]}{u9J ފꏘAUFWN÷!*2
RXǠ`Wp}Xɐ۴ₕ=qHmc?ܾPSLzeE@P,H@$#.$Wsrh'/>%|fzBUc J܂(z]~icQUHeZ"(@D ˅.,`I+&YBv!DH$ȤMٔIFҹC;SҢi,wjo}J%"Ť[s@DNlRQjIWSE0qlݷwF7MV.\o+*JB|*"("(@G)d"ݟFݤzm"("jnZJP@OU;6)
(8oR1V*"("("("(%R.pc
E"("P@:O]MӌyI̊"("("("(5%b\ӒٵkW{wŸ*...S? [EPE@؟@$&KNpJoPR
jK~oܴeo^4="("("("(U%b\LKdǎQGeJǰaäs&` tP;vLͦ("T.M5r+"("("("HqY b٭[9ʿiӦGEPE@PE@PE@PE@PE@P@ݚvBz>"("("("("("(U%uV("("("("("("PP"]R=!E@PE@PE@PE@PE@PE@PJDU렭PE@PE@PE@PE@PEwR]>.UTD@DP@ذb/X}ٰc/`EA
6l
*ҥ^{[{7L&'r9g @(]Έ 6qM; @ @RlպUU4'? RJٺuRc{!&௯u*?"-E ~H$;]|F-͋-}8> @ BB`[߰fK_SWByɒ%ɊX|kNŗ?$Ķ-A ~G$;]|F-!jK_@ @hVk隵k
IifV]klZjͳgNVm̙3]Nv*!%m c>'QE3ʦ?oi^Q[
p|@ @ DUںl՚Uh
Iif]ÕkVݵMGYU\.\h-]T}l*]~ݤkk}sȦ6ҟ=N(:ג31+Ģ+6dHkႍ#6lM5@ @ 2qM[2" tR]`ҤI!n>5jd?k\Zi?LϞDz?Y&W]국dɒ~dt@ @ ~5g8>4'҉:yܹsmŊDEE*D$:i~&K'*QTX9 G??{Px-M ?s3_93 @ @ @ H@BsD" @ @ @ @ʜ{@ @ @ A !*
H @ @ @ Ȝ BT @ @ @
Qi@ @ @ @ @2g @ @ @ i@JE @ @ @ 2'93 @ @ @ H BT(@ @ @ 9̙ @ @ @ @ҀD@ @ @ DeΌ= @ @ @ $@ @ @ dN !*sf@ @ @ 4 Q @ @ @ sQ3c@ @ @ 4 D" @ @ @ @ʜ{@ @ @ A !*
H @ @ @ Ȝ@wcᒕX@ @ @ P, U,/;'
@ @ @ 6=|Vo-G @ @ @ bDDeƋ @ @ @ i@J @ @ @ 2#/JC @ @ I !*MP @ @ @ Ȍ BTf(
@ @ @ &4AQ @ @ @ 3Q4 @ @ @ @E1@ @ @ DeƋ @ @ @ i@J @ @ @ 2#/JC @ @ I !*MP @ @ @ Ȍ BTf(
@ @ @ &4AQ @ @ @ 3Q4 @ @ @ @E1@ @ @ DeƋ @ @ @ i@J @ @ @ 2#/JC @ @ I !*MP @ @ @ Ȍ BTf(
@ @ @ &4AQ @ @ @ 3Q4 @ @ @ @E1@ @ @ DeƋ @ @ @ i@J @ @ @ vݺ-q|9&BT`@ @ @ /\l4V^o6d@ @ @ (_dkM1$`y#dvխFUV!j@ @ @ M`Y+oٚ5NR:Fl,2_bC}j+V^?-,]K[! @ @ @ ȜDeCG|iUЪVL3x͚=/MVZGYmμxYsً
l
{칁VbEks>}~h @ @ @ &Mf=_D(U#H5VCKunC6ݏްSgIM`z ;
.VXe&N_]?YOA @ @ ߝ5F~X.[vXeW";~n{_wG|aV;hncr6sc84`oʕm[i@&"@_@ @ @ ȞEKl܄IH0p$IBRLu~/0h"O"Ԇ
9˕)]ڎl?8Qm'~h @ @ @ [͚4O>:x!1闆ʕ2>Ѿ#>W&GYU1k=w9\"T2e#<jըgHjh! @ @ @ +˗j+LJ/\l}uV!(X^<^
EFRF +r2o{6b[>g(Tҥ!hYP:["r_s@ @ @ @$I2 I$,I`JeP}yoGc֯ϱD3N8ЊP:!"r\V>@ @ @ QǴ;*RO0fϝ$%F.2Jly Tin74rK.*bkհ]NeD)+g=}U뱶vݺ8J,i:B/|2Qa,C @ @ ( BQ>f8&aĦ=*UȲ+m_l5ۅie CD1R$O/FuDA4TB/BIX@ @ @ ($I P$($0Ihhen` B}͏"iF1#n=",@ @ @ ج$F={^:D#"Veo]\;+ltygk.V4C9s_Qcڵksh;ìFrm++J,ZbC6_L
6̦ @ @ @`XnvڴG\ί>mYzMduלoM4RHiv]=m܄IsN(rJ`N#m*v/0זjk+%ߚlOA @ @ Ph H0p$IBRIx E'u.[&)8/BDK @ @ bE@bT]7wu<wQ"UDBEKw>a|?!2IGٹwj[UE*C @ @ B@vjPj۱iWGJϖv[>X-^j}?~];Y:o*/u"D@# @ @ @ [@%lmj٣ݯLKGV{7'_kn,([t_>ӎ?.:+[LmEiBTQIev뭷رcJo˭G'aڵv[mժU ˱5۷wypM~"GE @ IDAT={GyĖ-[ɏ'
6?n?YWX;Ν[XOvg@@\p}ݑ?j3}3Xox䥙!?
8f̘.9{%sT@ @ EM%Q,B=k&!jޟobD(Oސwt<ut+WhP:ҹΞEʕ+m 6o<k&9uTVZ Y}&М9sNX
Bm/^:7eQFիsVR\RcN֪U9f6̙3mٙ쒰lRl]'}&@q9 ٳ:/\UfL;쐧} fŊֶm[PBRAJҥs<y=ڴi-,Yc]˕+YLm
d5:uDI+Æ
s9'YQA @ (40qyA)Skqm[fz0^n?ﳇoҶQ-ǶL>,XĺP/J.e֮MEsNA=͢}b&MJu$ I:~9?իgrlEL!9֬YcAVlPxHtR[]Z-6 ]ae ~뭷:=DŽ?>ϙ*UE]QA$~ݺu3;'e䀿+6%]Enn F AGqYPQ"O6l_|1)믿$k`}?D}4}qTVQh I+Xh~tDdڴinG}dtPSqƑH^`{vm?7o<+-q@ @ @"C(F)Sڥ[edG"Եw<n~1%B SbBT!z@(FkݻwOY[n'e~i,U"f29}E^KOO?mkT|~Ko@Ŋ]
TQ"R*RᬳrќKd(%p{5kc{ڵs8!S_4;q!$|YEEVwH{ëܲ9.$n[5k:q-\/%aQ{:EDO}멧Jx%>`siӦN~+Ww96dҥVjUoĉ^eGof7 F"P2e'pu7.HP1o;FO7*;Q}-7xcxU䲸ըQ#r[+5pc1)~? S2 USi0@ @ vݝ=iM (k2ߥRu2z6g6,c/xǖi&1ꊛ{n&i`Gxs>g|EgFglɅ=w= b8[,g
KkR
M3ީTx~|8)رs;{~r$Kdw~ܪC=ԥcUhDWr:l
S?C/i~t{ ?bo\Jdg{R4%;&
=iT[KRT]{k.&9տ٠xp#{wͩmZ>zo
vm71]Qz7 g#VrG-z%mͻ薨>oZ,oB}]Wt}{\iPUFCosLCʫ?T^2'_~q&TVGwjPy ̋Zo*$[ϤC9lMPk.*:-٩S''Le?e! @ $#nz۟vشGF-mmٯAV~;+YWA[yG;_EhoOȦۃsj)ţ3Xo5G=Pb @SS֓k"!*qv5wXݥ7w]cw^9t;v}w+#Lˉ_u#5ZFȔOF+OfHh/^HhRiLQGrϼb8"=:_?d?놋R5tЌӌJer!'&s1ɪ| FkEi`ZU9g>JQv9Wj1z-G r@w&{"SU(mZAJks$fejrh;.`U4RoMPߧ8^DdnT4OLL00 ]uԳ2/D"pԇwuWSĜ7?Ygj6풨~yx|DT3ϸrTWPԣ>Ĩtl~ @ @ uU8(~Q$h61\DT!~<n
)5}gHbvd#ˊG,K!O}=DP6b{«.ˁ(R4o7o^BGģxgRzk.z J
<ͥ2;p˗^z>@P:/=1.[pal.
9SSQ2#՟JPNNC?rkT~ij_'&53GXt֔BNL*5WD"K$$*^}J)9xo喘@g*AUg.]\4d֩3<33[KH[+o4@mH$HS?X`TX\߶9ΠӫO0ϒu
D6/
7ܐ+c2_W^qUI\ELېβ}'-U^.̒%KFfE߅/wi ;RsW{~ۉ3+UD @ @oAΝeʗCon_rf6}=o<ɗڊr&1]q{v* += 2<x͙ G$F|vg5Ræh{^+sB]~rU^Vd=,D')Ři61F}QInE
(b t%$,I%\}ny+r(Dsho͛ W#՞ύVzZ˖-]Y$' \(S" [ioݺM.b7ߌ{*'JQȤ+a*!T}3t]rƩ0pleXޘK4">,]n}>tZ^vܑ[Zճ4F
aR_t)gDp4hP/282;Ylc*<ZA>Ҷw>0UUoP}=H]dr۫gJ!JJ/?Dˋ-r7x|M;ӝNPQzn*JNb"jkNJϪ1?MjIo3_\ ~FnJO>35/j? O_~c+~[or&od}Y! @ Xff恧٬7ϚBetʕ )AKϴٰ5vȩkZ#O#Vqϧ {GZ?:~`?cFP[Udv]zIAQy9>~de5{&*'ɹ*Qx9p$xZUFmg}v,
gas"Ou|_ӎ;n1,˨?ގKL96֦>Ega6YW\ƍ]Jѥ<?+UFEEUy'~>JEQX4~K7ntAe}
.Zbg͵fK&elmђ
DDQlMT
G_hٗ1zF3U%2OUW%˶y=>gNd0Q˽1ovVfu n͉T;w6}J d)۴u]mTP[%zyӳ>REu=62eJ,"7-뻨0"5FBlժUY`((;~?z++jXu*W\U5 @ $$W*aJ,%KB0Q'u^ڔ/^:owN$FM6zR
wtVvY{JXB#/u"\l\V&A!s9MkJ?I_e^{)rndcJa#>s#ͩ "aR994y_{Nr .viǘ&2
_G5dQX7H-5PTa愨:3|pJ
&SHT.OԲQ?\Ԍڡ9ƎIOEKnEmO"GacPӎk'!Jj]sor-Sԧp9>zWcG?s;s*TpI̎oC.ٰiL\J/i9餓"h; (e9śtZ|:^}sx8kܰz\HT;64s.84G}{6|s*a+Jpx~p'|RV\I
ĖOt+Zo^t<E`'wU>}\Ooc^|)k6 ^vaPµRE8c4oW; @ VcO0fEO??CnNٜ|3Sx#HI/ߖ,?AdTe˕PbT^/yw៍ve/tB`gՉoOdo\f"#pNM T?,^n)'frTL(;PyI4O'0/5h9cW-Ⱦ>ͱre9A̯=76&rzыSNPB396HA SG4Mʤ$|9NKi$tJ<hsEasntls=)
[gILeߣGdEDϔLM>Qm6c/O?R)
Pg/▣nC=5W_m9nԬY:s3ϵE+VD
`Q`FJm:PrAJGҪ
3|0]gEK܋@nwO>"^}OѢhtL)+,P}?U$Dɚ4iCDr+SQTJVSNɵ"eN+^fbJu4S>ObN;۵^z]7x*| @ hߛ6wŗUe;CIGZ`ʐT&3sbGآKs"Kj͕\˧ G|eew7mZ3O]R;C;0DZb2,Aa:V9D4:Uc9& -Ϟ=́QL,9s M;G*?N;4PyLv_tEn>:H4pL;vԴc?0䄗P<#JW>!R4u7J^z9GcTˊz H hDA$L?k̶U}NGQu?-RϺy',Y]~9Yڦ($E(m"1vm@%F^:H>A4L}_!|+J qJEɒ)}=Mm~\9\~U}Y=٠ yind&v2ӽn_yr>?kyA0^)-&tHWЯסKs,"H'ԩ
<8}pU%j㎱8&Y +;ߓ¦z$~
MchKD&PqRB<c}%p{.~ċJ)b '&L4ٔV@ @ E<4 Vd( _dI:kCsQQH:1:<A*Z'rӑCΉxt0FFˇGj恘3gsk瑣TQ
r!*i=~$J}4ũjmڴ:;P)D(j+E9%G#oh(E٘>sTJGxWJ*={4/& m)!6M&Oio}0Ҿa}VJcLse$D)/*:B$/$}<~sm_i~iJǒ_ z6Ԧr{=WE+t^a1_EԷئJ7?7QZdQ_VpͧDeL?u6\<nWYTiru9;#MP:b` :Y*H<>ې ԫ2E^W>J ᔚ^xt^oԩWzwO&Խ@Ŵirե{JrVPoYXhp{$
y})=BT2l @ &1՞zi- L˜I۷jĨ2h4=SEIRÚ0~s\*w{#v_Ͻ 4wd:"OW$Gʧ+Ɂw_AJ_iћaMqW)}惒Ot#/IITzQI+Tkr J";(>*Fߋ/؎?x7ZfX_N`9O@3Mv7:Aj=4%ҥK@6#aA}YT{}TW_"`R_]U(&j
>&mm]N9ڦ9y
=wP;5UtowJ_:f'\TT?H=|N1qͷ$Lh5ͳ#Vg[rg}~]N:ztj<G[ ~AMڶm뢫&Qhĉn`I:;|J %>Sn@[h)}F{O>qە0|^Q%Zw-fSHx[X{EQZjQuY0z_ޯ{c˲@ O.eMPjը:m<SAZ?Q5ڠ&uxkQ_zdS9MOno'B),7LZoR)q#VN2[],y꼨4VBQ_cǎQ
Jao^{7ɰhlR)%mfݻww#w%Y (֜Q_Φy4j)tw}rFJPrfc
{-5U_ΝhLr<*1*Tus)F<)lN1ӵїFfe#X/}%ykl%dEbwzq?IRd29͛DLۻvTTڜH))/Yse?)a:>\'o4Ju9t%@i2}G+ɧ{שeEլ=_X~ht}i~_9L$ G)Še.'y.n-|2@
_"وRvM}|af2ɞJҵ=̒6 @ d7+_"PHВŋQmlڠ6ӿSn<y!9Ĩ
wf藍[`&"DK*Ec])}+m)mδ|lGw
Z߾}j9NꪘKS.!K1GF)+_X;wnl>Z@ilyw<Ehds:&ǖRaFH Hr?9%tPd 9NO9Oo&\HQLP\kwP{/li F>O]xl}vmk;Nҁ#<SԛJagTR?GիLEg&':9.9L.INO*2ELEetVDI*5Y;崖/ީ}:]Ɏ_ܶWIz͚4:`eS<+5p_T$&VZD۵^}UOtHR"$BRP!E50E{Us ~%-_萱E=KG8JG}HB͏)Nk
o$+
LT
j_` @ RyN'hڵjX.'"EI:./
6ч.;'89)]=h_w^=?4}3}Y`>BTF9*-qԉGF;ͨf>`ђ3f=9%Z'gF2ĉGJ֫W/'(h"N;4-LBrԨQ#6T@h;%RŏVj,EVrpa$i$uZ4GQgxEO$Fw9R}^T}U瓏v?>F7f=7c\̷7,;g]u4ڠH'{7MN_1mw9^GMX*U{#ϕTe,m"kٲ$
HRﮧ7dw+/bWc5-^j?γ1]~o~fu.bvXtz<5O㿃}]-(?K׀ UꔠM&"rxS5(Wt$/*uoiJa
4VES#eݯzxKEkO @ 䕀Aնl-ww/HjhIv1mζίվ{Xre}/
8hQ,nfiA
<OMj3KdneD:&З_~Z}+Ui&=z{?Jdg}^zȀ:ש;}FR(W*͢RID*| J'1r9vS!"^Pӈz?/D&PwAe4k@p^p.VϪk̳O?d?kbi~4ĺ/pueJ%؋<nE>Ѽ,?Sc縓j%գoNf7EY\,NZ䢞D95 aĈn?
PćO4`x,G@EۻQNo)= vɖ,]nO2hLu|~.kܸqs6J6"SJ=E-I7J~DC"AIBR[u*+t(աD* m$Qt&>TD=3yn;0 @ v(7[%t5
2ԮUݯ.w>{j7\ebN.)BTz
d)9=hTdJuQrVrkҗiNYhD(ɇD.rda%KJMVi䠼:}YfRG rjT{9vM} W={tR*mRa RGkڶ[p!ƹK^8\̛«VN͛=}!J;fIsIGJ#*k"(p%b=a')"Fe*`͞=ET(h"ӜM~~ˏ<])N[QtN;åTL"i@Q?f[ ɏ>EJT_4Bշ'J %St?{AX5HEz}Yi6l袻^x')_UN>NSO=5\$en4j >=z0v! @ خsohj
2MC_;iE};BT>]_&eUF2T<LlΔKhTMS9m43trlHJfr(3ΰ~|s\&ۏm'Gys~}5\*#nw6۸tDPI%C_#㝑jEFF#B)^`ևӯKXupK\SRE+Y>*z,rxgEVEȕp[oNs#t0RĨѱcK/JeOJ¦:n'T)SN oα糞UӝIѯ;w{.VڭǷ'VrZ/"fϿE.[n VǴ庨94%ꥈBFHo+/Ihb\4d"krm.INR ]=On7 LbO|[YeX)%Y9DR// "|T"0uIL @ HҔ4x8BT>]k^pRT߁*hXwi29D29)4v4P5IQW^qyСBLi9S:x&ZhDVBDX_ O8'*u]FsITT"@`_sEw#XwF)GwU?,95GGTa*/l䩶S,D~V^.;Oz]Rէ( ԏ4ORI[=+\pdQGe{lq.ЪW)$ED9(9%v}w(:WDh"7D>ݻw,h?E
\$)ՙ2U߰?Z0|1GE]l+S_$@Vi%ėÇ;A_QLzIѳXX>P>fUcl}玞|pZMW5!{S]i^& OJ'XbJLLg)h"o50a$&ޔoԩcD>sd @ l"ԫ[(|z2dJN(UV9ܺ`vOǢ 5Fjt7#YJ5zذa6fk&LWDAc T3,r+ILx. 4PFK իm۶ֱc\dNϬGT+`>~QTr[PCϻ[5nX/:OV='"爞_&1JUD]*ajȑ1GC=ݻ;G7|5k5RF|>s>b
W~؉1QVeՠAq糢S߶wy'I\UyuzP]>ݶU~TXSL6h#ju͓MDVRD:X'ѻQ}R"Mo^y_{!ʒoqT??P#I"[, AQ@dDNU4xdz8qb!:x @ @`|{B߯LVEsA< |