Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BIGTOP-4324: Update agent cache files before job runs #146

Merged
merged 2 commits into from
Jan 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,24 +16,23 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.bigtop.manager.agent.executor;
package org.apache.bigtop.manager.agent.service;

import org.apache.bigtop.manager.common.constants.MessageConstants;
import org.apache.bigtop.manager.common.message.entity.payload.CacheMessagePayload;
import org.apache.bigtop.manager.common.utils.JsonUtils;
import org.apache.bigtop.manager.common.utils.ProjectPathUtils;
import org.apache.bigtop.manager.grpc.generated.CommandType;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.apache.bigtop.manager.grpc.generated.JobCacheReply;
import org.apache.bigtop.manager.grpc.generated.JobCacheRequest;
import org.apache.bigtop.manager.grpc.generated.JobCacheServiceGrpc;

import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;

import static org.apache.bigtop.manager.common.constants.CacheFiles.CLUSTER_INFO;
import static org.apache.bigtop.manager.common.constants.CacheFiles.COMPONENTS_INFO;
Expand All @@ -43,41 +42,33 @@
import static org.apache.bigtop.manager.common.constants.CacheFiles.USERS_INFO;

@Slf4j
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class CacheFileUpdateCommandExecutor extends AbstractCommandExecutor {

@Override
public CommandType getCommandType() {
return CommandType.UPDATE_CACHE_FILES;
}
@GrpcService
public class JobCacheServiceGrpcImpl extends JobCacheServiceGrpc.JobCacheServiceImplBase {

@Override
public void doExecute() {
CacheMessagePayload cacheMessagePayload =
JsonUtils.readFromString(commandRequest.getPayload(), CacheMessagePayload.class);
public void save(JobCacheRequest request, StreamObserver<JobCacheReply> responseObserver) {
CacheMessagePayload payload = JsonUtils.readFromString(request.getPayload(), CacheMessagePayload.class);
String cacheDir = ProjectPathUtils.getAgentCachePath();
Path p = Paths.get(cacheDir);
if (!Files.exists(p)) {
try {
Files.createDirectories(p);
} catch (Exception e) {
log.error("Create directory failed: {}", cacheDir, e);
commandReplyBuilder.setCode(MessageConstants.FAIL_CODE);
commandReplyBuilder.setResult(
MessageFormat.format("Create directory {0}, failed: {1}", cacheDir, e.getMessage()));
return;
responseObserver.onError(e);
}
}

JsonUtils.writeToFile(cacheDir + CONFIGURATIONS_INFO, cacheMessagePayload.getConfigurations());
JsonUtils.writeToFile(cacheDir + HOSTS_INFO, cacheMessagePayload.getClusterHostInfo());
JsonUtils.writeToFile(cacheDir + USERS_INFO, cacheMessagePayload.getUserInfo());
JsonUtils.writeToFile(cacheDir + COMPONENTS_INFO, cacheMessagePayload.getComponentInfo());
JsonUtils.writeToFile(cacheDir + REPOS_INFO, cacheMessagePayload.getRepoInfo());
JsonUtils.writeToFile(cacheDir + CLUSTER_INFO, cacheMessagePayload.getClusterInfo());
JsonUtils.writeToFile(cacheDir + CONFIGURATIONS_INFO, payload.getConfigurations());
JsonUtils.writeToFile(cacheDir + HOSTS_INFO, payload.getClusterHostInfo());
JsonUtils.writeToFile(cacheDir + USERS_INFO, payload.getUserInfo());
JsonUtils.writeToFile(cacheDir + COMPONENTS_INFO, payload.getComponentInfo());
JsonUtils.writeToFile(cacheDir + REPOS_INFO, payload.getRepoInfo());
JsonUtils.writeToFile(cacheDir + CLUSTER_INFO, payload.getClusterInfo());

commandReplyBuilder.setCode(MessageConstants.SUCCESS_CODE);
commandReplyBuilder.setResult("Successfully cached files");
JobCacheReply reply = JobCacheReply.newBuilder()
.setCode(MessageConstants.SUCCESS_CODE)
.build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
36 changes: 36 additions & 0 deletions bigtop-manager-grpc/src/main/resources/proto/job_cache.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
syntax = "proto3";

option java_multiple_files = true;
option java_package = "org.apache.bigtop.manager.grpc.generated";
option java_outer_classname = "JobCacheProto";

service JobCacheService {
rpc save (JobCacheRequest) returns (JobCacheReply) {}
}

message JobCacheRequest {
int64 job_id = 1;
string payload = 2;
}

message JobCacheReply {
int32 code = 1;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,11 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.bigtop.manager.server.command.task;
package org.apache.bigtop.manager.server.command.helper;

import org.apache.bigtop.manager.common.enums.Command;
import org.apache.bigtop.manager.common.constants.MessageConstants;
import org.apache.bigtop.manager.common.message.entity.payload.CacheMessagePayload;
import org.apache.bigtop.manager.common.message.entity.pojo.ClusterInfo;
import org.apache.bigtop.manager.common.message.entity.pojo.ComponentInfo;
import org.apache.bigtop.manager.common.message.entity.pojo.RepoInfo;
import org.apache.bigtop.manager.common.utils.JsonUtils;
import org.apache.bigtop.manager.dao.po.ClusterPO;
Expand All @@ -35,8 +34,11 @@
import org.apache.bigtop.manager.dao.repository.HostDao;
import org.apache.bigtop.manager.dao.repository.RepoDao;
import org.apache.bigtop.manager.dao.repository.ServiceConfigDao;
import org.apache.bigtop.manager.grpc.generated.CommandRequest;
import org.apache.bigtop.manager.grpc.generated.CommandType;
import org.apache.bigtop.manager.grpc.generated.JobCacheReply;
import org.apache.bigtop.manager.grpc.generated.JobCacheRequest;
import org.apache.bigtop.manager.grpc.generated.JobCacheServiceGrpc;
import org.apache.bigtop.manager.server.exception.ServerException;
import org.apache.bigtop.manager.server.grpc.GrpcClient;
import org.apache.bigtop.manager.server.holder.SpringContextHolder;
import org.apache.bigtop.manager.server.model.converter.RepoConverter;
import org.apache.bigtop.manager.server.model.dto.ServiceDTO;
Expand All @@ -49,59 +51,72 @@
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import static org.apache.bigtop.manager.common.constants.Constants.ALL_HOST_KEY;

public class CacheFileUpdateTask extends AbstractTask {
public class JobCacheHelper {

private ClusterDao clusterDao;
private ServiceConfigDao serviceConfigDao;
private RepoDao repoDao;
private HostDao hostDao;
private ComponentDao componentDao;
private static ClusterDao clusterDao;
private static ServiceConfigDao serviceConfigDao;
private static RepoDao repoDao;
private static HostDao hostDao;
private static ComponentDao componentDao;

private ClusterInfo clusterInfo;
private Map<String, ComponentInfo> componentInfoMap;
private Map<String, Map<String, Object>> serviceConfigMap;
private Map<String, Set<String>> hostMap;
private List<RepoInfo> repoList;
private Map<String, String> userMap;
private static final AtomicBoolean INITIALIZED = new AtomicBoolean(false);

public CacheFileUpdateTask(TaskContext taskContext) {
super(taskContext);
}

@Override
protected void injectBeans() {
super.injectBeans();
private static void initialize() {
clusterDao = SpringContextHolder.getBean(ClusterDao.class);
serviceConfigDao = SpringContextHolder.getBean(ServiceConfigDao.class);
repoDao = SpringContextHolder.getBean(RepoDao.class);
hostDao = SpringContextHolder.getBean(HostDao.class);
componentDao = SpringContextHolder.getBean(ComponentDao.class);

this.clusterDao = SpringContextHolder.getBean(ClusterDao.class);
this.serviceConfigDao = SpringContextHolder.getBean(ServiceConfigDao.class);
this.repoDao = SpringContextHolder.getBean(RepoDao.class);
this.hostDao = SpringContextHolder.getBean(HostDao.class);
this.componentDao = SpringContextHolder.getBean(ComponentDao.class);
INITIALIZED.set(true);
}

@Override
public void beforeRun() {
super.beforeRun();
public static void sendJobCache(Long clusterId, Long jobId, List<String> hostnames) {
CacheMessagePayload payload = genPayload(clusterId);
JobCacheRequest request = JobCacheRequest.newBuilder()
.setJobId(jobId)
.setPayload(JsonUtils.writeAsString(payload))
.build();
List<HostPO> hostPOList = hostDao.findAllByHostnames(hostnames);
List<CompletableFuture<Boolean>> futures = new ArrayList<>();
for (HostPO hostPO : hostPOList) {
futures.add(CompletableFuture.supplyAsync(() -> {
JobCacheServiceGrpc.JobCacheServiceBlockingStub stub = GrpcClient.getBlockingStub(
hostPO.getHostname(),
hostPO.getGrpcPort(),
JobCacheServiceGrpc.JobCacheServiceBlockingStub.class);
JobCacheReply reply = stub.save(request);
return reply != null && reply.getCode() == MessageConstants.SUCCESS_CODE;
}));
}

genCaches();
List<Boolean> results = futures.stream()
.map((future) -> {
try {
return future.get();
} catch (Exception e) {
return false;
}
})
.toList();

boolean allSuccess = results.stream().allMatch(Boolean::booleanValue);
if (!allSuccess) {
throw new ServerException("Failed to send job cache");
}
}

private void genCaches() {
if (taskContext.getClusterId() == null) {
genEmptyCaches();
} else {
genFullCaches();
private static CacheMessagePayload genPayload(Long clusterId) {
if (!INITIALIZED.get()) {
initialize();
}
}

@SuppressWarnings("unchecked")
private void genFullCaches() {
Long clusterId = taskContext.getClusterId();
List<String> hostnames = (List<String>) taskContext.getProperties().get("hostnames");
ClusterPO clusterPO = clusterDao.findById(clusterId);

ComponentQuery componentQuery =
Expand All @@ -110,14 +125,14 @@ private void genFullCaches() {
List<ServiceConfigPO> serviceConfigPOList = serviceConfigDao.findByClusterId(clusterPO.getId());
List<ComponentPO> componentPOList = componentDao.findByQuery(componentQuery);
List<RepoPO> repoPOList = repoDao.findAll();
List<HostPO> hostPOList = hostDao.findAllByHostnames(hostnames);
List<HostPO> hostPOList = hostDao.findAll();

clusterInfo = new ClusterInfo();
ClusterInfo clusterInfo = new ClusterInfo();
clusterInfo.setName(clusterPO.getName());
clusterInfo.setUserGroup(clusterPO.getUserGroup());
clusterInfo.setRootDir(clusterPO.getRootDir());

serviceConfigMap = new HashMap<>();
Map<String, Map<String, Object>> serviceConfigMap = new HashMap<>();
for (ServiceConfigPO serviceConfigPO : serviceConfigPOList) {
List<Map<String, Object>> properties = JsonUtils.readFromString(serviceConfigPO.getPropertiesJson());
Map<String, String> kvMap = properties.stream()
Expand All @@ -134,7 +149,7 @@ private void genFullCaches() {
}
}

hostMap = new HashMap<>();
Map<String, Set<String>> hostMap = new HashMap<>();
componentPOList.forEach(x -> {
if (hostMap.containsKey(x.getName())) {
hostMap.get(x.getName()).add(x.getHostname());
Expand All @@ -149,81 +164,25 @@ private void genFullCaches() {
Set<String> hostNameSet = hostPOList.stream().map(HostPO::getHostname).collect(Collectors.toSet());
hostMap.put(ALL_HOST_KEY, hostNameSet);

repoList = new ArrayList<>();
List<RepoInfo> repoList = new ArrayList<>();
repoPOList.forEach(repoPO -> {
RepoInfo repoInfo = RepoConverter.INSTANCE.fromPO2Message(repoPO);
repoList.add(repoInfo);
});

userMap = new HashMap<>();
Map<String, String> userMap = new HashMap<>();
for (StackDTO stackDTO : StackUtils.getAllStacks()) {
for (ServiceDTO serviceDTO : StackUtils.getServiceDTOList(stackDTO)) {
userMap.put(serviceDTO.getName(), serviceDTO.getUser());
}
}
}

@SuppressWarnings("unchecked")
private void genEmptyCaches() {
List<String> hostnames = (List<String>) taskContext.getProperties().get("hostnames");

List<RepoPO> repoPOList = repoDao.findAll();
List<HostPO> hostPOList = hostDao.findAllByHostnames(hostnames);

componentInfoMap = new HashMap<>();
serviceConfigMap = new HashMap<>();

clusterInfo = new ClusterInfo();
clusterInfo.setUserGroup(taskContext.getUserGroup());
clusterInfo.setRootDir(taskContext.getRootDir());

hostMap = new HashMap<>();
Set<String> hostNameSet = hostPOList.stream().map(HostPO::getHostname).collect(Collectors.toSet());
hostMap.put(ALL_HOST_KEY, hostNameSet);

repoList = new ArrayList<>();
repoPOList.forEach(repoPO -> {
RepoInfo repoInfo = RepoConverter.INSTANCE.fromPO2Message(repoPO);
repoList.add(repoInfo);
});

userMap = new HashMap<>();
for (StackDTO stackDTO : StackUtils.getAllStacks()) {
for (ServiceDTO serviceDTO : StackUtils.getServiceDTOList(stackDTO)) {
userMap.put(serviceDTO.getName(), serviceDTO.getUser());
}
}
}

@Override
protected Command getCommand() {
return Command.CUSTOM;
}

@Override
protected String getCustomCommand() {
return "update_cache_files";
}

@Override
protected CommandRequest getCommandRequest() {
CacheMessagePayload messagePayload = new CacheMessagePayload();
messagePayload.setClusterInfo(clusterInfo);
messagePayload.setConfigurations(serviceConfigMap);
messagePayload.setClusterHostInfo(hostMap);
messagePayload.setRepoInfo(repoList);
messagePayload.setUserInfo(userMap);
messagePayload.setComponentInfo(componentInfoMap);

CommandRequest.Builder builder = CommandRequest.newBuilder();
builder.setType(CommandType.UPDATE_CACHE_FILES);
builder.setPayload(JsonUtils.writeAsString(messagePayload));

return builder.build();
}

@Override
public String getName() {
return "Update cache files on " + taskContext.getHostname();
CacheMessagePayload payload = new CacheMessagePayload();
payload.setClusterInfo(clusterInfo);
payload.setConfigurations(serviceConfigMap);
payload.setClusterHostInfo(hostMap);
payload.setRepoInfo(repoList);
payload.setUserInfo(userMap);
return payload;
}
}
Loading
Loading