github-code-scanning[bot] commented on code in PR #12552: URL: https://github.com/apache/dolphinscheduler/pull/12552#discussion_r1006412971
########## dolphinscheduler-worker/src/main/java/org/apache/dolphinscheduler/server/worker/utils/TaskFilesTransferUtils.java: ########## @@ -0,0 +1,267 @@ +/* + * 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 + * + * http://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. + */ + +package org.apache.dolphinscheduler.server.worker.utils; + +import org.apache.dolphinscheduler.common.utils.DateUtils; +import org.apache.dolphinscheduler.common.utils.JSONUtils; +import org.apache.dolphinscheduler.plugin.task.api.TaskConstants; +import org.apache.dolphinscheduler.plugin.task.api.TaskException; +import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext; +import org.apache.dolphinscheduler.plugin.task.api.enums.DataType; +import org.apache.dolphinscheduler.plugin.task.api.enums.Direct; +import org.apache.dolphinscheduler.plugin.task.api.model.Property; +import org.apache.dolphinscheduler.service.storage.StorageOperate; + +import org.apache.commons.lang3.StringUtils; + +import java.io.File; +import java.io.IOException; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.zeroturnaround.zip.ZipUtil; + +import com.fasterxml.jackson.databind.JsonNode; + +public class TaskFilesTransferUtils { + + protected final static Logger logger = LoggerFactory + .getLogger(String.format(TaskConstants.TASK_LOG_LOGGER_NAME_FORMAT, TaskFilesTransferUtils.class)); + + // root path in resource storage + final static String RESOURCE_TAG = "DATA_TRANSFER"; + + // tmp path in local path for transfer + final static String DOWNLOAD_TMP = ".DT_TMP"; + + // suffix of the package file + final static String PACK_SUFFIX = "_ds_pack.zip"; + + /** + * upload output files to resource storage + * + * @param taskExecutionContext taskExecutionContext + * @param storageOperate storageOperate + * @throws TaskException TaskException + */ + public static void uploadOutputFiles(StorageOperate storageOperate, + TaskExecutionContext taskExecutionContext) throws TaskException { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get OUTPUT FILE parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.OUT); + + if (localParamsProperty.isEmpty()) { + return; + } + + logger.info("Upload output files ..."); + for (Property property : localParamsProperty) { + // get local file path + String srcPath = + packIfDir(String.format("%s/%s", taskExecutionContext.getExecutePath(), property.getValue())); + // get remote file path + String resourcePath = getResourcePath(taskExecutionContext, new File(srcPath).getName()); + try { + // upload file to storage + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Local:{} to Remote:{}", property, srcPath, resourceWholePath); + storageOperate.upload(taskExecutionContext.getTenantCode(), srcPath, resourceWholePath, false, true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // update varPool + Property oriProperty; + // if the property is not in varPool, add it + if (varPoolsMap.containsKey(property.getProp())) { + oriProperty = varPoolsMap.get(property.getProp()); + } else { + oriProperty = new Property(property.getProp(), Direct.OUT, DataType.FILE, property.getValue()); + varPools.add(oriProperty); + } + oriProperty.setProp(String.format("%s.%s", taskExecutionContext.getTaskName(), oriProperty.getProp())); + oriProperty.setValue(resourcePath); + } + taskExecutionContext.setVarPool(JSONUtils.toJsonString(varPools)); + } + + /** + * download upstream files from storage + * only download files which are defined in the task parameters + * + * @param storageOperate storage operate + * @param taskExecutionContext taskExecutionContext + * @throws TaskException task exception + */ + public static void downloadUpstreamFiles(TaskExecutionContext taskExecutionContext, StorageOperate storageOperate) { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get "IN FILE" parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.IN); + + if (localParamsProperty.isEmpty()) { + return; + } + + String executePath = taskExecutionContext.getExecutePath(); + // data path to download packaged data + String DownloadTmpPath = String.format("%s/%s", executePath, DOWNLOAD_TMP); + + logger.info("Download upstream files..."); + for (Property property : localParamsProperty) { + Property inVarPool = varPoolsMap.get(property.getValue()); + if (inVarPool == null) { + logger.error(String.format("%s not in %s", property.getValue(), varPoolsMap.keySet())); + throw new TaskException(String.format("Can not find upstream file using %s, please check the key", + property.getValue())); + } + + String resourcePath = inVarPool.getValue(); + String targetPath = String.format("%s/%s", executePath, property.getProp()); + + String downloadPath; + // If the data is packaged, download it to a special directory (DOWNLOAD_TMP) and unpack it to the + // targetPath + boolean isPack = resourcePath.endsWith(PACK_SUFFIX); + if (isPack) { + downloadPath = String.format("%s/%s", DownloadTmpPath, new File(resourcePath).getName()); + } else { + downloadPath = targetPath; + } + + try { + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Remote:{} to Local:{}", property, resourceWholePath, downloadPath); + storageOperate.download(taskExecutionContext.getTenantCode(), resourceWholePath, downloadPath, false, + true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // unpack if the data is packaged + if (isPack) { + File downloadFile = new File(downloadPath); + logger.info("Unpack {} to {}", downloadPath, targetPath); + ZipUtil.unpack(downloadFile, new File(targetPath)); + } + } + + // delete DownloadTmp Folder if DownloadTmpPath exists + try { + org.apache.commons.io.FileUtils.deleteDirectory(new File(DownloadTmpPath)); + } catch (IOException e) { + logger.error( + "Delete DownloadTmpPath {} failed, this will not affect the task status", DownloadTmpPath, e); + } + } + + /** + * get local parameters property which type is FILE and direction is equal to direct + * + * @param taskExecutionContext, TaskExecutionContext + * @param direct, Direct, may be Direct.IN or Direct.OUT. + * @return List<Property> + */ + public static List<Property> getFileLocalParams(TaskExecutionContext taskExecutionContext, Direct direct) { + List<Property> localParamsProperty = new ArrayList<>(); + JsonNode taskParams = JSONUtils.parseObject(taskExecutionContext.getTaskParams()); + for (JsonNode localParam : taskParams.get("localParams")) { + Property property = JSONUtils.parseObject(localParam.toString(), Property.class); + + if (property.getDirect().equals(direct) & property.getType().equals(DataType.FILE)) { Review Comment: ## Dangerous non-short-circuit logic Possibly dangerous use of non-short circuit logic. [Show more details](https://github.com/apache/dolphinscheduler/security/code-scanning/2131) ########## dolphinscheduler-worker/src/main/java/org/apache/dolphinscheduler/server/worker/utils/TaskFilesTransferUtils.java: ########## @@ -0,0 +1,267 @@ +/* + * 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 + * + * http://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. + */ + +package org.apache.dolphinscheduler.server.worker.utils; + +import org.apache.dolphinscheduler.common.utils.DateUtils; +import org.apache.dolphinscheduler.common.utils.JSONUtils; +import org.apache.dolphinscheduler.plugin.task.api.TaskConstants; +import org.apache.dolphinscheduler.plugin.task.api.TaskException; +import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext; +import org.apache.dolphinscheduler.plugin.task.api.enums.DataType; +import org.apache.dolphinscheduler.plugin.task.api.enums.Direct; +import org.apache.dolphinscheduler.plugin.task.api.model.Property; +import org.apache.dolphinscheduler.service.storage.StorageOperate; + +import org.apache.commons.lang3.StringUtils; + +import java.io.File; +import java.io.IOException; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.zeroturnaround.zip.ZipUtil; + +import com.fasterxml.jackson.databind.JsonNode; + +public class TaskFilesTransferUtils { + + protected final static Logger logger = LoggerFactory + .getLogger(String.format(TaskConstants.TASK_LOG_LOGGER_NAME_FORMAT, TaskFilesTransferUtils.class)); + + // root path in resource storage + final static String RESOURCE_TAG = "DATA_TRANSFER"; + + // tmp path in local path for transfer + final static String DOWNLOAD_TMP = ".DT_TMP"; + + // suffix of the package file + final static String PACK_SUFFIX = "_ds_pack.zip"; + + /** + * upload output files to resource storage + * + * @param taskExecutionContext taskExecutionContext + * @param storageOperate storageOperate + * @throws TaskException TaskException + */ + public static void uploadOutputFiles(StorageOperate storageOperate, + TaskExecutionContext taskExecutionContext) throws TaskException { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get OUTPUT FILE parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.OUT); + + if (localParamsProperty.isEmpty()) { + return; + } + + logger.info("Upload output files ..."); + for (Property property : localParamsProperty) { + // get local file path + String srcPath = + packIfDir(String.format("%s/%s", taskExecutionContext.getExecutePath(), property.getValue())); + // get remote file path + String resourcePath = getResourcePath(taskExecutionContext, new File(srcPath).getName()); + try { + // upload file to storage + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Local:{} to Remote:{}", property, srcPath, resourceWholePath); + storageOperate.upload(taskExecutionContext.getTenantCode(), srcPath, resourceWholePath, false, true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // update varPool + Property oriProperty; + // if the property is not in varPool, add it + if (varPoolsMap.containsKey(property.getProp())) { + oriProperty = varPoolsMap.get(property.getProp()); + } else { + oriProperty = new Property(property.getProp(), Direct.OUT, DataType.FILE, property.getValue()); + varPools.add(oriProperty); + } + oriProperty.setProp(String.format("%s.%s", taskExecutionContext.getTaskName(), oriProperty.getProp())); + oriProperty.setValue(resourcePath); + } + taskExecutionContext.setVarPool(JSONUtils.toJsonString(varPools)); + } + + /** + * download upstream files from storage + * only download files which are defined in the task parameters + * + * @param storageOperate storage operate + * @param taskExecutionContext taskExecutionContext + * @throws TaskException task exception + */ + public static void downloadUpstreamFiles(TaskExecutionContext taskExecutionContext, StorageOperate storageOperate) { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get "IN FILE" parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.IN); + + if (localParamsProperty.isEmpty()) { + return; + } + + String executePath = taskExecutionContext.getExecutePath(); + // data path to download packaged data + String DownloadTmpPath = String.format("%s/%s", executePath, DOWNLOAD_TMP); + + logger.info("Download upstream files..."); + for (Property property : localParamsProperty) { + Property inVarPool = varPoolsMap.get(property.getValue()); + if (inVarPool == null) { + logger.error(String.format("%s not in %s", property.getValue(), varPoolsMap.keySet())); + throw new TaskException(String.format("Can not find upstream file using %s, please check the key", + property.getValue())); + } + + String resourcePath = inVarPool.getValue(); + String targetPath = String.format("%s/%s", executePath, property.getProp()); + + String downloadPath; + // If the data is packaged, download it to a special directory (DOWNLOAD_TMP) and unpack it to the + // targetPath + boolean isPack = resourcePath.endsWith(PACK_SUFFIX); + if (isPack) { + downloadPath = String.format("%s/%s", DownloadTmpPath, new File(resourcePath).getName()); + } else { + downloadPath = targetPath; + } + + try { + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Remote:{} to Local:{}", property, resourceWholePath, downloadPath); + storageOperate.download(taskExecutionContext.getTenantCode(), resourceWholePath, downloadPath, false, + true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // unpack if the data is packaged + if (isPack) { + File downloadFile = new File(downloadPath); + logger.info("Unpack {} to {}", downloadPath, targetPath); + ZipUtil.unpack(downloadFile, new File(targetPath)); + } + } + + // delete DownloadTmp Folder if DownloadTmpPath exists + try { + org.apache.commons.io.FileUtils.deleteDirectory(new File(DownloadTmpPath)); + } catch (IOException e) { + logger.error( + "Delete DownloadTmpPath {} failed, this will not affect the task status", DownloadTmpPath, e); + } + } + + /** + * get local parameters property which type is FILE and direction is equal to direct + * + * @param taskExecutionContext, TaskExecutionContext + * @param direct, Direct, may be Direct.IN or Direct.OUT. Review Comment: ## Spurious Javadoc @param tags @param tag "direct," does not match any actual parameter of method "getFileLocalParams()". [Show more details](https://github.com/apache/dolphinscheduler/security/code-scanning/2125) ########## dolphinscheduler-worker/src/main/java/org/apache/dolphinscheduler/server/worker/utils/TaskFilesTransferUtils.java: ########## @@ -0,0 +1,267 @@ +/* + * 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 + * + * http://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. + */ + +package org.apache.dolphinscheduler.server.worker.utils; + +import org.apache.dolphinscheduler.common.utils.DateUtils; +import org.apache.dolphinscheduler.common.utils.JSONUtils; +import org.apache.dolphinscheduler.plugin.task.api.TaskConstants; +import org.apache.dolphinscheduler.plugin.task.api.TaskException; +import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext; +import org.apache.dolphinscheduler.plugin.task.api.enums.DataType; +import org.apache.dolphinscheduler.plugin.task.api.enums.Direct; +import org.apache.dolphinscheduler.plugin.task.api.model.Property; +import org.apache.dolphinscheduler.service.storage.StorageOperate; + +import org.apache.commons.lang3.StringUtils; + +import java.io.File; +import java.io.IOException; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.zeroturnaround.zip.ZipUtil; + +import com.fasterxml.jackson.databind.JsonNode; + +public class TaskFilesTransferUtils { + + protected final static Logger logger = LoggerFactory + .getLogger(String.format(TaskConstants.TASK_LOG_LOGGER_NAME_FORMAT, TaskFilesTransferUtils.class)); + + // root path in resource storage + final static String RESOURCE_TAG = "DATA_TRANSFER"; + + // tmp path in local path for transfer + final static String DOWNLOAD_TMP = ".DT_TMP"; + + // suffix of the package file + final static String PACK_SUFFIX = "_ds_pack.zip"; + + /** + * upload output files to resource storage + * + * @param taskExecutionContext taskExecutionContext + * @param storageOperate storageOperate + * @throws TaskException TaskException + */ + public static void uploadOutputFiles(StorageOperate storageOperate, + TaskExecutionContext taskExecutionContext) throws TaskException { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get OUTPUT FILE parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.OUT); + + if (localParamsProperty.isEmpty()) { + return; + } + + logger.info("Upload output files ..."); + for (Property property : localParamsProperty) { + // get local file path + String srcPath = + packIfDir(String.format("%s/%s", taskExecutionContext.getExecutePath(), property.getValue())); + // get remote file path + String resourcePath = getResourcePath(taskExecutionContext, new File(srcPath).getName()); + try { + // upload file to storage + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Local:{} to Remote:{}", property, srcPath, resourceWholePath); + storageOperate.upload(taskExecutionContext.getTenantCode(), srcPath, resourceWholePath, false, true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // update varPool + Property oriProperty; + // if the property is not in varPool, add it + if (varPoolsMap.containsKey(property.getProp())) { + oriProperty = varPoolsMap.get(property.getProp()); + } else { + oriProperty = new Property(property.getProp(), Direct.OUT, DataType.FILE, property.getValue()); + varPools.add(oriProperty); + } + oriProperty.setProp(String.format("%s.%s", taskExecutionContext.getTaskName(), oriProperty.getProp())); + oriProperty.setValue(resourcePath); + } + taskExecutionContext.setVarPool(JSONUtils.toJsonString(varPools)); + } + + /** + * download upstream files from storage + * only download files which are defined in the task parameters + * + * @param storageOperate storage operate + * @param taskExecutionContext taskExecutionContext + * @throws TaskException task exception + */ + public static void downloadUpstreamFiles(TaskExecutionContext taskExecutionContext, StorageOperate storageOperate) { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get "IN FILE" parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.IN); + + if (localParamsProperty.isEmpty()) { + return; + } + + String executePath = taskExecutionContext.getExecutePath(); + // data path to download packaged data + String DownloadTmpPath = String.format("%s/%s", executePath, DOWNLOAD_TMP); + + logger.info("Download upstream files..."); + for (Property property : localParamsProperty) { + Property inVarPool = varPoolsMap.get(property.getValue()); + if (inVarPool == null) { + logger.error(String.format("%s not in %s", property.getValue(), varPoolsMap.keySet())); + throw new TaskException(String.format("Can not find upstream file using %s, please check the key", + property.getValue())); + } + + String resourcePath = inVarPool.getValue(); + String targetPath = String.format("%s/%s", executePath, property.getProp()); + + String downloadPath; + // If the data is packaged, download it to a special directory (DOWNLOAD_TMP) and unpack it to the + // targetPath + boolean isPack = resourcePath.endsWith(PACK_SUFFIX); + if (isPack) { + downloadPath = String.format("%s/%s", DownloadTmpPath, new File(resourcePath).getName()); + } else { + downloadPath = targetPath; + } + + try { + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Remote:{} to Local:{}", property, resourceWholePath, downloadPath); + storageOperate.download(taskExecutionContext.getTenantCode(), resourceWholePath, downloadPath, false, + true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // unpack if the data is packaged + if (isPack) { + File downloadFile = new File(downloadPath); + logger.info("Unpack {} to {}", downloadPath, targetPath); + ZipUtil.unpack(downloadFile, new File(targetPath)); + } + } + + // delete DownloadTmp Folder if DownloadTmpPath exists + try { + org.apache.commons.io.FileUtils.deleteDirectory(new File(DownloadTmpPath)); + } catch (IOException e) { + logger.error( + "Delete DownloadTmpPath {} failed, this will not affect the task status", DownloadTmpPath, e); + } + } + + /** + * get local parameters property which type is FILE and direction is equal to direct + * + * @param taskExecutionContext, TaskExecutionContext Review Comment: ## Spurious Javadoc @param tags @param tag "taskExecutionContext," does not match any actual parameter of method "getFileLocalParams()". [Show more details](https://github.com/apache/dolphinscheduler/security/code-scanning/2124) ########## dolphinscheduler-worker/src/main/java/org/apache/dolphinscheduler/server/worker/utils/TaskFilesTransferUtils.java: ########## @@ -0,0 +1,267 @@ +/* + * 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 + * + * http://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. + */ + +package org.apache.dolphinscheduler.server.worker.utils; + +import org.apache.dolphinscheduler.common.utils.DateUtils; +import org.apache.dolphinscheduler.common.utils.JSONUtils; +import org.apache.dolphinscheduler.plugin.task.api.TaskConstants; +import org.apache.dolphinscheduler.plugin.task.api.TaskException; +import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext; +import org.apache.dolphinscheduler.plugin.task.api.enums.DataType; +import org.apache.dolphinscheduler.plugin.task.api.enums.Direct; +import org.apache.dolphinscheduler.plugin.task.api.model.Property; +import org.apache.dolphinscheduler.service.storage.StorageOperate; + +import org.apache.commons.lang3.StringUtils; + +import java.io.File; +import java.io.IOException; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.zeroturnaround.zip.ZipUtil; + +import com.fasterxml.jackson.databind.JsonNode; + +public class TaskFilesTransferUtils { + + protected final static Logger logger = LoggerFactory + .getLogger(String.format(TaskConstants.TASK_LOG_LOGGER_NAME_FORMAT, TaskFilesTransferUtils.class)); + + // root path in resource storage + final static String RESOURCE_TAG = "DATA_TRANSFER"; + + // tmp path in local path for transfer + final static String DOWNLOAD_TMP = ".DT_TMP"; + + // suffix of the package file + final static String PACK_SUFFIX = "_ds_pack.zip"; + + /** + * upload output files to resource storage + * + * @param taskExecutionContext taskExecutionContext + * @param storageOperate storageOperate + * @throws TaskException TaskException + */ + public static void uploadOutputFiles(StorageOperate storageOperate, + TaskExecutionContext taskExecutionContext) throws TaskException { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get OUTPUT FILE parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.OUT); + + if (localParamsProperty.isEmpty()) { + return; + } + + logger.info("Upload output files ..."); + for (Property property : localParamsProperty) { + // get local file path + String srcPath = + packIfDir(String.format("%s/%s", taskExecutionContext.getExecutePath(), property.getValue())); + // get remote file path + String resourcePath = getResourcePath(taskExecutionContext, new File(srcPath).getName()); + try { + // upload file to storage + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Local:{} to Remote:{}", property, srcPath, resourceWholePath); + storageOperate.upload(taskExecutionContext.getTenantCode(), srcPath, resourceWholePath, false, true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // update varPool + Property oriProperty; + // if the property is not in varPool, add it + if (varPoolsMap.containsKey(property.getProp())) { + oriProperty = varPoolsMap.get(property.getProp()); + } else { + oriProperty = new Property(property.getProp(), Direct.OUT, DataType.FILE, property.getValue()); + varPools.add(oriProperty); + } + oriProperty.setProp(String.format("%s.%s", taskExecutionContext.getTaskName(), oriProperty.getProp())); + oriProperty.setValue(resourcePath); + } + taskExecutionContext.setVarPool(JSONUtils.toJsonString(varPools)); + } + + /** + * download upstream files from storage + * only download files which are defined in the task parameters + * + * @param storageOperate storage operate + * @param taskExecutionContext taskExecutionContext + * @throws TaskException task exception + */ + public static void downloadUpstreamFiles(TaskExecutionContext taskExecutionContext, StorageOperate storageOperate) { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get "IN FILE" parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.IN); + + if (localParamsProperty.isEmpty()) { + return; + } + + String executePath = taskExecutionContext.getExecutePath(); + // data path to download packaged data + String DownloadTmpPath = String.format("%s/%s", executePath, DOWNLOAD_TMP); + + logger.info("Download upstream files..."); + for (Property property : localParamsProperty) { + Property inVarPool = varPoolsMap.get(property.getValue()); + if (inVarPool == null) { + logger.error(String.format("%s not in %s", property.getValue(), varPoolsMap.keySet())); + throw new TaskException(String.format("Can not find upstream file using %s, please check the key", + property.getValue())); + } + + String resourcePath = inVarPool.getValue(); + String targetPath = String.format("%s/%s", executePath, property.getProp()); + + String downloadPath; + // If the data is packaged, download it to a special directory (DOWNLOAD_TMP) and unpack it to the + // targetPath + boolean isPack = resourcePath.endsWith(PACK_SUFFIX); + if (isPack) { + downloadPath = String.format("%s/%s", DownloadTmpPath, new File(resourcePath).getName()); + } else { + downloadPath = targetPath; + } + + try { + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Remote:{} to Local:{}", property, resourceWholePath, downloadPath); + storageOperate.download(taskExecutionContext.getTenantCode(), resourceWholePath, downloadPath, false, + true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // unpack if the data is packaged + if (isPack) { + File downloadFile = new File(downloadPath); + logger.info("Unpack {} to {}", downloadPath, targetPath); + ZipUtil.unpack(downloadFile, new File(targetPath)); + } + } + + // delete DownloadTmp Folder if DownloadTmpPath exists + try { + org.apache.commons.io.FileUtils.deleteDirectory(new File(DownloadTmpPath)); + } catch (IOException e) { + logger.error( + "Delete DownloadTmpPath {} failed, this will not affect the task status", DownloadTmpPath, e); + } + } + + /** + * get local parameters property which type is FILE and direction is equal to direct + * + * @param taskExecutionContext, TaskExecutionContext + * @param direct, Direct, may be Direct.IN or Direct.OUT. + * @return List<Property> + */ + public static List<Property> getFileLocalParams(TaskExecutionContext taskExecutionContext, Direct direct) { + List<Property> localParamsProperty = new ArrayList<>(); + JsonNode taskParams = JSONUtils.parseObject(taskExecutionContext.getTaskParams()); + for (JsonNode localParam : taskParams.get("localParams")) { + Property property = JSONUtils.parseObject(localParam.toString(), Property.class); + + if (property.getDirect().equals(direct) & property.getType().equals(DataType.FILE)) { + localParamsProperty.add(property); + } + } + return localParamsProperty; + } + + /** + * get Resource path for manage files in storage + * + * @param taskExecutionContext, TaskExecutionContext + * @param fileName, String, file name + * @return resource path, RESOURCE_TAG/DATE/ProcessDefineCode/ProcessDefineVersion_ProcessInstanceID/TaskName_TaskInstanceID_FileName + */ + public static String getResourcePath(TaskExecutionContext taskExecutionContext, String fileName) { + String date = + DateUtils.formatTimeStamp(taskExecutionContext.getEndTime(), DateTimeFormatter.ofPattern("yyyyMMdd")); + // get resource Folder: RESOURCE_TAG/DATE/ProcessDefineCode/ProcessDefineVersion_ProcessInstanceID + String resourceFolder = + String.format("%s/%s/%d/%d_%d", RESOURCE_TAG, date, taskExecutionContext.getProcessDefineCode(), + taskExecutionContext.getProcessDefineVersion(), taskExecutionContext.getProcessInstanceId()); + // get resource fileL: resourceFolder/TaskName_TaskInstanceID_FileName + return String.format("%s/%s_%s_%s", resourceFolder, taskExecutionContext.getTaskName().replace(" ", "_"), + taskExecutionContext.getTaskInstanceId(), fileName); + } + + /** + * get varPool from taskExecutionContext + * + * @param taskExecutionContext, TaskExecutionContext + * @return List<Property> + */ + public static List<Property> getVarPools(TaskExecutionContext taskExecutionContext) { + List<Property> varPools = new ArrayList<>(); + + // get varPool + String varPoolString = taskExecutionContext.getVarPool(); + if (StringUtils.isEmpty(varPoolString)) { + return varPools; + } + // parse varPool + for (JsonNode varPoolData : JSONUtils.parseArray(varPoolString)) { + Property property = JSONUtils.parseObject(varPoolData.toString(), Property.class); + varPools.add(property); + } + return varPools; + } + + /** + * If the path is a directory, pack it and return the path of the package + * + * @param path, input path, may be a file or a directory Review Comment: ## Spurious Javadoc @param tags @param tag "path," does not match any actual parameter of method "packIfDir()". [Show more details](https://github.com/apache/dolphinscheduler/security/code-scanning/2129) ########## dolphinscheduler-worker/src/main/java/org/apache/dolphinscheduler/server/worker/utils/TaskFilesTransferUtils.java: ########## @@ -0,0 +1,267 @@ +/* + * 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 + * + * http://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. + */ + +package org.apache.dolphinscheduler.server.worker.utils; + +import org.apache.dolphinscheduler.common.utils.DateUtils; +import org.apache.dolphinscheduler.common.utils.JSONUtils; +import org.apache.dolphinscheduler.plugin.task.api.TaskConstants; +import org.apache.dolphinscheduler.plugin.task.api.TaskException; +import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext; +import org.apache.dolphinscheduler.plugin.task.api.enums.DataType; +import org.apache.dolphinscheduler.plugin.task.api.enums.Direct; +import org.apache.dolphinscheduler.plugin.task.api.model.Property; +import org.apache.dolphinscheduler.service.storage.StorageOperate; + +import org.apache.commons.lang3.StringUtils; + +import java.io.File; +import java.io.IOException; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.zeroturnaround.zip.ZipUtil; + +import com.fasterxml.jackson.databind.JsonNode; + +public class TaskFilesTransferUtils { + + protected final static Logger logger = LoggerFactory + .getLogger(String.format(TaskConstants.TASK_LOG_LOGGER_NAME_FORMAT, TaskFilesTransferUtils.class)); + + // root path in resource storage + final static String RESOURCE_TAG = "DATA_TRANSFER"; + + // tmp path in local path for transfer + final static String DOWNLOAD_TMP = ".DT_TMP"; + + // suffix of the package file + final static String PACK_SUFFIX = "_ds_pack.zip"; + + /** + * upload output files to resource storage + * + * @param taskExecutionContext taskExecutionContext + * @param storageOperate storageOperate + * @throws TaskException TaskException + */ + public static void uploadOutputFiles(StorageOperate storageOperate, + TaskExecutionContext taskExecutionContext) throws TaskException { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get OUTPUT FILE parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.OUT); + + if (localParamsProperty.isEmpty()) { + return; + } + + logger.info("Upload output files ..."); + for (Property property : localParamsProperty) { + // get local file path + String srcPath = + packIfDir(String.format("%s/%s", taskExecutionContext.getExecutePath(), property.getValue())); + // get remote file path + String resourcePath = getResourcePath(taskExecutionContext, new File(srcPath).getName()); + try { + // upload file to storage + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Local:{} to Remote:{}", property, srcPath, resourceWholePath); + storageOperate.upload(taskExecutionContext.getTenantCode(), srcPath, resourceWholePath, false, true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // update varPool + Property oriProperty; + // if the property is not in varPool, add it + if (varPoolsMap.containsKey(property.getProp())) { + oriProperty = varPoolsMap.get(property.getProp()); + } else { + oriProperty = new Property(property.getProp(), Direct.OUT, DataType.FILE, property.getValue()); + varPools.add(oriProperty); + } + oriProperty.setProp(String.format("%s.%s", taskExecutionContext.getTaskName(), oriProperty.getProp())); + oriProperty.setValue(resourcePath); + } + taskExecutionContext.setVarPool(JSONUtils.toJsonString(varPools)); + } + + /** + * download upstream files from storage + * only download files which are defined in the task parameters + * + * @param storageOperate storage operate + * @param taskExecutionContext taskExecutionContext + * @throws TaskException task exception + */ + public static void downloadUpstreamFiles(TaskExecutionContext taskExecutionContext, StorageOperate storageOperate) { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get "IN FILE" parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.IN); + + if (localParamsProperty.isEmpty()) { + return; + } + + String executePath = taskExecutionContext.getExecutePath(); + // data path to download packaged data + String DownloadTmpPath = String.format("%s/%s", executePath, DOWNLOAD_TMP); + + logger.info("Download upstream files..."); + for (Property property : localParamsProperty) { + Property inVarPool = varPoolsMap.get(property.getValue()); + if (inVarPool == null) { + logger.error(String.format("%s not in %s", property.getValue(), varPoolsMap.keySet())); + throw new TaskException(String.format("Can not find upstream file using %s, please check the key", + property.getValue())); + } + + String resourcePath = inVarPool.getValue(); + String targetPath = String.format("%s/%s", executePath, property.getProp()); + + String downloadPath; + // If the data is packaged, download it to a special directory (DOWNLOAD_TMP) and unpack it to the + // targetPath + boolean isPack = resourcePath.endsWith(PACK_SUFFIX); + if (isPack) { + downloadPath = String.format("%s/%s", DownloadTmpPath, new File(resourcePath).getName()); + } else { + downloadPath = targetPath; + } + + try { + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Remote:{} to Local:{}", property, resourceWholePath, downloadPath); + storageOperate.download(taskExecutionContext.getTenantCode(), resourceWholePath, downloadPath, false, + true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // unpack if the data is packaged + if (isPack) { + File downloadFile = new File(downloadPath); + logger.info("Unpack {} to {}", downloadPath, targetPath); + ZipUtil.unpack(downloadFile, new File(targetPath)); + } + } + + // delete DownloadTmp Folder if DownloadTmpPath exists + try { + org.apache.commons.io.FileUtils.deleteDirectory(new File(DownloadTmpPath)); + } catch (IOException e) { + logger.error( + "Delete DownloadTmpPath {} failed, this will not affect the task status", DownloadTmpPath, e); + } + } + + /** + * get local parameters property which type is FILE and direction is equal to direct + * + * @param taskExecutionContext, TaskExecutionContext + * @param direct, Direct, may be Direct.IN or Direct.OUT. + * @return List<Property> + */ + public static List<Property> getFileLocalParams(TaskExecutionContext taskExecutionContext, Direct direct) { + List<Property> localParamsProperty = new ArrayList<>(); + JsonNode taskParams = JSONUtils.parseObject(taskExecutionContext.getTaskParams()); + for (JsonNode localParam : taskParams.get("localParams")) { + Property property = JSONUtils.parseObject(localParam.toString(), Property.class); + + if (property.getDirect().equals(direct) & property.getType().equals(DataType.FILE)) { + localParamsProperty.add(property); + } + } + return localParamsProperty; + } + + /** + * get Resource path for manage files in storage + * + * @param taskExecutionContext, TaskExecutionContext + * @param fileName, String, file name + * @return resource path, RESOURCE_TAG/DATE/ProcessDefineCode/ProcessDefineVersion_ProcessInstanceID/TaskName_TaskInstanceID_FileName + */ + public static String getResourcePath(TaskExecutionContext taskExecutionContext, String fileName) { + String date = + DateUtils.formatTimeStamp(taskExecutionContext.getEndTime(), DateTimeFormatter.ofPattern("yyyyMMdd")); + // get resource Folder: RESOURCE_TAG/DATE/ProcessDefineCode/ProcessDefineVersion_ProcessInstanceID + String resourceFolder = + String.format("%s/%s/%d/%d_%d", RESOURCE_TAG, date, taskExecutionContext.getProcessDefineCode(), + taskExecutionContext.getProcessDefineVersion(), taskExecutionContext.getProcessInstanceId()); + // get resource fileL: resourceFolder/TaskName_TaskInstanceID_FileName + return String.format("%s/%s_%s_%s", resourceFolder, taskExecutionContext.getTaskName().replace(" ", "_"), + taskExecutionContext.getTaskInstanceId(), fileName); + } + + /** + * get varPool from taskExecutionContext + * + * @param taskExecutionContext, TaskExecutionContext Review Comment: ## Spurious Javadoc @param tags @param tag "taskExecutionContext," does not match any actual parameter of method "getVarPools()". [Show more details](https://github.com/apache/dolphinscheduler/security/code-scanning/2128) ########## dolphinscheduler-worker/src/test/java/org/apache/dolphinscheduler/server/worker/utils/TaskFilesTransferUtilsTest.java: ########## @@ -0,0 +1,145 @@ +/* + * 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 + * + * http://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. + */ + +package org.apache.dolphinscheduler.server.worker.utils; + +import org.apache.dolphinscheduler.common.utils.DateUtils; +import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext; +import org.apache.dolphinscheduler.plugin.task.api.enums.DataType; +import org.apache.dolphinscheduler.plugin.task.api.enums.Direct; +import org.apache.dolphinscheduler.plugin.task.api.model.Property; + +import org.apache.curator.shaded.com.google.common.io.Files; + +import java.io.File; +import java.time.format.DateTimeFormatter; +import java.util.List; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +public class TaskFilesTransferUtilsTest { + + @Test + public void testGetFileLocalParams() { + String taskParmas = "{\"localParams\":[" + + "{\"prop\":\"inputFile\",\"direct\":\"IN\",\"type\":\"FILE\",\"value\":\"task1.data\"}," + + "{\"prop\":\"outputFile\",\"direct\":\"OUT\",\"type\":\"FILE\",\"value\":\"data\"}," + + "{\"prop\":\"a\",\"direct\":\"IN\",\"type\":\"VARCHAR\",\"value\":\"a\"}," + + "{\"prop\":\"b\",\"direct\":\"OUT\",\"type\":\"VARCHAR\",\"value\":\"b\"}" + + "]}"; + TaskExecutionContext taskExecutionContext = Mockito.mock(TaskExecutionContext.class); + Mockito.when(taskExecutionContext.getTaskParams()).thenReturn(taskParmas); + + List<Property> fileLocalParamsIn = TaskFilesTransferUtils.getFileLocalParams(taskExecutionContext, Direct.IN); + Assertions.assertEquals(1, fileLocalParamsIn.size()); + Assertions.assertEquals("inputFile", fileLocalParamsIn.get(0).getProp()); + Assertions.assertEquals("task1.data", fileLocalParamsIn.get(0).getValue()); + + List<Property> fileLocalParamsOut = TaskFilesTransferUtils.getFileLocalParams(taskExecutionContext, Direct.OUT); + Assertions.assertEquals(1, fileLocalParamsOut.size()); + Assertions.assertEquals("outputFile", fileLocalParamsOut.get(0).getProp()); + Assertions.assertEquals("data", fileLocalParamsOut.get(0).getValue()); + + } + + @Test + public void testGetResourcePath() { + String fileName = "test.txt"; + TaskExecutionContext taskExecutionContext = Mockito.mock(TaskExecutionContext.class); + + long endTime = System.currentTimeMillis(); + String date = DateUtils.formatTimeStamp(endTime, DateTimeFormatter.ofPattern("yyyyMMdd")); + Mockito.when(taskExecutionContext.getEndTime()).thenReturn(endTime); + + Long processDefineCode = 123L; Review Comment: ## Boxed variable is never null The variable 'processDefineCode' is only assigned values of primitive type and is never 'null', but it is declared with the boxed type 'Long'. [Show more details](https://github.com/apache/dolphinscheduler/security/code-scanning/2130) ########## dolphinscheduler-worker/src/main/java/org/apache/dolphinscheduler/server/worker/utils/TaskFilesTransferUtils.java: ########## @@ -0,0 +1,267 @@ +/* + * 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 + * + * http://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. + */ + +package org.apache.dolphinscheduler.server.worker.utils; + +import org.apache.dolphinscheduler.common.utils.DateUtils; +import org.apache.dolphinscheduler.common.utils.JSONUtils; +import org.apache.dolphinscheduler.plugin.task.api.TaskConstants; +import org.apache.dolphinscheduler.plugin.task.api.TaskException; +import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext; +import org.apache.dolphinscheduler.plugin.task.api.enums.DataType; +import org.apache.dolphinscheduler.plugin.task.api.enums.Direct; +import org.apache.dolphinscheduler.plugin.task.api.model.Property; +import org.apache.dolphinscheduler.service.storage.StorageOperate; + +import org.apache.commons.lang3.StringUtils; + +import java.io.File; +import java.io.IOException; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.zeroturnaround.zip.ZipUtil; + +import com.fasterxml.jackson.databind.JsonNode; + +public class TaskFilesTransferUtils { + + protected final static Logger logger = LoggerFactory + .getLogger(String.format(TaskConstants.TASK_LOG_LOGGER_NAME_FORMAT, TaskFilesTransferUtils.class)); + + // root path in resource storage + final static String RESOURCE_TAG = "DATA_TRANSFER"; + + // tmp path in local path for transfer + final static String DOWNLOAD_TMP = ".DT_TMP"; + + // suffix of the package file + final static String PACK_SUFFIX = "_ds_pack.zip"; + + /** + * upload output files to resource storage + * + * @param taskExecutionContext taskExecutionContext + * @param storageOperate storageOperate + * @throws TaskException TaskException + */ + public static void uploadOutputFiles(StorageOperate storageOperate, + TaskExecutionContext taskExecutionContext) throws TaskException { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get OUTPUT FILE parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.OUT); + + if (localParamsProperty.isEmpty()) { + return; + } + + logger.info("Upload output files ..."); + for (Property property : localParamsProperty) { + // get local file path + String srcPath = + packIfDir(String.format("%s/%s", taskExecutionContext.getExecutePath(), property.getValue())); + // get remote file path + String resourcePath = getResourcePath(taskExecutionContext, new File(srcPath).getName()); + try { + // upload file to storage + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Local:{} to Remote:{}", property, srcPath, resourceWholePath); + storageOperate.upload(taskExecutionContext.getTenantCode(), srcPath, resourceWholePath, false, true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // update varPool + Property oriProperty; + // if the property is not in varPool, add it + if (varPoolsMap.containsKey(property.getProp())) { + oriProperty = varPoolsMap.get(property.getProp()); + } else { + oriProperty = new Property(property.getProp(), Direct.OUT, DataType.FILE, property.getValue()); + varPools.add(oriProperty); + } + oriProperty.setProp(String.format("%s.%s", taskExecutionContext.getTaskName(), oriProperty.getProp())); + oriProperty.setValue(resourcePath); + } + taskExecutionContext.setVarPool(JSONUtils.toJsonString(varPools)); + } + + /** + * download upstream files from storage + * only download files which are defined in the task parameters + * + * @param storageOperate storage operate + * @param taskExecutionContext taskExecutionContext + * @throws TaskException task exception + */ + public static void downloadUpstreamFiles(TaskExecutionContext taskExecutionContext, StorageOperate storageOperate) { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get "IN FILE" parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.IN); + + if (localParamsProperty.isEmpty()) { + return; + } + + String executePath = taskExecutionContext.getExecutePath(); + // data path to download packaged data + String DownloadTmpPath = String.format("%s/%s", executePath, DOWNLOAD_TMP); + + logger.info("Download upstream files..."); + for (Property property : localParamsProperty) { + Property inVarPool = varPoolsMap.get(property.getValue()); + if (inVarPool == null) { + logger.error(String.format("%s not in %s", property.getValue(), varPoolsMap.keySet())); + throw new TaskException(String.format("Can not find upstream file using %s, please check the key", + property.getValue())); + } + + String resourcePath = inVarPool.getValue(); + String targetPath = String.format("%s/%s", executePath, property.getProp()); + + String downloadPath; + // If the data is packaged, download it to a special directory (DOWNLOAD_TMP) and unpack it to the + // targetPath + boolean isPack = resourcePath.endsWith(PACK_SUFFIX); + if (isPack) { + downloadPath = String.format("%s/%s", DownloadTmpPath, new File(resourcePath).getName()); + } else { + downloadPath = targetPath; + } + + try { + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Remote:{} to Local:{}", property, resourceWholePath, downloadPath); + storageOperate.download(taskExecutionContext.getTenantCode(), resourceWholePath, downloadPath, false, + true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // unpack if the data is packaged + if (isPack) { + File downloadFile = new File(downloadPath); + logger.info("Unpack {} to {}", downloadPath, targetPath); + ZipUtil.unpack(downloadFile, new File(targetPath)); + } + } + + // delete DownloadTmp Folder if DownloadTmpPath exists + try { + org.apache.commons.io.FileUtils.deleteDirectory(new File(DownloadTmpPath)); + } catch (IOException e) { + logger.error( + "Delete DownloadTmpPath {} failed, this will not affect the task status", DownloadTmpPath, e); + } + } + + /** + * get local parameters property which type is FILE and direction is equal to direct + * + * @param taskExecutionContext, TaskExecutionContext + * @param direct, Direct, may be Direct.IN or Direct.OUT. + * @return List<Property> + */ + public static List<Property> getFileLocalParams(TaskExecutionContext taskExecutionContext, Direct direct) { + List<Property> localParamsProperty = new ArrayList<>(); + JsonNode taskParams = JSONUtils.parseObject(taskExecutionContext.getTaskParams()); + for (JsonNode localParam : taskParams.get("localParams")) { + Property property = JSONUtils.parseObject(localParam.toString(), Property.class); + + if (property.getDirect().equals(direct) & property.getType().equals(DataType.FILE)) { + localParamsProperty.add(property); + } + } + return localParamsProperty; + } + + /** + * get Resource path for manage files in storage + * + * @param taskExecutionContext, TaskExecutionContext Review Comment: ## Spurious Javadoc @param tags @param tag "taskExecutionContext," does not match any actual parameter of method "getResourcePath()". [Show more details](https://github.com/apache/dolphinscheduler/security/code-scanning/2126) ########## dolphinscheduler-worker/src/main/java/org/apache/dolphinscheduler/server/worker/utils/TaskFilesTransferUtils.java: ########## @@ -0,0 +1,267 @@ +/* + * 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 + * + * http://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. + */ + +package org.apache.dolphinscheduler.server.worker.utils; + +import org.apache.dolphinscheduler.common.utils.DateUtils; +import org.apache.dolphinscheduler.common.utils.JSONUtils; +import org.apache.dolphinscheduler.plugin.task.api.TaskConstants; +import org.apache.dolphinscheduler.plugin.task.api.TaskException; +import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext; +import org.apache.dolphinscheduler.plugin.task.api.enums.DataType; +import org.apache.dolphinscheduler.plugin.task.api.enums.Direct; +import org.apache.dolphinscheduler.plugin.task.api.model.Property; +import org.apache.dolphinscheduler.service.storage.StorageOperate; + +import org.apache.commons.lang3.StringUtils; + +import java.io.File; +import java.io.IOException; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.zeroturnaround.zip.ZipUtil; + +import com.fasterxml.jackson.databind.JsonNode; + +public class TaskFilesTransferUtils { + + protected final static Logger logger = LoggerFactory + .getLogger(String.format(TaskConstants.TASK_LOG_LOGGER_NAME_FORMAT, TaskFilesTransferUtils.class)); + + // root path in resource storage + final static String RESOURCE_TAG = "DATA_TRANSFER"; + + // tmp path in local path for transfer + final static String DOWNLOAD_TMP = ".DT_TMP"; + + // suffix of the package file + final static String PACK_SUFFIX = "_ds_pack.zip"; + + /** + * upload output files to resource storage + * + * @param taskExecutionContext taskExecutionContext + * @param storageOperate storageOperate + * @throws TaskException TaskException + */ + public static void uploadOutputFiles(StorageOperate storageOperate, + TaskExecutionContext taskExecutionContext) throws TaskException { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get OUTPUT FILE parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.OUT); + + if (localParamsProperty.isEmpty()) { + return; + } + + logger.info("Upload output files ..."); + for (Property property : localParamsProperty) { + // get local file path + String srcPath = + packIfDir(String.format("%s/%s", taskExecutionContext.getExecutePath(), property.getValue())); + // get remote file path + String resourcePath = getResourcePath(taskExecutionContext, new File(srcPath).getName()); + try { + // upload file to storage + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Local:{} to Remote:{}", property, srcPath, resourceWholePath); + storageOperate.upload(taskExecutionContext.getTenantCode(), srcPath, resourceWholePath, false, true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // update varPool + Property oriProperty; + // if the property is not in varPool, add it + if (varPoolsMap.containsKey(property.getProp())) { + oriProperty = varPoolsMap.get(property.getProp()); + } else { + oriProperty = new Property(property.getProp(), Direct.OUT, DataType.FILE, property.getValue()); + varPools.add(oriProperty); + } + oriProperty.setProp(String.format("%s.%s", taskExecutionContext.getTaskName(), oriProperty.getProp())); + oriProperty.setValue(resourcePath); + } + taskExecutionContext.setVarPool(JSONUtils.toJsonString(varPools)); + } + + /** + * download upstream files from storage + * only download files which are defined in the task parameters + * + * @param storageOperate storage operate + * @param taskExecutionContext taskExecutionContext + * @throws TaskException task exception + */ + public static void downloadUpstreamFiles(TaskExecutionContext taskExecutionContext, StorageOperate storageOperate) { + List<Property> varPools = getVarPools(taskExecutionContext); + // get map of varPools for quick search + Map<String, Property> varPoolsMap = varPools.stream().collect(Collectors.toMap(Property::getProp, x -> x)); + + // get "IN FILE" parameters + List<Property> localParamsProperty = getFileLocalParams(taskExecutionContext, Direct.IN); + + if (localParamsProperty.isEmpty()) { + return; + } + + String executePath = taskExecutionContext.getExecutePath(); + // data path to download packaged data + String DownloadTmpPath = String.format("%s/%s", executePath, DOWNLOAD_TMP); + + logger.info("Download upstream files..."); + for (Property property : localParamsProperty) { + Property inVarPool = varPoolsMap.get(property.getValue()); + if (inVarPool == null) { + logger.error(String.format("%s not in %s", property.getValue(), varPoolsMap.keySet())); + throw new TaskException(String.format("Can not find upstream file using %s, please check the key", + property.getValue())); + } + + String resourcePath = inVarPool.getValue(); + String targetPath = String.format("%s/%s", executePath, property.getProp()); + + String downloadPath; + // If the data is packaged, download it to a special directory (DOWNLOAD_TMP) and unpack it to the + // targetPath + boolean isPack = resourcePath.endsWith(PACK_SUFFIX); + if (isPack) { + downloadPath = String.format("%s/%s", DownloadTmpPath, new File(resourcePath).getName()); + } else { + downloadPath = targetPath; + } + + try { + String resourceWholePath = + storageOperate.getResourceFileName(taskExecutionContext.getTenantCode(), resourcePath); + logger.info("{} --- Remote:{} to Local:{}", property, resourceWholePath, downloadPath); + storageOperate.download(taskExecutionContext.getTenantCode(), resourceWholePath, downloadPath, false, + true); + } catch (IOException ex) { + throw new TaskException(ex.getMessage(), ex); + } + + // unpack if the data is packaged + if (isPack) { + File downloadFile = new File(downloadPath); + logger.info("Unpack {} to {}", downloadPath, targetPath); + ZipUtil.unpack(downloadFile, new File(targetPath)); + } + } + + // delete DownloadTmp Folder if DownloadTmpPath exists + try { + org.apache.commons.io.FileUtils.deleteDirectory(new File(DownloadTmpPath)); + } catch (IOException e) { + logger.error( + "Delete DownloadTmpPath {} failed, this will not affect the task status", DownloadTmpPath, e); + } + } + + /** + * get local parameters property which type is FILE and direction is equal to direct + * + * @param taskExecutionContext, TaskExecutionContext + * @param direct, Direct, may be Direct.IN or Direct.OUT. + * @return List<Property> + */ + public static List<Property> getFileLocalParams(TaskExecutionContext taskExecutionContext, Direct direct) { + List<Property> localParamsProperty = new ArrayList<>(); + JsonNode taskParams = JSONUtils.parseObject(taskExecutionContext.getTaskParams()); + for (JsonNode localParam : taskParams.get("localParams")) { + Property property = JSONUtils.parseObject(localParam.toString(), Property.class); + + if (property.getDirect().equals(direct) & property.getType().equals(DataType.FILE)) { + localParamsProperty.add(property); + } + } + return localParamsProperty; + } + + /** + * get Resource path for manage files in storage + * + * @param taskExecutionContext, TaskExecutionContext + * @param fileName, String, file name Review Comment: ## Spurious Javadoc @param tags @param tag "fileName," does not match any actual parameter of method "getResourcePath()". [Show more details](https://github.com/apache/dolphinscheduler/security/code-scanning/2127) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
