diff --git a/elasticsearch/src/main/java/org/elasticsearch/xpack/prelert/job/Job.java b/elasticsearch/src/main/java/org/elasticsearch/xpack/prelert/job/Job.java index 3454cd9559c..39cc2bd4285 100644 --- a/elasticsearch/src/main/java/org/elasticsearch/xpack/prelert/job/Job.java +++ b/elasticsearch/src/main/java/org/elasticsearch/xpack/prelert/job/Job.java @@ -693,7 +693,16 @@ public class Job extends AbstractDiffable implements Writeable, ToXContent Date lastDataTime; String modelSnapshotId; if (fromApi) { - id = this.id == null ? UUIDs.base64UUID().toLowerCase(Locale.ROOT): this.id; + if (this.id != null) { + id = this.id; + } else { + // Base64 UUIDs are not necessarily valid job IDs + id = "auto-" + UUIDs.base64UUID().toLowerCase(Locale.ROOT).replaceAll("/\\+=", "_"); + if (id.endsWith("_")) { + // Job IDs cannot end with underscores + id = id.substring(0, id.length() - 1) + "z"; + } + } createTime = this.createTime == null ? new Date() : this.createTime; finishedTime = null; lastDataTime = null; diff --git a/elasticsearch/src/test/java/org/elasticsearch/xpack/prelert/job/JobTests.java b/elasticsearch/src/test/java/org/elasticsearch/xpack/prelert/job/JobTests.java index 54af4355c95..434021f3c05 100644 --- a/elasticsearch/src/test/java/org/elasticsearch/xpack/prelert/job/JobTests.java +++ b/elasticsearch/src/test/java/org/elasticsearch/xpack/prelert/job/JobTests.java @@ -82,6 +82,12 @@ public class JobTests extends AbstractSerializingTestCase { assertNotNull(buildJobBuilder(null).build(true).getId()); // test auto id generation } + public void testNoIdStartsWithAuto() { + String autoId = buildJobBuilder(null).build(true).getId(); + assertTrue(autoId, autoId.startsWith("auto-")); + assertFalse(autoId, autoId.endsWith("_")); + } + public void testEquals_GivenDifferentClass() { Job job = buildJobBuilder("foo").build(); assertFalse(job.equals("a string"));