Skip to content

Instantly share code, notes, and snippets.

@gesellix
Forked from omniproc/dockerlog.java
Last active August 29, 2015 14:11
Show Gist options
  • Save gesellix/34864b23a9eaf821a865 to your computer and use it in GitHub Desktop.
Save gesellix/34864b23a9eaf821a865 to your computer and use it in GitHub Desktop.
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment