forked from openhab/openhab-addons
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DynamoDBConfig.java
264 lines (237 loc) · 12.1 KB
/
DynamoDBConfig.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
/**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.persistence.dynamodb.internal;
import java.nio.file.Path;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.awscore.retry.AwsRetryPolicy;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFile.Type;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.regions.Region;
/**
* Configuration for DynamoDB connections
*
* If table parameter is specified and is not blank, we use new table schema (ExpectedTableRevision.NEW).
* If tablePrefix parameter is specified and is not blank, we use legacy table schema (ExpectedTableRevision.LEGACY).
* Other cases conservatively set ExpectedTableRevision.MAYBE_LEGACY, detecting the right schema during runtime.
*
*
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class DynamoDBConfig {
public static final String DEFAULT_TABLE_PREFIX = "openhab-";
public static final String DEFAULT_TABLE_NAME = "openhab";
public static final long DEFAULT_READ_CAPACITY_UNITS = 1;
public static final long DEFAULT_WRITE_CAPACITY_UNITS = 1;
private static final Logger LOGGER = LoggerFactory.getLogger(DynamoDBConfig.class);
private long readCapacityUnits;
private long writeCapacityUnits;
private Region region;
private AwsCredentials credentials;
private Optional<RetryPolicy> retryPolicy;
private ExpectedTableSchema tableRevision;
private String table;
private String tablePrefixLegacy;
private @Nullable Integer expireDays;
/**
*
* @param config persistence service configuration
* @return DynamoDB configuration. Returns null in case of configuration errors
*/
public static @Nullable DynamoDBConfig fromConfig(Map<String, Object> config) {
ExpectedTableSchema tableRevision;
try {
String regionName = (String) config.get("region");
if (regionName == null) {
return null;
}
final Region region;
if (Region.regions().stream().noneMatch(r -> r.toString().equals(regionName))) {
LOGGER.warn("Region {} is not matching known regions: {}. The region might not be supported.",
regionName, Region.regions().stream().map(r -> r.toString()).collect(Collectors.joining(", ")));
}
region = Region.of(regionName);
Optional<RetryMode> retryMode = Optional.empty();
AwsCredentials credentials;
String accessKey = (String) config.get("accessKey");
String secretKey = (String) config.get("secretKey");
if (accessKey != null && !accessKey.isBlank() && secretKey != null && !secretKey.isBlank()) {
LOGGER.debug("accessKey and secretKey specified. Using those.");
credentials = AwsBasicCredentials.create(accessKey, secretKey);
} else {
LOGGER.debug("accessKey and/or secretKey blank. Checking profilesConfigFile and profile.");
String profilesConfigFile = (String) config.get("profilesConfigFile");
String profile = (String) config.get("profile");
if (profilesConfigFile == null || profilesConfigFile.isBlank() || profile == null
|| profile.isBlank()) {
LOGGER.error("Specify either 1) accessKey and secretKey; or 2) profilesConfigFile and "
+ "profile for providing AWS credentials");
return null;
}
ProfileFile profileFile = ProfileFile.builder().content(Path.of(profilesConfigFile))
.type(Type.CREDENTIALS).build();
credentials = ProfileCredentialsProvider.builder().profileFile(profileFile).profileName(profile).build()
.resolveCredentials();
retryMode = profileFile.profile(profile).flatMap(p -> p.property(ProfileProperty.RETRY_MODE))
.flatMap(retry_mode -> {
for (RetryMode value : RetryMode.values()) {
if (retry_mode.equalsIgnoreCase(value.name())) {
return Optional.of(value);
}
}
LOGGER.warn(
"Unknown retry_mode '{}' in profile. Ignoring and using SDK default retry mode.",
retry_mode);
return Optional.empty();
});
LOGGER.debug("Retry mode {}", retryMode);
}
String table = (String) config.get("table");
String tablePrefixLegacy;
if (table == null || table.isBlank()) {
// the new parameter 'table' has not been set. Check whether the legacy parameter 'tablePrefix' is set
table = DEFAULT_TABLE_NAME;
tablePrefixLegacy = (String) config.get("tablePrefix");
if (tablePrefixLegacy == null || tablePrefixLegacy.isBlank()) {
LOGGER.debug("Using default table prefix {}", DEFAULT_TABLE_PREFIX);
// No explicit value has been specified for tablePrefix, user could be still using the legacy setup
tableRevision = ExpectedTableSchema.MAYBE_LEGACY;
tablePrefixLegacy = DEFAULT_TABLE_PREFIX;
} else {
// Explicit value for tablePrefix, user certainly prefers LEGACY
tableRevision = ExpectedTableSchema.LEGACY;
}
} else {
tableRevision = ExpectedTableSchema.NEW;
tablePrefixLegacy = DEFAULT_TABLE_PREFIX;
}
final long readCapacityUnits;
String readCapacityUnitsParam = (String) config.get("readCapacityUnits");
if (readCapacityUnitsParam == null || readCapacityUnitsParam.isBlank()) {
readCapacityUnits = DEFAULT_READ_CAPACITY_UNITS;
} else {
readCapacityUnits = Long.parseLong(readCapacityUnitsParam);
}
final long writeCapacityUnits;
String writeCapacityUnitsParam = (String) config.get("writeCapacityUnits");
if (writeCapacityUnitsParam == null || writeCapacityUnitsParam.isBlank()) {
writeCapacityUnits = DEFAULT_WRITE_CAPACITY_UNITS;
} else {
writeCapacityUnits = Long.parseLong(writeCapacityUnitsParam);
}
final @Nullable Integer expireDays;
String expireDaysString = (String) config.get("expireDays");
if (expireDaysString == null || expireDaysString.isBlank()) {
expireDays = null;
} else {
expireDays = Integer.parseInt(expireDaysString);
if (expireDays <= 0) {
LOGGER.error("expireDays should be positive integer or null");
return null;
}
}
switch (tableRevision) {
case NEW:
LOGGER.debug("Using new DynamoDB table schema");
return DynamoDBConfig.newSchema(region, credentials, retryMode.map(AwsRetryPolicy::forRetryMode),
table, readCapacityUnits, writeCapacityUnits, expireDays);
case LEGACY:
LOGGER.warn(
"Using legacy DynamoDB table schema. It is recommended to transition to new schema by defining 'table' parameter and not configuring 'tablePrefix'");
return DynamoDBConfig.legacySchema(region, credentials, retryMode.map(AwsRetryPolicy::forRetryMode),
tablePrefixLegacy, readCapacityUnits, writeCapacityUnits);
case MAYBE_LEGACY:
LOGGER.debug(
"Unclear whether we should use new legacy DynamoDB table schema. It is recommended to explicitly define new 'table' parameter. The correct table schema will be detected at runtime.");
return DynamoDBConfig.maybeLegacySchema(region, credentials,
retryMode.map(AwsRetryPolicy::forRetryMode), table, tablePrefixLegacy, readCapacityUnits,
writeCapacityUnits, expireDays);
default:
throw new IllegalStateException("Unhandled enum. Bug");
}
} catch (Exception e) {
LOGGER.error("Error with configuration: {} {}", e.getClass().getSimpleName(), e.getMessage());
return null;
}
}
private static DynamoDBConfig newSchema(Region region, AwsCredentials credentials,
Optional<RetryPolicy> retryPolicy, String table, long readCapacityUnits, long writeCapacityUnits,
@Nullable Integer expireDays) {
return new DynamoDBConfig(region, credentials, retryPolicy, table, "", ExpectedTableSchema.NEW,
readCapacityUnits, writeCapacityUnits, expireDays);
}
private static DynamoDBConfig legacySchema(Region region, AwsCredentials credentials,
Optional<RetryPolicy> retryPolicy, String tablePrefixLegacy, long readCapacityUnits,
long writeCapacityUnits) {
return new DynamoDBConfig(region, credentials, retryPolicy, "", tablePrefixLegacy, ExpectedTableSchema.LEGACY,
readCapacityUnits, writeCapacityUnits, null);
}
private static DynamoDBConfig maybeLegacySchema(Region region, AwsCredentials credentials,
Optional<RetryPolicy> retryPolicy, String table, String tablePrefixLegacy, long readCapacityUnits,
long writeCapacityUnits, @Nullable Integer expireDays) {
return new DynamoDBConfig(region, credentials, retryPolicy, table, tablePrefixLegacy,
ExpectedTableSchema.MAYBE_LEGACY, readCapacityUnits, writeCapacityUnits, expireDays);
}
private DynamoDBConfig(Region region, AwsCredentials credentials, Optional<RetryPolicy> retryPolicy, String table,
String tablePrefixLegacy, ExpectedTableSchema tableRevision, long readCapacityUnits,
long writeCapacityUnits, @Nullable Integer expireDays) {
this.region = region;
this.credentials = credentials;
this.retryPolicy = retryPolicy;
this.table = table;
this.tablePrefixLegacy = tablePrefixLegacy;
this.tableRevision = tableRevision;
this.readCapacityUnits = readCapacityUnits;
this.writeCapacityUnits = writeCapacityUnits;
this.expireDays = expireDays;
}
public AwsCredentials getCredentials() {
return credentials;
}
public String getTablePrefixLegacy() {
return tablePrefixLegacy;
}
public String getTable() {
return table;
}
public ExpectedTableSchema getTableRevision() {
return tableRevision;
}
public Region getRegion() {
return region;
}
public long getReadCapacityUnits() {
return readCapacityUnits;
}
public long getWriteCapacityUnits() {
return writeCapacityUnits;
}
public Optional<RetryPolicy> getRetryPolicy() {
return retryPolicy;
}
public @Nullable Integer getExpireDays() {
return expireDays;
}
}