• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

openmrs / openmrs-core / 29845725671

21 Jul 2026 03:48PM UTC coverage: 63.994% (+0.01%) from 63.981%
29845725671

push

github

web-flow
TRUNK-6713: Switch to saner DaemonThread protection scheme (#6360)

54 of 80 new or added lines in 6 files covered. (67.5%)

7 existing lines in 6 files now uncovered.

24227 of 37858 relevant lines covered (63.99%)

0.64 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

51.03
/api/src/main/java/org/openmrs/module/ModuleFactory.java
1
/**
2
 * This Source Code Form is subject to the terms of the Mozilla Public License,
3
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
4
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
5
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
6
 * 
7
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
8
 * graphic logo is a trademark of OpenMRS Inc.
9
 */
10
package org.openmrs.module;
11

12
import java.io.File;
13
import java.io.IOException;
14
import java.io.InputStream;
15
import java.net.MalformedURLException;
16
import java.net.URL;
17
import java.util.ArrayList;
18
import java.util.Arrays;
19
import java.util.Collection;
20
import java.util.Collections;
21
import java.util.Comparator;
22
import java.util.HashMap;
23
import java.util.HashSet;
24
import java.util.LinkedHashSet;
25
import java.util.List;
26
import java.util.Map;
27
import java.util.Map.Entry;
28
import java.util.Set;
29
import java.util.SortedMap;
30
import java.util.concurrent.ConcurrentHashMap;
31
import java.util.concurrent.ExecutionException;
32

33
import com.google.common.cache.Cache;
34
import com.google.common.cache.CacheBuilder;
35
import org.aopalliance.aop.Advice;
36
import org.openmrs.GlobalProperty;
37
import org.openmrs.Privilege;
38
import org.openmrs.api.APIException;
39
import org.openmrs.api.AdministrationService;
40
import org.openmrs.api.OpenmrsService;
41
import org.openmrs.api.context.Context;
42
import org.openmrs.api.context.Daemon;
43
import org.openmrs.module.Extension.MEDIA_TYPE;
44
import org.openmrs.util.CycleException;
45
import org.openmrs.util.DatabaseUpdater;
46
import org.openmrs.util.Graph;
47
import org.openmrs.util.InputRequiredException;
48
import org.openmrs.util.OpenmrsClassLoader;
49
import org.openmrs.util.OpenmrsConstants;
50
import org.openmrs.util.OpenmrsUtil;
51
import org.openmrs.util.PrivilegeConstants;
52
import org.slf4j.Logger;
53
import org.slf4j.LoggerFactory;
54
import org.springframework.aop.Advisor;
55
import org.springframework.context.support.AbstractRefreshableApplicationContext;
56
import org.springframework.util.StringUtils;
57

58
import liquibase.Contexts;
59

60
/**
61
 * Methods for loading, starting, stopping, and storing OpenMRS modules
62
 */
63
public class ModuleFactory {
64
        
65
        private ModuleFactory() {
66
        }
67
        
68
        private static final Logger log = LoggerFactory.getLogger(ModuleFactory.class);
1✔
69
        
70
        protected static final Cache<String, Module> loadedModules = CacheBuilder.newBuilder()
1✔
71
                .softValues().build();
1✔
72
        
73
        protected static final Cache<String, Module> startedModules = CacheBuilder.newBuilder()
1✔
74
                .softValues().build();
1✔
75
        
76
        protected static final Map<String, List<Extension>> extensionMap = new HashMap<>();
1✔
77
        
78
        // maps to keep track of the memory and objects to free/close
79
        protected static final Cache<Module, ModuleClassLoader> moduleClassLoaders = CacheBuilder.newBuilder().weakKeys()
1✔
80
                .softValues().build();
1✔
81
        
82
        private static final Map<String, Set<ModuleClassLoader>> providedPackages = new ConcurrentHashMap<>();
1✔
83
        
84
        // the name of the file within a module file
85
        private static final String MODULE_CHANGELOG_FILENAME = "liquibase.xml";
86
        
87
        private static final Cache<String, DaemonToken> daemonTokens = CacheBuilder.newBuilder().softValues().build();
1✔
88
        
89
        private static final Set<String> actualStartupOrder = new LinkedHashSet<>();
1✔
90

91
        /**
92
         * The capability that proves to {@link Daemon} this class is allowed to act with daemon
93
     * permissions.
94
         */
95
        private static volatile Daemon.CallerKey daemonCallerKey;
96

97
        /**
98
         * Add a module (in the form of a jar file) to the list of openmrs modules Returns null if an error
99
         * occurred and/or module was not successfully loaded
100
         *
101
         * @param moduleFile
102
         * @return Module
103
         */
104
        public static Module loadModule(File moduleFile) throws ModuleException {
105
                
106
                return loadModule(moduleFile, true);
×
107
                
108
        }
109
        
110
        /**
111
         * Add a module (in the form of a jar file) to the list of openmrs modules Returns null if an error
112
         * occurred and/or module was not successfully loaded
113
         *
114
         * @param moduleFile
115
         * @param replaceIfExists unload a module that has the same moduleId if one is loaded already
116
         * @return Module
117
         */
118
        public static Module loadModule(File moduleFile, Boolean replaceIfExists) throws ModuleException {
119
                Module module = new ModuleFileParser(Context.getMessageSourceService()).parse(moduleFile);
1✔
120
                
121
                if (module != null) {
1✔
122
                        loadModule(module, replaceIfExists);
1✔
123
                }
124
                
125
                return module;
1✔
126
        }
127
        
128
        /**
129
         * Add a module to the list of openmrs modules
130
         *
131
         * @param module
132
         * @param replaceIfExists unload a module that has the same moduleId if one is loaded already
133
         *            <strong>Should</strong> load module if it is currently not loaded
134
         *            <strong>Should</strong> not load module if already loaded <strong>Should</strong>
135
         *            always load module if replacement is wanted <strong>Should</strong> not load an older
136
         *            version of the same module <strong>Should</strong> load a newer version of the same
137
         *            module
138
         * @return module the module that was loaded or if the module exists already with the same version,
139
         *         the old module
140
         */
141
        public static Module loadModule(Module module, Boolean replaceIfExists) throws ModuleException {
142
                
143
                log.debug("Adding module {} to the module queue", module.getName());
1✔
144
                
145
                Module oldModule = getLoadedModulesMap().get(module.getModuleId());
1✔
146
                if (oldModule != null) {
1✔
147
                        int versionComparison = ModuleUtil.compareVersion(oldModule.getVersion(), module.getVersion());
1✔
148
                        if (versionComparison < 0) {
1✔
149
                                // if oldModule version is lower, unload it and use the new
150
                                unloadModule(oldModule);
1✔
151
                        } else if (versionComparison == 0) {
1✔
152
                                if (replaceIfExists) {
1✔
153
                                        // if the versions are the same and we're told to replaceIfExists, use the new
154
                                        unloadModule(oldModule);
1✔
155
                                } else {
156
                                        // if the versions are equal and we're not told to replaceIfExists, jump out of here in a bad way
157
                                        throw new ModuleException("A module with the same id and version already exists", module.getModuleId());
1✔
158
                                }
159
                        } else {
160
                                // if the older (already loaded) module is newer, keep that original one that was loaded. return that one.
161
                                return oldModule;
1✔
162
                        }
163
                }
164
                
165
                getLoadedModulesMap().put(module.getModuleId(), module);
1✔
166
                
167
                return module;
1✔
168
        }
169
        
170
        /**
171
         * Load OpenMRS modules from <code>OpenmrsUtil.getModuleRepository()</code>
172
         */
173
        public static void loadModules() {
174
                
175
                // load modules from the user's module repository directory
176
                File modulesFolder = ModuleUtil.getModuleRepository();
×
177
                
178
                log.debug("Loading modules from: {}", modulesFolder.getAbsolutePath());
×
179
                
180
                File[] files = modulesFolder.listFiles();
×
181
                if (modulesFolder.isDirectory() && files != null) {
×
182
                        loadModules(Arrays.asList(files));
×
183
                } else {
184
                        log.error("modules folder: '" + modulesFolder.getAbsolutePath() + "' is not a directory or IO error occurred");
×
185
                }
186
        }
×
187
        
188
        /**
189
         * Attempt to load the given files as OpenMRS modules
190
         *
191
         * @param modulesToLoad the list of files to try and load <strong>Should</strong> not crash when
192
         *            file is not found or broken <strong>Should</strong> setup requirement mappings for
193
         *            every module <strong>Should</strong> not start the loaded modules
194
         */
195
        public static void loadModules(List<File> modulesToLoad) {
196
                // loop over the modules and load all the modules that we can
197
                for (File f : modulesToLoad) {
1✔
198
                        if (f.exists()) {
1✔
199
                                // ignore .svn folder and the like
200
                                if (!f.getName().startsWith(".")) {
1✔
201
                                        try {
202
                                                // last module loaded wins
203
                                                Module mod = loadModule(f, true);
1✔
204
                                                log.debug("Loaded module: " + mod + " successfully");
1✔
205
                                        }
206
                                        catch (Exception e) {
×
207
                                                log.error("Unable to load file in module directory: " + f + ". Skipping file.", e);
×
208
                                        }
1✔
209
                                }
210
                        } else {
211
                                log.error("Could not find file in module directory: " + f);
1✔
212
                        }
213
                }
1✔
214
                
215
                //inform modules, that they can't start before other modules
216
                
217
                Map<String, Module> loadedModulesMap = getLoadedModulesMapPackage();
1✔
218
                for (Module m : loadedModulesMap.values()) {
1✔
219
                        Map<String, String> startBeforeModules = m.getStartBeforeModulesMap();
1✔
220
                        if (startBeforeModules.size() > 0) {
1✔
221
                                for (String s : startBeforeModules.keySet()) {
1✔
222
                                        Module mod = loadedModulesMap.get(s);
1✔
223
                                        if (mod != null) {
1✔
224
                                                mod.addRequiredModule(m.getPackageName(), m.getVersion());
1✔
225
                                        }
226
                                }
1✔
227
                        }
228
                }
1✔
229
        }
1✔
230
        
231
        /**
232
         * Try to start all of the loaded modules that have the global property <i>moduleId</i>.started is
233
         * set to "true" or the property does not exist. Otherwise, leave it as only "loaded"<br>
234
         * <br>
235
         * Modules that are already started will be skipped.
236
         */
237
        public static void startModules() {
238
                
239
                // loop over and try starting each of the loaded modules
240
                if (!getLoadedModules().isEmpty()) {
1✔
241
                        
242
                        List<Module> modules = getModulesThatShouldStart();
1✔
243
                        
244
                        try {
245
                                modules = getModulesInStartupOrder(modules);
1✔
246
                        }
247
                        catch (CycleException ex) {
×
248
                                String message = getCyclicDependenciesMessage(ex.getMessage());
×
249
                                log.error(message, ex);
×
250
                                notifySuperUsersAboutCyclicDependencies(ex);
×
251
                                modules = (List<Module>) ex.getExtraData();
×
252
                        }
1✔
253
                        
254
                        // try and start the modules that should be started
255
                        for (Module mod : modules) {
1✔
256
                                
257
                                if (mod.isStarted()) {
1✔
258
                                        // skip over modules that are already started
259
                                        continue;
×
260
                                }
261
                                
262
                                // Skip module if required ones are not started
263
                                if (!requiredModulesStarted(mod)) {
1✔
264
                                        String message = getFailedToStartModuleMessage(mod);
×
265
                                        log.error(message);
×
266
                                        mod.setStartupErrorMessage(message);
×
267
                                        notifySuperUsersAboutModuleFailure(mod);
×
268
                                        continue;
×
269
                                }
270
                                
271
                                try {
272
                                        log.debug("starting module: {}", mod.getModuleId());
1✔
273
                                        startModule(mod);
1✔
274
                                }
275
                                catch (Exception e) {
×
276
                                        log.error("Error while starting module: " + mod.getName(), e);
×
277
                                        mod.setStartupErrorMessage("Error while starting module", e);
×
278
                                        notifySuperUsersAboutModuleFailure(mod);
×
279
                                }
1✔
280
                        }
1✔
281
                }
282
        }
1✔
283
        
284
        /**
285
         * Obtain the list of modules that should be started
286
         *
287
         * @return list of modules
288
         */
289
        private static List<Module> getModulesThatShouldStart() {
290
                List<Module> modules = new ArrayList<>();
1✔
291
                
292
                AdministrationService adminService = Context.getAdministrationService();
1✔
293
                
294
                for (Module mod : getLoadedModules()) {
1✔
295
                        
296
                        String key = mod.getModuleId() + ".started";
1✔
297
                        String startedProp = adminService.getGlobalProperty(key, null);
1✔
298
                        String mandatoryProp = adminService.getGlobalProperty(mod.getModuleId() + ".mandatory", null);
1✔
299
                        
300
                        // if a 'moduleid.started' property doesn't exist, start the module anyway
301
                        // as this is probably the first time they are loading it
302
                        if (startedProp == null || "true".equals(startedProp) || "true".equalsIgnoreCase(mandatoryProp)
1✔
303
                                || mod.isMandatory()) {
×
304
                                modules.add(mod);
1✔
305
                        }
306
                }
1✔
307
                return modules;
1✔
308
        }
309
        
310
        /**
311
         * Sort modules in startup order based on required and aware-of dependencies
312
         *
313
         * @param modules list of modules to sort
314
         * @return list of modules sorted by dependencies
315
         * @throws CycleException
316
         */
317
        public static List<Module> getModulesInStartupOrder(Collection<Module> modules) throws CycleException {
318
                Graph<Module> graph = new Graph<>();
1✔
319
                
320
                for (Module mod : modules) {
1✔
321
                        
322
                        graph.addNode(mod);
1✔
323
                        
324
                        // Required dependencies
325
                        for (String key : mod.getRequiredModules()) {
1✔
326
                                Module module = getModuleByPackage(key);
1✔
327
                                Module fromNode = graph.getNode(module);
1✔
328
                                if (fromNode == null) {
1✔
329
                                        fromNode = module;
1✔
330
                                }
331
                                
332
                                if (fromNode != null) {
1✔
333
                                        graph.addEdge(graph.new Edge(
1✔
334
                                                fromNode,
335
                                                mod));
336
                                }
337
                        }
1✔
338
                        
339
                        // Aware-of dependencies
340
                        for (String key : mod.getAwareOfModules()) {
1✔
341
                                Module module = getModuleByPackage(key);
1✔
342
                                Module fromNode = graph.getNode(module);
1✔
343
                                if (fromNode == null) {
1✔
344
                                        fromNode = module;
1✔
345
                                }
346
                                
347
                                if (fromNode != null) {
1✔
348
                                        graph.addEdge(graph.new Edge(
×
349
                                                fromNode,
350
                                                mod));
351
                                }
352
                        }
1✔
353
                }
1✔
354
                
355
                return graph.topologicalSort();
1✔
356
        }
357
        
358
        /**
359
         * Send an Alert to all super users that the given module did not start successfully.
360
         *
361
         * @param mod The Module that failed
362
         */
363
        private static void notifySuperUsersAboutModuleFailure(Module mod) {
364
                try {
365
                        // Add the privileges necessary for notifySuperUsers
366
                        Context.addProxyPrivilege(PrivilegeConstants.MANAGE_ALERTS);
×
367
                        
368
                        // Send an alert to all administrators
369
                        Context.getAlertService().notifySuperUsers("Module.startupError.notification.message", null, mod.getName());
×
370
                }
371
                catch (Exception e) {
×
372
                        log.error("Unable to send an alert to the super users", e);
×
373
                }
374
                finally {
375
                        // Remove added privileges
376
                        Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_ALERTS);
×
377
                }
378
        }
×
379
        
380
        /**
381
         * Send an Alert to all super users that modules did not start due to cyclic dependencies
382
         */
383
        private static void notifySuperUsersAboutCyclicDependencies(Exception ex) {
384
                try {
385
                        Context.addProxyPrivilege(PrivilegeConstants.MANAGE_ALERTS);
×
386
                        Context.getAlertService().notifySuperUsers("Module.error.cyclicDependencies", ex, ex.getMessage());
×
387
                }
388
                catch (Exception e) {
×
389
                        log.error("Unable to send an alert to the super users", e);
×
390
                }
391
                finally {
392
                        Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_ALERTS);
×
393
                }
394
        }
×
395

396
        /**
397
         * Convenience method to return a List of Strings containing a description of which modules the
398
         * passed module requires but which are not started. The returned description of each module is the
399
         * moduleId followed by the required version if one is specified
400
         *
401
         * @param module the module to check required modules for
402
         * @return List&lt;String&gt; of module names + optional required versions: "org.openmrs.formentry
403
         *         1.8, org.rg.patientmatching"
404
         */
405
        private static List<String> getMissingRequiredModules(Module module) {
406
                List<String> ret = new ArrayList<>();
×
407
                for (String moduleName : module.getRequiredModules()) {
×
408
                        boolean started = false;
×
409
                        for (Module mod : getStartedModules()) {
×
410
                                if (mod.getPackageName().equals(moduleName)) {
×
411
                                        String reqVersion = module.getRequiredModuleVersion(moduleName);
×
412
                                        if (reqVersion == null || ModuleUtil.compareVersion(mod.getVersion(), reqVersion) >= 0) {
×
413
                                                started = true;
×
414
                                        }
415
                                        break;
416
                                }
417
                        }
×
418
                        
419
                        if (!started) {
×
420
                                String moduleVersion = module.getRequiredModuleVersion(moduleName);
×
421
                                moduleName = moduleName.replace("org.openmrs.module.", "").replace("org.openmrs.", "");
×
422
                                ret.add(moduleName + (moduleVersion != null ? " " + moduleVersion : ""));
×
423
                        }
424
                }
×
425
                return ret;
×
426
        }
427
        
428
        /**
429
         * Returns all modules found/loaded into the system (started and not started)
430
         *
431
         * @return <code>Collection&lt;Module&gt;</code> of the modules loaded into the system
432
         */
433
        public static Collection<Module> getLoadedModules() {
434
                if (getLoadedModulesMap().size() > 0) {
1✔
435
                        return getLoadedModulesMap().values();
1✔
436
                }
437
                
438
                return Collections.emptyList();
1✔
439
        }
440
        
441
        /**
442
         * Returns all modules found/loaded into the system (started and not started) in the form of a
443
         * map&lt;ModuleId, Module&gt;
444
         *
445
         * @return map&lt;ModuleId, Module&gt;
446
         */
447
        public static Map<String, Module> getLoadedModulesMap() {
448
                return loadedModules.asMap();
1✔
449
        }
450
        
451
        /**
452
         * Returns all modules found/loaded into the system (started and not started) in the form of a
453
         * map&lt;PackageName, Module&gt;
454
         *
455
         * @return map&lt;PackageName, Module&gt;
456
         */
457
        public static Map<String, Module> getLoadedModulesMapPackage() {
458
                Map<String, Module> map = new HashMap<>();
1✔
459
                for (Module loadedModule : getLoadedModulesMap().values()) {
1✔
460
                        map.put(loadedModule.getPackageName(), loadedModule);
1✔
461
                }
1✔
462
                return map;
1✔
463
        }
464
        
465
        /**
466
         * Returns the modules that have been successfully started
467
         *
468
         * @return <code>Collection&lt;Module&gt;</code> of the started modules
469
         */
470
        public static Collection<Module> getStartedModules() {
471
                if (getStartedModulesMap().size() > 0) {
1✔
472
                        return getStartedModulesMap().values();
1✔
473
                }
474
                
475
                return Collections.emptyList();
1✔
476
        }
477
        
478
        public static List<Module> getStartedModulesInOrder() {
479
                List<Module> modules = new ArrayList<>();
×
480
                if (actualStartupOrder != null) {
×
481
                        for (String moduleId : actualStartupOrder) {
×
482
                                modules.add(getStartedModulesMap().get(moduleId));
×
483
                        }
×
484
                } else {
485
                        modules.addAll(getStartedModules());
×
486
                }
487
                return modules;
×
488
        }
489
        
490
        /**
491
         * Returns the modules that have been successfully started in the form of a map&lt;ModuleId,
492
         * Module&gt;
493
         *
494
         * @return Map&lt;ModuleId, Module&gt;
495
         */
496
        public static Map<String, Module> getStartedModulesMap() {
497
                return startedModules.asMap();
1✔
498
        }
499
        
500
        /**
501
         * @param moduleId
502
         * @return Module matching module id or null if none
503
         */
504
        public static Module getModuleById(String moduleId) {
505
                return getLoadedModulesMap().get(moduleId);
1✔
506
        }
507
        
508
        /**
509
         * @param moduleId
510
         * @return Module matching moduleId, if it is started or null otherwise
511
         */
512
        public static Module getStartedModuleById(String moduleId) {
513
                return getStartedModulesMap().get(moduleId);
1✔
514
        }
515
        
516
        /**
517
         * @param modulePackage
518
         * @return Module matching module package or null if none
519
         */
520
        public static Module getModuleByPackage(String modulePackage) {
521
                for (Module mod : getLoadedModulesMap().values()) {
1✔
522
                        if (mod.getPackageName().equals(modulePackage)) {
1✔
523
                                return mod;
1✔
524
                        }
525
                }
1✔
526
                return null;
1✔
527
        }
528
        
529
        /**
530
         * @see #startModule(Module, boolean, AbstractRefreshableApplicationContext)
531
         * @see #startModuleInternal(Module)
532
         * @see Daemon#startModule(Module)
533
         */
534
        public static Module startModule(Module module) throws ModuleException {
535
                return startModule(module, false, null);
1✔
536
        }
537
        
538
        /**
539
         * Runs through extensionPoints and then calls {@link BaseModuleActivator#willStart()} on the
540
         * Module's activator. This method is run in a new thread and is authenticated as the Daemon user.
541
         * If a non null application context is passed in, it gets refreshed to make the module's services
542
         * available
543
         *
544
         * @param module Module to start
545
         * @param isOpenmrsStartup Specifies whether this module is being started at application startup or
546
         *            not, this argument is ignored if a null application context is passed in
547
         * @param applicationContext the spring application context instance to refresh
548
         * @throws ModuleException if the module throws any kind of error at startup or in an activator
549
         * @see #startModuleInternal(Module, boolean, AbstractRefreshableApplicationContext)
550
         * @see Daemon#startModule(Module, boolean, AbstractRefreshableApplicationContext)
551
         */
552
        public static Module startModule(Module module, boolean isOpenmrsStartup,
553
                AbstractRefreshableApplicationContext applicationContext) throws ModuleException {
554
                
555
                if (!requiredModulesStarted(module)) {
1✔
556
                        int missingModules = 0;
1✔
557
                        
558
                        for (String packageName : module.getRequiredModulesMap().keySet()) {
1✔
559
                                Module mod = getModuleByPackage(packageName);
1✔
560
                                
561
                                // mod not installed
562
                                if (mod == null) {
1✔
563
                                        missingModules++;
×
564
                                        continue;
×
565
                                }
566
                                
567
                                if (!mod.isStarted()) {
1✔
568
                                        startModule(mod);
1✔
569
                                }
570
                        }
1✔
571
                        
572
                        if (missingModules > 0) {
1✔
573
                                String message = getFailedToStartModuleMessage(module);
×
574
                                log.error(message);
×
575
                                module.setStartupErrorMessage(message);
×
576
                                notifySuperUsersAboutModuleFailure(module);
×
577
                                // instead of return null, i realized that Daemon.startModule() always returns a Module
578
                                // object,irrespective of whether the startup succeeded
579
                                return module;
×
580
                        }
581
                }
582
                return Daemon.startModule(module, isOpenmrsStartup, applicationContext, daemonCallerKey());
1✔
583
        }
584
        
585
        /**
586
         * This method should not be called directly.<br>
587
         * <br>
588
         * The {@link #startModule(Module)} (and hence {@link Daemon#startModule(Module)}) calls this method
589
         * in a new Thread and is authenticated as the {@link Daemon} user<br>
590
         * <br>
591
         * Runs through extensionPoints and then calls {@link BaseModuleActivator#willStart()} on the
592
         * Module's activator.
593
         *
594
         * @param module Module to start
595
         */
596
        public static Module startModuleInternal(Module module) throws ModuleException {
597
                return startModuleInternal(module, false, null);
×
598
        }
599
        
600
        /**
601
         * This method should not be called directly.<br>
602
         * <br>
603
         * The {@link #startModule(Module)} (and hence {@link Daemon#startModule(Module)}) calls this method
604
         * in a new Thread and is authenticated as the {@link Daemon} user<br>
605
         * <br>
606
         * Runs through extensionPoints and then calls {@link BaseModuleActivator#willStart()} on the
607
         * Module's activator. <br>
608
         * <br>
609
         * If a non null application context is passed in, it gets refreshed to make the module's services
610
         * available
611
         *
612
         * @param module Module to start
613
         * @param isOpenmrsStartup Specifies whether this module is being started at application startup or
614
         *            not, this argument is ignored if a null application context is passed in
615
         * @param applicationContext the spring application context instance to refresh
616
         */
617
        public static Module startModuleInternal(Module module, boolean isOpenmrsStartup,
618
                AbstractRefreshableApplicationContext applicationContext) throws ModuleException {
619
                
620
                if (module != null) {
1✔
621
                        String moduleId = module.getModuleId();
1✔
622
                        
623
                        try {
624
                                
625
                                // check to be sure this module can run with our current version
626
                                // of OpenMRS code
627
                                String requireVersion = module.getRequireOpenmrsVersion();
1✔
628
                                ModuleUtil.checkRequiredVersion(OpenmrsConstants.OPENMRS_VERSION_SHORT, requireVersion);
1✔
629
                                
630
                                // check for required modules
631
                                if (!requiredModulesStarted(module)) {
1✔
632
                                        throw new ModuleException(getFailedToStartModuleMessage(module));
×
633
                                }
634
                                
635
                                // fire up the classloader for this module
636
                                ModuleClassLoader moduleClassLoader = new ModuleClassLoader(module, ModuleFactory.class.getClassLoader());
1✔
637
                                getModuleClassLoaderMap().put(module, moduleClassLoader);
1✔
638
                                registerProvidedPackages(moduleClassLoader);
1✔
639
                                
640
                                // don't load the advice objects into the Context
641
                                // At startup, the spring context isn't refreshed until all modules
642
                                // have been loaded.  This causes errors if called here during a
643
                                // module's startup if one of these advice points is on another
644
                                // module because that other module's service won't have been loaded
645
                                // into spring yet.  All advice for all modules must be reloaded
646
                                // a spring context refresh anyway
647
                                
648
                                // map extension point to a list of extensions for this module only
649
                                Map<String, List<Extension>> moduleExtensionMap = new HashMap<>();
1✔
650
                                for (Extension ext : module.getExtensions()) {
1✔
651
                                        
652
                                        String extId = ext.getExtensionId();
×
653
                                        List<Extension> tmpExtensions = moduleExtensionMap.computeIfAbsent(extId, k -> new ArrayList<>());
×
654
                                        
655
                                        tmpExtensions.add(ext);
×
656
                                }
×
657
                                
658
                                // Sort this module's extensions, and merge them into the full extensions map
659
                                Comparator<Extension> sortOrder = (e1, e2) -> Integer.valueOf(e1.getOrder()).compareTo(e2.getOrder());
1✔
660
                                for (Map.Entry<String, List<Extension>> moduleExtensionEntry : moduleExtensionMap.entrySet()) {
1✔
661
                                        // Sort this module's extensions for current extension point
662
                                        List<Extension> sortedModuleExtensions = moduleExtensionEntry.getValue();
×
663
                                        sortedModuleExtensions.sort(sortOrder);
×
664
                                        
665
                                        // Get existing extensions, and append the ones from the new module
666
                                        List<Extension> extensions = getExtensionMap().computeIfAbsent(moduleExtensionEntry.getKey(),
×
667
                                                k -> new ArrayList<>());
×
668
                                        for (Extension ext : sortedModuleExtensions) {
×
669
                                                log.debug("Adding to mapping ext: " + ext.getExtensionId() + " ext.class: " + ext.getClass());
×
670
                                                extensions.add(ext);
×
671
                                        }
×
672
                                }
×
673
                                
674
                                // run the module's sql update script
675
                                // This and the property updates are the only things that can't
676
                                // be undone at startup, so put these calls after any other
677
                                // calls that might hinder startup
678
                                SortedMap<String, String> diffs = SqlDiffFileParser.getSqlDiffs(module);
1✔
679
                                
680
                                try {
681
                                        // this method must check and run queries against the database.
682
                                        // to do this, it must be "authenticated".  Give the current
683
                                        // "user" the proxy privilege so this can be done. ("user" might
684
                                        // be nobody because this is being run at startup)
685
                                        Context.addProxyPrivilege("");
1✔
686
                                        
687
                                        for (Map.Entry<String, String> entry : diffs.entrySet()) {
1✔
688
                                                String version = entry.getKey();
×
689
                                                String sql = entry.getValue();
×
690
                                                if (StringUtils.hasText(sql)) {
×
691
                                                        runDiff(module, version, sql);
×
692
                                                }
693
                                        }
×
694
                                }
695
                                finally {
696
                                        // take the "authenticated" privilege away from the current "user"
697
                                        Context.removeProxyPrivilege("");
1✔
698
                                }
699
                                
700
                                if (Context.getAdministrationService().isModuleSetupOnVersionChangeNeeded(module.getModuleId())) {
1✔
701
                                        log.info("Module {} changed, running setup.", module.getModuleId());
1✔
702
                                        Context.getAdministrationService().runModuleSetupOnVersionChange(module);
1✔
703
                                }
704
                                
705
                                // effectively mark this module as started successfully
706
                                getStartedModulesMap().put(moduleId, module);
1✔
707

708
                                actualStartupOrder.add(moduleId);
1✔
709
                                
710
                                try {
711
                                        // save the state of this module for future restarts
712
                                        saveGlobalProperty(moduleId + ".started", "true", getGlobalPropertyStartedDescription(moduleId));
1✔
713
                                        
714
                                        // save the mandatory status
715
                                        saveGlobalProperty(moduleId + ".mandatory", String.valueOf(module.isMandatory()),
1✔
716
                                                getGlobalPropertyMandatoryModuleDescription(moduleId));
1✔
717
                                }
718
                                catch (Exception e) {
×
719
                                        // pass over errors because this doesn't really concern startup
720
                                        // passing over this also allows for multiple of the same-named modules
721
                                        // to be loaded in junit tests that are run within one session
722
                                        log.debug("Got an error when trying to set the global property on module startup", e);
×
723
                                }
1✔
724
                                
725
                                // (this must be done after putting the module in the started
726
                                // list)
727
                                // if this module defined any privileges or global properties,
728
                                // make sure they are added to the database
729
                                // (Unfortunately, placing the call here will duplicate work
730
                                // done at initial app startup)
731
                                if (!module.getPrivileges().isEmpty() || !module.getGlobalProperties().isEmpty()) {
1✔
732
                                        log.debug("Updating core dataset");
×
733
                                        Context.checkCoreDataset();
×
734
                                        // checkCoreDataset() currently doesn't throw an error. If
735
                                        // it did, it needs to be
736
                                        // caught and the module needs to be stopped and given a
737
                                        // startup error
738
                                }
739
                                
740
                                // should be near the bottom so the module has all of its stuff
741
                                // set up for it already.
742
                                try {
743
                                        if (module.getModuleActivator() != null) {
1✔
744
                                                // if extends BaseModuleActivator
745
                                                module.getModuleActivator().willStart();
1✔
746
                                        }
747
                                }
748
                                catch (ModuleException e) {
×
749
                                        // just rethrow module exceptions. This should be used for a
750
                                        // module marking that it had trouble starting
751
                                        throw e;
×
752
                                }
753
                                catch (Exception e) {
×
754
                                        throw new ModuleException("Error while calling module's Activator.startup()/willStart() method", e);
×
755
                                }
1✔
756
                                
757
                                // erase any previous startup error
758
                                module.clearStartupError();
1✔
759
                        }
760
                        catch (Exception e) {
×
761
                                log.error("Error while trying to start module: {}", moduleId, e);
×
762
                                module.setStartupErrorMessage("Error while trying to start module", e);
×
763
                                notifySuperUsersAboutModuleFailure(module);
×
764
                                // undo all of the actions in startup
765
                                try {
766
                                        boolean skipOverStartedProperty = false;
×
767
                                        
768
                                        if (e instanceof ModuleMustStartException) {
×
769
                                                skipOverStartedProperty = true;
×
770
                                        }
771
                                        
772
                                        stopModule(module, skipOverStartedProperty, true);
×
773
                                }
774
                                catch (Exception e2) {
×
775
                                        // this will probably occur about the same place as the
776
                                        // error in startup
777
                                        log.debug("Error while stopping module: {}", moduleId, e2);
×
778
                                }
×
779
                        }
1✔
780
                        
781
                }
782
                
783
                if (applicationContext != null) {
1✔
784
                        ModuleUtil.refreshApplicationContext(applicationContext, isOpenmrsStartup, module);
×
785
                }
786
                
787
                return module;
1✔
788
        }
789
        
790
        private static void registerProvidedPackages(ModuleClassLoader moduleClassLoader) {
791
                for (String providedPackage : moduleClassLoader.getProvidedPackages()) {
1✔
792
                        Set<ModuleClassLoader> newSet = new HashSet<>();
1✔
793
                        
794
                        Set<ModuleClassLoader> set = providedPackages.get(providedPackage);
1✔
795
                        if (set != null) {
1✔
796
                                newSet.addAll(set);
1✔
797
                        }
798
                        
799
                        newSet.add(moduleClassLoader);
1✔
800
                        providedPackages.put(providedPackage, newSet);
1✔
801
                }
1✔
802
        }
1✔
803
        
804
        private static void unregisterProvidedPackages(ModuleClassLoader moduleClassLoader) {
805
                for (String providedPackage : moduleClassLoader.getProvidedPackages()) {
1✔
806
                        Set<ModuleClassLoader> newSet = new HashSet<>();
1✔
807
                        
808
                        Set<ModuleClassLoader> set = providedPackages.get(providedPackage);
1✔
809
                        if (set != null) {
1✔
810
                                newSet.addAll(set);
1✔
811
                        }
812
                        newSet.remove(moduleClassLoader);
1✔
813
                        
814
                        providedPackages.put(providedPackage, newSet);
1✔
815
                }
1✔
816
        }
1✔
817
        
818
        public static Set<ModuleClassLoader> getModuleClassLoadersForPackage(String packageName) {
819
                Set<ModuleClassLoader> set = providedPackages.get(packageName);
1✔
820
                if (set == null) {
1✔
821
                        return Collections.emptySet();
1✔
822
                } else {
823
                        return new HashSet<>(set);
1✔
824
                }
825
        }
826
        
827
        /**
828
         * Gets the error message of a module which fails to start.
829
         *
830
         * @param module the module that has failed to start.
831
         * @return the message text.
832
         */
833
        private static String getFailedToStartModuleMessage(Module module) {
834
                String[] params = { module.getName(), String.join(",", getMissingRequiredModules(module)) };
×
835
                return Context.getMessageSourceService().getMessage("Module.error.moduleCannotBeStarted", params,
×
836
                        Context.getLocale());
×
837
        }
838
        
839
        /**
840
         * Gets the error message of cyclic dependencies between modules
841
         *
842
         * @return the message text.
843
         */
844
        private static String getCyclicDependenciesMessage(String message) {
845
                return Context.getMessageSourceService().getMessage("Module.error.cyclicDependencies", new Object[] { message },
×
846
                        Context.getLocale());
×
847
        }
848
        
849
        /**
850
         * Loop over the given module's advice objects and load them into the Context This needs to be
851
         * called for all started modules after every restart of the Spring Application Context
852
         *
853
         * @param module
854
         */
855
        public static void loadAdvice(Module module) {
856
                for (AdvicePoint advice : module.getAdvicePoints()) {
×
857
                        Class<?> cls;
858
                        try {
859
                                cls = Context.loadClass(advice.getPoint());
×
860
                                Object aopObject = advice.getClassInstance();
×
861
                                if (aopObject instanceof Advisor) {
×
862
                                        log.debug("adding advisor [{}]", aopObject.getClass());
×
863
                                        Context.addAdvisor(cls, (Advisor) aopObject);
×
864
                                } else if (aopObject != null) {
×
865
                                        log.debug("adding advice [{}]", aopObject.getClass());
×
866
                                        Context.addAdvice(cls, (Advice) aopObject);
×
867
                                } else {
868
                                        log.debug("Could not load advice class for {} [{}]", advice.getPoint(), advice.getClassName());
×
869
                                }
870
                        }
871
                        catch (ClassNotFoundException | NoClassDefFoundError e) {
×
872
                                log.warn("Could not load advice point [{}]", advice.getPoint(), e);
×
873
                        }
×
874
                }
×
875
        }
×
876
        
877
        /**
878
         * Execute the given sql diff section for the given module
879
         *
880
         * @param module the module being executed on
881
         * @param version the version of this sql diff
882
         * @param sql the actual sql statements to run (separated by semi colons)
883
         */
884
        private static void runDiff(Module module, String version, String sql) {
885
                AdministrationService as = Context.getAdministrationService();
×
886
                
887
                String key = module.getModuleId() + ".database_version";
×
888
                GlobalProperty gp = as.getGlobalPropertyObject(key);
×
889
                
890
                boolean executeSQL = false;
×
891
                
892
                // check given version against current version
893
                if (gp != null && StringUtils.hasLength(gp.getPropertyValue())) {
×
894
                        String currentDbVersion = gp.getPropertyValue();
×
895
                        if (log.isDebugEnabled()) {
×
896
                                log.debug("version:column {}:{}", version, currentDbVersion);
×
897
                                log.debug("compare: {}", ModuleUtil.compareVersion(version, currentDbVersion));
×
898
                        }
899
                        if (ModuleUtil.compareVersion(version, currentDbVersion) > 0) {
×
900
                                executeSQL = true;
×
901
                        }
902
                } else {
×
903
                        executeSQL = true;
×
904
                }
905
                
906
                // version is greater than the currently installed version. execute this update.
907
                if (executeSQL) {
×
908
                        try {
909
                                Context.addProxyPrivilege(PrivilegeConstants.SQL_LEVEL_ACCESS);
×
910
                                log.debug("Executing sql: " + sql);
×
911
                                String[] sqlStatements = sql.split(";");
×
912
                                for (String sqlStatement : sqlStatements) {
×
913
                                        if (sqlStatement.trim().length() > 0) {
×
914
                                                as.executeSQL(sqlStatement, false);
×
915
                                        }
916
                                }
917
                        }
918
                        finally {
919
                                Context.removeProxyPrivilege(PrivilegeConstants.SQL_LEVEL_ACCESS);
×
920
                        }
921
                        
922
                        // save the global property
923
                        try {
924
                                Context.addProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
×
925
                                
926
                                String description = "DO NOT MODIFY.  Current database version number for the " + module.getModuleId()
×
927
                                        + " module.";
928
                                
929
                                if (gp == null) {
×
930
                                        log.info("Global property " + key + " was not found. Creating one now.");
×
931
                                        gp = new GlobalProperty(key, version, description);
×
932
                                        as.saveGlobalProperty(gp);
×
933
                                } else if (!gp.getPropertyValue().equals(version)) {
×
934
                                        log.info("Updating global property " + key + " to version: " + version);
×
935
                                        gp.setDescription(description);
×
936
                                        gp.setPropertyValue(version);
×
937
                                        as.saveGlobalProperty(gp);
×
938
                                } else {
939
                                        log.error("Should not be here. GP property value and sqldiff version should not be equal");
×
940
                                }
941
                                
942
                        }
943
                        finally {
944
                                Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
×
945
                        }
946
                        
947
                }
948
                
949
        }
×
950

951
        /**
952
         * This is a convenience method that exposes the private {@link #runLiquibase(Module)} method.
953
         * @since 2.9.0
954
         */
955
        public static void runLiquibaseForModule(Module module) {
956
                runLiquibase(module);
1✔
957
        }
1✔
958
        
959
        /**
960
         * Execute all not run changeSets in liquibase.xml for the given module
961
         *
962
         * @param module the module being executed on
963
         */
964
        private static void runLiquibase(Module module) {
965
                ModuleClassLoader moduleClassLoader = getModuleClassLoader(module);
1✔
966
                boolean liquibaseFileExists = false;
1✔
967
                
968
                if (moduleClassLoader != null) {
1✔
969
                        try (InputStream inStream = moduleClassLoader.getResourceAsStream(MODULE_CHANGELOG_FILENAME)) {
1✔
970
                                liquibaseFileExists = (inStream != null);
1✔
971
                        }
972
                        catch (IOException ignored) {
×
973
                                
974
                        }
1✔
975
                }
976
                
977
                if (liquibaseFileExists) {
1✔
978
                        try {
979
                                // run liquibase.xml by Liquibase API
980
                                DatabaseUpdater.executeChangelog(MODULE_CHANGELOG_FILENAME, new Contexts(), null, moduleClassLoader);
×
981
                        }
982
                        catch (InputRequiredException e) {
×
983
                                // the user would be stepped through the questions returned here.
984
                                throw new ModuleException("Input during database updates is not yet implemented.", module.getName(), e);
×
985
                        }
986
                        catch (Exception e) {
×
987
                                throw new ModuleException("Unable to update data model using " + MODULE_CHANGELOG_FILENAME + ".",
×
988
                                        module.getName(), e);
×
989
                        }
×
990
                }
991
        }
1✔
992
        
993
        /**
994
         * Runs through the advice and extension points and removes from api. <br>
995
         * Also calls mod.Activator.shutdown()
996
         *
997
         * @param mod module to stop
998
         * @see ModuleFactory#stopModule(Module, boolean, boolean)
999
         */
1000
        public static void stopModule(Module mod) {
1001
                stopModule(mod, false, false);
1✔
1002
        }
1✔
1003
        
1004
        /**
1005
         * Runs through the advice and extension points and removes from api.<br>
1006
         * Also calls mod.Activator.shutdown()
1007
         *
1008
         * @param mod the module to stop
1009
         * @param isShuttingDown true if this is called during the process of shutting down openmrs
1010
         * @see #stopModule(Module, boolean, boolean)
1011
         */
1012
        public static void stopModule(Module mod, boolean isShuttingDown) {
1013
                stopModule(mod, isShuttingDown, false);
1✔
1014
        }
1✔
1015
        
1016
        /**
1017
         * Runs through the advice and extension points and removes from api.<br>
1018
         * <code>skipOverStartedProperty</code> should only be true when openmrs is stopping modules because
1019
         * it is shutting down. When normally stopping a module, use {@link #stopModule(Module)} (or leave
1020
         * value as false). This property controls whether the globalproperty is set for startup/shutdown.
1021
         * <br>
1022
         * Also calls module's {@link ModuleActivator#stopped()}
1023
         *
1024
         * @param mod module to stop
1025
         * @param skipOverStartedProperty true if we don't want to set &lt;moduleid&gt;.started to false
1026
         * @param isFailedStartup true if this is being called as a cleanup because of a failed module
1027
         *            startup
1028
         * @return list of dependent modules that were stopped because this module was stopped. This will
1029
         *         never be null.
1030
         */
1031
        public static List<Module> stopModule(Module mod, boolean skipOverStartedProperty, boolean isFailedStartup)
1032
                throws ModuleMustStartException {
1033
                
1034
                List<Module> dependentModulesStopped = new ArrayList<>();
1✔
1035
                
1036
                if (mod != null) {
1✔
1037
                        
1038
                        if (!ModuleFactory.isModuleStarted(mod)) {
1✔
1039
                                return dependentModulesStopped;
×
1040
                        }
1041
                        
1042
                        try {
1043
                                // if extends BaseModuleActivator
1044
                                if (mod.getModuleActivator() != null) {
1✔
1045
                                        mod.getModuleActivator().willStop();
1✔
1046
                                }
1047
                        }
1048
                        catch (Exception t) {
×
1049
                                log.warn("Unable to call module's Activator.willStop() method", t);
×
1050
                        }
1✔
1051
                        
1052
                        String moduleId = mod.getModuleId();
1✔
1053
                        
1054
                        // don't allow mandatory modules to be stopped
1055
                        // don't use database checks here because spring might be in a bad state
1056
                        if (!isFailedStartup && mod.isMandatory()) {
1✔
1057
                                throw new MandatoryModuleException(moduleId);
×
1058
                        }
1059

1060
                        String modulePackage = mod.getPackageName();
1✔
1061
                        
1062
                        // stop all dependent modules
1063
                        // copy modules to new list to avoid "concurrent modification exception"
1064
                        List<Module> startedModulesCopy = new ArrayList<>(getStartedModules());
1✔
1065
                        for (Module dependentModule : startedModulesCopy) {
1✔
1066
                                if (dependentModule != null && !dependentModule.equals(mod)
1✔
1067
                                        && isModuleRequiredByAnother(dependentModule, modulePackage)) {
1✔
1068
                                        dependentModulesStopped.add(dependentModule);
1✔
1069
                                        dependentModulesStopped.addAll(stopModule(dependentModule, skipOverStartedProperty, isFailedStartup));
1✔
1070
                                }
1071
                        }
1✔
1072
                        
1073
                        getStartedModulesMap().remove(moduleId);
1✔
1074
                        if (actualStartupOrder != null) {
1✔
1075
                                actualStartupOrder.remove(moduleId);
1✔
1076
                                for (Module depModule : dependentModulesStopped) {
1✔
1077
                                        actualStartupOrder.remove(depModule.getModuleId());
1✔
1078
                                }
1✔
1079
                        }
1080
                        
1081
                        if (!skipOverStartedProperty && !Context.isRefreshingContext()) {
1✔
1082
                                saveGlobalProperty(moduleId + ".started", "false", getGlobalPropertyStartedDescription(moduleId));
1✔
1083
                        }
1084
                        
1085
                        ModuleClassLoader moduleClassLoader = getModuleClassLoaderMap().get(mod);
1✔
1086
                        if (moduleClassLoader != null) {
1✔
1087
                                unregisterProvidedPackages(moduleClassLoader);
1✔
1088
                                
1089
                                log.debug("Mod was in classloader map.  Removing advice and extensions.");
1✔
1090
                                // remove all advice by this module
1091
                                try {
1092
                                        for (AdvicePoint advice : mod.getAdvicePoints()) {
1✔
1093
                                                Class cls;
1094
                                                try {
1095
                                                        cls = Context.loadClass(advice.getPoint());
×
1096
                                                        Object aopObject = advice.getClassInstance();
×
1097
                                                        if (aopObject instanceof Advisor) {
×
1098
                                                                log.debug("adding advisor: " + aopObject.getClass());
×
1099
                                                                Context.removeAdvisor(cls, (Advisor) aopObject);
×
1100
                                                        } else {
1101
                                                                log.debug("Adding advice: " + aopObject.getClass());
×
1102
                                                                Context.removeAdvice(cls, (Advice) aopObject);
×
1103
                                                        }
1104
                                                }
1105
                                                catch (Exception t) {
×
1106
                                                        log.warn("Could not remove advice point: " + advice.getPoint(), t);
×
1107
                                                }
×
1108
                                        }
×
1109
                                }
1110
                                catch (Exception t) {
×
1111
                                        log.warn("Error while getting advicePoints from module: " + moduleId, t);
×
1112
                                }
1✔
1113
                                
1114
                                // remove all extensions by this module
1115
                                try {
1116
                                        for (Extension ext : mod.getExtensions()) {
1✔
1117
                                                String extId = ext.getExtensionId();
×
1118
                                                try {
1119
                                                        List<Extension> tmpExtensions = getExtensions(extId);
×
1120
                                                        tmpExtensions.remove(ext);
×
1121
                                                        getExtensionMap().put(extId, tmpExtensions);
×
1122
                                                }
1123
                                                catch (Exception exterror) {
×
1124
                                                        log.warn("Error while getting extension: " + ext, exterror);
×
1125
                                                }
×
1126
                                        }
×
1127
                                }
1128
                                catch (Exception t) {
×
1129
                                        log.warn("Error while getting extensions from module: " + moduleId, t);
×
1130
                                }
1✔
1131
                        }
1132
                        
1133
                        //Run the onShutdown() method for openmrs services in this module.
1134
                        List<OpenmrsService> services = Context.getModuleOpenmrsServices(modulePackage);
1✔
1135
                        if (services != null) {
1✔
1136
                                for (OpenmrsService service : services) {
1✔
1137
                                        service.onShutdown();
1✔
1138
                                }
1✔
1139
                        }
1140
                        
1141
                        try {
1142
                                if (mod.getModuleActivator() != null) {// extends BaseModuleActivator
1✔
1143
                                        mod.getModuleActivator().stopped();
1✔
1144
                                }
1145
                        }
1146
                        catch (Exception t) {
×
1147
                                log.warn("Unable to call module's Activator.shutdown() method", t);
×
1148
                        }
1✔
1149
                        
1150
                        //Since extensions are loaded by the module class loader which is about to be disposed,
1151
                        //we need to clear them, else we shall never be able to unload the class loader until
1152
                        //when we unload the module, hence resulting into two problems:
1153
                        // 1) Memory leakage for start/stop module.
1154
                        // 2) Calls to Context.getService(Service.class) which are made within these extensions 
1155
                        //          will throw APIException("Service not found: ") because their calls to Service.class
1156
                        //    will pass in a Class from the old module class loader (which loaded them) yet the
1157
                        //    ServiceContext will have new services from a new module class loader.
1158
                        //
1159
                        //Same thing applies to activator, moduleActivator and AdvicePoint classInstance.
1160
                        mod.getExtensions().clear();
1✔
1161
                        mod.setModuleActivator(null);
1✔
1162
                        mod.disposeAdvicePointsClassInstance();
1✔
1163
                        
1164
                        ModuleClassLoader cl = removeClassLoader(mod);
1✔
1165
                        if (cl != null) {
1✔
1166
                                cl.dispose();
1✔
1167
                        }
1168
                }
1169
                
1170
                return dependentModulesStopped;
1✔
1171
        }
1172
        
1173
        /**
1174
         * Checks if a module is required by another
1175
         *
1176
         * @param dependentModule the module whose required modules are to be checked
1177
         * @param modulePackage the package of the module to check if required by another
1178
         * @return true if the module is required, else false
1179
         */
1180
        private static boolean isModuleRequiredByAnother(Module dependentModule, String modulePackage) {
1181
                return dependentModule.getRequiredModules() != null && dependentModule.getRequiredModules().contains(modulePackage);
1✔
1182
        }
1183
        
1184
        private static ModuleClassLoader removeClassLoader(Module mod) {
1185
                // create map if it is null
1186
                ModuleClassLoader cl = moduleClassLoaders.getIfPresent(mod);
1✔
1187
                if (cl == null) {
1✔
1188
                        log.warn("Module: " + mod.getModuleId() + " does not exist");
×
1189
                }
1190
                
1191
                moduleClassLoaders.invalidate(mod);
1✔
1192
                
1193
                return cl;
1✔
1194
        }
1195
        
1196
        /**
1197
         * Removes module from module repository
1198
         *
1199
         * @param mod module to unload
1200
         */
1201
        public static void unloadModule(Module mod) {
1202
                
1203
                // remove this module's advice and extensions
1204
                if (isModuleStarted(mod)) {
1✔
1205
                        stopModule(mod, true);
1✔
1206
                }
1207
                
1208
                // remove from list of loaded modules
1209
                getLoadedModules().remove(mod);
1✔
1210
                
1211
                if (mod != null) {
1✔
1212
                        // remove the file from the module repository
1213
                        File file = mod.getFile();
1✔
1214
                        
1215
                        boolean deleted = file.delete();
1✔
1216
                        if (!deleted) {
1✔
1217
                                file.deleteOnExit();
×
1218
                                log.warn("Could not delete " + file.getAbsolutePath());
×
1219
                        }
1220
                        
1221
                }
1222
        }
1✔
1223
        
1224
        /**
1225
         * Return all of the extensions associated with the given <code>pointId</code> Returns empty
1226
         * extension list if no modules extend this pointId
1227
         *
1228
         * @param pointId
1229
         * @return List of extensions
1230
         */
1231
        public static List<Extension> getExtensions(String pointId) {
1232
                List<Extension> extensions;
1233
                Map<String, List<Extension>> extensionMap = getExtensionMap();
×
1234
                
1235
                // get all extensions for this exact pointId
1236
                extensions = extensionMap.get(pointId);
×
1237
                if (extensions == null) {
×
1238
                        extensions = new ArrayList<>();
×
1239
                }
1240
                
1241
                // if this pointId doesn't contain the separator character, search
1242
                // for this point prepended with each MEDIA TYPE
1243
                if (!pointId.contains(Extension.EXTENSION_ID_SEPARATOR)) {
×
1244
                        for (MEDIA_TYPE mediaType : Extension.MEDIA_TYPE.values()) {
×
1245
                                
1246
                                // get all extensions for this type and point id
1247
                                List<Extension> tmpExtensions = extensionMap.get(Extension.toExtensionId(pointId, mediaType));
×
1248
                                
1249
                                // 'extensions' should be a unique list
1250
                                if (tmpExtensions != null) {
×
1251
                                        for (Extension ext : tmpExtensions) {
×
1252
                                                if (!extensions.contains(ext)) {
×
1253
                                                        extensions.add(ext);
×
1254
                                                }
1255
                                        }
×
1256
                                }
1257
                        }
1258
                }
1259
                
1260
                log.debug("Getting extensions defined by : " + pointId);
×
1261
                return extensions;
×
1262
        }
1263
        
1264
        /**
1265
         * Return all of the extensions associated with the given <code>pointId</code> Returns
1266
         * getExtension(pointId) if no modules extend this pointId for given media type
1267
         *
1268
         * @param pointId
1269
         * @param type Extension.MEDIA_TYPE
1270
         * @return List of extensions
1271
         */
1272
        public static List<Extension> getExtensions(String pointId, Extension.MEDIA_TYPE type) {
1273
                String key = Extension.toExtensionId(pointId, type);
×
1274
                List<Extension> extensions = getExtensionMap().get(key);
×
1275
                if (extensions != null) {
×
1276
                        log.debug("Getting extensions defined by : " + key);
×
1277
                        return extensions;
×
1278
                } else {
1279
                        return getExtensions(pointId);
×
1280
                }
1281
        }
1282
        
1283
        /**
1284
         * Get a list of required Privileges defined by the modules
1285
         *
1286
         * @return <code>List&lt;Privilege&gt;</code> of the required privileges
1287
         */
1288
        public static List<Privilege> getPrivileges() {
1289
                
1290
                List<Privilege> privileges = new ArrayList<>();
1✔
1291
                
1292
                for (Module mod : getStartedModules()) {
1✔
1293
                        privileges.addAll(mod.getPrivileges());
×
1294
                }
×
1295
                
1296
                log.debug(privileges.size() + " new privileges");
1✔
1297
                
1298
                return privileges;
1✔
1299
        }
1300
        
1301
        /**
1302
         * Get a list of required GlobalProperties defined by the modules
1303
         *
1304
         * @return <code>List&lt;GlobalProperty&gt;</code> object of the module's global properties
1305
         */
1306
        public static List<GlobalProperty> getGlobalProperties() {
1307
                
1308
                List<GlobalProperty> globalProperties = new ArrayList<>();
×
1309
                
1310
                for (Module mod : getStartedModules()) {
×
1311
                        globalProperties.addAll(mod.getGlobalProperties());
×
1312
                }
×
1313
                
1314
                log.debug(globalProperties.size() + " new global properties");
×
1315
                
1316
                return globalProperties;
×
1317
        }
1318
        
1319
        /**
1320
         * Checks whether the given module is activated
1321
         *
1322
         * @param mod Module to check
1323
         * @return true if the module is started, false otherwise
1324
         */
1325
        public static boolean isModuleStarted(Module mod) {
1326
                return getStartedModulesMap().containsValue(mod);
1✔
1327
        }
1328
        
1329
        /**
1330
         * Checks whether the given module, identified by its id, is started.
1331
         *
1332
         * @param moduleId module id. e.g formentry, logic
1333
         * @since 1.9
1334
         * @return true if the module is started, false otherwise
1335
         */
1336
        public static boolean isModuleStarted(String moduleId) {
1337
                return getStartedModulesMap().containsKey(moduleId);
1✔
1338
        }
1339
        
1340
        /**
1341
         * Get a module's classloader
1342
         *
1343
         * @param mod Module to fetch the class loader for
1344
         * @return ModuleClassLoader pertaining to this module. Returns null if the module is not started
1345
         * @throws ModuleException if the module does not have a registered classloader
1346
         */
1347
        public static ModuleClassLoader getModuleClassLoader(Module mod) throws ModuleException {
1348
                ModuleClassLoader mcl = getModuleClassLoaderMap().get(mod);
1✔
1349
                
1350
                if (mcl == null) {
1✔
1351
                        log.debug("Module classloader not found for module with id: " + mod.getModuleId());
1✔
1352
                }
1353
                
1354
                return mcl;
1✔
1355
        }
1356
        
1357
        /**
1358
         * Get a module's classloader via the module id
1359
         *
1360
         * @param moduleId <code>String</code> id of the module
1361
         * @return ModuleClassLoader pertaining to this module. Returns null if the module is not started
1362
         * @throws ModuleException if this module isn't started or doesn't have a classloader
1363
         * @see #getModuleClassLoader(Module)
1364
         */
1365
        public static ModuleClassLoader getModuleClassLoader(String moduleId) throws ModuleException {
1366
                Module mod = getStartedModulesMap().get(moduleId);
×
1367
                if (mod == null) {
×
1368
                        log.debug("Module id not found in list of started modules: " + moduleId);
×
1369
                }
1370
                
1371
                return getModuleClassLoader(mod);
×
1372
        }
1373
        
1374
        /**
1375
         * Returns all module classloaders This method will not return null
1376
         *
1377
         * @return Collection&lt;ModuleClassLoader&gt; all known module classloaders or empty list.
1378
         */
1379
        public static Collection<ModuleClassLoader> getModuleClassLoaders() {
1380
                Map<Module, ModuleClassLoader> classLoaders = getModuleClassLoaderMap();
1✔
1381
                if (classLoaders.size() > 0) {
1✔
1382
                        return classLoaders.values();
1✔
1383
                }
1384
                
1385
                return Collections.emptyList();
1✔
1386
        }
1387
        
1388
        /**
1389
         * Return all current classloaders keyed on module object
1390
         *
1391
         * @return Map&lt;Module, ModuleClassLoader&gt;
1392
         */
1393
        public static Map<Module, ModuleClassLoader> getModuleClassLoaderMap() {
1394
                // because the OpenMRS classloader depends on this static function, it is weirdly possible for this to get called
1395
                // as this classfile is loaded, in which case, the static final field can be null.
1396
                if (moduleClassLoaders == null) {
1✔
1397
                        return Collections.emptyMap();
×
1398
                }
1399
                
1400
                return moduleClassLoaders.asMap();
1✔
1401
        }
1402
        
1403
        /**
1404
         * Return the current extension map keyed on extension point id
1405
         *
1406
         * @return Map&lt;String, List&lt;Extension&gt;&gt;
1407
         */
1408
        public static Map<String, List<Extension>> getExtensionMap() {
1409
                return extensionMap;
×
1410
        }
1411
        
1412
        /**
1413
         * Tests whether all modules mentioned in module.requiredModules are loaded and started already (by
1414
         * being in the startedModules list)
1415
         *
1416
         * @param module
1417
         * @return true/false boolean whether this module's required modules are all started
1418
         */
1419
        private static boolean requiredModulesStarted(Module module) {
1420
                //required
1421
                for (String reqModPackage : module.getRequiredModules()) {
1✔
1422
                        boolean started = false;
1✔
1423
                        for (Module mod : getStartedModules()) {
1✔
1424
                                if (mod.getPackageName().equals(reqModPackage)) {
1✔
1425
                                        String reqVersion = module.getRequiredModuleVersion(reqModPackage);
1✔
1426
                                        if (reqVersion == null || ModuleUtil.compareVersion(mod.getVersion(), reqVersion) >= 0) {
1✔
1427
                                                started = true;
1✔
1428
                                        }
1429
                                        break;
1430
                                }
1431
                        }
×
1432
                        
1433
                        if (!started) {
1✔
1434
                                return false;
1✔
1435
                        }
1436
                }
1✔
1437
                
1438
                return true;
1✔
1439
        }
1440
        
1441
        /**
1442
         * Update the module: 1) Download the new module 2) Unload the old module 3) Load/start the new
1443
         * module
1444
         *
1445
         * @param mod
1446
         */
1447
        public static Module updateModule(Module mod) throws ModuleException {
1448
                if (mod.getDownloadURL() == null) {
×
1449
                        return mod;
×
1450
                }
1451
                
1452
                URL url;
1453
                try {
1454
                        url = new URL(mod.getDownloadURL());
×
1455
                }
1456
                catch (MalformedURLException e) {
×
1457
                        throw new ModuleException("Unable to download module update", e);
×
1458
                }
×
1459
                
1460
                unloadModule(mod);
×
1461
                
1462
                // copy content to a temporary file
1463
                InputStream inputStream = ModuleUtil.getURLStream(url);
×
1464
                log.warn("url pathname: " + url.getPath());
×
1465
                String filename = url.getPath().substring(url.getPath().lastIndexOf("/"));
×
1466
                File moduleFile = ModuleUtil.insertModuleFile(inputStream, filename);
×
1467
                
1468
                try {
1469
                        // load, and start the new module
1470
                        Module newModule = loadModule(moduleFile);
×
1471
                        startModule(newModule);
×
1472
                        return newModule;
×
1473
                }
1474
                catch (Exception e) {
×
1475
                        log.warn("Error while unloading old module and loading in new module");
×
1476
                        moduleFile.delete();
×
1477
                        return mod;
×
1478
                }
1479
                
1480
        }
1481
        
1482
        /**
1483
         * Validates the given token.
1484
         * <p>
1485
         * It is thread safe.
1486
         *
1487
         * @param token
1488
         * @since 1.9.2
1489
         */
1490
        public static boolean isTokenValid(DaemonToken token) {
1491
                if (token == null) {
×
1492
                        return false;
×
1493
                } else {
1494
                        //We need to synchronize to guarantee that the last passed token is valid.
1495
                        synchronized (daemonTokens) {
×
1496
                                DaemonToken validToken = daemonTokens.getIfPresent(token.getId());
×
1497
                                //Compare by reference to defend from overridden equals.
1498
                                return validToken != null && validToken == token;
×
1499
                        }
1500
                }
1501
        }
1502
        
1503
        /**
1504
         * Passes a daemon token to the given module.
1505
         * <p>
1506
         * The token is passed to that module's {@link ModuleActivator} if it implements
1507
         * {@link DaemonTokenAware}.
1508
         * <p>
1509
         * This method is called automatically before {@link ModuleActivator#contextRefreshed()} or
1510
         * {@link ModuleActivator#started()}. Note that it may be called multiple times and there is no
1511
         * guarantee that it will always pass the same token. The last passed token is valid, whereas
1512
         * previously passed tokens may be invalidated.
1513
         * <p>
1514
         * It is thread safe.
1515
         *
1516
         * @param module
1517
         * @since 1.9.2
1518
         */
1519
        static void passDaemonToken(Module module) {
1520
                ModuleActivator moduleActivator = module.getModuleActivator();
×
1521
                if (moduleActivator instanceof DaemonTokenAware) {
×
1522
                        DaemonToken daemonToken = getDaemonToken(module);
×
1523
                        ((DaemonTokenAware) module.getModuleActivator()).setDaemonToken(daemonToken);
×
1524
                }
1525
        }
×
1526
        
1527
        /**
1528
         * Gets a new or existing token. Uses weak references for tokens so that they are garbage collected
1529
         * when not needed.
1530
         * <p>
1531
         * It is thread safe.
1532
         *
1533
         * @param module
1534
         * @return the token
1535
         */
1536
        private static DaemonToken getDaemonToken(Module module) {
1537
                DaemonToken token;
1538
                try {
1539
                        token = daemonTokens.get(module.getModuleId(), () -> new DaemonToken(module.getModuleId()));
×
1540
                }
1541
                catch (ExecutionException e) {
×
1542
                        throw new APIException(e);
×
1543
                }
×
1544
                
1545
                return token;
×
1546
        }
1547
        
1548
        /**
1549
         * Returns the description for the [moduleId].started global property
1550
         *
1551
         * @param moduleId
1552
         * @return description to use for the .started property
1553
         */
1554
        private static String getGlobalPropertyStartedDescription(String moduleId) {
1555
                String ret = "DO NOT MODIFY. true/false whether or not the " + moduleId;
1✔
1556
                ret += " module has been started.  This is used to make sure modules that were running ";
1✔
1557
                ret += " prior to a restart are started again";
1✔
1558
                
1559
                return ret;
1✔
1560
        }
1561
        
1562
        /**
1563
         * Returns the description for the [moduleId].mandatory global property
1564
         *
1565
         * @param moduleId
1566
         * @return description to use for .mandatory property
1567
         */
1568
        private static String getGlobalPropertyMandatoryModuleDescription(String moduleId) {
1569
                String ret = "true/false whether or not the " + moduleId;
1✔
1570
                ret += " module MUST start when openmrs starts.  This is used to make sure that mission critical";
1✔
1571
                ret += " modules are always running if openmrs is running.";
1✔
1572
                
1573
                return ret;
1✔
1574
        }
1575
        
1576
        /**
1577
         * Convenience method to save a global property with the given value. Proxy privileges are added so
1578
         * that this can occur at startup.
1579
         *
1580
         * @param key the property for this global property
1581
         * @param value the value for this global property
1582
         * @param desc the description
1583
         * @see AdministrationService#saveGlobalProperty(GlobalProperty)
1584
         */
1585
        private static void saveGlobalProperty(String key, String value, String desc) {
1586
                try {
1587
                        AdministrationService as = Context.getAdministrationService();
1✔
1588
                        GlobalProperty gp = as.getGlobalPropertyObject(key);
1✔
1589
                        if (gp == null) {
1✔
1590
                                gp = new GlobalProperty(key, value, desc);
1✔
1591
                        } else {
1592
                                gp.setPropertyValue(value);
1✔
1593
                        }
1594
                        
1595
                        as.saveGlobalProperty(gp);
1✔
1596
                }
1597
                catch (Exception e) {
×
1598
                        log.warn("Unable to save the global property", e);
×
1599
                }
1✔
1600
        }
1✔
1601
        
1602
        /**
1603
         * Convenience method used to identify module interdependencies and alert the user before modules
1604
         * are shut down.
1605
         *
1606
         * @param moduleId the moduleId used to identify the module being validated
1607
         * @return List&lt;dependentModules&gt; the list of moduleId's which depend on the module about to
1608
         *         be shutdown.
1609
         * @since 1.10
1610
         */
1611
        public static List<String> getDependencies(String moduleId) {
1612
                List<String> dependentModules = null;
×
1613
                Module module = getModuleById(moduleId);
×
1614
                
1615
                Map<String, Module> startedModules = getStartedModulesMap();
×
1616
                String modulePackage = module.getPackageName();
×
1617
                
1618
                for (Entry<String, Module> entry : startedModules.entrySet()) {
×
1619
                        if (!moduleId.equals(entry.getKey()) && entry.getValue().getRequiredModules().contains(modulePackage)) {
×
1620
                                if (dependentModules == null) {
×
1621
                                        dependentModules = new ArrayList<>();
×
1622
                                }
1623
                                dependentModules.add(entry.getKey() + " " + entry.getValue().getVersion());
×
1624
                        }
1625
                }
×
1626
                return dependentModules;
×
1627
        }
1628

1629
        /**
1630
         * Receives the {@link Daemon} caller key. Called only by {@link Daemon} during its initialization.
1631
         *
1632
         * @param callerKey the caller key issued by {@link Daemon}
1633
         * @since 3.0.0, 2.9.0, 2.8.9
1634
         */
1635
        public static void setDaemonCallerKey(Daemon.CallerKey callerKey) {
1636
                if (callerKey != null && daemonCallerKey == null) {
1✔
1637
                        daemonCallerKey = callerKey;
1✔
1638
                }
1639
        }
1✔
1640

1641
        private static Daemon.CallerKey daemonCallerKey() {
1642
                if (daemonCallerKey == null) {
1✔
1643
                        // Guarantee Daemon has initialized and therefore handed us the key, regardless of the order in
1644
                        // which the two classes were first loaded.
NEW
1645
                        Daemon.ensureInitialized();
×
1646
                }
1647
                return daemonCallerKey;
1✔
1648
        }
1649
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc