Skip to content

Instantly share code, notes, and snippets.

@omniproc
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save omniproc/1dfd41460b45ea17eb71 to your computer and use it in GitHub Desktop.

Select an option

Save omniproc/1dfd41460b45ea17eb71 to your computer and use it in GitHub Desktop.

Revisions

  1. Robert Szymczak renamed this gist Jul 26, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. Robert Szymczak created this gist Jul 5, 2014.
    51 changes: 51 additions & 0 deletions gistfile1.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.HttpURLConnection;

    // This is a very basic implementation of the Docker API v. 1.12 for attaching to a containers StdOut and StdErr stream using HTTP
    // It is not perfect (see official Docker API documentation for details and how to handle the bytestream) but up to this date its
    // the most compleate, working example for this to get an idea what's going on there. Happy about any improvement ideas.

    public class Readin
    {
    // Docker hostname or IP
    private final static String hostname = "";
    // Port that the docker deamon is listening on (API port)
    private final static String port = "4243";
    // The container name or id that we want to attach to
    private final static String container = "";

    private final static Boolean showStdOut = true;
    private final static Boolean showStdErr = false;

    public static void main(String[] args) throws IOException
    {
    // Remember that we will only see output if there is output in the specified container stream (Stdout and/or Stderr)
    URL url = new URL("http://"+hostname+":"+port+"/containers/"+container+"/attach?logs=1&stream=1&stdout="+showStdOut.toString()+"&stderr="+showStdErr.toString()+"&tty=false");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    con.setRequestMethod("POST"); // we have to use post as specified in API v 1.12
    con.setConnectTimeout(0); // since we listen to a stream we want to timeout
    con.setReadTimeout(0); // since we listen to a stream we want to timeout
    con.setUseCaches(false);

    // Quick error checking. See Docker API and the Java HttpURLConnection documentationfor the meaning of the return codes.
    int status = con.getResponseCode();
    System.out.println("Returncode: " + status);

    InputStream stream = null;
    stream = con.getInputStream();

    int b = -1;
    do {
    b = stream.read();
    // We use simple int to char conversion (quick and dirty)
    // Yet it is not perfect, but good enough to get the idea of how to fetch the hijacked HTTP stream of a Docker containers StdOut and StdErr
    System.out.print((char) b);

    } while (b != -1);

    stream.close();
    }
    }