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

openmrs / openmrs-core / 44617254895

19 Nov 2026 09:17PM UTC coverage: 69.102% (-0.2%) from 69.299%
44617254895

Pull #6841

github

web-flow
Merge 613c9f9ce into 57615988d
Pull Request #6841: TRUNK-6868: Allow the session timeout to be configured (2.8.x)

24 of 28 new or added lines in 2 files covered. (85.71%)

88 existing lines in 14 files now uncovered.

26833 of 38831 relevant lines covered (69.1%)

0.69 hits per line

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

67.31
/api/src/main/java/org/openmrs/util/DatabaseUpdater.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.util;
11

12
import liquibase.Contexts;
13
import liquibase.GlobalConfiguration;
14
import liquibase.LabelExpression;
15
import liquibase.Liquibase;
16
import liquibase.RuntimeEnvironment;
17
import liquibase.Scope;
18
import liquibase.changelog.ChangeLogHistoryServiceFactory;
19
import liquibase.changelog.ChangeLogIterator;
20
import liquibase.changelog.ChangeSet;
21
import liquibase.changelog.DatabaseChangeLog;
22
import liquibase.changelog.filter.ChangeSetFilterResult;
23
import liquibase.changelog.filter.ContextChangeSetFilter;
24
import liquibase.changelog.filter.DbmsChangeSetFilter;
25
import liquibase.changelog.filter.ShouldRunChangeSetFilter;
26
import liquibase.changelog.visitor.UpdateVisitor;
27
import liquibase.command.core.StatusCommandStep;
28
import liquibase.database.Database;
29
import liquibase.database.DatabaseFactory;
30
import liquibase.database.jvm.JdbcConnection;
31
import liquibase.exception.LiquibaseException;
32
import liquibase.exception.LockException;
33
import liquibase.lockservice.LockService;
34
import liquibase.lockservice.LockServiceFactory;
35
import liquibase.resource.CompositeResourceAccessor;
36
import liquibase.resource.FileSystemResourceAccessor;
37
import liquibase.resource.ResourceAccessor;
38
import org.apache.commons.io.IOUtils;
39
import org.openmrs.api.context.Context;
40
import org.openmrs.liquibase.ChangeLogDetective;
41
import org.openmrs.liquibase.ChangeLogVersionFinder;
42
import org.openmrs.liquibase.ChangeSetExecutorCallback;
43
import org.openmrs.liquibase.LiquibaseProvider;
44
import org.openmrs.liquibase.OpenmrsClassLoaderResourceAccessor;
45
import org.openmrs.module.ModuleClassLoader;
46
import org.slf4j.Logger;
47
import org.slf4j.LoggerFactory;
48

49
import java.io.BufferedWriter;
50
import java.io.File;
51
import java.io.FileNotFoundException;
52
import java.io.FileOutputStream;
53
import java.io.InputStream;
54
import java.io.OutputStreamWriter;
55
import java.io.PrintWriter;
56
import java.nio.charset.StandardCharsets;
57
import java.sql.Connection;
58
import java.sql.DriverManager;
59
import java.sql.SQLException;
60
import java.util.ArrayList;
61
import java.util.Arrays;
62
import java.util.Calendar;
63
import java.util.Collections;
64
import java.util.Date;
65
import java.util.HashMap;
66
import java.util.HashSet;
67
import java.util.LinkedList;
68
import java.util.List;
69
import java.util.Map;
70
import java.util.Properties;
71
import java.util.Set;
72

73
/**
74
 * This class uses Liquibase to update the database. <br>
75
 * <br>
76
 * See src/main/resources/liquibase-update-to-latest.xml for the changes. This class will also run
77
 * arbitrary liquibase xml files on the associated database as well. Details for the database are
78
 * taken from the openmrs runtime properties.
79
 *
80
 * @since 1.5
81
 */
82
public class DatabaseUpdater {
×
83
        
84
        private static final Logger log = LoggerFactory.getLogger(DatabaseUpdater.class);
1 ✔
85
        
86
        private static final String EMPTY_CHANGE_LOG_FILE = "liquibase-empty-changelog.xml";
87
        
88
        public static final String CONTEXT = "core";
89
        
90
        public static final String DATABASE_UPDATES_LOG_FILE = "liquibaseUpdateLogs.txt";
91
        
92
        private static Integer authenticatedUserId;
93
        
94
        private static final ChangeLogDetective changeLogDetective;
95
        
96
        private static final ChangeLogVersionFinder changeLogVersionFinder;
97
        
98
        private static LiquibaseProvider liquibaseProvider;
99
        
100
        static {
101
                changeLogDetective = ChangeLogDetective.getInstance();
1 ✔
102
                changeLogVersionFinder = new ChangeLogVersionFinder();
1 ✔
103
        }
104
        
105
        /**
106
         * Allows to inject a LiquibaseProvider instance for testing purposes.
107
         * 
108
         * @param liquibaseProvider
109
         */
110
        static void setLiquibaseProvider(LiquibaseProvider liquibaseProvider) {
111
                DatabaseUpdater.liquibaseProvider = liquibaseProvider;
1 ✔
112
        }
1 ✔
113

114
        /**
115
         * Removes any LiquibaseProvider instance that was set for testing purposes.
116
         */
117
        static void unsetLiquibaseProvider() {
118
                DatabaseUpdater.liquibaseProvider = null;
1 ✔
119
        }
1 ✔
120
        
121
        /**
122
         * Holds the update warnings generated by the custom liquibase changesets as they are executed
123
         */
124
        private static volatile List<String> updateWarnings = null;
1 ✔
125
        
126
        /**
127
         * Convenience method to run the changesets using Liquibase to bring the database up to a version
128
         * compatible with the code
129
         */
130
        public static void executeChangelog() throws DatabaseUpdateException {
131
                final LiquibaseProvider liquibaseProvider = new DatabaseUpdaterLiquibaseProvider();
×
132
                
133
                final List<String> changeLogs;
134
                try {
135
                        final String version = changeLogDetective.getInitialLiquibaseSnapshotVersion(CONTEXT, liquibaseProvider);
×
136
                        log.debug(
×
137
                                "updating the database with versions of liquibase-update-to-latest files greater than '{}'",
138
                                version);
139
                        
140
                        changeLogs = changeLogDetective.getUnrunLiquibaseUpdateFileNames(version, CONTEXT, liquibaseProvider);
×
141
                        log.debug("found applicable Liquibase update change logs: {}", changeLogs);
×
142
                }
143
                catch (Exception e) {
×
144
                        log.error("Error while trying to find database changes to run", e);
×
145
                        throw new DatabaseUpdateException("Error while trying to find database changes to run", e);
×
146
                }
×
147
                
148
                if (changeLogs.isEmpty()) {
×
149
                        return;
×
150
                }
151
                
152
                for (String changeLog : changeLogs) {
×
153
                        log.debug("applying Liquibase changelog '{}'", changeLog);
×
154
                        executeChangelog(changeLog, (ChangeSetExecutorCallback) null);
×
155
                }
×
156
        }
×
157
        
158
        /**
159
         * Run changesets on database using Liquibase to get the database up to the most recent version
160
         *
161
         * @param changelog the liquibase changelog file to use (or null to use the default file)
162
         * @param userInput nullable map from question to user answer. Used if a call to update(null) threw
163
         *            an {@link InputRequiredException}
164
         * @throws DatabaseUpdateException if an error occurs
165
         * @deprecated as of 2.4 see {@link #executeChangelog(String, ChangeSetExecutorCallback)}
166
         */
167
        @Deprecated
168
        public static void executeChangelog(String changelog, Map<String, Object> userInput)
169
                throws DatabaseUpdateException {
170
                log.debug("Executing changelog: {}" , changelog);
×
171
                executeChangelog(changelog, (ChangeSetExecutorCallback) null);
×
172
        }
×
173

174
        /**
175
         * Executes the given changelog file. This file is assumed to be on the classpath.
176
         *
177
         * @param changelog The string filename of a liquibase changelog xml file to run
178
         * @return A list of messages or warnings generated by the executed changesets
179
         */
180
        public static List<String> executeChangelog(String changelog, ChangeSetExecutorCallback callback)
181
                throws DatabaseUpdateException {
182
                log.debug("installing the tables into the database");
1 ✔
183
                
184
                if (changelog == null) {
1 ✔
185
                        throw new IllegalArgumentException("changelog must not be null");
1 ✔
186
                }
187
                
188
                try {
189
                        log.debug("executing liquibase changelog {}", changelog);
1 ✔
190
                        return executeChangelog(changelog, new Contexts(CONTEXT), callback, null);
1 ✔
191
                }
192
                catch (Exception e) {
×
193
                        throw new DatabaseUpdateException("There was an error while updating the database to the latest. file: "
×
194
                                + changelog + ". Error: " + e.getMessage(), e);
×
195
                }
196
        }
197
        
198
        /**
199
         * This code was borrowed from the liquibase jar so that we can call the given callback function.
200
         *
201
         * @param changeLogFile the file to execute
202
         * @param contexts the liquibase changeset context
203
         * @param callback the function to call after every changeset
204
         * @return A list of messages or warnings generated by the executed changesets
205
         * @throws Exception
206
         */
207
        public static List<String> executeChangelog(String changeLogFile, Contexts contexts, ChangeSetExecutorCallback callback,
208
                ClassLoader cl) throws Exception {
209
                
210
                if (cl == null) {
1 ✔
211
                        cl = OpenmrsClassLoader.getInstance();
1 ✔
212
                }
213
                
214
                Thread.currentThread().setContextClassLoader(cl);
1 ✔
215
                
216
                log.debug("Setting up liquibase object to run changelog: {}", changeLogFile);
1 ✔
217
                Liquibase liquibase = getLiquibase(changeLogFile, cl);
1 ✔
218

219
                Database database = null;
1 ✔
220
                LockService lockHandler = null;
1 ✔
221
                
222
                try {
223
                        database = liquibase.getDatabase();
1 ✔
224
                        lockHandler = LockServiceFactory.getInstance().getLockService(database);
1 ✔
225
                        lockHandler.waitForLock();
1 ✔
226
                        
227
                        Map<String, Object> scopeValues = new HashMap<>();
1 ✔
228
                        scopeValues.put(Scope.Attr.resourceAccessor.name(), getCompositeResourceAccessor(null));
1 ✔
229
                        String scopeId = null;
1 ✔
230
                        try {
231
                                scopeId = Scope.enter(scopeValues);
1 ✔
232

233
                                // counted inside the scope: for already-run runOnChange changesets the status check recomputes
234
                                // checksums, which reads files such as <sqlFile> through the scope's resource accessor
235
                                int numChangeSetsToRun = new StatusCommandStep()
1 ✔
236
                                        .listUnrunChangeSets(contexts,
1 ✔
237
                                                new LabelExpression(), liquibase.getDatabaseChangeLog(), database).size();
1 ✔
238

239
                                DatabaseChangeLog changeLog = liquibase.getDatabaseChangeLog();
1 ✔
240
                                changeLog.setChangeLogParameters(liquibase.getChangeLogParameters());
1 ✔
241
                                changeLog.validate(database);
1 ✔
242

243
                                ChangeLogIterator logIterator = new ChangeLogIterator(changeLog, new ShouldRunChangeSetFilter(database),
1 ✔
244
                                        new ContextChangeSetFilter(contexts), new DbmsChangeSetFilter(database));
245

246
                                // ensure that the change log history service is initialised
247
                                Scope.getCurrentScope().getSingleton(ChangeLogHistoryServiceFactory.class).getChangeLogService(database).init();
1 ✔
248

249
                                logIterator.run(new OpenmrsUpdateVisitor(database, callback, numChangeSetsToRun),
1 ✔
250
                                        new RuntimeEnvironment(database, contexts, new LabelExpression()));
251
                        }
252
                        finally {
253
                                try {
254
                                        Scope.exit(scopeId);
1 ✔
255
                                }
256
                                catch (Exception e) {
×
257
                                        log.warn("An error occurred trying to exit the liquibase scope", e);
×
258
                                }
1 ✔
259
                        }
260
                }
261
                finally {
262
                        try {
263
                                if (lockHandler != null) {
1 ✔
264
                                        lockHandler.releaseLock();
1 ✔
265
                                }
266
                        }
267
                        catch (Exception e) {
×
268
                                log.error("Could not release lock", e);
×
269
                        }
1 ✔
270

271
                        try {
272
                                if (database != null && database.getConnection() != null) {
1 ✔
273
                                        database.getConnection().close();
1 ✔
274
                                }
275
                        }
276
                        catch (Exception e) {
×
277
                                //pass
278
                        }
1 ✔
279
                }
280
                
281
                return updateWarnings;
1 ✔
282
        }
283
        
284
        /**
285
         * Ask Liquibase if it needs to do any updates.
286
         *
287
         * @return true/false whether database updates are required
288
         * @throws Exception when an exception is raised while processing Liquibase changelog files
289
         */
290
        public static boolean updatesRequired() throws Exception {
291
                log.debug("checking for updates");
1 ✔
292
                List<OpenMRSChangeSet> changesets = getUnrunDatabaseChanges(new DatabaseUpdaterLiquibaseProvider());
1 ✔
293
                
294
                // if the db is locked, it means there was a crash
295
                // or someone is executing db updates right now. either way
296
                // returning true here stops the openmrs startup and shows
297
                // the user the maintenance wizard for updates
298
                if (isLocked() && changesets.isEmpty()) {
1 ✔
299
                        // if there is a db lock but there are no db changes we undo the
300
                        // lock
301
                        DatabaseUpdater.releaseDatabaseLock();
×
302
                        log.debug("db lock found and released automatically");
×
303
                        return false;
×
304
                }
305
                
306
                return !changesets.isEmpty();
1 ✔
307
        }
308
        
309
        /**
310
         * Ask Liquibase if it needs to do any updates
311
         *
312
         * @param changeLogFilenames the filenames of all files to search for unrun changesets
313
         * @return true/false whether database updates are required <strong>Should</strong> always have a
314
         *         valid update to latest file
315
         */
316
        public static boolean updatesRequired(String... changeLogFilenames) throws Exception {
317
                log.debug("checking for updates");
×
318
                List<OpenMRSChangeSet> changesets = getUnrunDatabaseChanges(changeLogFilenames);
×
319
                return !changesets.isEmpty();
×
320
        }
321
        
322
        /**
323
         * Indicates whether automatic database updates are allowed by this server. Automatic updates are
324
         * disabled by default. In order to enable automatic updates, the admin needs to add
325
         * 'auto_update_database=true' to the runtime properties file.
326
         *
327
         * @return true/false whether the 'auto_update_database' has been enabled.
328
         */
329
        public static Boolean allowAutoUpdate() {
330
                String allowAutoUpdate = Context.getRuntimeProperties()
×
331
                        .getProperty(OpenmrsConstants.AUTO_UPDATE_DATABASE_RUNTIME_PROPERTY, "false");
×
332
                
333
                return "true".equals(allowAutoUpdate);
×
334
                
335
        }
336
        
337
        /**
338
         * Takes the default properties defined in /metadata/api/hibernate/hibernate.default.properties and
339
         * merges it into the user-defined runtime properties
340
         *
341
         * @see org.openmrs.api.db.ContextDAO#mergeDefaultRuntimeProperties(Properties)
342
         */
343
        private static void mergeDefaultRuntimeProperties(Properties runtimeProperties) {
344
                
345
                // loop over runtime properties and precede each with "hibernate" if
346
                // it isn't already
347
                // must do it this way to prevent concurrent mod errors
348
                Set<Object> runtimePropertyKeys = new HashSet<>(runtimeProperties.keySet());
1 ✔
349
                for (Object key : runtimePropertyKeys) {
1 ✔
350
                        String prop = (String) key;
1 ✔
351
                        String value = (String) runtimeProperties.get(key);
1 ✔
352
                        log.trace("Setting property: " + prop + ":" + value);
1 ✔
353
                        if (!prop.startsWith("hibernate") && !runtimeProperties.containsKey("hibernate." + prop)) {
1 ✔
354
                                runtimeProperties.setProperty("hibernate." + prop, value);
1 ✔
355
                        }
356
                }
1 ✔
357
                
358
                // load in the default hibernate properties from hibernate.default.properties
359
                InputStream propertyStream = null;
1 ✔
360
                try {
361
                        Properties props = new Properties();
1 ✔
362
                        // TODO: This is a dumb requirement to have hibernate in here.  Clean this up
363
                        propertyStream = DatabaseUpdater.class.getClassLoader().getResourceAsStream("hibernate.default.properties");
1 ✔
364
                        OpenmrsUtil.loadProperties(props, propertyStream);
1 ✔
365
                        // add in all default properties that don't exist in the runtime
366
                        // properties yet
367
                        for (Map.Entry<Object, Object> entry : props.entrySet()) {
1 ✔
368
                                if (!runtimeProperties.containsKey(entry.getKey())) {
1 ✔
369
                                        runtimeProperties.put(entry.getKey(), entry.getValue());
1 ✔
370
                                }
371
                        }
1 ✔
372
                }
373
                finally {
374
                        try {
375
                                propertyStream.close();
1 ✔
376
                        }
377
                        catch (Exception e) {
×
378
                                // pass
379
                        }
1 ✔
380
                }
381
        }
1 ✔
382
        
383
        /**
384
         * Exposes Liquibase instances created by this class. When calling
385
         * org.openmrs.util.DatabaseUpdater#getInitialLiquibaseSnapshotVersion(LiquibaseProvider) and
386
         * org.openmrs.util.DatabaseUpdater#getInitialLiquibaseSnapshotVersion(String,LiquibaseProvider), a
387
         * Liquibase instance created by this class is injected into these methods. The Liquibase instance
388
         * is injected into these methods instead of calling
389
         * org.openmrs.util.DatabaseUpdater#getLiquibase(String,ClassLoader) directly. The reason for that
390
         * design decision is that injecting a Liquibase instance (via a Liquibase provider) makes it
391
         * possible to test the two methods mentioned above in isolation. The respective integration test is
392
         * org.openmrs.util.DatabaseUpdateIT.
393
         * 
394
         * @see LiquibaseProvider
395
         * @param changeLogFile name of a Liquibase change log file
396
         * @return a Liquibase instance
397
         * @throws Exception
398
         */
399
        static Liquibase getLiquibase(String changeLogFile) throws Exception {
400
                if (liquibaseProvider != null) {
1 ✔
401
                        return liquibaseProvider.getLiquibase(changeLogFile);
1 ✔
402
                }
403
                return getLiquibase(changeLogFile, OpenmrsClassLoader.getInstance());
1 ✔
404
        }
405
        
406
        /**
407
         * Get a connection to the database through Liquibase. The calling method /must/ close the database
408
         * connection when finished with this Liquibase object.
409
         * liquibase.getDatabase().getConnection().close()
410
         *
411
         * @param changeLogFile the name of the file to look for the on classpath or filesystem
412
         * @param cl the {@link ClassLoader} to use to find the file (or null to use
413
         *            {@link OpenmrsClassLoader})
414
         * @return Liquibase object based on the current connection settings
415
         * @throws Exception
416
         */
417
        private static Liquibase getLiquibase(String changeLogFile, ClassLoader cl) throws Exception {
418
                Connection connection;
419
                try {
420
                        connection = getConnection();
1 ✔
421
                }
422
                catch (SQLException e) {
×
423
                        throw new Exception(
×
424
                                "Unable to get a connection to the database.  Please check your openmrs runtime properties file and make sure you have the correct connection.username and connection.password set",
425
                                e);
426
                }
1 ✔
427
                
428
                if (cl == null) {
1 ✔
429
                        cl = OpenmrsClassLoader.getInstance();
1 ✔
430
                }
431
                
432
                try {
433
                        Database database = DatabaseFactory.getInstance()
1 ✔
434
                                .findCorrectDatabaseImplementation(new JdbcConnection(connection));
1 ✔
435
                        database.setDatabaseChangeLogTableName("liquibasechangelog");
1 ✔
436
                        database.setDatabaseChangeLogLockTableName("liquibasechangeloglock");
1 ✔
437
                        
438
                        if (connection.getMetaData().getDatabaseProductName().contains("HSQL Database Engine")
1 ✔
439
                                || connection.getMetaData().getDatabaseProductName().contains("H2")) {
1 ✔
440
                                // a hack because hsqldb and h2 seem to be checking table names in the metadata section case sensitively
441
                                database.setDatabaseChangeLogTableName(database.getDatabaseChangeLogTableName().toUpperCase());
1 ✔
442
                                database.setDatabaseChangeLogLockTableName(database.getDatabaseChangeLogLockTableName().toUpperCase());
1 ✔
443
                        }
444

445
                        if (changeLogFile == null) {
1 ✔
446
                                changeLogFile = EMPTY_CHANGE_LOG_FILE;
1 ✔
447
                        }
448

449
                        configureLiquibaseDuplicateFileMode();
1 ✔
450

451
                        // ensure that the change log history service is initialised
452
                        Scope.getCurrentScope()
1 ✔
453
                                .getSingleton(ChangeLogHistoryServiceFactory.class)
1 ✔
454
                                .getChangeLogService(database)
1 ✔
455
                                .init();
1 ✔
456
                        return new Liquibase(changeLogFile, getCompositeResourceAccessor(cl), database);
1 ✔
457
                }
458
                catch (Exception e) {
×
459
                        // if an error occurs, close the connection
460
                        if (connection != null) {
×
461
                                connection.close();
×
462
                        }
463
                        throw e;
×
464
                }
465
        }
466
        
467
        /**
468
         * Gets a database connection for liquibase to do the updates
469
         *
470
         * @return a java.sql.connection based on the current runtime properties
471
         */
472
        public static Connection getConnection() throws Exception {
473
                Properties props = Context.getRuntimeProperties();
1 ✔
474
                mergeDefaultRuntimeProperties(props);
1 ✔
475
                
476
                String driver = props.getProperty("hibernate.connection.driver_class");
1 ✔
477
                String username = props.getProperty("hibernate.connection.username");
1 ✔
478
                String password = props.getProperty("hibernate.connection.password");
1 ✔
479
                String url = props.getProperty("hibernate.connection.url");
1 ✔
480
                
481
                // hack for mysql to make sure innodb tables are created
482
                if (url.contains("mysql") && !url.contains("InnoDB")) {
1 ✔
483
                        url = url + "&sessionVariables=default_storage_engine=InnoDB";
×
484
                }
485
                
486
                Class.forName(driver);
1 ✔
487
                return DriverManager.getConnection(url, username, password);
1 ✔
488
        }
489
        
490
        /**
491
         * Represents each change in the files referenced by liquibase-update-to-latest
492
         */
493
        public static class OpenMRSChangeSet {
494
                
495
                private String id;
496
                
497
                private String author;
498
                
499
                private String comments;
500
                
501
                private String description;
502
                
503
                private ChangeSet.RunStatus runStatus;
504
                
505
                private Date ranDate;
506
                
507
                /**
508
                 * Create an OpenmrsChangeSet from the given changeset
509
                 *
510
                 * @param changeSet
511
                 * @param database
512
                 */
513
                public OpenMRSChangeSet(ChangeSet changeSet, Database database) throws Exception {
1 ✔
514
                        setId(changeSet.getId());
1 ✔
515
                        setAuthor(changeSet.getAuthor());
1 ✔
516
                        setComments(changeSet.getComments());
1 ✔
517
                        setDescription(changeSet.getDescription());
1 ✔
518
                        setRunStatus(database.getRunStatus(changeSet));
1 ✔
519
                        setRanDate(database.getRanDate(changeSet));
1 ✔
520
                }
1 ✔
521
                
522
                /**
523
                 * @return the author
524
                 */
525
                public String getAuthor() {
526
                        return author;
×
527
                }
528
                
529
                /**
530
                 * @param author the author to set
531
                 */
532
                public void setAuthor(String author) {
533
                        this.author = author;
1 ✔
534
                }
1 ✔
535
                
536
                /**
537
                 * @return the comments
538
                 */
539
                public String getComments() {
540
                        return comments;
×
541
                }
542
                
543
                /**
544
                 * @param comments the comments to set
545
                 */
546
                public void setComments(String comments) {
547
                        this.comments = comments;
1 ✔
548
                }
1 ✔
549
                
550
                /**
551
                 * @return the description
552
                 */
553
                public String getDescription() {
554
                        return description;
×
555
                }
556
                
557
                /**
558
                 * @param description the description to set
559
                 */
560
                public void setDescription(String description) {
561
                        this.description = description;
1 ✔
562
                }
1 ✔
563
                
564
                /**
565
                 * @return the runStatus
566
                 */
567
                public ChangeSet.RunStatus getRunStatus() {
568
                        return runStatus;
×
569
                }
570
                
571
                /**
572
                 * @param runStatus the runStatus to set
573
                 */
574
                public void setRunStatus(ChangeSet.RunStatus runStatus) {
575
                        this.runStatus = runStatus;
1 ✔
576
                }
1 ✔
577
                
578
                /**
579
                 * @return the ranDate
580
                 */
581
                public Date getRanDate() {
582
                        return ranDate;
×
583
                }
584
                
585
                /**
586
                 * @param ranDate the ranDate to set
587
                 */
588
                public void setRanDate(Date ranDate) {
589
                        this.ranDate = ranDate;
1 ✔
590
                }
1 ✔
591
                
592
                /**
593
                 * @return the id
594
                 */
595
                public String getId() {
596
                        return id;
×
597
                }
598
                
599
                /**
600
                 * @param id the id to set
601
                 */
602
                public void setId(String id) {
603
                        this.id = id;
1 ✔
604
                }
1 ✔
605
                
606
        }
607
        
608
        /**
609
         * Returns all change sets defined by (a) the Liquibase snapshot files that had been used to
610
         * initialise the OpenMRS database and (b) the Liquibase update files that that are applicable on
611
         * top of the snapshot version.
612
         * 
613
         * @return list of change sets that both have and haven't been run
614
         */
615
        public static List<OpenMRSChangeSet> getDatabaseChanges() throws Exception {
616
                if (Context.isSessionOpen()) { // Do not check privileges if not run in webapp context (e.g. in tests)
1 ✔
617
                        Context.requirePrivilege(PrivilegeConstants.GET_DATABASE_CHANGES);
×
618
                }
619
                List<OpenMRSChangeSet> result = new ArrayList<>();
1 ✔
620
                
621
                String initialSnapshotVersion = changeLogDetective.getInitialLiquibaseSnapshotVersion(CONTEXT,
1 ✔
622
                    new DatabaseUpdaterLiquibaseProvider());
623
                List<String> updateVersions = changeLogVersionFinder.getUpdateVersionsGreaterThan(initialSnapshotVersion);
1 ✔
624
                
625
                Map<String, List<String>> snapshotCombinations = changeLogVersionFinder.getSnapshotCombinations();
1 ✔
626

627
                List<String> changeLogFileNames = new ArrayList<>();
1 ✔
628
                changeLogFileNames.addAll(snapshotCombinations.get(initialSnapshotVersion));
1 ✔
629
                changeLogFileNames.addAll(changeLogVersionFinder.getUpdateFileNames(updateVersions));
1 ✔
630
                
631
                Liquibase liquibase = null;
1 ✔
632
                try {
633
                        for (String filename : changeLogFileNames) {
1 ✔
634
                                liquibase = getLiquibase(filename);
1 ✔
635
                                List<ChangeSet> changeSets = liquibase.getDatabaseChangeLog().getChangeSets();
1 ✔
636
                                
637
                                for (ChangeSet changeSet : changeSets) {
1 ✔
638
                                        OpenMRSChangeSet openMRSChangeSet = new OpenMRSChangeSet(changeSet, liquibase.getDatabase());
1 ✔
639
                                        result.add(openMRSChangeSet);
1 ✔
640
                                }
1 ✔
641
                                liquibase.close();
1 ✔
642
                        }
1 ✔
643
                }
644
                finally {
645
                        if (liquibase != null) {
1 ✔
646
                                try {
647
                                        liquibase.close();
1 ✔
648
                                }
649
                                catch (Exception e) {
×
650
                                        // ignore exceptions triggered by closing liquibase a second time 
651
                                }
1 ✔
652
                        }
653
                }
654
                
655
                return result;
1 ✔
656
        }
657
        
658
        /**
659
         * Returns a list of Liquibase change sets were not run yet.
660
         *
661
         * @param liquibaseProvider provides access to a Liquibase instance
662
         * @return list of change sets that were not run yet.
663
         */
664
        public static List<OpenMRSChangeSet> getUnrunDatabaseChanges(LiquibaseProvider liquibaseProvider) throws Exception {
665
                if (Context.isSessionOpen()) { // Do not check privileges if not run in webapp context (e.g. in tests)
1 ✔
666
                        Context.requirePrivilege(PrivilegeConstants.GET_DATABASE_CHANGES);
1 ✔
667
                }
668
                String initialSnapshotVersion = changeLogDetective.getInitialLiquibaseSnapshotVersion(CONTEXT, liquibaseProvider);
1 ✔
669
                log.debug("initial snapshot version is '{}'", initialSnapshotVersion);
1 ✔
670
                
671
                List<String> liquibaseUpdateFilenames = changeLogDetective.getUnrunLiquibaseUpdateFileNames(initialSnapshotVersion,
1 ✔
672
                    CONTEXT, liquibaseProvider);
673
                
674
                if (!liquibaseUpdateFilenames.isEmpty()) {
1 ✔
675
                        return getUnrunDatabaseChanges(liquibaseUpdateFilenames.toArray(new String[0]));
1 ✔
676
                }
677
                
678
                return new ArrayList<OpenMRSChangeSet>();
×
679
        }
680
        
681
        /**
682
         * Looks at the specified liquibase change log files and returns all changesets in the files that
683
         * have not been run on the database yet. If no argument is specified, then it looks at the current
684
         * liquibase-update-to-latest.xml file
685
         *
686
         * @param changeLogFilenames the filenames of all files to search for unrun changesets
687
         * @return list of change sets
688
         */
689
        public static List<OpenMRSChangeSet> getUnrunDatabaseChanges(String... changeLogFilenames) {
690
                if (Context.isSessionOpen()) { // Do not check privileges if not run in webapp context (e.g. in tests)
1 ✔
691
                        Context.requirePrivilege(PrivilegeConstants.GET_DATABASE_CHANGES);
1 ✔
692
                }
693
                log.debug("looking for un-run change sets in '{}'", Arrays.toString(changeLogFilenames));
1 ✔
694
                
695
                Database database = null;
1 ✔
696
                try {
697
                        if (changeLogFilenames == null || changeLogFilenames.length == 0) {
1 ✔
698
                                throw new IllegalArgumentException("changeLogFilenames can neither null nor an empty array");
1 ✔
699
                        }
700
                        
701
                        List<OpenMRSChangeSet> results = new ArrayList<>();
1 ✔
702
                        
703
                        for (String changelogFile : changeLogFilenames) {
1 ✔
704
                                Liquibase liquibase = getLiquibase(changelogFile, null);
1 ✔
705
                                database = liquibase.getDatabase();
1 ✔
706
                                
707
                                // same resource accessor as executeChangelog, so files read for checksums resolve the same way
708
                                List<ChangeSet> changeSets = Scope.child(
1 ✔
709
                                        Collections.singletonMap(Scope.Attr.resourceAccessor.name(), getCompositeResourceAccessor(null)),
1 ✔
710
                                        () -> new StatusCommandStep().listUnrunChangeSets(new Contexts(CONTEXT),
1 ✔
711
                                                new LabelExpression(), liquibase.getDatabaseChangeLog(), liquibase.getDatabase()));
1 ✔
712

713
                                for (ChangeSet changeSet : changeSets) {
1 ✔
714
                                        OpenMRSChangeSet omrschangeset = new OpenMRSChangeSet(changeSet, database);
1 ✔
715
                                        results.add(omrschangeset);
1 ✔
716
                                }
1 ✔
717
                        }
718
                        
719
                        return results;
1 ✔
720
                        
721
                }
722
                catch (Exception e) {
1 ✔
723
                        throw new RuntimeException(
1 ✔
724
                                "Error occurred while trying to get the updates needed for the database. " + e.getMessage(), e);
1 ✔
725
                }
726
                finally {
727
                        try {
728
                                database.getConnection().close();
1 ✔
729
                        }
730
                        catch (Exception e) {
1 ✔
731
                                //pass
732
                        }
1 ✔
733
                }
734
        }
735
        
736
        /**
737
         * @return the authenticatedUserId
738
         */
739
        public static Integer getAuthenticatedUserId() {
740
                return authenticatedUserId;
1 ✔
741
        }
742
        
743
        /**
744
         * @param userId the authenticatedUserId to set
745
         */
746
        public static void setAuthenticatedUserId(Integer userId) {
747
                authenticatedUserId = userId;
×
748
        }
×
749
        
750
        /**
751
         * This method is called by an executing custom changeset to register warning messages.
752
         *
753
         * @param warnings list of warnings to append to the end of the current list
754
         */
755
        public static void reportUpdateWarnings(List<String> warnings) {
756
                if (updateWarnings == null) {
1 ✔
757
                        updateWarnings = new LinkedList<>();
1 ✔
758
                }
759
                updateWarnings.addAll(warnings);
1 ✔
760
        }
1 ✔
761
        
762
        /**
763
         * This method writes the given text to the database updates log file located in the application
764
         * data directory.
765
         *
766
         * @param text text to be written to the file
767
         */
768
        public static void writeUpdateMessagesToFile(String text) {
769
                OutputStreamWriter streamWriter = null;
×
770
                PrintWriter writer = null;
×
771
                File destFile = new File(OpenmrsUtil.getApplicationDataDirectory(), DatabaseUpdater.DATABASE_UPDATES_LOG_FILE);
×
772
                try {
773
                        String lineSeparator = System.getProperty("line.separator");
×
774
                        Date date = Calendar.getInstance().getTime();
×
775
                        
776
                        streamWriter = new OutputStreamWriter(new FileOutputStream(destFile, true), StandardCharsets.UTF_8);
×
777
                        writer = new PrintWriter(new BufferedWriter(streamWriter));
×
778
                        writer.write("********** START OF DATABASE UPDATE LOGS AS AT " + date + " **********");
×
779
                        writer.write(lineSeparator);
×
780
                        writer.write(lineSeparator);
×
781
                        writer.write(text);
×
782
                        writer.write(lineSeparator);
×
783
                        writer.write(lineSeparator);
×
784
                        writer.write("*********** END OF DATABASE UPDATE LOGS AS AT " + date + " ***********");
×
785
                        writer.write(lineSeparator);
×
786
                        writer.write(lineSeparator);
×
787
                        
788
                        //check if there was an error while writing to the file
789
                        if (writer.checkError()) {
×
790
                                log.warn("An Error occured while writing warnings to the database update log file'");
×
791
                        }
792
                        
793
                        writer.close();
×
794
                }
795
                catch (FileNotFoundException e) {
×
796
                        log.warn("Failed to find the database update log file", e);
×
797
                }
798
                finally {
799
                        IOUtils.closeQuietly(streamWriter);
×
800
                        IOUtils.closeQuietly(writer);
×
801
                }
802
        }
×
803
        
804
        /**
805
         * This method releases the liquibase db lock, and is intended to be usd after a crashed database update.
806
         * <br>
807
         * This should only be called if the user is sure that no one else is currently running database
808
         * updates. This method should be used if there was a db crash while updates were being written and
809
         * the lock table was never cleaned up.
810
         *
811
         * @throws LockException
812
         */
813
        public static synchronized void releaseDatabaseLock() throws LockException {
814
                Database database = null;
×
815
                try {
816
                        Liquibase liquibase = getLiquibase(null, null);
×
817
                        database = liquibase.getDatabase();
×
818
                        LockService lockService = LockServiceFactory.getInstance().getLockService(database);
×
819
                        if (isLocked()) {
×
820
                                lockService.forceReleaseLock();
×
821
                        }
822
                }
823
                catch (Exception e) {
×
824
                        throw new LockException(e);
×
825
                }
826
                finally {
827
                        try {
828
                                database.getConnection().close();
×
829
                        }
830
                        catch (Exception e) {
×
831
                                // pass
832
                        }
×
833
                }
834
        }
×
835
        
836
        /**
837
         * This method currently checks the liquibasechangeloglock table to see if there is a row with a
838
         * lock in it. This uses the liquibase API to do this
839
         *
840
         * @return true if database is currently locked
841
         */
842
        public static boolean isLocked() {
843
                Database database = null;
1 ✔
844
                try {
845
                        Liquibase liquibase = getLiquibase(null, null);
1 ✔
846
                        database = liquibase.getDatabase();
1 ✔
847
                        return LockServiceFactory.getInstance().getLockService(database).listLocks().length > 0;
1 ✔
848
                }
849
                catch (Exception e) {
×
850
                        return false;
×
851
                }
852
                finally {
853
                        try {
854
                                database.getConnection().close();
1 ✔
855
                        }
856
                        catch (Exception e) {
×
857
                                // pass
858
                        }
1 ✔
859
                }
860
        }
861

862
        private final static class OpenmrsUpdateVisitor extends UpdateVisitor {
863

864
                private final ChangeSetExecutorCallback callback;
865

866
                private final int numChangeSetsToRun;
867

868
                public OpenmrsUpdateVisitor(Database database, ChangeSetExecutorCallback callback, int numChangeSetsToRun) {
869
                        super(database, null);
1 ✔
870
                        this.callback = callback;
1 ✔
871
                        this.numChangeSetsToRun = numChangeSetsToRun;
1 ✔
872
                }
1 ✔
873

874
                @Override
875
                public void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database,
876
                        Set<ChangeSetFilterResult> filterResults) throws LiquibaseException {
877
                        if (callback != null) {
1 ✔
UNCOV
878
                                callback.executing(changeSet, numChangeSetsToRun);
×
879
                        }
880
                        Map<String, Object> scopeValues = new HashMap<>();
1 ✔
881
                        scopeValues.put(Scope.Attr.resourceAccessor.name(), getCompositeResourceAccessor(null));
1 ✔
882
                        String scopeId = null;
1 ✔
883
                        try {
884
                                scopeId = Scope.enter(scopeValues);
1 ✔
885
                                super.visit(changeSet, databaseChangeLog, database, filterResults);
1 ✔
886
                        }
887
                        catch (Exception e) {
×
888
                                throw new LiquibaseException("Unable to execute change set: " + changeSet, e);
×
889
                        }
890
                        finally {
891
                                try {
892
                                        Scope.exit(scopeId);
1 ✔
893
                                }
894
                                catch (Exception e) {
×
895
                                        log.warn("An error occurred trying to exit the liquibase scope", e);
×
896
                                }
1 ✔
897
                        }
898
                }
1 ✔
899
        }
900

901
        /**
902
         * @return a resourceAccessor that includes both classpath and filesystem at the application data directory
903
         */
904
        private static CompositeResourceAccessor getCompositeResourceAccessor(ClassLoader classLoader) {
905
                if (classLoader == null) {
1 ✔
906
                        classLoader = Thread.currentThread().getContextClassLoader();
1 ✔
907
                        if (!(classLoader instanceof OpenmrsClassLoader) && !(classLoader instanceof ModuleClassLoader)) {
1 ✔
908
                                classLoader = OpenmrsClassLoader.getInstance();
×
909
                        }
910
                }
911
                
912
                ResourceAccessor openmrsFO = new OpenmrsClassLoaderResourceAccessor(classLoader);
1 ✔
913
                ResourceAccessor fsFO = new FileSystemResourceAccessor(OpenmrsUtil.getApplicationDataDirectoryAsFile());
1 ✔
914
                return new CompositeResourceAccessor(openmrsFO, fsFO);
1 ✔
915
        }
916
        
917
        private static void configureLiquibaseDuplicateFileMode() {
918
                final String dupFlagModeKey = GlobalConfiguration.DUPLICATE_FILE_MODE.getKey();
1 ✔
919
                final String dupFlagMode = Context.getRuntimeProperties().getProperty(dupFlagModeKey);
1 ✔
920

921
                if (dupFlagMode != null) {
1 ✔
922
                        System.setProperty(dupFlagModeKey, dupFlagMode);
×
923
                } else if (System.getProperty(dupFlagModeKey) == null) {
1 ✔
924
                        System.setProperty(dupFlagModeKey, OpenmrsConstants.LIQUIBASE_DUPLICATE_FILE_MODE_DEFAULT);
1 ✔
925
                }
926
        }
1 ✔
927
}
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