Skip to content

Instantly share code, notes, and snippets.

@hashbrowncipher
Created January 10, 2019 22:14
Show Gist options
  • Save hashbrowncipher/a6322891101157f148541b35885a7850 to your computer and use it in GitHub Desktop.
Save hashbrowncipher/a6322891101157f148541b35885a7850 to your computer and use it in GitHub Desktop.
a java PoC for launching threads into CGroups
import java.io.IOException;
import java.lang.Runnable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
public class CGroupThreads {
static class CGThread extends Thread {
private final String cgroupName;
private int osId;
public CGThread(String cgroupName, Runnable r) {
super(r);
this.cgroupName = cgroupName;
}
public void run() {
try {
setup();
} catch(IOException e) {
throw new RuntimeException(e);
}
super.run();
}
private void setup() throws IOException {
String tid = Files.readSymbolicLink(Paths.get("/proc/thread-self")).getFileName().toString();
this.osId = Integer.parseInt(tid);
Files.write(
Paths.get("/sys/fs/cgroup/net_prio", cgroupName, "tasks"),
Integer.toString(this.osId).getBytes()
);
}
public int getOSId() {
return this.osId;
}
}
static class CGThreadFactory implements ThreadFactory {
private final String cgroupName;
public CGThreadFactory(String name) {
this.cgroupName = name;
}
public Thread newThread(Runnable r) {
return new CGroupThreads.CGThread(cgroupName, r);
}
}
public static void main(String[] args) throws Exception {
if(args.length == 0) {
System.err.println("Please pass the desired CGroup name as an argument");
System.exit(1);
}
ExecutorService exs = Executors.newFixedThreadPool(1, new CGThreadFactory(args[0]));
exs.submit(() -> {
System.out.println(((CGThread)Thread.currentThread()).getOSId());
}).get();
exs.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment