question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
I am using Liquibase for generating a MySQL and a HSQLDB databases. In several tables I have a column called 'last_modified' which is the TIMESTAMP of the last update on that particular record. <changeSet author="bob" id="7"> <createTable tableName="myTable"> <column autoIncrement="true" name="id" type="INT"> <constraints nullable="false" primaryKey="true" /> </column> <column name="name" type="VARCHAR(128)"> <constraints nullable="false" /> </column> <column name="description" type="VARCHAR(512)" /> <column defaultValueBoolean="true" name="enabled" type="BIT"> <constraints nullable="false" /> </column> <column name="last_modified" type="TIMESTAMP"/> </createTable> <modifySql dbms="mysql"> <append value=" engine innodb" /> </modifySql> </changeSet> I noticed that if I use MySQL, the generated SQL for that column is: `last_modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, While if I use HSQLDB, in case of update nothing happens, but I would like to have the same behaviour of the MySQL database with a default value on update equals to the CURRENT_TIMESTAMP. How can I set the CURRENT_TIMESTAMP as a default value ON UPDATE?
Or you could try this, as you have already have modifySql tag added: <column defaultValue="CURRENT_TIMESTAMP" name="timestamp" type="TIMESTAMP"> <constraints nullable="false"/> </column> <modifySql dbms="mysql"> <regExpReplace replace="'CURRENT_TIMESTAMP'" with="CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"/> <append value=" engine innodb" /> </modifySql> Liquibase 3.1.1 does not produce what you described above. I have to deal with it as given above
Liquibase
19,230,489
14
Starting yesterday (Sunday) morning my production app fails to start, with no code changes from my side. It's running Springboot 2.3.4, Liquibase-core 3.8.0 and is hosted on Amazon linux2. Funny thing is there are no exceptions locally, only when deployed. Here is the relevant stack trace: Caused by: liquibase.exception.UnexpectedLiquibaseException: java.nio.file.NoSuchFileException: /tmp/agent12302722365010540729.jar at liquibase.servicelocator.ServiceLocator.setResourceAccessor(ServiceLocator.java:129) at liquibase.servicelocator.ServiceLocator.<init>(ServiceLocator.java:69) at liquibase.servicelocator.CustomResolverServiceLocator.<init>(CustomResolverServiceLocator.java:16) at org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener$LiquibasePresent.replaceServiceLocator(LiquibaseServiceLocatorApplicationListener.java:55) at org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener.onApplicationEvent(LiquibaseServiceLocatorApplicationListener.java:44) at org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener.onApplicationEvent(LiquibaseServiceLocatorApplicationListener.java:36) ... Caused by: java.nio.file.NoSuchFileException: /tmp/agent801508645517312012.jar at liquibase.resource.ClassLoaderResourceAccessor.getResourcesAsStream(ClassLoaderResourceAccessor.java:53) at liquibase.servicelocator.ServiceLocator.setResourceAccessor(ServiceLocator.java:115) I double checked all application related files and env variables and they are all the same. The file in question is in no way related to my app. Do you have any idea what this file is and why is Liquibase trying to find it all of the sudden?
I had the same problem. On the startup of the amazon linux 2, there is a security patch that is installed. The package causing the problem is log4j-cve-2021-44228-hotpatch.noarch (you can check that in /var/log/yum.log) A temporary solution is to uninstall the patch and install another java version. yum remove log4j-cve-2021-44228-hotpatch.noarch yum install java-11-openjdk-11.0.12.0.7-0.amzn2.0.2.x86_64 Thanks to @mihristov for the solution.
Liquibase
70,421,613
14
I have an entity with a group of fields in primary key. Like this : @Entity @Table(name = "pv_object") @NamedQuery(name = "PreviousObject.findAll", query = "SELECT p FROM PreviousObject p") public class PreviousObject implements Serializable { @EmbeddedId private FieldsDTO fieldsdto; // } FieldsDTO class contains 2 String and 2 Integer. I have and I use Liquidbase on my project in a XML file, but, I don't know how to represent this ID of 4 fields in liquidbase. Thanks for your help :)
In <addPrimaryKey you can configure columnNames by all your columns that compose your primary key <changeSet author="liquibase-docs" id="addPrimaryKey-example"> <addPrimaryKey columnNames="id, name" constraintName="pk_person" schemaName="public" tableName="person" tablespace="A String"/> </changeSet>
Liquibase
54,440,479
14
I have a Spring Boot 1.4.0 based Project that uses Liquibase. Is it possible to execute a Method AFTER liquibase finished? Something like Bean Post Processor? What i want to do is adding some data to my database when the application is started in development mode. In developement mode the application uses an in-memory h2 database, so liquibase has to create the tables before i can write my data.
Spring Boot auto-configures a SpringLiquibase bean named liquibase. Any bean that depends on this bean will be created after Liquibase has finished. For example, you could use @PostConstruct to populate the database: @Bean @DependsOn("liquibase") public YourBean yourBean() { return new YourBean(); } static class YourBean { @PostConstruct public void populateDatabase() { System.out.println("This will be called after Liquibase has finished"); } }
Liquibase
38,825,670
14
I have fresh mysql instance and want to be able to create a plenty of databases and populate it with liquibase. While I have scripts (changesets) which works fine on manually created databases I want to be able to create databases with liquibase as well. When I try to connect without specifing database in URL I've got the error: liquibase --driver=com.mysql.jdbc.Driver --url=jdbc:mysql://localhost:3306/ --username=root --password=admin --changeLogFile=create_dbs.sql tag empty Unexpected error running Liquibase: Incorrect database name '' [Failed SQL: CREATE TABLE ``.DATABASECHANGELOGLOCK (ID INT NOT NULL, LOCKED BIT(1) NOT NULL, LOCKGRANTED datetime NULL, LOCKEDBY VARCHAR(255) NULL, CONSTRAINT PK_DATABASECHANGELOGLOCK PRIMARY KEY (ID))] I don't need these changes (database creation) to be tracked by liquibase, seems like I want to use LB as quick bootstrap tool.
Very first need to add database name in URL like jdbc:mysql://localhost:3306/database_name. you can also create a fresh database using this URL jdbc:mysql://localhost:3306/database_name?createDatabaseIfNotExist=true createDatabaseIfNotExist this keyword create a fresh new database in your system. If the database does not exist. if exist, skip executing. How to create database with Liquibase
Liquibase
34,283,630
14
This is what I have --preconditions onFail:CONTINUE --preconditions not tableExists tableName:QRTZ_CALENDARS schemaName:dbo CREATE TABLE dbo.QRTZ_CALENDARS ( SCHED_NAME VARCHAR (120) NOT NULL , CALENDAR_NAME VARCHAR (200) NOT NULL , CALENDAR IMAGE NOT NULL ) GO Background. I'm using liquibase to setup a h2 database for test cases in java.
Add a pre-Condition to your changeset for example: <preConditions onFail="MARK_RAN"> <not> <tableExists tableName="Table_name"/> </not> </preConditions> <createTable tableName="Table_name" > <column name="column1" type="NUMBER(20,0)"/> </createTable>
Liquibase
48,015,336
14
I am looking to drop a table in MySQL using Liquibase only if the table exists. I am not able to figure out how to check if a table exists in Liquibase.
You should use <changeSet author="liquibase-docs" id="dropTable-example"> <preConditions onFail="MARK_RAN"><tableExists schemaName="schemaName" tableName="tableName"/></preConditions> <dropTable cascadeConstraints="true" catalogName="cat" schemaName="public" tableName="person"/> </changeSet> Also, you can check this link for more <preConditions> options: http://www.liquibase.org/documentation/preconditions.html
Liquibase
44,083,766
14
I'm having a SQL syntax error when my Spring Boot application tries to start. It cannot instantiate the SpringLiquibase bean, because the outputed SQL of a changeset is leading to a syntax error. I need to check the SQL generated from Liquibase in order to find what's wrong. How can I do that?
You can try liquibase updateSQL command http://www.liquibase.org/documentation/command_line.html http://www.liquibase.org/documentation/update.html
Liquibase
28,636,472
14
I am working with the new Spring Boot 2.1.0 version. In Spring Boot 2.1.0, Liquibase was updated from 3.5.5 to 3.6.2. I've noticed several things in my change sets are no long working. -- test_table.sql CREATE TABLE test_table ( id SERIAL PRIMARY KEY, --Works fine as TEXT or VARCHAR with Liquibase 3.5 which is bundled with Spring Boot version 2.0.6.RELEASE --Will only work as VARCHAR with Liquibase 3.6.2 which is bundled with Spring Boot version 2.1.0.RELEASE and above worksheet_data TEXT ); -- test_table.csv id,worksheet_data 1,fff -- Liquibase Changeset <changeSet id="DATA_01" author="me" runOnChange="false"> <loadData file="${basedir}/sql/data/test_table.csv" tableName="test_table"/> </changeSet> This will not work. I am presented with this odd stacktrace. It complains it can't find liquibase/changelog/fff which I'm not referencing at all in the changeset. The "fff" coincidentally matches the data value in table_test.csv. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration$LiquibaseConfiguration.class]: Invocation of init method failed; nested exception is liquibase.exception.MigrationFailedException: Migration failed for change set liquibase/changelog/data_nonprod.xml::DATA_NONPROD_02::scott_winters: Reason: liquibase.exception.DatabaseException: class path resource [liquibase/changelog/fff] cannot be resolved to URL because it does not exist at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1745) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:307) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1083) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:853) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE] at net.migov.amar.MiAmarApiApplication.main(MiAmarApiApplication.java:33) [classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.1.RELEASE.jar:2.1.1.RELEASE] Caused by: liquibase.exception.MigrationFailedException: Migration failed for change set liquibase/changelog/data_nonprod.xml::DATA_NONPROD_02::scott_winters: Reason: liquibase.exception.DatabaseException: class path resource [liquibase/changelog/fff] cannot be resolved to URL because it does not exist at liquibase.changelog.ChangeSet.execute(ChangeSet.java:637) ~[liquibase-core-3.6.2.jar:na] at liquibase.changelog.visitor.UpdateVisitor.visit(UpdateVisitor.java:53) ~[liquibase-core-3.6.2.jar:na] at liquibase.changelog.ChangeLogIterator.run(ChangeLogIterator.java:78) ~[liquibase-core-3.6.2.jar:na] at liquibase.Liquibase.update(Liquibase.java:202) ~[liquibase-core-3.6.2.jar:na] at liquibase.Liquibase.update(Liquibase.java:179) ~[liquibase-core-3.6.2.jar:na] at liquibase.integration.spring.SpringLiquibase.performUpdate(SpringLiquibase.java:353) ~[liquibase-core-3.6.2.jar:na] at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:305) ~[liquibase-core-3.6.2.jar:na] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1804) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE] ... 23 common frames omitted Caused by: liquibase.exception.DatabaseException: class path resource [liquibase/changelog/fff] cannot be resolved to URL because it does not exist at liquibase.statement.ExecutablePreparedStatementBase.applyColumnParameter(ExecutablePreparedStatementBase.java:191) ~[liquibase-core-3.6.2.jar:na] at liquibase.statement.ExecutablePreparedStatementBase.attachParams(ExecutablePreparedStatementBase.java:110) ~[liquibase-core-3.6.2.jar:na] at liquibase.statement.BatchDmlExecutablePreparedStatement.attachParams(BatchDmlExecutablePreparedStatement.java:51) ~[liquibase-core-3.6.2.jar:na] at liquibase.statement.ExecutablePreparedStatementBase.execute(ExecutablePreparedStatementBase.java:81) ~[liquibase-core-3.6.2.jar:na] at liquib ase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:115) ~[liquibase-core-3.6.2.jar:na] at liquibase.database.AbstractJdbcDatabase.execute(AbstractJdbcDatabase.java:1229) ~[liquibase-core-3.6.2.jar:na] at liquibase.database.AbstractJdbcDatabase.executeStatements(AbstractJdbcDatabase.java:1211) ~[liquibase-core-3.6.2.jar:na] at liquibase.changelog.ChangeSet.execute(ChangeSet.java:600) ~[liquibase-core-3.6.2.jar:na] ... 31 common frames omitted Caused by: java.io.FileNotFoundException: class path resource [liquibase/changelog/fff] cannot be resolved to URL because it does not exist at org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:195) ~[spring-core-5.1.3.RELEASE.jar:5.1.3.RELEASE] at liquibase.integration.spring.SpringLiquibase$SpringResourceOpener.getResourcesAsStream(SpringLiquibase.java:556) ~[liquibase-core-3.6.2.jar:na] at liquibase.statement.ExecutablePreparedStatementBase.getResourceAsStream(ExecutablePreparedStatementBase.java:281) ~[liquibase-core-3.6.2.jar:na] at liquibase.statement.ExecutablePreparedStatementBase.toCharacterStream(ExecutablePreparedStatementBase.java:241) ~[liquibase-core-3.6.2.jar:na] at liquibase.statement.ExecutablePreparedStatementBase.applyColumnParameter(ExecutablePreparedStatementBase.java:184) ~[liquibase-core-3.6.2.jar:na] ... 38 common frames omitted If I change TEXT to VARCHAR it works. From my understanding these column types are the same in postgres, so I can work around this. However, this is frustrating, and I don't see this new behavior documented. From this link 3.6.2 is advertised as a "drop in" change (http://www.liquibase.org/2018/04/liquibase-3-6-0-released.html). I would like to use the new features of Spring Boot 2.1.0, but I cannot specify liquibase 3.5.5 in my build because Spring Boot will complain about incompatible versions. This is just one issue I'm seeing with changesets that worked in 3.5.5. Maybe the folks at Spring should consider rolling back the version of liquibase. Any advice on this matter would be greatly appreciated. Thanks. UPDATED I have created a sample Spring Boot project to demonstrate this: https://github.com/pcalouche/postgres-liquibase-text
They broke TEXT data type. Try to use VARCHAR May be it could be interesting too https://liquibase.jira.com/browse/CORE-865 You can find all availible types here https://github.com/liquibase/liquibase/tree/master/liquibase-core/src/main/java/liquibase/datatype/core I think that NVARCHAR(MAX) should works for you Also the closed issue with CLOB type for Postgresql https://liquibase.jira.com/browse/CORE-2220
Liquibase
53,405,317
13
How to tell Liquibase to map BLOB datatype to BYTEA on PostgreSQL? It seems that Hibernate people has taken over and adapted the tool to their needs: https://liquibase.jira.com/browse/CORE-1863 , however, EclipseLink don't support oid's and the bug seems to be still open: https://bugs.eclipse.org/bugs/show_bug.cgi?id=337467 I need to use EclipseLink, and I need to use blobs with PostgreSQL. I'd like to use Liquibase, is it possible to make those things work together?
You have two options. If you only need this for Postgres and don't plan to support other DBMS, simply use bytea as the column type. Any data type that is not listed as one of the "generic" types in the description of the column tag will be passed "as-is" to the database, e.g. <createTable tableName="foo"> <column name="id" type="integer"/> <column name="picture" type="bytea"/> </createTable> If you want to support different DBMS, you can define a property depending on the DBMS: <property name="blob_type" value="bytea" dbms="postgresql"/> <property name="blob_type" value="blob" dbms="oracle"/> then later <createTable tableName="foo"> <column name="id" type="integer"/> <column name="picture" type="${blob_type}"/> </createTable>
Liquibase
42,388,886
13
I`m trying to include changeset.yaml file into changelog.yaml for Liquidbase. file changelog.yaml databaseChangeLog: - include: file: migrations/changeset.yaml changeset.yaml changeset: id: 1 author: vlad Getting this when executing update Unexpected error running Liquibase: Could not find databaseChangeLog node Any ideas why? Thanks. UPDATE: Seems to be the same if im using xml format.
changeset.yaml must contain databaseChangeLog So in my case i should have had this: changeset.yaml databaseChangeLog: - changeSet: id: 1 author: vlad Documentation wasn`t really helpful. Found answer here in github
Liquibase
33,563,763
13
In my current project, there's a DB team that checks all the scripts before applying them to production. We are using Liquibase to apply changesets to development, but for production, we need to be able to generate a *.sql file with all the statements. According to the documentation of liquibase-maven-plugin, updateSQL should be what I want: http://www.liquibase.org/documentation/maven/maven_updatesql.html. So I created two maven profiles. One to apply changes to the local development database (using liquibase:update) and one other that would just generate the script. The problem is: doing liquibase:updateSQL does generate the *.sql file (as expected), but it also tries to connect to the database and apply changes (not expected). I believe the documentation for updateSQL leads into error as it says: Generates the SQL that is required to update the database to the current version as specified in the DatabaseChangeLogs. Makes no mention whatsoever that it would actually apply the changesets, like liquibase:update does. I may be missunderstanding the documentation here, but shouldn't updateSQL only generate the sql or it should actually do update + generate sql? Here's my plugin configuration: <plugin> <groupId>org.liquibase</groupId> <artifactId>liquibase-maven-plugin</artifactId> <version>3.0.5</version> <configuration> <changeLogFile>src/main/resources/db/liquibase_changeset.xml</changeLogFile> <driver>oracle.jdbc.driver.OracleDriver</driver> <url>${liquibase.db.url}</url> <username>${liquibase.db.user}</username> <password>${liquibase.db.password}</password> <promptOnNonLocalDatabase>false</promptOnNonLocalDatabase> </configuration> <executions> <execution> <phase>process-resources</phase> <goals> <goal>${liquibase.exec.goal}</goal> </goals> </execution> </executions> </plugin> And I created the profiles likes this: <profiles> <profile> <id>local</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <liquibase.exec.goal>update</liquibase.exec.goal> <liquibase.exec.prompt>false</liquibase.exec.prompt> <liquibase.db.url>jdbc:oracle:thin:@host:1521:xe</liquibase.db.url> <liquibase.db.user>user</liquibase.db.user> <liquibase.db.password>password</liquibase.db.password> </properties> </profile> <profile> <id>uat</id> <properties> <liquibase.exec.goal>updateSQL</liquibase.exec.goal> <liquibase.exec.prompt>true</liquibase.exec.prompt> <liquibase.db.url>jdbc:oracle:thin:@host2:1521:xe</liquibase.db.url> <liquibase.db.user>user2</liquibase.db.user> <liquibase.db.password>password2</liquibase.db.password> </properties> </profile> </profiles> Given my maven config and my understanding, I would expect mvn install -P uat to only generate the script and not trying to connect to the database. The fact that I'm forced to specify db properties (driver, etc) makes me believe that this is intended to always change database, but I suppose it should be possible to just generate the script without attempting to apply changes against a database. Any thoughts? Is it possible but I'm completely in the wrong path? Or I'm missing some simple property? Or it's simply not supported at all? Thanks in advance.
UpdateSQL does not actually update the database, it just outputs SQL. The reason it needs the database connection information and makes an actual connection because it needs to select from the databasechangelog table to determine which changeSets have been ran and which have not.
Liquibase
22,941,876
13
In Liquibase I would like to insert values if the values are not already set. With a normal insert I suspect that the inserted value will overwrite the previous value if the value is already there. I want it to ony insert if it does not exist. Can this be done? Right now I am using the insert as seen below: <insert tableName="state"> <column name="name" value="fooFoo"/> <column name="enabled" valueBoolean="true"/> </insert>
The proper way to do this is to use preConditions. There's an <sqlCheck> preCondition. sqlCheck Executes an SQL string and checks the returned value. The SQL must return a single row with a single value. To check numbers of rows, use the “count” SQL function. To check for ranges of values, perform the check in the SQL and return a value that can be easily compared against. <sqlCheck expectedResult="1">SELECT COUNT(1) FROM pg_tables WHERE TABLENAME = 'myRequiredTable'</sqlCheck> With it your changeSet will look like this: <changeSet id="foo" author="bar"> <preConditions onFail="MARK_RAN"> <sqlCheck expectedResult="0"> SELECT COUNT(*) FROM state WHERE name='fooFoo' AND enabled=true; </sqlCheck> </preConditions> <insert tableName="state"> <column name="name" value="fooFoo"/> <column name="enabled" valueBoolean="true"/> </insert> </changeSet>
Liquibase
61,845,118
12
How do I create a composite index using liquibase? This is what I have so far: <createIndex indexName="idx_value" tableName="test"> <column name="value"/> </createIndex> I have the following in mind, but I just need to confirm. <createIndex indexName="idx_value" tableName="test"> <column name="value0"/> <column name="value1"/> </createIndex>
I'd be amazed if: <createIndex indexName="idx_value" tableName="test"> <column name="value" type="varchar(255)"/> <column name="othercolumn" type="varchar(255)"/> </createIndex> didn't work...
Liquibase
24,254,201
12
Looking at the docs for liquibase and add-foreign-key-constraint there is a property called deferrable. But the docs don't really mention what that property does. Anyone know?
DEFERRABLE NOT DEFERRABLE This controls whether the constraint can be deferred. A constraint that is not deferrable will be checked immediately after every command. Checking of constraints that are deferrable may be postponed until the end of the transaction (using the SET CONSTRAINTS command). NOT DEFERRABLE is the default. Only foreign key constraints currently accept this clause. All other constraint types are not deferrable. [Source] http://www.postgresql.org/docs/8.1/static/sql-createtable.html In short, assume two tables have cyclic FK dependency. When we perform insert data for which reference data is not present in both tables and FK constraint is not deferred, the DB would throw error since there is a violation of FK constraint. If deferred, the validation would be performed at the time of committing a transaction.
Liquibase
11,405,034
12
Running liquibase --url=jdbc:oracle:thin:@localhost:1521/XE -- driver=oracle.jdbc.OracleDriver --changeLogFile=db.changelog-next.xml -- username=owner --password=xxxx --logLevel=info clearCheckSums clears ALL checksums from the database. Is there a way to clear only the checksums for changesets in db.changelog-next.xml. Thanks
I don't think there is another command or a parameter to clearCheckSums that does this. But you could do this manually. All that clearCheckSums does is nullifying the MD5SUM column of the databasechangelog table. So something like: update databasechangelog set md5sum=null where filename like '%db.changelog-next.xml'; should work. (I haven't tested this SQL. It's just an example - so before you apply this to your production database make sure this works on a development db.)
Liquibase
30,472,289
12
According to the liquibase website, there is an intellij IDEA plugin available in the plugin store, but I cannot seem to find it. Is the plugin discontinued? Is there some alternative for liquibase integrations?
Yes, the Liquibase Intellij plugin has been discontinued. I'll update the website to remove the reference.
Liquibase
33,285,267
12
I want to add a unique constraint to my table during it's creation. I thought something like this would work but it seems to just do nothing. <createTable tableName="MY_TABLE"> <column name="MY_TABLE_ID" type="SMALLINT" autoIncrement="true"> <constraints primaryKey="true" nullable="false"/> </column> <column name="TABLE_FIELD" type="SMALLINT"> <constraints nullable="false" uniqueConstraintName="TABLE_FIELD_ix1"/> </column> <column name="TABLE_FIELD_TWO" type="SMALLINT"> <constraints nullable="false" uniqueConstraintName="TABLE_FIELD_ix1"/> </column> </createTable> I know I can use the addUniqueConstraint tag (and have successfully used it) after I create the table but I wanted to know if that was avoidable. Basically I want to do this but during the create table portion <addUniqueConstraint tableName="MY_TABLE" columnNames="TABLE_FIELD, TABLE_FIELD_TWO" constraintName="TABLE_FIELD_ix1"/>
Try adding unique="true" to <constraints>. <createTable tableName="MY_TABLE"> <column name="MY_TABLE_ID" type="SMALLINT" autoIncrement="true"> <constraints primaryKey="true" nullable="false"/> </column> <column name="TABLE_FIELD" type="SMALLINT"> <constraints nullable="false" unique="true" uniqueConstraintName="TABLE_FIELD_ix1"/> </column> <column name="TABLE_FIELD_TWO" type="SMALLINT"> <constraints nullable="false" unique="true" uniqueConstraintName="TABLE_FIELD_ix2"/> </column> </createTable> This creates two separate unique constraints, one on each of the two fields. It does not create a unique constraint for the set of (TABLE_FIELD, TABLE_FIELD_TWO).
Liquibase
52,950,169
12
Following this documentation: To automatically run Liquibase database migrations on startup, add the org.liquibase:liquibase-core to your classpath. The master change log is by default read from db/changelog/db.changelog-master.yaml but can be set using liquibase.change-log. In addition to YAML, Liquibase also supports JSON, XML, and SQL change log formats. I configured my application to use liquibase migrations. I added liquibase.change-log property so my whole application.properties file looks like this: spring.jpa.hibernate.ddl-auto=none spring.datasource.url=jdbc:mysql://192.168.0.1/db_name spring.datasource.username=db_username spring.datasource.password=super_secret_secret!123 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.testOnBorrow=true spring.datasource.timeBetweenEvictionRunsMillis = 60000 spring.datasource.validationQuery=SELECT 1 liquibase.change-log=db.changelog-master.xml and here is my pom.xml with liquibase-core <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.my.application</groupId> <artifactId>application-name</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>application_name</name> <description>Best app ever</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.BUILD-SNAPSHOT</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <!--<scope>provided</scope>--> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-cas</artifactId> <version>4.0.3.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.5</version> </dependency> <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <version>3.4.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> <pluginRepository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </pluginRepository> </pluginRepositories> </project> But unfortunately nothing happens on startup. I believed that this would add the table specified in my db.changelog-master.xml to my database but SHOW TABLES prints an empty set. <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd"> <include file="classpath:liquibase/changelogs/init.xml" relativeToChangelogFile="false"/> <changeSet id="1" author="bob"> <createTable tableName="department"> <column name="id" type="int"> <constraints primaryKey="true" nullable="false"/> </column> <column name="name" type="varchar(50)"> <constraints nullable="false"/> </column> <column name="active" type="boolean" defaultValueBoolean="true"/> </createTable> </changeSet> </databaseChangeLog>
I believe you are missing <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> in your dependencies
Liquibase
41,960,588
12
I am using Postgresql for my db and created all the entities using the JHipster entity wizard. When I try to make any changes like adding/removing fields, relations to an existing entity I am getting a check sum error and Liquibase is not starting. Also, I haven't made any changes on the DB manually. Any help is appreciated. Thanks. Here is the error I am getting: 2016-12-07 07:36:12.136 ERROR 8644 --- [cker-Executor-1] i.f.p.c.liquibase.AsyncSpringLiquibase : Liquibase could not start correctly, your database is NOT ready: Validation Failed: 1 change sets check sum classpath:config/liquibase/changelog/20161205191514_added_entity_Person.xml::20161205191514-1::jhipster is now: 7:b92d6a054bbdf952b81fa58376bd6a75 liquibase.exception.ValidationFailedException: Validation Failed: 1 change sets check sum classpath:config/liquibase/changelog/20161205191514_added_entity_Person.xml::20161205191514-1::jhipster is now: 7:b92d6a054bbdf952b81fa58376bd6a75 at liquibase.changelog.DatabaseChangeLog.validate(DatabaseChangeLog.java:215) at liquibase.Liquibase.update(Liquibase.java:208) at liquibase.Liquibase.update(Liquibase.java:192) at liquibase.integration.spring.SpringLiquibase.performUpdate(SpringLiquibase.java:434) at liquibase.integration.spring.SpringLiquibase.afterPropertiesSet(SpringLiquibase.java:391) at in.factly.promisetracker.config.liquibase.AsyncSpringLiquibase.initDb(AsyncSpringLiquibase.java:67) at in.factly.promisetracker.config.liquibase.AsyncSpringLiquibase.lambda$afterPropertiesSet$3(AsyncSpringLiquibase.java:50) at in.factly.promisetracker.config.liquibase.AsyncSpringLiquibase$$Lambda$28/847553836.run(Unknown Source) at in.factly.promisetracker.async.ExceptionHandlingAsyncTaskExecutor.lambda$createWrappedRunnable$1(ExceptionHandlingAsyncTaskExecutor.java:47) at in.factly.promisetracker.async.ExceptionHandlingAsyncTaskExecutor$$Lambda$29/342644967.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745)
Executed the following query in Postgres DB which resolved the issue: UPDATE databasechangelog SET md5sum = null
Liquibase
41,019,034
12
I want to insert usernames to the database based on a system property. The system property value can be users="user1;user2;user3" This process must be repeatable, meaning that every time the applications is deployed, the migration/changeset must check the system property, and if it has changed and the users are not already in the database it should insert them. In order to achieve this I am thinking of using the customChange tag. But I want this change to run every time the liquibase runs. Is this possible using liquibase or should I create a custom contextLoadListener?
A standard attribute available to all changesets is the runAlways attribute, which should do what you want. There is also a runOnChange attribute available. Documentation on the attributes available is here: http://www.liquibase.org/documentation/changeset.html
Liquibase
35,775,597
12
I am implementing a changeset in Liquibase that needs a few different preconditions to be valid before it attempts to run. Scenario #1: If table A,B,C exists, mark as ran Scenario #2: If table X,Y,Z doesn't exist, halt execution of changeset In other words, I need two <preConditions> tags with different onFail clauses. Is this at all allowed in Liquibase? I can't seem to make it work. The docs aren't very informative.
It is not allowed currently. There can be just one block. Would it work to break it up into two separate changeSets?
Liquibase
18,866,793
12
We use liquibase to keep track of our database changes.. First changeSet contains those lines: <column name="SHORT_ID" type="INTEGER"> <constraints unique="true" /> </column> Basically it means that SHORT_ID column has unique constraint but the name of this constraint can be whatever and usually is different each time (we run some integration tests against H2 databases and new bases are made each time we run tests) So.. problem is: I can't change this first changeSet but now we have to get rid of this unique constraint. Any ideas how to achieve that by using liquibase?
Liquibase provides an implementation for dropping a not null constraint without knowing the constraint name. It may not have existed when this question was asked (I realise it's quite old). dropNotNullConstraint <dropNotNullConstraint catalogName="cat" columnDataType="int" columnName="id" schemaName="public" tableName="person"/> A dropUniqueConstraint exists but you probably already knew about it as it requires the constraint name.
Liquibase
3,618,234
12
We use liquibase to manage one of our MySQL databases' updates, rollbacks, etc. One small curiosity I've come across is the process of setting values to null in the course of updates or rollbacks. Example: <rollback> <update tableName="boats"> <column name="engine" value="null" /> <column name="oars" value="2" /> At first I was a bit worried that "null" would literally insert the string "null", but it turns out that liquibase seems to have some smarts that actually inserts a null value. I was wondering if this was the recommended way of doing this, or whether there is a platform-agnostic way of saying 'nullValue' explicitly within Liquibase?
Just omit the value attribute on <column>: <rollback> <update tableName="boats"> <column name="engine" type="varchar(255)"/> </update> </rollback> Reference: Update
Liquibase
50,110,456
11
I'm using spring-boot with the liquibase-maven-plugin to generate database changes according to my classes, but the "mvn compile liquibase: diff" command always generates removals and inclusions of indexes and foreign keys even though the database is updated and has no change in the classes (and therefore should have no change in the database). Anyone have any idea if this is right or how to avoid it? I want only the new changes to database to be generated in change sets of the Project.
First of all, I think you are missing the liquibase-hibernate4 maven plugin. From the project Readme.md: This extension lets you use your Hibernate configuration as a comparison database for diff, diffChangeLog and generateChangeLog in Liquibase. Which actually means that you can use it to compare the real database with your java entities in order to generate the new changelogs. As the project wiki suggest, it's important to keep in mind that you need to take a look to the new changelogs and modify it manually if there is something wrong. I also recommend you to read this article from Baeldung that explains that: Your pom.xml should look like: ... <dependencies> ... <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-maven-plugin</artifactId> <version>3.4.1</version> </dependency> ... </dependencies> ... <plugins> ... <plugin> <groupId>org.liquibase</groupId> <artifactId>liquibase-maven-plugin</artifactId> <version>3.4.1</version> <configuration> <propertyFile>src/main/resources/liquibase.properties</propertyFile> </configuration> <dependencies> <dependency> <groupId>org.liquibase.ext</groupId> <artifactId>liquibase-hibernate4</artifactId> <version>3.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.7.3.RELEASE</version> </dependency> </dependencies> </plugin> ... </plugins> ... And your src/main/resources/liquibase.properties: url=jdbc:mysql://localhost:3306/your_db username=your_user password=your_pw driver=com.mysql.jdbc.Driver #orYourDriver outputChangeLogFile=src/main/resources/liquibase-outputChangeLog.xml hibernate:spring:your.model.package?dialect=org.hibernate.dialect.MySQLDialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy Im not sure which persistence storage are you using but please be sure to use the correct drivers and datasource urls. After configure it completely, you should be able to run mvn liquibase:diffChangeLog to generate the new changelogs.
Liquibase
46,019,203
11
I have spring boot application which use 2 databases. I defined 2 configurations providing specified datasources. I want to have that datasources managed separately by liquibase. I defined 2 separated changelog files. The problem is that I can't define 2 separate beans for liquibase. Here are my config classes: ... public class CCSConfiguration { ... @Bean @ConfigurationProperties("ccs.liquibase") public LiquibaseProperties ccsLiquibaseProperties() { return new LiquibaseProperties(); } @Bean public SpringLiquibase ccsLiquibase(LiquibaseProperties liquibaseProperties) { ... } ... } ... public class CCAConfiguration { ... @ConfigurationProperties("cca.liquibase") public LiquibaseProperties ccaLiquibaseProperties() { return new LiquibaseProperties(); } @Bean public SpringLiquibase ccaLiquibase(LiquibaseProperties liquibaseProperties) { ... } ... } And properties: cca: liquibase: change-log: classpath:config/liquibase/cca/master.xml ccs: liquibase: change-log: classpath:config/liquibase/ccs/master.xml With this config i get following error while running appliction: 2017-04-11 14:26:55.664 WARN 34292 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'liquibase' available 2017-04-11 14:26:55.711 WARN 34292 --- [ restartedMain] o.s.boot.SpringApplication : Error handling failed (Error creating bean with name 'delegatingApplicationListener' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.cache.config.internalCacheAdvisor' defined in class path resource [org/springframework/cache/annotation/ProxyCachingConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cache.interceptor.BeanFactoryCacheOperationSourceAdvisor]: Factory method 'cacheAdvisor' threw exception; nested exception is java.lang.NullPointerException) 2017-04-11 14:26:55.939 ERROR 34292 --- [ restartedMain] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: A component required a bean named 'liquibase' that could not be found. Action: Consider defining a bean named 'liquibase' in your configuration. So, is it possible to define multiple liquibase beans for different datasources?
there are two options: you define a bean named liquibase to let spring-boot integrated process to update your schema on you first DS. You have to handle the second one by hand you disable liquibase automatic update at startup with enabled: false and define your way DS and liquibase beans to update your two databases
Liquibase
43,346,062
11
I'm looking into Liquibase as a potential solution to deploy my web application using pre-existing database servers (of different types). This application should access the database with a user that can only manipulate data, I would like to use a different user as schema owner. Since my application uses Spring I thought I could use the integration class, though it would mean I have to create a second datasource which will remain opened for as long as my application runs which defeats the purpose of separating accounts. Does anyone ever faced the same problem ? Any idea for a solution ? I sure can execute liquibase manually and pass relevant information but I wondered if someone figured a cleaner approach. Thanks in advance for your help.
Using Liquibase with Spring Boot (at least 2.0+), there is now the possibility to configure a separate Liquibase db user in your application.yml: spring: datasource: driver-class-name: org.mariadb.jdbc.Driver url: jdbc:mariadb://... username: <app_user> password: ${DB_PASSWORD} liquibase: default-schema: my_schema user: <admin_user> password: ${DB_ADMIN_PASSWORD}
Liquibase
26,774,525
11
For our application we use liquibase. We have a need to run DB migrations both from command line (manually on production) AND automatically as the application starts up (test environment etc). The problem is that Liquibase considers the whole filename as a portion of a changeSet's identity, therefore it tries to reapply the changesets if the path is different. For example, in case of "fully qualified path" VS "relative path" to to the db-changelog file. How to disable FILENAME column check?
Based on this, the approach is as follows: Always use the logicalFilePath attribute on both the databaseChangeLog element and every changeSet element. Example: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <databaseChangeLog logicalFilePath="does-not-matter" xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-2.0.xsd"> <changeSet logicalFilePath="path-independent" author="authorId" id="1"> ... </changeSet> </databaseChangeLog> As result, FILENAME column for all changesets will contain 'path-independent' and check will be omitted.
Liquibase
19,959,755
11
I'm getting my hands on the Liquibase tool and I'd like to mimic working with an existing database. From the command line, I managed to generate the changelog. I was wondering whether it's possible to generate insert statements for data insides the tables?
Yes. Use the --diffTypes="data" parameter output CSV files that are referenced from the generated changelog and will populate your database.
Liquibase
3,290,983
11
I'm using SpringLiquibase for liquibase configuration, below configuration works fine with single changelog file (sql formatted) @Configuration @Slf4j public class LiquibaseConfiguration { @Inject private DataSource dataSource; @Bean public SpringLiquibase liquibase() { log.info("################## Entering into liquibase #################"); SpringLiquibase liquibase = new SpringLiquibase(); liquibase.setDataSource(dataSource); liquibase.setChangeLog("classpath:schema/update-schema-01.sql"); // Configure rest of liquibase here... // ... return liquibase; } } In my application, i may need to run more than one changelog files and i couldn't make such execution, I tried to feed multiple changelogs as follows, liquibase.setChangeLog("classpath:schema/update-schema-01.sql"); liquibase.setChangeLog("classpath:schema/update-schema-02.sql"); the last one changelog file alone getting executed. liquibase.setChangeLog("classpath:schema/*.sql"); Getting error as liquibase.exception.ChangeLogParseException: java.io.IOException: Found 2 files that match classpath:schema/*.sql Please suggest a way to includeAll changelogs here.
One of the possible solution: you can create the main changelog, which will includes other changelogs as much as you wish. And in the SpringLiquibase object you will set only one main liquibase changelog. For example, assume you have 2 changelog files: one-changelog.xml and two-changelog.xml and you need to run the both. I suggest you to create one more file main-changelog.xml and include in it one-changelog.xml and two-changelog.xml files like this: <?xml version="1.0" encoding="UTF-8"?> <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog/1.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog/1.9 http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-1.9.xsd"> <include file="one.xml"/> <include file="two.xml"/> </databaseChangeLog> And set main-changelog.xml file as changelog for SpringLiquibase. As result, you will have 2 separate changelog files.
Liquibase
56,292,517
11
I am using Spring-Liquibase to perform any migration that is needed on the staging database. The applicationContext.xml looks like <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.yahoo.comma"/> <bean id="liquibase" class="liquibase.integration.spring.SpringLiquibase"> <property name="dataSource" ref="dataSource"/> <property name="changeLog" value="classpath:liquibase/changelog.xml"/> <property name="defaultSchema" value="pryme_dev"/> </bean> </beans> When I deploy the war file, i see errors in log as INFO 6/11/14 9:32 AM:liquibase: Successfully acquired change log lock INFO 6/11/14 9:32 AM:liquibase: Reading from pryme_dev.DATABASECHANGELOG INFO 6/11/14 9:32 AM:liquibase: Reading from pryme_dev.DATABASECHANGELOG INFO 6/11/14 9:32 AM:liquibase: Reading from pryme_dev.DATABASECHANGELOG INFO 6/11/14 9:32 AM:liquibase: liquibase/changelog.xml: liquibase/2014/1-1.xml::05192014.1525::harith: Reading from pryme_dev.DATABASECHANGELOG SEVERE 6/11/14 9:32 AM:liquibase: liquibase/changelog.xml: liquibase/2014/1-1.xml::05192014.1525::harith: Change Set liquibase/2014/1-1.xml::05192014.1525::harith failed. Error: Error executing SQL CREATE TABLE pryme_dev.network (id INT NOT NULL, network_id BIGINT UNSIGNED NOT NULL, name VARCHAR(255) NOT NULL, display_name VARCHAR(255) NOT NULL, active TINYINT(1) DEFAULT 1 NOT NULL, created_at TIMESTAMP DEFAULT NOW() NOT NULL, updated_at TIMESTAMP DEFAULT '1970-01-01 00:00:01' NOT NULL, created_by VARCHAR(50) DEFAULT 'pryme_user' NULL, updated_by VARCHAR(50) DEFAULT 'pryme_user' NULL, CONSTRAINT PK_NETWORK PRIMARY KEY (id)): Table 'network' already exists liquibase.exception.DatabaseException: Error executing SQL CREATE TABLE pryme_dev.network (id INT NOT NULL, network_id BIGINT UNSIGNED NOT NULL, name VARCHAR(255) NOT NULL, display_name VARCHAR(255) NOT NULL, active TINYINT(1) DEFAULT 1 NOT NULL, created_at TIMESTAMP DEFAULT NOW() NOT NULL, updated_at TIMESTAMP DEFAULT '1970-01-01 00:00:01' NOT NULL, created_by VARCHAR(50) DEFAULT 'pryme_user' NULL, updated_by VARCHAR(50) DEFAULT 'pryme_user' NULL, CONSTRAINT PK_NETWORK PRIMARY KEY (id)): Table 'network' already exists at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:61) at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:106) at liquibase.database.AbstractJdbcDatabase.execute(AbstractJdbcDatabase.java:1189) at liquibase.database.AbstractJdbcDatabase.executeStatements(AbstractJdbcDatabase.java:1172) at liquibase.changelog.ChangeSet.execute(ChangeSet.java:352) at liquibase.changelog.visitor.UpdateVisitor.visit(UpdateVisitor.java:40) at liquibase.changelog.ChangeLogIterator.run(ChangeLogIterator.java:64) at liquibase.Liquibase.update(Liquibase.java:202) at liquibase.Liquibase.update(Liquibase.java:181) at com.yahoo.comma.persistence.DataSetupTest.liquibaseUpdate(DataSetupTest.java:53) at com.yahoo.comma.integration.IT1DataSetup.generateDataSet(IT1DataSetup.java:46) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:232) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:175) at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:236) at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:134) at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:113) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189) at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165) at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85) at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:103) at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:74) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'network' already exists at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at com.mysql.jdbc.Util.handleNewInstance(Util.java:406) at com.mysql.jdbc.Util.getInstance(Util.java:381) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2536) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465) at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:734) at org.apache.commons.dbcp.DelegatingStatement.execute(DelegatingStatement.java:264) at org.apache.commons.dbcp.DelegatingStatement.execute(DelegatingStatement.java:264) at liquibase.executor.jvm.JdbcExecutor$ExecuteStatementCallback.doInStatement(JdbcExecutor.java:294) at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:54) ... 44 more INFO 6/11/14 9:32 AM:liquibase: liquibase/2014/1-1.xml::05192014.1525::harith: Successfully released change log lock 09:32:14.299 [main] DEBUG o.s.t.c.s.DirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@3ba0fcf Questions - Why is it applying all the changesets when database is already populated and that the database has DATABASECHANGELOG file present? - How do I resolve this issue? Thanks
The problem is often because part of the unique identifier for each changeSet is the path to the changelog file. It looks like it currently sees it as "liquibase/2014/1-1.xml". If you run select * from databasechangelog where id='05192014.1525' what is the path already in the database?
Liquibase
24,168,223
11
I am getting the following liquibase error when I run my Spring Boot application: Specifying files by absolute path was removed in Liquibase 4.0. Please use a relative path or add '/' to the classpath parameter. Here is the class path in application.yaml: liquibase: change-log: classpath:db/changelog/db-changelog-master.xml I also tried: liquibase: change-log: classpath:/db/changelog/db-changelog-master.xml Here is folder structure: Changlog master: <?xml version="1.0" encoding="UTF-8"?> <databaseChangeLog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd"> <include file="db-changelog-1.0.xml"/> </databaseChangeLog>
I got this issue when putting the changelog files outside the resources folder, but if I include them under resources/db/changelog, then it would work fine with setting the bellow config. spring.liquibase.change-log=classpath:/db/changelog/changelog-master.xml Tested under 4.6.2
Liquibase
68,874,846
11
I am looking for an example on how to use the <whereparams></whereparams> which belongs to <update></update>, but I couldn't find anything (even in the official documentation). any help is much appreciated.thanks.
An example usage is <update tableName="updateTest"> <column name="varcharColumn" value="new column 1 value"/> <column name="dateCol" valueDate="2008-01-01"/> <column name="intCol" valueNumeric="11"/> <where>id=:value</where> <whereParams> <param valueNumeric="134" /> </whereParams> </update> where the :value statements in the <where> block is replaced with the values in the `param' blocks. If there are multiple :value statements they are replaced in order within the where clause. However, looking at the code, it looks like the usage of whereParams is not well used or integrated. Perhaps I am missing where it is being picked up, but it may not even be working outside blob/clob updating. Give it a try and see if it works for you, otherwise I'd say stick with the standard where block until support is improved.
Liquibase
22,941,373
11
I've read about how you can generate changelog.xml from an existing schema. That's fine, but I have existing systems that I don't want to touch, except to bring in new changes. I also have completely new systems which require all changes be applied. So, I want to get liquibase to only perform migrations from changeset X when running on an existing system. I.e. that system's DB is at revision X-1 (but no liquibase sys tables), and I don't want any preceeding migrations applied. Many thanks, Pat
I would recommend a slightly different approach, as commented in this Liquibase forum thread generate a changelog from your existing schema. The liquibase CLI can do that for you. I usually take the resulting XML and smooth it out a bit (group related changes into single changelogs, do vendor-specific cleanups and so on), but Liquibase does most of the legwork. run that changelog against the existing database (changelogSync command), but only marking it as applied (without actually modifying the schema). use liquibase for applying new changes from that point on.
Liquibase
6,912,125
11
I currently have the following in my application.properties: liquibase.change-log=classpath:/db/changelog/db.changelog-master.xml The actual path to the file is src/main/resources/db/changelog/db.changelog-master.xml. The changelog is found by Liquibase and everything is working as I would expect. I've moved the changelog and all of the project's JPA entities and repositories into a separate project so that they can be shared with other projects. This second project is a Maven dependency of the first project. What path do I need to use in application.properties of the first project to access the liquibase changelog in the second project? Update I have: projectA.jar -> pom.xml <dependency> <groupId>com.foo</groupId> <artifactId>projectB</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> projectA.jar -> application.properties liquibase.change-log=classpath:/db/changelog/db.changelog-master.xml projectB.jar -> src/main/resources/db/changelog/db.changelog-master.xml But I'm getting: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration$LiquibaseConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find changelog location: class path resource [db/changelog/db.changelog-master.xml] (please add changelog or check your Liquibase configuration)
I'm an idiot. My local ~/.m2 repository had an old version of the jar without the Liquibase changelog. A mvn clean install fixed the issue.
Liquibase
30,353,472
10
I'm using SpringLiquibase to apply my liquibase update automatically during the application startup. In general this works fine, but when I set hibernate.hbm2ddl.auto to "validate" then hibernate starts to complain about the database scheme before liquibase seems to have the chance to apply the updates. My configuration looks like this: @Configuration @EnableTransactionManagement @ComponentScan(basePackages = "com.myapp") @PropertySource(value = {"classpath:myapp.properties"}) @EnableJpaRepositories("com.myapp") public class MyappConfig { @Resource private Environment env; @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getRequiredProperty("jdbc.driver")); dataSource.setUrl(env.getRequiredProperty("jdbc.url")); dataSource.setUsername(env.getRequiredProperty("jdbc.username")); dataSource.setPassword(env.getRequiredProperty("jdbc.password")); return dataSource; } @Bean public SpringLiquibase liquibase() { SpringLiquibase liquibase = new SpringLiquibase(); liquibase.setDataSource(dataSource()); liquibase.setChangeLog("classpath:liquibase/liquibase-master-changelog.xml"); return liquibase; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean(); entityManagerFactoryBean.setDataSource(dataSource()); entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class); entityManagerFactoryBean.setPackagesToScan("com.myapp"); entityManagerFactoryBean.setJpaProperties(hibernateProperties()); return entityManagerFactoryBean; } private Properties hibernateProperties() { Properties properties = new Properties(); String[] propertyNames = new String[]{"hibernate.dialect", "hibernate.show_sql", "hibernate.hbm2ddl.auto"}; for (String propertyName : propertyNames) { properties.put(propertyName, env.getRequiredProperty(propertyName)); } return properties; } @Bean public JpaTransactionManager transactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); return transactionManager; } } Is there any way to get liquibase to apply its updates BEFORE hibernate tries to validate the schema?
Thanks to M. Deinum I was able to solve this by using @Bean @DependsOn("liquibase") public LocalContainerEntityManagerFactoryBean entityManagerFactory() { [...] } The @DependsOn makes sure that liquibase is run before Hibernates schema validation.
Liquibase
27,677,656
10
I am using liquibase 3.5.3 to run liquibase update command on MySql 5.5. I have below changeSet to create a table which has a column as Created_Time that should have a default value as CURRENT_TIMESTAMP. <changeSet author="authorName" id="AutoGeneratedId"> <createTable tableName="aTable"> <column autoIncrement="true" name="Id" type="INT"> <constraints primaryKey="true"/> </column> <column name="Code" type="VARCHAR(45)"/> <column defaultValueComputed="CURRENT_TIMESTAMP" name="Created_Time" type="TIMESTAMP(19)"/> </createTable> </changeSet> While firing liquibase command it throws an exception as Unexpected error running Liquibase: Invalid default value for 'Created_Time' [Failed SQL: CREATE TABLE aTable (Id INT AUTO_INCREMENT NOT NULL, Code VARCHAR(45) NULL, Created_Time TIMESTAMP(19) DEFAULT NOW() NULL, CONSTRAINT PK_ATABLE PRIMARY KEY (Id))] Liquibase is converting CURRENT_TIMESTAMP into NOW() that might be causing this issue. Can some please provide me any solution or alternative to this issue?
Add type as 'TIMESTAMP' as following <column defaultValueComputed="CURRENT_TIMESTAMP" name="Created_Time" type="TIMESTAMP"/>
Liquibase
48,793,666
10
I am trying to export data from an Oracle (ojdbc7) database using liquibase. My property file has below options: driver: oracle.jdbc.driver.OracleDriver url: jdbc:oracle:thin:@localhost:1521:XE username: user password: user outputChangeLogFile:src/main/resources/output.xml defaultSchemaName: USERS In STS I used below command to generate the changelog liquibase:generateChangeLog -DdiffTypes="data" and through command prompt I used: mvn liquibase:generateChangeLog -DdiffTypes="data" But nothing works, I got only crateTable commands not the insert queries. Please guide.
I would suggest try to export data via CLI liquibase version. Download it here, unpack, put ojdbc7.jar into liquibase folder: liquibase --driver=oracle.jdbc.OracleDriver \ --classpath=\path\to\classes:ojdbc7.jar \ --changeLogFile=db.changelog.xml \ --url="jdbc:oracle:thin:@localhost:1521:XE" \ --username=user \ --password=user \ --diffTypes="data" generateChangeLog If everything will work fine we can move to the next step - try to migrate data via maven.
Liquibase
41,627,301
10
Tried to find an answer to this question, but couldn't. So, for example I have this table: TABLE: col1 | col2 123 0 124 1 and I want to change col2 value to 1 and this is how I'm trying to do it: <changeSet author="myName" id="7799"> <sql> UPDATE TABLENAME; SET COL1='1' WHERE col1='123'; </sql> </changeSet> Alas, it doesn't work. So, I was wondering if it is even possible to do that with liquibase? Since, most tags in the documentation have to do with creating table, adding columns etc.
You can use the following liquibase syntax to update: <changeSet author="myname" id="7799"> <update catalogName="dbname" schemaName="public" tableName="TABLENAME"> <column name="COL1" value='1' type="varchar(50)"/> <where>col1='123'</where> </update> </changeSet> For the other options available please check Liquibase Update
Liquibase
16,655,504
10
I have a bunch of sql scripts that create / drop sequences, users and other objects. I'm running these scripts through liquibase, but they fail because oracle complains when I try to drop a non existing sequence, or create an existing user. Is there an oracle way to prevent errors from happening? Something of the sort Create User / Sequence if not exists Drop User/ Secuence if exists As far as I know, I have these options: Write a plsql script Use liquibase contexts. Use liquibase preconditions, but this would mean too much work. Any thoughts / ideas will be greatly appreciated.
Liquibase has a failOnError attribute you can set to false on changeSets that include a call that could fail. <changeSet failOnError="false"> <createSequence sequenceName="new_sequence"/> </changeSet> This allows you to have simple create user, create sequence, drop user, and drop sequence changeSets and if the statement throws an error because they users/sequences exist/don't exist they will still be marked as ran and the update will continue. The downside of this approach is that it will also mark them as ran and continue if they error for some other reason (bad permissions, connection failure, invalid SQL, etc.) The more accurate approach is to use preconditions, like this: <changeSet> <preconditions onFail="MARK_RAN"><not><sequenceExists/></not></preconditions> <createSequence name="new_sequence"/> </changeSet> There is no userExists precondition currently, but you can create custom preconditions or fall back to the precondition. See http://www.liquibase.org/documentation/preconditions.html for documentation
Liquibase
1,625,567
10
Here is the structure, one of the maven dependency jar project, which one contains liquibase change logs in classpath as following: chorke─init─change-1.0.00.GA.jar! └─ META-INF/ └─ migrations/ ├─ db.changelog-master.xml ├─ config/ │ ├─ db.changelog-config.xml │ ├─ db.changelog-property.xml │ └─ db.changelog-restrict.xml └─ change/ ├─ db.changelog-1.xml ├─ db.changelog-2.xml ├─ V1/ │ ├─ db.changelog-1.0.xml │ ├─ db.changelog-1.1.xml │ ├─ V1.0/ │ │ ├─ db.changelog-1.0.00.xml │ │ ├─ db.changelog-1.0.01.xml │ │ ├─ V1.0.00/ │ │ │ ├─ db.changelog-1.0.00.000.xml │ │ │ ├─ db.changelog-1.0.00.001.xml │ │ │ ├─ db.changelog-1.0.00.002.xml │ │ │ └─ db.changelog-1.0.00.999.xml │ │ └─ V1.0.01/ │ │ ├─ db.changelog-1.0.01.000.xml │ │ ├─ db.changelog-1.0.01.001.xml │ │ ├─ db.changelog-1.0.01.002.xml │ │ └─ db.changelog-1.0.01.999.xml │ └─ V1.1/ │ ├─ db.changelog-1.1.00.xml │ ├─ db.changelog-1.1.01.xml │ ├─ V1.1.00/db.changelog-1.1.00.###.xml │ └─ V1.1.01/db.changelog-1.1.01.###.xml └─ V2/ ├─ db.changelog-2.#.xml └─ V2.#/V2.#.##/db.changelog-2.#.##.###.xml Here is db.changelog-master.xml <?xml version="1.0" encoding="UTF-8"?> <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd http://www.liquibase.org/xml/ns/dbchangelog-ext http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-ext.xsd"> <includeAll path="config" relativeToChangelogFile="true"/> <include file="change/db.changelog-1.xml" relativeToChangelogFile="true"/> <include file="change/db.changelog-2.xml" relativeToChangelogFile="true"/> </databaseChangeLog> Which one loaded by spring-boot application.propertiesas following liquibase.change-log=classpath:/META-INF/migrations/db.changelog-master.xml Executed well when it's in the same project. On dependent project it executed as following: DATABASECHANGELOG table created DATABASECHANGELOGLOCK table created But no update migration performed! When db.changelog-master.xml loaded by liquibase maven plugin as following: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <!-- intentionally configuration skipped --> <dependencies> <dependency> <groupId>org.chorke.init</groupId> <artifactId>chorke-init-change</artifactId> <version>1.0.00.GA</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.liquibase</groupId> <artifactId>liquibase-maven-plugin</artifactId> <version>3.5.3</version> <configuration> <propertyFileWillOverride>true</propertyFileWillOverride> <promptOnNonLocalDatabase>false</promptOnNonLocalDatabase> <changeLogFile>classpath:/META-INF/migrations/db.changelog-master.xml</changeLogFile> <propertyFile>${project.build.directory}/test-classes/liquibase-update.properties</propertyFile> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>update</goal> </goals> </execution> </executions> <dependencies> <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.14</version> </dependency> </dependencies> </plugin> </plugins> </build> </project> Error with the message: Failed to execute goal org.liquibase:liquibase-maven-plugin:3.5.3:update (default) on project chorke-init-migrat: Error setting up or running Liquibase: classpath:/META-INF/migrations/db.changelog-master.xml does not exist In this situation your guideline expected for error free liquibase migration for the dependent project those are using spring-boot or liquibase-maven-plugin
The structure mentioned for chorke─init─change-1.0.00.GA.jar contains liquibase change logs in classpath is good enough and spring-boot application.properties also configured exactly. But there were some silly mistake in liquibase-maven-plugin configuration, It should be corrected as following: <configuration> <propertyFileWillOverride>true</propertyFileWillOverride> <promptOnNonLocalDatabase>false</promptOnNonLocalDatabase> <changeLogFile>META-INF/migrations/db.changelog-master.xml</changeLogFile> <propertyFile>liquibase-update.properties</propertyFile> </configuration> There were two mistakes in liquibase-maven-plugin configuration those are: First one for changeLogFile Second one for propertyFile No need to use prefix like classpath: or classpath:/ for changeLogFile, Also need not to use absolute or relative path like ${project.build.directory}/test-classes/ for propertyFile. Leave it simple. It's the own business of liquibase-maven-plugin how to resolve it from classpath. Beside that, there is some additional tips might be helpful for hassle free portable migration those are as following Always use relative path for each databaseChangeLog. Example is mentioned in your db.changelog-master.xml Use Logical File Path for each changeSet Here is the example for Logical File Path: <changeSet author="chorkeorg" id="1508234245316-1" logicalFilePath="V0/V0.0/V0.0.00/db.changelog-0.0.00.000.xml"> <createSequence cacheSize="20" cycle="false" incrementBy="1" maxValue="999999999999999999999999999" minValue="10001" ordered="false" sequenceName="CK_SQ_AUTHOR" startValue="10181" /> </changeSet> Hope it would be resolve your issues properly.
Liquibase
46,810,712
10
Using gradle-liquibase plugin in our project with all dependencies resolved. I have the following liquibase task as suggested by Gradle liquibase plugin: liquibase { activities { main { changeLogFile 'src/main/resources/db/dbchangelog-master.xml' url 'jdbc:mysql://localhost:3306/test' username 'XXX' password 'XXX' } } runList = 'main' } But encountered problems with the changeLogFile not being identified by liquibase though the logfile is in project classpath directory (src/main/resources/) Error: Caused by: liquibase.exception.ChangeLogParseException: src/main/resources/dbchangelog/db.changelog-master.xml does not exist Any help with regards to how should I resolve this classpath related issue?
Just add a classpath parameter where your src directory is liquibase { activities { main { changeLogFile 'src/main/resources/db/dbchangelog-master.xml' url 'jdbc:mysql://localhost:3306/test' username 'XXX' password 'XXX' classpath "$rootDir" } } runList = 'main' }
Liquibase
27,187,979
10
I am new to R2DBC (https://r2dbc.io/). I would like to know whether r2dbc's ecosystem has a database migration tool/framework. It seems Liquibase & Flyway depend on JDBC. Is there a plan for allowing those frameworks to support a r2dbc driver? Any input or feedback welcome.
Steve's answer is correct hat R2DBC is primarily about interaction with the actual data. I'd like to add a different perspective. It's true that a reactive API does not provide any improvement during migrations. In fact, looking closely, migrations are part of the startup process which is typically synchronous, at least synchronized to some extent. Requiring JDBC for migration adds to complexity in such an application arrangement. You are required to include a JDBC driver to an existing R2DBC setup and you need to configure another database connection that points to the same database as with R2DBC. Both requirements are error-prone as they need to be configured to do the exact same thing. Nowadays, application configuration frameworks (Spring Boot, Micronaut, Quarkus) activate functionality when a certain library is available from the classpath. Having a JDBC driver configured boots functionality that isn't required for the application but required during bootstrapping and that is sort of a waste of resources. Ideally, you configure a single database connection technology that is reused for schema migration and for later data interaction within your application. Therefore it makes sense to ask Liquibase and Flyway to provide an R2DBC-based integration.
Liquibase
57,183,169
10
I'm currently using Liquibase in a small project of mine, which works pretty fine. But right now i'm facing a problem. My ChangeLog works as expected in my testenv but fails on my productiv one. This happens because my prod-tables contain a few rows of data. I know there is an UPDATE-Command in liquibase, but im not sure how to use it correctly. What i want to archive is to move a column from table B to table A without losing its data. Table B contains a foreignkey of table A. A normal SQL-Statement would look smth like update A set A.x = (select B.x from B where B.id = A.id) It would be nice if someone could give me a example of such an update-changeset. Thx!
It may look like <changeSet ...> <update tableName="TABLE_A"> <column name="x" valueComputed="(select b.x from TABLE_B b where b.id=id)"/> </update> </changeset>
Liquibase
33,820,620
10
As described here (https://github.com/liquibase/liquibase-hibernate/issues/74) I'm having an issue getting the liquibase-hibernate extension to work properly. I think I have everything setup, but it seems like I keep running into weird problems. I feel like I'm missing something simple, but I think I've followed all the instructions as provided. I'm using liquibase 3.3.2, Hibernate 4.3.0.Final, java 1.7.0_71 and the liquibase-hibernate4-3.5.jar. My CLASSPATH environmental variable is empty, but some stuff gets added to it by the liquibase shell script. When I'm using normal liquibase commands interacting, and I remove the extension from $LIQUIBASE_HOME/lib/ directory without the extension it works just fine. I reran the commands with DEBUG output on to provide some more information. $ echo $CLASSPATH $ java -version java version "1.7.0_71" Java(TM) SE Runtime Environment (build 1.7.0_71-b14) Java HotSpot(TM) 64-Bit Server VM (build 24.71-b01, mixed mode) $ liquibase --version Liquibase Version: 3.3.2 $ liquibase diffChangeLog //The below is the stuff liquibase is adding to my classpath .:/c/repos/ServeDirtyLibsInJava/liquibaseLib/liquibase.jar:/c/repos/ServeDirtyLibsInJava/liquibaseLib/lib/liquibase-hibernate4-3.5.jar:/c/repos/ServeDirtyLibsInJava/liquibaseLib/lib/snakeyaml-1.13.jar WARNING 1/19/15 12:42 AM: liquibase: Can not use class liquibase.ext.hibernate.database.HibernateEjb3Database as a Liquibase service because org.hibernate.dialect.Dialect is not in the classpath WARNING 1/19/15 12:42 AM: liquibase: Can not use class liquibase.ext.hibernate.database.HibernateSpringDatabase as a Liquibase service because org.hibernate.dialect.Dialect is not in the classpath WARNING 1/19/15 12:42 AM: liquibase: Can not use class liquibase.ext.hibernate.database.HibernateClassicDatabase as a Liquibase service because org.hibernate.dialect.Dialect is not in the classpath DEBUG 1/19/15 10:20 AM: liquibase: Connected to root@localhost@jdbc:mysql://localhost:3306/dirtylibs DEBUG 1/19/15 10:20 AM: liquibase: Setting auto commit to false from true Unexpected error running Liquibase: java.lang.RuntimeException: Cannot find database driver: Driver class was not specified and could not be determined from the url (hibernate:spring:com.companyname.dirtylibs.persistence.entities?dialect=org.hibernate.dialect.MySQL5Dialect) SEVERE 1/19/15 10:20 AM: liquibase: java.lang.RuntimeException: Cannot find database driver: Driver class was not specified and could not be determined from the url (hibernate:spring:com.companyname.dirtylibs.persistence.entities?dialect=org.hibernate.dialect.MySQL5Dialect) liquibase.exception.DatabaseException: liquibase.exception.DatabaseException: java.lang.RuntimeException: Cannot find database driver: Driver class was not specified and could not be determined from the url (hibernate:spring:com.companyname.dirtylibs.persistence.entities?dialect=org.hibernate.dialec t.MySQL5Dialect) at liquibase.integration.commandline.CommandLineUtils.createDatabaseObject(CommandLineUtils.java:69) at liquibase.integration.commandline.Main.createReferenceDatabaseFromCommandParams(Main.java:1169) at liquibase.integration.commandline.Main.doMigration(Main.java:936) at liquibase.integration.commandline.Main.run(Main.java:175) at liquibase.integration.commandline.Main.main(Main.java:94) Caused by: liquibase.exception.DatabaseException: java.lang.RuntimeException: Cannot find database driver: Driver class was not specified and could not be determined from the url (hibernate:spring:com.companyname.dirtylibs.persistence.entities?dialect=org.hibernate.dialect.MySQL5Dialect) at liquibase.database.DatabaseFactory.openConnection(DatabaseFactory.java:239) at liquibase.database.DatabaseFactory.openDatabase(DatabaseFactory.java:143) at liquibase.integration.commandline.CommandLineUtils.createDatabaseObject(CommandLineUtils.java:50) ... 4 more Caused by: java.lang.RuntimeException: Cannot find database driver: Driver class was not specified and could not be determined from the url (hibernate:spring:com.companyname.dirtylibs.persistence.entities?dialect=org.hibernate.dialect.MySQL5Dialect) at liquibase.database.DatabaseFactory.openConnection(DatabaseFactory.java:191) ... 6 more My liquibase.properties file driver=com.mysql.jdbc.Driver classpath=mysql-connector-java-5.1.6.jar url=jdbc:mysql://localhost:3306/dirtylibs username=root password=password changeLogFile=changelog.xml #referenceDriver=liquibase.ext.hibernate.database.connection.HibernateDriver referenceUrl=hibernate:spring:com.companyname.dirtylibs.persistence.entities?dialect=org.hibernate.dialect.MySQL5Dialect referenceUsername=root referencePassword=password If I uncomment my referenceDriver I get this. Is there something I'm missing here? I thought I had all the required dependencies, and I'm not sure if this is some manifestation of the earlier problem where the extension could not load stuff properly. $ liquibase diffChangeLog WARNING 1/19/15 12:49 AM: liquibase: Can not use class liquibase.ext.hibernate.database.HibernateEjb3Database as a Liquibase service because org.hibernate.dialect.Dialect is not in the classpath WARNING 1/19/15 12:49 AM: liquibase: Can not use class liquibase.ext.hibernate.database.HibernateSpringDatabase as a Liquibase service because org.hibernate.dialect.Dialect is not in the classpath WARNING 1/19/15 12:49 AM: liquibase: Can not use class liquibase.ext.hibernate.database.HibernateClassicDatabase as a Liquibase service because org.hibernate.dialect.Dialect is not in the classpath WARNING 1/19/15 12:49 AM: liquibase: Can not use class liquibase.ext.hibernate.snapshot.SequenceSnapshotGenerator as a Liquibase service because org.hibernate.id.factory.IdentifierGeneratorFactory is not in the classpath WARNING 1/19/15 12:49 AM: liquibase: Can not use class liquibase.ext.hibernate.snapshot.TableSnapshotGenerator as a Liquibase service because org.hibernate.id.factory.IdentifierGeneratorFactory is not in the classpath Unexpected error running Liquibase: org.hibernate.sql.Alias SEVERE 1/19/15 10:22 AM: liquibase: org.hibernate.sql.Alias java.lang.NoClassDefFoundError: org/hibernate/sql/Alias at liquibase.ext.hibernate.snapshot.PrimaryKeySnapshotGenerator.<clinit>(PrimaryKeySnapshotGenerator.java:27) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at liquibase.snapshot.SnapshotGeneratorFactory.<init>(SnapshotGeneratorFactory.java:29) at liquibase.snapshot.SnapshotGeneratorFactory.getInstance(SnapshotGeneratorFactory.java:43) at liquibase.snapshot.SnapshotControl.addType(SnapshotControl.java:95) at liquibase.snapshot.SnapshotControl.setTypes(SnapshotControl.java:88) at liquibase.snapshot.SnapshotControl.<init>(SnapshotControl.java:25) at liquibase.command.DiffCommand.createReferenceSnapshot(DiffCommand.java:185) at liquibase.command.DiffCommand.createDiffResult(DiffCommand.java:140) at liquibase.command.DiffToChangeLogCommand.run(DiffToChangeLogCommand.java:51) at liquibase.command.AbstractCommand.execute(AbstractCommand.java:8) at liquibase.integration.commandline.CommandLineUtils.doDiffToChangeLog(CommandLineUtils.java:121) at liquibase.integration.commandline.Main.doMigration(Main.java:936) at liquibase.integration.commandline.Main.run(Main.java:175) at liquibase.integration.commandline.Main.main(Main.java:94) Caused by: java.lang.ClassNotFoundException: org.hibernate.sql.Alias at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ... 18 more After adding the hibernate jar to the liquibase/lib folder (which is really wrong) the error turned into this. I tried reverting to an older version of the plugin (while downgrading liquibase as well), and it did not help. $ liquibase --logLevel=DEBUG diffChangeLog .:/c/repos/ServeDirtyLibsInJava/liquibaseLib/liquibase.jar:/c/repos/ServeDirtyLibsInJava/liquibaseLib/lib/hibernate-core-4.3.0.Final.jar:/c/repos/ServeDirtyLibsInJava/liquibaseLib/lib/liquibase-hibernate4-3.5.jar:/c/repos/ServeDirtyLibsInJava/liquibaseLib/lib/snakeyaml-1.13.jar WARNING 1/19/15 10:38 AM: liquibase: Can not use class liquibase.ext.hibernate.database.HibernateSpringDatabase as a Liquibase service because org.springframework.beans.factory.support.BeanDefinitionRegistry is not in the classpath DEBUG 1/19/15 10:38 AM: liquibase: Connected to root@localhost@jdbc:mysql://localhost:3306/dirtylibs DEBUG 1/19/15 10:38 AM: liquibase: Setting auto commit to false from true WARNING 1/19/15 10:38 AM: liquibase: Unknown database: Hibernate DEBUG 1/19/15 10:38 AM: liquibase: Connected to null@hibernate:spring:com.companyname.dirtylibs.persistence.entities?dialect=org.hibernate.dialect.MySQL5Dialect DEBUG 1/19/15 10:38 AM: liquibase: Not adjusting the auto commit mode; it is already false INFO 1/19/15 10:38 AM: liquibase: Error getting default schema java.lang.NullPointerException at liquibase.executor.jvm.JdbcExecutor$QueryCallableStatementCallback.doInCallableStatement(JdbcExecutor.java:383) at liquibase.executor.jvm.JdbcExecutor.execute(JdbcExecutor.java:96) at liquibase.executor.jvm.JdbcExecutor.query(JdbcExecutor.java:132) at liquibase.executor.jvm.JdbcExecutor.query(JdbcExecutor.java:143) at liquibase.executor.jvm.JdbcExecutor.queryForObject(JdbcExecutor.java:151) at liquibase.executor.jvm.JdbcExecutor.queryForObject(JdbcExecutor.java:166) at liquibase.executor.jvm.JdbcExecutor.queryForObject(JdbcExecutor.java:161) at liquibase.database.AbstractJdbcDatabase.getConnectionSchemaName(AbstractJdbcDatabase.java:318) at liquibase.database.AbstractJdbcDatabase.getDefaultSchemaName(AbstractJdbcDatabase.java:301) at liquibase.CatalogAndSchema.customize(CatalogAndSchema.java:132) at liquibase.snapshot.SnapshotGeneratorFactory.createSnapshot(SnapshotGeneratorFactory.java:116) at liquibase.command.DiffCommand.createReferenceSnapshot(DiffCommand.java:190) at liquibase.command.DiffCommand.createDiffResult(DiffCommand.java:140) at liquibase.command.DiffToChangeLogCommand.run(DiffToChangeLogCommand.java:51) at liquibase.command.AbstractCommand.execute(AbstractCommand.java:8) at liquibase.integration.commandline.CommandLineUtils.doDiffToChangeLog(CommandLineUtils.java:121) at liquibase.integration.commandline.Main.doMigration(Main.java:936) at liquibase.integration.commandline.Main.run(Main.java:175) at liquibase.integration.commandline.Main.main(Main.java:94) DEBUG 1/19/15 10:38 AM: liquibase: Computed checksum for 1421681927678 as b60efdd1567f2fd4e5407a8d157cb0b6 Unexpected error running Liquibase: java.lang.NullPointerException SEVERE 1/19/15 10:38 AM: liquibase: java.lang.NullPointerException liquibase.exception.LiquibaseException: liquibase.command.CommandExecutionException: java.lang.NullPointerException at liquibase.integration.commandline.CommandLineUtils.doDiffToChangeLog(CommandLineUtils.java:123) at liquibase.integration.commandline.Main.doMigration(Main.java:936) at liquibase.integration.commandline.Main.run(Main.java:175) at liquibase.integration.commandline.Main.main(Main.java:94) Caused by: liquibase.command.CommandExecutionException: java.lang.NullPointerException at liquibase.command.AbstractCommand.execute(AbstractCommand.java:13) at liquibase.integration.commandline.CommandLineUtils.doDiffToChangeLog(CommandLineUtils.java:121) ... 3 more Caused by: java.lang.NullPointerException at liquibase.snapshot.jvm.CatalogSnapshotGenerator.getDatabaseCatalogNames(CatalogSnapshotGenerator.java:82) at liquibase.snapshot.jvm.CatalogSnapshotGenerator.snapshotObject(CatalogSnapshotGenerator.java:41) at liquibase.snapshot.jvm.JdbcSnapshotGenerator.snapshot(JdbcSnapshotGenerator.java:60) at liquibase.snapshot.SnapshotGeneratorChain.snapshot(SnapshotGeneratorChain.java:50) at liquibase.snapshot.DatabaseSnapshot.include(DatabaseSnapshot.java:163) at liquibase.snapshot.DatabaseSnapshot.init(DatabaseSnapshot.java:55) at liquibase.snapshot.DatabaseSnapshot.<init>(DatabaseSnapshot.java:37) at liquibase.snapshot.JdbcDatabaseSnapshot.<init>(JdbcDatabaseSnapshot.java:25) at liquibase.snapshot.SnapshotGeneratorFactory.createSnapshot(SnapshotGeneratorFactory.java:126) at liquibase.snapshot.SnapshotGeneratorFactory.createSnapshot(SnapshotGeneratorFactory.java:119) at liquibase.command.DiffCommand.createReferenceSnapshot(DiffCommand.java:190) at liquibase.command.DiffCommand.createDiffResult(DiffCommand.java:140) at liquibase.command.DiffToChangeLogCommand.run(DiffToChangeLogCommand.java:51) at liquibase.command.AbstractCommand.execute(AbstractCommand.java:8) ... 4 more
I got it working by adding these jars to my classpath. This is super confusing and not well documented. The process I went through was: Download the source for the correct plugin project found here (https://github.com/liquibase/liquibase-hibernate/releases) in my case it was liquibase-hibernate4-3.5. Run mvn dependency:copy-dependencies. This dumps them into /target/dependency/. Copy all these jars and put them into your LIQUIBASE_HOME/lib directory. I'm using gradle so I used a custom task to copy all my dependencies. If you're using maven you can use the same step from 2 on your own project to fetch all your depdenencies. I copied these libs from my output directory into the LIQUIBASE_HOME/lib directory. task copyToLib(type: Copy) { into "$buildDir/output/libs" from configurations.runtime } I also put the correct hibernate-liquibase-4.3.5.jar into the LIQUIBASE_HOME/lib directory. That gave me all the dependencies I needed for the plugin. This is a big nasty ball of mess, but what can you do :(
Liquibase
28,029,556
10
I have been trying for quite some time to figure out a solution for my problem, to no avail. Anyway, i have a bunch of integration tests (in a nonstandard directory testRegression parallel to the standard test directory). These integration tests use an h2 in memory database. In production as well as for testing i am using liquibase to simulate the schema evolution. My properties (in application-testRegession.properties) look as follows: spring.liquibase.enabled=true spring.liquibase.user=sa spring.liquibase.password= spring.liquibase.change-log=classpath:/liquibase/changelog-master.xml spring.datasource.url=jdbc:p6spy:h2:mem:testdb;MODE=PostgreSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS nmc\\;CREATE SCHEMA IF NOT EXISTS mkt\\;CREATE SCHEMA IF NOT EXISTS cdb\\;CREATE SCHEMA IF NOT EXISTS pg_temp spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver spring.datasource.username=sa spring.datasource.password= The error i consistenly keep getting is: 2020-07-21 15:57:34.173 INFO [liquibase.lockservice.StandardLockService] [Test worker:13]: Successfully acquired change log lock 2020-07-21 15:57:34.303 INFO [liquibase.changelog.StandardChangeLogHistoryService] [Test worker:13]: Creating database history table with name: PUBLIC.DATABASECHANGELOG 2020-07-21 15:57:34.305 INFO [liquibase.executor.jvm.JdbcExecutor] [Test worker:13]: CREATE TABLE PUBLIC.DATABASECHANGELOG (ID VARCHAR(255) NOT NULL, AUTHOR VARCHAR(255) NOT NULL, FILENAME VARCHAR(255) NOT NULL, DATEEXECUTED TIMESTAMP NOT NULL, ORDEREXECUTED INT NOT NULL, EXECTYPE VARCHAR(10) NOT NULL, MD5SUM VARCHAR(35), DESCRIPTION VARCHAR(255), COMMENTS VARCHAR(255), TAG VARCHAR(255), LIQUIBASE VARCHAR(20), CONTEXTS VARCHAR(255), LABELS VARCHAR(255), DEPLOYMENT_ID VARCHAR(10)) 2020-07-21 15:57:34.307 INFO [liquibase.lockservice.StandardLockService] [Test worker:13]: Successfully released change log lock 2020-07-21 15:57:34.309 WARN [org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext] [Test worker:13]: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration$LiquibaseConfiguration.class]: Invocation of init method failed; nested exception is liquibase.exception.DatabaseException: Table "DATABASECHANGELOG" already exists; SQL statement: CREATE TABLE PUBLIC.DATABASECHANGELOG (ID VARCHAR(255) NOT NULL, AUTHOR VARCHAR(255) NOT NULL, FILENAME VARCHAR(255) NOT NULL, DATEEXECUTED TIMESTAMP NOT NULL, ORDEREXECUTED INT NOT NULL, EXECTYPE VARCHAR(10) NOT NULL, MD5SUM VARCHAR(35), DESCRIPTION VARCHAR(255), COMMENTS VARCHAR(255), TAG VARCHAR(255), LIQUIBASE VARCHAR(20), CONTEXTS VARCHAR(255), LABELS VARCHAR(255), DEPLOYMENT_ID VARCHAR(10)) [42101-197] [Failed SQL: (42101) CREATE TABLE PUBLIC.DATABASECHANGELOG (ID VARCHAR(255) NOT NULL, AUTHOR VARCHAR(255) NOT NULL, FILENAME VARCHAR(255) NOT NULL, DATEEXECUTED TIMESTAMP NOT NULL, ORDEREXECUTED INT NOT NULL, EXECTYPE VARCHAR(10) NOT NULL, MD5SUM VARCHAR(35), DESCRIPTION VARCHAR(255), COMMENTS VARCHAR(255), TAG VARCHAR(255), LIQUIBASE VARCHAR(20), CONTEXTS VARCHAR(255), LABELS VARCHAR(255), DEPLOYMENT_ID VARCHAR(10))] 2020-07-21 15:57:34.309 INFO [com.zaxxer.hikari.HikariDataSource] [Test worker:13]: HikariPool-3 - Shutdown initiated... 2020-07-21 15:57:34.324 INFO [com.zaxxer.hikari.HikariDataSource] [Test worker:13]: HikariPool-3 - Shutdown completed. 2020-07-21 15:57:34.326 INFO [org.apache.catalina.core.StandardService] [Test worker:13]: Stopping service [Tomcat] 2020-07-21 15:57:34.342 INFO [org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener] [Test worker:13]: Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2020-07-21 15:57:34.345 ERROR [org.springframework.boot.SpringApplication] [Test worker:13]: Application run failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration$LiquibaseConfiguration.class]: Invocation of init method failed; nested exception is liquibase.exception.DatabaseException: Table "DATABASECHANGELOG" already exists; SQL statement: So how can i get around this issue? My basic understanding is that each test class creates its own ApplicationContext. For that it creates and loads a liquibase bean into it. However, this problem occurs only for 2 out of 42 tests. I would really like to get to the bottom of this and understand whats going on. Can anyone shed light on my problem? ADDITIONALLY The test all run fine individually, but when run as a group they fail. UPDATE 1 The relevant properties are as follows: spring.main.allow-bean-definition-overriding=true spring.datasource.url=jdbc:p6spy:h2:mem:testdb;MODE=PostgreSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=FALSE;INIT=CREATE SCHEMA IF NOT EXISTS nmc\\;CREATE SCHEMA IF NOT EXISTS mkt\\;CREATE SCHEMA IF NOT EXISTS cdb\\;CREATE SCHEMA IF NOT EXISTS pg_temp spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver spring.datasource.username=sa spring.datasource.password= spring.datasource.hikari.connectionTimeout=10000 spring.datasource.hikari.idleTimeout=60000 spring.datasource.hikari.maxLifetime=180000 spring.datasource.hikari.maximumPoolSize=50 spring.h2.console.enabled=true spring.h2.console.path=/h2-console My configuration is: @Configuration @ComponentScan( basePackages = { "com.aareal.nmc" }, excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = CommandLineRunner.class) }) @EnableTransactionManagement @Profile("testRegression") @SpringBootApplication(exclude = SecurityAutoConfiguration.class) @EnableConfigurationProperties(LiquibaseProperties.class) public class RegressionTestConfig { My two tests are annotated as: @RunWith(SpringRunner.class) @SpringBootTest( classes = { RegressionTestConfig.class }, //webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) Thanks
I had the same issue, and it seems to have been caused by case sensitive checking of the database table name. That is, the table was created as 'DATABASECHANGELOG', but Liquibase was checking for the existence of 'databasechangelog'. The fix (at least for an H2 database) is to specify case insensitive identifiers in the database URL. For example: jdbc:h2:mem:~/mydb;CASE_INSENSITIVE_IDENTIFIERS=TRUE Explanation: The Spring test process fires up one or more instances of the Spring container to run tests on. If it thinks the config is exactly the same for two tests it will re-use an instance, otherwise it will start a new one. The instances are shared to avoid needing to start a whole new Springboot application for each test. But, the problem is that the instances may share some resources, such as databases and network ports. Therefore errors might occur from trying to start multiple instances at the same time. In this case, the test suite is starting two instances using the same database, but the second one is trying to re-run the whole Liquibase setup because the case sensitive issue means it doesn't see the table has already been created.
Liquibase
63,036,299
10
My package structure is looks like: In /db.changelog/db.changelod-master.xml i include /db.changelog/v1/db.changelog-1.0.xml where i also include all changelogs from /db.changelog/v1/changeset package. In my application, I have two profiles: dev and prod, and I need to divide the structure of packages according to "Best Practises" of Liquibase. Some changelogs can be in prod and dev environment. Also, I can use context attribute in changeset tag and explicitly set dev or prod value, but this workaround is not preferable. Simple usage looks like: i switch to prod profile and some tables will not be created or some inserts to Database will be skipped. Can you please help me refactor structure of packages according to Liquibase "Best Practices??
Solution1: You need to define 'liquibase.contexts' property into your yaml file. Something like below. spring: profiles: dev datasource: url: jdbc:postgresql://localhost:5432/dev username: postgres password: password driver-class-name: org.postgresql.Driver liquibase: contexts: dev After adding this the below change set will only execute when your local profile is 'dev' (i.e. spring-boot:run -Dspring.profiles.active=dev) <changeSet id="20161016_my_first_change2" author="krudland" context="dev"> <sql> insert into customer (firstname, lastname) values ('Franklin','Ike'); </sql> <rollback> delete from customer where firstname = 'Franklin' and lastname = 'Ike'; </rollback> </changeSet> Solution2: If you don't want to use liquibase.context, You might can use maven to filter recourses : The key was to use the maven filter element in conjunction with the resource element as explained in Liquibase Documentation. Also it's important to include the resources goal in the maven command: mvn resources:resources liquibase:update -Plocal This is the file hierarchy I used: |-- pom.xml `-- src `-- main |-- resources | `-- liquibase.properties | |-- changelog | `-- db-changelog-master.xml | `-- db-changelog-1.0.xml |-- filters |-- local | `-- db.properties |-- dev | `-- db.properties The db.properties file would look like the following: database.driver = oracle.jdbc.driver.OracleDriver database.url = jdbc:oracle:thin:@<host_name>:<port_number>/instance database.username = user database.password = password123 database.changelogfile = db.changelog-master.xml The liquibase.properties file would look like the following: changeLogFile: changelog/${database.changelogfile} driver: ${database.driver} url: ${database.url} username: ${database.username} password: ${database.password} verbose: true The POM file would look like the following: <build> <pluginManagement> <plugins> <plugin> <groupId>org.liquibase</groupId> <artifactId>liquibase-maven-plugin</artifactId> <version>3.1.0</version> <configuration> <propertyFile>target/classes/liquibase.properties</propertyFile> </configuration> </plugin> </plugins> </pluginManagement> </build> <profiles> <profile> <id>local</id> <activation> <activeByDefault>true</activeByDefault> </activation> <build> <filters> <filter>src/main/filters/local/db.properties</filter> </filters> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </build> </profile> <profile> <id>dev</id> <build> <filters> <filter>src/main/filters/dev/db.properties</filter> </filters> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> </build> </profile> </profiles>
Liquibase
52,645,232
10
I'm having a hard time setting up LiquiBase in my Spring Boot project. I tried looking through the docs and finding some guides - but they seem contradict each other. I wish to use LiquiBase via Gradle and I want it to generate the changelogs from Hibernate and end up with a SQL script I can run on the server to update the schema to the appropriate version. To get it to run via Gradle I'm using this plugin https://github.com/liquibase/liquibase-gradle-plugin using the recommended setup shown in their README. To get the Hibernate diff to work I'm using https://github.com/liquibase/liquibase-hibernate Here's my build.gradle file: buildscript { ext { springBootVersion = '2.0.5.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } plugins { id 'java' id 'net.ltgt.apt' version '0.10' // https://projectlombok.org/setup/gradle id 'org.liquibase.gradle' version '2.0.1' // https://github.com/liquibase/liquibase-gradle-plugin } apply plugin: 'eclipse-wtp' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' apply plugin: 'war' group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() maven { credentials { username = oracleUser password = oraclePass } url 'https://www.oracle.com/content/secure/maven/content' } } liquibase { activities { main { changeLogFile 'main.groovy' url 'jdbc:oracle:thin:@localhost:1521:XE' referenceUrl 'hibernate:spring:com.example?dialect=org.hibernate.dialect.Oracle10gDialect' username 'user' password 'pass' } } } configurations { providedRuntime } dependencies { compile('org.springframework.boot:spring-boot-starter-data-jpa') compile('org.springframework.boot:spring-boot-starter-data-rest') compile('org.springframework.boot:spring-boot-starter-hateoas') compile('org.springframework.boot:spring-boot-starter-jooq') compile('org.springframework.boot:spring-boot-starter-web') compile('org.springframework.boot:spring-boot-starter-mail') compile('com.github.waffle:waffle-spring-boot-starter:1.9.0') compile('com.oracle.jdbc:ojdbc8:12.2.0.1') runtime('org.springframework.boot:spring-boot-devtools') compileOnly('org.projectlombok:lombok') apt('org.projectlombok:lombok:1.18.2') liquibaseRuntime('org.liquibase:liquibase-core:3.6.2') liquibaseRuntime('org.liquibase:liquibase-groovy-dsl:2.0.1') liquibaseRuntime('org.liquibase.ext:liquibase-hibernate5:3.6') liquibaseRuntime('com.oracle.jdbc:ojdbc8:12.2.0.1') // duplicate... providedRuntime('org.springframework.boot:spring-boot-starter-tomcat') testCompile('org.springframework.boot:spring-boot-starter-test') testCompile('org.springframework.restdocs:spring-restdocs-mockmvc') } Running it via > .\gradlew diffChangeLog -PrunList=main But fails with Task :diffChangeLog liquibase-plugin: Running the 'main' activity... Starting Liquibase at Wed, 26 Sep 2018 13:36:24 CEST (version 3.6.2 built at 2018-07-03 11:28:09) Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/core/io/ClassPathResource at liquibase.ext.hibernate.database.HibernateSpringPackageDatabase.isXmlFile(HibernateSpringPackageDatabase.java:54) It looks like it cannot find Spring Boot. So I then tried removing the liquibaseRuntime but then the LiquiBase Gradle plugin complains that liquibaseRuntime is missing. Seems I'm stuck in a loop. What is a sane way of setting this up? I really don't want to repeat every dependency inside the liquibaseRuntime. Also the doc literally says: dependencies { // All of your normal project dependencies would be here in addition to... liquibaseRuntime 'org.liquibase:liquibase-core:3.6.1' liquibaseRuntime 'org.liquibase:liquibase-groovy-dsl:2.0.1' liquibaseRuntime 'mysql:mysql-connector-java:5.1.34' } Note the // All of your normal project dependencies would be here in addition to... Why is this happening? Also, I noticed that you have to write database config twice. Why is that needed when it's already set in spring boot config? Progress So changing liquibaseRuntime to liquibaseRuntime('org.liquibase:liquibase-core:3.6.2') liquibaseRuntime('org.liquibase:liquibase-groovy-dsl:2.0.1') liquibaseRuntime('org.liquibase.ext:liquibase-hibernate5:3.6') liquibaseRuntime('com.oracle.jdbc:ojdbc8:12.2.0.1') liquibaseRuntime('org.springframework.boot:spring-boot-starter-data-jpa') liquibaseRuntime files('src/main') Makes the errors go away. But it still doesn't work. Running this command: .\gradlew diff Gives me this output: > Task :diff liquibase-plugin: Running the 'main' activity... Starting Liquibase at Wed, 26 Sep 2018 16:47:19 CEST (version 3.6.2 built at 2018-07-03 11:28:09) Diff Results: Reference Database: null @ hibernate:spring:com.example.model?dialect=org.hibernate.dialect.Oracle10gDialect (Default Schema: HIBERNATE) Comparison Database: SYSTEM @ jdbc:oracle:thin:@localhost:1521:XE (Default Schema: SYSTEM) Compared Schemas: HIBERNATE -> SYSTEM Product Name: Reference: 'Hibernate' Target: 'Oracle' Product Version: Reference: '5.2.17.Final' Target: 'Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production' Missing Catalog(s): HIBERNATE Unexpected Catalog(s): NONE Changed Catalog(s): NONE Missing Column(s): NONE Unexpected Column(s): NONE Changed Column(s): NONE Missing Foreign Key(s): NONE Unexpected Foreign Key(s): NONE Changed Foreign Key(s): NONE Missing Index(s): NONE Unexpected Index(s): NONE Changed Index(s): NONE Missing Primary Key(s): NONE Unexpected Primary Key(s): NONE Changed Primary Key(s): NONE Missing Sequence(s): NONE Unexpected Sequence(s): NONE Changed Sequence(s): NONE Missing Stored Procedure(s): NONE Unexpected Stored Procedure(s): NONE Changed Stored Procedure(s): NONE Missing Table(s): NONE Unexpected Table(s): NONE Changed Table(s): NONE Missing Unique Constraint(s): NONE Unexpected Unique Constraint(s): NONE Changed Unique Constraint(s): NONE Missing View(s): NONE Unexpected View(s): NONE Changed View(s): NONE Liquibase command 'diff' was executed successfully. BUILD SUCCESSFUL in 7s 1 actionable task: 1 executed When running against an empty database.
Turns out I needed to add some undocumented magic sauce. diff.dependsOn compileJava diffChangeLog.dependsOn compileJava generateChangelog.dependsOn compileJava dependencies { // as before liquibaseRuntime sourceSets.main.output // replaces liquibaseRuntime files('src/main') }
Liquibase
52,517,215
10
I have a spring boot application and I want to add liquibase configuration change log for it. I have created a LiquibaseConfig class for configuring liquibase: @Configuration public class LiquibaseConfiguration { @Value("${com.foo.bar.liquibase.changelog}") private String changelog; @Autowired MysqlDataSource dataSource; @Bean public SpringLiquibase liquibase() { SpringLiquibase liquibase = new SpringLiquibase(); liquibase.setDataSource(dataSource); liquibase.setChangeLog(changelog); return liquibase; } } and I have configured the datasource information in properties file: spring.datasource.url=jdbc:mysql://localhost:3306/dms spring.datasource.username=root spring.datasource.password=test spring.datasource.testWhileIdle = true spring.jpa.show-sql = true #liquibase com.foo.bar.liquibase.changelog=classpath:/db/changelog/db.changelog.xml when I run my application I receive this error: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'liquibaseConfiguration': Unsatisfied dependency expressed through field 'dataSource': No qualifying bean of type [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] found for dependency [com.mysql.jdbc.jdbc2.optional.MysqlDataSource]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mysql.jdbc.jdbc2.optional.MysqlDataSource] found for dependency [com.mysql.jdbc.jdbc2.optional.MysqlDataSource]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} Now I understood that this means the application cannot autowire the MysqlDataSource dataSource; but I need to pass the data source to liquibase bean. How can I do that?
Here's a simple step to integrate liquibase in spring boot STEP 1 Add liquibase dependency Gradle runtime "org.liquibase:liquibase-core" Maven <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <scope>runtime</scope> </dependency> STEP 2 Add liquibase changelog file path in application.yml liquibase: enabled: true #this is optional as enabled by default change-log: classpath:/liquibase/db-changelog.xml Notice property liquibase.change-log. I'm referring path as /liquibase/db-changelog.xml. so you should have a file name db-changelog.xml inside src/main/resources/liquibase/ STEP 3 Add your changesets on the file and when Spring-Boot application is started (spring-boot:run) your changeset will be loaded. This will use default dataSource that your app uses. More Info: http://docs.spring.io/spring-boot/docs/1.4.3.RELEASE/reference/htmlsingle/#howto-execute-liquibase-database-migrations-on-startup Update For Spring Boot 2.0 as @veben pointed out in comment use spring: liquibase: change-log: #path
Liquibase
41,491,234
10
I have a Spring boot, spring data jpa project with a parent and three children modules. One of my modules is responsible for my JPA entities. I need generate one xml changelog with liquibase from this entities. In my liquibase.properties i have the code: changeLogFile=src/main/resources/db/changelog/db.changelog-master.xml url=jdbc:mysql://localhost:3306/test username=root password=root driver=com.mysql.jdbc.Driver outputChangeLogFile=src/main/resources/db/outputChangeLog/liquibase-outputChangeLog.xml referenceUrl=hibernate:spring:br.com.company.vacation.domain?dialect=org.hibernate.dialect.MySQLDialect diffChangeLogFile=src/main/resources/liquibase-diff-changeLog.xml So, if i try execute the command: liquibase:diff i receive the error: In my pom.xml i configured the liquibase just like this: <plugin> <groupId>org.liquibase</groupId> <artifactId>liquibase-maven-plugin</artifactId> <version>3.4.1</version> <configuration> <propertyFile>src/main/resources/liquibase.properties</propertyFile> </configuration> <dependencies> <dependency> <groupId>org.liquibase.ext</groupId> <artifactId>liquibase-hibernate4</artifactId> <version>3.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.1.7.RELEASE</version> </dependency> </dependencies> </plugin> If i execute the liquibase:generateChangeLog the liquibase generate the log from my existing database... But if i tried execute liquibase:diff i receive the error: [ERROR] Failed to execute goal org.liquibase:liquibase-maven-plugin:3.4.1:diff (default-cli) on project vacation-club-web: Execution default-cli of goal org.liquibase:liquibase-maven-plugin:3.4.1:diff failed: A required class was missing while executing org.liquibase:liquibase-maven-plugin:3.4.1:diff: org/springframework/orm/jpa/persistenceunit/DefaultPersistenceUnitManager [ERROR] ----------------------------------------------------- [ERROR] realm = plugin>org.liquibase:liquibase-maven-plugin:3.4.1 [ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy [ERROR] urls[0] = file:/C:/Users/lucas.araujo/.m2/repository/org/liquibase/liquibase-maven-plugin/3.4.1/liquibase-maven-plugin-3.4.1.jar [ERROR] urls[1] = file:/C:/Users/lucas.araujo/.m2/repository/org/liquibase/ext/liquibase-hibernate4/3.5/liquibase-hibernate4-3.5.jar [ERROR] urls[2] = file:/C:/Users/lucas.araujo/.m2/repository/org/hibernate/hibernate-core/4.3.1.Final/hibernate-core-4.3.1.Final.jar [ERROR] urls[3] = file:/C:/Users/lucas.araujo/.m2/repository/org/jboss/logging/jboss-logging/3.1.3.GA/jboss-logging-3.1.3.GA.jar [ERROR] urls[4] = file:/C:/Users/lucas.araujo/.m2/repository/org/jboss/logging/jboss-logging-annotations/1.2.0.Beta1/jboss-logging-annotations-1.2.0.Beta1.jar [ERROR] urls[5] = file:/C:/Users/lucas.araujo/.m2/repository/org/jboss/spec/javax/transaction/jboss-transaction-api_1.2_spec/1.0.0.Final/jboss-transaction-api_1.2_spec-1.0.0.Final.jar [ERROR] urls[6] = file:/C:/Users/lucas.araujo/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar [ERROR] urls[7] = file:/C:/Users/lucas.araujo/.m2/repository/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar [ERROR] urls[8] = file:/C:/Users/lucas.araujo/.m2/repository/org/hibernate/common/hibernate-commons-annotations/4.0.4.Final/hibernate-commons-annotations-4.0.4.Final.jar [ERROR] urls[9] = file:/C:/Users/lucas.araujo/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar [ERROR] urls[10] = file:/C:/Users/lucas.araujo/.m2/repository/org/javassist/javassist/3.18.1-GA/javassist-3.18.1-GA.jar [ERROR] urls[11] = file:/C:/Users/lucas.araujo/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7.jar [ERROR] urls[12] = file:/C:/Users/lucas.araujo/.m2/repository/org/jboss/jandex/1.1.0.Final/jandex-1.1.0.Final.jar [ERROR] urls[13] = file:/C:/Users/lucas.araujo/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.0-api/1.0.1.Final/hibernate-jpa-2.0-api-1.0.1.Final.jar [ERROR] urls[14] = file:/C:/Users/lucas.araujo/.m2/repository/org/hibernate/hibernate-entitymanager/4.3.1.Final/hibernate-entitymanager-4.3.1.Final.jar [ERROR] urls[15] = file:/C:/Users/lucas.araujo/.m2/repository/org/hibernate/hibernate-envers/4.3.1.Final/hibernate-envers-4.3.1.Final.jar [ERROR] urls[16] = file:/C:/Users/lucas.araujo/.m2/repository/org/springframework/spring-beans/4.1.7.RELEASE/spring-beans-4.1.7.RELEASE.jar [ERROR] urls[17] = file:/C:/Users/lucas.araujo/.m2/repository/org/springframework/spring-core/4.1.7.RELEASE/spring-core-4.1.7.RELEASE.jar [ERROR] urls[18] = file:/C:/Users/lucas.araujo/.m2/repository/commons-logging/commons-logging/1.2/commons-logging-1.2.jar [ERROR] urls[19] = file:/C:/Users/lucas.araujo/.m2/repository/org/codehaus/plexus/plexus-utils/1.0.4/plexus-utils-1.0.4.jar [ERROR] urls[20] = file:/C:/Users/lucas.araujo/.m2/repository/org/liquibase/liquibase-core/3.4.1/liquibase-core-3.4.1.jar [ERROR] Number of foreign imports: 1 [ERROR] import: Entry[import from realm ClassRealm[maven.api, parent: null]] [ERROR] [ERROR] -----------------------------------------------------: org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager Someone already had this problem?
i solved this problem. The solution is one dependency it's missing in my pom.xml file. Pom.xml <!-- Liquibase --> <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-maven-plugin</artifactId> <version>3.4.1</version> </dependency> <plugin> <groupId>org.liquibase</groupId> <artifactId>liquibase-maven-plugin</artifactId> <version>3.4.1</version> <configuration> <propertyFile>src/main/resources/liquibase.properties</propertyFile> </configuration> <dependencies> <dependency> <groupId>org.liquibase.ext</groupId> <artifactId>liquibase-hibernate4</artifactId> <version>3.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.7.3.RELEASE</version> </dependency> </dependencies> </plugin>
Liquibase
36,549,359
10
A Spring Boot Java application using Liquibase to manage the database schema changes is started with a parameter (e.g. dev, int) specifying the environment it runs in. There are corresponding properties files (e.g. dev.properties, int.properties) which define properties for the corresponding environment. So in dev.properties there is e.g. url.info=http://dev.app.info and in tst.properties there is url.info=http://tst.app.info The application reads in the properties from the file corresponding to the passed in parameter. This mechanism works fine when the application is deployed and started in each environment. There are many instances when the corresponding property is used. However, it doesn't work with a Liquibase yaml changeset containing the following insert statement - insert: tableName: result columns: - column: name: id value: a88b6708-5c9f-40c4-a3ca-41e7a6b57fc8 - column: name: infoUrl value: ${url.info} I have tried double and single quotes in the yaml file, i.e. "${url.info}" and '${url.info}' but the database always ends up with the String ${url.info} Is there another notation I have to use for properties in yaml files? or Can properties not be referenced in liquibase yaml files the way they can with xml files?
As you are using Spring Boot, you can use its application.properties file to define change log parameters. Any property with a name that begins with spring.liquibase.parameters. can be referenced in a changelog. For example, the property spring.liquibase.parameters.url.info can be referenced as ${url.info} in your changelog (YAML or XML). To use different configuration files for dev, QA, production etc you can use profiles and profile-specific configuration files. For example, the application-dev.properties file will only be loaded when the dev profile is active.
Liquibase
34,326,981
10
I configured Jenkins in Spinnaker as follows and setup the Spinnaker pipeline. jenkins: # If you are integrating Jenkins, set its location here using the baseUrl # field and provide the username/password credentials. # You must also enable the "igor" service listed separately. # # If you have multiple Jenkins servers, you will need to list # them in an igor-local.yml. See jenkins.masters in config/igor.yml. # # Note that Jenkins is not installed with Spinnaker so you must obtain this # on your own if you are interested. enabled: ${services.igor.enabled:false} defaultMaster: name: default baseUrl: http://server:8080 username: spinnaker password: password But I am seeing the following error when trying to run the Spinnaker pipeline. Exception ( Start Jenkins Job ) 403 No valid crumb was included in the request
Finally, this post helped me to do away with the crumb problem, but still securing Jenkins from a CSRF attack. Solution for no-valid crumb included in the request issue Basically, we need to first request for a crumb with authentication and then issue a POST API calls with a crumb as a header along with authentication again. This is how I did it, curl -v -X GET http://jenkins-url:8080/crumbIssuer/api/json --user <username>:<password> The response was, { "_class":"hudson.security.csrf.DefaultCrumbIssuer", "crumb":"0db38413bd7ec9e98974f5213f7ead8b", "crumbRequestField":"Jenkins-Crumb" } Then the POST API call with the above crumb information in it. curl -X POST http://jenkins-url:8080/job/<job-name>/build --user <username>:<password> -H 'Jenkins-Crumb: 0db38413bd7ec9e98974f5213f7ead8b'
Spinnaker
44,711,696
108
I've heard both used to describe the idea of deploying an update on new machines while keeping old machines active, ready to rollback if an issue occurs. I've also heard it used to describe sharing load between updated services and old service, again for the purpose of a rollbacks —sometimes terminating inactive older patches and sometimes not. My understanding also is that it is strictly for cloud services. Can someone help to demystify these terms?
Blue-green deployment Classic deployment technique described in the Continuous Delivery book by Jez Humble and David Farley: The idea is to have two identical versions of your production environment, which we’ll call blue and green... Users of the system are routed to the green environment, which is the currently designated production. We want to release a new version of the application. So we deploy it to the blue environment... This does not in any way affect the operation of the green environment. We can run smoke tests against the blue environment to check it is working properly. When we’re ready, moving to the new version is as simple as changing the router configuration to point to the blue environment instead of the green environment. The blue environment thus becomes production. This switchover can typically be performed in much less than a second. If something goes wrong, we simply switch the router back to the green environment.' Humble and Farley then go on to mention the main challenge: dealing with database schema changes between green and blue versions. The main benefit of blue-green deployment is zero or near-zero downtime when releasing a new version. And blue-green deployment enables canary releasing. Red-black deployment The Red version is live in production. You deploy the Black version to one or more servers. When the Black version is fully operational, you switch the router to direct all traffic to it (or you scale Red to 0 instances and Black to N). If anything goes wrong, you revert the operation. So, it's similar to blue-green deployment, but there's a slight difference: in blue-green deployment, both versions may be getting requests at the same time temporarily, while in red-black only one of the versions is getting traffic at any point in time. Here's some corroboration: At any time, only one of the environments is live, with the live environment serving all production traffic. For this example, Red is currently live and Black is idle (in this case we have kept the Black down-scaled to zero servers)... Therefore, red-black is a specialization of blue-green. But red-black deployment is a newer term being used by Netflix, Istio, and other frameworks/platforms that support container orchestration. The actual meaning can vary and many people are using "red-black" as another term for "blue-green", maybe just because their team colors are red and black. :^)
Spinnaker
45,259,589
90
I was following this documentation to setup Spinnaker on Kubernetes. I ran the scripts as they specified. Then the replication controllers and services are started. But some of PODs are not started root@nveeru~# kubectl get pods --namespace=spinnaker NAME READY STATUS RESTARTS AGE data-redis-master-v000-zsn7e 1/1 Running 0 2h spin-clouddriver-v000-6yr88 1/1 Running 0 47m spin-deck-v000-as4v7 1/1 Running 0 2h spin-echo-v000-g737r 1/1 Running 0 2h spin-front50-v000-v1g6e 0/1 CrashLoopBackOff 21 2h spin-gate-v000-9k401 0/1 Running 0 2h spin-igor-v000-zfc02 1/1 Running 0 2h spin-orca-v000-umxj1 0/1 CrashLoopBackOff 20 2h Then I kubectl describe the pods root@veeru:~# kubectl describe pod spin-orca-v000-umxj1 --namespace=spinnaker Name: spin-orca-v000-umxj1 Namespace: spinnaker Node: 172.25.30.21/172.25.30.21 Start Time: Mon, 19 Sep 2016 00:53:00 -0700 Labels: load-balancer-spin-orca=true,replication-controller=spin-orca-v000 Status: Running IP: 172.16.33.8 Controllers: ReplicationController/spin-orca-v000 Containers: orca: Container ID: docker://e6d77e9fd92dc9614328d09a5bfda319dc7883b82f50cc352ff58dec2e933d04 Image: quay.io/spinnaker/orca:latest Image ID: docker://sha256:2400633b89c1c7aa48e5195c040c669511238af9b55ff92201703895bd67a131 Port: 8083/TCP QoS Tier: cpu: BestEffort memory: BestEffort State: Waiting Reason: CrashLoopBackOff Last State: Terminated Reason: Error Exit Code: 1 Started: Mon, 19 Sep 2016 02:59:09 -0700 Finished: Mon, 19 Sep 2016 02:59:39 -0700 Ready: False Restart Count: 21 Readiness: http-get http://:8083/env delay=20s timeout=1s period=10s #success=1 #failure=3 Environment Variables: Conditions: Type Status Ready False Volumes: spinnaker-config: Type: Secret (a volume populated by a Secret) SecretName: spinnaker-config default-token-6irrl: Type: Secret (a volume populated by a Secret) SecretName: default-token-6irrl Events: FirstSeen LastSeen Count From SubobjectPath Type Reason Message --------- -------- ----- ---- ------------- -------- ------ ------- 1h 3m 22 {kubelet 172.25.30.21} spec.containers{orca} Normal Pulling pulling image "quay.io/spinnaker/orca:latest" 1h 3m 22 {kubelet 172.25.30.21} spec.containers{orca} Normal Pulled Successfully pulled image "quay.io/spinnaker/orca:latest" 1h 3m 13 {kubelet 172.25.30.21} spec.containers{orca} Normal Created (events with common reason combined) 1h 3m 13 {kubelet 172.25.30.21} spec.containers{orca} Normal Started (events with common reason combined) 1h 3m 23 {kubelet 172.25.30.21} spec.containers{orca} Warning Unhealthy Readiness probe failed: Get http://172.16.33.8:8083/env: dial tcp 172.16.33.8:8083: connection refused 1h <invalid> 399 {kubelet 172.25.30.21} spec.containers{orca} Warning BackOff Back-off restarting failed docker container 1h <invalid> 373 {kubelet 172.25.30.21} Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "orca" with CrashLoopBackOff: "Back-off 5m0s restarting failed container=orca pod=spin-orca-v000-umxj1_spinnaker(ee2511f0-7e3d-11e6-ab16-0022195df673)" spin-front50-v000-v1g6e root@veeru:~# kubectl describe pod spin-front50-v000-v1g6e --namespace=spinnaker Name: spin-front50-v000-v1g6e Namespace: spinnaker Node: 172.25.30.21/172.25.30.21 Start Time: Mon, 19 Sep 2016 00:53:00 -0700 Labels: load-balancer-spin-front50=true,replication-controller=spin-front50-v000 Status: Running IP: 172.16.33.9 Controllers: ReplicationController/spin-front50-v000 Containers: front50: Container ID: docker://f5559638e9ea4e30b3455ed9fea2ab1dd52be95f177b4b520a7e5bfbc033fc3b Image: quay.io/spinnaker/front50:latest Image ID: docker://sha256:e774808d76b096f45d85c43386c211a0a839c41c8d0dccb3b7ee62d17e977eb4 Port: 8080/TCP QoS Tier: memory: BestEffort cpu: BestEffort State: Waiting Reason: CrashLoopBackOff Last State: Terminated Reason: Error Exit Code: 1 Started: Mon, 19 Sep 2016 03:02:08 -0700 Finished: Mon, 19 Sep 2016 03:02:15 -0700 Ready: False Restart Count: 23 Readiness: http-get http://:8080/env delay=20s timeout=1s period=10s #success=1 #failure=3 Environment Variables: Conditions: Type Status Ready False Volumes: spinnaker-config: Type: Secret (a volume populated by a Secret) SecretName: spinnaker-config creds-config: Type: Secret (a volume populated by a Secret) SecretName: creds-config aws-config: Type: Secret (a volume populated by a Secret) SecretName: aws-config default-token-6irrl: Type: Secret (a volume populated by a Secret) SecretName: default-token-6irrl Events: FirstSeen LastSeen Count From SubobjectPath Type Reason Message --------- -------- ----- ---- ------------- -------- ------ ------- 1h 3m 24 {kubelet 172.25.30.21} spec.containers{front50} Normal Pulling pulling image "quay.io/spinnaker/front50:latest" 1h 3m 24 {kubelet 172.25.30.21} spec.containers{front50} Normal Pulled Successfully pulled image "quay.io/spinnaker/front50:latest" 1h 3m 15 {kubelet 172.25.30.21} spec.containers{front50} Normal Created (events with common reason combined) 1h 3m 15 {kubelet 172.25.30.21} spec.containers{front50} Normal Started (events with common reason combined) 1h <invalid> 443 {kubelet 172.25.30.21} spec.containers{front50} Warning BackOff Back-off restarting failed docker container 1h <invalid> 417 {kubelet 172.25.30.21} Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "front50" with CrashLoopBackOff: "Back-off 5m0s restarting failed container=front50 pod=spin-front50-v000-v1g6e_spinnaker(edf85f41-7e3d-11e6-ab16-0022195df673)" spin-gate-v000-9k401 root@n42-poweredge-5:~# kubectl describe pod spin-gate-v000-9k401 --namespace=spinnaker Name: spin-gate-v000-9k401 Namespace: spinnaker Node: 172.25.30.21/172.25.30.21 Start Time: Mon, 19 Sep 2016 00:53:00 -0700 Labels: load-balancer-spin-gate=true,replication-controller=spin-gate-v000 Status: Running IP: 172.16.33.6 Controllers: ReplicationController/spin-gate-v000 Containers: gate: Container ID: docker://7507c9d7c00e5834572cde2c0b0b54086288e9e30d3af161f0a1dbdf44672332 Image: quay.io/spinnaker/gate:latest Image ID: docker://sha256:074d9616a43de8690c0a6a00345e422c903344f6876d9886f7357505082d06c7 Port: 8084/TCP QoS Tier: memory: BestEffort cpu: BestEffort State: Running Started: Mon, 19 Sep 2016 01:14:54 -0700 Ready: False Restart Count: 0 Readiness: http-get http://:8084/env delay=20s timeout=1s period=10s #success=1 #failure=3 Environment Variables: Conditions: Type Status Ready False Volumes: spinnaker-config: Type: Secret (a volume populated by a Secret) SecretName: spinnaker-config default-token-6irrl: Type: Secret (a volume populated by a Secret) SecretName: default-token-6irrl Events: FirstSeen LastSeen Count From SubobjectPath Type Reason Message --------- -------- ----- ---- ------------- -------- ------ ------- 1h <invalid> 696 {kubelet 172.25.30.21} spec.containers{gate} Warning Unhealthy Readiness probe failed: Get http://172.16.33.6:8084/env: dial tcp 172.16.33.6:8084: connection refused what's wrong here? UPDATE1 Logs (Please check the logs here) 2016-09-20 06:49:45.062 ERROR 1 --- [ main] o.s.boot.SpringApplication : Application startup failed org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:133) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:690) at org.springframework.boot.SpringApplication.run(SpringApplication.java:322) at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:134) at org.springframework.boot.builder.SpringApplicationBuilder$run$0.call(Unknown Source) at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116) at com.netflix.spinnaker.front50.Main.main(Main.groovy:47) Caused by: org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.initialize(TomcatEmbeddedServletContainer.java:99) at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.<init>(TomcatEmbeddedServletContainer.java:76) at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getTomcatEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:384) at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory.getEmbeddedServletContainer(TomcatEmbeddedServletContainerFactory.java:156) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:159) at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:130) ... 10 common frames omitted Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration'........ .......... UPDATE-1(02-06-2017) I tried above setup again in latest version of K8 Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T18:44:27Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"} Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T18:33:17Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"} Still not all PODs are up ubuntu@ip-172-31-18-78:~/spinnaker/experimental/kubernetes/simple$ kubectl get pods --namespace=spinnaker NAME READY STATUS RESTARTS AGE data-redis-master-v000-rzmzq 1/1 Running 0 31m spin-clouddriver-v000-qhz97 1/1 Running 0 31m spin-deck-v000-0sz8q 1/1 Running 0 31m spin-echo-v000-q9xv5 1/1 Running 0 31m spin-front50-v000-646vg 0/1 CrashLoopBackOff 10 31m spin-gate-v000-vfvhg 0/1 Running 0 31m spin-igor-v000-8j4r0 1/1 Running 0 31m spin-orca-v000-ndpcx 0/1 CrashLoopBackOff 9 31m Here is the logs links Front50 https://pastebin.com/ge5TR4eR Orca https://pastebin.com/wStmBtst Gate https://pastebin.com/T8vjqL2K Deck https://pastebin.com/kZnzN62W Clouddriver https://pastebin.com/1pEU6V5D Echo https://pastebin.com/cvJ4dVta Igor https://pastebin.com/QYkHBxkr Did I miss any configuration? I have not touched yaml config(Updated Jenkins URL,uname, passwd), that's I'm getting errors?. I'm new to Spinnaker. I had little knowledge on normal Spinnaker installation. Please guide me the installation. Thanks
use halyard to install spinnaker. it is the recommended approach for deploying spinnaker in kubernetes clsuter
Spinnaker
39,570,765
20
K8 Version: Client Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T18:44:27Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"} Server Version: version.Info{Major:"1", Minor:"6", GitVersion:"v1.6.4", GitCommit:"d6f433224538d4f9ca2f7ae19b252e6fcb66a3ae", GitTreeState:"clean", BuildDate:"2017-05-19T18:33:17Z", GoVersion:"go1.7.5", Compiler:"gc", Platform:"linux/amd64"} I tried to launch spinnaker pods(yaml files here). I choose Flannel(kubectl apply -f kube-flannel.yml) while installing K8. Then I see the pods are not starting, it is struck in "ContainerCreating" status. I kubectl describe a pod, showing NetworkPlugin cni failed to set up pod veeru@ubuntu:/opt/spinnaker/experimental/kubernetes/simple$ kubectl describe pod data-redis-master-v000-38j80 --namespace=spinnaker Name: data-redis-master-v000-38j80 Namespace: spinnaker Node: ubuntu/192.168.6.136 Start Time: Thu, 01 Jun 2017 02:54:14 -0700 Labels: load-balancer-data-redis-server=true replication-controller=data-redis-master-v000 Annotations: kubernetes.io/created-by={"kind":"SerializedReference","apiVersion":"v1","reference":{"kind":"ReplicaSet","namespace":"spinnaker","name":"data-redis-master-v000","uid":"43d4a44c-46b0-11e7-b0e1-000c29b... Status: Pending IP: Controllers: ReplicaSet/data-redis-master-v000 Containers: redis-master: Container ID: Image: gcr.io/kubernetes-spinnaker/redis-cluster:v2 Image ID: Port: 6379/TCP State: Waiting Reason: ContainerCreating Ready: False Restart Count: 0 Limits: cpu: 100m Requests: cpu: 100m Environment: MASTER: true Mounts: /redis-master-data from data (rw) /var/run/secrets/kubernetes.io/serviceaccount from default-token-71p4q (ro) Conditions: Type Status Initialized True Ready False PodScheduled True Volumes: data: Type: EmptyDir (a temporary directory that shares a pod's lifetime) Medium: default-token-71p4q: Type: Secret (a volume populated by a Secret) SecretName: default-token-71p4q Optional: false QoS Class: Burstable Node-Selectors: <none> Tolerations: node.alpha.kubernetes.io/notReady=:Exists:NoExecute for 300s node.alpha.kubernetes.io/unreachable=:Exists:NoExecute for 300s Events: FirstSeen LastSeen Count From SubObjectPath Type Reason Message --------- -------- ----- ---- ------------- -------- ------ ------- 45m 45m 1 default-scheduler Normal Scheduled Successfully assigned data-redis-master-v000-38j80 to ubuntu 43m 43m 1 kubelet, ubuntu Warning FailedSync Error syncing pod, skipping: failed to "KillPodSandbox" for "447d302c-46b0-11e7-b0e1-000c29b1270f" with KillPodSandboxError: "rpc error: code = 2 desc = NetworkPlugin cni failed to teardown pod \"_\" network: CNI failed to retrieve network namespace path: Error: No such container: 8265d80732e7b73ebf8f1493d40403021064b61436c4c559b41330e7592fd47f" 43m 43m 1 kubelet, ubuntu Warning FailedSync Error syncing pod, skipping: rpc error: code = 2 desc = Error: No such container: b972862d763e621e026728073deb9a304748c4ec4522982db0a168663ab59d36 42m 42m 1 kubelet, ubuntu Warning FailedSync Error syncing pod, skipping: failed to "KillPodSandbox" for "447d302c-46b0-11e7-b0e1-000c29b1270f" with KillPodSandboxError: "rpc error: code = 2 desc = NetworkPlugin cni failed to teardown pod \"_\" network: CNI failed to retrieve network namespace path: Error: No such container: 72b39083a3a81c0da1d4b7fa65b5d6450b62a3562a05452c27b185bc33197327" 41m 41m 1 kubelet, ubuntu Warning FailedSync Error syncing pod, skipping: failed to "KillPodSandbox" for "447d302c-46b0-11e7-b0e1-000c29b1270f" with KillPodSandboxError: "rpc error: code = 2 desc = NetworkPlugin cni failed to teardown pod \"_\" network: CNI failed to retrieve network namespace path: Error: No such container: d315511bfa9f6f09d7ef4cd277bde44e4885291ea566e3089460356c1ed34413" 40m 40m 1 kubelet, ubuntu Warning FailedSync Error syncing pod, skipping: failed to "KillPodSandbox" for "447d302c-46b0-11e7-b0e1-000c29b1270f" with KillPodSandboxError: "rpc error: code = 2 desc = NetworkPlugin cni failed to teardown pod \"_\" network: CNI failed to retrieve network namespace path: Error: No such container: a03d776d2d7c5c4ae9c1ec31681b0b6e40759326a452916cff0e60c4d4e2c954" 40m 40m 1 kubelet, ubuntu Warning FailedSync Error syncing pod, skipping: failed to "KillPodSandbox" for "447d302c-46b0-11e7-b0e1-000c29b1270f" with KillPodSandboxError: "rpc error: code = 2 desc = NetworkPlugin cni failed to teardown pod \"_\" network: CNI failed to retrieve network namespace path: Error: No such container: acf30a4aacda0c53bdbb8bc2d416704720bd1b623c43874052b4029f15950052" 39m 39m 1 kubelet, ubuntu Warning FailedSync Error syncing pod, skipping: failed to "KillPodSandbox" for "447d302c-46b0-11e7-b0e1-000c29b1270f" with KillPodSandboxError: "rpc error: code = 2 desc = NetworkPlugin cni failed to teardown pod \"_\" network: CNI failed to retrieve network namespace path: Error: No such container: ea49f5f9428d585be7138f4ebce54f713eef549b16104a3d7aa728175b6ebc2a" 38m 38m 1 kubelet, ubuntu Warning FailedSync Error syncing pod, skipping: failed to "KillPodSandbox" for "447d302c-46b0-11e7-b0e1-000c29b1270f" with KillPodSandboxError: "rpc error: code = 2 desc = NetworkPlugin cni failed to teardown pod \"_\" network: CNI failed to retrieve network namespace path: Error: No such container: ec2483435b4b22576c9bd7bffac5d67d53893c189c0cf26aca1ae6af79d09914" 38m 1m 39 kubelet, ubuntu Warning FailedSync (events with common reason combined) 45m 1s 448 kubelet, ubuntu Normal SandboxChanged Pod sandbox changed, it will be killed and re-created. 45m 0s 412 kubelet, ubuntu Warning FailedSync Error syncing pod, skipping: failed to "CreatePodSandbox" for "data-redis-master-v000-38j80_spinnaker(447d302c-46b0-11e7-b0e1-000c29b1270f)" with CreatePodSandboxError: "CreatePodSandbox for pod \"data-redis-master-v000-38j80_spinnaker(447d302c-46b0-11e7-b0e1-000c29b1270f)\" failed: rpc error: code = 2 desc = NetworkPlugin cni failed to set up pod \"data-redis-master-v000-38j80_spinnaker\" network: open /run/flannel/subnet.env: no such file or directory" How can I resolve above issue? UPDATE-1 I have reinitialized K8 with kubeadm init --pod-network-cidr=10.244.0.0/16 and deployed sample nginx pod. Still getting same error -----------------OUTPUT REMOVED------------------------------- Events: FirstSeen LastSeen Count From SubObjectPath Type Reason Message --------- -------- ----- ---- ------------- -------- ------ ------- 3m 3m 1 default-scheduler Normal Scheduled Successfully assigned nginx-622qj to ubuntu 1m 1m 1 kubelet, ubuntu Warning FailedSync Error syncing pod, skipping: failed to "KillPodSandbox" for "0728fece-46fe-11e7-ae5d-000c29b1270f" with KillPodSandboxError: "rpc error: code = 2 desc = NetworkPlugin cni failed to teardown pod \"_\" network: CNI failed to retrieve network namespace path: Error: No such container: 38250afd765f0108aeff6e31bbe5a642a60db99b97cbbf15711f810cbe8f3829" 24s 24s 1 kubelet, ubuntu Warning FailedSync Error syncing pod, skipping: failed to "KillPodSandbox" for "0728fece-46fe-11e7-ae5d-000c29b1270f" with KillPodSandboxError: "rpc error: code = 2 desc = NetworkPlugin cni failed to teardown pod \"_\" network: CNI failed to retrieve network namespace path: Error: No such container: 3bebcef02cb5f6645a65dcf06b2730144080f9d3c4fb18267feca5c5ce21031c" 2m 9s 33 kubelet, ubuntu Normal SandboxChanged Pod sandbox changed, it will be killed and re-created. 3m 7s 32 kubelet, ubuntu Warning FailedSync Error syncing pod, skipping: failed to "CreatePodSandbox" for "nginx-622qj_default(0728fece-46fe-11e7-ae5d-000c29b1270f)" with CreatePodSandboxError: "CreatePodSandbox for pod \"nginx-622qj_default(0728fece-46fe-11e7-ae5d-000c29b1270f)\" failed: rpc error: code = 2 desc = NetworkPlugin cni failed to set up pod \"nginx-622qj_default\" network: open /run/flannel/subnet.env: no such file or directory"
Running the following command resolved my issues: kubeadm init --pod-network-cidr=10.244.0.0/16 For flannel as cni the api server needs to have the argument --pod-network-cidr=... to be set to the overlay.
Spinnaker
44,305,615
16
I would like to know what each strategy means and how they work behind the scenes (i.e., Highlander, Red/Black, Rolling Push). It would be very useful to have this information on the official website. Thanks
There is useful information out there that can help you with your question, I'll do my best to summarize it below. Type and Strategies of Deployments Introduction "There are a variety of techniques to deploy new applications to production, so choosing the right strategy is an important decision, weighing the options in terms of the impact of change on the system, and on the endusers." Recreate: (also known as Highlander) Version A is terminated then version B is rolled out. Ramped (also known as Rolling-Update or Incremental): Version B is slowly rolled out and replacing version A. Blue/Green (also known as Red/Black): Version B is released alongside version A, then the traffic is switched to version B. Canary: Version B is released to a subset of users, then proceed to a full rollout. A/B Testing: Version B is released to a subset of users under specific condition. Shadow: Version B receives real-world traffic alongside version A and doesn’t impact the response. Type and Strategies of Deployments Summary Table Ref link 1: https://thenewstack.io/deployment-strategies/ Spinnaker Deployment Strategies Spinnaker treats cloud-native deployment strategies as first class constructs, handling the underlying orchestration such as verifying health checks, disabling old server groups and enabling new server groups. Spinnaker supported deployment strategies (in active development): Highlander Red/Black (a.k.a. Blue/Green) Rolling Red/Black Canary Illustrated in the Figure below as follows: Highlander: This deployment strategy is aptly named after the film Highlander because of the famous line, "there can be only one." With this strategy, there is a load balancer fronting a single cluster. Highlander destroys the previous cluster after the deployment is completed. This is the simplest strategy, and it works well when rollback speed is unimportant or infrastructure costs need to be kept down. Red/Black: This deployment strategy is also referred to as Blue/Green. The Red/Black strategy uses a load balancer and two target clusters / server groups (known as red/black or blue/green). The load balancer routes traffic to the active (enabled) cluster / server group. Then, a new deployment replaces servers (w/ K8s provider -> Replica Sets & Pods) in the disabled cluster / server group. When the newly enabled cluster / server group is ready, the load balancer routes traffic to this cluster and the previous cluster becomes disabled. The currently disabled cluster / server group (previously enabled cluster / server groups) is kept around by spinnaker in case a rollback is needed for the next X deployments (which is a configurable parameter). Rolling Red/Black: is a slower red/black with more possible verification points. The process is the same as red/black, but difference is in how traffic switches over. The above image illustrates this difference. Blue is the enabled cluster. Blue instances are gradually replaced by new instances in the green cluster until all enabled instances are running the newest version. The rollout may occur in 20% increments, so it can be 80/20, 60/40, 40/60, 20/80, or 100%. Both blue/green clusters receive traffic until the rollout is complete. Canary: deployments is a process in which a change is partially deployed, then tested against baseline metrics before continuing. This process reduces the risk that a change will cause problems when it has been completely rolled out by limiting your blast radius to a small percentage of your user-base. The baseline metrics are set when configuring the canary. Metrics may be error count or latency. Higher-than-baseline error counts or latency spikes kill the canary, and thus stop the pipeline. Ref link 2: https://www.spinnaker.io/concepts/#deployment-strategies Ref link 3: https://blog.armory.io/advanced-deployment-strategies-with-armory-spinnaker/ Ref link 4: https://www.weave.works/blog/kubernetes-deployment-strategies
Spinnaker
36,072,412
12
I have a values.yaml file in which I have given spring_datasource_hikari_maximum_pool_size: "10" In deployment yaml I have used this value as - name: SPRING_DATASOURCE_HIKARI_MAXIMUM-POOL-SIZE value: {{ .Values.spring_datasource_hikari_maximum_pool_size }} However, when used inside the deployment.yaml file it fails with the below error. Deploy failed: The request is invalid: patch: Invalid value: "map[metadata:map[annotations:map[kubectl.kubernetes.io/last-applied-configuration:{"apiVersion":"apps/v1","kind":"Deployment","metadata":{"annotations": { (helm values etc) `{"name":"SPRING_DATASOURCE_HIKARI_MAXIMUM-POOL-SIZE","value":10}]` **(this is the incorrect value)** } cannot convert int64 to string What is the correct format of using an integer value from values.yaml file in a deployment.yaml file? I have also tried multiple combinations with quotes "" but nothing seems to be working. Any help is appreciated, Thanks in advance.
I was able to resolve this by using double quotes on the value itself in deployment.yaml file - name: SPRING_DATASOURCE_HIKARI_MAXIMUM-POOL-SIZE value: "{{ .Values.spring_datasource_hikari_maximum_pool_size }}" Since this was a production instance I could not check with @David Maze and Vit's solution. Edit: Tried with quote option and it worked too. - name: SPRING_DATASOURCE_HIKARI_MAXIMUMPOOLSIZE value: {{ quote .Values.spring_datasource_hikari_maximum_pool_size }}
Spinnaker
68,013,476
11
I've heard these words related to concurrent programming, but what's the difference between lock, mutex and semaphore?
A lock allows only one thread to enter the part that's locked and the lock is not shared with any other processes. A mutex is the same as a lock but it can be system wide (shared by multiple processes). A semaphore does the same as a mutex but allows x number of threads to enter, this can be used for example to limit the number of cpu, io or ram intensive tasks running at the same time. For a more detailed post about the differences between mutex and semaphore read here. You also have read/write locks that allows either unlimited number of readers or 1 writer at any given time. The descriptions are from a .NET perspective and might not be 100% accurate for all OS/Languages.
Semaphore
2,332,765
666
What are the major differences between a Monitor and a Semaphore?
A Monitor is an object designed to be accessed from multiple threads. The member functions or methods of a monitor object will enforce mutual exclusion, so only one thread may be performing any action on the object at a given time. If one thread is currently executing a member function of the object then any other thread that tries to call a member function of that object will have to wait until the first has finished. A Semaphore is a lower-level object. You might well use a semaphore to implement a monitor. A semaphore essentially is just a counter. When the counter is positive, if a thread tries to acquire the semaphore then it is allowed, and the counter is decremented. When a thread is done then it releases the semaphore, and increments the counter. If the counter is already zero when a thread tries to acquire the semaphore then it has to wait until another thread releases the semaphore. If multiple threads are waiting when a thread releases a semaphore then one of them gets it. The thread that releases a semaphore need not be the same thread that acquired it. A monitor is like a public toilet. Only one person can enter at a time. They lock the door to prevent anyone else coming in, do their stuff, and then unlock it when they leave. A semaphore is like a bike hire place. They have a certain number of bikes. If you try and hire a bike and they have one free then you can take it, otherwise you must wait. When someone returns their bike then someone else can take it. If you have a bike then you can give it to someone else to return --- the bike hire place doesn't care who returns it, as long as they get their bike back.
Semaphore
7,335,950
278
When to use a semaphore and when to use a conditional variable?
Locks are used for mutual exclusion. When you want to ensure that a piece of code is atomic, put a lock around it. You could theoretically use a binary semaphore to do this, but that's a special case. Semaphores and condition variables build on top of the mutual exclusion provide by locks and are used for providing synchronized access to shared resources. They can be used for similar purposes. A condition variable is generally used to avoid busy waiting (looping repeatedly while checking a condition) while waiting for a resource to become available. For instance, if you have a thread (or multiple threads) that can't continue onward until a queue is empty, the busy waiting approach would be to just doing something like: //pseudocode while(!queue.empty()) { sleep(1); } The problem with this is that you're wasting processor time by having this thread repeatedly check the condition. Why not instead have a synchronization variable that can be signaled to tell the thread that the resource is available? //pseudocode syncVar.lock.acquire(); while(!queue.empty()) { syncVar.wait(); } //do stuff with queue syncVar.lock.release(); Presumably, you'll have a thread somewhere else that is pulling things out of the queue. When the queue is empty, it can call syncVar.signal() to wake up a random thread that is sitting asleep on syncVar.wait() (or there's usually also a signalAll() or broadcast() method to wake up all the threads that are waiting). I generally use synchronization variables like this when I have one or more threads waiting on a single particular condition (e.g. for the queue to be empty). Semaphores can be used similarly, but I think they're better used when you have a shared resource that can be available and unavailable based on some integer number of available things. Semaphores are good for producer/consumer situations where producers are allocating resources and consumers are consuming them. Think about if you had a soda vending machine. There's only one soda machine and it's a shared resource. You have one thread that's a vendor (producer) who is responsible for keeping the machine stocked and N threads that are buyers (consumers) who want to get sodas out of the machine. The number of sodas in the machine is the integer value that will drive our semaphore. Every buyer (consumer) thread that comes to the soda machine calls the semaphore down() method to take a soda. This will grab a soda from the machine and decrement the count of available sodas by 1. If there are sodas available, the code will just keep running past the down() statement without a problem. If no sodas are available, the thread will sleep here waiting to be notified of when soda is made available again (when there are more sodas in the machine). The vendor (producer) thread would essentially be waiting for the soda machine to be empty. The vendor gets notified when the last soda is taken from the machine (and one or more consumers are potentially waiting to get sodas out). The vendor would restock the soda machine with the semaphore up() method, the available number of sodas would be incremented each time and thereby the waiting consumer threads would get notified that more soda is available. The wait() and signal() methods of a synchronization variable tend to be hidden within the down() and up() operations of the semaphore. Certainly there's overlap between the two choices. There are many scenarios where a semaphore or a condition variable (or set of condition variables) could both serve your purposes. Both semaphores and condition variables are associated with a lock object that they use to maintain mutual exclusion, but then they provide extra functionality on top of the lock for synchronizing thread execution. It's mostly up to you to figure out which one makes the most sense for your situation. That's not necessarily the most technical description, but that's how it makes sense in my head.
Semaphore
3,513,045
160
Here is the code I have but I don't understand what SemaphoreSlim is doing. async Task WorkerMainAsync() { SemaphoreSlim ss = new SemaphoreSlim(10); List<Task> trackedTasks = new List<Task>(); while (DoMore()) { await ss.WaitAsync(); trackedTasks.Add(Task.Run(() => { DoPollingThenWorkAsync(); ss.Release(); })); } await Task.WhenAll(trackedTasks); } void DoPollingThenWorkAsync() { var msg = Poll(); if (msg != null) { Thread.Sleep(2000); // process the long running CPU-bound job } } What do await ss.WaitAsync(); and ss.Release(); do? I guess that if I run 50 threads at a time then write code like SemaphoreSlim ss = new SemaphoreSlim(10); then it will be forced to run 10 active thread at time. When one of 10 threads completes then another thread will start. If I am not right then help me to understand with sample situation. Why is await needed along with ss.WaitAsync();? What does ss.WaitAsync(); do?
In the kindergarden around the corner they use a SemaphoreSlim to control how many kids can play in the PE room. They painted on the floor, outside of the room, 5 pairs of footprints. As the kids arrive, they leave their shoes on a free pair of footprints and enter the room. Once they are done playing they come out, collect their shoes and "release" a slot for another kid. If a kid arrives and there are no footprints left, they go play elsewhere or just stay around for a while and check every now and then (i.e., no FIFO priorities). When a teacher is around, she "releases" an extra row of 5 footprints on the other side of the corridor such that 5 more kids can play in the room at the same time. It also has the same "pitfalls" of SemaphoreSlim... If a kid finishes playing and leaves the room without collecting the shoes (does not trigger the "release") then the slot remains blocked, even though there is theoretically an empty slot. The kid usually gets told off, though. Sometimes one or two sneaky kid hide their shoes elsewhere and enter the room, even if all footprints are already taken (i.e., the SemaphoreSlim does not "really" control how many kids are in the room). This does not usually end well, since the overcrowding of the room tends to end in kids crying and the teacher fully closing the room.
Semaphore
20,056,727
159
Their public interfaces appear similar. The documentation states that the SemaphoreSlim is a lightweight alternative and doesn't use Windows Kernel semaphores. This resource states that the SemaphoreSlim is much faster. In what situations does the SemaphoreSlim make more sense over the Semaphore and vice versa?
One difference is that SemaphoreSlim does not permit named semaphores, which can be system-wide. This would mean that a SemaphoreSlim could not be used for cross-process synchronization. The MSDN documentation also indicates that SemSlim should be used when "wait times are expected to be very short". That would usually dovetail nicely with the idea that the slim version is more lightweight for most of the trade offs.
Semaphore
4,154,480
143
Is there a Mutex object in java or a way to create one? I am asking because a Semaphore object initialized with 1 permit does not help me. Think of this case: try { semaphore.acquire(); //do stuff semaphore.release(); } catch (Exception e) { semaphore.release(); } if an exception happens at the first acquire, the release in the catch block will increase the permits, and the semaphore is no longer a binary semaphore. Will the correct way be? try { semaphore.acquire(); //do stuff } catch (Exception e) { //exception stuff } finally { semaphore.release(); } Will the above code ensure that the semaphore will be binary?
Any object in Java can be used as a lock using a synchronized block. This will also automatically take care of releasing the lock when an exception occurs. Object someObject = ...; synchronized (someObject) { ... } You can read more about this here: Intrinsic Locks and Synchronization
Semaphore
5,291,041
134
What is mutex and semaphore in Java ? What is the main difference ?
Unfortunately everyone has missed the most important difference between the semaphore and the mutex; the concept of "ownership". Semaphores have no notion of ownership, this means that any thread can release a semaphore (this can lead to many problems in itself but can help with "death detection"). Whereas a mutex does have the concept of ownership (i.e. you can only release a mutex you have acquired). Ownership is incredibly important for safe programming of concurrent systems. I would always recommend using mutex in preference to a semaphore (but there are performance implications). Mutexes also may support priority inheritance (which can help with the priority inversion problem) and recursion (eliminating one type of deadlock). It should also be pointed out that there are "binary" semaphores and "counting/general" semaphores. Java's semaphore is a counting semaphore and thus allows it to be initialized with a value greater than one (whereas, as pointed out, a mutex can only a conceptual count of one). The usefulness of this has been pointed out in other posts. So to summarize, unless you have multiple resources to manage, I would always recommend the mutex over the semaphore.
Semaphore
771,347
119
Is there any advantage of using java.util.concurrent.CountdownLatch instead of java.util.concurrent.Semaphore? As far as I can tell the following fragments are almost equivalent: 1. Semaphore final Semaphore sem = new Semaphore(0); for (int i = 0; i < num_threads; ++ i) { Thread t = new Thread() { public void run() { try { doStuff(); } finally { sem.release(); } } }; t.start(); } sem.acquire(num_threads); 2: CountDownLatch final CountDownLatch latch = new CountDownLatch(num_threads); for (int i = 0; i < num_threads; ++ i) { Thread t = new Thread() { public void run() { try { doStuff(); } finally { latch.countDown(); } } }; t.start(); } latch.await(); Except that in case #2 the latch cannot be reused and more importantly you need to know in advance how many threads will be created (or wait until they are all started before creating the latch.) So in what situation might the latch be preferable?
CountDownLatch is frequently used for the exact opposite of your example. Generally, you would have many threads blocking on await() that would all start simultaneously when the countown reached zero. final CountDownLatch countdown = new CountDownLatch(1); for (int i = 0; i < 10; ++ i) { Thread racecar = new Thread() { public void run() { countdown.await(); //all threads waiting System.out.println("Vroom!"); } }; racecar.start(); } System.out.println("Go"); countdown.countDown(); //all threads start now! You could also use this as an MPI-style "barrier" that causes all threads to wait for other threads to catch up to a certain point before proceeding. final CountDownLatch countdown = new CountDownLatch(num_thread); for (int i = 0; i < num_thread; ++ i) { Thread t= new Thread() { public void run() { doSomething(); countdown.countDown(); System.out.printf("Waiting on %d other threads.",countdown.getCount()); countdown.await(); //waits until everyone reaches this point finish(); } }; t.start(); } That all said, the CountDownLatch can safely be used in the manner you've shown in your example.
Semaphore
184,147
114
I would like to run a bunch of async tasks, with a limit on how many tasks may be pending completion at any given time. Say you have 1000 URLs, and you only want to have 50 requests open at a time; but as soon as one request completes, you open up a connection to the next URL in the list. That way, there are always exactly 50 connections open at a time, until the URL list is exhausted. I also want to utilize a given number of threads if possible. I came up with an extension method, ThrottleTasksAsync that does what I want. Is there a simpler solution already out there? I would assume that this is a common scenario. Usage: class Program { static void Main(string[] args) { Enumerable.Range(1, 10).ThrottleTasksAsync(5, 2, async i => { Console.WriteLine(i); return i; }).Wait(); Console.WriteLine("Press a key to exit..."); Console.ReadKey(true); } } Here is the code: static class IEnumerableExtensions { public static async Task<Result_T[]> ThrottleTasksAsync<Enumerable_T, Result_T>(this IEnumerable<Enumerable_T> enumerable, int maxConcurrentTasks, int maxDegreeOfParallelism, Func<Enumerable_T, Task<Result_T>> taskToRun) { var blockingQueue = new BlockingCollection<Enumerable_T>(new ConcurrentBag<Enumerable_T>()); var semaphore = new SemaphoreSlim(maxConcurrentTasks); // Run the throttler on a separate thread. var t = Task.Run(() => { foreach (var item in enumerable) { // Wait for the semaphore semaphore.Wait(); blockingQueue.Add(item); } blockingQueue.CompleteAdding(); }); var taskList = new List<Task<Result_T>>(); Parallel.ForEach(IterateUntilTrue(() => blockingQueue.IsCompleted), new ParallelOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism }, _ => { Enumerable_T item; if (blockingQueue.TryTake(out item, 100)) { taskList.Add( // Run the task taskToRun(item) .ContinueWith(tsk => { // For effect Thread.Sleep(2000); // Release the semaphore semaphore.Release(); return tsk.Result; } ) ); } }); // Await all the tasks. return await Task.WhenAll(taskList); } static IEnumerable<bool> IterateUntilTrue(Func<bool> condition) { while (!condition()) yield return true; } } The method utilizes BlockingCollection and SemaphoreSlim to make it work. The throttler is run on one thread, and all the async tasks are run on the other thread. To achieve parallelism, I added a maxDegreeOfParallelism parameter that's passed to a Parallel.ForEach loop re-purposed as a while loop. The old version was: foreach (var master = ...) { var details = ...; Parallel.ForEach(details, detail => { // Process each detail record here }, new ParallelOptions { MaxDegreeOfParallelism = 15 }); // Perform the final batch updates here } But, the thread pool gets exhausted fast, and you can't do async/await. Bonus: To get around the problem in BlockingCollection where an exception is thrown in Take() when CompleteAdding() is called, I'm using the TryTake overload with a timeout. If I didn't use the timeout in TryTake, it would defeat the purpose of using a BlockingCollection since TryTake won't block. Is there a better way? Ideally, there would be a TakeAsync method.
As suggested, use TPL Dataflow. A TransformBlock<TInput, TOutput> may be what you're looking for. You define a MaxDegreeOfParallelism to limit how many strings can be transformed (i.e., how many urls can be downloaded) in parallel. You then post urls to the block, and when you're done you tell the block you're done adding items and you fetch the responses. var downloader = new TransformBlock<string, HttpResponse>( url => Download(url), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 50 } ); var buffer = new BufferBlock<HttpResponse>(); downloader.LinkTo(buffer); foreach(var url in urls) downloader.Post(url); //or await downloader.SendAsync(url); downloader.Complete(); await downloader.Completion; IList<HttpResponse> responses; if (buffer.TryReceiveAll(out responses)) { //process responses } Note: The TransformBlock buffers both its input and output. Why, then, do we need to link it to a BufferBlock? Because the TransformBlock won't complete until all items (HttpResponse) have been consumed, and await downloader.Completion would hang. Instead, we let the downloader forward all its output to a dedicated buffer block - then we wait for the downloader to complete, and inspect the buffer block.
Semaphore
22,492,383
69
I am working on some code which uses the pthread and semaphore libraries. The sem_init function works fine on my Ubuntu machine, but on OS X the sem_init function has absolutely no effect. Is there something wrong with the library or is there a different way of doing it? This is the code I am using to test. sem_t sem1; sem_t sem2; sem_t sem3; sem_t sem4; sem_t sem5; sem_t sem6; sem_init(&sem1, 1, 1); sem_init(&sem2, 1, 2); sem_init(&sem3, 1, 3); sem_init(&sem4, 1, 4); sem_init(&sem5, 1, 5); sem_init(&sem6, 1, 6); The values appear to be random numbers, and they do not change after the sem_init call.
Unnamed semaphores are not supported, you need to use named semaphores. To use named semaphores instead of unnamed semaphores, use sem_open instead of sem_init, and use sem_close and sem_unlink instead of sem_destroy.
Semaphore
1,413,785
66
I read that mutex is a semaphore with value 1 (binary semaphore) used to enforce mutual exclusion. I read this link Semaphore vs. Monitors - what's the difference? which says that monitor helps in achieving mutual exclusion. Can someone tell me the difference between mutex and monitor as both help achieve the same thing (Mutual Exclusion)?
Since you haven't specified which OS or language/library you are talking about, let me answer in a generic way. Conceptually they are the same. But usually they are implemented slightly differently Monitor Usually, the implementation of monitors is faster/light-weight, since it is designed for multi-threaded synchronization within the same process. Also, usually, it is provided by a framework/library itself (as opposed to requesting the OS). Mutex Usually, mutexes are provided by the OS kernel and libraries/frameworks simply provide an interface to invoke it. This makes them heavy-weight/slower, but they work across threads on different processes. OS might also provide features to access the mutex by name for easy sharing between instances of separate executables (as opposed to using a handle that can be used by fork only).
Semaphore
38,159,668
54
I would assume that I am aware of how to work with DispatchGroup, for understanding the issue, I've tried: class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() performUsingGroup() } func performUsingGroup() { let dq1 = DispatchQueue.global(qos: .userInitiated) let dq2 = DispatchQueue.global(qos: .userInitiated) let group = DispatchGroup() group.enter() dq1.async { for i in 1...3 { print("\(#function) DispatchQueue 1: \(i)") } group.leave() } group.wait() dq2.async { for i in 1...3 { print("\(#function) DispatchQueue 2: \(i)") } } group.notify(queue: DispatchQueue.main) { print("done by group") } } } and the result -as expected- is: performUsingGroup() DispatchQueue 1: 1 performUsingGroup() DispatchQueue 1: 2 performUsingGroup() DispatchQueue 1: 3 performUsingGroup() DispatchQueue 2: 1 performUsingGroup() DispatchQueue 2: 2 performUsingGroup() DispatchQueue 2: 3 done by group For using the Semaphore, I implemented: func performUsingSemaphore() { let dq1 = DispatchQueue.global(qos: .userInitiated) let dq2 = DispatchQueue.global(qos: .userInitiated) let semaphore = DispatchSemaphore(value: 1) dq1.async { semaphore.wait() for i in 1...3 { print("\(#function) DispatchQueue 1: \(i)") } semaphore.signal() } dq2.async { semaphore.wait() for i in 1...3 { print("\(#function) DispatchQueue 2: \(i)") } semaphore.signal() } } and called it in the viewDidLoad method. The result is: performUsingSemaphore() DispatchQueue 1: 1 performUsingSemaphore() DispatchQueue 1: 2 performUsingSemaphore() DispatchQueue 1: 3 performUsingSemaphore() DispatchQueue 2: 1 performUsingSemaphore() DispatchQueue 2: 2 performUsingSemaphore() DispatchQueue 2: 3 Conceptually, both of DispachGroup and Semaphore serve the same purpose (unless I misunderstand something). Honestly, I am unfamiliar with: when to use the Semaphore, especially when workin with DispachGroup -probably- handles the issue. What is the part that I am missing?
Conceptually, both of DispatchGroup and Semaphore serve the same purpose (unless I misunderstand something). The above is not exactly true. You can use a semaphore to do the same thing as a dispatch group but it is much more general. Dispatch groups are used when you have a load of things you want to do that can all happen at once, but you need to wait for them all to finish before doing something else. Semaphores can be used for the above but they are general purpose synchronisation objects and can be used for many other purposes too. The concept of a semaphore is not limited to Apple and can be found in many operating systems. In general, a semaphore has a value which is a non negative integer and two operations: wait If the value is not zero, decrement it, otherwise block until something signals the semaphore. signal If there are threads waiting, unblock one of them, otherwise increment the value. Needless to say both operations have to be thread safe. In olden days, when you only had one CPU, you'd simply disable interrupts whilst manipulating the value and the queue of waiting threads. Nowadays, it is more complicated because of multiple CPU cores and on chip caches etc. A semaphore can be used in any case where you have a resource that can be accessed by at most N threads at the same time. You set the semaphore's initial value to N and then the first N threads that wait on it are not blocked but the next thread has to wait until one of the first N threads has signaled the semaphore. The simplest case is N = 1. In that case, the semaphore behaves like a mutex lock. A semaphore can be used to emulate a dispatch group. You start the sempahore at 0, start all the tasks - tracking how many you have started and wait on the semaphore that number of times. Each task must signal the semaphore when it completes. However, there are some gotchas. For example, you need a separate count to know how many times to wait. If you want to be able to add more tasks to the group after you have started waiting, the count can only be updated in a mutex protected block and that may lead to problems with deadlocking. Also, I think the Dispatch implementation of semaphores might be vulnerable to priority inversion. Priority inversion occurs when a high priority thread waits for a resource that a low priority has grabbed. The high priority thread is blocked until the low priority thread releases the resource. If there is a medium priority thread running, this may never happen. You can pretty much do anything with a semaphore that other higher level synchronisation abstractions can do, but doing it right is often a tricky business to get right. The higher level abstractions are (hopefully) carefully written and you should use them in preference to a "roll your own" implementation with semaphores, if possible.
Semaphore
49,923,810
53
I have multiple apps compiled with g++, running in Ubuntu. I'm using named semaphores to co-ordinate between different processes. All works fine except in the following situation: If one of the processes calls sem_wait() or sem_timedwait() to decrement the semaphore and then crashes or is killed -9 before it gets a chance to call sem_post(), then from that moment on, the named semaphore is "unusable". By "unusable", what I mean is the semaphore count is now zero, and the process that should have incremented it back to 1 has died or been killed. I cannot find a sem_*() API that might tell me the process that last decremented it has crashed. Am I missing an API somewhere? Here is how I open the named semaphore: sem_t *sem = sem_open( "/testing", O_CREAT | // create the semaphore if it does not already exist O_CLOEXEC , // close on execute S_IRWXU | // permissions: user S_IRWXG | // permissions: group S_IRWXO , // permissions: other 1 ); // initial value of the semaphore Here is how I decrement it: struct timespec timeout = { 0, 0 }; clock_gettime( CLOCK_REALTIME, &timeout ); timeout.tv_sec += 5; if ( sem_timedwait( sem, &timeout ) ) { throw "timeout while waiting for semaphore"; }
Turns out there isn't a way to reliably recover the semaphore. Sure, anyone can post_sem() to the named semaphore to get the count to increase past zero again, but how to tell when such a recovery is needed? The API provided is too limited and doesn't indicate in any way when this has happened. Beware of the ipc tools also available -- the common tools ipcmk, ipcrm, and ipcs are only for the outdated SysV semaphores. They specifically do not work with the new POSIX semaphores. But it looks like there are other things that can be used to lock things, which the operating system does automatically release when an application dies in a way that cannot be caught in a signal handler. Two examples: a listening socket bound to a particular port, or a lock on a specific file. I decided the lock on a file is the solution I needed. So instead of a sem_wait() and sem_post() call, I'm using: lockf( fd, F_LOCK, 0 ) and lockf( fd, F_ULOCK, 0 ) When the application exits in any way, the file is automatically closed which also releases the file lock. Other client apps waiting for the "semaphore" are then free to proceed as expected. Thanks for the help, guys. UPDATE: 12 years later, thought I should point out that posix mutexes do have a "robust" attribute. That way, if the owner of the mutex gets killed or exits, the next user to lock the mutex will get the non-error return value of EOWNERDEAD, allowing the mutex to be recovered. This will make it similar to the file and socket locking solution. Look up pthread_mutexattr_setrobust() and pthread_mutex_consistent() for details. Thanks, Reinier Torenbeek, for this hint.
Semaphore
2,053,679
51
What are the pros / cons of using pthread_cond_wait or using a semaphore ? I am waiting for a state change like this : pthread_mutex_lock(&cam->video_lock); while(cam->status == WAIT_DISPLAY) { pthread_cond_wait(&cam->video_cond, &cam->video_lock); } pthread_mutex_unlock(&cam->video_lock); Using a properly initialised semaphore, I think I could do it like this : while(cam->status == WAIT_DISPLAY) { sem_wait(&some_semaphore); } What are the pros and cons of each method ?
A semaphore is suited cleanly to a producer-consumer model, although it has other uses. Your program logic is responsible for ensuring that the right number of posts are made for the number of waits. If you post a semaphore and nobody is waiting on it yet, then when they do wait they continue immediately. If your problem is such that it can be explained in terms of the count value of a semaphore, then it should be easy to solve with a semaphore. A condition variable is a bit more forgiving in some respects. You can for example use cond_broadcast to wake up all waiters, without the producer knowing how many there are. And if you cond_signal a condvar with nobody waiting on it then nothing happens. This is good if you don't know whether there's going to be a listener interested. It is also why the listener should always check the state with the mutex held before waiting - if they don't then they can miss a signal and not wake up until the next one (which could be never). So a condition variable is suitable for notifying interested parties that state has changed: you acquire the mutex, change the state, signal (or broadcast) the condvar and release the mutex. If this describes your problem you're in condvar territory. If different listeners are interested in different states you can just broadcast and they'll each in turn wake up, figure out whether they've found the state they want, and if not wait again. It's very gnarly indeed to attempt this sort of thing with a mutex and a semaphore. The problem comes when you want to take the mutex, check some state, then wait on the semaphore for changes. Unless you can atomically release the mutex and wait on the semaphore (which in pthreads you can't), you end up waiting on the semaphore while holding the mutex. This blocks the mutex, meaning that others can't take it to make the change you care about. So you will be tempted to add another mutex in a way which depends on your specific requirements. And maybe another semaphore. The result is generally incorrect code with harmful race conditions. Condition variables escape this problem, because calling cond_wait automatically releases the mutex, freeing it for use by others. The mutex is regained before cond_wait returns. IIRC it is possible to implement a kind of condvar using only semaphores, but if the mutex you're implementing to go with the condvar is required to have trylock, then it's a serious head-scratcher, and timed waits are out. Not recommended. So don't assume that anything you can do with a condvar can be done with semaphores. Plus of course mutexes can have nice behaviours that semaphores lack, principally priority-inversion avoidance.
Semaphore
70,773
49
According to the documentation: "a SemaphoreSlim doesn't use a Windows kernel semaphore". Are there any special resources used by the SemaphoreSlim which make it important to call Dispose when the SemaphoreSlim will no longer be used?
If you access the AvailableWaitHandle property, then Yes, you must call Dispose() to cleanup unmanaged resources. If you do not access AvailableWaitHandle, then No, calling Dispose() won't do anything important. SemaphoreSlim will create a ManualResetEvent on demand if you access the AvailableWaitHandle. This may be useful, for example if you need to wait on multiple handles. If you do access the AvailableWaitHandle property, and then fail to call Dispose() you will have a leaked ManualResetEvent, which presumably wraps a handle to an unmanaged CreateEvent resource that needs a corresponding call to CloseHandle to clean up. As other posters have pointed out, you should call Dispose() when you are done with any object that implements IDisposable. In this case, there are several risks to ignoring that practice, even though it may technically be safe to do so: My statements are based the reference source code to .NET 4.6.1. There is always the slim (pun intended) possibility that some future version of the framework will change SemaphoreSlim to where Dispose() is required. If your SemaphoreSlim is exposed outside of your class, calling code might reference the AvailableWaitHandle property not realizing that your class isn't disposing the SemaphoreSlim and create an unmanaged resource leak.
Semaphore
32,033,416
45
Throughout the resources I've read about multithreading, mutex is more often used and discussed compared to a semaphore. My question is when do you use a semaphore over a mutex? I don't see semaphores in Boost thread. Does that mean semaphores no longer used much these days? As far as I've understand, semaphores allow a resource to be shared by several threads. This is only possible if those threads are only reading the resource but not writing. Is this correct?
The typical use case for a mutex (allowing only one thread access to a resource at any time) is far more common than the typical uses if a semaphore. But a semaphore is actually the more general concept: A mutex is (almost) a special case of a semaphore. Typical applications would be: You don't want to create more than (e.g.) 5 database connections. No matter how many worker threads there are, they have to share these 5 connections. Or, if you run on a N-core machine, you might want to make sure that certain CPU/memory-intensive tasks don't run in more than N threads at the same time (because that would only reduce throughput due to context switches and cache thrashing effects). You might even want to limit the number of parallel CPU/memory intensive tasks to N-1, so the rest of the system doesn't starve. Or imagine a certain task needs a lot of memory, so running more than N instances of that task at the same time would lead to paging. You could use a semaphore here, to make sure that no more than N instances of this particular task run at the same time. EDIT/PS: From your question "This is only possible if those threads are only reading the resource but not writing. Is this correct?" and your comment, it seems to me as if you're thinking of a resource as a variable or a stream, that can be read or written and that can only be written to by one thread at a time. Don't. This is misleading in this context. Think of resources like "water". You can use water to wash your dishes. I can use water to wash my dishes at the same time. We don't need any kind of synchronization for that, because there is enough water for both of us. We don't necessarily use the same water. (And you can't "read" or "write" water.) But the total amount of water is finite. So it's not possible for any number of parties to wash their dishes at the same time. This kind of synchronization is done with a semaphore. Only usually not with water but with other finite resources like memory, disk space, IO throughput or CPU cores.
Semaphore
2,350,544
44
I'm looking for mutex/semaphore/concurrency mechanism in shell script. Consider following situation: Unless "a" user does not close the shared file, "b" user should not able to open/update it. I'm just wondering how to implement mutex, semaphore, critical sections, etc. in shell scripting. Which is the easiest way to implement locking mechanism [file level] in shell scripting?
The BashFAQ noted by shellter has some good examples. The basic idea, which I'm moving here so the page is self-contained, is to use an operation that both tests and sets at the same time: mkdir mkdir will fail if the directory exists and will make it if it does not. It's an atomic operation and you can use it like so to do a mutex in your shell script (from the above BashFAQ) # Bourne lockdir=/tmp/myscript.lock if mkdir "$lockdir" then # directory did not exist, but was created successfully echo >&2 "successfully acquired lock: $lockdir" # continue script else # failed to create the directory, presumably because it already exists echo >&2 "cannot acquire lock, giving up on $lockdir" exit 0 fi follow the link for more detail on cleanup and other items.
Semaphore
6,870,221
44
This is an interview question. Is it possible to use mutex in multiprocessing case on Linux/UNIX ? My idea: No, different processes have separate memory space. mutex is only used for multithreading. semaphore is used for multiprocessing to do synchronization. right ? Any comments are welcome. thanks
Mutual exclusion locks (mutexes) prevent multiple threads from simultaneously executing critical sections of code that access shared data (that is, mutexes are used to serialize the execution of threads). All mutexes must be global. A successful call for a mutex lock by way of mutex_lock() will cause another thread that is also trying to lock the same mutex to block until the owner thread unlocks it by way of mutex_unlock(). Threads within the same process or within other processes can share mutexes. Mutexes can synchronize threads within the same process or in other processes. Mutexes can be used to synchronize threads between processes if the mutexes are allocated in writable memory and shared among the cooperating processes (see mmap(2)), and have been initialized for this task. Initialization Mutexes are either intra-process or inter-process, depending upon the argument passed implicitly or explicitly to the initialization of that mutex. A statically allocated mutex does not need to be explicitly initialized; by default, a statically allocated mutex is initialized with all zeros and its scope is set to be within the calling process. For inter-process synchronization, a mutex needs to be allo- cated in memory shared between these processes. Since the memory for such a mutex must be allocated dynamically, the mutex needs to be explicitly initialized using mutex_init().
Semaphore
9,389,730
42
Trying to use a semaphore to control asynchronous requests to control the requests to my target host but I am getting the following error which I have assume means that my asycio.sleep() is not actually sleeping. How can I fix this? I want to add a delay to my requests for each URL targeted. Error: RuntimeWarning: coroutine 'sleep' was never awaited Coroutine created at (most recent call last) File "sephora_scraper.py", line 71, in <module> loop.run_until_complete(main()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 571, in run_until_complete self.run_forever() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 539, in run_forever self._run_once() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 1767, in _run_once handle._run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/events.py", line 88, in _run self._context.run(self._callback, *self._args) File "makeup.py", line 26, in get_html asyncio.sleep(delay) asyncio.sleep(delay) RuntimeWarning: Enable tracemalloc to get the object allocation traceback Code: import sys import time import asyncio import aiohttp async def get_html(semaphore, session, url, delay=6): await semaphore.acquire() async with session.get(url) as res: html = await res.text() asyncio.sleep(delay) semaphore.release() return html async def main(): categories = { "makeup": "https://www.sephora.com/shop/" } semaphore = asyncio.Semaphore(value=1) tasks = [] async with aiohttp.ClientSession(loop=loop, connector=aiohttp.TCPConnector(ssl=False)) as session: for category, url in categories.items(): # Get HTML of all pages tasks.append(get_html(semaphore, session, url)) res = await asyncio.gather(*tasks) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main())
asyncio.sleep(delay) Change it to: await asyncio.sleep(delay) asyncio.sleep is a coroutine and should be awaited.
Semaphore
54,088,263
41
I have to synchronize N client processes with one server. These processes are forked by a main function in which I declared 3 semaphores. I decided to use POSIX semaphores but I don't know how to share them between these processes. I thought that shared memory should work correctly, but I have some questions: How can I allocate the right space of memory in my segment? Can I use sizeof(sem_t) in size_t field of shmget in order to allocate exactly the space I need? Does anyone have some examples similar to this situation?
It's easy to share named POSIX semaphores Choose a name for your semaphore #define SNAME "/mysem" Use sem_open with O_CREAT in the process that creates them sem_t *sem = sem_open(SNAME, O_CREAT, 0644, 3); /* Initial value is 3. */ Open semaphores in the other processes sem_t *sem = sem_open(SEM_NAME, 0); /* Open a preexisting semaphore. */ If you insist on using shared memory, it's certainly possible. int fd = shm_open("shmname", O_CREAT, O_RDWR); ftruncate(fd, sizeof(sem_t)); sem_t *sem = mmap(NULL, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); sem_init(sem, 1, 1); I haven't tested the above so it could be completely bonkers.
Semaphore
8,359,322
37
I've been trying to understand Reentrant locks and Semaphores ( the nesting of Reentrant locks vs release/unlock mechanism ). It seems that having a Semaphore requires you to write a more thoroughly tested application because the release() method does not check if the thread releasing the permit is actually holding it. When I tested my test code, I found out that this may subsequently increase the number of permits beyond the initial limit. On the other hand, if a thread is not holding a reentrant lock when it invokes the unlock method, we get an IllegalMonitorException. So would it be right to say that there is no real reason ever to have a binary semaphore as everything that a binary semaphore can do can also be done by a ReentrantLock. If we use binary semaphores we would have to check the entire method call stack to see if a permit was acquired before ( also was it released too if there is a possibility of a subsequent acquire - which might block if a release does not proceed it and so on ). Also since reentrant locks also provide one lock per object, isn't it always a better idea to prefer a reentrant lock to a binary semaphore? I have checked a post here that talks about difference between a binary semaphore and a mutex but is there a thing like a mutex in Java? Thanks, Chan. P.S - I had posted this question in another forum ( http://www.coderanch.com/t/615796/threads/java/reason-prefer-binary-Semaphore-Reentrant ) and I haven't received a response yet. I thought I'd post it here as well to see what I can get.
there is no real reason ever to have a binary semaphore as everything that a binary semaphore can do can also be done by a ReentrantLock If all you need is reentrant mutual exclusion, then yes, there is no reason to use a binary semaphore over a ReentrantLock. If for any reason you need non-ownership-release semantics then obviously semaphore is your only choice. Also since reentrant locks also provide one lock per object, isn't it always a better idea to prefer a reentrant lock to a binary semaphore? It depends on the need. Like previously explained, if you need a simple mutex, then don't choose a semaphore. If more than one thread (but a limited number) can enter a critical section you can do this through either thread-confinement or a semaphore. I have checked a post here that talks about difference between a binary semaphore and a mutex but is there a thing like a mutex in Java? ReentrantLock and synchronized are examples of mutexes in Java.
Semaphore
17,683,575
37
I have read the docs for SemaphoreSlim SemaphoreSlim MSDN which indicates that the SemaphoreSlim will limit a section of code to be run by only 1 thread at a time if you configure it as: SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1); However, it doesn't indicate if it stops the same thread from accessing that code. This comes up with async and await. If one uses await in a method, control leaves that method and returns when whatever task or thread has completed. In my example, I use a button with an async button handler. It calls another method (Function1) with 'await'. Function1 in turn calls await Task.Run(() => Function2(beginCounter)); Around my Task.Run() I have a SemaphoreSlim. It sure seems like it stops the same thread from getting to Function2. But this is not guaranteed (as I read it) from the documentation and I wonder if that can be counted on. I have posted my complete example below. Thanks, Dave using System; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace AsynchAwaitExample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private readonly SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1); public MainWindow() { InitializeComponent(); } static int beginCounter = 0; static int endCounter = 0; /// <summary> /// Suggest hitting button 3 times in rapid succession /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void button_Click(object sender, RoutedEventArgs e) { beginCounter++; endCounter++; // Notice that if you click fast, you'll get all the beginCounters first, then the endCounters Console.WriteLine("beginCounter: " + beginCounter + " threadId: " + Thread.CurrentThread.ManagedThreadId); await Function1(beginCounter); Console.WriteLine("endCounter: " + endCounter + " threadId: " + Thread.CurrentThread.ManagedThreadId); } private async Task Function1(int beginCounter) { try { Console.WriteLine("about to grab lock" + " threadId: " + Thread.CurrentThread.ManagedThreadId + " beginCounter: " + beginCounter); await _semaphoreSlim.WaitAsync(); // get rid of _semaphoreSlim calls and you'll get into beginning of Function2 3 times before exiting Console.WriteLine("grabbed lock" + " threadId: " + Thread.CurrentThread.ManagedThreadId + " beginCounter: " + beginCounter); await Task.Run(() => Function2(beginCounter)); } finally { Console.WriteLine("about to release lock" + " threadId: " + Thread.CurrentThread.ManagedThreadId + " beginCounter: " + beginCounter); _semaphoreSlim.Release(); Console.WriteLine("released lock" + " threadId: " + Thread.CurrentThread.ManagedThreadId + " beginCounter: " + beginCounter); } } private void Function2(int beginCounter) { Console.WriteLine("Function2 start" + " threadId: " + Thread.CurrentThread.ManagedThreadId + " beginCounter: " + beginCounter); Thread.Sleep(1000); Console.WriteLine("Function2 end" + " threadId: " + Thread.CurrentThread.ManagedThreadId + " beginCounter: " + beginCounter); return; } } } Sample output if you click button 3 times. Notice that Function2 always finishes for a given counter before it starts again. beginCounter: 1 threadId: 9 about to grab lock threadId: 9 beginCounter: 1 grabbed lock threadId: 9 beginCounter: 1 Function2 start threadId: 13 beginCounter: 1 beginCounter: 2 threadId: 9 about to grab lock threadId: 9 beginCounter: 2 beginCounter: 3 threadId: 9 about to grab lock threadId: 9 beginCounter: 3 Function2 end threadId: 13 beginCounter: 1 about to release lock threadId: 9 beginCounter: 1 released lock threadId: 9 beginCounter: 1 grabbed lock threadId: 9 beginCounter: 2 Function2 start threadId: 13 beginCounter: 2 endCounter: 3 threadId: 9 Function2 end threadId: 13 beginCounter: 2 about to release lock threadId: 9 beginCounter: 2 released lock threadId: 9 beginCounter: 2 endCounter: 3 threadId: 9 grabbed lock threadId: 9 beginCounter: 3 Function2 start threadId: 13 beginCounter: 3 Function2 end threadId: 13 beginCounter: 3 about to release lock threadId: 9 beginCounter: 3 released lock threadId: 9 beginCounter: 3 endCounter: 3 threadId: 9 If you get rid of the SemaphoreSlim calls you'll get: beginCounter: 1 threadId: 10 about to grab lock threadId: 10 beginCounter: 1 grabbed lock threadId: 10 beginCounter: 1 Function2 start threadId: 13 beginCounter: 1 beginCounter: 2 threadId: 10 about to grab lock threadId: 10 beginCounter: 2 grabbed lock threadId: 10 beginCounter: 2 Function2 start threadId: 14 beginCounter: 2 beginCounter: 3 threadId: 10 about to grab lock threadId: 10 beginCounter: 3 grabbed lock threadId: 10 beginCounter: 3 Function2 start threadId: 15 beginCounter: 3 Function2 end threadId: 13 beginCounter: 1 about to release lock threadId: 10 beginCounter: 1 released lock threadId: 10 beginCounter: 1 endCounter: 3 threadId: 10 Function2 end threadId: 14 beginCounter: 2 about to release lock threadId: 10 beginCounter: 2 released lock threadId: 10 beginCounter: 2 endCounter: 3 threadId: 10
From the documentation: The SemaphoreSlim class doesn’t enforce thread or task identity on calls to the Wait, WaitAsync, and Release methods In other words, the class doesn't look to see which thread is calling it. It's just a simple counter. The same thread can acquire the semaphore multiple times, and that will be the same as if multiple threads acquired the semaphore. If the thread count remaining is down to 0, then even if a thread already was one that had acquired the semaphore that thread, if it calls Wait(), it will block until some other thread releases the semaphore. So, with respect to async/await, the fact that an await may or may not resume in the same thread where it was started doesn't matter. As long as you keep your Wait() and Release() calls balanced, it will work as one would hope and expect. In your example, you're even waiting on the semaphore asynchronously, and thus not blocking any thread. Which is good, because otherwise you'd deadlock the UI thread the second time you pressed your button. Related reading: Resource locking between iterations of the main thread (Async/Await) Why does this code not end in a deadlock Locking with nested async calls Note in particular caveats on re-entrant/recursive locking, especially with async/await. Thread synchronization is tricky enough as it is, and that difficulty is what async/await is designed to simplify. And it does so significantly in most cases. But not when you mix it with yet another synchronization/locking mechanism.
Semaphore
40,985,233
35
What are the trade-offs between using a System V and a Posix semaphore?
From O'Reilly: One marked difference between the System V and POSIX semaphore implementations is that in System V you can control how much the semaphore count can be increased or decreased; whereas in POSIX, the semaphore count is increased and decreased by 1. POSIX semaphores do not allow manipulation of semaphore permissions, whereas System V semaphores allow you to change the permissions of semaphores to a subset of the original permission. Initialization and creation of semaphores is atomic (from the user's perspective) in POSIX semaphores. From a usage perspective, System V semaphores are clumsy, while POSIX semaphores are straight-forward The scalability of POSIX semaphores (using unnamed semaphores) is much higher than System V semaphores. In a user/client scenario, where each user creates her own instances of a server, it would be better to use POSIX semaphores. System V semaphores, when creating a semaphore object, creates an array of semaphores whereas POSIX semaphores create just one. Because of this feature, semaphore creation (memory footprint-wise) is costlier in System V semaphores when compared to POSIX semaphores. It has been said that POSIX semaphore performance is better than System V-based semaphores. POSIX semaphores provide a mechanism for process-wide semaphores rather than system-wide semaphores. So, if a developer forgets to close the semaphore, on process exit the semaphore is cleaned up. In simple terms, POSIX semaphores provide a mechanism for non-persistent semaphores.
Semaphore
368,322
33
How do i tell if one instance of my program is running? I thought I could do this with a data file but it would just be messy :( I want to do this as I only want 1 instance to ever be open at one point.
As Jon first suggested, you can try creating a mutex. Call CreateMutex. If you get a non-null handle back, then call GetLastError. It will tell you whether you were the one who created the mutex or whether the mutex was already open before (Error_Already_Exists). Note that it is not necessary to acquire ownership of the mutex. The mutex is not being used for mutual exclusion. It's being used because it is a named kernel object. An event or semaphore could work, too. The mutex technique gives you a Boolean answer: Yes, there is another instance, or no, there is not. You frequently want to know more than just that. For instance, you might want to know the handle of the other instance's main window so you can tell it to come to the foreground in place of your other instance. That's where a memory-mapped file can come in handy; it can hold information about the first instance so later instances can refer to it. Be careful when choosing the name of the mutex. Read the documentation carefully, and keep in mind that some characters (such as backslash) are not allowed in some OS versions, but are required for certain features in other OS versions. Also remember the problem of other users. If your program could be run via remote desktop or fast user switching, then there could be other users already running your program, and you might not really want to restrict the current user from running your program. In that case, don't use a global name. If you do want to restrict access for all users, then make sure the mutex object's security attributes are such that everyone will be able to open a handle to it. Using a null pointer for the lpSecurityAttributes parameter is not sufficient for that; the "default security descriptor" that MSDN mentions gives full access to the current user and no access to others. You're allowed to edit the DPR file of your program. That's usually a good place to do this kind of thing. If you wait until the OnCreate event of one of your forms, then your program already has a bit of momentum toward running normally, so it's clumsy to try to terminate the program at that point. Better to terminate before too much UI work has been done. For example: var mutex: THandle; mutexName: string; begin mutexName := ConstructMutexName(); mutex := CreateMutex(nil, False, PChar(mutexName)); if mutex = 0 then RaiseLastOSError; // Couldn't open handle at all. if GetLastError = Error_Already_Exists then begin // We are not the first instance. SendDataToPreviousInstance(...); exit; end; // We are the first instance. // Do NOT close the mutex handle here. It must // remain open for the duration of your program, // or else later instances won't be able to // detect this instance. Application.Initialize; Application.CreateForm(...); Application.Run; end. There's a question of when to close the mutex handle. You don't have to close it. When your process finally terminates (even if it crashes), the OS will automatically close any outstanding handles, and when there are no more handles open, the mutex object will be destroyed (thus allowing another instance of your program to start and consider itself to be the first instance). But you might want to close the handle anyway. Suppose you chose to implement the SendDataToPreviousInstance function I mentioned in the code. If you want to get fancy, then you could account for the case that the previous instance is already shutting down and is unable to accept new data. Then you won't really want to close the second instance. The first instance could close the mutex handle as soon as it knows it's shutting down, in effect becoming a "lame duck" instance. The second instance will try to create the mutex handle, succeed, and consider itself the real first instance. The previous instance will close uninterrupted. Use CloseHandle to close the mutex; call it from your main form's OnClose event handler, or wherever else you call Application.Terminate, for example.
Semaphore
459,554
32
I am doing experiments with IPC, especially with Mutex, Semaphore and Spin Lock. What I learnt is Mutex is used for Asynchronous Locking (with sleeping (as per theories I read on NET)) Mechanism, Semaphore are Synchronous Locking (with Signaling and Sleeping) Mechanism, and Spin Locks are Synchronous but Non-sleeping Mechanism. Can anyone help me to clarify these stuff deeply? And another doubt is about Mutex, when I wrote program with thread & mutex, while one thread is running another thread is not in Sleep state but it continuously tries to acquire the Lock. So Mutex is sleeping or Non-sleeping???
First, remember the goal of these 'synchronizing objects' : These objects were designed to provide an efficient and coherent use of 'shared data' between more than 1 thread among 1 process or from different processes. These objects can be 'acquired' or 'released'. That is it!!! End of story!!! Now, if it helps to you, let me put my grain of sand: 1) Critical Section= User object used for allowing the execution of just one active thread from many others within one process. The other non selected threads (@ acquiring this object) are put to sleep. [No interprocess capability, very primitive object]. 2) Mutex Semaphore (aka Mutex)= Kernel object used for allowing the execution of just one active thread from many others, within one process or among different processes. The other non selected threads (@ acquiring this object) are put to sleep. This object supports thread ownership, thread termination notification, recursion (multiple 'acquire' calls from same thread) and 'priority inversion avoidance'. [Interprocess capability, very safe to use, a kind of 'high level' synchronization object]. 3) Counting Semaphore (aka Semaphore)= Kernel object used for allowing the execution of a group of active threads from many others, within one process or among different processes. The other non selected threads (@ acquiring this object) are put to sleep. [Interprocess capability however not very safe to use because it lacks following 'mutex' attributes: thread termination notification, recursion?, 'priority inversion avoidance'?, etc]. 4) And now, talking about 'spinlocks', first some definitions: Critical Region= A region of memory shared by 2 or more processes. Lock= A variable whose value allows or denies the entrance to a 'critical region'. (It could be implemented as a simple 'boolean flag'). Busy waiting= Continuosly testing of a variable until some value appears. Finally: Spin-lock (aka Spinlock)= A lock which uses busy waiting. (The acquiring of the lock is made by xchg or similar atomic operations). [No thread sleeping, mostly used at kernel level only. Ineffcient for User level code]. As a last comment, I am not sure but I can bet you some big bucks that the above first 3 synchronizing objects (#1, #2 and #3) make use of this simple beast (#4) as part of their implementation. Have a good day!. References: -Real-Time Concepts for Embedded Systems by Qing Li with Caroline Yao (CMP Books). -Modern Operating Systems (3rd) by Andrew Tanenbaum (Pearson Education International). -Programming Applications for Microsoft Windows (4th) by Jeffrey Richter (Microsoft Programming Series).
Semaphore
23,511,058
31
Perhaps it's too late at night, but I can't think of a nice way to do this. I've started a bunch of asynchronous downloads, and I want to wait until they all complete before the program terminates. This leads me to believe I should increment something when a download starts, and decrement it when it finishes. But then how do I wait until the count is 0 again? Semaphores sort of work in the opposite way in that you block when there are no resources available, not when they're all available (blocks when count is 0, rather than non-zero).
Check out the CountdownLatch class in this magazine article. Update: now covered by the framework since version 4.0, CountdownEvent class.
Semaphore
1,965,578
30
Please tell what is difference between a Semaphore initialized with 1 and Vs. intialized zero, as below: public static Semaphore semOne = new Semaphore(1); and public static Semaphore semZero = new Semaphore(0);
The argument to the Semaphore instance is the number of "permits" that are available. It can be any integer, not just 0 or 1. For semZero all acquire() calls will block and tryAcquire() calls will return false, until you do a release() For semOne the first acquire() calls will succeed and the rest will block until the first one releases. The class is well documented here. Parameters: permits - the initial number of permits available. This value may be negative, in which case releases must occur before any acquires will be granted.
Semaphore
25,563,640
30
What is the difference between Counting and binary semaphore. What I have seen somewhere is that both can control N number of processes which have requested for a resource. Both have taken and Free states. Is there any restriction on how many Resources a Binary semaphore and Counting semaphore can protect? Both allow only One process to use a resource at a time... Is there any other difference? Are the above mentioned properties correct?
Actually, both types are used to synchronize access to a shared resource, whether the entity which is trying to access is a process or even a thread. The difference is as follows: Binary semaphores are binary, they can have two values only; one to represent that a process/thread is in the critical section(code that access the shared resource) and others should wait, the other indicating the critical section is free. On the other hand, counting semaphores take more than two values, they can have any value you want. The max value X they take allows X process/threads to access the shared resource simultaneously. For further information, take a look at this link. http://www.chibios.org/dokuwiki/doku.php?id=chibios:articles:semaphores_mutexes EDIT The max value that a counting semaphore can take is the the number of processes you want to allow into the critical section at the same time. Again, you might have a case where you want exclusion over a certain resource, yet you know this resource can be accessed by a max number of processes (say X), so you set a counting semaphore with the value X. This would allow the X processes to access that resource at the same time; yet the process X+1 would have to wait till one of the processes in the critical section gets out.
Semaphore
10,898,022
29
When I run this code in Python 3.7: import asyncio sem = asyncio.Semaphore(2) async def work(): async with sem: print('working') await asyncio.sleep(1) async def main(): await asyncio.gather(work(), work(), work()) asyncio.run(main()) It fails with RuntimeError: $ python3 demo.py working working Traceback (most recent call last): File "demo.py", line 13, in <module> asyncio.run(main()) File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/runners.py", line 43, in run return loop.run_until_complete(main) File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete return future.result() File "demo.py", line 11, in main await asyncio.gather(work(), work(), work()) File "demo.py", line 6, in work async with sem: File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/locks.py", line 92, in __aenter__ await self.acquire() File "/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/locks.py", line 474, in acquire await fut RuntimeError: Task <Task pending coro=<work() running at demo.py:6> cb=[gather.<locals>._done_callback() at /opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/tasks.py:664]> got Future <Future pending> attached to a different loop
Python 3.10+: This error message should not occur anymore, see answer from @mmdanziger: (...) the implementation of Semaphore has been changed and no longer grabs the current loop on init Python 3.9 and older: It's because Semaphore constructor sets its _loop attribute – in asyncio/locks.py: class Semaphore(_ContextManagerMixin): def __init__(self, value=1, *, loop=None): if value < 0: raise ValueError("Semaphore initial value must be >= 0") self._value = value self._waiters = collections.deque() if loop is not None: self._loop = loop else: self._loop = events.get_event_loop() But asyncio.run() starts a completely new loop – in asyncio/runners.py, it's also metioned in the documentation: def run(main, *, debug=False): if events._get_running_loop() is not None: raise RuntimeError( "asyncio.run() cannot be called from a running event loop") if not coroutines.iscoroutine(main): raise ValueError("a coroutine was expected, got {!r}".format(main)) loop = events.new_event_loop() ... Semaphore initiated outside of asyncio.run() grabs the asyncio "default" loop and so cannot be used with the event loop created with asyncio.run(). Solution Initiate Semaphore from code called by asyncio.run(). You will have to pass them to the right place, there are more possibilities how to do that, you can for example use contextvars, but I will just give the simplest example: import asyncio async def work(sem): async with sem: print('working') await asyncio.sleep(1) async def main(): sem = asyncio.Semaphore(2) await asyncio.gather(work(sem), work(sem), work(sem)) asyncio.run(main()) The same issue (and solution) is probably also with asyncio.Lock, asyncio.Event, and asyncio.Condition.
Semaphore
55,918,048
28
I know that threading.Lock() is equal to threading.Semaphore(1). Is also threading.Lock() equal to threading.BoundedSemaphore(1) ? And newly I saw threading.BoundedSemaphore(), what is the difference between them? For example in the following code snippet (applying limitation on threads): import threading sem = threading.Semaphore(5) sem = threading.BoundedSemaphore(5)
A Semaphore can be released more times than it's acquired, and that will raise its counter above the starting value. A BoundedSemaphore can't be raised above the starting value. from threading import Semaphore, BoundedSemaphore # Usually, you create a Semaphore that will allow a certain number of threads # into a section of code. This one starts at 5. s1 = Semaphore(5) # When you want to enter the section of code, you acquire it first. # That lowers it to 4. (Four more threads could enter this section.) s1.acquire() # Then you do whatever sensitive thing needed to be restricted to five threads. # When you're finished, you release the semaphore, and it goes back to 5. s1.release() # That's all fine, but you can also release it without acquiring it first. s1.release() # The counter is now 6! That might make sense in some situations, but not in most. print(s1._value) # => 6 # If that doesn't make sense in your situation, use a BoundedSemaphore. s2 = BoundedSemaphore(5) # Start at 5. s2.acquire() # Lower to 4. s2.release() # Go back to 5. try: s2.release() # Try to raise to 6, above starting value. except ValueError: print('As expected, it complained.')
Semaphore
48,971,121
28
I want to fork multiple processes and then use a semaphore on them. Here is what I tried: sem_init(&sem, 1, 1); /* semaphore*, pshared, value */ . . . if(pid != 0){ /* parent process */ wait(NULL); /* wait all child processes */ printf("\nParent: All children have exited.\n"); . . /* cleanup semaphores */ sem_destroy(&sem); exit(0); } else{ /* child process */ sem_wait(&sem); /* P operation */ printf(" Child(%d) is in critical section.\n",i); sleep(1); *p += i%3; /* increment *p by 0, 1 or 2 based on i */ printf(" Child(%d) new value of *p=%d.\n",i,*p); sem_post(&sem); /* V operation */ exit(0); } And the output is: child(0) forked child(1) forked Child(0) is in critical section. Child(1) is in critical section. child(2) forked Child(2) is in critical section. child(3) forked Child(3) is in critical section. child(4) forked Child(4) is in critical section. Child(0) new value of *p=0. Child(1) new value of *p=1. Child(2) new value of *p=3. Child(3) new value of *p=3. Child(4) new value of *p=4. Parent: All children have exited. This clearly means the semaphore didn't work as it was supposed to. Can you explain how I should use semaphores on forked processes?
The problem you are facing is the misunderstanding of sem_init() function. When you read the manual page you will see this: The pshared argument indicates whether this semaphore is to be shared between the threads of a process, or between processes. If you are done reading up to this point, you will think that the non-zero value of pshared will make the semaphore inter-process semaphore. However, this is wrong. You should continue reading and you'll understand that you have to locate the semaphore in a shared memory region. To do that, several functions can be used as you can see below: If pshared is nonzero, then the semaphore is shared between processes, and should be located in a region of shared memory (see shm_open(3), mmap(2), and shmget(2)). (Since a child created by fork(2) inherits its parent's memory mappings, it can also access the semaphore.) Any process that can access the shared memory region can operate on the semaphore using sem_post(3), sem_wait(3), etc. I find this approach as a more complicated approach than others, therefore I want to encourage people to use sem_open() instead of sem_init(). Below you can see a complete program illustrates the following: How to allocate shared memory and use shared variables between forked processes. How to initialize a semaphore in a shared memory region and is used by multiple processes. How to fork multiple processes and make the parent wait until all of its children exit. #include <stdio.h> /* printf() */ #include <stdlib.h> /* exit(), malloc(), free() */ #include <sys/types.h> /* key_t, sem_t, pid_t */ #include <sys/shm.h> /* shmat(), IPC_RMID */ #include <errno.h> /* errno, ECHILD */ #include <semaphore.h> /* sem_open(), sem_destroy(), sem_wait().. */ #include <fcntl.h> /* O_CREAT, O_EXEC */ int main (int argc, char **argv){ int i; /* loop variables */ key_t shmkey; /* shared memory key */ int shmid; /* shared memory id */ sem_t *sem; /* synch semaphore *//*shared */ pid_t pid; /* fork pid */ int *p; /* shared variable *//*shared */ unsigned int n; /* fork count */ unsigned int value; /* semaphore value */ /* initialize a shared variable in shared memory */ shmkey = ftok ("/dev/null", 5); /* valid directory name and a number */ printf ("shmkey for p = %d\n", shmkey); shmid = shmget (shmkey, sizeof (int), 0644 | IPC_CREAT); if (shmid < 0){ /* shared memory error check */ perror ("shmget\n"); exit (1); } p = (int *) shmat (shmid, NULL, 0); /* attach p to shared memory */ *p = 0; printf ("p=%d is allocated in shared memory.\n\n", *p); /********************************************************/ printf ("How many children do you want to fork?\n"); printf ("Fork count: "); scanf ("%u", &n); printf ("What do you want the semaphore value to be?\n"); printf ("Semaphore value: "); scanf ("%u", &value); /* initialize semaphores for shared processes */ sem = sem_open ("pSem", O_CREAT | O_EXCL, 0644, value); /* name of semaphore is "pSem", semaphore is reached using this name */ printf ("semaphores initialized.\n\n"); /* fork child processes */ for (i = 0; i < n; i++){ pid = fork (); if (pid < 0) { /* check for error */ sem_unlink ("pSem"); sem_close(sem); /* unlink prevents the semaphore existing forever */ /* if a crash occurs during the execution */ printf ("Fork error.\n");  } else if (pid == 0) break; /* child processes */ } /******************************************************/ /****************** PARENT PROCESS ****************/ /******************************************************/ if (pid != 0){ /* wait for all children to exit */ while (pid = waitpid (-1, NULL, 0)){ if (errno == ECHILD) break; } printf ("\nParent: All children have exited.\n"); /* shared memory detach */ shmdt (p); shmctl (shmid, IPC_RMID, 0); /* cleanup semaphores */ sem_unlink ("pSem"); sem_close(sem); /* unlink prevents the semaphore existing forever */ /* if a crash occurs during the execution */ exit (0); } /******************************************************/ /****************** CHILD PROCESS *****************/ /******************************************************/ else{ sem_wait (sem); /* P operation */ printf (" Child(%d) is in critical section.\n", i); sleep (1); *p += i % 3; /* increment *p by 0, 1 or 2 based on i */ printf (" Child(%d) new value of *p=%d.\n", i, *p); sem_post (sem); /* V operation */ exit (0); } } OUTPUT ./a.out shmkey for p = 84214791 p=0 is allocated in shared memory. How many children do you want to fork? Fork count: 6 What do you want the semaphore value to be? Semaphore value: 2 semaphores initialized. Child(0) is in critical section. Child(1) is in critical section. Child(0) new value of *p=0. Child(1) new value of *p=1. Child(2) is in critical section. Child(3) is in critical section. Child(2) new value of *p=3. Child(3) new value of *p=3. Child(4) is in critical section. Child(5) is in critical section. Child(4) new value of *p=4. Child(5) new value of *p=6. Parent: All children have exited. It is not bad to check shmkey since when ftok() fails, it returns -1. However if you have multiple shared variables and if the ftok() function fails multiple times, the shared variables that have a shmkey with value -1 will reside in the same region of the shared memory resulting in a change in one affecting the other. Therefore the program execution will get messy. To avoid this, it is better checked if the ftok() returns -1 or not (better to check in source code rather than printing to screen like I did, although I wanted to show you the key values in case there is a collision). Pay attention to how the semaphore is declared and initialized. It's different than what you have done in the question (sem_t sem vs sem_t* sem). Moreover, you should use them as they appear in this example. You cannot define sem_t* and use it in sem_init().
Semaphore
16,400,820
27
I'm currently training for an OS exam with previous iterations and I came across this: Implement a "N Process Barrier", that is, making sure that each process out of a group of them waits, at some point in its respective execution, for the other processes to reach their given point. You have the following ops available: init(sem,value), wait(sem) and signal(sem) N is an arbitrary number. I can make it so that it works for a given number of processes, but not for any number. Any ideas? It's OK to reply with the pseudo-code, this is not an assignment, just personal study.
This is well presented in The Little Book of Semaphores. n = the number of threads count = 0 mutex = Semaphore(1) barrier = Semaphore(0) mutex.wait() count = count + 1 mutex.signal() if count == n: barrier.signal() # unblock ONE thread barrier.wait() barrier.signal() # once we are unblocked, it's our duty to unblock the next thread
Semaphore
6,331,301
27
I am trying to understand the usefulness of fairness property in Semaphore class. Specifically to quote the Javadoc mentions that: Generally, semaphores used to control resource access should be initialized as fair, to ensure that no thread is starved out from accessing a resource. When using semaphores for other kinds of synchronization control, the throughput advantages of non-fair ordering often outweigh fairness considerations. Could someone provide an example where barging might be desired here. I cannot think past resource access use case. Also, why is that the default is non-fair behavior? Lastly, are there any performance implications in using the fairness behavior?
Java's built-in concurrency constructs (synchronized, wait(), notify(),...) do not specify which thread should be freed when a lock is released. It is up to the JVM implementation to decide which algorithm to use. Fairness gives you more control: when the lock is released, the thread with the longest wait time is given the lock (FIFO processing). Without fairness (and with a very bad algorithm) you might have a situation where a thread is always waiting for the lock because there is a continuous stream of other threads. If the Semaphore is set to be fair, there's a small overhead because it needs to maintain a queue of all the threads waiting for the lock. Unless you're writing a high throughput/high performance/many cores application, you won't probably see the difference though! Scenario where fairness is not needed If you have N identical worker threads, it doesn't matter which one gets a task to execute Scenario where fairness is needed If you have N tasks queues, you don't want one queue to be waiting forever and never acquiring the lock.
Semaphore
17,825,508
26
I want to check the state of a Semaphore to see if it is signalled or not (so if t is signalled, I can release it). How can I do this? EDIT1: I have two threads, one would wait on semaphore and the other should release a Semaphore. The problem is that the second thread may call Release() several times when the first thread is not waiting on it. So the second thread should detect that if it calls Release() it generate any error or not (it generate an error if you try to release a semaphore if nobody waiting on it). How can I do this? I know that I can use a flag to do this, but it is ugly. Is there any better way?
You can check to see if a Semaphore is signaled by calling WaitOne and passing a timeout value of 0 as a parameter. This will cause WaitOne to return immediately with a true or false value indicating whether the semaphore was signaled. This, of course, could change the state of the semaphore which makes it cumbersome to use. Another reason why this trick will not help you is because a semaphore is said to be signaled when at least one count is available. It sounds like you want to know when the semaphore has all counts available. The Semaphore class does not have that exact ability. You can use the return value from Release to infer what the count is, but that causes the semaphore to change its state and, of course, it will still throw an exception if the semaphore already had all counts available prior to making the call. What we need is a semaphore with a release operation that does not throw. This is not terribly difficult. The TryRelease method below will return true if a count became available or false if the semaphore was already at the maximumCount. Either way it will never throw an exception. public class Semaphore { private int count = 0; private int limit = 0; private object locker = new object(); public Semaphore(int initialCount, int maximumCount) { count = initialCount; limit = maximumCount; } public void Wait() { lock (locker) { while (count == 0) { Monitor.Wait(locker); } count--; } } public bool TryRelease() { lock (locker) { if (count < limit) { count++; Monitor.PulseAll(locker); return true; } return false; } } }
Semaphore
7,330,834
25
Nonbinary ones.. I have never encountered a problem that required me to use a semaphore instead of mutex. So is this mostly theoretical construct, or real sw like Office, Firefox have places where they use it? If so what are the common use patterns for semaphores?
Non-binary semaphores are used in resource allocation. A semaphore might hold the count of the number of a particular resource. If you have a pool of connections, such as a web browser might use, then an individual thread might reserve a member of the pool by waiting on the semaphore to get a connection, uses the connection, then releases the connection by releasing the semaphore. You can emulate a semaphore by creating a counter and then establishing a mutual exclusion region around the counter. However, waiting for a resource such as above, requires a two-level mutex and is not quite so elegant as using the semaphore.
Semaphore
21,736,741
25
I've got the following code and the semaphore wouldn't lock it as expected. (I'm aware of apc_inc. This is not what I'm looking for.) $semkey = sem_get(123); sem_acquire($semkey); $count = apc_fetch('count111'); if(!$count) $count = 0; $count++; apc_store('count111', $count); sem_release($semkey); followed by ab -n 4000 -c 200 http://localhost/test.php 0 requests failed. but after that an apc_fetch('count111') shows only ~ 1200 hits nginx on ubuntu 12.04 (64bit), php 5.3.16~dotdeb, php-fpm update 1: works perfectly on Linux mint, 5.4.6~dotdeb, built in web server. I'm going to try the same machine with the same version with nginx.
The problem was, apparently, with the APC itself, not with the semaphore. Updating to PHP 5.4.8-1~dotdeb.0 has solved the problem for both nginx and built-in server test runs.
Semaphore
12,407,767
23
How to interrupt all Cypress tests on the first test failure? We are using semaphore to launch complete e2e tests with Cypress for each PR. But it takes too much time. I'd like to interrupt all tests on the first test failure. Getting the complete errors is each developer's business when they develop. I just want to be informed ASAP if there is anything wrong prior to deploy, and don't have to wait for the full tests to complete. So far the only solution I came up with was interrupting the tests on the current spec file with Cypress. afterEach(() => { if (this.currentTest.state === 'failed') { Cypress.runner.end(); } }); But this is not enough since it only interrupts the tests located on the spec file, not ALL the other files. I've done some intensive search on this matter today and it doesn't seem like this is a thing on Cypress. So I'm trying other solutions. 1: with Semaphore fail_fast: stop: when: "true" It is supposed to interrupt the script on error. But it doesn't work: tests keep running after error. My guess is that Cypress will throw an error only when all tests are complete. 2: maybe with the script launching Cypress, but I'm out of ideas Right now here are my scripts "cy:run": "npx cypress run", "cy:run:dev": "CYPRESS_env=dev npx cypress run", "cy:test": "start-server-and-test start http-get://localhost:4202 cy:run"
EDIT: It seems like this feature was introduced, but it requires paid version of Cypress (Business Plan). More about it: Docs, comment in the thread Original answer: This has been a long-requested feature in Cypress for some reason still has not been introduced. There are some workarounds proposed by the community, however it is not guaranteed they will work. Check this thread on Cypress' Github for more details, maybe you will find a workaround that works for your case.
Semaphore
61,661,932
23
Does anybody know why semaphore operations are called P and V? Every time I read a chapter on semaphores it says something like the following: In order for the thread to obtain a resource it executes a P operation. And in order for the thread to release a resource it executes a V operation. What does P and V stand for? Why they are not called wait and signal?
Dijkstra, one of the inventors of semaphores, used P and V. The letters come from the Dutch words Probeer (try) and Verhoog (increment). See also: https://cs.nyu.edu/~yap/classes/os/resources/origin_of_PV.html
Semaphore
29,606,162
23
Short version Is it possible to share a semaphore (or any other synchronization lock) between user space and kernel space? Named POSIX semaphores have kernel persistence, that's why I was wondering if it is possible to also create, and/or access them from kernel context. Searching the internet didn't help much due to the sea of information on normal usage of POSIX semaphores. Long version I am developing a unified interface to real-time systems in which I have some added book keeping to take care of, protected by a semaphore. These book keepings are done on resource allocation and deallocation, which is done in non-real-time context. With RTAI, the thread waiting and posting a semaphore however needs to be in real-time context. This means that using RTAI's named semaphore means switching between real-time and non-real-time context on every wait/post in user space, and worse, creating a short real-time thread for every sem/wait in kernel space. What I am looking for is a way to share a normal Linux or POSIX semaphore between kernel and user spaces so that I can safely wait/post it in non-real-time context. Any information on this subject would be greatly appreciated. If this is not possible, do you have any other ideas how this task could be accomplished?1 1 One way would be to add a system call, have the semaphore in kernel space, and have user space processes invoke that system call and the semaphore would be all managed in kernel space. I would be happier if I didn't have to patch the kernel just because of this though.
Well, you were in the right direction, but not quite - Linux named POSIX semaphore are based on FUTex, which stands for Fast User-space Mutex. As the name implies, while their implementation is assisted by the kernel, a big chunk of it is done by user code. Sharing such a semaphore between kernel and user space would require re-implementing this infrastructure in the kernel. Possible, but certainly not easy. SysV Semaphores on the other hand are implemented completely in kernel and are only accessible to user space via standard system calls (e.g. sem_timedwait() and friends). This means that every SysV related operations (semaphore creation, taking or release) is actually implemented in the kernel and you can simply call the underlying kernel function from your code to take the same semaphore from the kernel is needed. Thus, your user code will simply call sem_timedwait(). That's the easy part. The kernel part is just a little bit more tricky: you have to find the code that implement sem_timedwait() and related calls in the kernel (they are are all in the file ipc/sem.c) and create a replica of each of the functions that does what the original function does without the calls to copy_from_user(...) and copy_to_user(..) and friends. The reason for this is that those kernel function expect to be called from a system call with a pointer to a user buffer, while you want to call them with parameters in kernel buffers. Take for example sem_timedwait() - the relevant kernel function is sys_timedwait() in ipc/sem.c (see here: http://lxr.free-electrons.com/source/ipc/sem.c#L1537). If you copy this function in your kernel code and just remove the parts that do copy_from_user() and copy_to_user() and simply use the passed pointers (since you'll call them from kernel space), you'll get kernel equivalent functions that can take SysV semaphore from kernel space, along side user space - so long as you call them from process context in the kernel (if you don't know what this last sentence mean, I highly recommend reading up on Linux Device Drivers, 3rd edition). Best of luck.
Semaphore
17,391,276
23
I need to stop a thread until another thread sets a boolean value and I don't want to share between them an event. What I currently have is the following code using a Sleep (and that's the code I want to change): while (!_engine.IsReadyToStop()) { System.Threading.Thread.Sleep(Properties.Settings.Default.IntervalForCheckingEngine); } Any ideas? EDIT TO CLARIFY THINGS: There is an object called _engine of a class that I don't own. I cannot modify it, that's why I don't want to share an event between them. I need to wait until a method of that class returns true.
SpinWait.SpinUntil is the right answer, regardless where you're gonna place this code. SpinUntil offers "a nice mix of spinning, yielding, and sleeping in between invocations".
Semaphore
12,412,167
23
What do I need and how can I use threads in C on Windows Vista? Could you please give me a simple code example?
Here is the MSDN sample on how to use CreateThread() on Windows. The basic idea is you call CreateThread() and pass it a pointer to your thread function, which is what will be run on the target thread once it is created. The simplest code to do it is: #include <windows.h> DWORD WINAPI ThreadFunc(void* data) { // Do stuff. This will be the first function called on the new thread. // When this function returns, the thread goes away. See MSDN for more details. return 0; } int main() { HANDLE thread = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL); if (thread) { // Optionally do stuff, such as wait on the thread. } } You also have the option of calling SHCreateThread()—same basic idea but will do some shell-type initialization for you if you ask it, such as initializing COM, etc.
Semaphore
1,981,459
22
I'm trying to find out what is the difference between the SemaphoreSlim use of Wait and WaitAsync, used in this kind of context: private SemaphoreSlim semaphore = new SemaphoreSlim(1); public async Task<string> Get() { // What's the difference between using Wait and WaitAsync here? this.semaphore.Wait(); // await this.semaphore.WaitAsync() string result; try { result = this.GetStringAsync(); } finally { this.semaphore.Release(); } return result; }
If you have async method - you want to avoid any blocking calls if possible. SemaphoreSlim.Wait() is a blocking call. So what will happen if you use Wait() and semaphore is not available at the moment? It will block the caller, which is very unexpected thing for async methods: // this will _block_ despite calling async method and using await // until semaphore is available var myTask = Get(); var myString = await Get(); // will block also If you use WaitAsync - it will not block the caller if semaphore is not available at the moment. var myTask = Get(); // can continue with other things, even if semaphore is not available Also you should beware to use regular locking mechanisms together with async\await. After doing this: result = await this.GetStringAsync(); You may be on another thread after await, which means when you try to release the lock you acquired - it might fail, because you are trying to release it not from the same thread you acquired it. Note this is NOT the case for semaphore, because it does not have thread affinity (unlike other such constructs like Monitor.Enter, ReaderWriterLock and so on).
Semaphore
44,305,825
19
I have a slice of integers, which are manipulated concurrently: ints := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} I'm using a buffered channel as semaphore in order to have an upper bound of concurrently running go routines: sem := make(chan struct{}, 2) for _, i := range ints { // acquire semaphore sem <- struct{}{} // start long running go routine go func(id int, sem chan struct{}) { // do something // release semaphore <- sem }(i, sem) } The code above works pretty well until the last or last two integers are reached, because the program ends before those last go routines are finished. Question: how do I wait for the buffered channel to drain?
You can't use a semaphore (channel in this case) in that manner. There's no guarantee it won't be empty any point while you are processing values and dispatching more goroutines. That's not a concern in this case specifically since you're dispatching work synchronously, but because there's no race-free way to check a channel's length, there's no primitive to wait for a channel's length to reach 0. Use a sync.WaitGroup to wait for all goroutines to complete sem := make(chan struct{}, 2) var wg sync.WaitGroup for _, i := range ints { wg.Add(1) // acquire semaphore sem <- struct{}{} // start long running go routine go func(id int) { defer wg.Done() // do something // release semaphore <-sem }(i) } wg.Wait()
Semaphore
39,776,481
19