Skip to content

Commit

Permalink
Merge pull request cdapio#15519 from cdapio/CDAP-20933
Browse files Browse the repository at this point in the history
[CDAP-20933] Fix k8s resource name cleaning logic
  • Loading branch information
rmstar authored Jan 17, 2024
2 parents 93f8fe1 + 4576314 commit 2bd5171
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.apache.twill.api.ClassAcceptor;
import org.apache.twill.api.Configs;
import org.apache.twill.api.LocalFile;
Expand Down Expand Up @@ -780,11 +781,17 @@ private String asLabel(String val) {

/**
* Kubernetes names must be lowercase alphanumeric, or '-'. Some are less restrictive, but those
* characters should always be ok.
* characters should always be ok. They should also start and end with an alphanumeric.
*/
private String cleanse(String val, int maxLength) {
@VisibleForTesting
static String cleanse(String val, int maxLength) {
// Replace characters that are not alphanumeric or '=' with '-'
String cleansed = val.replaceAll("[^A-Za-z0-9\\-]", "-").toLowerCase();
return cleansed.length() > maxLength ? cleansed.substring(0, maxLength) : cleansed;
// Truncate to maxLength if needed
cleansed = cleansed.length() > maxLength ? cleansed.substring(0, maxLength) : cleansed;
// Remove leading and trailing '-'
cleansed = StringUtils.stripEnd(cleansed, "-");
return StringUtils.stripStart(cleansed, "-");
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,19 @@ public void testCreatePodSpecSystemNamespaceWithConfigmapOption()
.anyMatch(v -> v.getName().equals("cdap-config-abc-123") && v.getMountPath().equals("/config")));
}

@Test
public void testResourceNameCleanse() {
// Trailing '-' is stripped
Assert.assertEquals("name", KubeTwillPreparer.cleanse("name-1",
5));
// Leading '-' removed
Assert.assertEquals("name", KubeTwillPreparer.cleanse("--name",
6));
// '_' is replaced with '-'
Assert.assertEquals("name-1", KubeTwillPreparer.cleanse("name_1",
6));
}

private static Map<String, String> getTwillConfigs() {
HashMap<String, String> cConf = new HashMap<>();
cConf.put(Configs.Keys.JAVA_RESERVED_MEMORY_MB, "1024");
Expand Down

0 comments on commit 2bd5171

Please sign in to comment.