
com.google.sitebricks.cloud.ProcRunner Maven / Gradle / Ivy
The newest version!
package com.google.sitebricks.cloud;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import com.google.common.io.CharStreams;
import com.google.sitebricks.cloud.proc.DynamicCompilation;
import com.google.sitebricks.cloud.proc.Proc;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author [email protected] (Dhanji R. Prasanna)
*/
public class ProcRunner implements Command {
@Override
public void run(List commands, Config config) throws Exception {
List procs = readProcs(config);
// Compile project first, if necessary.
DynamicCompilation.compile(config);
// Load environment config.
String envName = System.getenv("ENV");
if (envName == null)
envName = "local";
Map env = readEnvironment(envName);
if (env == null) {
Cloud.quit("unknown environment: " + envName);
}
// Default to log level info for our app.
assert env != null;
if (env.get("loglevel") == null)
env.put("loglevel", "info");
// Start procs.
for (Proc proc : procs) {
proc.start(toEnvironmentArray(env));
}
LoggerFactory.getLogger("sitebricks").info("all jobs started");
for (Proc proc : procs) {
proc.await();
}
}
private static String[] toEnvironmentArray(Map env) {
List array = new ArrayList();
for (Map.Entry entry : env.entrySet()) {
array.add(entry.getKey() + "=" + entry.getValue());
}
return array.toArray(new String[env.size()]);
}
static Map readEnvironment(String name) throws Exception {
return readEnvironment(new FileReader("pom.xml"), name);
}
@VisibleForTesting
static Map readEnvironment(Reader pom, String name) throws Exception {
Document document = DocumentHelper.parseText(CharStreams.toString(pom));
Map envConfig = new LinkedHashMap();
List nodes = DomUtil.select(document, "/m:project/m:profiles/m:profile");
for (Node node : nodes) {
List select = DomUtil.select(node, "m:id");
if (!select.isEmpty() && name.equals(select.get(0).getStringValue())) {
List properties = DomUtil.select(node, "m:properties/*");
for (Node property : properties) {
envConfig.put(property.getName(), property.getStringValue());
}
}
}
return envConfig;
}
public static List readProcs(Config config) throws IOException {
File procfile = new File("Procfile");
if (!procfile.exists())
Cloud.quit("Procfile not found. cannot proceed");
List procs = Lists.newArrayList();
List lines = CharStreams.readLines(new FileReader(procfile));
for (String line : lines) {
line = line.trim();
if (line.isEmpty())
continue;
procs.add(new Proc(line, config));
}
return procs;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy