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

openmrs / openmrs-core / 29845974054

21 Jul 2026 03:51PM UTC coverage: 66.106% (-0.004%) from 66.11%
29845974054

push

github

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

60 of 90 new or added lines in 6 files covered. (66.67%)

6 existing lines in 4 files now uncovered.

24347 of 36830 relevant lines covered (66.11%)

0.66 hits per line

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

51.2
/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} that 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
                                // run module's optional liquibase.xml immediately after sqldiff.xml
701
                                runLiquibase(module);
1✔
702
                                
703
                                // effectively mark this module as started successfully
704
                                getStartedModulesMap().put(moduleId, module);
1✔
705

706
                                actualStartupOrder.add(moduleId);
1✔
707
                                
708
                                try {
709
                                        // save the state of this module for future restarts
710
                                        saveGlobalProperty(moduleId + ".started", "true", getGlobalPropertyStartedDescription(moduleId));
1✔
711
                                        
712
                                        // save the mandatory status
713
                                        saveGlobalProperty(moduleId + ".mandatory", String.valueOf(module.isMandatory()),
1✔
714
                                                getGlobalPropertyMandatoryModuleDescription(moduleId));
1✔
715
                                }
716
                                catch (Exception e) {
×
717
                                        // pass over errors because this doesn't really concern startup
718
                                        // passing over this also allows for multiple of the same-named modules
719
                                        // to be loaded in junit tests that are run within one session
720
                                        log.debug("Got an error when trying to set the global property on module startup", e);
×
721
                                }
1✔
722
                                
723
                                // (this must be done after putting the module in the started
724
                                // list)
725
                                // if this module defined any privileges or global properties,
726
                                // make sure they are added to the database
727
                                // (Unfortunately, placing the call here will duplicate work
728
                                // done at initial app startup)
729
                                if (!module.getPrivileges().isEmpty() || !module.getGlobalProperties().isEmpty()) {
1✔
730
                                        log.debug("Updating core dataset");
×
731
                                        Context.checkCoreDataset();
×
732
                                        // checkCoreDataset() currently doesn't throw an error. If
733
                                        // it did, it needs to be
734
                                        // caught and the module needs to be stopped and given a
735
                                        // startup error
736
                                }
737
                                
738
                                // should be near the bottom so the module has all of its stuff
739
                                // set up for it already.
740
                                try {
741
                                        if (module.getModuleActivator() != null) {
1✔
742
                                                // if extends BaseModuleActivator
743
                                                module.getModuleActivator().willStart();
1✔
744
                                        }
745
                                }
746
                                catch (ModuleException e) {
×
747
                                        // just rethrow module exceptions. This should be used for a
748
                                        // module marking that it had trouble starting
749
                                        throw e;
×
750
                                }
751
                                catch (Exception e) {
×
752
                                        throw new ModuleException("Error while calling module's Activator.startup()/willStart() method", e);
×
753
                                }
1✔
754
                                
755
                                // erase any previous startup error
756
                                module.clearStartupError();
1✔
757
                        }
758
                        catch (Exception e) {
×
759
                                log.warn("Error while trying to start module: " + moduleId, e);
×
760
                                module.setStartupErrorMessage("Error while trying to start module", e);
×
761
                                notifySuperUsersAboutModuleFailure(module);
×
762
                                // undo all of the actions in startup
763
                                try {
764
                                        boolean skipOverStartedProperty = false;
×
765
                                        
766
                                        if (e instanceof ModuleMustStartException) {
×
767
                                                skipOverStartedProperty = true;
×
768
                                        }
769
                                        
770
                                        stopModule(module, skipOverStartedProperty, true);
×
771
                                }
772
                                catch (Exception e2) {
×
773
                                        // this will probably occur about the same place as the
774
                                        // error in startup
775
                                        log.debug("Error while stopping module: " + moduleId, e2);
×
776
                                }
×
777
                        }
1✔
778
                        
779
                }
780
                
781
                if (applicationContext != null) {
1✔
782
                        ModuleUtil.refreshApplicationContext(applicationContext, isOpenmrsStartup, module);
×
783
                }
784
                
785
                return module;
1✔
786
        }
787
        
788
        private static void registerProvidedPackages(ModuleClassLoader moduleClassLoader) {
789
                for (String providedPackage : moduleClassLoader.getProvidedPackages()) {
1✔
790
                        Set<ModuleClassLoader> newSet = new HashSet<>();
1✔
791
                        
792
                        Set<ModuleClassLoader> set = providedPackages.get(providedPackage);
1✔
793
                        if (set != null) {
1✔
794
                                newSet.addAll(set);
1✔
795
                        }
796
                        
797
                        newSet.add(moduleClassLoader);
1✔
798
                        providedPackages.put(providedPackage, newSet);
1✔
799
                }
1✔
800
        }
1✔
801
        
802
        private static void unregisterProvidedPackages(ModuleClassLoader moduleClassLoader) {
803
                for (String providedPackage : moduleClassLoader.getProvidedPackages()) {
1✔
804
                        Set<ModuleClassLoader> newSet = new HashSet<>();
1✔
805
                        
806
                        Set<ModuleClassLoader> set = providedPackages.get(providedPackage);
1✔
807
                        if (set != null) {
1✔
808
                                newSet.addAll(set);
1✔
809
                        }
810
                        newSet.remove(moduleClassLoader);
1✔
811
                        
812
                        providedPackages.put(providedPackage, newSet);
1✔
813
                }
1✔
814
        }
1✔
815
        
816
        public static Set<ModuleClassLoader> getModuleClassLoadersForPackage(String packageName) {
817
                Set<ModuleClassLoader> set = providedPackages.get(packageName);
1✔
818
                if (set == null) {
1✔
819
                        return Collections.emptySet();
1✔
820
                } else {
821
                        return new HashSet<>(set);
1✔
822
                }
823
        }
824
        
825
        /**
826
         * Gets the error message of a module which fails to start.
827
         *
828
         * @param module the module that has failed to start.
829
         * @return the message text.
830
         */
831
        private static String getFailedToStartModuleMessage(Module module) {
832
                String[] params = { module.getName(), String.join(",", getMissingRequiredModules(module)) };
×
833
                return Context.getMessageSourceService().getMessage("Module.error.moduleCannotBeStarted", params,
×
834
                        Context.getLocale());
×
835
        }
836
        
837
        /**
838
         * Gets the error message of cyclic dependencies between modules
839
         *
840
         * @return the message text.
841
         */
842
        private static String getCyclicDependenciesMessage(String message) {
843
                return Context.getMessageSourceService().getMessage("Module.error.cyclicDependencies", new Object[] { message },
×
844
                        Context.getLocale());
×
845
        }
846
        
847
        /**
848
         * Loop over the given module's advice objects and load them into the Context This needs to be
849
         * called for all started modules after every restart of the Spring Application Context
850
         *
851
         * @param module
852
         */
853
        public static void loadAdvice(Module module) {
854
                for (AdvicePoint advice : module.getAdvicePoints()) {
×
855
                        Class<?> cls;
856
                        try {
857
                                cls = Context.loadClass(advice.getPoint());
×
858
                                Object aopObject = advice.getClassInstance();
×
859
                                if (aopObject instanceof Advisor) {
×
860
                                        log.debug("adding advisor [{}]", aopObject.getClass());
×
861
                                        Context.addAdvisor(cls, (Advisor) aopObject);
×
862
                                } else if (aopObject != null) {
×
863
                                        log.debug("adding advice [{}]", aopObject.getClass());
×
864
                                        Context.addAdvice(cls, (Advice) aopObject);
×
865
                                } else {
866
                                        log.debug("Could not load advice class for {} [{}]", advice.getPoint(), advice.getClassName());
×
867
                                }
868
                        }
869
                        catch (ClassNotFoundException | NoClassDefFoundError e) {
×
870
                                log.warn("Could not load advice point [{}]", advice.getPoint(), e);
×
871
                        }
×
872
                }
×
873
        }
×
874
        
875
        /**
876
         * Execute the given sql diff section for the given module
877
         *
878
         * @param module the module being executed on
879
         * @param version the version of this sql diff
880
         * @param sql the actual sql statements to run (separated by semi colons)
881
         */
882
        private static void runDiff(Module module, String version, String sql) {
883
                AdministrationService as = Context.getAdministrationService();
×
884
                
885
                String key = module.getModuleId() + ".database_version";
×
886
                GlobalProperty gp = as.getGlobalPropertyObject(key);
×
887
                
888
                boolean executeSQL = false;
×
889
                
890
                // check given version against current version
891
                if (gp != null && StringUtils.hasLength(gp.getPropertyValue())) {
×
892
                        String currentDbVersion = gp.getPropertyValue();
×
893
                        if (log.isDebugEnabled()) {
×
894
                                log.debug("version:column {}:{}", version, currentDbVersion);
×
895
                                log.debug("compare: {}", ModuleUtil.compareVersion(version, currentDbVersion));
×
896
                        }
897
                        if (ModuleUtil.compareVersion(version, currentDbVersion) > 0) {
×
898
                                executeSQL = true;
×
899
                        }
900
                } else {
×
901
                        executeSQL = true;
×
902
                }
903
                
904
                // version is greater than the currently installed version. execute this update.
905
                if (executeSQL) {
×
906
                        try {
907
                                Context.addProxyPrivilege(PrivilegeConstants.SQL_LEVEL_ACCESS);
×
908
                                log.debug("Executing sql: " + sql);
×
909
                                String[] sqlStatements = sql.split(";");
×
910
                                for (String sqlStatement : sqlStatements) {
×
911
                                        if (sqlStatement.trim().length() > 0) {
×
912
                                                as.executeSQL(sqlStatement, false);
×
913
                                        }
914
                                }
915
                        }
916
                        finally {
917
                                Context.removeProxyPrivilege(PrivilegeConstants.SQL_LEVEL_ACCESS);
×
918
                        }
919
                        
920
                        // save the global property
921
                        try {
922
                                Context.addProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
×
923
                                
924
                                String description = "DO NOT MODIFY.  Current database version number for the " + module.getModuleId()
×
925
                                        + " module.";
926
                                
927
                                if (gp == null) {
×
928
                                        log.info("Global property " + key + " was not found. Creating one now.");
×
929
                                        gp = new GlobalProperty(key, version, description);
×
930
                                        as.saveGlobalProperty(gp);
×
931
                                } else if (!gp.getPropertyValue().equals(version)) {
×
932
                                        log.info("Updating global property " + key + " to version: " + version);
×
933
                                        gp.setDescription(description);
×
934
                                        gp.setPropertyValue(version);
×
935
                                        as.saveGlobalProperty(gp);
×
936
                                } else {
937
                                        log.error("Should not be here. GP property value and sqldiff version should not be equal");
×
938
                                }
939
                                
940
                        }
941
                        finally {
942
                                Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
×
943
                        }
944
                        
945
                }
946
                
947
        }
×
948
        
949
        /**
950
         * Execute all not run changeSets in liquibase.xml for the given module
951
         *
952
         * @param module the module being executed on
953
         */
954
        private static void runLiquibase(Module module) {
955
                ModuleClassLoader moduleClassLoader = getModuleClassLoader(module);
1✔
956
                boolean liquibaseFileExists = false;
1✔
957
                
958
                if (moduleClassLoader != null) {
1✔
959
                        try (InputStream inStream = moduleClassLoader.getResourceAsStream(MODULE_CHANGELOG_FILENAME)) {
1✔
960
                                liquibaseFileExists = (inStream != null);
1✔
961
                        }
962
                        catch (IOException ignored) {
×
963
                                
964
                        }
1✔
965
                }
966
                
967
                if (liquibaseFileExists) {
1✔
968
                        try {
969
                                // run liquibase.xml by Liquibase API
970
                                DatabaseUpdater.executeChangelog(MODULE_CHANGELOG_FILENAME, new Contexts(), null, moduleClassLoader);
×
971
                        }
972
                        catch (InputRequiredException e) {
×
973
                                // the user would be stepped through the questions returned here.
974
                                throw new ModuleException("Input during database updates is not yet implemented.", module.getName(), e);
×
975
                        }
976
                        catch (Exception e) {
×
977
                                throw new ModuleException("Unable to update data model using " + MODULE_CHANGELOG_FILENAME + ".",
×
978
                                        module.getName(), e);
×
979
                        }
×
980
                }
981
        }
1✔
982
        
983
        /**
984
         * Runs through the advice and extension points and removes from api. <br>
985
         * Also calls mod.Activator.shutdown()
986
         *
987
         * @param mod module to stop
988
         * @see ModuleFactory#stopModule(Module, boolean, boolean)
989
         */
990
        public static void stopModule(Module mod) {
991
                stopModule(mod, false, false);
1✔
992
        }
1✔
993
        
994
        /**
995
         * Runs through the advice and extension points and removes from api.<br>
996
         * Also calls mod.Activator.shutdown()
997
         *
998
         * @param mod the module to stop
999
         * @param isShuttingDown true if this is called during the process of shutting down openmrs
1000
         * @see #stopModule(Module, boolean, boolean)
1001
         */
1002
        public static void stopModule(Module mod, boolean isShuttingDown) {
1003
                stopModule(mod, isShuttingDown, false);
1✔
1004
        }
1✔
1005
        
1006
        /**
1007
         * Runs through the advice and extension points and removes from api.<br>
1008
         * <code>skipOverStartedProperty</code> should only be true when openmrs is stopping modules because
1009
         * it is shutting down. When normally stopping a module, use {@link #stopModule(Module)} (or leave
1010
         * value as false). This property controls whether the globalproperty is set for startup/shutdown.
1011
         * <br>
1012
         * Also calls module's {@link ModuleActivator#stopped()}
1013
         *
1014
         * @param mod module to stop
1015
         * @param skipOverStartedProperty true if we don't want to set &lt;moduleid&gt;.started to false
1016
         * @param isFailedStartup true if this is being called as a cleanup because of a failed module
1017
         *            startup
1018
         * @return list of dependent modules that were stopped because this module was stopped. This will
1019
         *         never be null.
1020
         */
1021
        public static List<Module> stopModule(Module mod, boolean skipOverStartedProperty, boolean isFailedStartup)
1022
                throws ModuleMustStartException {
1023
                
1024
                List<Module> dependentModulesStopped = new ArrayList<>();
1✔
1025
                
1026
                if (mod != null) {
1✔
1027
                        
1028
                        if (!ModuleFactory.isModuleStarted(mod)) {
1✔
1029
                                return dependentModulesStopped;
×
1030
                        }
1031
                        
1032
                        try {
1033
                                // if extends BaseModuleActivator
1034
                                if (mod.getModuleActivator() != null) {
1✔
1035
                                        mod.getModuleActivator().willStop();
1✔
1036
                                }
1037
                        }
1038
                        catch (Exception t) {
×
1039
                                log.warn("Unable to call module's Activator.willStop() method", t);
×
1040
                        }
1✔
1041
                        
1042
                        String moduleId = mod.getModuleId();
1✔
1043
                        
1044
                        // don't allow mandatory modules to be stopped
1045
                        // don't use database checks here because spring might be in a bad state
1046
                        if (!isFailedStartup && mod.isMandatory()) {
1✔
1047
                                throw new MandatoryModuleException(moduleId);
×
1048
                        }
1049

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

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

1640
        private static Daemon.CallerKey daemonCallerKey() {
1641
                if (daemonCallerKey == null) {
1✔
1642
                        // Guarantee Daemon has initialized and therefore handed us the key, regardless of the order in
1643
                        // which the two classes were first loaded.
NEW
1644
                        Daemon.ensureInitialized();
×
1645
                }
1646
                return daemonCallerKey;
1✔
1647
        }
1648
}
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