com.jeesuite.scheduler.monitor.SchedulerMonitor Maven / Gradle / Ivy
/**
*
*/
package com.jeesuite.scheduler.monitor;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jeesuite.common.json.JsonUtils;
import com.jeesuite.scheduler.model.JobConfig;
import com.jeesuite.scheduler.model.JobGroupInfo;
import com.jeesuite.scheduler.registry.ZkJobRegistry;
/**
* @description
* @author vakin
* @date 2016年10月30日
*/
public class SchedulerMonitor implements Closeable{
private static final Logger logger = LoggerFactory.getLogger(SchedulerMonitor.class);
private ZkClient zkClient;
public SchedulerMonitor(String registryType, String servers) {
if ("redis".equals(registryType)) {
} else {
ZkConnection zkConnection = new ZkConnection(servers);
zkClient = new ZkClient(zkConnection, 3000);
}
}
@Override
public void close() throws IOException {
if(zkClient != null)zkClient.close();
}
public JobGroupInfo getJobGroupInfo(String groupName){
JobGroupInfo groupInfo = new JobGroupInfo();
groupInfo.setName(groupName);
//
String path = ZkJobRegistry.ROOT + groupName;
List children = zkClient.getChildren(path);
for (String child : children) {
if("nodes".equals(child)){
path = ZkJobRegistry.ROOT + groupName + "/nodes";
groupInfo.setClusterNodes(zkClient.getChildren(path));
}else{
path = ZkJobRegistry.ROOT + groupName + "/" + child;
Object data = zkClient.readData(path);
if(data != null){
JobConfig jobConfig = JsonUtils.toObject(data.toString(), JobConfig.class);
groupInfo.getJobs().add(jobConfig);
}
}
}
if(groupInfo.getClusterNodes().size() > 0){
return groupInfo;
}
return null;
}
public List getGroups(){
String path = ZkJobRegistry.ROOT.substring(0,ZkJobRegistry.ROOT.length() - 1);
return zkClient.getChildren(path);
}
public List getAllJobGroups(){
//zk registry
List result = new ArrayList<>();
List groupNames = getGroups();
if(groupNames == null)return result;
for (String groupName : groupNames) {
JobGroupInfo groupInfo = getJobGroupInfo(groupName);
if(groupInfo != null){
result.add(groupInfo);
}
}
return result;
}
public void publishEvent(MonitorCommond cmd){
String path = ZkJobRegistry.ROOT + cmd.getJobGroup() + "/nodes";
List nodeIds = zkClient.getChildren(path);
for (String node : nodeIds) {
String nodePath = path + "/" + node;
zkClient.writeData(nodePath, cmd);
logger.info("publishEvent finish,path:{},content:{}",nodePath,cmd);
break;
}
}
public static void main(String[] args) throws IOException {
SchedulerMonitor monitor = new SchedulerMonitor("zookeeper", "127.0.0.1:2181");
List groups = monitor.getAllJobGroups();
System.out.println(JsonUtils.toJson(groups));
monitor.close();
}
}