use of com.bonree.brfs.common.service.ServiceManager in project BRFS by zhangnianli.
the class CreateSystemTaskJob method operation.
@Override
public void operation(JobExecutionContext context) {
LOG.info("create system task working");
// 判断是否有恢复任务,有恢复任务则不进行创建
JobDataMap data = context.getJobDetail().getJobDataMap();
long checkTtl = data.getLong(JobDataMapConstract.CHECK_TTL);
ManagerContralFactory mcf = ManagerContralFactory.getInstance();
MetaTaskManagerInterface release = mcf.getTm();
// 获取开启的任务名称
List<TaskType> switchList = mcf.getTaskOn();
if (switchList == null || switchList.isEmpty()) {
LOG.warn("switch on task is empty !!!");
return;
}
// 获取可用服务
String groupName = mcf.getGroupName();
ServiceManager sm = mcf.getSm();
// 2.设置可用服务
List<String> serverIds = CreateSystemTask.getServerIds(sm, groupName);
if (serverIds == null || serverIds.isEmpty()) {
LOG.warn("{} available server list is null", groupName);
return;
}
// 3.获取storageName
StorageRegionManager snm = mcf.getSnm();
List<StorageRegion> snList = snm.getStorageRegionList();
if (snList == null || snList.isEmpty()) {
LOG.info("skip create system task !!! because storageName is null !!!");
return;
}
TaskModel task;
String taskName;
TaskTypeModel tmodel;
long ttl = 0;
Pair<TaskModel, TaskTypeModel> result;
List<String> srs = TaskStateLifeContral.getSRs(snm);
for (TaskType taskType : switchList) {
if (TaskType.SYSTEM_COPY_CHECK.equals(taskType) || TaskType.USER_DELETE.equals(taskType)) {
continue;
}
TaskStateLifeContral.watchSR(release, srs, taskType.name());
if (TaskType.SYSTEM_DELETE.equals(taskType)) {
ttl = 0;
} else if (TaskType.SYSTEM_CHECK.equals(taskType)) {
ttl = checkTtl;
}
tmodel = release.getTaskTypeInfo(taskType.name());
if (tmodel == null) {
tmodel = new TaskTypeModel();
tmodel.setSwitchFlag(true);
LOG.warn("taskType{} is switch but metadata is null");
}
result = CreateSystemTask.createSystemTask(tmodel, taskType, snList, ttl);
if (result == null) {
LOG.warn("create sys task is empty {}", taskType.name());
continue;
}
task = result.getFirst();
taskName = CreateSystemTask.updateTask(release, task, serverIds, taskType);
if (!BrStringUtils.isEmpty(taskName)) {
LOG.info("create {} {} task successfull !!!", taskType.name(), taskName);
release.setTaskTypeModel(taskType.name(), tmodel);
}
}
}
use of com.bonree.brfs.common.service.ServiceManager in project BRFS by zhangnianli.
the class BootStrap method main.
public static void main(String[] args) {
ProcessFinalizer finalizer = new ProcessFinalizer();
try {
// 初始化email发送配置
EmailPool.getInstance();
String zkAddresses = Configs.getConfiguration().GetConfig(CommonConfigs.CONFIG_ZOOKEEPER_ADDRESSES);
String host = Configs.getConfiguration().GetConfig(RegionNodeConfigs.CONFIG_HOST);
int port = Configs.getConfiguration().GetConfig(RegionNodeConfigs.CONFIG_PORT);
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient(zkAddresses, 3000, 15000, retryPolicy);
client.start();
client.blockUntilConnected();
finalizer.add(client);
CuratorCacheFactory.init(zkAddresses);
String clusterName = Configs.getConfiguration().GetConfig(CommonConfigs.CONFIG_CLUSTER_NAME);
ZookeeperPaths zookeeperPaths = ZookeeperPaths.create(clusterName, zkAddresses);
ServerIDManager idManager = new ServerIDManager(client, zookeeperPaths);
SimpleAuthentication simpleAuthentication = SimpleAuthentication.getAuthInstance(zookeeperPaths.getBaseUserPath(), zookeeperPaths.getBaseLocksPath(), client);
UserModel model = simpleAuthentication.getUser("root");
if (model == null) {
LOG.error("please init server!!!");
System.exit(1);
}
Service service = new Service(UUID.randomUUID().toString(), Configs.getConfiguration().GetConfig(CommonConfigs.CONFIG_REGION_SERVICE_GROUP_NAME), host, port);
ServiceManager serviceManager = new DefaultServiceManager(client.usingNamespace(zookeeperPaths.getBaseClusterName().substring(1)));
serviceManager.start();
finalizer.add(serviceManager);
TimeExchangeEventEmitter timeEventEmitter = new TimeExchangeEventEmitter(2);
finalizer.add(timeEventEmitter);
StorageRegionIdBuilder storageIdBuilder = new ZkStorageRegionIdBuilder(client.usingNamespace(zookeeperPaths.getBaseClusterName().substring(1)));
StorageRegionManager storageNameManager = new DefaultStorageRegionManager(client.usingNamespace(zookeeperPaths.getBaseClusterName().substring(1)), storageIdBuilder);
storageNameManager.start();
finalizer.add(storageNameManager);
// HttpDiskNodeConnectionPool connectionPool = new HttpDiskNodeConnectionPool(serviceManager);
// finalizer.add(connectionPool);
AsyncTcpClientGroup tcpClientGroup = new AsyncTcpClientGroup(Configs.getConfiguration().GetConfig(RegionNodeConfigs.CONFIG_WRITER_WORKER_NUM));
TcpDiskNodeConnectionPool connectionPool = new TcpDiskNodeConnectionPool(serviceManager, tcpClientGroup);
finalizer.add(tcpClientGroup);
FilePathMaker pathMaker = new IDFilePathMaker(idManager);
int workerThreadNum = Configs.getConfiguration().GetConfig(RegionNodeConfigs.CONFIG_SERVER_IO_THREAD_NUM);
HttpConfig httpConfig = HttpConfig.newBuilder().setHost(host).setPort(port).setAcceptWorkerNum(1).setRequestHandleWorkerNum(workerThreadNum).setBacklog(Integer.parseInt(System.getProperty(SystemProperties.PROP_NET_BACKLOG, "2048"))).build();
NettyHttpServer httpServer = new NettyHttpServer(httpConfig);
httpServer.addHttpAuthenticator(new HttpAuthenticator() {
@Override
public int check(String userName, String passwd) {
StringBuilder tokenBuilder = new StringBuilder();
tokenBuilder.append(userName).append(":").append(passwd);
return simpleAuthentication.auth(tokenBuilder.toString()) ? 0 : ReturnCode.USER_FORBID.getCode();
}
});
ExecutorService requestHandlerExecutor = Executors.newFixedThreadPool(Math.max(4, Runtime.getRuntime().availableProcessors() / 4), new PooledThreadFactory("request_handler"));
finalizer.add(new Closeable() {
@Override
public void close() throws IOException {
requestHandlerExecutor.shutdown();
}
});
FileObjectSyncProcessor processor = new DefaultFileObjectSyncProcessor(connectionPool, pathMaker);
DefaultFileObjectSynchronier fileSynchronizer = new DefaultFileObjectSynchronier(processor, serviceManager, 10, TimeUnit.SECONDS);
fileSynchronizer.start();
finalizer.add(fileSynchronizer);
FileNodeStorer storer = new ZkFileNodeStorer(client.usingNamespace(zookeeperPaths.getBaseClusterName().substring(1)), ZkFileCoordinatorPaths.COORDINATOR_FILESTORE);
// 资源缓存器
String diskGroup = Configs.getConfiguration().GetConfig(CommonConfigs.CONFIG_DATA_SERVICE_GROUP_NAME);
String rPath = zookeeperPaths.getBaseResourcesPath() + "/" + diskGroup + "/resource";
ClusterResource clusterResource = ClusterResource.newBuilder().setCache(true).setClient(client).setListenPath(rPath).setPool(Executors.newSingleThreadExecutor()).build().start();
// 资源选择策略
// 获取限制值
double diskRemainRate = Configs.getConfiguration().GetConfig(ResourceConfigs.CONFIG_LIMIT_DISK_AVAILABLE_RATE);
double diskForceRemainRate = Configs.getConfiguration().GetConfig(ResourceConfigs.CONFIG_LIMIT_FORCE_DISK_AVAILABLE_RATE);
double diskwriteValue = Configs.getConfiguration().GetConfig(ResourceConfigs.CONFIG_LIMIT_DISK_WRITE_SPEED);
double diskForcewriteValue = Configs.getConfiguration().GetConfig(ResourceConfigs.CONFIG_LIMIT_FORCE_DISK_WRITE_SPEED);
long diskRemainSize = Configs.getConfiguration().GetConfig(ResourceConfigs.CONFIG_LIMIT_DISK_REMAIN_SIZE);
long diskForceRemainSize = Configs.getConfiguration().GetConfig(ResourceConfigs.CONFIG_LIMIT_FORCE_DISK_REMAIN_SIZE);
LimitServerResource lmit = new LimitServerResource();
lmit.setDiskRemainRate(diskRemainRate);
lmit.setDiskWriteValue(diskwriteValue);
lmit.setForceDiskRemainRate(diskForceRemainRate);
lmit.setForceWriteValue(diskForcewriteValue);
lmit.setRemainWarnSize(diskRemainSize);
lmit.setRemainForceSize(diskForceRemainSize);
int centSize = Configs.getConfiguration().GetConfig(ResourceConfigs.CONFIG_RESOURCE_CENT_SIZE);
long fileSize = Configs.getConfiguration().GetConfig(DataNodeConfigs.CONFIG_FILE_MAX_CAPACITY) / 1024;
MachineResourceWriterSelector serviceSelector = new MachineResourceWriterSelector(connectionPool, storer, lmit, diskGroup, fileSize, centSize);
// 生成备用选择器
DuplicateNodeSelector bakSelect = new MinimalDuplicateNodeSelector(serviceManager, connectionPool);
// 选择
DuplicateNodeSelector nodeSelector = ResourceWriteSelector.newBuilder().setBakSelector(bakSelect).setDaemon(clusterResource).setGroupName(diskGroup).setStorageRegionManager(storageNameManager).setResourceSelector(serviceSelector).build();
FileObjectFactory fileFactory = new DefaultFileObjectFactory(service, storer, nodeSelector, idManager, connectionPool);
int closerThreadNum = Configs.getConfiguration().GetConfig(RegionNodeConfigs.CONFIG_CLOSER_THREAD_NUM);
DefaultFileObjectCloser fileCloser = new DefaultFileObjectCloser(closerThreadNum, fileSynchronizer, storer, connectionPool, pathMaker);
finalizer.add(fileCloser);
FileNodeSinkManager sinkManager = new ZkFileNodeSinkManager(client.usingNamespace(zookeeperPaths.getBaseClusterName().substring(1)), service, serviceManager, timeEventEmitter, storer, new RandomFileNodeSinkSelector(), fileCloser);
sinkManager.start();
finalizer.add(sinkManager);
DataPoolFactory dataPoolFactory = new BlockingQueueDataPoolFactory(Configs.getConfiguration().GetConfig(RegionNodeConfigs.CONFIG_DATA_POOL_CAPACITY));
FileObjectSupplierFactory fileSupplierFactory = new DefaultFileObjectSupplierFactory(fileFactory, fileCloser, fileSynchronizer, sinkManager, timeEventEmitter);
DiskWriter diskWriter = new DiskWriter(Configs.getConfiguration().GetConfig(RegionNodeConfigs.CONFIG_WRITER_WORKER_NUM), connectionPool, pathMaker);
finalizer.add(diskWriter);
DataEngineFactory engineFactory = new DefaultDataEngineFactory(dataPoolFactory, fileSupplierFactory, diskWriter);
DefaultDataEngineManager engineManager = new DefaultDataEngineManager(storageNameManager, engineFactory);
finalizer.add(engineManager);
DefaultStorageRegionWriter writer = new DefaultStorageRegionWriter(engineManager);
NettyHttpRequestHandler requestHandler = new NettyHttpRequestHandler(requestHandlerExecutor);
requestHandler.addMessageHandler("POST", new WriteDataMessageHandler(writer));
requestHandler.addMessageHandler("GET", new ReadDataMessageHandler());
requestHandler.addMessageHandler("DELETE", new DeleteDataMessageHandler(zookeeperPaths, serviceManager, storageNameManager));
httpServer.addContextHandler(URI_DATA_ROOT, requestHandler);
NettyHttpRequestHandler snRequestHandler = new NettyHttpRequestHandler(requestHandlerExecutor);
snRequestHandler.addMessageHandler("PUT", new CreateStorageRegionMessageHandler(storageNameManager));
snRequestHandler.addMessageHandler("POST", new UpdateStorageRegionMessageHandler(storageNameManager));
snRequestHandler.addMessageHandler("GET", new OpenStorageRegionMessageHandler(storageNameManager));
snRequestHandler.addMessageHandler("DELETE", new DeleteStorageRegionMessageHandler(zookeeperPaths, storageNameManager, serviceManager));
httpServer.addContextHandler(URI_STORAGE_REGION_ROOT, snRequestHandler);
httpServer.start();
finalizer.add(httpServer);
serviceManager.registerService(service);
finalizer.add(new Closeable() {
@Override
public void close() throws IOException {
try {
serviceManager.unregisterService(service);
} catch (Exception e) {
LOG.error("unregister service[{}] error", service, e);
}
}
});
} catch (Exception e) {
LOG.error("launch server error!!!", e);
System.exit(1);
} finally {
Runtime.getRuntime().addShutdownHook(finalizer);
}
}
use of com.bonree.brfs.common.service.ServiceManager in project BRFS by zhangnianli.
the class CopyRecovery method recoveryDirs.
/**
* 概述:修复目录
* @param content
* @param zkHosts
* @param baseRoutesPath
* @return
* @user <a href=mailto:zhucg@bonree.com>朱成岗</a>
*/
public static TaskResultModel recoveryDirs(String content, String zkHosts, String baseRoutesPath, String dataPath) {
TaskResultModel result = new TaskResultModel();
BatchAtomModel batch = converStringToBatch(content);
if (batch == null) {
result.setSuccess(false);
LOG.debug("batch is empty");
return result;
}
List<AtomTaskModel> atoms = batch.getAtoms();
if (atoms == null || atoms.isEmpty()) {
result.setSuccess(true);
LOG.debug(" files is empty");
return result;
}
ManagerContralFactory mcf = ManagerContralFactory.getInstance();
ServerIDManager sim = mcf.getSim();
ServiceManager sm = mcf.getSm();
StorageRegionManager snm = mcf.getSnm();
CuratorClient curatorClient = mcf.getClient();
StorageRegion sn;
SecondIDParser parser;
String snName;
int snId;
AtomTaskResultModel atomR;
List<String> errors;
for (AtomTaskModel atom : atoms) {
atomR = new AtomTaskResultModel();
atomR.setFiles(atom.getFiles());
atomR.setSn(atom.getStorageName());
snName = atom.getStorageName();
sn = snm.findStorageRegionByName(snName);
if (sn == null) {
atomR.setSuccess(false);
result.setSuccess(false);
result.add(atomR);
LOG.debug("sn == null snName :{}", snName);
continue;
}
snId = sn.getId();
parser = new SecondIDParser(curatorClient, snId, baseRoutesPath);
parser.updateRoute();
errors = recoveryFiles(sm, sim, parser, sn, atom, dataPath);
if (errors == null || errors.isEmpty()) {
result.add(atomR);
LOG.debug("result is empty snName:{}", snName);
continue;
}
atomR.addAll(errors);
atomR.setSuccess(false);
result.setSuccess(false);
}
return result;
}
Aggregations