├── .editorconfig ├── .github └── workflows │ ├── boot.yml │ ├── ci.yml │ └── release-to-maven-central.yml ├── .gitignore ├── .java-version ├── .license └── license-header.txt ├── LICENSE ├── README.md ├── db-scheduler-log-boot-starter ├── pom.xml └── src │ ├── main │ ├── java │ │ └── io │ │ │ └── rocketbase │ │ │ └── extension │ │ │ └── boot │ │ │ ├── autoconfigure │ │ │ ├── DbSchedulerLogAutoConfiguration.java │ │ │ └── DbSchedulerLogMetricAutoConfiguration.java │ │ │ ├── config │ │ │ └── DbSchedulerLogProperties.java │ │ │ └── package-info.java │ └── resources │ │ └── META-INF │ │ ├── spring.factories │ │ └── spring │ │ └── org.springframework.boot.autoconfigure.AutoConfiguration.imports │ └── test │ ├── java │ └── io │ │ └── rocketbase │ │ └── extension │ │ └── boot │ │ └── DbSchedulerLogAutoConfigurationTest.java │ └── resources │ └── schema.sql ├── db-scheduler-log ├── pom.xml └── src │ ├── main │ └── java │ │ └── io │ │ └── rocketbase │ │ └── extension │ │ ├── ExecutionLog.java │ │ ├── LogRepository.java │ │ ├── jdbc │ │ ├── IdProvider.java │ │ ├── JdbcLogRepository.java │ │ └── Snowflake.java │ │ └── stats │ │ ├── LogStatsMicrometerRegistry.java │ │ └── LogStatsPlainRegistry.java │ └── test │ ├── java │ └── io │ │ └── rocketbase │ │ └── extension │ │ ├── CustomTableNameTest.java │ │ ├── DbUtils.java │ │ ├── EmbeddedPostgresqlExtension.java │ │ └── compatibility │ │ ├── CompatibilityTest.java │ │ ├── MssqlCompatibilityTest.java │ │ ├── MysqlCompatibilityTest.java │ │ ├── NoAutoCommitPostgresqlCompatibilityTest.java │ │ └── Oracle11gCompatibilityTest.java │ └── resources │ ├── container-license-acceptance.txt │ ├── hsql_tables.sql │ ├── io │ └── rocketbase │ │ └── extension │ │ └── postgresql_custom_tablename.sql │ ├── mssql_tables.sql │ ├── mysql_tables.sql │ ├── oracle_tables.sql │ └── postgresql_tables.sql └── pom.xml /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | trim_trailing_whitespace = true 7 | charset = utf-8 8 | 9 | [*.java] 10 | indent_style = space 11 | indent_size = 4 12 | -------------------------------------------------------------------------------- /.github/workflows/boot.yml: -------------------------------------------------------------------------------- 1 | name: spring-boot-compatibility 2 | on: [ push, pull_request ] 3 | jobs: 4 | build: 5 | runs-on: ubuntu-latest 6 | strategy: 7 | matrix: 8 | spring-boot: [ '2.5.14', '2.6.12', '2.7.4', '3.1.0' ] 9 | name: Spring Boot ${{ matrix.spring-boot }} 10 | steps: 11 | - uses: actions/checkout@v3 12 | 13 | - name: Set up Java 14 | uses: actions/setup-java@v3 15 | with: 16 | java-version: '17' 17 | distribution: 'temurin' 18 | cache: 'maven' 19 | 20 | - name: Run Spring Boot tests 21 | run: mvn -B -Dspring-boot.version=${{ matrix.spring-boot }} -PspringBootDevelopment clean test --file pom.xml 22 | env: 23 | TZ: UTC 24 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | on: [push, pull_request] 3 | jobs: 4 | build: 5 | runs-on: ubuntu-latest 6 | strategy: 7 | matrix: 8 | java: [ '8', '11', '17' ] 9 | name: Temurin ${{ matrix.java }} 10 | steps: 11 | - uses: actions/checkout@v3 12 | 13 | - name: Set up Java ${{ matrix.java }} 14 | uses: actions/setup-java@v3 15 | with: 16 | java-version: ${{ matrix.java }} 17 | distribution: 'temurin' 18 | cache: 'maven' 19 | 20 | - name: Run all tests 21 | run: mvn -B -Pcompatibility clean test --file pom.xml 22 | env: 23 | TZ: UTC 24 | -------------------------------------------------------------------------------- /.github/workflows/release-to-maven-central.yml: -------------------------------------------------------------------------------- 1 | name: release-to-maven-central 2 | on: 3 | workflow_dispatch: 4 | inputs: 5 | releaseversion: 6 | description: 'Release version' 7 | required: true 8 | default: '1.0.0' 9 | 10 | jobs: 11 | publish: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - run: | 15 | echo "Release version ${{ github.event.inputs.releaseversion }}!" 16 | 17 | - uses: actions/checkout@v2 18 | 19 | - name: Set up Maven Central Repository 20 | uses: actions/setup-java@v1 21 | with: 22 | java-version: 11 23 | server-id: ossrh 24 | server-username: MAVEN_USERNAME 25 | server-password: MAVEN_PASSWORD 26 | gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} 27 | gpg-passphrase: MAVEN_GPG_PASSPHRASE 28 | 29 | - name: Set projects Maven version to GitHub Action GUI set version 30 | run: mvn versions:set "-DnewVersion=${{ github.event.inputs.releaseversion }}" 31 | 32 | - name: Publish package 33 | run: mvn --batch-mode clean deploy -P release -DskipTests=true 34 | env: 35 | MAVEN_USERNAME: ${{ secrets.OSS_SONATYPE_USERNAME }} 36 | MAVEN_PASSWORD: ${{ secrets.OSS_SONATYPE_PASSWORD }} 37 | MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} 38 | 39 | - name: Create GitHub Release 40 | id: create_release 41 | uses: actions/create-release@v1 42 | env: 43 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 44 | with: 45 | tag_name: ${{ github.event.inputs.releaseversion }} 46 | release_name: ${{ github.event.inputs.releaseversion }} 47 | body: | 48 | New version ${{ github.event.inputs.releaseversion }} published 49 | draft: false 50 | prerelease: false 51 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .idea 3 | target/ 4 | .classpath 5 | .project 6 | .settings/ 7 | dependency-reduced-pom.xml 8 | .terraform 9 | terraform.tfstate* 10 | -------------------------------------------------------------------------------- /.java-version: -------------------------------------------------------------------------------- 1 | 1.8 2 | -------------------------------------------------------------------------------- /.license/license-header.txt: -------------------------------------------------------------------------------- 1 | Copyright (C) Marten Prieß 2 |
3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 |
7 | http://www.apache.org/licenses/LICENSE-2.0 8 |
9 | Unless required by applicable law or agreed to in writing, software
10 | distributed under the License is distributed on an "AS IS" BASIS,
11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | See the License for the specific language governing permissions and
13 | limitations under the License.
14 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # db-scheduler-log
2 |
3 | 
4 | [](https://maven-badges.herokuapp.com/maven-central/io.rocketbase.extension/db-scheduler-log)
5 | [](http://www.apache.org/licenses/LICENSE-2.0.html)
6 |
7 | ## Getting started
8 |
9 | 1. Add maven dependency
10 |
11 | ```xml
12 |
13 |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.rocketbase.extension.boot.autoconfigure;
17 |
18 | import com.github.kagkarlsson.scheduler.boot.autoconfigure.DbSchedulerMetricsAutoConfiguration;
19 | import com.github.kagkarlsson.scheduler.boot.config.DbSchedulerCustomizer;
20 | import com.github.kagkarlsson.scheduler.exceptions.SerializationException;
21 | import com.github.kagkarlsson.scheduler.serializer.Serializer;
22 | import com.github.kagkarlsson.scheduler.stats.StatsRegistry;
23 | import io.rocketbase.extension.LogRepository;
24 | import io.rocketbase.extension.boot.config.DbSchedulerLogProperties;
25 | import io.rocketbase.extension.jdbc.IdProvider;
26 | import io.rocketbase.extension.jdbc.JdbcLogRepository;
27 | import io.rocketbase.extension.jdbc.Snowflake;
28 | import io.rocketbase.extension.stats.LogStatsPlainRegistry;
29 | import org.slf4j.Logger;
30 | import org.slf4j.LoggerFactory;
31 | import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
32 | import org.springframework.boot.autoconfigure.AutoConfigureAfter;
33 | import org.springframework.boot.autoconfigure.AutoConfigureBefore;
34 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
35 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
36 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
37 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
38 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
39 | import org.springframework.boot.context.properties.EnableConfigurationProperties;
40 | import org.springframework.context.annotation.Bean;
41 | import org.springframework.context.annotation.Configuration;
42 | import org.springframework.core.ConfigurableObjectInputStream;
43 |
44 | import javax.sql.DataSource;
45 | import java.io.*;
46 | import java.util.Objects;
47 |
48 | @Configuration
49 | @EnableConfigurationProperties(DbSchedulerLogProperties.class)
50 | @AutoConfigurationPackage
51 | @AutoConfigureAfter({
52 | DataSourceAutoConfiguration.class,
53 | })
54 | @AutoConfigureBefore({
55 | DbSchedulerMetricsAutoConfiguration.class,
56 | })
57 | @ConditionalOnBean(DataSource.class)
58 | @ConditionalOnProperty(value = "db-scheduler-log.enabled", matchIfMissing = true)
59 | public class DbSchedulerLogAutoConfiguration {
60 | private static final Logger log = LoggerFactory.getLogger(DbSchedulerLogAutoConfiguration.class);
61 | private final DbSchedulerLogProperties config;
62 | private final DataSource existingDataSource;
63 |
64 | public DbSchedulerLogAutoConfiguration(DbSchedulerLogProperties dbSchedulerLogProperties,
65 | DataSource dataSource) {
66 | this.config = Objects.requireNonNull(dbSchedulerLogProperties, "Can't configure db-scheduler-log without required configuration");
67 | this.existingDataSource = Objects.requireNonNull(dataSource, "An existing javax.sql.DataSource is required");
68 | }
69 |
70 | @ConditionalOnMissingBean(LogRepository.class)
71 | @Bean
72 | LogRepository logRepository(DbSchedulerCustomizer customizer, IdProvider idProvider) {
73 | log.debug("Missing LogRepository bean in context, creating a JdbcLogRepository");
74 | return new JdbcLogRepository(existingDataSource, customizer.serializer().orElse(SPRING_JAVA_SERIALIZER), config.getTableName(), idProvider);
75 | }
76 |
77 | @ConditionalOnMissingBean(IdProvider.class)
78 | @Bean
79 | IdProvider idProvider() {
80 | log.debug("Missing IdProvider bean in context, creating a Snowflake");
81 | return new Snowflake();
82 | }
83 |
84 |
85 | @ConditionalOnMissingClass("io.micrometer.core.instrument.MeterRegistry")
86 | @ConditionalOnMissingBean(StatsRegistry.class)
87 | @Bean
88 | StatsRegistry plainLogStatsRegistry(LogRepository logRepository) {
89 | log.debug("No Spring Boot Actuator / Micrometer has been detected. Will use: {} for StatsRegistry", logRepository.getClass().getName());
90 | return new LogStatsPlainRegistry(logRepository);
91 | }
92 |
93 | /**
94 | * {@link Serializer} compatible with Spring Boot Devtools.
95 | *
96 | * @see
98 | * Devtools known limitations
99 | */
100 | private static final Serializer SPRING_JAVA_SERIALIZER = new Serializer() {
101 |
102 | public byte[] serialize(Object data) {
103 | if (data == null)
104 | return null;
105 | try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
106 | ObjectOutput out = new ObjectOutputStream(bos)) {
107 | out.writeObject(data);
108 | return bos.toByteArray();
109 | } catch (Exception e) {
110 | throw new SerializationException("Failed to serialize object", e);
111 | }
112 | }
113 |
114 | public
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.rocketbase.extension.boot.autoconfigure;
17 |
18 | import com.github.kagkarlsson.scheduler.boot.autoconfigure.DbSchedulerMetricsAutoConfiguration;
19 | import com.github.kagkarlsson.scheduler.stats.StatsRegistry;
20 | import com.github.kagkarlsson.scheduler.task.Task;
21 | import io.micrometer.core.instrument.MeterRegistry;
22 | import io.rocketbase.extension.LogRepository;
23 | import io.rocketbase.extension.stats.LogStatsMicrometerRegistry;
24 | import org.slf4j.Logger;
25 | import org.slf4j.LoggerFactory;
26 | import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration;
27 | import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
28 | import org.springframework.boot.autoconfigure.AutoConfigureAfter;
29 | import org.springframework.boot.autoconfigure.AutoConfigureBefore;
30 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
31 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
32 | import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
33 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
34 | import org.springframework.context.annotation.Bean;
35 | import org.springframework.context.annotation.Configuration;
36 |
37 | import java.util.List;
38 |
39 | @Configuration
40 | @ConditionalOnClass({
41 | MetricsAutoConfiguration.class,
42 | CompositeMeterRegistryAutoConfiguration.class,
43 | })
44 | @AutoConfigureAfter({
45 | MetricsAutoConfiguration.class,
46 | CompositeMeterRegistryAutoConfiguration.class,
47 | DbSchedulerLogAutoConfiguration.class
48 | })
49 | @AutoConfigureBefore(DbSchedulerMetricsAutoConfiguration.class)
50 | @ConditionalOnProperty(value = "db-scheduler-log.enabled", matchIfMissing = true)
51 | public class DbSchedulerLogMetricAutoConfiguration {
52 | private static final Logger log = LoggerFactory.getLogger(DbSchedulerLogMetricAutoConfiguration.class);
53 | private final List
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.rocketbase.extension.boot.config;
17 |
18 | import io.rocketbase.extension.jdbc.JdbcLogRepository;
19 | import org.springframework.boot.context.properties.ConfigurationProperties;
20 |
21 | @ConfigurationProperties("db-scheduler-log")
22 | public class DbSchedulerLogProperties {
23 | /**
24 | * Whether to enable auto configuration of the db-scheduler-log.
25 | */
26 | private boolean enabled = true;
27 |
28 | /**
29 | * Name of the table used to log executions. Must match the database. Change name in the
30 | * table definitions accordingly when creating or modifying the table.
31 | */
32 | private String tableName = JdbcLogRepository.DEFAULT_TABLE_NAME;
33 |
34 | public boolean isEnabled() {
35 | return enabled;
36 | }
37 |
38 | public void setEnabled(final boolean enabled) {
39 | this.enabled = enabled;
40 | }
41 |
42 | public String getTableName() {
43 | return tableName;
44 | }
45 |
46 | public void setTableName(final String tableName) {
47 | this.tableName = tableName;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/db-scheduler-log-boot-starter/src/main/java/io/rocketbase/extension/boot/package-info.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) Marten Prieß
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | /**
17 | * Spring Boot related autoconfiguration and glue code.
18 | */
19 | package io.rocketbase.extension.boot;
20 |
--------------------------------------------------------------------------------
/db-scheduler-log-boot-starter/src/main/resources/META-INF/spring.factories:
--------------------------------------------------------------------------------
1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
2 | io.rocketbase.extension.boot.autoconfigure.DbSchedulerLogAutoConfiguration,\
3 | io.rocketbase.extension.boot.autoconfigure.DbSchedulerLogMetricAutoConfiguration
4 |
--------------------------------------------------------------------------------
/db-scheduler-log-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports:
--------------------------------------------------------------------------------
1 | io.rocketbase.extension.boot.autoconfigure.DbSchedulerLogAutoConfiguration
2 | io.rocketbase.extension.boot.autoconfigure.DbSchedulerLogMetricAutoConfiguration
3 |
--------------------------------------------------------------------------------
/db-scheduler-log-boot-starter/src/test/java/io/rocketbase/extension/boot/DbSchedulerLogAutoConfigurationTest.java:
--------------------------------------------------------------------------------
1 | package io.rocketbase.extension.boot;
2 |
3 | import com.github.kagkarlsson.scheduler.boot.autoconfigure.DbSchedulerActuatorAutoConfiguration;
4 | import com.github.kagkarlsson.scheduler.boot.autoconfigure.DbSchedulerAutoConfiguration;
5 | import com.github.kagkarlsson.scheduler.boot.autoconfigure.DbSchedulerMetricsAutoConfiguration;
6 | import com.github.kagkarlsson.scheduler.stats.StatsRegistry;
7 | import io.rocketbase.extension.LogRepository;
8 | import io.rocketbase.extension.boot.autoconfigure.DbSchedulerLogAutoConfiguration;
9 | import io.rocketbase.extension.boot.autoconfigure.DbSchedulerLogMetricAutoConfiguration;
10 | import io.rocketbase.extension.jdbc.IdProvider;
11 | import io.rocketbase.extension.stats.LogStatsMicrometerRegistry;
12 | import org.junit.jupiter.api.Test;
13 | import org.slf4j.Logger;
14 | import org.slf4j.LoggerFactory;
15 | import org.springframework.boot.actuate.autoconfigure.health.HealthContributorAutoConfiguration;
16 | import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration;
17 | import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
18 | import org.springframework.boot.autoconfigure.AutoConfigurations;
19 | import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
20 | import org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration;
21 | import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
22 | import org.springframework.boot.test.context.runner.ApplicationContextRunner;
23 |
24 | import javax.sql.DataSource;
25 |
26 | import static org.assertj.core.api.Assertions.assertThat;
27 |
28 |
29 | public class DbSchedulerLogAutoConfigurationTest {
30 | private static final Logger log = LoggerFactory.getLogger(DbSchedulerLogAutoConfigurationTest.class);
31 | private final ApplicationContextRunner ctxRunner;
32 |
33 | public DbSchedulerLogAutoConfigurationTest() {
34 | ctxRunner = new ApplicationContextRunner()
35 | .withPropertyValues(
36 | "spring.application.name=db-scheduler-boot-starter-test",
37 | "spring.profiles.active=integration-test"
38 | ).withConfiguration(AutoConfigurations.of(
39 | DataSourceAutoConfiguration.class,
40 | SqlInitializationAutoConfiguration.class,
41 | MetricsAutoConfiguration.class,
42 | CompositeMeterRegistryAutoConfiguration.class,
43 | HealthContributorAutoConfiguration.class,
44 | DbSchedulerMetricsAutoConfiguration.class,
45 | DbSchedulerActuatorAutoConfiguration.class,
46 | DbSchedulerAutoConfiguration.class,
47 | DbSchedulerLogMetricAutoConfiguration.class,
48 | DbSchedulerLogAutoConfiguration.class
49 | ));
50 | }
51 |
52 | @Test
53 | public void it_should_initialize() {
54 | ctxRunner.run((AssertableApplicationContext ctx) -> {
55 | assertThat(ctx).hasSingleBean(DataSource.class);
56 | assertThat(ctx).hasSingleBean(LogRepository.class);
57 | assertThat(ctx).hasSingleBean(IdProvider.class);
58 | assertThat(ctx).hasSingleBean(StatsRegistry.class);
59 |
60 | assertThat(ctx.getBean(StatsRegistry.class)).isInstanceOf(LogStatsMicrometerRegistry.class);
61 | });
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/db-scheduler-log-boot-starter/src/test/resources/schema.sql:
--------------------------------------------------------------------------------
1 | create table if not exists scheduled_tasks (
2 | task_name varchar(100),
3 | task_instance varchar(100),
4 | task_data blob,
5 | execution_time TIMESTAMP WITH TIME ZONE,
6 | picked BIT,
7 | picked_by varchar(50),
8 | last_success TIMESTAMP WITH TIME ZONE,
9 | last_failure TIMESTAMP WITH TIME ZONE,
10 | consecutive_failures INT,
11 | last_heartbeat TIMESTAMP WITH TIME ZONE,
12 | version BIGINT,
13 | PRIMARY KEY (task_name, task_instance)
14 | );
15 |
--------------------------------------------------------------------------------
/db-scheduler-log/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.rocketbase.extension;
17 |
18 | import com.github.kagkarlsson.scheduler.task.ExecutionComplete;
19 | import com.github.kagkarlsson.scheduler.task.TaskInstance;
20 |
21 | import java.time.Instant;
22 | import java.util.Objects;
23 |
24 | public final class ExecutionLog {
25 |
26 | public final TaskInstance taskInstance;
27 | public final String pickedBy;
28 | public final Instant timeStarted;
29 | public final Instant timeFinished;
30 | public final boolean succeeded;
31 | public final Throwable cause;
32 |
33 | public ExecutionLog(ExecutionComplete exec) {
34 | taskInstance = exec.getExecution().taskInstance;
35 | pickedBy = exec.getExecution().pickedBy;
36 | timeStarted = exec.getTimeDone().minus(exec.getDuration());
37 | timeFinished = exec.getTimeDone();
38 | succeeded = ExecutionComplete.Result.OK.equals(exec.getResult());
39 | cause = exec.getCause().orElse(null);
40 | }
41 |
42 | @Override
43 | public boolean equals(Object o) {
44 | if (this == o) return true;
45 | if (o == null || getClass() != o.getClass()) return false;
46 | ExecutionLog execLog = (ExecutionLog) o;
47 | return Objects.equals(timeStarted, execLog.timeStarted) &&
48 | Objects.equals(timeFinished, execLog.timeFinished) &&
49 | Objects.equals(taskInstance, execLog.taskInstance);
50 | }
51 |
52 |
53 | @Override
54 | public int hashCode() {
55 | return Objects.hash(timeStarted, timeFinished, taskInstance);
56 | }
57 |
58 | @Override
59 | public String toString() {
60 | return "ExecutionLog: " +
61 | "task=" + taskInstance.getTaskName() +
62 | ", id=" + taskInstance.getId() +
63 | ", pickedBy=" + pickedBy +
64 | ", timeStarted=" + timeStarted +
65 | ", timeFinished=" + timeFinished +
66 | ", succeeded=" + succeeded;
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/db-scheduler-log/src/main/java/io/rocketbase/extension/LogRepository.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) Marten Prieß
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.rocketbase.extension;
17 |
18 | public interface LogRepository {
19 | boolean createIfNotExists(ExecutionLog log);
20 | }
21 |
--------------------------------------------------------------------------------
/db-scheduler-log/src/main/java/io/rocketbase/extension/jdbc/IdProvider.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) Marten Prieß
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.rocketbase.extension.jdbc;
17 |
18 | public interface IdProvider {
19 |
20 | long nextId();
21 | }
22 |
--------------------------------------------------------------------------------
/db-scheduler-log/src/main/java/io/rocketbase/extension/jdbc/JdbcLogRepository.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) Marten Prieß
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.rocketbase.extension.jdbc;
17 |
18 | import com.github.kagkarlsson.jdbc.JdbcRunner;
19 | import com.github.kagkarlsson.jdbc.SQLRuntimeException;
20 | import com.github.kagkarlsson.scheduler.jdbc.AutodetectJdbcCustomization;
21 | import com.github.kagkarlsson.scheduler.jdbc.JdbcCustomization;
22 | import com.github.kagkarlsson.scheduler.serializer.Serializer;
23 | import io.rocketbase.extension.ExecutionLog;
24 | import io.rocketbase.extension.LogRepository;
25 | import org.slf4j.Logger;
26 | import org.slf4j.LoggerFactory;
27 |
28 | import javax.sql.DataSource;
29 | import java.io.NotSerializableException;
30 | import java.io.PrintWriter;
31 | import java.io.StringWriter;
32 | import java.sql.PreparedStatement;
33 | import java.time.Duration;
34 |
35 | public class JdbcLogRepository implements LogRepository {
36 |
37 | public static final String DEFAULT_TABLE_NAME = "scheduled_execution_logs";
38 |
39 | private static final Logger LOG = LoggerFactory.getLogger(JdbcLogRepository.class);
40 | private final JdbcRunner jdbcRunner;
41 | private final Serializer serializer;
42 | private final String tableName;
43 | private final JdbcCustomization jdbcCustomization;
44 | private final IdProvider idProvider;
45 |
46 |
47 | public JdbcLogRepository(DataSource dataSource, Serializer serializer, String tableName, IdProvider idProvider) {
48 | this(tableName, new JdbcRunner(dataSource, true), serializer, new AutodetectJdbcCustomization(dataSource), idProvider);
49 | }
50 |
51 | public JdbcLogRepository(String tableName, JdbcRunner jdbcRunner, Serializer serializer, JdbcCustomization jdbcCustomization, IdProvider idProvider) {
52 | this.tableName = tableName;
53 | this.jdbcRunner = jdbcRunner;
54 | this.serializer = serializer;
55 | this.jdbcCustomization = jdbcCustomization;
56 | this.idProvider = idProvider;
57 | }
58 |
59 | @Override
60 | @SuppressWarnings({"unchecked"})
61 | public boolean createIfNotExists(ExecutionLog log) {
62 | try {
63 | jdbcRunner.execute(
64 | "insert into " + tableName + "(id, task_name, task_instance, task_data, picked_by, time_started, time_finished, succeeded, duration_ms, exception_class, exception_message, exception_stacktrace) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
65 | (PreparedStatement p) -> {
66 | p.setLong(1, idProvider.nextId());
67 | p.setString(2, log.taskInstance.getTaskName());
68 | p.setString(3, log.taskInstance.getId());
69 | p.setObject(4, serialize(log.taskInstance.getData()));
70 | p.setString(5, log.pickedBy);
71 | jdbcCustomization.setInstant(p, 6, log.timeStarted);
72 | jdbcCustomization.setInstant(p, 7, log.timeFinished);
73 | p.setBoolean(8, log.succeeded);
74 | p.setLong(9, Duration.between(log.timeStarted, log.timeFinished).toMillis());
75 | p.setString(10, log.cause != null ? log.cause.getClass().getName() : null);
76 | p.setString(11, log.cause != null ? log.cause.getMessage() : null);
77 | p.setString(12, getStacktrace(log.cause));
78 | });
79 | return true;
80 | } catch (SQLRuntimeException e) {
81 | LOG.error("Exception when inserting execution-log. Assuming it to be a constraint violation: {}", e.getMessage());
82 | return false;
83 | }
84 | }
85 |
86 | protected String getStacktrace(Throwable cause) {
87 | if (cause == null) {
88 | return null;
89 | }
90 | StringWriter writer = new StringWriter();
91 | PrintWriter out = new PrintWriter(writer);
92 | cause.printStackTrace(out);
93 | return writer.toString();
94 | }
95 |
96 | protected byte[] serialize(Object value) {
97 | if (serializer == null || value == null) {
98 | return null;
99 | }
100 | try {
101 | return serializer.serialize(value);
102 | } catch (Exception e) {
103 | if (e instanceof NotSerializableException) {
104 | LOG.warn("object is not serializable - you need to add Serializable");
105 | } else {
106 | LOG.error("serialization failed for {} -> {}", value.getClass(), e.getMessage());
107 | }
108 | return null;
109 | }
110 | }
111 |
112 | }
113 |
--------------------------------------------------------------------------------
/db-scheduler-log/src/main/java/io/rocketbase/extension/jdbc/Snowflake.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) Marten Prieß
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.rocketbase.extension.jdbc;
17 |
18 | import com.github.kagkarlsson.scheduler.SchedulerName;
19 |
20 | import java.security.SecureRandom;
21 | import java.time.Instant;
22 |
23 | /**
24 | * @author callicoder: https://github.com/callicoder/java-snowflake
25 | *
26 | * Distributed Sequence Generator.
27 | * Inspired by Twitter snowflake: https://github.com/twitter/snowflake/tree/snowflake-2010
28 | *
29 | * This class should be used as a Singleton.
30 | * Make sure that you create and reuse a Single instance of Snowflake per node in your distributed system cluster.
31 | */
32 | public final class Snowflake implements IdProvider {
33 |
34 | private static Snowflake INSTANCE;
35 |
36 | public static final int UNUSED_BITS = 1; // Sign bit, Unused (always set to 0)
37 | public static final int EPOCH_BITS = 43;
38 | public static final int NODE_ID_BITS = 10;
39 | public static final int SEQUENCE_BITS = 10;
40 |
41 | public static final long maxNodeId = (1L << NODE_ID_BITS) - 1;
42 | public static final long maxSequence = (1L << SEQUENCE_BITS) - 1;
43 |
44 | // Custom Epoch (January 1, 2020 Midnight UTC = 2020-01-01T00:00:00Z)
45 | public static final long DEFAULT_CUSTOM_EPOCH = 1577836800000L;
46 |
47 | private final long nodeId;
48 | private final long customEpoch;
49 |
50 | private volatile long lastTimestamp = -1L;
51 | private volatile long sequence = 0L;
52 |
53 | // Create Snowflake with a nodeId and custom epoch
54 | public Snowflake(long nodeId, long customEpoch) {
55 | if (nodeId < 0 || nodeId > maxNodeId) {
56 | throw new IllegalArgumentException(String.format("NodeId must be between %d and %d", 0, maxNodeId));
57 | }
58 | this.nodeId = nodeId;
59 | this.customEpoch = customEpoch;
60 | }
61 |
62 | // Create Snowflake with a nodeId
63 | public Snowflake(long nodeId) {
64 | this(nodeId, DEFAULT_CUSTOM_EPOCH);
65 | }
66 |
67 | // Let Snowflake generate a nodeId
68 | public Snowflake() {
69 | this.nodeId = createNodeId();
70 | this.customEpoch = DEFAULT_CUSTOM_EPOCH;
71 | }
72 |
73 | public static Snowflake getInstance() {
74 | if (INSTANCE == null) {
75 | INSTANCE = new Snowflake();
76 | }
77 | return INSTANCE;
78 | }
79 |
80 | public synchronized long nextId() {
81 | long currentTimestamp = timestamp();
82 |
83 | if (currentTimestamp < lastTimestamp) {
84 | throw new IllegalStateException("Invalid System Clock!");
85 | }
86 |
87 | if (currentTimestamp == lastTimestamp) {
88 | sequence = (sequence + 1) & maxSequence;
89 | if (sequence == 0) {
90 | // Sequence Exhausted, wait till next millisecond.
91 | currentTimestamp = waitNextMillis(currentTimestamp);
92 | }
93 | } else {
94 | // reset sequence to start with zero for the next millisecond
95 | sequence = 0;
96 | }
97 |
98 | lastTimestamp = currentTimestamp;
99 |
100 | long id = currentTimestamp << (NODE_ID_BITS + SEQUENCE_BITS)
101 | | (nodeId << SEQUENCE_BITS)
102 | | sequence;
103 |
104 | return id;
105 | }
106 |
107 |
108 | // Get current timestamp in milliseconds, adjust for the custom epoch.
109 | private long timestamp() {
110 | return Instant.now().toEpochMilli() - customEpoch;
111 | }
112 |
113 | // Block and wait till next millisecond
114 | private long waitNextMillis(long currentTimestamp) {
115 | while (currentTimestamp == lastTimestamp) {
116 | currentTimestamp = timestamp();
117 | }
118 | return currentTimestamp;
119 | }
120 |
121 | private long createNodeId() {
122 | long nodeId;
123 | try {
124 | nodeId = new SchedulerName.Hostname().hashCode();
125 | } catch (Exception ex) {
126 | nodeId = (new SecureRandom().nextInt());
127 | }
128 | nodeId = nodeId & maxNodeId;
129 | return nodeId;
130 | }
131 |
132 | public long[] parse(long id) {
133 | long maskNodeId = ((1L << NODE_ID_BITS) - 1) << SEQUENCE_BITS;
134 | long maskSequence = (1L << SEQUENCE_BITS) - 1;
135 |
136 | long timestamp = (id >> (NODE_ID_BITS + SEQUENCE_BITS)) + customEpoch;
137 | long nodeId = (id & maskNodeId) >> SEQUENCE_BITS;
138 | long sequence = id & maskSequence;
139 |
140 | return new long[]{timestamp, nodeId, sequence};
141 | }
142 |
143 | @Override
144 | public String toString() {
145 | return "Snowflake Settings [EPOCH_BITS=" + EPOCH_BITS + ", NODE_ID_BITS=" + NODE_ID_BITS
146 | + ", SEQUENCE_BITS=" + SEQUENCE_BITS + ", CUSTOM_EPOCH=" + customEpoch
147 | + ", NodeId=" + nodeId + "]";
148 | }
149 | }
150 |
--------------------------------------------------------------------------------
/db-scheduler-log/src/main/java/io/rocketbase/extension/stats/LogStatsMicrometerRegistry.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) Marten Prieß
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.rocketbase.extension.stats;
17 |
18 | import com.github.kagkarlsson.scheduler.stats.MicrometerStatsRegistry;
19 | import com.github.kagkarlsson.scheduler.task.ExecutionComplete;
20 | import com.github.kagkarlsson.scheduler.task.Task;
21 | import io.micrometer.core.instrument.MeterRegistry;
22 | import io.rocketbase.extension.ExecutionLog;
23 | import io.rocketbase.extension.LogRepository;
24 |
25 | import java.util.List;
26 | import java.util.concurrent.ExecutorService;
27 | import java.util.concurrent.Executors;
28 |
29 | public class LogStatsMicrometerRegistry extends MicrometerStatsRegistry {
30 |
31 | private final LogRepository logRepository;
32 | private ExecutorService executorService;
33 |
34 | public LogStatsMicrometerRegistry(MeterRegistry meterRegistry, List extends Task>> expectedTasks, LogRepository logRepository) {
35 | super(meterRegistry, expectedTasks);
36 | this.logRepository = logRepository;
37 | this.executorService = Executors.newFixedThreadPool(5);
38 | }
39 |
40 | @Override
41 | public void registerSingleCompletedExecution(ExecutionComplete completeEvent) {
42 | super.registerSingleCompletedExecution(completeEvent);
43 |
44 | executorService.submit(() -> {
45 | logRepository.createIfNotExists(new ExecutionLog(completeEvent));
46 | });
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/db-scheduler-log/src/main/java/io/rocketbase/extension/stats/LogStatsPlainRegistry.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) Marten Prieß
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package io.rocketbase.extension.stats;
17 |
18 | import com.github.kagkarlsson.scheduler.stats.StatsRegistry;
19 | import com.github.kagkarlsson.scheduler.task.ExecutionComplete;
20 | import io.rocketbase.extension.ExecutionLog;
21 | import io.rocketbase.extension.LogRepository;
22 |
23 | import java.util.concurrent.ExecutorService;
24 | import java.util.concurrent.Executors;
25 |
26 | public class LogStatsPlainRegistry implements StatsRegistry {
27 |
28 | private final LogRepository logRepository;
29 | private ExecutorService executorService;
30 |
31 | public LogStatsPlainRegistry(LogRepository logRepository) {
32 | this.logRepository = logRepository;
33 | this.executorService = Executors.newFixedThreadPool(5);
34 | }
35 |
36 | @Override
37 | public void register(SchedulerStatsEvent e) {
38 | }
39 |
40 | @Override
41 | public void register(CandidateStatsEvent e) {
42 | }
43 |
44 | @Override
45 | public void register(ExecutionStatsEvent e) {
46 | }
47 |
48 | @Override
49 | public void registerSingleCompletedExecution(ExecutionComplete completeEvent) {
50 | executorService.submit(() -> {
51 | logRepository.createIfNotExists(new ExecutionLog(completeEvent));
52 | });
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/db-scheduler-log/src/test/java/io/rocketbase/extension/CustomTableNameTest.java:
--------------------------------------------------------------------------------
1 | package io.rocketbase.extension;
2 |
3 | import com.github.kagkarlsson.jdbc.JdbcRunner;
4 | import com.github.kagkarlsson.jdbc.RowMapper;
5 | import com.github.kagkarlsson.scheduler.serializer.JavaSerializer;
6 | import com.github.kagkarlsson.scheduler.task.Execution;
7 | import com.github.kagkarlsson.scheduler.task.ExecutionComplete;
8 | import com.github.kagkarlsson.scheduler.task.TaskInstance;
9 | import io.rocketbase.extension.compatibility.CompatibilityTest;
10 | import io.rocketbase.extension.jdbc.JdbcLogRepository;
11 | import io.rocketbase.extension.jdbc.Snowflake;
12 | import org.junit.jupiter.api.AfterEach;
13 | import org.junit.jupiter.api.BeforeEach;
14 | import org.junit.jupiter.api.Test;
15 | import org.junit.jupiter.api.extension.RegisterExtension;
16 |
17 | import java.time.Instant;
18 |
19 | import static com.github.kagkarlsson.jdbc.PreparedStatementSetter.NOOP;
20 | import static java.time.temporal.ChronoUnit.MILLIS;
21 |
22 | public class CustomTableNameTest {
23 |
24 | private static final String CUSTOM_TABLENAME = "custom_tablename_logs";
25 |
26 | @RegisterExtension
27 | public EmbeddedPostgresqlExtension DB = new EmbeddedPostgresqlExtension();
28 |
29 | private JdbcLogRepository logRepository;
30 |
31 | @BeforeEach
32 | public void setUp() {
33 | logRepository = new JdbcLogRepository(DB.getDataSource(), new JavaSerializer(), CUSTOM_TABLENAME, new Snowflake());
34 |
35 | DbUtils.runSqlResource("postgresql_custom_tablename.sql").accept(DB.getDataSource());
36 | }
37 |
38 | @Test
39 | public void can_customize_table_name() {
40 | Instant now = Instant.now().truncatedTo(MILLIS);
41 | final Execution execution = new Execution(now, new TaskInstance("taskName", "213456", new CompatibilityTest.SampleData("sample", 1234L)), true, "pickedBy", now, now, 0, now, 1);
42 | final ExecutionComplete complete = ExecutionComplete.success(execution, now.minusMillis(10_000), now);
43 |
44 |
45 | logRepository.createIfNotExists(new ExecutionLog(complete));
46 |
47 | JdbcRunner jdbcRunner = new JdbcRunner(DB.getDataSource());
48 | jdbcRunner.query("SELECT count(1) AS number_of_tasks FROM " + CUSTOM_TABLENAME, NOOP, (RowMapper