简体   繁体   中英

Reconstruct dockerfile from image with java docker client

I'm using docker in java code through java docker client ( https://github.com/docker-java/docker-java ) and I need to analyze what's coming from docker hub by user request starting docker pull operation (it's going to be a service running user-defined code related to computational biology in docker container on cluster remotely). I've found this approach based on ruby: https://github.com/CenturyLinkLabs/dockerfile-from-image/blob/master/dockerfile-from-image.rb

So I'm curious if there is a similar code already implemented in java? I know it looks like laziness and code should be fairly easy to port. But I'm not asking to do it for me. I ask only to check the case it's already done (and tested) by somebody and I don't need to reinvent the wheel in this case.

It looks like nobody could suggest some known solution to it. Here it is in case someone would be interested:

public static List<String> reconstructDockerfile(DockerClient cl, String imageIdOrTag) throws Exception {
    Image img = null;
    Map<String, Image> idToImage = new HashMap<String, Image>();
    for (Image image: cl.listImagesCmd().withShowAll(true).exec()) {
        idToImage.put(image.getId(), image);
        if (image.getId().equals(imageIdOrTag))
            img = image;
        if (image.getRepoTags() != null)
            for (String imageTag : image.getRepoTags())
                if (imageTag.equals(imageIdOrTag))
                    img = image;
    }
    if (img == null)
        throw new IllegalArgumentException("Image id or tag wasn't found: " + imageIdOrTag);
    List<String> cmds = new ArrayList<String>();
    String fromTag = null;
    while (true) {
        InspectImageResponse iir = cl.inspectImageCmd(img.getId()).exec();
        String[] cmd = iir.getContainerConfig().getCmd();
        String cmdLine;
        if (cmd.length == 3 && cmd[0].equals("/bin/sh") && cmd[1].equals("-c")) {
            cmdLine = cmd[2];
            if (cmdLine.startsWith("#(nop) ")) {
                cmdLine = cmdLine.substring(7);
            } else {
                cmdLine = "RUN " + cmdLine;
            }
        } else {
            cmdLine ="Unexpected command format: " + Arrays.asList(cmd);
        }
        cmds.add(0, cmdLine + "    #### ---> " + img.getId());
        String imageId = img.getParentId();
        if (imageId == null || imageId.trim().isEmpty())
            break;
        img = idToImage.get(imageId);
        if (img.getRepoTags().length >= 1 && !img.getRepoTags()[0].equals("<none>:<none>")) {
            fromTag = img.getRepoTags()[0];
            break;
        }
    }
    if (fromTag != null)
        cmds.add(0, "FROM " + fromTag);
    return cmds;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM