use of com.hortonworks.registries.schemaregistry.errors.IncompatibleSchemaException in project registry by hortonworks.
the class SchemaRegistryClient method handleSchemaIdVersionResponse.
private SchemaIdVersion handleSchemaIdVersionResponse(SchemaMetadataInfo schemaMetadataInfo, Response response) throws IncompatibleSchemaException, InvalidSchemaException {
int status = response.getStatus();
String msg = response.readEntity(String.class);
if (status == Response.Status.BAD_REQUEST.getStatusCode() || status == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
CatalogResponse catalogResponse = readCatalogResponse(msg);
if (CatalogResponse.ResponseMessage.INCOMPATIBLE_SCHEMA.getCode() == catalogResponse.getResponseCode()) {
throw new IncompatibleSchemaException(catalogResponse.getResponseMessage());
} else if (CatalogResponse.ResponseMessage.INVALID_SCHEMA.getCode() == catalogResponse.getResponseCode()) {
throw new InvalidSchemaException(catalogResponse.getResponseMessage());
} else {
throw new RuntimeException(catalogResponse.getResponseMessage());
}
}
Integer version = readEntity(msg, Integer.class);
SchemaVersionInfo schemaVersionInfo = doGetSchemaVersionInfo(new SchemaVersionKey(schemaMetadataInfo.getSchemaMetadata().getName(), version));
return new SchemaIdVersion(schemaMetadataInfo.getId(), version, schemaVersionInfo.getId());
}
use of com.hortonworks.registries.schemaregistry.errors.IncompatibleSchemaException in project registry by hortonworks.
the class AvroSchemaRegistryClientTest method testValidationLevels.
@Test
public void testValidationLevels() throws Exception {
SchemaMetadata schemaMetadata = createSchemaMetadata(TEST_NAME_RULE.getMethodName(), SchemaCompatibility.BOTH);
String schemaName = schemaMetadata.getName();
Long id = SCHEMA_REGISTRY_CLIENT.registerSchemaMetadata(schemaMetadata);
SCHEMA_REGISTRY_CLIENT.addSchemaVersion(schemaName, new SchemaVersion(AvroSchemaRegistryClientUtil.getSchema("/schema-1.avsc"), "Initial version of the schema"));
SCHEMA_REGISTRY_CLIENT.addSchemaVersion(schemaName, new SchemaVersion(AvroSchemaRegistryClientUtil.getSchema("/schema-2.avsc"), "Second version of the schema"));
SCHEMA_REGISTRY_CLIENT.addSchemaVersion(schemaName, new SchemaVersion(AvroSchemaRegistryClientUtil.getSchema("/schema-3.avsc"), "Third version of the schema, removes name field"));
try {
SCHEMA_REGISTRY_CLIENT.addSchemaVersion(schemaName, new SchemaVersion(AvroSchemaRegistryClientUtil.getSchema("/schema-4.avsc"), "Forth version of the schema, adds back name field, but different type"));
Assert.fail("Should throw IncompatibleSchemaException as check against all schema's would find name field is not compatible with v1 and v2");
} catch (IncompatibleSchemaException ise) {
// expected
}
SchemaMetadata currentSchemaMetadata = SCHEMA_REGISTRY_CLIENT.getSchemaMetadataInfo(schemaName).getSchemaMetadata();
SchemaMetadata schemaMetadataToUpdateTo = new SchemaMetadata.Builder(currentSchemaMetadata).validationLevel(SchemaValidationLevel.LATEST).build();
SchemaMetadataInfo updatedSchemaMetadata = SCHEMA_REGISTRY_CLIENT.updateSchemaMetadata(schemaName, schemaMetadataToUpdateTo);
Assert.assertEquals(SchemaValidationLevel.LATEST, updatedSchemaMetadata.getSchemaMetadata().getValidationLevel());
try {
SCHEMA_REGISTRY_CLIENT.addSchemaVersion(schemaName, new SchemaVersion(AvroSchemaRegistryClientUtil.getSchema("/schema-4.avsc"), "Forth version of the schema, adds back name field, but different type"));
} catch (IncompatibleSchemaException ise) {
Assert.fail("Should not throw IncompatibleSchemaException as check against only latest schema as such should ignore v1 and v2");
}
}
use of com.hortonworks.registries.schemaregistry.errors.IncompatibleSchemaException in project registry by hortonworks.
the class SchemaVersionLifecycleManager method createSchemaVersion.
private SchemaVersionInfo createSchemaVersion(String schemaBranchName, SchemaMetadata schemaMetadata, Long schemaMetadataId, SchemaVersion schemaVersion) throws IncompatibleSchemaException, InvalidSchemaException, SchemaNotFoundException, SchemaBranchNotFoundException {
Preconditions.checkNotNull(schemaBranchName, "schemaBranchName must not be null");
Preconditions.checkNotNull(schemaMetadataId, "schemaMetadataId must not be null");
String type = schemaMetadata.getType();
if (getSchemaProvider(type) == null) {
throw new UnsupportedSchemaTypeException("Given schema type " + type + " not supported");
}
SchemaBranch schemaBranch = null;
try {
schemaBranch = schemaBranchCache.get(SchemaBranchCache.Key.of(new SchemaBranchKey(schemaBranchName, schemaMetadata.getName())));
} catch (SchemaBranchNotFoundException e) {
// Ignore this error
}
if (schemaBranch == null) {
if (getAllVersions(schemaBranchName, schemaMetadata.getName()).size() != 0)
throw new RuntimeException(String.format("Schema name : '%s' and branch name : '%s' has schema version, yet failed to obtain schema branch instance", schemaMetadata.getName(), schemaBranchName));
}
// generate fingerprint, it parses the schema and checks for semantic validation.
// throws InvalidSchemaException for invalid schemas.
final String fingerprint = getFingerprint(type, schemaVersion.getSchemaText());
final String schemaName = schemaMetadata.getName();
SchemaVersionStorable schemaVersionStorable = new SchemaVersionStorable();
final Long schemaVersionStorableId = storageManager.nextId(schemaVersionStorable.getNameSpace());
schemaVersionStorable.setId(schemaVersionStorableId);
schemaVersionStorable.setSchemaMetadataId(schemaMetadataId);
schemaVersionStorable.setFingerprint(fingerprint);
schemaVersionStorable.setName(schemaName);
schemaVersionStorable.setSchemaText(schemaVersion.getSchemaText());
schemaVersionStorable.setDescription(schemaVersion.getDescription());
schemaVersionStorable.setTimestamp(System.currentTimeMillis());
schemaVersionStorable.setState(DEFAULT_VERSION_STATE.getId());
if (!schemaBranchName.equals(SchemaBranch.MASTER_BRANCH)) {
schemaVersion.setState(SchemaVersionLifecycleStates.INITIATED.getId());
schemaVersion.setStateDetails(null);
}
// take a lock for a schema with same name.
int retryCt = 0;
while (true) {
try {
Integer version = 0;
Byte initialState = schemaVersion.getInitialState();
if (schemaMetadata.isEvolve()) {
// if the given version is added with enabled or initiated state then only check for compatibility
if (SchemaVersionLifecycleStates.ENABLED.getId().equals(initialState) || SchemaVersionLifecycleStates.INITIATED.getId().equals(initialState)) {
CompatibilityResult compatibilityResult = checkCompatibility(schemaBranchName, schemaName, schemaVersion.getSchemaText());
if (!compatibilityResult.isCompatible()) {
String errMsg = String.format("Given schema is not compatible with latest schema versions. \n" + "Error location: [%s] \n" + "Error encountered is: [%s]", compatibilityResult.getErrorLocation(), compatibilityResult.getErrorMessage());
LOG.error(errMsg);
throw new IncompatibleSchemaException(errMsg);
}
}
SchemaVersionInfo latestSchemaVersionInfo = getLatestSchemaVersionInfo(schemaName);
if (latestSchemaVersionInfo != null) {
version = latestSchemaVersionInfo.getVersion();
}
}
schemaVersionStorable.setVersion(version + 1);
storageManager.add(schemaVersionStorable);
updateSchemaVersionState(schemaVersionStorable.getId(), 1, initialState, schemaVersion.getStateDetails());
break;
} catch (StorageException e) {
// optimistic to try the next try would be successful. When retry attempts are exhausted, throw error back to invoker.
if (++retryCt == DEFAULT_RETRY_CT) {
LOG.error("Giving up after retry attempts [{}] while trying to add new version of schema with metadata [{}]", retryCt, schemaMetadata, e);
throw e;
}
LOG.debug("Encountered storage exception while trying to add a new version, attempting again : [{}] with error: [{}]", retryCt, e);
}
}
// fetching this as the ID may have been set by storage manager.
Long schemaInstanceId = schemaVersionStorable.getId();
SchemaBranchVersionMapping schemaBranchVersionMapping = new SchemaBranchVersionMapping(schemaBranch.getId(), schemaInstanceId);
storageManager.add(schemaBranchVersionMapping);
String storableNamespace = new SchemaFieldInfoStorable().getNameSpace();
List<SchemaFieldInfo> schemaFieldInfos = getSchemaProvider(type).generateFields(schemaVersionStorable.getSchemaText());
for (SchemaFieldInfo schemaFieldInfo : schemaFieldInfos) {
final Long fieldInstanceId = storageManager.nextId(storableNamespace);
SchemaFieldInfoStorable schemaFieldInfoStorable = SchemaFieldInfoStorable.fromSchemaFieldInfo(schemaFieldInfo, fieldInstanceId);
schemaFieldInfoStorable.setSchemaInstanceId(schemaInstanceId);
schemaFieldInfoStorable.setTimestamp(System.currentTimeMillis());
storageManager.add(schemaFieldInfoStorable);
}
return schemaVersionStorable.toSchemaVersionInfo();
}
use of com.hortonworks.registries.schemaregistry.errors.IncompatibleSchemaException in project registry by hortonworks.
the class SchemaVersionLifecycleManager method mergeSchemaVersion.
public SchemaVersionMergeResult mergeSchemaVersion(Long schemaVersionId, SchemaVersionMergeStrategy schemaVersionMergeStrategy) throws SchemaNotFoundException, IncompatibleSchemaException {
try {
SchemaVersionInfo schemaVersionInfo = getSchemaVersionInfo(new SchemaIdVersion(schemaVersionId));
SchemaMetadataInfo schemaMetadataInfo = getSchemaMetadataInfo(schemaVersionInfo.getName());
Set<SchemaBranch> schemaBranches = getSchemaBranches(schemaVersionId).stream().filter(schemaBranch -> {
try {
return !getRootVersion(schemaBranch).getId().equals(schemaVersionId);
} catch (SchemaNotFoundException e) {
throw new RuntimeException(e);
}
}).collect(Collectors.toSet());
if (schemaBranches.size() > 1) {
throw new SchemaVersionMergeException(String.format("Can't determine a unique schema branch for schema version id : '%s'", schemaVersionId));
} else if (schemaBranches.size() == 0) {
throw new SchemaVersionMergeException(String.format("Schema version id : '%s' is not associated with any branch", schemaVersionId));
}
Long schemaBranchId = schemaBranches.iterator().next().getId();
SchemaBranch schemaBranch = schemaBranchCache.get(SchemaBranchCache.Key.of(schemaBranchId));
if (schemaVersionMergeStrategy.equals(SchemaVersionMergeStrategy.PESSIMISTIC)) {
SchemaVersionInfo latestSchemaVersion = getLatestEnabledSchemaVersionInfo(SchemaBranch.MASTER_BRANCH, schemaMetadataInfo.getSchemaMetadata().getName());
SchemaVersionInfo rootSchemaVersion = getRootVersion(schemaBranch);
if (!latestSchemaVersion.getId().equals(rootSchemaVersion.getId())) {
throw new SchemaVersionMergeException(String.format("The latest version of '%s' is different from the root version of the branch : '%s'", SchemaBranch.MASTER_BRANCH, schemaMetadataInfo.getSchemaMetadata().getName()));
}
}
byte[] initializedStateDetails;
try {
initializedStateDetails = ObjectMapperUtils.serialize(new InitializedStateDetails(schemaBranch.getName(), schemaVersionInfo.getId()));
} catch (JsonProcessingException e) {
throw new RuntimeException(String.format("Failed to serialize initializedState for %s and %s", schemaBranch.getName(), schemaVersionInfo.getId()));
}
SchemaVersionInfo createdSchemaVersionInfo;
try {
SchemaVersionInfo existingSchemaVersionInfo = findSchemaVersion(SchemaBranch.MASTER_BRANCH, schemaMetadataInfo.getSchemaMetadata().getType(), schemaVersionInfo.getSchemaText(), schemaMetadataInfo.getSchemaMetadata().getName());
if (existingSchemaVersionInfo != null) {
String mergeMessage = String.format("Given version %d is already merged to master with version %d", schemaVersionId, existingSchemaVersionInfo.getVersion());
LOG.info(mergeMessage);
return new SchemaVersionMergeResult(new SchemaIdVersion(schemaMetadataInfo.getId(), existingSchemaVersionInfo.getVersion(), existingSchemaVersionInfo.getId()), mergeMessage);
}
createdSchemaVersionInfo = createSchemaVersion(SchemaBranch.MASTER_BRANCH, schemaMetadataInfo.getSchemaMetadata(), schemaMetadataInfo.getId(), new SchemaVersion(schemaVersionInfo.getSchemaText(), schemaVersionInfo.getDescription(), SchemaVersionLifecycleStates.INITIATED.getId(), initializedStateDetails));
} catch (InvalidSchemaException e) {
throw new SchemaVersionMergeException(String.format("Failed to merge schema version : '%s'", schemaVersionId.toString()), e);
}
Collection<SchemaVersionStateStorable> schemaVersionStates = storageManager.find(SchemaVersionStateStorable.NAME_SPACE, Collections.singletonList(new QueryParam(SchemaVersionStateStorable.SCHEMA_VERSION_ID, schemaVersionId.toString())), Collections.singletonList(OrderByField.of(SchemaVersionStateStorable.SEQUENCE, true)));
if (schemaVersionStates == null || schemaVersionStates.isEmpty()) {
throw new RuntimeException(String.format("The database doesn't have any state transition recorded for the schema version id : '%s'", schemaVersionId));
}
updateSchemaVersionState(createdSchemaVersionInfo.getId(), schemaVersionStates.iterator().next().getSequence(), SchemaVersionLifecycleStates.ENABLED.getId(), null);
String mergeMessage = String.format("Given version %d is merged successfully to master with version %d", schemaVersionId, createdSchemaVersionInfo.getVersion());
LOG.info(mergeMessage);
return new SchemaVersionMergeResult(new SchemaIdVersion(schemaMetadataInfo.getId(), createdSchemaVersionInfo.getVersion(), createdSchemaVersionInfo.getId()), mergeMessage);
} catch (SchemaBranchNotFoundException e) {
throw new SchemaVersionMergeException(String.format("Failed to merge schema version : '%s'", schemaVersionId.toString()), e);
}
}
use of com.hortonworks.registries.schemaregistry.errors.IncompatibleSchemaException in project registry by hortonworks.
the class ConfluentSchemaRegistryCompatibleResource method registerSchemaVersion.
@POST
@Path("/subjects/{subject}/versions")
@ApiOperation(value = "Register a new version of the schema", notes = "Registers the given schema version to schema with subject if the given schemaText is not registered as a version for this schema, " + "and returns respective unique id." + "In case of incompatible schema errors, it throws error message like 'Unable to read schema: <> using schema <>' ", response = Id.class, tags = OPERATION_GROUP_CONFLUENT_SR)
@Timed
@UnitOfWork
public Response registerSchemaVersion(@ApiParam(value = "subject", required = true) @PathParam("subject") String subject, @ApiParam(value = "Details about the schema", required = true) String schema, @Context UriInfo uriInfo) {
LOG.info("registerSchema for [{}] is [{}]", subject);
return handleLeaderAction(uriInfo, () -> {
Response response;
try {
LOG.info("registerSchema for [{}] is [{}]", subject);
SchemaMetadataInfo schemaMetadataInfo = schemaRegistry.getSchemaMetadataInfo(subject);
if (schemaMetadataInfo == null) {
SchemaMetadata schemaMetadata = new SchemaMetadata.Builder(subject).type(AvroSchemaProvider.TYPE).schemaGroup("Kafka").build();
schemaRegistry.addSchemaMetadata(schemaMetadata);
schemaMetadataInfo = schemaRegistry.getSchemaMetadataInfo(subject);
}
SchemaIdVersion schemaVersionInfo = schemaRegistry.addSchemaVersion(schemaMetadataInfo.getSchemaMetadata(), new SchemaVersion(schemaStringFromJson(schema).getSchema(), null));
Id id = new Id();
id.setId(schemaVersionInfo.getSchemaVersionId());
response = WSUtils.respondEntity(id, Response.Status.OK);
} catch (InvalidSchemaException ex) {
LOG.error("Invalid schema error encountered while adding subject [{}]", subject, ex);
response = invalidSchemaError();
} catch (IncompatibleSchemaException ex) {
LOG.error("Incompatible schema error encountered while adding subject [{}]", subject, ex);
response = incompatibleSchemaError();
} catch (UnsupportedSchemaTypeException ex) {
LOG.error("Unsupported schema type encountered while adding subject [{}]", subject, ex);
response = incompatibleSchemaError();
} catch (Exception ex) {
LOG.error("Encountered error while adding subject [{}]", subject, ex);
response = serverError();
}
return response;
});
}
Aggregations