001/*-
002 * #%L
003 * Smile CDR - CDR
004 * %%
005 * Copyright (C) 2016 - 2026 Smile CDR, Inc.
006 * %%
007 * All rights reserved.
008 * #L%
009 */
010package ca.cdr.test.extensions;
011
012import ca.cdr.test.app.harness.api.HarnessContext;
013import ca.cdr.test.app.harness.api.SmileHarness;
014import ca.cdr.test.app.harness.impl.LocalhostSmileHarness;
015import ca.cdr.test.util.PropertiesTestUtil;
016import ca.cdr.test.util.UrlPathUtil;
017import jakarta.annotation.Nonnull;
018import org.apache.commons.lang3.StringUtils;
019import org.slf4j.Logger;
020import org.slf4j.LoggerFactory;
021import org.testcontainers.containers.GenericContainer;
022import org.testcontainers.containers.output.OutputFrame;
023import org.testcontainers.containers.output.WaitingConsumer;
024import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy;
025import org.testcontainers.utility.DockerImageName;
026import org.testcontainers.utility.MountableFile;
027
028import java.io.File;
029import java.io.FileInputStream;
030import java.io.IOException;
031import java.nio.file.Files;
032import java.nio.file.Path;
033import java.nio.file.Paths;
034import java.time.Duration;
035import java.util.ArrayList;
036import java.util.Arrays;
037import java.util.HashMap;
038import java.util.List;
039import java.util.Map;
040import java.util.Optional;
041import java.util.Properties;
042import java.util.stream.Collectors;
043
044/**
045 * SmileCdrContainer is a container abstraction for orchestrating Smile CDR instances
046 * within Docker environments.
047 * <p>
048 * Instances of this container allow for flexible customization and configuration of
049 * Smile CDR images, including properties file specifications, logback configurations,
050 * and support for customer JAR files. It supports smooth integration and automated
051 * provisioning of Smile CDR services for testing and development environments.
052 * <p>
053 * The design facilitates:
054 * - Configuration of Smile CDR version and the corresponding Docker image.
055 * - Mounting of custom resources such as properties files, logback configurations, or JARs.
056 * - Automatic setup of exposed ports based on specified or default configurations.
057 * - Log consumption to aid in debugging and diagnostics during container runtime.
058 * - Ensuring modular support with organized port mapping and harness configuration.
059 * <p>
060 * This class was generated partly with the help of Claude Sonnet 3.7
061 */
062public class SmileCdrContainer extends GenericContainer<SmileCdrContainer> {
063
064        private static final Logger ourLog = LoggerFactory.getLogger(SmileCdrContainer.class);
065        private static final String DEFAULT_REGISTRY = "docker.smilecdr.com";
066        private static final String DEFAULT_IMAGE = "smilecdr";
067        private static final String DEFAULT_TAG = "latest";
068        private static final String HOST_NETWORK_MODE = "host";
069        private static final String CDR_HOME = "/home/smile/smilecdr";
070        private static final String DEFAULT_ADMIN_JSON_MODULE_ID = "admin_json";
071        private static final String CLASSPATH_PREFIX = "classpath:";
072        private static final String FILE_PREFIX = "file:";
073        private static final DockerImageName DEFAULT_DOCKER_IMAGE_NAME =
074                        DockerImageName.parse(DEFAULT_REGISTRY + "/" + DEFAULT_IMAGE + ":" + DEFAULT_TAG);
075
076        private final Map<String, Map<String, Integer>> myPortValues = new HashMap<>();
077        private String myResolvedPropertiesFileLocation;
078        private HarnessContext myHarnessContext;
079        private LocalhostSmileHarness myHarness;
080        private String myCustomPropertiesFileLocation;
081        private Path myCustomPropertiesFilePath;
082        private String myCustomLogbackFile;
083        private Path myCustomLogbackFilePath;
084        private List<String> myCustomerJarNames;
085        private boolean myDebugEnabled = false;
086        private boolean myDebugSuspendUntilDebuggerAttached = true;
087        private static final int DEBUG_PORT = 5005;
088
089        public SmileCdrContainer() {
090                this(DEFAULT_DOCKER_IMAGE_NAME);
091        }
092
093        /**
094         * Use this constructor to change the version of Smile CDR, but use Smile's container registry.
095         */
096        public SmileCdrContainer(String theSmileCdrVersion) {
097                this(new DockerImageName(DEFAULT_REGISTRY + "/" + DEFAULT_IMAGE + ":" + theSmileCdrVersion));
098        }
099
100        /**
101         * Use this constructor to provide a completely custom Docker Image Name to use. Use this if you need to use your own private registry
102         */
103        public SmileCdrContainer(DockerImageName imageName) {
104                super(imageName);
105                // Wait for startup completion (success or failure)
106                LogMessageWaitStrategy logMessageWaitStrategy = new LogMessageWaitStrategy();
107                logMessageWaitStrategy
108                                .withRegEx(".*(Smile, we're up and running|Smile started with errors).*")
109                                .withStartupTimeout(Duration.ofMinutes(3));
110                waitingFor(logMessageWaitStrategy);
111
112                // Also output logs to stdout to ensure they appear in test output
113                withLogConsumer(new WaitingConsumer() {
114                        @Override
115                        public void accept(OutputFrame theFrame) {
116                                System.out.printf("Container[%s]: %s", getContainerName(), theFrame.getUtf8String());
117                        }
118                });
119        }
120
121        @Override
122        public void start() {
123                copyCustomLogbackConfiguration();
124
125                // Copy JAR files from cdr-interceptor-starterproject/target to the container
126                copyCustomerJars();
127                copyPropertiesFileAndResolveReferences();
128
129                if (myDebugEnabled) {
130                        ourLog.info("Debug mode enabled - container is accessible for debuggers on port {}", DEBUG_PORT);
131                        if (!isHostNetwork()) {
132                                addFixedExposedPort(DEBUG_PORT, DEBUG_PORT);
133                        }
134                        String jvmArgs = buildJvmArgs();
135                        ourLog.info("JVMARGS is now set to: {}", jvmArgs);
136                        withEnv("JVMARGS", jvmArgs);
137                        if (myDebugSuspendUntilDebuggerAttached) {
138                                ourLog.warn("==========================================");
139                                ourLog.warn("DEBUG MODE(suspend): Container will wait for debugger");
140                                ourLog.warn("Connect your IDE debugger to: localhost:{}", DEBUG_PORT);
141                                ourLog.warn("Container will resume after debugger attaches");
142                                ourLog.warn("==========================================");
143                        }
144                }
145                super.start();
146        }
147
148        private void copyCustomLogbackConfiguration() {
149                MountableFile mountableFile;
150                if (myCustomLogbackFilePath != null) {
151                        ourLog.info("Custom logback file provided, using it. [file={}]", myCustomLogbackFilePath);
152                        mountableFile = MountableFile.forHostPath(myCustomLogbackFilePath);
153                } else if (!StringUtils.isBlank(myCustomLogbackFile)) {
154                        ourLog.info("Custom logback file provided, using it. [file={}]", myCustomLogbackFile);
155                        mountableFile = MountableFile.forClasspathResource(myCustomLogbackFile);
156                } else {
157                        ourLog.info(
158                                        "No custom logback file provided, using default logback file. [file={}]",
159                                        "/all-troubleshooters-enabled-logback.xml");
160                        mountableFile = MountableFile.forClasspathResource("/all-troubleshooters-enabled-logback.xml");
161                }
162                withCopyFileToContainer(mountableFile, CDR_HOME + "/customerlib/logback-smile-custom.xml");
163        }
164
165        private void copyPropertiesFileAndResolveReferences() {
166                MountableFile mountableFile = resolvePropertiesFile();
167                withCopyFileToContainer(mountableFile, CDR_HOME + "/classes/cdr-config-Master.properties");
168
169                myResolvedPropertiesFileLocation = mountableFile.getResolvedPath();
170                exposePortsFromPropertiesFile(mountableFile.getResolvedPath());
171                bootstrapContainerFilesFromProperties(mountableFile.getResolvedPath());
172        }
173
174        private String buildJvmArgs() {
175                return new StringBuilder()
176                                .append("-agentlib:jdwp=transport=dt_socket,server=y,suspend=")
177                                .append(myDebugSuspendUntilDebuggerAttached ? "y" : "n")
178                                .append(",address=*:")
179                                .append(DEBUG_PORT)
180                                .toString();
181        }
182
183        private void bootstrapContainerFilesFromProperties(String thePropertiesFileLocation) {
184                try {
185                        // Read the properties file
186                        Properties properties = new Properties();
187                        try (FileInputStream fis = new FileInputStream(thePropertiesFileLocation)) {
188                                properties.load(fis);
189                        }
190
191                        // Look for classpath and file references in property values
192                        for (String key : properties.stringPropertyNames()) {
193                                String value = properties.getProperty(key);
194                                if (value != null && (value.startsWith(CLASSPATH_PREFIX) || value.startsWith(FILE_PREFIX))) {
195                                        copyReferencedFileToContainer(value);
196                                }
197                        }
198                } catch (IOException e) {
199                        throw new IllegalArgumentException(
200                                        "Failed to process properties file for bootstrap files: " + thePropertiesFileLocation, e);
201                }
202        }
203
204        private void copyReferencedFileToContainer(String theReference) {
205                String resourcePath;
206                if (theReference.startsWith(CLASSPATH_PREFIX)) {
207                        resourcePath = StringUtils.stripStart(theReference.substring(CLASSPATH_PREFIX.length()), "/");
208                } else if (theReference.startsWith(FILE_PREFIX)) {
209                        String filePath = theReference.substring(FILE_PREFIX.length());
210                        if (copyHostFileToContainer(filePath)) {
211                                return;
212                        }
213                        resourcePath = StringUtils.stripStart(filePath, "/");
214                } else {
215                        return;
216                }
217
218                String containerPath = containerPathForReference(theReference);
219                try {
220                        MountableFile mountableFile = MountableFile.forClasspathResource(resourcePath);
221                        withCopyFileToContainer(mountableFile, containerPath);
222                        ourLog.info("Copied classpath resource to container: {} -> {}", resourcePath, containerPath);
223                } catch (IllegalArgumentException e) {
224                        // Many references name resources that ship inside the Smile CDR image itself.
225                        ourLog.info("Referenced file is not on the test classpath, leaving it to the image: {}", theReference);
226                }
227        }
228
229        /**
230         * Copies a {@code file:} reference from the host, to the path Smile CDR will read it from:
231         * the same absolute path, or a relative path resolved against the Smile CDR home directory.
232         * Relative paths are looked up on the host relative to the working directory.
233         *
234         * @return true if the file was found on the host
235         */
236        private boolean copyHostFileToContainer(String theFilePath) {
237                Path hostPath = Paths.get(theFilePath);
238                if (!Files.exists(hostPath)) {
239                        return false;
240                }
241                String containerPath = fileReferenceContainerPath(theFilePath);
242                withCopyFileToContainer(MountableFile.forHostPath(hostPath), containerPath);
243                ourLog.info("Copied host file to container: {} -> {}", hostPath, containerPath);
244                return true;
245        }
246
247        /**
248         * Where Smile CDR reads a {@code classpath:} or {@code file:} reference from. A {@code file:}
249         * reference lands there whether it was found on the host or, failing that, on the classpath.
250         *
251         * @throws IllegalArgumentException for a value that is neither kind of reference
252         */
253        static String containerPathForReference(String theReference) {
254                if (theReference.startsWith(CLASSPATH_PREFIX)) {
255                        return CDR_HOME + "/classes/"
256                                        + StringUtils.stripStart(theReference.substring(CLASSPATH_PREFIX.length()), "/");
257                }
258                if (theReference.startsWith(FILE_PREFIX)) {
259                        return fileReferenceContainerPath(theReference.substring(FILE_PREFIX.length()));
260                }
261                throw new IllegalArgumentException("Not a classpath: or file: reference: " + theReference);
262        }
263
264        /**
265         * Where Smile CDR reads a {@code file:} reference from: the same absolute path, or a relative path
266         * resolved against the Smile CDR home directory.
267         */
268        private static String fileReferenceContainerPath(String theFilePath) {
269                return Paths.get(theFilePath).isAbsolute() ? theFilePath : CDR_HOME + "/" + theFilePath;
270        }
271
272        private MountableFile resolvePropertiesFile() {
273                if (myCustomPropertiesFilePath != null) {
274                        ourLog.info("Custom properties file provided, using it. [file={}]", myCustomPropertiesFilePath);
275                        return MountableFile.forHostPath(myCustomPropertiesFilePath);
276                }
277                if (StringUtils.isBlank(myCustomPropertiesFileLocation)) {
278                        ourLog.info(
279                                        "No custom properties file provided, using default properties file. [file={}]",
280                                        "/cdr-config-fallback.properties");
281                        return MountableFile.forClasspathResource("/cdr-config-fallback.properties");
282                }
283                ourLog.info("Custom properties file provided, using it. [file={}]", myCustomPropertiesFileLocation);
284                return MountableFile.forClasspathResource(myCustomPropertiesFileLocation);
285        }
286
287        /**
288         * Binds the target/classes and target/test-classes directories into the container's `/classes` directory.
289         * Only mounts directories if they exist and are non-empty.
290         * @return the SmileCdrContainer.
291         */
292        public SmileCdrContainer withBoundProjectClasspath() {
293                String root = Paths.get(".").toAbsolutePath().normalize().toString();
294
295                Path classesPath = Paths.get(root, "target", "classes");
296                if (Files.exists(classesPath) && isDirectoryNonEmpty(classesPath)) {
297                        MountableFile mountableFile = MountableFile.forHostPath(classesPath.toString());
298                        withCopyFileToContainer(mountableFile, "/home/smile/smilecdr/classes");
299                        ourLog.info("Mounted target/classes directory to container");
300                } else {
301                        ourLog.info("Skipping target/classes mount - directory does not exist or is empty");
302                }
303
304                Path testClassesPath = Paths.get(root, "target", "test-classes");
305                if (Files.exists(testClassesPath) && isDirectoryNonEmpty(testClassesPath)) {
306                        MountableFile testMountableFile = MountableFile.forHostPath(testClassesPath.toString());
307                        withCopyFileToContainer(testMountableFile, "/home/smile/smilecdr/classes");
308                        ourLog.info("Mounted target/test-classes directory to container");
309                } else {
310                        ourLog.info("Skipping target/test-classes mount - directory does not exist or is empty");
311                }
312
313                return this;
314        }
315
316        /**
317         * Checks if a directory is non-empty by attempting to read at least one entry.
318         * @param thePath the directory path to check
319         * @return true if the directory contains at least one file or subdirectory, false otherwise
320         */
321        private boolean isDirectoryNonEmpty(Path thePath) {
322                try (var stream = Files.list(thePath)) {
323                        return stream.findFirst().isPresent();
324                } catch (IOException e) {
325                        ourLog.warn("Error checking if directory is non-empty: {}", thePath, e);
326                        return false;
327                }
328        }
329
330        public SmileCdrContainer withPreseedFiles(String... filesToMount) {
331                for (String fileToMount : filesToMount) {
332                        MountableFile mountableFile = MountableFile.forClasspathResource(fileToMount);
333                        withCopyFileToContainer(mountableFile, "/home/smile/smilecdr/classes/config_seeding/");
334                }
335                return this;
336        }
337
338        /**
339         * Sets the {@link HarnessContext} the harness is built from. Discards any harness already handed
340         * out, so that a context set after the first {@link #getHarness()} still takes effect rather
341         * than being silently ignored.
342         */
343        public synchronized @Nonnull SmileCdrContainer withCustomHarnessContext(@Nonnull HarnessContext theHarnessContext) {
344                closeHarness();
345                myHarnessContext = theHarnessContext;
346                return this;
347        }
348
349        /**
350         * Uses a properties file from the classpath as the container's {@code cdr-config-Master.properties}.
351         */
352        public SmileCdrContainer withPropertiesFile(String thePropertiesFileLocation) {
353                myCustomPropertiesFileLocation = thePropertiesFileLocation;
354                myCustomPropertiesFilePath = null;
355                return this;
356        }
357
358        /**
359         * Uses a properties file from the host filesystem as the container's
360         * {@code cdr-config-Master.properties}, for configuration that is generated or selected at runtime
361         * rather than packaged on the test classpath.
362         */
363        public SmileCdrContainer withPropertiesFile(@Nonnull Path thePropertiesFile) {
364                myCustomPropertiesFilePath = thePropertiesFile;
365                myCustomPropertiesFileLocation = null;
366                return this;
367        }
368
369        public SmileCdrContainer withCustomLogback(String theCustomLogbackLocation) {
370                requireNoCustomLogback();
371                myCustomLogbackFile = theCustomLogbackLocation;
372                return this;
373        }
374
375        /**
376         * Uses a logback configuration from the host filesystem as the container's
377         * {@code customerlib/logback-smile-custom.xml}.
378         */
379        public SmileCdrContainer withCustomLogback(@Nonnull Path theCustomLogbackFile) {
380                requireNoCustomLogback();
381                myCustomLogbackFilePath = theCustomLogbackFile;
382                return this;
383        }
384
385        private void requireNoCustomLogback() {
386                if (!StringUtils.isBlank(myCustomLogbackFile) || myCustomLogbackFilePath != null) {
387                        throw new IllegalStateException("A custom logback file has already been set");
388                }
389        }
390
391        public SmileCdrContainer withAllTroubleshootingLogsEnabled() {
392                requireNoCustomLogback();
393                myCustomLogbackFile = "/all-troubleshooters-enabled-logback.xml";
394                return this;
395        }
396
397        /**
398         * Specifies which JAR files from the cdr-interceptor-starterproject's target folder should be copied
399         * into the SmileCdrContainer at /home/smile/smilecdr/customerlib/.
400         * <p>
401         * First looks in the classpath for a jar with a given name. If it does not find one,
402         * it also looks in the target/ directory. If it still doesn't find one, then it fails.
403         *
404         * @param theJarNames A comma-separated list of JAR filenames to copy. If null or empty, all JAR files
405         *                    in the target directory will be copied.
406         * @return This container instance for method chaining
407         */
408        public SmileCdrContainer withCustomerJars(String... theJarNames) {
409                if (theJarNames != null && theJarNames.length > 0) {
410                        myCustomerJarNames = Arrays.stream(theJarNames)
411                                        .map(String::trim)
412                                        .filter(s -> !s.isEmpty())
413                                        .collect(Collectors.toList());
414
415                        ourLog.info("Registered {} JAR file(s) to be mounted into customerlib", myCustomerJarNames.size());
416                }
417                return this;
418        }
419
420        /**
421         * Enables remote debugging for the Smile CDR instance running in this container.
422         * When enabled, the container will expose port 5005 (fixed mapping) and wait for a debugger to attach
423         * before completing startup (suspend=y).
424         *
425         * <h3>How to Connect IntelliJ IDEA Debugger:</h3>
426         * <ol>
427         *   <li>Run → Edit Configurations → Add New → Remote JVM Debug</li>
428         *   <li>Set Host: localhost (or container host)</li>
429         *   <li>Set Port: 5005 (always fixed to this port)</li>
430         *   <li>Set Debugger mode: Attach to remote JVM</li>
431         *   <li>Click Debug - the container will resume startup once debugger connects</li>
432         * </ol>
433         *
434         * <h3>Example Usage:</h3>
435         * <pre>
436         * {@code
437         * @Container
438         * SmileCdrContainer container = new SmileCdrContainer()
439         *     .withPropertiesFile("/my-config.properties")
440         *     .withDebugEnabled();
441         *
442         * // Port 5005 is always used - no need to query for mapped port
443         * // Just connect your debugger to localhost:5005
444         * }
445         * </pre>
446         *
447         * <p><strong>IMPORTANT:</strong> The container will pause during startup until a debugger
448         * connects. This is intentional to allow setting breakpoints before code execution begins.
449         * Port 5005 must be available on the host machine.</p>
450         *
451         * @return This container instance for method chaining
452         */
453        public SmileCdrContainer withDebugEnabled() {
454                return withDebugEnabled(true);
455        }
456
457        /**
458         * Enables remote debugging for the Smile CDR instance running in this container.
459         * When enabled, the container will expose port 5005 (fixed mapping).
460         *
461         * - If `theSuspendUntilDebuggerAttached` is true, the container will pause until a debugger is connected.
462         * - If `theSuspendUntilDebuggerAttached` is false, the container will boot without waiting for the debugger.
463         *
464         *
465         * <h3>How to Connect IntelliJ IDEA Debugger:</h3>
466         * <ol>
467         *   <li>Run → Edit Configurations → Add New → Remote JVM Debug</li>
468         *   <li>Set Host: localhost (or container host)</li>
469         *   <li>Set Port: 5005 (always fixed to this port)</li>
470         *   <li>Set Debugger mode: Attach to remote JVM</li>
471         *   <li>Click Debug - the container will resume startup once debugger connects</li>
472         * </ol>
473         *
474         * <h3>Example Usage:</h3>
475         * <pre>
476         * {@code
477         * @Container
478         * SmileCdrContainer container = new SmileCdrContainer()
479         *     .withPropertiesFile("/my-config.properties")
480         *     .withDebugEnabled(false);
481         *
482         * // Port 5005 is always used - no need to query for mapped port
483         * // Just connect your debugger to localhost:5005
484         * }
485         * </pre>
486         *
487         * <p><strong>IMPORTANT:</strong> If you have set `theSuspendUntilDebuggerAttached` to True,
488         * the container will pause during startup until a debugger
489         * connects. This is intentional to allow setting breakpoints before code execution begins.
490         * Port 5005 must be available on the host machine.</p>
491         *
492         * @param theSuspendUntilDebuggerAttached if set to true, blocks the container startup until a debugger connects.
493         *
494         * @return This container instance for method chaining
495         */
496        public SmileCdrContainer withDebugEnabled(boolean theSuspendUntilDebuggerAttached) {
497                myDebugEnabled = true;
498                myDebugSuspendUntilDebuggerAttached = theSuspendUntilDebuggerAttached;
499                return this;
500        }
501
502        private void exposePortsFromPropertiesFile(String thePropertiesFileLocation) {
503                Map<String, Map<String, Integer>> portsByModuleType =
504                                PropertiesTestUtil.loadPortsFromPropertiesFile(thePropertiesFileLocation);
505
506                // On the host network the modules bind host ports directly; Docker maps nothing, so
507                // exposing ports would leave Testcontainers waiting for mappings that never appear.
508                if (!isHostNetwork()) {
509                        for (Map<String, Integer> modulePortMap : portsByModuleType.values()) {
510                                for (Integer portValue : modulePortMap.values()) {
511                                        addExposedPort(portValue);
512                                }
513                        }
514                }
515
516                // Merge the loaded ports into myPortValues
517                for (Map.Entry<String, Map<String, Integer>> entry : portsByModuleType.entrySet()) {
518                        String moduleType = entry.getKey();
519                        Map<String, Integer> modulePorts = entry.getValue();
520                        myPortValues.computeIfAbsent(moduleType, k -> new HashMap<>()).putAll(modulePorts);
521                }
522        }
523
524        /**
525         * Returns this container's harness, creating it on first call.
526         * <p>
527         * The harness is cached because it owns an HTTP connection pool and a cookie store: handing
528         * out a fresh one per call would mean each caller got its own session, which any multi-request
529         * login flow depends on sharing. The cached harness is closed and discarded when the container
530         * stops, so a restarted container gets a harness bound to its new port mapping.
531         * <p>
532         * A harness reads the node's modules and their ports once, when it is built. A test that adds,
533         * removes or re-ports a module through the Admin JSON API must therefore call
534         * {@link #refreshHarness()}; calling {@code getHarness()} again returns the same harness, still
535         * holding the configuration from before the change.
536         * <p>
537         * A harness a caller closed itself is replaced rather than handed back: {@link SmileHarness} is
538         * {@link AutoCloseable}, so a try-with-resources around this call would otherwise shut the
539         * connection pool and leave every later call returning a harness whose every request fails.
540         */
541        public synchronized @Nonnull SmileHarness getHarness() {
542                if (myHarness != null && myHarness.isClosed()) {
543                        myHarness = null;
544                }
545                if (myHarness == null) {
546                        if (myHarnessContext == null) {
547                                // Find the admin JSON port from the discovered ports
548                                Optional<Map.Entry<String, Integer>> adminJsonModule = adminJsonModule(myPortValues.get("ADMIN_JSON"));
549                                Integer adminJsonPort = null;
550                                String adminJsonContextPath = "";
551                                if (adminJsonModule.isPresent()) {
552                                        Map.Entry<String, Integer> adminJson = adminJsonModule.get();
553                                        adminJsonPort = adminJson.getValue();
554                                        if (myResolvedPropertiesFileLocation != null) {
555                                                adminJsonContextPath = UrlPathUtil.normalizeContextPath(PropertiesTestUtil.loadContextPath(
556                                                                myResolvedPropertiesFileLocation, adminJson.getKey()));
557                                        }
558                                }
559                                myHarnessContext = new HarnessContext(
560                                                "http", this.getHost(), adminJsonPort, "admin", "password", adminJsonContextPath);
561                        }
562                        myHarness = new LocalhostSmileHarness(myHarnessContext, getPortMapping());
563                }
564                return myHarness;
565        }
566
567        /**
568         * The Admin JSON module the harness is built against when the properties file configures several:
569         * {@code admin_json} if present, otherwise the lowest module ID. A properties file has no order
570         * of its own to fall back on.
571         */
572        static Optional<Map.Entry<String, Integer>> adminJsonModule(Map<String, Integer> theAdminJsonPorts) {
573                if (theAdminJsonPorts == null || theAdminJsonPorts.isEmpty()) {
574                        return Optional.empty();
575                }
576                if (theAdminJsonPorts.containsKey(DEFAULT_ADMIN_JSON_MODULE_ID)) {
577                        return Optional.of(
578                                        Map.entry(DEFAULT_ADMIN_JSON_MODULE_ID, theAdminJsonPorts.get(DEFAULT_ADMIN_JSON_MODULE_ID)));
579                }
580                return theAdminJsonPorts.entrySet().stream()
581                                .min(Map.Entry.comparingByKey())
582                                .map(e -> Map.entry(e.getKey(), e.getValue()));
583        }
584
585        /**
586         * Discards the cached harness and builds a replacement, which rediscovers the node's modules and
587         * ports. Call this after changing module configuration through the Admin JSON API.
588         * <p>
589         * Any session held by the old harness ends with it, and any reference still pointing at it is
590         * dead — use the returned harness rather than the one you were holding.
591         *
592         * @return the replacement harness, already bound to the node's current configuration
593         */
594        public synchronized @Nonnull SmileHarness refreshHarness() {
595                closeHarness();
596                return getHarness();
597        }
598
599        @Override
600        public void stop() {
601                closeHarness();
602                super.stop();
603        }
604
605        private synchronized void closeHarness() {
606                if (myHarness == null) {
607                        return;
608                }
609                try {
610                        myHarness.close();
611                } catch (RuntimeException e) {
612                        // Never let a teardown failure mask whatever the caller was actually doing.
613                        ourLog.warn("Failed to close the harness", e);
614                } finally {
615                        myHarness = null;
616                }
617        }
618
619        /**
620         * Maps each port a module listens on inside the container to the port it is reachable on from the
621         * host. On the host network ({@code withNetworkMode("host")}) every port maps to itself.
622         */
623        public Map<Integer, Integer> getPortMapping() {
624                if (isHostNetwork()) {
625                        return myPortValues.values().stream()
626                                        .flatMap(modulePorts -> modulePorts.values().stream())
627                                        .distinct()
628                                        .collect(Collectors.toMap(port -> port, port -> port));
629                }
630                return getExposedPorts().stream().collect(Collectors.toMap(port -> port, this::getMappedPort));
631        }
632
633        private boolean isHostNetwork() {
634                return HOST_NETWORK_MODE.equals(getNetworkMode());
635        }
636
637        /**
638         * Gets the port values organized by Module Type and Module ID.
639         *
640         * @return A map where the key is the Module Type and the value is a map of Module ID to port
641         */
642        public Map<String, Map<String, Integer>> getPortValuesByModuleType() {
643                return new HashMap<>(myPortValues);
644        }
645
646        /**
647         * Copies JAR files from the cdr-interceptor-starterproject's target directory to the container.
648         * If myCustomerJarNames is not null, only the specified JAR files will be copied.
649         * Otherwise, all JAR files in the target directory will be copied.
650         * <p>
651         * First attempts to load JAR files from the classpath using MountableFile.forClasspathResource().
652         * If that fails (because the JAR file is not on the classpath), falls back to using MountableFile.forHostPath().
653         * If a JAR is not found in either location, throws a RuntimeException.
654         */
655        private void copyCustomerJars() {
656                // If specific JAR names are provided, try to load them from the classpath first
657                if (myCustomerJarNames != null && !myCustomerJarNames.isEmpty()) {
658                        List<String> jarsFoundOnClasspath = new ArrayList<>();
659                        List<String> jarsNotFoundOnClasspath = new ArrayList<>();
660
661                        for (String jarName : myCustomerJarNames) {
662                                try {
663                                        ourLog.info("Attempting to load JAR file from classpath: {}", jarName);
664                                        MountableFile mountableFile = MountableFile.forClasspathResource(jarName);
665                                        withCopyFileToContainer(mountableFile, "/home/smile/smilecdr/customerlib/" + jarName);
666                                        jarsFoundOnClasspath.add(jarName);
667                                } catch (IllegalArgumentException e) {
668                                        ourLog.info("JAR file not found on classpath: {}. Will try local filesystem.", jarName);
669                                        jarsNotFoundOnClasspath.add(jarName);
670                                }
671                        }
672
673                        // If all JARs were found on the classpath, we're done
674                        if (jarsNotFoundOnClasspath.isEmpty()) {
675                                ourLog.info("All specified JAR files were loaded from the classpath.");
676                                return;
677                        }
678
679                        // Fall back to loading from the local filesystem for JARs not found on classpath
680                        try {
681                                // Find the cdr-interceptor-starterproject directory
682                                Path projectRoot = Paths.get(".");
683                                Path targetDir = projectRoot.resolve("target");
684
685                                if (!Files.exists(targetDir)) {
686                                        throw new IllegalArgumentException(
687                                                        "Could not find target directory. The following JAR files were not found on the classpath: "
688                                                                        + jarsNotFoundOnClasspath);
689                                }
690
691                                // Get all JAR files in the target directory
692                                List<File> jarFiles;
693                                try (var paths = Files.list(targetDir)) {
694                                        jarFiles = paths.filter(path -> path.toString().endsWith(".jar"))
695                                                        .map(Path::toFile)
696                                                        .toList();
697                                }
698
699                                if (jarFiles.isEmpty()) {
700                                        throw new IllegalArgumentException(
701                                                        "No JAR files found in target directory. The following JAR files were not found on the classpath: "
702                                                                        + jarsNotFoundOnClasspath);
703                                }
704
705                                // Filter JAR files based on jarsNotFoundOnClasspath
706                                List<File> filesToCopy = jarFiles.stream()
707                                                .filter(file -> jarsNotFoundOnClasspath.contains(file.getName()))
708                                                .toList();
709
710                                // Check if all JARs not found on classpath were found in target directory
711                                if (filesToCopy.size() < jarsNotFoundOnClasspath.size()) {
712                                        List<String> jarsNotFound = new ArrayList<>(jarsNotFoundOnClasspath);
713                                        jarsNotFound.removeAll(
714                                                        filesToCopy.stream().map(File::getName).toList());
715                                        throw new IllegalArgumentException(
716                                                        "The following JAR files were not found in either the classpath or the target directory: "
717                                                                        + jarsNotFound);
718                                }
719
720                                for (File jarFile : filesToCopy) {
721                                        ourLog.info("Copying JAR file from local filesystem to container: {}", jarFile.getName());
722                                        MountableFile mountableFile = MountableFile.forHostPath(jarFile.toPath());
723                                        withCopyFileToContainer(mountableFile, "/home/smile/smilecdr/customerlib/" + jarFile.getName());
724                                }
725
726                                ourLog.info("Copied {} JAR file(s) to container from local filesystem", filesToCopy.size());
727                        } catch (IOException e) {
728                                throw new IllegalArgumentException("Error copying JAR files to container from local filesystem", e);
729                        }
730                }
731        }
732}