Skywalking-13: skywalking module loading mechanism

Switch 2021-10-14 05:38:50

Module loading mechanism

Basic overview

Module yes Skywalking stay OAP Provides a mechanism for managing functional features . adopt Module Mechanism , Modules can be easily defined , And can provide a variety of implementations , Select any implementation in the configuration file .

For module related configuration files, please refer to :Backend setupConfiguration Vocabulary

Class diagram

Skywalking Module management related functions in org.apache.skywalking.oap.server.library.module It's a bag .

Through the class diagram, we can understand Skywalking The module mechanism is roughly divided into the following modules :

  • The module configuration : ApplicationConfigurationModuleConfigurationProviderConfiguration

    • PS: Just corresponding application.yml  Three tier structure : modular -> Module implementation -> The configuration implemented by a module .
  • Module definition class : ModuleDefine
  • Module provides classes : ModuleProvider
  • service : Service
  • Management category : ModuleManager
  • Some auxiliary classes

    • ModuleDefineHolder : Interface to be implemented by module management class , Provides functions related to finding modules
    • ModuleProviderHolder : The module defines the interface that the class needs to implement , Provide the service class function of the module
    • ModuleServiceHolder : The module provides the interface that the class needs to implement , Provide registration service to realize 、 Get the function of the service object
    • ModuleConfig : Module configuration class , The module definition class will ProviderConfiguration It maps to ModuleConfig
    • ApplicationConfigLoaderApplicationConfiguration Auxiliary class , take application.yml Load the configuration file into memory , Set up selector Corresponding Provider Configuration information

file

Class diagram source file :Skywalking-Module.uml

The source code parsing

ModuleDefine

package org.apache.skywalking.oap.server.library.module;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.Properties;
import java.util.ServiceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Module definition
public abstract class ModuleDefine implements ModuleProviderHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(ModuleDefine.class);
// Module actual
private ModuleProvider loadedProvider = null;
private final String name;
public ModuleDefine(String name) {
this.name = name;
}
// Module name
public final String name() {
return name;
}
// The implementation class can define the service class provided by the module
public abstract Class[] services();
/**
* Run the prepare stage for the module, including finding all potential providers, and asking them to prepare.
*
* @param moduleManager of this module
* @param configuration of this module
* @throws ProviderNotFoundException when even don't find a single one providers.
*/
// Preparation stage , find configuration Configuration class corresponding to ModuleProvider object , Perform initialization operation
void prepare(
// Module management object
ModuleManager moduleManager,
// Module configuration class
ApplicationConfiguration.ModuleConfiguration configuration,
// The module provides the service loader of the class
ServiceLoader<ModuleProvider> moduleProviderLoader
) throws ProviderNotFoundException, ServiceNotProvidedException, ModuleConfigException, ModuleStartException {
// find configuration Configuration class corresponding to ModuleProvider object
for (ModuleProvider provider : moduleProviderLoader) {
if (!configuration.has(provider.name())) {
continue;
}
if (provider.module().equals(getClass())) {
if (loadedProvider == null) {
loadedProvider = provider;
loadedProvider.setManager(moduleManager);
loadedProvider.setModuleDefine(this);
} else {
throw new DuplicateProviderException(this.name() + " module has one " + loadedProvider.name() + "[" + loadedProvider.getClass().getName() + "] provider already, " + provider.name() + "[" + provider.getClass().getName() + "] is defined as 2nd provider.");
}
}
}
if (loadedProvider == null) {
throw new ProviderNotFoundException(this.name() + " module no provider found.");
}
// Copy the configuration file of the provided class to ModuleConfig object
LOGGER.info("Prepare the {} provider in {} module.", loadedProvider.name(), this.name());
try {
copyProperties(
loadedProvider.createConfigBeanIfAbsent(),
configuration.getProviderConfiguration(loadedProvider.name()),
this.name(),
loadedProvider.name()
);
} catch (IllegalAccessException e) {
throw new ModuleConfigException(this.name() + " module config transport to config bean failure.", e);
}
// The module provides the object to enter the preparation stage
loadedProvider.prepare();
}
// Use reflection to copy attributes
private void copyProperties(ModuleConfig dest, Properties src, String moduleName, String providerName) throws IllegalAccessException {
if (dest == null) {
return;
}
Enumeration<?> propertyNames = src.propertyNames();
while (propertyNames.hasMoreElements()) {
String propertyName = (String) propertyNames.nextElement();
Class<? extends ModuleConfig> destClass = dest.getClass();
try {
Field field = getDeclaredField(destClass, propertyName);
field.setAccessible(true);
field.set(dest, src.get(propertyName));
} catch (NoSuchFieldException e) {
LOGGER.warn(propertyName + " setting is not supported in " + providerName + " provider of " + moduleName + " module");
}
}
}
private Field getDeclaredField(Class<?> destClass, String fieldName) throws NoSuchFieldException {
if (destClass != null) {
Field[] fields = destClass.getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals(fieldName)) {
return field;
}
}
return getDeclaredField(destClass.getSuperclass(), fieldName);
}
throw new NoSuchFieldException();
}
// Get the corresponding module definition Provider object
@Override
public final ModuleProvider provider() throws DuplicateProviderException, ProviderNotFoundException {
if (loadedProvider == null) {
throw new ProviderNotFoundException("There is no module provider in " + this.name() + " module!");
}
return loadedProvider;
}
}

ModuleProviderHolder

package org.apache.skywalking.oap.server.library.module;
// The module provides a holding interface , Through this interface , You can get modules Provider The object corresponds to Service Holding interface , To get the module Provider Object corresponds to the service object
public interface ModuleProviderHolder {
// Get the object provided by the module
ModuleServiceHolder provider() throws DuplicateProviderException, ProviderNotFoundException;
}

ModuleProvider

package org.apache.skywalking.oap.server.library.module;
import java.util.HashMap;
import java.util.Map;
import lombok.Setter;
// Modules provide abstract classes , All module providing classes need to inherit the abstract class
// A module definition can configure multiple modules to provide classes , By means of application.yml Switch
public abstract class ModuleProvider implements ModuleServiceHolder {
// Module manager
@Setter
private ModuleManager manager;
// Module definition object
@Setter
private ModuleDefine moduleDefine;
// The module provides the corresponding service object map
private final Map<Class<? extends Service>, Service> services = new HashMap<>();
public ModuleProvider() {
}
protected final ModuleManager getManager() {
return manager;
}
// Get the implementation class of the service provider name, You need a subclass implementation
public abstract String name();
// Define the module definition class implemented by the module provider
public abstract Class<? extends ModuleDefine> module();
// Create a module definition configuration object
public abstract ModuleConfig createConfigBeanIfAbsent();
// Preparation stage ( Initialize things that have nothing to do with other modules )
public abstract void prepare() throws ServiceNotProvidedException, ModuleStartException;
// Start-up phase ( At this stage, modules can operate with each other )
public abstract void start() throws ServiceNotProvidedException, ModuleStartException;
// Notification stage after completion ( Execute after all modules are successfully started )
public abstract void notifyAfterCompleted() throws ServiceNotProvidedException, ModuleStartException;
// The module needs to rely on other module names
public abstract String[] requiredModules();
// Register the service implementation class
@Override
public final void registerServiceImplementation(Class<? extends Service> serviceType, Service service) throws ServiceNotProvidedException {
if (serviceType.isInstance(service)) {
this.services.put(serviceType, service);
} else {
throw new ServiceNotProvidedException(serviceType + " is not implemented by " + service);
}
}
// Ensure that all services are implemented
void requiredCheck(Class<? extends Service>[] requiredServices) throws ServiceNotProvidedException {
if (requiredServices == null)
return;
for (Class<? extends Service> service : requiredServices) {
if (!services.containsKey(service)) {
throw new ServiceNotProvidedException("Service:" + service.getName() + " not provided");
}
}
if (requiredServices.length != services.size()) {
throw new ServiceNotProvidedException("The " + this.name() + " provider in " + moduleDefine.name() + " moduleDefine provide more service implementations than ModuleDefine requirements.");
}
}
// Get the service implementation object
@Override
public @SuppressWarnings("unchecked")
<T extends Service> T getService(Class<T> serviceType) throws ServiceNotProvidedException {
Service serviceImpl = services.get(serviceType);
if (serviceImpl != null) {
return (T) serviceImpl;
}
throw new ServiceNotProvidedException("Service " + serviceType.getName() + " should not be provided, based on moduleDefine define.");
}
ModuleDefine getModule() {
return moduleDefine;
}
String getModuleName() {
return moduleDefine.name();
}
}

ModuleConfig

package org.apache.skywalking.oap.server.library.module;
// Module configuration class
public abstract class ModuleConfig {
}

ModuleServiceHolder

package org.apache.skywalking.oap.server.library.module;
// Module services hold interfaces
public interface ModuleServiceHolder {
// Register the service implementation object
void registerServiceImplementation(Class<? extends Service> serviceType, Service service) throws ServiceNotProvidedException;
// Get the service implementation object
<T extends Service> T getService(Class<T> serviceType) throws ServiceNotProvidedException;
}

Service

package org.apache.skywalking.oap.server.library.module;
// Service interface
public interface Service {
}

ModuleDefineHolder

package org.apache.skywalking.oap.server.library.module;
// The module definition holds the interface
public interface ModuleDefineHolder {
// Determine whether there is this module
boolean has(String moduleName);
// Get the module definition object through the module name
ModuleProviderHolder find(String moduleName) throws ModuleNotFoundRuntimeException;
}

ModuleManager

package org.apache.skywalking.oap.server.library.module;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.ServiceLoader;
// Module management , Managing the life cycle of a module
public class ModuleManager implements ModuleDefineHolder {
// Whether all modules have passed the preparation stage
private boolean isInPrepareStage = true;
// All loaded module definition objects map
private final Map<String, ModuleDefine> loadedModules = new HashMap<>();
// Initialize all configured modules
public void init(ApplicationConfiguration applicationConfiguration) throws ModuleNotFoundException, ProviderNotFoundException, ServiceNotProvidedException, CycleDependencyException, ModuleConfigException, ModuleStartException {
// Get the module name in the configuration class
String[] moduleNames = applicationConfiguration.moduleList();
// SPI Load all module definition objects
ServiceLoader<ModuleDefine> moduleServiceLoader = ServiceLoader.load(ModuleDefine.class);
// SPI Load all module provided objects
ServiceLoader<ModuleProvider> moduleProviderLoader = ServiceLoader.load(ModuleProvider.class);
// Modules defined in all configuration classes , Go through the preparation phase
LinkedList<String> moduleList = new LinkedList<>(Arrays.asList(moduleNames));
for (ModuleDefine module : moduleServiceLoader) {
for (String moduleName : moduleNames) {
if (moduleName.equals(module.name())) {
module.prepare(this, applicationConfiguration.getModuleConfiguration(moduleName), moduleProviderLoader);
loadedModules.put(moduleName, module);
moduleList.remove(moduleName);
}
}
}
// The preparation phase is over
isInPrepareStage = false;
if (moduleList.size() > 0) {
throw new ModuleNotFoundException(moduleList.toString() + " missing.");
}
// Provide... In the object according to the module requiredModules Method , Determine the initialization order of the module ( The dependent modules are loaded first )
BootstrapFlow bootstrapFlow = new BootstrapFlow(loadedModules);
// All modules enter the startup phase
bootstrapFlow.start(this);
// All modules enter the post completion notification stage
bootstrapFlow.notifyAfterCompleted();
}
// Determine whether there is this module
@Override
public boolean has(String moduleName) {
return loadedModules.get(moduleName) != null;
}
// Get the module definition object through the module name
@Override
public ModuleProviderHolder find(String moduleName) throws ModuleNotFoundRuntimeException {
assertPreparedStage();
ModuleDefine module = loadedModules.get(moduleName);
if (module != null)
return module;
throw new ModuleNotFoundRuntimeException(moduleName + " missing.");
}
// Whether the assertion is still in the preparation stage , If it's still in the preparation stage , Throw an exception
private void assertPreparedStage() {
if (isInPrepareStage) {
throw new AssertionError("Still in preparing stage.");
}
}
}

BootstrapFlow

package org.apache.skywalking.oap.server.library.module;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.skywalking.oap.server.library.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Provide... In the object according to the module requiredModules Method , Determine the initialization order of the module ( The dependent modules are loaded first )
class BootstrapFlow {
private static final Logger LOGGER = LoggerFactory.getLogger(BootstrapFlow.class);
private Map<String, ModuleDefine> loadedModules;
// Modules sorted in dependency order provide a list of objects
private List<ModuleProvider> startupSequence;
BootstrapFlow(Map<String, ModuleDefine> loadedModules) throws CycleDependencyException, ModuleNotFoundException {
this.loadedModules = loadedModules;
startupSequence = new LinkedList<>();
// The dependent modules are loaded first
makeSequence();
}
@SuppressWarnings("unchecked")
void start(
ModuleManager moduleManager) throws ModuleNotFoundException, ServiceNotProvidedException, ModuleStartException {
for (ModuleProvider provider : startupSequence) {
LOGGER.info("start the provider {} in {} module.", provider.name(), provider.getModuleName());
provider.requiredCheck(provider.getModule().services());
provider.start();
}
}
void notifyAfterCompleted() throws ServiceNotProvidedException, ModuleStartException {
for (ModuleProvider provider : startupSequence) {
provider.notifyAfterCompleted();
}
}
private void makeSequence() throws CycleDependencyException, ModuleNotFoundException {
List<ModuleProvider> allProviders = new ArrayList<>();
// Determine whether all dependent modules exist
for (final ModuleDefine module : loadedModules.values()) {
String[] requiredModules = module.provider().requiredModules();
if (requiredModules != null) {
for (String requiredModule : requiredModules) {
if (!loadedModules.containsKey(requiredModule)) {
throw new ModuleNotFoundException(requiredModule + " module is required by " + module.provider().getModuleName() + "." + module.provider().name() + ", but not found.");
}
}
}
allProviders.add(module.provider());
}
do {
int numOfToBeSequenced = allProviders.size();
for (int i = 0; i < allProviders.size(); i++) {
ModuleProvider provider = allProviders.get(i);
String[] requiredModules = provider.requiredModules();
if (CollectionUtils.isNotEmpty(requiredModules)) {
// Whether all dependent modules are in startupSequence in
boolean isAllRequiredModuleStarted = true;
for (String module : requiredModules) {
boolean exist = false;
for (ModuleProvider moduleProvider : startupSequence) {
if (moduleProvider.getModuleName().equals(module)) {
exist = true;
break;
}
}
if (!exist) {
isAllRequiredModuleStarted = false;
break;
}
}
// All dependent modules are in startupSequence, Then add the object provided by the module to startupSequence
if (isAllRequiredModuleStarted) {
startupSequence.add(provider);
allProviders.remove(i);
i--;
}
} else {
// If the module provides an object that does not depend on any other module , Join in startupSequence
startupSequence.add(provider);
allProviders.remove(i);
i--;
}
}
// If after one cycle , No object is added to startupSequence, Then it proves that there is cyclic dependence
if (numOfToBeSequenced == allProviders.size()) {
StringBuilder unSequencedProviders = new StringBuilder();
allProviders.forEach(provider -> unSequencedProviders.append(provider.getModuleName()).append("[provider=").append(provider.getClass().getName()).append("]\n"));
throw new CycleDependencyException("Exist cycle module dependencies in \n" + unSequencedProviders.substring(0, unSequencedProviders.length() - 1));
}
} while (allProviders.size() != 0); // When the supplied object list is not empty , Then it will be executed in a loop
}
}

ApplicationConfiguration

package org.apache.skywalking.oap.server.library.module;
import java.util.HashMap;
import java.util.Properties;
// OAP Application configuration class
public class ApplicationConfiguration {
// Module definition configuration map
private HashMap<String, ModuleConfiguration> modules = new HashMap<>();
// List of module configuration names
public String[] moduleList() {
return modules.keySet().toArray(new String[0]);
}
// Add module definition configuration
public ModuleConfiguration addModule(String moduleName) {
ModuleConfiguration newModule = new ModuleConfiguration();
modules.put(moduleName, newModule);
return newModule;
}
// Judge whether the module definition configuration exists for the specified module name map in
public boolean has(String moduleName) {
return modules.containsKey(moduleName);
}
// Get module definition configuration
public ModuleConfiguration getModuleConfiguration(String name) {
return modules.get(name);
}
// Module definition configuration class
public static class ModuleConfiguration {
// Modules provide objects map
private HashMap<String, ProviderConfiguration> providers = new HashMap<>();
private ModuleConfiguration() {
}
// Get the configuration provided by the module
public Properties getProviderConfiguration(String name) {
return providers.get(name).getProperties();
}
// Whether there is a module to provide configuration
public boolean has(String name) {
return providers.containsKey(name);
}
// Add modules to provide configuration
public ModuleConfiguration addProviderConfiguration(String name, Properties properties) {
ProviderConfiguration newProvider = new ProviderConfiguration(properties);
providers.put(name, newProvider);
return this;
}
}
// Module provides configuration classes
public static class ProviderConfiguration {
// Module provides properties
private Properties properties;
ProviderConfiguration(Properties properties) {
this.properties = properties;
}
private Properties getProperties() {
return properties;
}
}
}

ApplicationConfigLoader

package org.apache.skywalking.oap.server.starter.config;
import java.io.FileNotFoundException;
import java.io.Reader;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.util.PropertyPlaceholderHelper;
import org.apache.skywalking.oap.server.library.module.ApplicationConfiguration;
import org.apache.skywalking.oap.server.library.module.ProviderNotFoundException;
import org.apache.skywalking.oap.server.library.util.CollectionUtils;
import org.apache.skywalking.oap.server.library.util.ResourceUtils;
import org.yaml.snakeyaml.Yaml;
// application.yml Load class , Three tier structure : Module definition name . Provide module name . attribute key
@Slf4j
public class ApplicationConfigLoader implements ConfigLoader<ApplicationConfiguration> {
// When the module provider is not configured , Use "-"
private static final String DISABLE_SELECTOR = "-";
// This field selects the module provider
private static final String SELECTOR = "selector";
private final Yaml yaml = new Yaml();
@Override
public ApplicationConfiguration load() throws ConfigFileNotFoundException {
ApplicationConfiguration configuration = new ApplicationConfiguration();
this.loadConfig(configuration);
this.overrideConfigBySystemEnv(configuration);
return configuration;
}
@SuppressWarnings("unchecked")
private void loadConfig(ApplicationConfiguration configuration) throws ConfigFileNotFoundException {
try {
Reader applicationReader = ResourceUtils.read("application.yml");
Map<String, Map<String, Object>> moduleConfig = yaml.loadAs(applicationReader, Map.class);
if (CollectionUtils.isNotEmpty(moduleConfig)) {
selectConfig(moduleConfig);
moduleConfig.forEach((moduleName, providerConfig) -> {
if (providerConfig.size() > 0) {
log.info("Get a module define from application.yml, module name: {}", moduleName);
ApplicationConfiguration.ModuleConfiguration moduleConfiguration = configuration.addModule(moduleName);
providerConfig.forEach((providerName, config) -> {
log.info("Get a provider define belong to {} module, provider name: {}", moduleName, providerName);
final Map<String, ?> propertiesConfig = (Map<String, ?>) config;
final Properties properties = new Properties();
if (propertiesConfig != null) {
propertiesConfig.forEach((propertyName, propertyValue) -> {
if (propertyValue instanceof Map) {
Properties subProperties = new Properties();
((Map) propertyValue).forEach((key, value) -> {
subProperties.put(key, value);
replacePropertyAndLog(key, value, subProperties, providerName);
});
properties.put(propertyName, subProperties);
} else {
properties.put(propertyName, propertyValue);
replacePropertyAndLog(propertyName, propertyValue, properties, providerName);
}
});
}
moduleConfiguration.addProviderConfiguration(providerName, properties);
});
} else {
log.warn("Get a module define from application.yml, but no provider define, use default, module name: {}", moduleName);
}
});
}
} catch (FileNotFoundException e) {
throw new ConfigFileNotFoundException(e.getMessage(), e);
}
}
private void replacePropertyAndLog(final Object propertyName, final Object propertyValue, final Properties target, final Object providerName) {
final String valueString = PropertyPlaceholderHelper.INSTANCE.replacePlaceholders(propertyValue + "", target);
if (valueString != null) {
if (valueString.trim().length() == 0) {
target.replace(propertyName, valueString);
log.info("Provider={} config={} has been set as an empty string", providerName, propertyName);
} else {
// Use YAML to do data type conversion.
final Object replaceValue = yaml.load(valueString);
if (replaceValue != null) {
target.replace(propertyName, replaceValue);
log.info("Provider={} config={} has been set as {}", providerName, propertyName, replaceValue.toString());
}
}
}
}
private void overrideConfigBySystemEnv(ApplicationConfiguration configuration) {
for (Map.Entry<Object, Object> prop : System.getProperties().entrySet()) {
overrideModuleSettings(configuration, prop.getKey().toString(), prop.getValue().toString());
}
}
private void selectConfig(final Map<String, Map<String, Object>> moduleConfiguration) {
final Set<String> modulesWithoutProvider = new HashSet<>();
for (final Map.Entry<String, Map<String, Object>> entry : moduleConfiguration.entrySet()) {
final String moduleName = entry.getKey();
final Map<String, Object> providerConfig = entry.getValue();
if (!providerConfig.containsKey(SELECTOR)) {
continue;
}
final String selector = (String) providerConfig.get(SELECTOR);
final String resolvedSelector = PropertyPlaceholderHelper.INSTANCE.replacePlaceholders(
selector, System.getProperties()
);
providerConfig.entrySet().removeIf(e -> !resolvedSelector.equals(e.getKey()));
if (!providerConfig.isEmpty()) {
continue;
}
if (!DISABLE_SELECTOR.equals(resolvedSelector)) {
throw new ProviderNotFoundException("no provider found for module " + moduleName + ", " + "if you're sure it's not required module and want to remove it, " + "set the selector to -");
}
// now the module can be safely removed
modulesWithoutProvider.add(moduleName);
}
moduleConfiguration.entrySet().removeIf(e -> {
final String module = e.getKey();
final boolean shouldBeRemoved = modulesWithoutProvider.contains(module);
if (shouldBeRemoved) {
log.info("Remove module {} without any provider", module);
}
return shouldBeRemoved;
});
}
private void overrideModuleSettings(ApplicationConfiguration configuration, String key, String value) {
int moduleAndConfigSeparator = key.indexOf('.');
if (moduleAndConfigSeparator <= 0) {
return;
}
String moduleName = key.substring(0, moduleAndConfigSeparator);
String providerSettingSubKey = key.substring(moduleAndConfigSeparator + 1);
ApplicationConfiguration.ModuleConfiguration moduleConfiguration = configuration.getModuleConfiguration(moduleName);
if (moduleConfiguration == null) {
return;
}
int providerAndConfigSeparator = providerSettingSubKey.indexOf('.');
if (providerAndConfigSeparator <= 0) {
return;
}
String providerName = providerSettingSubKey.substring(0, providerAndConfigSeparator);
String settingKey = providerSettingSubKey.substring(providerAndConfigSeparator + 1);
if (!moduleConfiguration.has(providerName)) {
return;
}
Properties providerSettings = moduleConfiguration.getProviderConfiguration(providerName);
if (!providerSettings.containsKey(settingKey)) {
return;
}
Object originValue = providerSettings.get(settingKey);
Class<?> type = originValue.getClass();
if (type.equals(int.class) || type.equals(Integer.class))
providerSettings.put(settingKey, Integer.valueOf(value));
else if (type.equals(String.class))
providerSettings.put(settingKey, value);
else if (type.equals(long.class) || type.equals(Long.class))
providerSettings.put(settingKey, Long.valueOf(value));
else if (type.equals(boolean.class) || type.equals(Boolean.class)) {
providerSettings.put(settingKey, Boolean.valueOf(value));
} else {
return;
}
log.info("The setting has been override by key: {}, value: {}, in {} provider of {} module through {}", settingKey, value, providerName, moduleName, "System.properties");
}
}

ConfigLoader

package org.apache.skywalking.oap.server.starter.config;
// Configure the loading interface
public interface ConfigLoader<T> {
T load() throws ConfigFileNotFoundException;
}

OAPServerBootstrap

package org.apache.skywalking.oap.server.starter;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.oap.server.core.RunningMode;
import org.apache.skywalking.oap.server.library.module.ApplicationConfiguration;
import org.apache.skywalking.oap.server.library.module.ModuleManager;
import org.apache.skywalking.oap.server.starter.config.ApplicationConfigLoader;
import org.apache.skywalking.oap.server.starter.config.ConfigLoader;
import org.apache.skywalking.oap.server.telemetry.TelemetryModule;
import org.apache.skywalking.oap.server.telemetry.api.MetricsCreator;
import org.apache.skywalking.oap.server.telemetry.api.MetricsTag;
// OAP Start class , Load profile , Initialization module
@Slf4j
public class OAPServerBootstrap {
public static void start() {
String mode = System.getProperty("mode");
// Boot mode
RunningMode.setMode(mode);
ApplicationConfigLoader configLoader = new ApplicationConfigLoader();
ModuleManager manager = new ModuleManager();
try {
// Load configuration from configuration file
ApplicationConfiguration applicationConfiguration = configLoader.load();
// Initialization module
manager.init(applicationConfiguration);
// Send the start time to Telemetry
manager.find(TelemetryModule.NAME)
.provider()
.getService(MetricsCreator.class)
.createGauge("uptime", "oap server start up time", MetricsTag.EMPTY_KEY, MetricsTag.EMPTY_VALUE)
// Set uptime to second
.setValue(System.currentTimeMillis() / 1000d);
if (RunningMode.isInitMode()) {
log.info("OAP starts up in init mode successfully, exit now...");
System.exit(0);
}
} catch (Throwable t) {
log.error(t.getMessage(), t);
System.exit(1);
}
}
}

OAPServerStartUp

package org.apache.skywalking.oap.server.starter;
// OAP Start class
public class OAPServerStartUp {
public static void main(String[] args) {
OAPServerBootstrap.start();
}
}

With Skywalking OAP Start the process analysis module loading mechanism

Sequence diagram

file

Source file :OAPServerStartUp.sdt

Case study : Enclosure load analysis

The configuration file

from application.yml The configuration file , It can be seen that .

Modules are defined in a three-tier structure :

  • first floor : Module definition name
  • The second floor : Provide module name / selector
  • The third level : The module provides configuration information / selector The selected module provides configuration
storage:
selector: ${SW_STORAGE:h2}
elasticsearch:
nameSpace: ${SW_NAMESPACE:""}
clusterNodes: ${SW_STORAGE_ES_CLUSTER_NODES:localhost:9200}
# etc...
elasticsearch7:
nameSpace: ${SW_NAMESPACE:""}
clusterNodes: ${SW_STORAGE_ES_CLUSTER_NODES:localhost:9200}
# etc...
h2:
driver: ${SW_STORAGE_H2_DRIVER:org.h2.jdbcx.JdbcDataSource}
url: ${SW_STORAGE_H2_URL:jdbc:h2:mem:skywalking-oap-db;DB_CLOSE_DELAY=-1}
# etc...
mysql:
properties:
jdbcUrl: ${SW_JDBC_URL:"jdbc:mysql://localhost:3306/swtest"}
dataSource.user: ${SW_DATA_SOURCE_USER:root}
dataSource.password: ${SW_DATA_SOURCE_PASSWORD:[email protected]}
# etc...
tidb:
properties:
jdbcUrl: ${SW_JDBC_URL:"jdbc:mysql://localhost:4000/tidbswtest"}
dataSource.user: ${SW_DATA_SOURCE_USER:root}
dataSource.password: ${SW_DATA_SOURCE_PASSWORD:""}
# etc...
influxdb:
url: ${SW_STORAGE_INFLUXDB_URL:http://localhost:8086}
user: ${SW_STORAGE_INFLUXDB_USER:root}
password: ${SW_STORAGE_INFLUXDB_PASSWORD:}
# etc...

Load the configuration

after org.apache.skywalking.oap.server.starter.config.ApplicationConfigLoader#load Call to , org.apache.skywalking.oap.server.starter.OAPServerBootstrap#start Get all the modules that need to be loaded , This includes enclosures .

stay org.apache.skywalking.oap.server.starter.config.ApplicationConfigLoader#selectConfig Also through storage.selector=h2 , The enclosure only retains h2 Configuration information :

storage:
h2:
driver: ${SW_STORAGE_H2_DRIVER:org.h2.jdbcx.JdbcDataSource}
url: ${SW_STORAGE_H2_URL:jdbc:h2:mem:skywalking-oap-db;DB_CLOSE_DELAY=-1}
# etc...

Preparation stage

stay org.apache.skywalking.oap.server.library.module.ModuleManager#init in , adopt SPI Loaded the module definition object , The definition classes corresponding to the enclosure are as follows :

PS: You can see that a lot of Service  Interface

package org.apache.skywalking.oap.server.core.storage;
import org.apache.skywalking.oap.server.core.storage.cache.INetworkAddressAliasDAO;
import org.apache.skywalking.oap.server.core.storage.management.UITemplateManagementDAO;
import org.apache.skywalking.oap.server.core.storage.profile.IProfileTaskLogQueryDAO;
import org.apache.skywalking.oap.server.core.storage.profile.IProfileTaskQueryDAO;
import org.apache.skywalking.oap.server.core.storage.profile.IProfileThreadSnapshotQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.IAggregationQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.IAlarmQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.IBrowserLogQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.ILogQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.IMetadataQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.IMetricsQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.ITopNRecordsQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.ITopologyQueryDAO;
import org.apache.skywalking.oap.server.core.storage.query.ITraceQueryDAO;
import org.apache.skywalking.oap.server.library.module.ModuleDefine;
/**
* StorageModule provides the capabilities(services) to interact with the database. With different databases, this
* module could have different providers, such as currently, H2, MySQL, ES, TiDB.
*/
public class StorageModule extends ModuleDefine {
public static final String NAME = "storage";
public StorageModule() {
super(NAME);
}
@Override
public Class[] services() {
return new Class[]{
IBatchDAO.class,
StorageDAO.class,
IHistoryDeleteDAO.class,
INetworkAddressAliasDAO.class,
ITopologyQueryDAO.class,
IMetricsQueryDAO.class,
ITraceQueryDAO.class,
IMetadataQueryDAO.class,
IAggregationQueryDAO.class,
IAlarmQueryDAO.class,
ITopNRecordsQueryDAO.class,
ILogQueryDAO.class,
IProfileTaskQueryDAO.class,
IProfileTaskLogQueryDAO.class,
IProfileThreadSnapshotQueryDAO.class,
UITemplateManagementDAO.class,
IBrowserLogQueryDAO.class
};
}
}

It also calls org.apache.skywalking.oap.server.library.module.ModuleDefine#prepare Enter the preparation stage

 String[] moduleNames = applicationConfiguration.moduleList();
ServiceLoader<ModuleDefine> moduleServiceLoader = ServiceLoader.load(ModuleDefine.class);
ServiceLoader<ModuleProvider> moduleProviderLoader = ServiceLoader.load(ModuleProvider.class);
LinkedList<String> moduleList = new LinkedList<>(Arrays.asList(moduleNames));
for (ModuleDefine module : moduleServiceLoader) {
for (String moduleName : moduleNames) {
if (moduleName.equals(module.name())) {
module.prepare(this, applicationConfiguration.getModuleConfiguration(moduleName), moduleProviderLoader);
loadedModules.put(moduleName, module);
moduleList.remove(moduleName);
}
}
}

stay org.apache.skywalking.oap.server.library.module.ModuleDefine#prepare Through the incoming configuration , Only match the modules selected in the configuration file to provide objects .

 for (ModuleProvider provider : moduleProviderLoader) {
if (!configuration.has(provider.name())) {
continue;
}
if (provider.module().equals(getClass())) {
if (loadedProvider == null) {
loadedProvider = provider;
loadedProvider.setManager(moduleManager);
loadedProvider.setModuleDefine(this);
} else {
throw new DuplicateProviderException(this.name() + " module has one " + loadedProvider.name() + "[" + loadedProvider.getClass().getName()
+ "] provider already, " + provider.name() + "[" + provider.getClass().getName() + "] is defined as 2nd provider.");
}
}
}
if (loadedProvider == null) {
throw new ProviderNotFoundException(this.name() + " module no provider found.");
}
LOGGER.info("Prepare the {} provider in {} module.", loadedProvider.name(), this.name());
try {
copyProperties(loadedProvider.createConfigBeanIfAbsent(), configuration.getProviderConfiguration(loadedProvider.name()), this.name(), loadedProvider.name());
} catch (IllegalAccessException e) {
throw new ModuleConfigException(this.name() + " module config transport to config bean failure.", e);
}
loadedProvider.prepare();

for example “ The configuration file ” A section selected h2 , Then the loaded provider class is org.apache.skywalking.oap.server.storage.plugin.jdbc.h2.H2StorageProvider

its prepare The method is as follows , You can see : Registered all StorageModule Declarative Service Interface

 @Override
public void prepare() throws ServiceNotProvidedException, ModuleStartException {
Properties settings = new Properties();
settings.setProperty("dataSourceClassName", config.getDriver());
settings.setProperty("dataSource.url", config.getUrl());
settings.setProperty("dataSource.user", config.getUser());
settings.setProperty("dataSource.password", config.getPassword());
h2Client = new JDBCHikariCPClient(settings);
this.registerServiceImplementation(IBatchDAO.class, new H2BatchDAO(h2Client));
this.registerServiceImplementation(
StorageDAO.class,
new H2StorageDAO(
getManager(), h2Client, config.getMaxSizeOfArrayColumn(), config.getNumOfSearchableValuesPerTag())
);
this.registerServiceImplementation(
INetworkAddressAliasDAO.class, new H2NetworkAddressAliasDAO(h2Client));
this.registerServiceImplementation(ITopologyQueryDAO.class, new H2TopologyQueryDAO(h2Client));
this.registerServiceImplementation(IMetricsQueryDAO.class, new H2MetricsQueryDAO(h2Client));
this.registerServiceImplementation(
ITraceQueryDAO.class, new H2TraceQueryDAO(
getManager(),
h2Client,
config.getMaxSizeOfArrayColumn(),
config.getNumOfSearchableValuesPerTag()
));
this.registerServiceImplementation(IBrowserLogQueryDAO.class, new H2BrowserLogQueryDAO(h2Client));
this.registerServiceImplementation(
IMetadataQueryDAO.class, new H2MetadataQueryDAO(h2Client, config.getMetadataQueryMaxSize()));
this.registerServiceImplementation(IAggregationQueryDAO.class, new H2AggregationQueryDAO(h2Client));
this.registerServiceImplementation(IAlarmQueryDAO.class, new H2AlarmQueryDAO(h2Client));
this.registerServiceImplementation(
IHistoryDeleteDAO.class, new H2HistoryDeleteDAO(h2Client));
this.registerServiceImplementation(ITopNRecordsQueryDAO.class, new H2TopNRecordsQueryDAO(h2Client));
this.registerServiceImplementation(
ILogQueryDAO.class,
new H2LogQueryDAO(
h2Client,
getManager(),
config.getMaxSizeOfArrayColumn(),
config.getNumOfSearchableValuesPerTag()
)
);
this.registerServiceImplementation(IProfileTaskQueryDAO.class, new H2ProfileTaskQueryDAO(h2Client));
this.registerServiceImplementation(IProfileTaskLogQueryDAO.class, new H2ProfileTaskLogQueryDAO(h2Client));
this.registerServiceImplementation(
IProfileThreadSnapshotQueryDAO.class, new H2ProfileThreadSnapshotQueryDAO(h2Client));
this.registerServiceImplementation(UITemplateManagementDAO.class, new H2UITemplateManagementDAO(h2Client));
}

Start-up phase

stay org.apache.skywalking.oap.server.library.module.ModuleManager#init By calling org.apache.skywalking.oap.server.library.module.BootstrapFlow#start Enter start-up phase

 void start(
ModuleManager moduleManager) throws ModuleNotFoundException, ServiceNotProvidedException, ModuleStartException {
for (ModuleProvider provider : startupSequence) {
LOGGER.info("start the provider {} in {} module.", provider.name(), provider.getModuleName());
provider.requiredCheck(provider.getModule().services());
provider.start();
}
}

for example “ The configuration file ” A section selected h2 , Then the loaded provider class is org.apache.skywalking.oap.server.storage.plugin.jdbc.h2.H2StorageProvider

its start The method is as follows , You can see : start-up h2client And monitor ModelCreator

 @Override
public void start() throws ServiceNotProvidedException, ModuleStartException {
final ConfigService configService = getManager().find(CoreModule.NAME)
.provider()
.getService(ConfigService.class);
final int numOfSearchableTracesTags = configService.getSearchableTracesTags().split(Const.COMMA).length;
if (numOfSearchableTracesTags * config.getNumOfSearchableValuesPerTag() > config.getMaxSizeOfArrayColumn()) {
throw new ModuleStartException("Size of searchableTracesTags[" + numOfSearchableTracesTags
+ "] * numOfSearchableValuesPerTag[" + config.getNumOfSearchableValuesPerTag()
+ "] > maxSizeOfArrayColumn[" + config.getMaxSizeOfArrayColumn()
+ "]. Potential out of bound in the runtime.");
}
final int numOfSearchableLogsTags = configService.getSearchableLogsTags().split(Const.COMMA).length;
if (numOfSearchableLogsTags * config.getNumOfSearchableValuesPerTag() > config.getMaxSizeOfArrayColumn()) {
throw new ModuleStartException("Size of searchableLogsTags[" + numOfSearchableLogsTags
+ "] * numOfSearchableValuesPerTag[" + config.getNumOfSearchableValuesPerTag()
+ "] > maxSizeOfArrayColumn[" + config.getMaxSizeOfArrayColumn()
+ "]. Potential out of bound in the runtime.");
}
MetricsCreator metricCreator = getManager().find(TelemetryModule.NAME)
.provider()
.getService(MetricsCreator.class);
HealthCheckMetrics healthChecker = metricCreator.createHealthCheckerGauge(
"storage_h2", MetricsTag.EMPTY_KEY, MetricsTag.EMPTY_VALUE);
h2Client.registerChecker(healthChecker);
try {
h2Client.connect();
H2TableInstaller installer = new H2TableInstaller(
h2Client, getManager(), config.getMaxSizeOfArrayColumn(), config.getNumOfSearchableValuesPerTag());
getManager().find(CoreModule.NAME).provider().getService(ModelCreator.class).addModelListener(installer);
} catch (StorageException e) {
throw new ModuleStartException(e.getMessage(), e);
}
}

Notification stage after completion

stay org.apache.skywalking.oap.server.library.module.ModuleManager#init By calling org.apache.skywalking.oap.server.library.module.BootstrapFlow#notifyAfterCompleted Enter the post completion notification stage

 void notifyAfterCompleted() throws ServiceNotProvidedException, ModuleStartException {
for (ModuleProvider provider : startupSequence) {
provider.notifyAfterCompleted();
}
}

for example “ The configuration file ” A section selected h2 , Then the loaded provider class is org.apache.skywalking.oap.server.storage.plugin.jdbc.h2.H2StorageProvider

its notifyAfterCompleted The method is as follows , You can see : There's nothing to do

 @Override
public void notifyAfterCompleted() throws ServiceNotProvidedException, ModuleStartException {
}

H2StorageProvider Complete source code

package org.apache.skywalking.oap.server.storage.plugin.jdbc.h2;
// etc...
/**
* H2 Storage provider is for demonstration and preview only. I will find that haven't implemented several interfaces,
* because not necessary, and don't consider about performance very much.
* <p>
* If someone wants to implement SQL-style database as storage, please just refer the logic.
*/
@Slf4j
public class H2StorageProvider extends ModuleProvider {
private H2StorageConfig config;
private JDBCHikariCPClient h2Client;
public H2StorageProvider() {
config = new H2StorageConfig();
}
@Override
public String name() {
return "h2";
}
@Override
public Class<? extends ModuleDefine> module() {
return StorageModule.class;
}
@Override
public ModuleConfig createConfigBeanIfAbsent() {
return config;
}
@Override
public void prepare() throws ServiceNotProvidedException, ModuleStartException {
Properties settings = new Properties();
settings.setProperty("dataSourceClassName", config.getDriver());
settings.setProperty("dataSource.url", config.getUrl());
settings.setProperty("dataSource.user", config.getUser());
settings.setProperty("dataSource.password", config.getPassword());
h2Client = new JDBCHikariCPClient(settings);
this.registerServiceImplementation(IBatchDAO.class, new H2BatchDAO(h2Client));
this.registerServiceImplementation(
StorageDAO.class,
new H2StorageDAO(
getManager(), h2Client, config.getMaxSizeOfArrayColumn(), config.getNumOfSearchableValuesPerTag())
);
this.registerServiceImplementation(
INetworkAddressAliasDAO.class, new H2NetworkAddressAliasDAO(h2Client));
this.registerServiceImplementation(ITopologyQueryDAO.class, new H2TopologyQueryDAO(h2Client));
this.registerServiceImplementation(IMetricsQueryDAO.class, new H2MetricsQueryDAO(h2Client));
this.registerServiceImplementation(
ITraceQueryDAO.class, new H2TraceQueryDAO(
getManager(),
h2Client,
config.getMaxSizeOfArrayColumn(),
config.getNumOfSearchableValuesPerTag()
));
this.registerServiceImplementation(IBrowserLogQueryDAO.class, new H2BrowserLogQueryDAO(h2Client));
this.registerServiceImplementation(
IMetadataQueryDAO.class, new H2MetadataQueryDAO(h2Client, config.getMetadataQueryMaxSize()));
this.registerServiceImplementation(IAggregationQueryDAO.class, new H2AggregationQueryDAO(h2Client));
this.registerServiceImplementation(IAlarmQueryDAO.class, new H2AlarmQueryDAO(h2Client));
this.registerServiceImplementation(
IHistoryDeleteDAO.class, new H2HistoryDeleteDAO(h2Client));
this.registerServiceImplementation(ITopNRecordsQueryDAO.class, new H2TopNRecordsQueryDAO(h2Client));
this.registerServiceImplementation(
ILogQueryDAO.class,
new H2LogQueryDAO(
h2Client,
getManager(),
config.getMaxSizeOfArrayColumn(),
config.getNumOfSearchableValuesPerTag()
)
);
this.registerServiceImplementation(IProfileTaskQueryDAO.class, new H2ProfileTaskQueryDAO(h2Client));
this.registerServiceImplementation(IProfileTaskLogQueryDAO.class, new H2ProfileTaskLogQueryDAO(h2Client));
this.registerServiceImplementation(
IProfileThreadSnapshotQueryDAO.class, new H2ProfileThreadSnapshotQueryDAO(h2Client));
this.registerServiceImplementation(UITemplateManagementDAO.class, new H2UITemplateManagementDAO(h2Client));
}
@Override
public void start() throws ServiceNotProvidedException, ModuleStartException {
final ConfigService configService = getManager().find(CoreModule.NAME)
.provider()
.getService(ConfigService.class);
final int numOfSearchableTracesTags = configService.getSearchableTracesTags().split(Const.COMMA).length;
if (numOfSearchableTracesTags * config.getNumOfSearchableValuesPerTag() > config.getMaxSizeOfArrayColumn()) {
throw new ModuleStartException("Size of searchableTracesTags[" + numOfSearchableTracesTags
+ "] * numOfSearchableValuesPerTag[" + config.getNumOfSearchableValuesPerTag()
+ "] > maxSizeOfArrayColumn[" + config.getMaxSizeOfArrayColumn()
+ "]. Potential out of bound in the runtime.");
}
final int numOfSearchableLogsTags = configService.getSearchableLogsTags().split(Const.COMMA).length;
if (numOfSearchableLogsTags * config.getNumOfSearchableValuesPerTag() > config.getMaxSizeOfArrayColumn()) {
throw new ModuleStartException("Size of searchableLogsTags[" + numOfSearchableLogsTags
+ "] * numOfSearchableValuesPerTag[" + config.getNumOfSearchableValuesPerTag()
+ "] > maxSizeOfArrayColumn[" + config.getMaxSizeOfArrayColumn()
+ "]. Potential out of bound in the runtime.");
}
MetricsCreator metricCreator = getManager().find(TelemetryModule.NAME)
.provider()
.getService(MetricsCreator.class);
HealthCheckMetrics healthChecker = metricCreator.createHealthCheckerGauge(
"storage_h2", MetricsTag.EMPTY_KEY, MetricsTag.EMPTY_VALUE);
h2Client.registerChecker(healthChecker);
try {
h2Client.connect();
H2TableInstaller installer = new H2TableInstaller(
h2Client, getManager(), config.getMaxSizeOfArrayColumn(), config.getNumOfSearchableValuesPerTag());
getManager().find(CoreModule.NAME).provider().getService(ModelCreator.class).addModelListener(installer);
} catch (StorageException e) {
throw new ModuleStartException(e.getMessage(), e);
}
}
@Override
public void notifyAfterCompleted() throws ServiceNotProvidedException, ModuleStartException {
}
@Override
public String[] requiredModules() {
return new String[] {CoreModule.NAME};
}
}

summary

Skywalking The module mechanism provided is very well designed , At work , If there are more than one N choose 1 Scene , We can learn from its design .

Reference documents

Please bring the original link to reprint ,thank
Similar articles

2021-10-14

2021-10-14

2021-10-14

2021-10-14

2021-10-14

2021-10-14

2021-10-14