release version 1.10.0

This commit is contained in:
2024-10-07 18:42:55 +03:00
parent 2034182607
commit a5088587f7
1501 changed files with 28818 additions and 59966 deletions

View File

@ -4,7 +4,7 @@
<parent>
<groupId>ru.entaxy.esb.platform.runtime.core</groupId>
<artifactId>initializer</artifactId>
<version>1.9.0</version>
<version>1.10.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@ -29,7 +29,7 @@
<extensions>true</extensions>
<configuration>
<instructions>
<Entaxy-Initializer-Class>ru.entaxy.esb.platform.runtime.core.initializer.connection.ConnectionInitializer?id=connections&amp;repeat=true&amp;retries=10&amp;interval=2000&amp;depends-on=core,datasources</Entaxy-Initializer-Class>
<Entaxy-Initializer-Class-0>ru.entaxy.esb.platform.runtime.core.initializer.connection.ConnectionInitializer?id=connections&amp;repeat=true&amp;retries=10&amp;interval=2000&amp;depends-on=core,datasources</Entaxy-Initializer-Class-0>
</instructions>
</configuration>
</plugin>
@ -45,16 +45,21 @@
</goals>
<configuration>
<artifacts>
<artifact>
<file>src/main/non-packaged-resources/etc/init/entaxy-platform-connections.json</file>
<type>json</type>
<classifier>init-config</classifier>
</artifact>
<artifact>
<file>src/main/non-packaged-resources/etc/init/file-connections.json</file>
<type>json</type>
<classifier>init-config-files</classifier>
</artifact>
<artifact>
<file>src/main/non-packaged-resources/etc/init/db-connections.json</file>
<type>json</type>
<classifier>init-config-databases</classifier>
</artifact>
<artifact>
<file>src/main/non-packaged-resources/etc/init/broker-connections.json</file>
<type>json</type>
<classifier>init-config-brokers</classifier>
</artifact>
</artifacts>
</configuration>
</execution>
@ -68,11 +73,6 @@
<groupId>org.osgi</groupId>
<artifactId>osgi.core</artifactId>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.platform.runtime.core.management</groupId>
<artifactId>connection-manager</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* connection-initializer
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
@ -27,278 +27,319 @@ package ru.entaxy.esb.platform.runtime.core.initializer.connection;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonObject;
import ru.entaxy.esb.platform.runtime.core.initializer.api.AbstractInitializer;
import ru.entaxy.esb.platform.runtime.core.initializer.api.InitializerException;
import ru.entaxy.esb.platform.runtime.core.management.connection.util.ConnectionManagerUtil;
import ru.entaxy.esb.platform.runtime.core.initializer.api.AbstractStandaloneInitializer;
import ru.entaxy.esb.platform.runtime.core.initializer.api.Initialized;
import ru.entaxy.esb.platform.runtime.core.initializer.api.StandaloneInitializer;
import ru.entaxy.platform.base.objects.factory.exceptions.FactoryNotFoundException;
import ru.entaxy.platform.base.support.FileUtils;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.platform.base.support.osgi.OSGIUtils;
import ru.entaxy.platform.core.artifact.ArtifactCoordinates;
import ru.entaxy.platform.core.producer.api.EntaxyProducerService;
import ru.entaxy.platform.core.producer.api.EntaxyProducerUtils;
import ru.entaxy.platform.core.producer.api.ProducerResult;
import ru.entaxy.platform.core.producer.api.ProducerResult.CommandResult;
import ru.entaxy.platform.core.producer.executor.generationmodel.GenerateTask;
import ru.entaxy.platform.core.producer.executor.generationmodel.GenerationModel;
import ru.entaxy.platform.core.producer.executor.installer.InstalledObjectList;
import ru.entaxy.platform.core.producer.executor.objectmodel.ObjectModel;
public class ConnectionInitializer extends AbstractInitializer {
@Component(service = ConnectionInitializer.class, immediate = true)
@StandaloneInitializer(id = "connections")
public class ConnectionInitializer extends AbstractStandaloneInitializer {
private static final Logger log = LoggerFactory.getLogger(ConnectionInitializer.class);
private static final String JSON_FILE_NAME = "entaxy-platform-connections.json";
private static final String jsonBundlePath = "/connection/" + JSON_FILE_NAME;
protected static final Logger log = LoggerFactory.getLogger(ConnectionInitializer.class);
private static final String INIT_FILES_PATH = System.getProperty("karaf.etc")
+ File.separator
+ "init";
private static final String JSON_FILE_PATH = INIT_FILES_PATH
+ File.separator
+ JSON_FILE_NAME;
private static final String INIT_FILES_PATH = System.getProperty("karaf.etc")
+ File.separator
+ "init";
private EntaxyProducerService entaxyProducerService;
@Override
public void init() throws InitializerException {
log.info("ConnectionInitializer started");
log.info("-->> " + JSON_FILE_PATH);
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY, target = "(id=core)")
volatile Initialized coreInitializedMarker;
try {
entaxyProducerService = OSGIUtils.services().bundleContext(bundleContext)
.ofClass(EntaxyProducerService.class)
.waitService(50000)
.get();
if (entaxyProducerService == null)
throw new InitializerException(this, "Service EntaxyProducerService not found", "", null);
} catch (Exception e) {
log.error("Error getting EntaxyProducerService", e);
throw new InitializerException(this, "Error getting EntaxyProducerService", "", e);
}
// first scan factory-base files
try {
scanAndInitFromFactoryFiles();
} catch (Exception e) {
log.error("Error initializing connections from factory files", e);
throw new InitializerException(this, "Can't create platform connections", "", e);
}
// then use the old one
try {
initPlatformConnections(bundleContext);
} catch (Exception e) {
log.error("Error initializing connections from " + JSON_FILE_PATH, e);
throw new InitializerException(this, "Can't create platform connections", "", e);
}
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY, target = "(id=datasources)")
volatile Initialized datasourcesInitializedMarker;
@Reference
EntaxyProducerService entaxyProducerService;
ExecutorService threadPool = Executors.newCachedThreadPool();
int globalRetriesCount = 10;
int globalRetryInterval = 2000;
boolean factoryFilesTaskResult = false;
public void setFactoryFilesTaskResult(boolean factoryFilesTaskResult) {
this.factoryFilesTaskResult = factoryFilesTaskResult;
}
@Override
public void reinit() throws InitializerException {
// TODO Auto-generated method stub
protected void checkAndRegister() {
if (factoryFilesTaskResult)
register();
}
private void scanAndInitFromFactoryFiles() throws Exception {
File initDir = new File(INIT_FILES_PATH);
if (!initDir.exists() || !initDir.isDirectory())
return;
File[] files = initDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json") && !JSON_FILE_NAME.equals(name);
}
});
if ((files == null) || (files.length==0))
return;
for (int i=0; i<files.length; i++) {
log.debug("FOUND FILE :: " + files[i].getName());
//
// check if the file contains objects
//
FileUtils.FileHelper helper = new FileUtils.FileHelper(files[i].getAbsolutePath());
if (!helper.isReadable()) {
// TODO throw exception
log.warn("Platform connections file {} is not readable", JSON_FILE_PATH);
continue;
protected class FactoryFilesTask implements Runnable {
protected CommandResult getCommandResult(final String id, ProducerResult producerResult) {
Optional<CommandResult> result =
producerResult.getCommandResults().stream().filter(c -> c.commandId.equals(id))
.findFirst();
if (result.isEmpty())
return null;
return result.get();
}
protected boolean checkResult(ProducerResult producerResult) {
CommandResult cr = getCommandResult("install", producerResult);
if (cr == null)
return false;
if (!cr.result || cr.skipped)
return false;
try {
GenerationModel generationModel = producerResult.findResultObject(GenerationModel.class);
List<GenerateTask> generateTasks = generationModel.getTasks().stream()
.filter(t -> (t instanceof GenerateTask))
.filter(t -> !t.isToMerge())
.map(t -> (GenerateTask) t)
.collect(Collectors.toList());
InstalledObjectList installedList = producerResult.findResultObject(InstalledObjectList.class);
log.debug("FactoryFilesTask :: Generated:[{}]; Installed:[{}]", generateTasks.size(),
installedList.size());
return installedList.size() == generateTasks.size();
} catch (Exception e) {
return false;
}
JsonObject jsonData;
try {
URL url = files[i].toURI().toURL();
jsonData = JSONUtils.getJsonRootObject(url);
} catch (Exception e) {
log.warn("Configuration loading failed:" + e.getMessage());
continue;
}
ObjectModel objectModel = new ObjectModel();
try {
objectModel.load(jsonData);
objectModel.checkRefs();
} catch (Exception e) {
log.warn("Error loading model from " + files[i].getAbsolutePath(), e);
continue;
}
if (objectModel.objects.size() == 0)
continue;
log.debug("CONTAINS OBJECTS :: " + files[i].getName());
//
// check availability of factories
//
List<String> factoryIds = objectModel.objects.stream()
.map(obj -> obj.factoryId)
.collect(Collectors.toList());
for (String factoryId: factoryIds) {
String message = "CHECK FACTORY :: " + factoryId + "..";
if (entaxyProducerService.findFactoryById(factoryId) == null) {
message += " NOT FOUND";
log.debug(message);
throw new InitializerException(this, "Factory not found: " + factoryId, "", null);
}
message += " FOUND";
log.debug(message);
}
log.debug("FACTORIES AVAILABLE :: " + files[i].getName());
//
// produce objects
//
EntaxyProducerUtils.InstructionsBuilder builder = EntaxyProducerUtils.instructions()
.lifecycle("general")
.any()
.command("add-config")
.command("pre-generate")
.set(EntaxyProducerService.INSTRUCTIONS.PRINT_OUTPUT, false)
.command("build")
.set(EntaxyProducerService.INSTRUCTIONS.ARTIFACT.VERSION_POLICY
, ArtifactCoordinates.VERSION_POLICY_DATED_EMBEDDED)
.command("deploy")
.set("deployLocal", true);
if (helper.isChanged()) {
log.info("File is new or changed, install/update connections: " + files[i].getAbsolutePath());
// we need to create/update connections with new timestamp
String oldTimestamp = helper.getTimestamp();
String newTimestamp = helper.updateTimestamp();
builder
.command("build")
.set(EntaxyProducerService.INSTRUCTIONS.ARTIFACT.TIMESTAMP, newTimestamp)
.command("install")
.set("update", "")
.set("installLocal", true)
.set("startLevel", 75);
String instructions = builder
.getInstructionsString();
entaxyProducerService.produce(jsonData, instructions);
helper.updateMd5();
} else {
log.info("File is not changed, install/check connection: " + files[i].getAbsolutePath());
String oldTimestamp = helper.getTimestamp();
builder
.command("build")
.set(EntaxyProducerService.INSTRUCTIONS.ARTIFACT.TIMESTAMP, oldTimestamp)
.command("install")
.set("installOnlyIfMissing", true)
.set("installLocal", true)
.set("startLevel", 75);
String instructions = builder
.getInstructionsString();
entaxyProducerService.produce(jsonData, instructions);
}
}
}
private void initPlatformConnections(BundleContext bundleContext) throws Exception {
checkAndPrepareFile(bundleContext);
String json = getJsonAsString(bundleContext);
FileUtils.FileHelper helper = new FileUtils.FileHelper(JSON_FILE_PATH);
if (!helper.isReadable()) {
// TODO throw exception
log.error("Platform connections file {} is not readable", JSON_FILE_PATH);
return;
// return true;
}
if (helper.isChanged()) {
log.info("File is new or changed, install/update connections");
// we need to create/update connections with new timestamp
String oldTimestamp = helper.getTimestamp();
String newTimestamp = helper.updateTimestamp();
// ConnectionManagerUtil.getService().createAndInstallConnections(json);
ConnectionManagerUtil.getService().installUpdateConnections(json, newTimestamp);
helper.updateMd5();
} else {
log.info("File is not changed, install/check connections");
// we need to create if absent connections with old timestamp
// ConnectionManagerUtil.getService().createAndInstallConnections(json);
ConnectionManagerUtil.getService().checkInstallConnections(json, helper.getTimestamp());
@Override
public void run() {
int retriesLeft = globalRetriesCount;
File initDir = new File(INIT_FILES_PATH);
if (!initDir.exists() || !initDir.isDirectory()) {
log.info("FactoryFilesTask :: initDir not available");
return;
}
File[] files = initDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
});
if ((files == null) || (files.length == 0)) {
log.info("FactoryFilesTask :: files not found in initDir");
return;
}
while (retriesLeft > 0) {
try {
for (int i = 0; i < files.length; i++) {
log.debug("FactoryFilesTask :: FOUND FILE :: " + files[i].getName());
//
// check if the file contains objects
//
FileUtils.FileHelper helper = new FileUtils.FileHelper(files[i].getAbsolutePath());
if (!helper.isReadable()) {
// TODO throw exception
log.warn("FactoryFilesTask :: file {} is not readable", files[i].getAbsolutePath());
continue;
}
JsonObject jsonData;
try {
URL url = files[i].toURI().toURL();
jsonData = JSONUtils.getJsonRootObject(url);
} catch (Exception e) {
log.warn("FactoryFilesTask :: Configuration loading failed:" + e.getMessage());
continue;
}
ObjectModel objectModel = new ObjectModel();
try {
objectModel.load(jsonData);
objectModel.checkRefs();
} catch (Exception e) {
log.warn("FactoryFilesTask :: Error loading model from " + files[i].getAbsolutePath(), e);
continue;
}
if (objectModel.objects.size() == 0)
continue;
log.debug("FactoryFilesTask :: CONTAINS OBJECTS :: " + files[i].getName());
//
// check availability of factories
//
List<String> factoryIds = objectModel.objects.stream()
.map(obj -> obj.factoryId)
.collect(Collectors.toList());
for (String factoryId : factoryIds) {
String message = "CHECK FACTORY :: " + factoryId + "..";
if (entaxyProducerService.findFactoryById(factoryId) == null) {
message += " NOT FOUND";
log.debug(message);
throw new FactoryNotFoundException("Factory not found: " + factoryId);// (this,
// "Factory
// not
// found:
// "
// +
// factoryId,
// "",
// null);
}
message += " FOUND";
log.debug(message);
}
log.debug("FactoryFilesTask :: FACTORIES AVAILABLE :: " + files[i].getName());
//
// produce objects
//
EntaxyProducerUtils.InstructionsBuilder builder = EntaxyProducerUtils.instructions()
.lifecycle("general")
.any()
.command("add-config")
.command("pre-generate")
.set(EntaxyProducerService.INSTRUCTIONS.PRINT_OUTPUT, false)
.command("build")
.set(EntaxyProducerService.INSTRUCTIONS.ARTIFACT.VERSION_POLICY,
ArtifactCoordinates.VERSION_POLICY_DATED_EMBEDDED)
.command("deploy")
.set("deployLocal", true);
if (helper.isChanged()) {
log.info("FactoryFilesTask :: File is new or changed, install/update connections: "
+ files[i].getAbsolutePath());
// we need to create/update connections with new timestamp
String oldTimestamp = helper.getTimestamp();
String newTimestamp = helper.updateTimestamp();
builder
.command("build")
.set(EntaxyProducerService.INSTRUCTIONS.ARTIFACT.TIMESTAMP, newTimestamp)
.command("install")
.set("update", "")
.set("installLocal", true)
.set("startLevel", 75);
String instructions = builder
.getInstructionsString();
log.info("FactoryFilesTask :: running with instructions [" + instructions + "]");
ProducerResult result = entaxyProducerService.produce(jsonData, instructions);
log.debug("FactoryFilesTask :: last result command ["
+ result.getLastCommandResult().commandId + "]");
if (!result.getAllExceptions().isEmpty()) {
throw new Exception("ProducerResult contains exceptions");
}
if (!checkResult(result)) {
throw new Exception("ProducerResult not valid");
}
helper.updateMd5();
} else {
log.info("FactoryFilesTask :: File is not changed, install/check connection: "
+ files[i].getAbsolutePath());
String oldTimestamp = helper.getTimestamp();
builder
.command("build")
.set(EntaxyProducerService.INSTRUCTIONS.ARTIFACT.TIMESTAMP, oldTimestamp)
.command("install")
.set("installOnlyIfMissing", true)
.set("installLocal", true)
.set("startLevel", 75);
String instructions = builder
.getInstructionsString();
ProducerResult result = entaxyProducerService.produce(jsonData, instructions);
if (!result.getAllExceptions().isEmpty()) {
throw new Exception("ProducerResult contains exceptions");
}
if (!checkResult(result)) {
throw new Exception("ProducerResult not valid");
}
}
}
setFactoryFilesTaskResult(true);
checkAndRegister();
return;
} catch (Exception e) {
log.error(
String.format("Error in FactoryFilesTask; iteration=%d", globalRetriesCount - retriesLeft),
e);
try {
Thread.sleep(globalRetryInterval);
} catch (InterruptedException e1) {
log.warn("FactoryFilesTask interrupted");
checkAndRegister();
return;
}
}
retriesLeft--;
}
checkAndRegister();
}
}
private void checkAndPrepareFile(BundleContext context) throws IOException {
File f = new File(JSON_FILE_PATH);
if (!f.exists()) {
FileUtils.string2file(getJsonAsString(context), JSON_FILE_PATH);
}
}
private String getJsonAsString(BundleContext context) throws IOException {
URL jsonUrl;
File f = new File(JSON_FILE_PATH);
if (f.exists() && f.canRead()) {
jsonUrl = f.toURI().toURL();
log.info("Path to json file: " + jsonUrl.toString());
} else {
jsonUrl = context.getBundle().getEntry(jsonBundlePath);
log.debug("Path to json file: " + jsonUrl.toString());
}
InputStream inputStream = jsonUrl.openStream();
byte[] bytes = inputStream.readAllBytes();
String result = new String(bytes, Charset.defaultCharset());
inputStream.close();
return result;
}
@Activate
public void activate(ComponentContext componentContext) {
log.info("ConnectionInitializer started");
setBundleContext(componentContext.getBundleContext());
threadPool.execute(new FactoryFilesTask());
}
}

View File

@ -1,42 +0,0 @@
{
"connections": [
{
"nodeType": "connection",
"uuid": "connection-uuid-2",
"name": "entaxy-broker",
"adapterName": "artemisAdapter",
"platform": true,
"pathParameter": "queue:entaxy.default",
"properties": {
"url": "(tcp://localhost:61616)",
"username": "entaxy",
"password": "entaxy",
"maxConnections": "20",
"maxSessionsPerConnection": "100"
},
"options": {}
},
{
"nodeType": "connection",
"uuid": "connection-uuid-3",
"name": "entaxy-db-storage",
"adapterName.pg": "postgresqlAdapter",
"adapterName": "h2Adapter",
"platform": true,
"pathParameter": "entaxy.esb.storage",
"properties": {},
"options": {}
},
{
"nodeType": "connection",
"uuid": "connection-uuid-4",
"name": "entaxy-db-cache",
"adapterName.pg": "postgresqlAdapter",
"adapterName": "h2Adapter",
"platform": true,
"pathParameter": "entaxy.esb.cache",
"properties": {},
"options": {}
}
]
}

View File

@ -5,7 +5,8 @@
"objectId": "entaxy-file",
"properties": {
"rootDirectory": "data/shared",
"createResourceProvider": true
"createResourceProvider": true,
"isPlatform": true
}
},
{
@ -13,7 +14,8 @@
"objectId": "entaxy-file-internal",
"properties": {
"rootDirectory": "data/shared/.entaxy",
"createResourceProvider": true
"createResourceProvider": true,
"isPlatform": true
}
}
]

View File

@ -3,7 +3,7 @@
<parent>
<groupId>ru.entaxy.esb.platform.runtime.core</groupId>
<artifactId>initializer</artifactId>
<version>1.9.0</version>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.esb.platform.runtime.core.initializer</groupId>
<artifactId>core-initializer</artifactId>
@ -23,7 +23,7 @@
<extensions>true</extensions>
<configuration>
<instructions>
<Entaxy-Initializer-Class>ru.entaxy.esb.platform.runtime.core.initializer.core.CoreInitializer?id=core&amp;repeat=true&amp;depends-on=repositories,datasources</Entaxy-Initializer-Class>
<Entaxy-Initializer-Class-0>ru.entaxy.esb.platform.runtime.core.initializer.core.CoreInitializer?id=core&amp;repeat=true&amp;depends-on=repositories,datasources</Entaxy-Initializer-Class-0>
</instructions>
</configuration>
</plugin>

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* core-initializer
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
@ -25,31 +25,49 @@
*/
package ru.entaxy.esb.platform.runtime.core.initializer.core;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.platform.runtime.core.initializer.api.AbstractInitializer;
import ru.entaxy.esb.platform.runtime.core.initializer.api.InitializerException;
import ru.entaxy.esb.platform.runtime.core.initializer.api.AbstractStandaloneInitializer;
import ru.entaxy.esb.platform.runtime.core.initializer.api.Initialized;
import ru.entaxy.esb.platform.runtime.core.initializer.api.StandaloneInitializer;
/**
*
* NOOP-class for now, just to check everything works
* Can be filled with the functionality in the future
* NOOP-class for now, just to check everything works Can be filled with the functionality in the
* future
*
* @author sstarovoytenkov
*
*/
public class CoreInitializer extends AbstractInitializer {
@Component(service = CoreInitializer.class, immediate = true)
@StandaloneInitializer(id = "core")
public class CoreInitializer extends AbstractStandaloneInitializer {
protected static final Logger log = LoggerFactory.getLogger(CoreInitializer.class);
@Override
public void init() throws InitializerException {
log.info("Init in CoreInitializer is called");
}
protected static final Logger log = LoggerFactory.getLogger(CoreInitializer.class);
@Override
public void reinit() throws InitializerException {
log.info("ReInit in CoreInitializer is called");
}
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY,
target = "(id=repositories)")
volatile Initialized repositoriesMarker;
@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC,
policyOption = ReferencePolicyOption.GREEDY,
target = "(id=datasources)")
volatile Initialized datasourcesMarker;
@Activate
public void activate(ComponentContext componentContext) {
setBundleContext(componentContext.getBundleContext());
register();
}
}

View File

@ -3,7 +3,7 @@
<parent>
<groupId>ru.entaxy.esb.platform.runtime.core</groupId>
<artifactId>initializer</artifactId>
<version>1.9.0</version>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.esb.platform.runtime.core.initializer</groupId>
<artifactId>datasources-initializer</artifactId>
@ -29,7 +29,7 @@
<extensions>true</extensions>
<configuration>
<instructions>
<Entaxy-Initializer-Class>ru.entaxy.esb.platform.runtime.core.initializer.datasources.DataSourcesInitializer?id=datasources&amp;repeat=false&amp;retries=10&amp;interval=2000&amp;depends-on=repositories</Entaxy-Initializer-Class>
<Entaxy-Initializer-Class-0>ru.entaxy.esb.platform.runtime.core.initializer.datasources.DataSourcesInitializer?id=datasources&amp;repeat=false&amp;retries=10&amp;interval=2000&amp;depends-on=repositories</Entaxy-Initializer-Class-0>
</instructions>
</configuration>
</plugin>

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
entaxy-assembly
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* datasources-initializer
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* datasources-initializer
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
# ~~~~~~licensing~~~~~~
# h2-adapter
# ==========
# Copyright (C) 2020 - 2023 EmDev LLC
# Copyright (C) 2020 - 2024 EmDev LLC
# ==========
# You may not use this file except in accordance with the License Terms of the Copyright
# Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
# ~~~~~~licensing~~~~~~
# datasources-initializer
# ==========
# Copyright (C) 2020 - 2023 EmDev LLC
# Copyright (C) 2020 - 2024 EmDev LLC
# ==========
# You may not use this file except in accordance with the License Terms of the Copyright
# Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
# ~~~~~~licensing~~~~~~
# h2-adapter
# ==========
# Copyright (C) 2020 - 2023 EmDev LLC
# Copyright (C) 2020 - 2024 EmDev LLC
# ==========
# You may not use this file except in accordance with the License Terms of the Copyright
# Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
# ~~~~~~licensing~~~~~~
# datasources-initializer
# ==========
# Copyright (C) 2020 - 2023 EmDev LLC
# Copyright (C) 2020 - 2024 EmDev LLC
# ==========
# You may not use this file except in accordance with the License Terms of the Copyright
# Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
datasources-initializer
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
<parent>
<groupId>ru.entaxy.esb.platform.runtime.core</groupId>
<artifactId>initializer</artifactId>
<version>1.9.0</version>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.esb.platform.runtime.core.initializer</groupId>
<artifactId>init-manager</artifactId>

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* init-manager
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* init-manager
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
@ -29,7 +29,9 @@ import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ -40,13 +42,14 @@ import org.apache.felix.utils.properties.TypedProperties;
import org.apache.karaf.config.core.ConfigRepository;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.wiring.BundleWiring;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.entaxy.esb.platform.runtime.core.initializer.api.Initialized;
import ru.entaxy.esb.platform.runtime.core.initializer.api.Initializer;
import ru.entaxy.esb.platform.runtime.core.initializer.api.InitializerException;
@ -54,390 +57,436 @@ import ru.entaxy.esb.platform.runtime.core.initializer.api.InitializerException;
*
* Manager for initializers
*
* TODO (if needed):
* 1. keep map "initializerClassName -> bundleId"
* 2. publish as a service
* 3. provide interface with method "reinit(String className)"
* TODO (if needed): 1. keep map "initializerClassName -> bundleId" 2. publish as a service 3.
* provide interface with method "reinit(String className)"
*
*
* @author sstarovoytenkov
*
*/
public class InitManager {
protected static final Logger log = LoggerFactory.getLogger(InitManager.class);
public static final String PROP_SKIP_ALL = "skip.all";
/**
* pid of config to store initialization status (true/false)
* will be created on first start of InitManager
*/
protected final String pid = "ru.entaxy.esb.initializer";
protected ConfigRepository configRepository;
protected BundleContext bundleContext;
// used when updating to avoid multiple extra initializations
protected boolean skipAll = false;
protected Map<String, Set<String>> initersToDeps = new HashMap<>();
protected Map<String, Set<String>> depsToIniters = new HashMap<>();
protected Map<String, InitializerMeta> initializers = new HashMap<>();
protected List<String> waiting = new ArrayList<>();
protected class InitializerMeta implements Initializer.Callback {
String id;
String className;
boolean repeat;
// Bundle bundle;
long bundleId;
BundleContext bundleContext;
Map<String, InitializerMeta> dependsOn = new HashMap<>();
Map<String, InitializerMeta> dependedBy = new HashMap<>();
boolean executed = false;
boolean toBeExecuted = true;
int retries = 1;
int interval = 1000;
public void load(String initializerData) {
String[] data = initializerData.split("\\?");
this.className = data[0];
String queryString = data.length>1?data[1]:"";
String[] queryStringData = queryString.split("&");
Map<String, String> params = new HashMap<>();
for (int i=0; i<queryStringData.length; i++) {
String[] paramData = queryStringData[i].split("=");
params.put(paramData[0], paramData.length>1?paramData[1]:"");
}
this.id = params.containsKey(Initializer.INITIALIZER_QUERY_STRING_PARAM_ID)
?(Strings.isNullOrEmpty(params.get(Initializer.INITIALIZER_QUERY_STRING_PARAM_ID))
?className
:params.get(Initializer.INITIALIZER_QUERY_STRING_PARAM_ID))
:className;
String dependsOn = params.get(Initializer.INITIALIZER_QUERY_STRING_PARAM_DEPENDS_ON);
if (!Strings.isNullOrEmpty(dependsOn)) {
String[] dependencies = dependsOn.split(",");
for (int i=0; i<dependencies.length; i++) {
InitializerMeta meta = InitManager.this.getMetaById(dependencies[i]);
addDependency(meta);
}
}
String repeat = params.get(Initializer.INITIALIZER_QUERY_STRING_PARAM_REPEAT);
this.repeat = "true".equals(repeat);
String retriesValue = params.get(Initializer.INITIALIZER_QUERY_STRING_PARAM_RETRIES);
if (!Strings.isNullOrEmpty(retriesValue))
try {
this.retries = Integer.parseInt(retriesValue);
} catch (NumberFormatException e) {
log.error("Retries parameter [{}] is not an integer", retriesValue);
}
String intervalValue = params.get(Initializer.INITIALIZER_QUERY_STRING_PARAM_INTERVAL);
if (!Strings.isNullOrEmpty(intervalValue))
try {
this.interval = Integer.parseInt(intervalValue);
} catch (NumberFormatException e) {
log.error("Interval parameter [{}] is not an integer", intervalValue);
}
}
protected void addDependency(InitializerMeta meta) {
synchronized (meta) {
if (meta.toBeExecuted && !meta.executed)
synchronized (this.dependsOn) {
meta.addDependent(this);
this.dependsOn.put(meta.id, meta);
}
}
}
public void load(InitializerMeta other) {
this.className = other.className;
this.bundleId = other.bundleId;
this.repeat = other.repeat;
this.retries = other.retries;
this.interval = other.interval;
this.bundleContext = other.bundleContext;
for (InitializerMeta meta: other.dependsOn.values())
this.addDependency(meta);
}
public void addDependent(InitializerMeta meta) {
synchronized (this.dependedBy) {
this.dependedBy.put(meta.id, meta);
}
}
protected static final Logger log = LoggerFactory.getLogger(InitManager.class);
public boolean isExecutedBefore() {
return InitManager.this.getValueById(id);
}
public boolean canExecute() {
return this.dependsOn.isEmpty();
}
public void notifyDependent() {
for (InitializerMeta meta: this.dependedBy.values())
meta.dependencyReady(this);
}
public Bundle getBundle() {
return bundleContext.getBundle(bundleId);
}
public boolean execute() {
/**
* instantiate initializer and call "init"
* if no exceptions, set status to "true"
*
* @see <code>Initializer</code>
*/
Bundle bundle = getBundle();
BundleWiring wiring = bundle.adapt(BundleWiring.class);
ClassLoader cl = wiring.getClassLoader();
Class<?> clazz;
try {
if (!InitManager.this.skipAll) {
clazz = cl.loadClass(className);
log.info("Loaded class {}", clazz.getName());
Constructor<?> constructor = clazz.getConstructor();
Initializer initializer = (Initializer) constructor.newInstance();
initializer.setBundleContext(bundle.getBundleContext());
initializer.setInitializerId(id);
initializer.init();
}
InitManager.this.updateById(id, true);
this.executed = true;
this.notifyDependent();
return true;
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InitializerException e) {
log.error("Initializer error: class=" + className
+ ", id=" + id + " -> [" + e.getMessage() + "] :: "
+ (e instanceof InitializerException?((InitializerException)e).getDescription():""), e);
return false;
}
}
public static final String PROP_SKIP_ALL = "skip.all";
public void runInitializer() {
Thread thread = new Thread(new Executor(this));
thread.setContextClassLoader(Thread.currentThread().getContextClassLoader());
thread.start();
}
public void setCallback() {
BundleWiring wiring = getBundle().adapt(BundleWiring.class);
ClassLoader cl = wiring.getClassLoader();
Class<?> clazz;
try {
clazz = cl.loadClass(className);
log.info("Loaded class {}", clazz.getName());
Constructor<?> constructor = clazz.getConstructor();
Initializer initializer = (Initializer) constructor.newInstance();
initializer.setCallback(this);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void dependencyReady(InitializerMeta meta) {
synchronized (this.dependsOn) {
this.dependsOn.remove(meta.id);
if (!this.executed && this.canExecute())
// this.execute();
this.runInitializer();
}
}
@Override
public void inited(Initializer owner) {
log.info("Initializer with id {} notified of successful init via callback", id);
InitManager.this.updateById(id, true);
this.executed = true;
this.notifyDependent();
owner.setCallback(null);
}
};
protected static class Executor implements Runnable {
InitializerMeta meta;
public Executor(InitializerMeta meta) {
this.meta = meta;
}
@Override
public void run() {
/**
* pid of config to store initialization status (true/false) will be created on first start of
* InitManager
*/
protected final String pid = "ru.entaxy.esb.initializer";
/**
* check the initialization status
*/
if (meta.isExecutedBefore()) {
log.info("Initializer with id {} in bundle [{}] {} is already inited", meta.id,
meta.bundleId, meta.getBundle().getSymbolicName());
protected ConfigRepository configRepository;
protected BundleContext bundleContext;
if (meta.repeat)
log.info("Initializer with id {} is set to be repeated", meta.id);
else {
meta.toBeExecuted = false;
meta.notifyDependent();
return;
}
}
if (!meta.canExecute()) {
String dependsOn = meta.dependsOn.values().stream().map((m)->m.id).collect(Collectors.joining(","));
log.info("Initializer with id {} is waiting for dependencies: {}", meta.id, dependsOn);
// used when updating to avoid multiple extra initializations
protected boolean skipAll = false;
/*
* synchronized (this.waiting) { this.waiting.add(meta.id); }
*/
return;
}
int retriesCount = meta.retries;
boolean result = false;
while (!result && (retriesCount > 0)) {
log.info("Executing initializer with id {}: try {} of {}", meta.id, meta.retries-retriesCount+1, meta.retries);
retriesCount--;
result = meta.execute();
if ((retriesCount > 0) && !result)
try {
log.info("Executing initializer with id {}: sleeping for {}", meta.id, meta.interval);
Thread.sleep(meta.interval);
} catch (InterruptedException e) {
log.error("Failed sleep for thread {} on initializer {}", Thread.currentThread().getId(), meta.id);
e.printStackTrace();
}
}
// last try
if (!result)
meta.setCallback();
protected Map<String, Set<String>> initersToDeps = new HashMap<>();
protected Map<String, Set<String>> depsToIniters = new HashMap<>();
}
}
protected InitializerMeta getMetaById(String id) {
synchronized (initializers) {
if (!initializers.containsKey(id)) {
InitializerMeta meta = new InitializerMeta();
meta.id = id;
initializers.put(id, meta);
}
return initializers.get(id);
}
}
public InitManager(BundleContext context) {
this.bundleContext = context;
ServiceReference<ConfigRepository> ref1 = this.bundleContext.getServiceReference(ConfigRepository.class);
this.configRepository = this.bundleContext.getService(ref1);
if (!getValueById(this.getClass().getName())){
updateById(this.getClass().getName(), true);
}
this.skipAll = getValueById(PROP_SKIP_ALL);
}
protected InitializerMeta createMeta(String initializerMeta, Bundle bundle) {
InitializerMeta meta = new InitializerMeta();
meta.load(initializerMeta);
meta.bundleId = bundle.getBundleId();
meta.bundleContext = bundleContext;
synchronized (this.initializers) {
if (this.initializers.containsKey(meta.id)) {
this.initializers.get(meta.id).load(meta);
} else {
this.initializers.put(meta.id, meta);
}
}
protected Map<String, InitializerMeta> initializers = new HashMap<>();
return this.initializers.get(meta.id);
}
/**
*
* @param initializerClass class name read by tracker from Entaxy-Initializer-Class manifest header
* @param bundle
*/
public void init(String initializerClass, Bundle bundle) {
log.info("Found initializer of class {} in bundle [{}] {}", initializerClass,
bundle.getBundleId(), bundle.getSymbolicName());
InitializerMeta meta = createMeta(initializerClass, bundle);
meta.runInitializer();
// Thread thread = new Thread(new Executor(meta));
// thread.setContextClassLoader(Thread.currentThread().getContextClassLoader());
// thread.start();
}
/* protected void execute(InitializerMeta meta) {
if (meta.execute())
synchronized (this.waiting) {
this.waiting.remove(meta.id);
}
for (String id: this.waiting) {
InitializerMeta waits = getMetaById(id);
synchronized (waits) {
if (waits.canExecute())
}
}
}
*/
/**
*
* @param initializerId class name to check
* @return true if the initializer is already completed, false otherwise
*/
protected boolean getValueById(String initializerId) {
try {
TypedProperties tp = this.configRepository.getConfig(pid);
if (!tp.containsKey(initializerId))
return false;
return "true".equals(tp.get(initializerId).toString());
} catch (IOException | InvalidSyntaxException e) {
log.warn("Can't get property " + initializerId, e);
}
return false;
}
protected List<String> waiting = new ArrayList<>();
protected class InitializerMeta implements Initializer.Callback {
String id;
String className;
boolean repeat;
// Bundle bundle;
long bundleId;
BundleContext bundleContext;
Map<String, InitializerMeta> dependsOn = new HashMap<>();
Map<String, InitializerMeta> dependedBy = new HashMap<>();
boolean executed = false;
boolean toBeExecuted = true;
int retries = 1;
int interval = 1000;
InitializedImpl initializedImpl;
public void load(String initializerData) {
String[] data = initializerData.split("\\?");
this.className = data[0];
String queryString = data.length > 1 ? data[1] : "";
String[] queryStringData = queryString.split("&");
Map<String, String> params = new HashMap<>();
for (int i = 0; i < queryStringData.length; i++) {
String[] paramData = queryStringData[i].split("=");
params.put(paramData[0], paramData.length > 1 ? paramData[1] : "");
}
this.id = params.containsKey(Initializer.INITIALIZER_QUERY_STRING_PARAM_ID)
? (Strings.isNullOrEmpty(params.get(Initializer.INITIALIZER_QUERY_STRING_PARAM_ID))
? className
: params.get(Initializer.INITIALIZER_QUERY_STRING_PARAM_ID))
: className;
String dependsOn = params.get(Initializer.INITIALIZER_QUERY_STRING_PARAM_DEPENDS_ON);
if (!Strings.isNullOrEmpty(dependsOn)) {
String[] dependencies = dependsOn.split(",");
for (int i = 0; i < dependencies.length; i++) {
InitializerMeta meta = InitManager.this.getMetaById(dependencies[i]);
addDependency(meta);
}
}
String repeat = params.get(Initializer.INITIALIZER_QUERY_STRING_PARAM_REPEAT);
this.repeat = "true".equals(repeat);
String retriesValue = params.get(Initializer.INITIALIZER_QUERY_STRING_PARAM_RETRIES);
if (!Strings.isNullOrEmpty(retriesValue))
try {
this.retries = Integer.parseInt(retriesValue);
} catch (NumberFormatException e) {
log.error("Retries parameter [{}] is not an integer", retriesValue);
}
String intervalValue = params.get(Initializer.INITIALIZER_QUERY_STRING_PARAM_INTERVAL);
if (!Strings.isNullOrEmpty(intervalValue))
try {
this.interval = Integer.parseInt(intervalValue);
} catch (NumberFormatException e) {
log.error("Interval parameter [{}] is not an integer", intervalValue);
}
}
protected void addDependency(InitializerMeta meta) {
synchronized (meta) {
if (meta.toBeExecuted && !meta.executed)
synchronized (this.dependsOn) {
meta.addDependent(this);
this.dependsOn.put(meta.id, meta);
}
}
}
public void load(InitializerMeta other) {
this.className = other.className;
this.bundleId = other.bundleId;
this.repeat = other.repeat;
this.retries = other.retries;
this.interval = other.interval;
this.bundleContext = other.bundleContext;
for (InitializerMeta meta : other.dependsOn.values())
this.addDependency(meta);
}
public void addDependent(InitializerMeta meta) {
synchronized (this.dependedBy) {
this.dependedBy.put(meta.id, meta);
}
}
public boolean isExecutedBefore() {
return InitManager.this.getValueById(id);
}
public boolean canExecute() {
return this.dependsOn.isEmpty();
}
public void notifyDependent() {
for (InitializerMeta meta : this.dependedBy.values())
meta.dependencyReady(this);
}
public Bundle getBundle() {
return bundleContext.getBundle(bundleId);
}
public boolean execute() {
/**
* instantiate initializer and call "init" if no exceptions, set status to "true"
*
* @see <code>Initializer</code>
*/
Bundle bundle = getBundle();
BundleWiring wiring = bundle.adapt(BundleWiring.class);
ClassLoader cl = wiring.getClassLoader();
Class<?> clazz;
try {
if (!InitManager.this.skipAll) {
clazz = cl.loadClass(className);
log.info("Loaded class {}", clazz.getName());
Constructor<?> constructor = clazz.getConstructor();
Initializer initializer = (Initializer) constructor.newInstance();
initializer.setBundleContext(bundle.getBundleContext());
initializer.setInitializerId(id);
initializer.init();
}
InitManager.this.updateById(id, true);
this.executed = true;
this.notifyDependent();
return true;
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
| IllegalAccessException | IllegalArgumentException | InvocationTargetException
| InitializerException e) {
log.error("Initializer error: class=" + className
+ ", id=" + id + " -> [" + e.getMessage() + "] :: "
+ (e instanceof InitializerException ? ((InitializerException) e).getDescription() : ""), e);
return false;
}
}
public void registerService() {
this.initializedImpl = new InitializedImpl(bundleContext, id);
this.initializedImpl.register();
}
public void runInitializer() {
Thread thread = new Thread(new Executor(this));
thread.setContextClassLoader(Thread.currentThread().getContextClassLoader());
thread.start();
}
public void setCallback() {
BundleWiring wiring = getBundle().adapt(BundleWiring.class);
ClassLoader cl = wiring.getClassLoader();
Class<?> clazz;
try {
clazz = cl.loadClass(className);
log.info("Loaded class {}", clazz.getName());
Constructor<?> constructor = clazz.getConstructor();
Initializer initializer = (Initializer) constructor.newInstance();
initializer.setCallback(this);
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
| IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void dependencyReady(InitializerMeta meta) {
synchronized (this.dependsOn) {
this.dependsOn.remove(meta.id);
if (!this.executed && this.canExecute())
// this.execute();
this.runInitializer();
}
}
@Override
public void inited(Initializer owner) {
log.info("Initializer with id {} notified of successful init via callback", id);
InitManager.this.updateById(id, true);
this.executed = true;
this.notifyDependent();
owner.setCallback(null);
}
};
protected static class InitializedImpl implements Initialized {
protected BundleContext bundleContext;
protected String initializerId;
protected ServiceRegistration<Initialized> serviceRegistration;
public InitializedImpl(BundleContext bundleContext, String id) {
this.bundleContext = bundleContext;
this.initializerId = id;
}
public void register() {
try {
Dictionary<String, Object> props = new Hashtable<>();
props.put(PROP_INITIALIZER_ID, initializerId);
this.serviceRegistration = bundleContext.registerService(Initialized.class, this, props);
} catch (Exception e) {
log.error("Error registering service for initializer [" + initializerId + "]", e);
}
}
public void unregister() {
if (serviceRegistration != null)
try {
serviceRegistration.unregister();
} catch (Exception e) {
log.error("Error unregistering service for initializer [" + initializerId + "]", e);
}
serviceRegistration = null;
}
public boolean isRegistered() {
return serviceRegistration != null;
}
}
protected static class Executor implements Runnable {
InitializerMeta meta;
public Executor(InitializerMeta meta) {
this.meta = meta;
}
@Override
public void run() {
/**
* check the initialization status
*/
if (meta.isExecutedBefore()) {
log.info("Initializer with id {} in bundle [{}] {} is already inited", meta.id,
meta.bundleId, meta.getBundle().getSymbolicName());
if (meta.repeat)
log.info("Initializer with id {} is set to be repeated", meta.id);
else {
meta.toBeExecuted = false;
meta.notifyDependent();
meta.registerService();
return;
}
}
if (!meta.canExecute()) {
String dependsOn = meta.dependsOn.values().stream().map((m) -> m.id).collect(Collectors.joining(","));
log.info("Initializer with id {} is waiting for dependencies: {}", meta.id, dependsOn);
/*
* synchronized (this.waiting) { this.waiting.add(meta.id); }
*/
return;
}
int retriesCount = meta.retries;
boolean result = false;
while (!result && (retriesCount > 0)) {
log.info("Executing initializer with id {}: try {} of {}", meta.id, meta.retries - retriesCount + 1,
meta.retries);
retriesCount--;
result = meta.execute();
if (result)
meta.registerService();
if ((retriesCount > 0) && !result)
try {
log.info("Executing initializer with id {}: sleeping for {}", meta.id, meta.interval);
Thread.sleep(meta.interval);
} catch (InterruptedException e) {
log.error("Failed sleep for thread {} on initializer {}", Thread.currentThread().getId(),
meta.id);
e.printStackTrace();
}
}
// last try
if (!result)
meta.setCallback();
}
}
protected InitializerMeta getMetaById(String id) {
synchronized (initializers) {
if (!initializers.containsKey(id)) {
InitializerMeta meta = new InitializerMeta();
meta.id = id;
initializers.put(id, meta);
}
return initializers.get(id);
}
}
public InitManager(BundleContext context) {
this.bundleContext = context;
ServiceReference<ConfigRepository> ref1 = this.bundleContext.getServiceReference(ConfigRepository.class);
this.configRepository = this.bundleContext.getService(ref1);
if (!getValueById(this.getClass().getName())) {
updateById(this.getClass().getName(), true);
}
this.skipAll = getValueById(PROP_SKIP_ALL);
}
protected InitializerMeta createMeta(String initializerMeta, Bundle bundle) {
InitializerMeta meta = new InitializerMeta();
meta.load(initializerMeta);
meta.bundleId = bundle.getBundleId();
meta.bundleContext = bundleContext;
synchronized (this.initializers) {
if (this.initializers.containsKey(meta.id)) {
this.initializers.get(meta.id).load(meta);
} else {
this.initializers.put(meta.id, meta);
}
}
return this.initializers.get(meta.id);
}
/**
*
* @param initializerClass class name read by tracker from Entaxy-Initializer-Class manifest
* header
* @param bundle
*/
public void init(String initializerClass, Bundle bundle) {
log.info("Found initializer of class {} in bundle [{}] {}", initializerClass,
bundle.getBundleId(), bundle.getSymbolicName());
InitializerMeta meta = createMeta(initializerClass, bundle);
meta.runInitializer();
// Thread thread = new Thread(new Executor(meta));
// thread.setContextClassLoader(Thread.currentThread().getContextClassLoader());
// thread.start();
}
/*
* protected void execute(InitializerMeta meta) { if (meta.execute()) synchronized
* (this.waiting) { this.waiting.remove(meta.id); } for (String id: this.waiting) {
* InitializerMeta waits = getMetaById(id); synchronized (waits) { if (waits.canExecute()) } } }
*/
/**
*
* @param initializerId class name to check
* @return true if the initializer is already completed, false otherwise
*/
protected boolean getValueById(String initializerId) {
try {
TypedProperties tp = this.configRepository.getConfig(pid);
if (!tp.containsKey(initializerId))
return false;
return "true".equals(tp.get(initializerId).toString());
} catch (IOException | InvalidSyntaxException e) {
log.warn("Can't get property " + initializerId, e);
}
return false;
}
protected void updateById(String initializerId, boolean value) {
log.info("Updating by id {}", initializerId);
try {
TypedProperties tp = this.configRepository.getConfig(pid);
tp.put(initializerId, value ? "true" : "false");
this.configRepository.update(pid, tp);
} catch (IOException | InvalidSyntaxException e) {
log.warn("Can't update property " + initializerId, e);
}
}
protected void updateById(String initializerId, boolean value) {
log.info("Updating by id {}", initializerId);
try {
TypedProperties tp = this.configRepository.getConfig(pid);
tp.put(initializerId, value?"true":"false");
this.configRepository.update(pid, tp);
} catch (IOException | InvalidSyntaxException e) {
log.warn("Can't update property " + initializerId, e);
}
}
}

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* init-manager
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* init-manager
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* init-manager
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* init-manager
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
<parent>
<groupId>ru.entaxy.esb.platform.runtime</groupId>
<artifactId>core</artifactId>
<version>1.9.0</version>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.esb.platform.runtime.core</groupId>
<artifactId>initializer</artifactId>
@ -16,5 +16,6 @@
<module>connection-initializer</module>
<module>storage-initializer</module>
<module>datasources-initializer</module>
<module>artifact-loader</module>
</modules>
</project>

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>storage-initializer</artifactId>
<groupId>ru.entaxy.esb.platform.runtime.core.initializer</groupId>
<version>1.9.0</version>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.esb.platform.runtime.core.initializer.storage.initializer</groupId>

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-cache
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
~~~~~~licensing~~~~~~
storage-cache
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-cache
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
~~~~~~licensing~~~~~~
storage-cache
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -5,7 +5,7 @@
<parent>
<artifactId>storage-initializer</artifactId>
<groupId>ru.entaxy.esb.platform.runtime.core.initializer</groupId>
<version>1.9.0</version>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.esb.platform.runtime.core.initializer.storage.initializer</groupId>

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
~~~~~~licensing~~~~~~
storage-esb_entaxy
==========
Copyright (C) 2020 - 2023 EmDev LLC
Copyright (C) 2020 - 2024 EmDev LLC
==========
You may not use this file except in accordance with the License Terms of the Copyright
Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
<parent>
<artifactId>storage-initializer</artifactId>
<groupId>ru.entaxy.esb.platform.runtime.core.initializer</groupId>
<version>1.9.0</version>
<version>1.10.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* liquibase-updater
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -3,7 +3,7 @@
<parent>
<groupId>ru.entaxy.esb.platform.runtime.core</groupId>
<artifactId>initializer</artifactId>
<version>1.9.0</version>
<version>1.10.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>