arina-ielchiieva commented on a change in pull request #1345: DRILL-6494: Drill Plugins Handler URL: https://github.com/apache/drill/pull/1345#discussion_r199737092
########## File path: exec/java-exec/src/main/java/org/apache/drill/exec/store/StoragePluginsHandlerService.java ########## @@ -0,0 +1,197 @@ +/* + * 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.drill.exec.store; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Charsets; +import com.google.common.io.Resources; +import com.jasonclawson.jackson.dataformat.hocon.HoconFactory; +import org.apache.drill.common.config.CommonConstants; +import org.apache.drill.common.config.LogicalPlanPersistence; +import org.apache.drill.common.exceptions.DrillRuntimeException; +import org.apache.drill.common.logical.StoragePluginConfig; +import org.apache.drill.common.scanner.ClassPathScanner; +import org.apache.drill.exec.planner.logical.StoragePlugins; +import org.apache.drill.exec.server.DrillbitContext; +import org.apache.drill.exec.store.sys.PersistentStore; + +import javax.annotation.Nullable; +import javax.validation.constraints.NotNull; +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import static org.apache.drill.exec.store.StoragePluginRegistry.ACTION_ON_STORAGE_PLUGINS_OVERRIDE_FILE; + +/** + * Drill plugins handler, which allows to update storage plugins configs from the + * {@link CommonConstants#STORAGE_PLUGINS_OVERRIDE_CONF} conf file + * + * TODO: DRILL-6564: It can be improved with configs versioning and service of creating + * {@link CommonConstants#STORAGE_PLUGINS_OVERRIDE_CONF} + */ +public class StoragePluginsHandlerService implements StoragePluginsHandler { + private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(StoragePluginsHandlerService.class); + + private final LogicalPlanPersistence hoconLogicalPlanPersistence; + private final DrillbitContext context; + private URL pluginsOverrideFileUrl; + + public StoragePluginsHandlerService(DrillbitContext context) { + this.context = context; + this.hoconLogicalPlanPersistence = new LogicalPlanPersistence(context.getConfig(), context.getClasspathScan(), + new ObjectMapper(new HoconFactory())); + } + + @Override + public void loadPlugins(@NotNull PersistentStore<StoragePluginConfig> persistentStore, + @Nullable StoragePlugins bootstrapPlugins) { + // if bootstrapPlugins is not null -- fresh Drill set up + StoragePlugins pluginsToBeWrittenToPersistentStore; + + StoragePlugins newPlugins = getNewStoragePlugins(); + + if (newPlugins != null) { + pluginsToBeWrittenToPersistentStore = new StoragePlugins(new HashMap<>()); + Optional.ofNullable(bootstrapPlugins) + .ifPresent(pluginsToBeWrittenToPersistentStore::putAll); + + for (Map.Entry<String, StoragePluginConfig> newPlugin : newPlugins) { + String pluginName = newPlugin.getKey(); + StoragePluginConfig oldPluginConfig = Optional.ofNullable(bootstrapPlugins) + .map(plugins -> plugins.getConfig(pluginName)) + .orElse(persistentStore.get(pluginName)); + StoragePluginConfig updatedStatusPluginConfig = updatePluginStatus(oldPluginConfig, newPlugin.getValue()); + pluginsToBeWrittenToPersistentStore.put(pluginName, updatedStatusPluginConfig); + } + } else { + pluginsToBeWrittenToPersistentStore = bootstrapPlugins; + } + + // load pluginsToBeWrittenToPersistentStore to Persistent Store + Optional.ofNullable(pluginsToBeWrittenToPersistentStore) + .ifPresent(plugins -> plugins.forEach(plugin -> persistentStore.put(plugin.getKey(), plugin.getValue()))); + + if (newPlugins != null) { + PluginsOverrideFileAction finalActionOnPluginsOverrideFile = + PluginsOverrideFileAction.valueOf(context.getConfig().getString(ACTION_ON_STORAGE_PLUGINS_OVERRIDE_FILE).toUpperCase()); + switch (finalActionOnPluginsOverrideFile) { + case RENAME: + renamePluginsOverrideFile(); + break; + case REMOVE: + removePluginsOverrideFile(); + break; + case NONE: + default: + // nothing to do + } + } + } + + /** + * Helper method to identify the enabled status for new storage plugins config. If this status is absent in the updater + * file, the status is kept from the configs, which are going to be updated + * + * @param oldPluginConfig current storage plugin config from Persistent Store or bootstrap config file + * @param newPluginConfig new storage plugin config + * @return new storage plugin config with updated enabled status + */ + private StoragePluginConfig updatePluginStatus(@Nullable StoragePluginConfig oldPluginConfig, + @NotNull StoragePluginConfig newPluginConfig) { + if (!newPluginConfig.isEnabledStatusPresent()) { + boolean newStatus = oldPluginConfig != null && oldPluginConfig.isEnabled(); + newPluginConfig.setEnabled(newStatus); + } + return newPluginConfig; + } + + /** + * Get the new storage plugins from the {@link CommonConstants#STORAGE_PLUGINS_OVERRIDE_CONF} file if it exists, + * null otherwise + * + * @return storage plugins + */ + private StoragePlugins getNewStoragePlugins() { + Set<URL> urlSet = ClassPathScanner.forResource(CommonConstants.STORAGE_PLUGINS_OVERRIDE_CONF, false); + if (!urlSet.isEmpty()) { + if (urlSet.size() != 1) { + DrillRuntimeException.format("More than one %s file is placed in Drill's classpath: %s", + CommonConstants.STORAGE_PLUGINS_OVERRIDE_CONF, urlSet); + } + pluginsOverrideFileUrl = urlSet.iterator().next(); + try { + String newPluginsData = Resources.toString(pluginsOverrideFileUrl, Charsets.UTF_8); + return hoconLogicalPlanPersistence.getMapper().readValue(newPluginsData, StoragePlugins.class); + } catch (IOException e) { + logger.error("Failures are obtained while loading %s file. Proceed without update", + CommonConstants.STORAGE_PLUGINS_OVERRIDE_CONF, e); + } + } + logger.debug("The {} file is absent. Proceed without updating of the storage plugins configs", + CommonConstants.STORAGE_PLUGINS_OVERRIDE_CONF); + return null; + } + + /** + * It renames the original {@link CommonConstants#STORAGE_PLUGINS_OVERRIDE_CONF} file to backup version with timestamp + */ + private void renamePluginsOverrideFile() { + File pluginsOverrideFile = new File(pluginsOverrideFileUrl.getPath()); + String oldName = CommonConstants.STORAGE_PLUGINS_OVERRIDE_CONF; + String currentDateTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); + String newFileName = new StringBuilder(oldName) + .insert(oldName.lastIndexOf("."), "-backup-" + currentDateTime) + .toString(); + Path pluginsOverrideFilePath = pluginsOverrideFile.toPath(); + try { + Files.move(pluginsOverrideFilePath, pluginsOverrideFilePath.resolveSibling(newFileName)); + } catch (IOException e) { + logger.error("%s file is not renamed after it's use", CommonConstants.STORAGE_PLUGINS_OVERRIDE_CONF, e); + } + } + + /** + * It removes the original {@link CommonConstants#STORAGE_PLUGINS_OVERRIDE_CONF} file + */ + private void removePluginsOverrideFile() { + File pluginsOverrideFile = new File(pluginsOverrideFileUrl.getPath()); + try { + Files.delete(pluginsOverrideFile.toPath()); + } catch (IOException e) { + logger.error("%s file is not deleted after it's use", CommonConstants.STORAGE_PLUGINS_OVERRIDE_CONF, e); + } + } + + /** + * The action on the {@link CommonConstants#STORAGE_PLUGINS_OVERRIDE_CONF} file being performed after it's use + */ + public enum PluginsOverrideFileAction { Review comment: 1. Extract enum as separate class. 2. Add abstract method action `void action(String fileName, URL url)` and each enum value will implement it. All you will need to get enum from string and call action method. 3. Please rename enum. ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org With regards, Apache Git Services