Search in sources :

Example 1 with ConsoleInstalledBuildItem

use of io.quarkus.deployment.console.ConsoleInstalledBuildItem in project kogito-runtimes by kiegroup.

the class KogitoDevServicesProcessor method startTrustyServiceDevService.

@SuppressWarnings("unused")
@BuildStep(onlyIf = { GlobalDevServicesConfig.Enabled.class, IsDevelopment.class })
public void startTrustyServiceDevService(final DevServicesConfig devServicesConfig, final BuildProducer<SystemPropertyBuildItem> systemProperties, final BuildProducer<TrustyServiceAvailableBuildItem> trustyServiceAvailableBuildItemBuildProducer, final LaunchModeBuildItem launchMode, final KogitoBuildTimeConfig buildTimeConfig, final List<DevServicesSharedNetworkBuildItem> devServicesSharedNetwork, final Optional<ConsoleInstalledBuildItem> consoleInstalled, final CuratedApplicationShutdownBuildItem applicationShutdown, final LoggingSetupBuildItem loggingSetup) {
    LOGGER.info("Docker Containers configuration...");
    DockerClientFactory.lazyClient().listContainersCmd().exec().forEach(c -> {
        LOGGER.debug("----> Image: " + c.getImage());
        if (Objects.nonNull(c.getNames())) {
            Arrays.stream(c.getNames()).forEach(n -> LOGGER.debug(String.format("----> Name: %s", n)));
        }
        if (Objects.nonNull(c.getLabels())) {
            c.getLabels().forEach((key, value) -> LOGGER.debug(String.format("----> Label: [%s]=[%s]", key, value)));
        }
        LOGGER.debug("----> Ports: " + Arrays.stream(c.getPorts()).map(p -> p.getPrivatePort() + ">>" + p.getPublicPort()).collect(Collectors.joining(", ")));
        LOGGER.debug("----> Network: " + (Objects.isNull(c.getNetworkSettings()) ? "" : c.getNetworkSettings().getNetworks().entrySet().stream().map(n -> String.format("%s=%s [%s]", n.getKey(), n.getValue(), n.getValue().getIpAddress())).collect(Collectors.joining(", "))));
    });
    final TrustyServiceDevServiceConfig configuration = getConfiguration(buildTimeConfig);
    if (closeable != null) {
        boolean shouldShutdown = !configuration.equals(cfg);
        if (!shouldShutdown) {
            // Signal the service is (still) available when DevServices may have restarted but the service not
            trustyServiceAvailableBuildItemBuildProducer.produce(new TrustyServiceAvailableBuildItem());
            return;
        }
        shutdownTrustyService();
        cfg = null;
    }
    final StartupLogCompressor compressor = new StartupLogCompressor((launchMode.isTest() ? "(test) " : "") + "Kogito TrustyService DevService starting:", consoleInstalled, loggingSetup);
    TrustyServiceInstance trustyService = null;
    try {
        trustyService = startTrustyService(configuration, devServicesConfig, launchMode, !devServicesSharedNetwork.isEmpty());
        if (trustyService != null) {
            // Signal the service is available
            trustyServiceAvailableBuildItemBuildProducer.produce(new TrustyServiceAvailableBuildItem());
            closeable = trustyService.getCloseable();
        }
        compressor.close();
    } catch (Throwable t) {
        compressor.closeAndDumpCaptured();
        throw new RuntimeException("Failed to start Kogito TrustyService DevServices", t);
    }
    // Discover TrustyService container
    LOGGER.info("Discovering TrustyService instance...");
    DockerClientFactory.lazyClient().listContainersCmd().exec().stream().filter(container -> isTrustyServiceImage(container, configuration)).findFirst().ifPresent(container -> {
        Optional<Integer> port = Optional.empty();
        Optional<String> ipAddress = Optional.empty();
        final ContainerPort[] containerPorts = container.getPorts();
        final ContainerNetworkSettings networkSettings = container.getNetworkSettings();
        if (Objects.nonNull(containerPorts)) {
            port = Arrays.stream(containerPorts).map(ContainerPort::getPrivatePort).filter(Objects::nonNull).findFirst();
        }
        if (Objects.nonNull(networkSettings)) {
            ipAddress = networkSettings.getNetworks().values().stream().map(ContainerNetwork::getIpAddress).filter(Objects::nonNull).findFirst();
        }
        LOGGER.debug(String.format("[TrustyService] Private Port: %s", port.orElse(0)));
        LOGGER.debug(String.format("[TrustyService] IP Address: %s", ipAddress.orElse("<None>")));
        if (ipAddress.isPresent() && port.isPresent()) {
            final String trustyServiceServer = String.format("http://%s:%s", ipAddress.get(), port.get());
            LOGGER.debug(String.format("Setting System Property '%s' to '%s'", KOGITO_TRUSTY_SERVICE, trustyServiceServer));
            systemProperties.produce(new SystemPropertyBuildItem(KOGITO_TRUSTY_SERVICE, trustyServiceServer));
        }
    });
    // Configure the watch dog
    if (first) {
        first = false;
        final Runnable closeTask = () -> {
            if (closeable != null) {
                shutdownTrustyService();
            }
            first = true;
            closeable = null;
            cfg = null;
        };
        applicationShutdown.addCloseTask(closeTask, true);
    }
    cfg = configuration;
    if (trustyService != null && trustyService.isOwner()) {
        LOGGER.info("DevServices for Kogito TrustyService started at {}", trustyService.getUrl());
    }
}
Also used : Arrays(java.util.Arrays) DockerImageName(org.testcontainers.utility.DockerImageName) DevServicesSharedNetworkBuildItem(io.quarkus.deployment.builditem.DevServicesSharedNetworkBuildItem) LoggerFactory(org.slf4j.LoggerFactory) Container(com.github.dockerjava.api.model.Container) SystemPropertyBuildItem(io.quarkus.deployment.builditem.SystemPropertyBuildItem) LaunchMode(io.quarkus.runtime.LaunchMode) ConsoleInstalledBuildItem(io.quarkus.deployment.console.ConsoleInstalledBuildItem) Supplier(java.util.function.Supplier) IsDevelopment(io.quarkus.deployment.IsDevelopment) IsDockerWorking(io.quarkus.deployment.IsDockerWorking) BuildProducer(io.quarkus.deployment.annotations.BuildProducer) BuildStep(io.quarkus.deployment.annotations.BuildStep) QuarkusDataSourcePassword(org.kie.kogito.tracing.decision.quarkus.deployment.DevServicesConfig.Property.QuarkusDataSourcePassword) CuratedApplicationShutdownBuildItem(io.quarkus.deployment.builditem.CuratedApplicationShutdownBuildItem) HibernateOrmDatabaseGeneration(org.kie.kogito.tracing.decision.quarkus.deployment.DevServicesConfig.Property.HibernateOrmDatabaseGeneration) QuarkusDataSourceDbKind(org.kie.kogito.tracing.decision.quarkus.deployment.DevServicesConfig.Property.QuarkusDataSourceDbKind) ContainerNetworkSettings(com.github.dockerjava.api.model.ContainerNetworkSettings) LoggingSetupBuildItem(io.quarkus.deployment.logging.LoggingSetupBuildItem) KafkaBootstrapServers(org.kie.kogito.tracing.decision.quarkus.deployment.DevServicesConfig.Property.KafkaBootstrapServers) TrustyServiceInMemoryContainer(org.kie.kogito.tracing.decision.quarkus.devservices.TrustyServiceInMemoryContainer) Logger(org.slf4j.Logger) StartupLogCompressor(io.quarkus.deployment.console.StartupLogCompressor) ContainerAddress(io.quarkus.devservices.common.ContainerAddress) TrustyServiceAvailableBuildItem(org.kie.kogito.quarkus.addons.common.deployment.TrustyServiceAvailableBuildItem) GlobalDevServicesConfig(io.quarkus.deployment.dev.devservices.GlobalDevServicesConfig) ContainerLocator(io.quarkus.devservices.common.ContainerLocator) Collectors(java.util.stream.Collectors) QuarkusDataSourceJdbcUrl(org.kie.kogito.tracing.decision.quarkus.deployment.DevServicesConfig.Property.QuarkusDataSourceJdbcUrl) QuarkusDataSourceUserName(org.kie.kogito.tracing.decision.quarkus.deployment.DevServicesConfig.Property.QuarkusDataSourceUserName) Objects(java.util.Objects) List(java.util.List) LaunchModeBuildItem(io.quarkus.deployment.builditem.LaunchModeBuildItem) Closeable(java.io.Closeable) Optional(java.util.Optional) ContainerPort(com.github.dockerjava.api.model.ContainerPort) DockerClientFactory(org.testcontainers.DockerClientFactory) KOGITO_TRUSTY_SERVICE(org.kie.kogito.tracing.decision.TrustyConstants.KOGITO_TRUSTY_SERVICE) ContainerNetwork(com.github.dockerjava.api.model.ContainerNetwork) SystemPropertyBuildItem(io.quarkus.deployment.builditem.SystemPropertyBuildItem) TrustyServiceAvailableBuildItem(org.kie.kogito.quarkus.addons.common.deployment.TrustyServiceAvailableBuildItem) StartupLogCompressor(io.quarkus.deployment.console.StartupLogCompressor) ContainerPort(com.github.dockerjava.api.model.ContainerPort) Objects(java.util.Objects) ContainerNetworkSettings(com.github.dockerjava.api.model.ContainerNetworkSettings) BuildStep(io.quarkus.deployment.annotations.BuildStep)

Example 2 with ConsoleInstalledBuildItem

use of io.quarkus.deployment.console.ConsoleInstalledBuildItem in project quarkus by quarkusio.

the class DevServicesDatasourceProcessor method launchDatabases.

@BuildStep(onlyIfNot = IsNormal.class, onlyIf = GlobalDevServicesConfig.Enabled.class)
DevServicesDatasourceResultBuildItem launchDatabases(CurateOutcomeBuildItem curateOutcomeBuildItem, DockerStatusBuildItem dockerStatusBuildItem, List<DefaultDataSourceDbKindBuildItem> installedDrivers, List<DevServicesDatasourceProviderBuildItem> devDBProviders, DataSourcesBuildTimeConfig dataSourceBuildTimeConfig, LaunchModeBuildItem launchMode, List<DevServicesDatasourceConfigurationHandlerBuildItem> configurationHandlerBuildItems, BuildProducer<DevServicesResultBuildItem> devServicesResultBuildItemBuildProducer, Optional<ConsoleInstalledBuildItem> consoleInstalledBuildItem, CuratedApplicationShutdownBuildItem closeBuildItem, LoggingSetupBuildItem loggingSetupBuildItem, GlobalDevServicesConfig globalDevServicesConfig) {
    // if not and the DB's have already started we just return
    if (databases != null) {
        boolean restartRequired = false;
        if (!restartRequired) {
            for (Map.Entry<String, String> entry : cachedProperties.entrySet()) {
                if (!Objects.equals(entry.getValue(), trim(ConfigProvider.getConfig().getOptionalValue(entry.getKey(), String.class).orElse(null)))) {
                    restartRequired = true;
                    break;
                }
            }
        }
        if (!restartRequired) {
            // devservices properties may have been added
            for (var name : ConfigProvider.getConfig().getPropertyNames()) {
                if (name.startsWith("quarkus.datasource.") && name.contains(".devservices.") && !cachedProperties.containsKey(name)) {
                    restartRequired = true;
                    break;
                }
            }
        }
        if (!restartRequired) {
            for (RunningDevService database : databases) {
                devServicesResultBuildItemBuildProducer.produce(database.toBuildItem());
            }
            // keep the previous behaviour of producing DevServicesDatasourceResultBuildItem only when the devservice first starts.
            return null;
        }
        for (Closeable i : databases) {
            try {
                i.close();
            } catch (Throwable e) {
                log.error("Failed to stop database", e);
            }
        }
        databases = null;
        cachedProperties = null;
    }
    DevServicesDatasourceResultBuildItem.DbResult defaultResult;
    Map<String, DevServicesDatasourceResultBuildItem.DbResult> namedResults = new HashMap<>();
    // now we need to figure out if we need to launch some databases
    // note that because we run in dev and test mode only we know the runtime
    // config at build time, as they both execute in the same JVM
    // to keep things simpler for now we are only going to support this for the default datasource
    // support for named datasources will come later
    Map<String, String> propertiesMap = new HashMap<>();
    List<RunningDevService> runningDevServices = new ArrayList<>();
    Map<String, List<DevServicesDatasourceConfigurationHandlerBuildItem>> configHandlersByDbType = configurationHandlerBuildItems.stream().collect(Collectors.toMap(DevServicesDatasourceConfigurationHandlerBuildItem::getDbKind, Collections::singletonList, (configurationHandlerBuildItems1, configurationHandlerBuildItems2) -> {
        List<DevServicesDatasourceConfigurationHandlerBuildItem> ret = new ArrayList<>();
        ret.addAll(configurationHandlerBuildItems1);
        ret.addAll(configurationHandlerBuildItems2);
        return ret;
    }));
    Map<String, DevServicesDatasourceProvider> devDBProviderMap = devDBProviders.stream().collect(Collectors.toMap(DevServicesDatasourceProviderBuildItem::getDatabase, DevServicesDatasourceProviderBuildItem::getDevServicesProvider));
    RunningDevService defaultDevService = startDevDb(null, curateOutcomeBuildItem, installedDrivers, !dataSourceBuildTimeConfig.namedDataSources.isEmpty(), devDBProviderMap, dataSourceBuildTimeConfig.defaultDataSource, configHandlersByDbType, propertiesMap, dockerStatusBuildItem, launchMode.getLaunchMode(), consoleInstalledBuildItem, loggingSetupBuildItem, globalDevServicesConfig);
    if (defaultDevService != null) {
        runningDevServices.add(defaultDevService);
    }
    defaultResult = toDbResult(defaultDevService);
    for (Map.Entry<String, DataSourceBuildTimeConfig> entry : dataSourceBuildTimeConfig.namedDataSources.entrySet()) {
        RunningDevService namedDevService = startDevDb(entry.getKey(), curateOutcomeBuildItem, installedDrivers, true, devDBProviderMap, entry.getValue(), configHandlersByDbType, propertiesMap, dockerStatusBuildItem, launchMode.getLaunchMode(), consoleInstalledBuildItem, loggingSetupBuildItem, globalDevServicesConfig);
        if (namedDevService != null) {
            runningDevServices.add(namedDevService);
            namedResults.put(entry.getKey(), toDbResult(namedDevService));
        }
    }
    if (first) {
        first = false;
        Runnable closeTask = new Runnable() {

            @Override
            public void run() {
                if (databases != null) {
                    for (Closeable i : databases) {
                        try {
                            i.close();
                        } catch (Throwable t) {
                            log.error("Failed to stop database", t);
                        }
                    }
                }
                first = true;
                databases = null;
                cachedProperties = null;
            }
        };
        closeBuildItem.addCloseTask(closeTask, true);
    }
    databases = runningDevServices;
    cachedProperties = propertiesMap;
    for (RunningDevService database : databases) {
        devServicesResultBuildItemBuildProducer.produce(database.toBuildItem());
    }
    return new DevServicesDatasourceResultBuildItem(defaultResult, namedResults);
}
Also used : IsNormal(io.quarkus.deployment.IsNormal) DataSourcesBuildTimeConfig(io.quarkus.datasource.runtime.DataSourcesBuildTimeConfig) DevServicesDatasourceProvider(io.quarkus.datasource.deployment.spi.DevServicesDatasourceProvider) Logger(org.jboss.logging.Logger) LaunchMode(io.quarkus.runtime.LaunchMode) HashMap(java.util.HashMap) DevServicesDatasourceConfigurationHandlerBuildItem(io.quarkus.datasource.deployment.spi.DevServicesDatasourceConfigurationHandlerBuildItem) RunningDevService(io.quarkus.deployment.builditem.DevServicesResultBuildItem.RunningDevService) ConsoleInstalledBuildItem(io.quarkus.deployment.console.ConsoleInstalledBuildItem) CurateOutcomeBuildItem(io.quarkus.deployment.pkg.builditem.CurateOutcomeBuildItem) DevServicesDatasourceResultBuildItem(io.quarkus.datasource.deployment.spi.DevServicesDatasourceResultBuildItem) BuildProducer(io.quarkus.deployment.annotations.BuildProducer) ArrayList(java.util.ArrayList) BuildStep(io.quarkus.deployment.annotations.BuildStep) CuratedApplicationShutdownBuildItem(io.quarkus.deployment.builditem.CuratedApplicationShutdownBuildItem) Map(java.util.Map) LoggingSetupBuildItem(io.quarkus.deployment.logging.LoggingSetupBuildItem) DevServicesResultBuildItem(io.quarkus.deployment.builditem.DevServicesResultBuildItem) StartupLogCompressor(io.quarkus.deployment.console.StartupLogCompressor) GlobalDevServicesConfig(io.quarkus.deployment.dev.devservices.GlobalDevServicesConfig) DataSourceBuildTimeConfig(io.quarkus.datasource.runtime.DataSourceBuildTimeConfig) Collectors(java.util.stream.Collectors) DevServicesDatasourceProviderBuildItem(io.quarkus.datasource.deployment.spi.DevServicesDatasourceProviderBuildItem) Objects(java.util.Objects) List(java.util.List) ConfigProvider(org.eclipse.microprofile.config.ConfigProvider) LaunchModeBuildItem(io.quarkus.deployment.builditem.LaunchModeBuildItem) Closeable(java.io.Closeable) DefaultDataSourceDbKindBuildItem(io.quarkus.datasource.deployment.spi.DefaultDataSourceDbKindBuildItem) Optional(java.util.Optional) DockerStatusBuildItem(io.quarkus.deployment.builditem.DockerStatusBuildItem) Collections(java.util.Collections) HashMap(java.util.HashMap) Closeable(java.io.Closeable) ArrayList(java.util.ArrayList) DevServicesDatasourceProvider(io.quarkus.datasource.deployment.spi.DevServicesDatasourceProvider) RunningDevService(io.quarkus.deployment.builditem.DevServicesResultBuildItem.RunningDevService) ArrayList(java.util.ArrayList) List(java.util.List) DevServicesDatasourceResultBuildItem(io.quarkus.datasource.deployment.spi.DevServicesDatasourceResultBuildItem) DataSourceBuildTimeConfig(io.quarkus.datasource.runtime.DataSourceBuildTimeConfig) HashMap(java.util.HashMap) Map(java.util.Map) BuildStep(io.quarkus.deployment.annotations.BuildStep)

Aggregations

BuildProducer (io.quarkus.deployment.annotations.BuildProducer)2 BuildStep (io.quarkus.deployment.annotations.BuildStep)2 CuratedApplicationShutdownBuildItem (io.quarkus.deployment.builditem.CuratedApplicationShutdownBuildItem)2 LaunchModeBuildItem (io.quarkus.deployment.builditem.LaunchModeBuildItem)2 ConsoleInstalledBuildItem (io.quarkus.deployment.console.ConsoleInstalledBuildItem)2 StartupLogCompressor (io.quarkus.deployment.console.StartupLogCompressor)2 GlobalDevServicesConfig (io.quarkus.deployment.dev.devservices.GlobalDevServicesConfig)2 LoggingSetupBuildItem (io.quarkus.deployment.logging.LoggingSetupBuildItem)2 LaunchMode (io.quarkus.runtime.LaunchMode)2 Closeable (java.io.Closeable)2 List (java.util.List)2 Objects (java.util.Objects)2 Optional (java.util.Optional)2 Collectors (java.util.stream.Collectors)2 Container (com.github.dockerjava.api.model.Container)1 ContainerNetwork (com.github.dockerjava.api.model.ContainerNetwork)1 ContainerNetworkSettings (com.github.dockerjava.api.model.ContainerNetworkSettings)1 ContainerPort (com.github.dockerjava.api.model.ContainerPort)1 DefaultDataSourceDbKindBuildItem (io.quarkus.datasource.deployment.spi.DefaultDataSourceDbKindBuildItem)1 DevServicesDatasourceConfigurationHandlerBuildItem (io.quarkus.datasource.deployment.spi.DevServicesDatasourceConfigurationHandlerBuildItem)1