From 382daad93fd065767095f87b203aa47707fade72 Mon Sep 17 00:00:00 2001 From: Neel Date: Tue, 17 Nov 2026 13:26:40 -0500 Subject: [PATCH 1/6] feat: allowing engines to add dependencies --- .../auth/utils/AbstractSecurityUtils.java | 93 +- .../utils/CatalogDependenciesMigration.java | 228 +++ src/prerna/auth/utils/CatalogTypes.java | 165 +++ .../utils/SecurityCatalogDependencyUtils.java | 1245 +++++++++++++++++ .../auth/utils/SecurityEngineUtils.java | 2 + src/prerna/auth/utils/SecurityOwlCreator.java | 9 +- .../auth/utils/SecurityProjectUtils.java | 1045 +------------- .../admin/AdminExportProjectAppReactor.java | 3 +- .../admin/AdminExportProjectReactor.java | 5 +- .../workspaces/AbstractWorkspaceReactor.java | 35 +- .../workspaces/AddWorkspaceReactor.java | 8 +- .../workspaces/EditWorkspaceReactor.java | 13 +- src/prerna/project/impl/ProjectHelper.java | 32 +- .../agent/AppBuilderHarnessConfiguration.java | 11 +- .../skill/AttachSkillToWorkspaceReactor.java | 37 +- .../DetachSkillFromWorkspaceReactor.java | 9 +- .../project/CreateAppFromTemplateReactor.java | 529 +++---- .../ExtractAndSetDependenciesReactor.java | 4 +- .../project/SaveAppBlocksJsonReactor.java | 370 ++--- .../project/UploadProjectAppReactor.java | 916 ++++++------ .../reactor/project/UploadProjectReactor.java | 736 +++++----- .../security/CatalogDependencyKeys.java | 22 + ...ava => GetCatalogDependenciesReactor.java} | 438 +++--- .../SetCatalogDependenciesReactor.java | 99 ++ .../SetProjectDependenciesReactor.java | 120 -- .../ValidateCatalogDependenciesReactor.java | 47 + .../ValidateProjectDependenciesReactor.java | 96 -- ...alidateUserProjectDependenciesReactor.java | 86 -- .../utils/ExportProjectAppReactor.java | 449 +++--- .../reactor/utils/ExportProjectReactor.java | 471 +++---- src/prerna/util/AgentProjectArchiveUtils.java | 19 +- .../utils/AbstractSecurityUtilsUnitTests.java | 29 +- ...rmissionBatchUtilsUsageLimitUnitTests.java | 14 +- ...curityCatalogDependencyUtilsUnitTests.java | 242 ++++ .../utils/SecurityProjectUtilsUnitTests.java | 16 +- .../AgentProjectArchiveUtilsUnitTests.java | 21 +- 36 files changed, 4235 insertions(+), 3429 deletions(-) create mode 100644 src/prerna/auth/utils/CatalogDependenciesMigration.java create mode 100644 src/prerna/auth/utils/CatalogTypes.java create mode 100644 src/prerna/auth/utils/SecurityCatalogDependencyUtils.java create mode 100644 src/prerna/reactor/security/CatalogDependencyKeys.java rename src/prerna/reactor/security/{GetProjectDependenciesReactor.java => GetCatalogDependenciesReactor.java} (85%) create mode 100644 src/prerna/reactor/security/SetCatalogDependenciesReactor.java delete mode 100644 src/prerna/reactor/security/SetProjectDependenciesReactor.java create mode 100644 src/prerna/reactor/security/ValidateCatalogDependenciesReactor.java delete mode 100644 src/prerna/reactor/security/ValidateProjectDependenciesReactor.java delete mode 100644 src/prerna/reactor/security/ValidateUserProjectDependenciesReactor.java create mode 100644 test/prerna/auth/utils/SecurityCatalogDependencyUtilsUnitTests.java diff --git a/src/prerna/auth/utils/AbstractSecurityUtils.java b/src/prerna/auth/utils/AbstractSecurityUtils.java index 8af7fded0cd..5ca7bcabc81 100644 --- a/src/prerna/auth/utils/AbstractSecurityUtils.java +++ b/src/prerna/auth/utils/AbstractSecurityUtils.java @@ -1598,38 +1598,60 @@ public static void initialize() throws Exception { } } - // PROJECTDEPENDENCIES - colNames = new String[] { "PROJECTID", "ENGINEID", "ENGINETYPE", "USERID", "TYPE", "DATEADDED" }; - types = new String[] { VARCHAR_255, VARCHAR_255, VARCHAR_255, VARCHAR_255, VARCHAR_255, + // CATALOGDEPENDENCIES + // an engine or a project (the catalog item) and the engines and projects it + // depends on, each kept with its own engine type or project type + colNames = new String[] { "CATALOGID", "CATALOGTYPE", "DEPENDENCYID", "DEPENDENCYTYPE", "USERID", "TYPE", + "DATEADDED" }; + types = new String[] { VARCHAR_255, VARCHAR_255, VARCHAR_255, VARCHAR_255, VARCHAR_255, VARCHAR_255, TIMESTAMP_DATATYPE_NAME }; defaultValues = null; if (allowIfExistsTable) { - String sql = queryUtil.createTableIfNotExists("PROJECTDEPENDENCIES", colNames, types); + String sql = queryUtil.createTableIfNotExists(CatalogDependenciesMigration.NEW_TABLE, colNames, types); classLogger.info("Running sql {}", sql); securityDb.insertData(sql); } else { // see if table exists - if (!queryUtil.tableExists(conn, "PROJECTDEPENDENCIES", database, schema)) { + if (!queryUtil.tableExists(conn, CatalogDependenciesMigration.NEW_TABLE, database, schema)) { // make the table - String sql = queryUtil.createTable("PROJECTDEPENDENCIES", colNames, types); + String sql = queryUtil.createTable(CatalogDependenciesMigration.NEW_TABLE, colNames, types); classLogger.info("Running sql {}", sql); securityDb.insertData(sql); } } // handle column changes { - List projectCols = queryUtil.getTableColumns(conn, "PROJECTDEPENDENCIES", database, schema); + List dependencyCols = queryUtil.getTableColumns(conn, CatalogDependenciesMigration.NEW_TABLE, + database, schema); for (int i = 0; i < colNames.length; i++) { String col = colNames[i]; - if (!projectCols.contains(col) && !projectCols.contains(col.toLowerCase())) { - classLogger.info("Column '{}' is not present in current list of columns: {}", col, projectCols); - String addColumnSql = queryUtil.alterTableAddColumn("PROJECTDEPENDENCIES", col, types[i]); + if (!dependencyCols.contains(col) && !dependencyCols.contains(col.toLowerCase())) { + classLogger.info("Column '{}' is not present in current list of columns: {}", col, + dependencyCols); + String addColumnSql = queryUtil.alterTableAddColumn(CatalogDependenciesMigration.NEW_TABLE, col, + types[i]); classLogger.info("Running sql {}", addColumnSql); securityDb.insertData(addColumnSql); } } } - performDependencyUpdate(securityDb); + for (String indexColumn : new String[] { "CATALOGID", "DEPENDENCYID" }) { + String indexName = CatalogDependenciesMigration.NEW_TABLE + "_" + indexColumn + "_INDEX"; + if (allowIfExistsIndexs) { + String sql = queryUtil.createIndexIfNotExists(indexName, CatalogDependenciesMigration.NEW_TABLE, + indexColumn); + classLogger.info("Running sql {}", sql); + securityDb.insertData(sql); + } else if (!queryUtil.indexExists(securityDb, indexName, CatalogDependenciesMigration.NEW_TABLE, + database, schema)) { + String sql = queryUtil.createIndex(indexName, CatalogDependenciesMigration.NEW_TABLE, indexColumn); + classLogger.info("Running sql {}", sql); + securityDb.insertData(sql); + } + } + // move the rows of PROJECTDEPENDENCIES, from before an engine could own + // dependencies, and drop it + CatalogDependenciesMigration.migrate(securityDb); /** * @@ -3177,7 +3199,7 @@ private static void updateUserTypeEnum() { allValues.put("PASSWORD_RESET", new String[] { "TYPE" }); allValues.put("PROJECT", new String[] { "CREATEDBYTYPE", "PORTALPUBLISHEDTYPE", "REACTORSCOMPILEDTYPE" }); allValues.put("PROJECTACCESSREQUEST", new String[] { "REQUEST_TYPE", "APPROVER_TYPE", "SUBMITTED_BY_TYPE" }); - allValues.put("PROJECTDEPENDENCIES", new String[] { "TYPE" }); + allValues.put("CATALOGDEPENDENCIES", new String[] { "TYPE" }); allValues.put("SESSION_SHARE", new String[] { "TYPE" }); allValues.put("SMSS_GROUP", new String[] { "TYPE", "USERIDTYPE" }); allValues.put("SMSS_USER", new String[] { "TYPE" }); @@ -3287,53 +3309,6 @@ private static void performSmssUserTemporaryUpdate(IRDBMSEngine securityDb, Abst securityDb.insertData(queryUtil.alterTableName("USER", "OLD_USER_TABLE")); } - /** - * Fills the engine type of the project dependencies that have none: the - * engine's type for an engine, and PROJECT for a project. Engines and projects - * are filled in a transaction each; one that fails is logged and saves nothing, - * and the other is still filled. - * - * @param securityDb the security database - */ - @Deprecated - private static void performDependencyUpdate(IRDBMSEngine securityDb) { - String[] queryArray = new String[] { """ - SELECT PROJECTDEPENDENCIES.ENGINEID, ENGINE.ENGINETYPE FROM ENGINE \ - INNER JOIN PROJECTDEPENDENCIES on PROJECTDEPENDENCIES.ENGINEID=ENGINE.ENGINEID \ - WHERE PROJECTDEPENDENCIES.ENGINETYPE IS NULL - """, """ - SELECT PROJECTDEPENDENCIES.ENGINEID, 'PROJECT' AS PROJECTTYPE FROM PROJECT \ - INNER JOIN PROJECTDEPENDENCIES on PROJECTDEPENDENCIES.ENGINEID=PROJECT.PROJECTID \ - WHERE PROJECTDEPENDENCIES.ENGINETYPE IS NULL - """ }; - String updateQuery = "UPDATE PROJECTDEPENDENCIES SET ENGINETYPE=? WHERE ENGINEID=?"; - - for (String query : queryArray) { - try { - QueryExecutionUtility.write(securityDb, connection -> { - Map existing = new HashMap<>(); - for (String[] row : QueryExecutionUtility.queryList(connection, query, - QueryExecutionUtility.NO_PARAMETERS, - rs -> new String[] { rs.getString(1), rs.getString(2) })) { - existing.put(row[0], row[1]); - } - if (!existing.isEmpty()) { - QueryExecutionUtility.executeBatch(connection, updateQuery, existing.entrySet(), - (ps, entry) -> { - ps.setString(1, entry.getValue()); - ps.setString(2, entry.getKey()); - }); - } - return null; - }); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - classLogger.error("Error filling PROJECTDEPENDENCIES engine types using query: {}", query, e); - } - } - } - /** * Whether an engine with this name exists in the security database. Also true * when ignoreDatabase leaves the name out of security. diff --git a/src/prerna/auth/utils/CatalogDependenciesMigration.java b/src/prerna/auth/utils/CatalogDependenciesMigration.java new file mode 100644 index 00000000000..5838ab381a3 --- /dev/null +++ b/src/prerna/auth/utils/CatalogDependenciesMigration.java @@ -0,0 +1,228 @@ +package prerna.auth.utils; + +import java.sql.Connection; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Supplier; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import prerna.engine.api.IRDBMSEngine; +import prerna.util.QueryExecutionUtility; +import prerna.util.sql.AbstractSqlQueryUtil; + +/** + * Moves the rows of PROJECTDEPENDENCIES, where only a project could own + * dependencies, into CATALOGDEPENDENCIES at start up, then drops + * PROJECTDEPENDENCIES. + * + *

+ * Each row is copied with the specific type of its owner (the project's type) + * and of its dependency (the engine's type, or the project's type), read from + * ENGINE and PROJECT. That also replaces the generic PROJECT type and fills the + * missing ones of older rows. A row whose owner or dependency is in neither + * table any more is logged and left out. + *

+ * + *

+ * Several servers can start on one security database at the same time, as on a + * cluster, so the move is safe to run at once and to run again: + *

+ *
    + *
  • The copy and the drop are one transaction that starts by locking the rows + * of PROJECTDEPENDENCIES, with an update that changes nothing. Another server's + * move waits on those rows until the first commits.
  • + *
  • A dependency already in CATALOGDEPENDENCIES is not copied again, so a + * second move adds nothing.
  • + *
  • A move that fails is tried again, and one that finds PROJECTDEPENDENCIES + * gone, dropped by another server meanwhile, is done.
  • + *
+ * + * @deprecated Only security databases from before CATALOGDEPENDENCIES have + * PROJECTDEPENDENCIES. Remove this class, and its call in + * {@link AbstractSecurityUtils}, once every security database has + * started on a release that moves it. + */ +@Deprecated +final class CatalogDependenciesMigration { + + private static final Logger classLogger = LogManager.getLogger(CatalogDependenciesMigration.class); + + /** The table the dependencies are kept in */ + static final String NEW_TABLE = "CATALOGDEPENDENCIES"; + /** The table from before an engine could own dependencies */ + @Deprecated + static final String OLD_TABLE = "PROJECTDEPENDENCIES"; + + /** + * Each old row with the types of its owner and its dependency: the owner's + * project type, and the dependency's engine type, project type, or null when + * it is in neither table + */ + private static final String SELECT_OLD_ROWS = "SELECT D.PROJECTID, OWNER.TYPE, D.ENGINEID, " + + "TARGETENGINE.ENGINETYPE, TARGETPROJECT.PROJECTID, TARGETPROJECT.TYPE, D.USERID, D.TYPE, D.DATEADDED " + + "FROM " + OLD_TABLE + " D " + "INNER JOIN PROJECT OWNER ON OWNER.PROJECTID = D.PROJECTID " + + "LEFT OUTER JOIN ENGINE TARGETENGINE ON TARGETENGINE.ENGINEID = D.ENGINEID " + + "LEFT OUTER JOIN PROJECT TARGETPROJECT ON TARGETPROJECT.PROJECTID = D.ENGINEID"; + private static final String SELECT_NEW_KEYS = "SELECT CATALOGID, DEPENDENCYID FROM " + NEW_TABLE; + private static final String INSERT_NEW_ROW = "INSERT INTO " + NEW_TABLE + + " (CATALOGID, CATALOGTYPE, DEPENDENCYID, DEPENDENCYTYPE, USERID, TYPE, DATEADDED) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)"; + /** How many times a move is tried */ + private static final int ATTEMPTS = 3; + /** How long to wait before trying a move again, in milliseconds */ + private static final long RETRY_WAIT_MS = 2000; + + private CatalogDependenciesMigration() { + + } + + /** + * Moves the rows of PROJECTDEPENDENCIES into CATALOGDEPENDENCIES and drops it, + * when the security database still has it. A move that cannot finish is + * logged, keeps PROJECTDEPENDENCIES, and runs again on the next start. + * + * @param securityDb the security database + */ + @Deprecated + static void migrate(IRDBMSEngine securityDb) { + if (!oldTableExists(securityDb)) { + return; + } + for (int attempt = 1;; attempt++) { + try { + int[] counts = QueryExecutionUtility.write(securityDb, + connection -> move(connection, securityDb.getQueryUtil())); + classLogger.info("Moved {} dependencies from {} to {} and left out {} rows, then dropped {}", + counts[0], OLD_TABLE, NEW_TABLE, counts[1], OLD_TABLE); + return; + } catch (Exception e) { + if (!oldTableExists(securityDb)) { + classLogger.info("{} was moved by another server starting at the same time", OLD_TABLE); + return; + } + if (attempt >= ATTEMPTS) { + classLogger.error("Unable to move " + OLD_TABLE + " to " + NEW_TABLE + ". " + OLD_TABLE + + " is kept, and the move runs again on the next start.", e); + return; + } + classLogger.warn("Unable to move {}, such as while another server starting at the same time " + + "moves it. Trying again.", OLD_TABLE, e); + try { + Thread.sleep(RETRY_WAIT_MS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return; + } + } + } + } + + /** + * The move, in the caller's transaction + * + * @return how many dependencies were copied and how many rows left out + */ + private static int[] move(Connection connection, AbstractSqlQueryUtil queryUtil) throws Exception { + // 1. lock the rows to move, so another server's move waits for this one + QueryExecutionUtility.executeUpdate(connection, "UPDATE " + OLD_TABLE + " SET TYPE = TYPE", + QueryExecutionUtility.NO_PARAMETERS); + + // 2. copy each row that is not there already, with the specific types + Set existing = new HashSet<>(QueryExecutionUtility.queryList(connection, SELECT_NEW_KEYS, + QueryExecutionUtility.NO_PARAMETERS, rs -> key(rs.getString(1), rs.getString(2)))); + List rows = QueryExecutionUtility.queryList(connection, SELECT_OLD_ROWS, + QueryExecutionUtility.NO_PARAMETERS, + rs -> new Object[] { rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), + rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getTimestamp(9) }); + int oldRowCount = QueryExecutionUtility.queryOne(connection, "SELECT COUNT(*) FROM " + OLD_TABLE, + QueryExecutionUtility.NO_PARAMETERS, rs -> rs.getInt(1)); + List toInsert = new ArrayList<>(); + for (Object[] row : rows) { + String ownerId = (String) row[0]; + String dependencyId = (String) row[2]; + String dependencyType = dependencyTypeOf((String) row[3], (String) row[4], (String) row[5]); + String ownerType = typeOrNull(() -> projectTypeOf((String) row[1])); + if (dependencyId == null || dependencyType == null || ownerType == null) { + classLogger.warn("Left out the dependency of project {} on {}: it is not an engine or a project", + ownerId, dependencyId); + continue; + } + if (ownerId.equals(dependencyId) || !existing.add(key(ownerId, dependencyId))) { + continue; + } + toInsert.add(new Object[] { ownerId, ownerType, dependencyId, dependencyType, row[6], + row[7], row[8] }); + } + if (!toInsert.isEmpty()) { + QueryExecutionUtility.executeBatch(connection, INSERT_NEW_ROW, toInsert, (ps, row) -> { + for (int i = 0; i < 6; i++) { + ps.setString(i + 1, (String) row[i]); + } + ps.setTimestamp(7, (Timestamp) row[6]); + }); + } + + // 3. drop the old table in the same transaction + QueryExecutionUtility.executeUpdate(connection, queryUtil.dropTable(OLD_TABLE), + QueryExecutionUtility.NO_PARAMETERS); + return new int[] { toInsert.size(), oldRowCount - toInsert.size() }; + } + + /** + * The type of a dependency: the engine's type, or else the project's type + * + * @return the type, or null when the dependency is in neither table + */ + private static String dependencyTypeOf(String engineType, String projectId, String projectType) { + if (engineType != null) { + return typeOrNull(() -> CatalogTypes.normalize(engineType)); + } + if (projectId != null) { + return typeOrNull(() -> projectTypeOf(projectType)); + } + return null; + } + + /** + * A type, or null when it is not one a catalog item can have, such as the + * deprecated VENV, so its row is left out rather than failing the move + */ + private static String typeOrNull(Supplier type) { + try { + return type.get(); + } catch (IllegalArgumentException e) { + classLogger.warn("Left out a dependency with an unknown type: {}", e.getMessage()); + return null; + } + } + + /** A project's type, where none or an unknown one is an INSIGHTS project */ + private static String projectTypeOf(String projectType) { + return CatalogTypes.projectTypeOf(projectType); + } + + private static String key(String ownerId, String dependencyId) { + return ownerId + "\u0000" + dependencyId; + } + + /** + * Whether the security database still has PROJECTDEPENDENCIES + * + * @return true when it has, or when that cannot be read, so nothing is taken + * as done that may not be + */ + private static boolean oldTableExists(IRDBMSEngine securityDb) { + try { + return securityDb.getQueryUtil().tableExists(securityDb, OLD_TABLE, securityDb.getDatabase(), + securityDb.getSchema()); + } catch (Exception e) { + classLogger.warn("Unable to read whether {} exists", OLD_TABLE, e); + return true; + } + } +} diff --git a/src/prerna/auth/utils/CatalogTypes.java b/src/prerna/auth/utils/CatalogTypes.java new file mode 100644 index 00000000000..f9c91f1fdff --- /dev/null +++ b/src/prerna/auth/utils/CatalogTypes.java @@ -0,0 +1,165 @@ +package prerna.auth.utils; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +import prerna.engine.api.IEngine; +import prerna.engine.api.IRDBMSEngine; +import prerna.project.api.IProject; +import prerna.util.QueryExecutionUtility; +import prerna.util.SystemEngineRegistry; + +/** + * The types a catalog item, an engine or a project, is kept with in + * CATALOGDEPENDENCIES: its own engine type (FUNCTION, MODEL, DATABASE, VECTOR, + * STORAGE, GUARDRAIL) or project type (CODE, BLOCKS, INSIGHTS, SKILL, NOTEBOOK, + * AUTOMATION, WORKSPACE). The engine and project type names do not overlap, so + * a type alone says whether the item is an engine or a project. + */ +public final class CatalogTypes { + + /** Whether a catalog item is an engine or a project */ + public enum Kind { + ENGINE, PROJECT + } + + /** The engine types an item can have, without the deprecated VENV */ + private static final List ENGINE_TYPES; + /** The project types an item can have */ + private static final List PROJECT_TYPES; + + static { + List engineTypes = new ArrayList<>(); + for (IEngine.CATALOG_TYPE type : IEngine.CATALOG_TYPE.values()) { + if (type != IEngine.CATALOG_TYPE.PROJECT && type != IEngine.CATALOG_TYPE.VENV) { + engineTypes.add(type.name()); + } + } + ENGINE_TYPES = Collections.unmodifiableList(engineTypes); + List projectTypes = new ArrayList<>(); + for (IProject.PROJECT_TYPE type : IProject.PROJECT_TYPE.values()) { + projectTypes.add(type.name()); + } + PROJECT_TYPES = Collections.unmodifiableList(projectTypes); + } + + private CatalogTypes() { + + } + + /** + * @return every engine type a catalog item can have, without VENV + */ + public static List engineTypes() { + return ENGINE_TYPES; + } + + /** + * @return every project type a catalog item can have + */ + public static List projectTypes() { + return PROJECT_TYPES; + } + + /** + * Reads a type as it is kept: upper case and trimmed, and INSIGHT, as the UI + * calls it, as INSIGHTS. + * + * @param type an engine type or a project type, in any case + * @return the type as it is kept + * @throws IllegalArgumentException when the type is none of them + */ + public static String normalize(String type) { + if (type == null || type.isBlank()) { + throw new IllegalArgumentException("A catalog type is required"); + } + String normalized = type.trim().toUpperCase(Locale.ROOT); + if ("INSIGHT".equals(normalized)) { + normalized = IProject.PROJECT_TYPE.INSIGHTS.name(); + } + if (!ENGINE_TYPES.contains(normalized) && !PROJECT_TYPES.contains(normalized)) { + throw new IllegalArgumentException("Unknown catalog type '" + type + "'. Use one of " + ENGINE_TYPES + + " or " + PROJECT_TYPES); + } + return normalized; + } + + /** + * Whether a type is an engine type or a project type. + * + * @param type an engine type or a project type, in any case + * @return its kind + * @throws IllegalArgumentException when the type is none of them + */ + public static Kind kindOf(String type) { + return PROJECT_TYPES.contains(normalize(type)) ? Kind.PROJECT : Kind.ENGINE; + } + + /** + * Whether a type is a project type + * + * @param type an engine type or a project type, in any case + * @return true for a project type + */ + public static boolean isProjectType(String type) { + return kindOf(type) == Kind.PROJECT; + } + + /** + * A project's type as it is kept, from PROJECT.TYPE. A project with no type, or + * one that is not a project type, such as a legacy value, is an INSIGHTS + * project, as {@link IProject.PROJECT_TYPE#fromSmss} reads one with none. + * + * @param projectType the PROJECT.TYPE value + * @return the project type + */ + public static String projectTypeOf(String projectType) { + if (projectType != null && !projectType.isBlank()) { + String normalized = projectType.trim().toUpperCase(Locale.ROOT); + if ("INSIGHT".equals(normalized)) { + return IProject.PROJECT_TYPE.INSIGHTS.name(); + } + if (PROJECT_TYPES.contains(normalized)) { + return normalized; + } + } + return IProject.PROJECT_TYPE.INSIGHTS.name(); + } + + /** + * Finds the type of an engine or project from the security database alone. It + * never loads the engine or project, or pulls it from cloud storage, so it is + * safe on a cluster where the item is not loaded on this server. + * + * @param id an engine id or a project id + * @return its engine type or project type, or null when the security database + * has neither. A project with no type is an INSIGHTS project. + */ + public static String resolve(String id) { + if (id == null || id.isBlank()) { + return null; + } + IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); + try { + String engineType = QueryExecutionUtility.queryOne(securityDb, + "SELECT ENGINETYPE FROM ENGINE WHERE ENGINEID = ?", ps -> ps.setString(1, id), + rs -> rs.getString(1)); + if (engineType != null) { + return normalize(engineType); + } + String[] project = QueryExecutionUtility.queryOne(securityDb, + "SELECT PROJECTID, TYPE FROM PROJECT WHERE PROJECTID = ?", ps -> ps.setString(1, id), + rs -> new String[] { rs.getString(1), rs.getString(2) }); + if (project != null) { + return projectTypeOf(project[1]); + } + return null; + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new IllegalStateException("Unable to read the catalog type of " + id, e); + } + } +} diff --git a/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java b/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java new file mode 100644 index 00000000000..79485932522 --- /dev/null +++ b/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java @@ -0,0 +1,1245 @@ +package prerna.auth.utils; + +import java.io.File; + +import com.google.gson.reflect.TypeToken; +import prerna.util.gson.GsonUtility; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.javatuples.Pair; +import prerna.auth.AccessPermissionEnum; +import prerna.auth.AccessToken; +import prerna.auth.AuthProvider; +import prerna.auth.User; +import prerna.auth.access.ModelUsageLimit; +import prerna.auth.access.PermissionChange; +import prerna.auth.access.PermissionErrorRules; +import prerna.auth.access.PermissionGrant; +import prerna.auth.access.PermissionProblem; +import prerna.auth.access.PermissionSubject; +import prerna.auth.access.PermissionTargetResource; +import prerna.date.SemossDate; +import prerna.engine.api.IEngine; +import prerna.engine.api.IHeadersDataRow; +import prerna.engine.api.IRDBMSEngine; +import prerna.engine.api.IRawSelectWrapper; +import prerna.engine.impl.InsightAdministrator; +import prerna.engine.impl.SmssUtilities; +import prerna.notifications.NotificationDbUtils; +import prerna.project.api.IProject; +import prerna.project.impl.ProjectHelper; +import prerna.query.querystruct.SelectQueryStruct; +import prerna.query.querystruct.filters.AndQueryFilter; +import prerna.query.querystruct.filters.IQueryFilter; +import prerna.query.querystruct.filters.OrQueryFilter; +import prerna.query.querystruct.filters.SimpleQueryFilter; +import prerna.query.querystruct.joins.IRelation; +import prerna.query.querystruct.joins.SubqueryRelationship; +import prerna.query.querystruct.selectors.QueryColumnOrderBySelector; +import prerna.query.querystruct.selectors.QueryColumnSelector; +import prerna.query.querystruct.selectors.QueryFunctionHelper; +import prerna.query.querystruct.selectors.QueryFunctionSelector; +import prerna.query.querystruct.selectors.QueryIfSelector; +import prerna.rdf.engine.wrappers.WrapperManager; +import prerna.sablecc2.PixelUtility; +import prerna.sablecc2.lexer.LexerException; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.execptions.SemossPixelException; +import prerna.sablecc2.parser.ParserException; +import prerna.usertracking.AuditEventType; +import prerna.usertracking.UserAuditTrailUtils; +import prerna.util.ConnectionUtils; +import prerna.util.Constants; +import prerna.util.EmailUtility; +import prerna.util.InsightsRDBMSUtils; +import prerna.util.InternalUtility; +import prerna.util.NotificationConstants; +import prerna.util.QueryExecutionUtility; +import prerna.util.SystemEngineRegistry; +import prerna.util.Utility; +import prerna.util.sql.AbstractSqlQueryUtil; +import prerna.util.sql.RdbmsTypeEnum; +import java.util.LinkedHashMap; + +/** + * The dependencies of catalog items, kept in CATALOGDEPENDENCIES: an engine or + * a project (the catalog item, or owner) and the engines and projects it depends + * on. Both are kept with their own engine type or project type (see + * {@link CatalogTypes}), never a generic ENGINE or PROJECT. + * + *

+ * Everything here reads and writes the security database alone. Nothing loads an + * engine or a project, or pulls one from cloud storage, so it works the same on + * every server of a cluster, whichever items that server has loaded. + *

+ */ +public class SecurityCatalogDependencyUtils extends AbstractSecurityUtils { + + private static final Logger classLogger = LogManager.getLogger(SecurityCatalogDependencyUtils.class); + + private static final String TABLE = "CATALOGDEPENDENCIES"; + + /** + * One dependency of a catalog item: the engine or project it depends on, and + * that item's own type. + * + * @param id the engine id or project id + * @param type its engine type or project type, read with + * {@link CatalogTypes#normalize} + */ + public record Dependency(String id, String type) { + public Dependency { + if (id == null || id.isBlank()) { + throw new IllegalArgumentException("A dependency id is required"); + } + type = CatalogTypes.normalize(type); + } + } + + SecurityCatalogDependencyUtils() { + + } + + /** + * The filter that a dependency is a project, for choosing between the ENGINE + * and PROJECT columns of a dependency + */ + private static SimpleQueryFilter isProjectDependency() { + return SimpleQueryFilter.makeColToValFilter("CATALOGDEPENDENCIES__DEPENDENCYTYPE", "==", + new ArrayList<>(CatalogTypes.projectTypes())); + } + + /* + * Types and permissions + */ + + /** + * The type of a catalog item: the one given, checked against the security + * database, or the one the security database has when none is given. + * + * @param catalogId an engine id or project id + * @param catalogType its type, or null to read it + * @return its engine type or project type + * @throws IllegalArgumentException when the security database has no such item, + * or the type given is not its type + */ + public static String resolveCatalogType(String catalogId, String catalogType) { + String stored = CatalogTypes.resolve(catalogId); + if (stored == null) { + throw new IllegalArgumentException("No engine or project has the id " + catalogId); + } + if (catalogType == null || catalogType.isBlank()) { + return stored; + } + // a project's type is read as PROJECT.TYPE is, so a legacy or missing one is + // INSIGHTS, the same as the stored type + String given = CatalogTypes.isProjectType(stored) && !CatalogTypes.engineTypes() + .contains(catalogType.trim().toUpperCase(java.util.Locale.ROOT)) ? CatalogTypes.projectTypeOf(catalogType) + : CatalogTypes.normalize(catalogType); + if (!stored.equals(given)) { + throw new IllegalArgumentException(catalogId + " is a " + stored + ", not a " + given); + } + return stored; + } + + /** + * Whether a user can view a catalog item + * + * @param user the user + * @param catalogId an engine id or project id + * @param catalogType its engine type or project type + * @return whether they can view it + */ + public static boolean userCanView(User user, String catalogId, String catalogType) { + if (CatalogTypes.isProjectType(catalogType)) { + return SecurityProjectUtils.userCanViewProject(user, catalogId); + } + return SecurityEngineUtils.userCanViewEngine(user, catalogId); + } + + /** + * Whether a user can edit a catalog item, and so its dependencies + * + * @param user the user + * @param catalogId an engine id or project id + * @param catalogType its engine type or project type + * @return whether they can edit it + */ + public static boolean userCanEdit(User user, String catalogId, String catalogType) { + if (CatalogTypes.isProjectType(catalogType)) { + return SecurityProjectUtils.userCanEditProject(user, catalogId); + } + return SecurityEngineUtils.userCanEditEngine(user, catalogId); + } + + /** + * Reads the types of engine ids and project ids from the security database. + * Never loads or pulls an engine or project. + * + * @param ids engine ids and project ids + * @param failed collects the ids that are in neither table, when not null + * @return the dependencies of the ids found, in order, once each + */ + public static List resolveDependencies(Collection ids, Collection failed) { + List dependencies = new ArrayList<>(); + Set seen = new HashSet<>(); + for (String id : ids) { + if (id == null || !seen.add(id)) { + continue; + } + String type = CatalogTypes.resolve(id); + if (type == null) { + classLogger.warn("{} is not an engine or a project, so it is not a dependency", id); + if (failed != null) { + failed.add(id); + } + continue; + } + dependencies.add(new Dependency(id, type)); + } + return dependencies; + } + + /* + * Writes + */ + + /** + * Replaces all the dependencies of a catalog item, in one transaction. + * + * @param user who sets them + * @param catalogId the engine id or project id + * @param catalogType its engine type or project type + * @param dependencies its dependencies; an empty list removes them all + * @throws IllegalStateException when they cannot be saved; nothing is changed + */ + public static void setDependencies(User user, String catalogId, String catalogType, + Collection dependencies) { + String ownerType = CatalogTypes.normalize(catalogType); + IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); + try { + QueryExecutionUtility.write(securityDb, connection -> { + QueryExecutionUtility.executeUpdate(connection, "DELETE FROM " + TABLE + " WHERE CATALOGID=?", + ps -> ps.setString(1, catalogId)); + insert(connection, user, catalogId, ownerType, withoutOwnerAndRepeats(catalogId, dependencies)); + return null; + }); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + classLogger.error("Failed to set the dependencies of {}", catalogId, e); + throw new IllegalStateException("Unable to save the dependencies of " + catalogId, e); + } + } + + /** + * Replaces all the dependencies of a catalog item with the engines and projects + * of these ids, reading their types from the security database. Ids that are + * neither are left out. + * + * @param user who sets them + * @param catalogId the engine id or project id + * @param catalogType its engine type or project type + * @param ids the engine ids and project ids it depends on + * @return the ids left out, which are neither an engine nor a project + */ + public static List setDependencyIds(User user, String catalogId, String catalogType, + Collection ids) { + List failed = new ArrayList<>(); + setDependencies(user, catalogId, catalogType, resolveDependencies(ids, failed)); + return failed; + } + + /** + * Adds dependencies to a catalog item, keeping the ones it has, in one + * transaction. + * + * @param user who adds them + * @param catalogId the engine id or project id + * @param catalogType its engine type or project type + * @param dependencies the dependencies to add; ones it has already are skipped + * @throws IllegalStateException when they cannot be saved; nothing is changed + */ + public static void addDependencies(User user, String catalogId, String catalogType, + Collection dependencies) { + String ownerType = CatalogTypes.normalize(catalogType); + IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); + try { + QueryExecutionUtility.write(securityDb, connection -> { + Set existing = new HashSet<>(QueryExecutionUtility.queryList(connection, + "SELECT DEPENDENCYID FROM " + TABLE + " WHERE CATALOGID=?", ps -> ps.setString(1, catalogId), + rs -> rs.getString(1))); + List toAdd = new ArrayList<>(); + for (Dependency dependency : withoutOwnerAndRepeats(catalogId, dependencies)) { + if (!existing.contains(dependency.id())) { + toAdd.add(dependency); + } + } + insert(connection, user, catalogId, ownerType, toAdd); + return null; + }); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + classLogger.error("Failed to add dependencies to {}", catalogId, e); + throw new IllegalStateException("Unable to save the dependencies of " + catalogId, e); + } + } + + /** + * Removes one dependency from a catalog item. + * + * @param user who removes it; they must be able to edit the item + * @param catalogId the engine id or project id + * @param dependencyId the engine id or project id it no longer depends on + * @throws IllegalAccessException when the user cannot edit the item + */ + public static void removeDependency(User user, String catalogId, String dependencyId) + throws IllegalAccessException { + String catalogType = resolveCatalogType(catalogId, null); + if (!userCanEdit(user, catalogId, catalogType)) { + throw new IllegalAccessException("User does not have permissions to remove dependencies"); + } + IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); + try { + QueryExecutionUtility.executeUpdate(securityDb, + "DELETE FROM " + TABLE + " WHERE CATALOGID=? AND DEPENDENCYID=?", ps -> { + ps.setString(1, catalogId); + ps.setString(2, dependencyId); + }); + } catch (Exception e) { + classLogger.error("Failed to remove the dependency of {} on {}", catalogId, dependencyId, e); + throw new IllegalStateException("Unable to remove the dependency on " + dependencyId, e); + } + } + + /** + * Removes the dependencies a deleted engine or project owned. The rows of other + * items that depend on it are kept, so validating them shows it is gone. + * + * @param catalogId the engine id or project id + */ + public static void deleteDependenciesOwnedBy(String catalogId) { + IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); + try { + QueryExecutionUtility.executeUpdate(securityDb, "DELETE FROM " + TABLE + " WHERE CATALOGID=?", + ps -> ps.setString(1, catalogId)); + } catch (Exception e) { + classLogger.error("Failed to delete the dependencies of {}", catalogId, e); + } + } + + /* + * Export and import + */ + + /** + * Reads the dependency file of an exported project, when it has one. + * + * @param file the {@code _dependencies.json} file + * @return its rows, or an empty list when there is no file or it cannot be read + */ + @SuppressWarnings("unchecked") + public static List> readDependencyFile(File file) { + if (file == null || !file.isFile()) { + return new ArrayList<>(); + } + try { + List> rows = (List>) GsonUtility.readJsonFileToObject(file, + new TypeToken>>() { + }.getType()); + return rows == null ? new ArrayList<>() : rows; + } catch (Exception e) { + classLogger.warn("Unable to read the dependencies in {}", file.getName(), e); + return new ArrayList<>(); + } + } + + /** + * Reads the rows of an exported dependency file as dependencies. Exports from + * this release give catalog_id and catalog_type; older ones give engine_id and + * engine_type, where a project's type is PROJECT. Each type is read from the + * security database when it has the item. Otherwise the exported type is kept + * when it is an engine type or project type, and the row is left out when it + * is not, such as an old PROJECT. + * + * @param rows the rows of an exported dependency file + * @return the dependencies, in order + */ + public static List fromExported(List> rows) { + List dependencies = new ArrayList<>(); + if (rows == null) { + return dependencies; + } + for (Map row : rows) { + Object idValue = row.containsKey("catalog_id") ? row.get("catalog_id") : row.get("engine_id"); + Object typeValue = row.containsKey("catalog_type") ? row.get("catalog_type") : row.get("engine_type"); + if (!(idValue instanceof String id) || id.isBlank()) { + continue; + } + String type = CatalogTypes.resolve(id); + if (type == null && typeValue instanceof String exported) { + try { + type = CatalogTypes.normalize(exported); + } catch (IllegalArgumentException e) { + type = null; + } + } + if (type == null) { + classLogger.warn("Left out the exported dependency on {}: its type is not known", id); + continue; + } + dependencies.add(new Dependency(id, type)); + } + return dependencies; + } + + private static List withoutOwnerAndRepeats(String catalogId, Collection dependencies) { + List kept = new ArrayList<>(); + if (dependencies == null) { + return kept; + } + Set seen = new HashSet<>(); + for (Dependency dependency : dependencies) { + if (dependency.id().equals(catalogId)) { + classLogger.warn("{} cannot depend on itself", catalogId); + continue; + } + if (seen.add(dependency.id())) { + kept.add(dependency); + } + } + return kept; + } + + private static void insert(Connection connection, User user, String catalogId, String catalogType, + List dependencies) throws Exception { + if (dependencies.isEmpty()) { + return; + } + AccessToken token = user == null ? null : user.getPrimaryLoginToken(); + String userId = token == null ? null : token.getId(); + String userType = token == null ? null : token.getProvider().getLabel(); + java.sql.Timestamp timestamp = Utility.getCurrentSqlTimestampUTC(); + String query = "INSERT INTO " + TABLE + + " (CATALOGID, CATALOGTYPE, DEPENDENCYID, DEPENDENCYTYPE, USERID, TYPE, DATEADDED) VALUES (?, ?, ?, ?, ?, ?, ?)"; + QueryExecutionUtility.executeBatch(connection, query, dependencies, (ps, dependency) -> { + ps.setString(1, catalogId); + ps.setString(2, catalogType); + ps.setString(3, dependency.id()); + ps.setString(4, dependency.type()); + ps.setString(5, userId); + ps.setString(6, userType); + ps.setTimestamp(7, timestamp); + }); + } + + /* + * Reads + */ + + /** + * The direct dependencies of a catalog item + * + * @param catalogId the engine id or project id + * @return each as parent_id, catalog_id and catalog_type + */ + public static List> getDependencies(String catalogId) { + return getDependencies(catalogId, false); + } + + /** + * The dependencies of a catalog item, with theirs when asked. Each item is + * visited once, so a cycle, such as an engine and a project that depend on each + * other, ends. + * + * @param catalogId the engine id or project id + * @param subdependencies whether to add the dependencies of its dependencies, + * all the way down + * @return each as parent_id, catalog_id and catalog_type + */ + public static List> getDependencies(String catalogId, boolean subdependencies) { + List> all = new ArrayList<>(); + collect(catalogId, subdependencies, new HashSet<>(), all, SecurityCatalogDependencyUtils::getDirectDependencies); + return all; + } + + private static List> getDirectDependencies(String catalogId) { + IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); + SelectQueryStruct qs = new SelectQueryStruct(); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__CATALOGID", "parent_id")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__DEPENDENCYID", "catalog_id")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__DEPENDENCYTYPE", "catalog_type")); + qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("CATALOGDEPENDENCIES__CATALOGID", "==", catalogId)); + return QueryExecutionUtility.flushRsToMap(securityDb, qs); + } + + private static void collect(String catalogId, boolean subdependencies, Set visited, + List> all, java.util.function.Function>> direct) { + if (!visited.add(catalogId)) { + return; + } + for (Map dependency : direct.apply(catalogId)) { + all.add(dependency); + if (subdependencies) { + collect((String) dependency.get("catalog_id"), true, visited, all, direct); + } + } + } + + /** + * Whether a user can view each dependency of a catalog item, all the way down + * + * @param user the user + * @param catalogId the engine id or project id + * @return each dependency id and whether they can view it + */ + public static Map validateDependencies(User user, String catalogId) { + Map canView = new LinkedHashMap<>(); + for (Map dependency : getDependencies(catalogId, true)) { + String id = (String) dependency.get("catalog_id"); + String type = (String) dependency.get("catalog_type"); + if (canView.containsKey(id)) { + continue; + } + boolean viewable; + try { + viewable = userCanView(user, id, type); + } catch (IllegalArgumentException e) { + // a type no longer known + viewable = false; + } + canView.put(id, viewable); + } + return canView; + } + + /** + * The direct dependencies of a catalog item with their names and settings, as + * written to an export + * + * @param catalogId the engine id or project id + * @return each with parent_id, catalog_id, catalog_type, catalog_name, + * catalog_subtype, catalog_date_created, catalog_discoverable and + * catalog_global + */ + public static List> getDependencyDetails(String catalogId) { + return getDependencyDetails(catalogId, false); + } + + /** + * The dependencies of a catalog item with their names and settings, with + * theirs when asked + * + * @param catalogId the engine id or project id + * @param subdependencies whether to add the dependencies of its dependencies + * @return each as {@link #getDependencyDetails(String)} gives them + */ + public static List> getDependencyDetails(String catalogId, boolean subdependencies) { + List> all = new ArrayList<>(); + collect(catalogId, subdependencies, new HashSet<>(), all, SecurityCatalogDependencyUtils::getDependencyDetailsQuery); + return all; + } + + private static List> getDependencyDetailsQuery(String catalogId) { + IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); + SelectQueryStruct qs = new SelectQueryStruct(); + addDetailSelectors(qs, catalogId); + return QueryExecutionUtility.flushRsToMap(securityDb, qs); + } + + /** + * Adds the selectors, joins and filter every detail query shares: the + * dependency, its type, and its name, subtype, date created, discoverable and + * global from ENGINE or PROJECT + */ + private static void addDetailSelectors(SelectQueryStruct qs, String catalogId) { + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__CATALOGID", "parent_id")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__DEPENDENCYID", "catalog_id")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__DEPENDENCYTYPE", "catalog_type")); + qs.addSelector(QueryIfSelector.makeQueryIfSelector(isProjectDependency(), + new QueryColumnSelector("PROJECT__PROJECTNAME"), new QueryColumnSelector("ENGINE__ENGINENAME"), + "catalog_name")); + qs.addSelector(QueryIfSelector.makeQueryIfSelector(isProjectDependency(), + new QueryColumnSelector("PROJECT__TYPE"), new QueryColumnSelector("ENGINE__ENGINESUBTYPE"), + "catalog_subtype")); + qs.addSelector(QueryIfSelector.makeQueryIfSelector(isProjectDependency(), + new QueryColumnSelector("PROJECT__DATECREATED"), new QueryColumnSelector("ENGINE__DATECREATED"), + "catalog_date_created")); + qs.addSelector(QueryIfSelector.makeQueryIfSelector(isProjectDependency(), + new QueryColumnSelector("PROJECT__DISCOVERABLE"), new QueryColumnSelector("ENGINE__DISCOVERABLE"), + "catalog_discoverable")); + qs.addSelector(QueryIfSelector.makeQueryIfSelector(isProjectDependency(), + new QueryColumnSelector("PROJECT__GLOBAL"), new QueryColumnSelector("ENGINE__GLOBAL"), + "catalog_global")); + qs.addRelation("CATALOGDEPENDENCIES__DEPENDENCYID", "ENGINE__ENGINEID", "left.outer.join"); + qs.addRelation("CATALOGDEPENDENCIES__DEPENDENCYID", "PROJECT__PROJECTID", "left.outer.join"); + qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("CATALOGDEPENDENCIES__CATALOGID", "==", catalogId)); + } + + /** + * The dependencies of a catalog item with their details and the user's access + * to each, with theirs when asked + * + * @param catalogId the engine id or project id + * @param user the user + * @param subdependencies whether to add the dependencies of its dependencies, + * with can_view_dependencies on each + * @return each with the details, permission, permission_name, group_permission, + * access_permission, description and tags + */ + public static List> getDependencyDetails(String catalogId, User user, + boolean subdependencies) { + if (!subdependencies) { + return getDependencyDetailsWithUserQuery(catalogId, user); + } + List> all = new ArrayList<>(); + collect(catalogId, true, new HashSet<>(), all, id -> getDependencyDetailsWithUserQuery(id, user)); + calculateCanViewDependencies(all); + return all; + } + + /** + * Calculate can_view_dependencies field for each dependency by checking if user + * has view access to all subdependencies. Works from leaf nodes up the tree. + * Now accounts for both user permissions and group permissions. + * + * @param allDependencies List of all dependencies (flat structure) + */ + private static void calculateCanViewDependencies(List> allDependencies) { + // Build a map of engineId -> dependency for quick lookup + Map> dependencyMap = new HashMap<>(); + for (Map dep : allDependencies) { + String engineId = (String) dep.get("catalog_id"); + dependencyMap.put(engineId, dep); + } + + // Build a map of parent -> list of children directly from allDependencies + // Since we already recursively fetched everything, we have all the parent-child + // relationships + Map> childrenMap = new HashMap<>(); + + for (Map dep : allDependencies) { + String parentId = (String) dep.get("parent_id"); + String engineId = (String) dep.get("catalog_id"); + + // Add this engine as a child of its parent (skip self-references to prevent + // infinite loops) + if (parentId != null && !parentId.equals(engineId)) { + childrenMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(engineId); + } + } + + // Calculate can_view_dependencies from leaf nodes up + Map canViewCache = new HashMap<>(); + Set visiting = new HashSet<>(); + for (Map dep : allDependencies) { + String engineId = (String) dep.get("catalog_id"); + boolean canView = calculateCanViewRecursive(engineId, dependencyMap, childrenMap, canViewCache, visiting); + dep.put("can_view_dependencies", canView); + } + } + + /** + * Recursively calculate if user can view all subdependencies for a given engine + * + * @param engineId The engine ID to check + * @param dependencyMap Map of engineId -> dependency data + * @param childrenMap Map of engineId -> list of child engine IDs + * @param canViewCache Cache to avoid recalculating + * @param visiting Set of engine IDs currently being processed (to detect + * circular dependencies) + * @return true if user has view access to this engine and all its + * subdependencies + */ + private static boolean calculateCanViewRecursive(String engineId, Map> dependencyMap, + Map> childrenMap, Map canViewCache, Set visiting) { + // Check cache first + if (canViewCache.containsKey(engineId)) { + return canViewCache.get(engineId); + } + + // Detect circular dependency - if we're already visiting this node, there's a + // cycle. Every node in the visiting set has already had its own + // hasViewPermission + // checked, so the back-edge doesn't introduce any new permission requirement. + // Return true to avoid poisoning the result for all nodes in the cycle. + if (visiting.contains(engineId)) { + return true; + } + + Map dependency = dependencyMap.get(engineId); + if (dependency == null) { + canViewCache.put(engineId, false); + return false; + } + + // Check if user has view permission for this engine + // Account for both user permissions and group permissions + boolean hasViewPermission = false; + Integer permission = (Integer) dependency.get("permission"); + Integer groupPermission = (Integer) dependency.get("group_permission"); + Boolean isGlobal = (Boolean) dependency.get("catalog_global"); + + // User has view permission if they have any user permission, group permission, + // or if engine is global + hasViewPermission = (permission != null) || (groupPermission != null) || (isGlobal != null && isGlobal); + + // If this is a leaf node (no children), return the permission status + List children = childrenMap.get(engineId); + if (children == null || children.isEmpty()) { + canViewCache.put(engineId, hasViewPermission); + return hasViewPermission; + } + + // Mark this node as being visited to detect cycles + visiting.add(engineId); + + try { + // If this has children, check all subdependencies + boolean allChildrenViewable = true; + for (String childId : children) { + if (!calculateCanViewRecursive(childId, dependencyMap, childrenMap, canViewCache, visiting)) { + allChildrenViewable = false; + break; + } + } + + // User can view dependencies if they have permission for this node AND all + // children are viewable + boolean result = hasViewPermission && allChildrenViewable; + canViewCache.put(engineId, result); + return result; + } finally { + // Remove from visiting set after processing + visiting.remove(engineId); + } + } + + /** + * Query to get project dependency details with user and group permissions for a + * single project + * + * @param projectId + * @param user + * @return + */ + private static List> getDependencyDetailsWithUserQuery(String projectId, User user) { + IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); + String userId = user.getPrimaryLoginToken().getId(); + SelectQueryStruct qs = new SelectQueryStruct(); + addDetailSelectors(qs, projectId); + + // METADATA sub-query - conditional based on type (ENGINEMETA vs PROJECTMETA) + { + // ENGINE metadata sub-query for description + SelectQueryStruct engineMetaQs = new SelectQueryStruct(); + engineMetaQs.addSelector(new QueryColumnSelector("ENGINEMETA__ENGINEID", "ENGINEID")); + engineMetaQs.addSelector(new QueryColumnSelector("ENGINEMETA__METAVALUE", "DESCRIPTION")); + engineMetaQs.addExplicitFilter( + SimpleQueryFilter.makeColToValFilter("ENGINEMETA__METAKEY", "==", "description")); + engineMetaQs.addGroupBy(new QueryColumnSelector("ENGINEMETA__ENGINEID")); + engineMetaQs.addGroupBy(new QueryColumnSelector("ENGINEMETA__METAVALUE")); + + SubqueryRelationship engineMetaRel = new SubqueryRelationship(engineMetaQs, "EM", "left.outer.join", + new String[] { "EM__ENGINEID", "ENGINE__ENGINEID", "=" }); + qs.addRelation(engineMetaRel); + + // PROJECT metadata sub-query for description + SelectQueryStruct projectMetaQs = new SelectQueryStruct(); + projectMetaQs.addSelector(new QueryColumnSelector("PROJECTMETA__PROJECTID", "PROJECTID")); + projectMetaQs.addSelector(new QueryColumnSelector("PROJECTMETA__METAVALUE", "DESCRIPTION")); + projectMetaQs.addExplicitFilter( + SimpleQueryFilter.makeColToValFilter("PROJECTMETA__METAKEY", "==", "description")); + projectMetaQs.addGroupBy(new QueryColumnSelector("PROJECTMETA__PROJECTID")); + projectMetaQs.addGroupBy(new QueryColumnSelector("PROJECTMETA__METAVALUE")); + + SubqueryRelationship projectMetaRel = new SubqueryRelationship(projectMetaQs, "PM", "left.outer.join", + new String[] { "PM__PROJECTID", "PROJECT__PROJECTID", "=" }); + qs.addRelation(projectMetaRel); + + // Use conditional selector for description + QueryIfSelector descriptionSelector = QueryIfSelector.makeQueryIfSelector( + isProjectDependency(), + new QueryColumnSelector("PM__DESCRIPTION"), new QueryColumnSelector("EM__DESCRIPTION"), + "description"); + qs.addSelector(descriptionSelector); + + // ENGINE metadata sub-query for tags - aggregated since there can be multiple + SelectQueryStruct engineTagsQs = new SelectQueryStruct(); + engineTagsQs.addSelector(new QueryColumnSelector("ENGINEMETA__ENGINEID", "ENGINEID")); + QueryFunctionSelector engineTagsAggregator = new QueryFunctionSelector(); + engineTagsAggregator.setFunction(QueryFunctionHelper.GROUP_CONCAT); + engineTagsAggregator.addInnerSelector(new QueryColumnSelector("ENGINEMETA__METAVALUE")); + engineTagsAggregator.setAlias("TAGS"); + engineTagsQs.addSelector(engineTagsAggregator); + engineTagsQs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("ENGINEMETA__METAKEY", "==", "tag")); + engineTagsQs.addGroupBy(new QueryColumnSelector("ENGINEMETA__ENGINEID")); + + SubqueryRelationship engineTagsRel = new SubqueryRelationship(engineTagsQs, "ET", "left.outer.join", + new String[] { "ET__ENGINEID", "ENGINE__ENGINEID", "=" }); + qs.addRelation(engineTagsRel); + + // PROJECT metadata sub-query for tags - aggregated since there can be multiple + SelectQueryStruct projectTagsQs = new SelectQueryStruct(); + projectTagsQs.addSelector(new QueryColumnSelector("PROJECTMETA__PROJECTID", "PROJECTID")); + QueryFunctionSelector projectTagsAggregator = new QueryFunctionSelector(); + projectTagsAggregator.setFunction(QueryFunctionHelper.GROUP_CONCAT); + projectTagsAggregator.addInnerSelector(new QueryColumnSelector("PROJECTMETA__METAVALUE")); + projectTagsAggregator.setAlias("TAGS"); + projectTagsQs.addSelector(projectTagsAggregator); + projectTagsQs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECTMETA__METAKEY", "==", "tag")); + projectTagsQs.addGroupBy(new QueryColumnSelector("PROJECTMETA__PROJECTID")); + + SubqueryRelationship projectTagsRel = new SubqueryRelationship(projectTagsQs, "PT", "left.outer.join", + new String[] { "PT__PROJECTID", "PROJECT__PROJECTID", "=" }); + qs.addRelation(projectTagsRel); + + // Use conditional selector for tags + QueryIfSelector tagsSelector = QueryIfSelector.makeQueryIfSelector( + isProjectDependency(), + new QueryColumnSelector("PT__TAGS"), new QueryColumnSelector("ET__TAGS"), "tags"); + qs.addSelector(tagsSelector); + } + + // PERMISSION sub-query - conditional based on type (ENGINEPERMISSION vs + // PROJECTPERMISSION) + { + // ENGINE permissions sub-query + SelectQueryStruct enginePermQs = new SelectQueryStruct(); + enginePermQs.addSelector(new QueryColumnSelector("ENGINEPERMISSION__ENGINEID", "ENGINEID")); + enginePermQs.addSelector(new QueryColumnSelector("ENGINEPERMISSION__PERMISSION", "PERMISSION")); + enginePermQs.addRelation("ENGINEPERMISSION__PERMISSION", "PERMISSION__ID", "inner.join"); + enginePermQs.addSelector(new QueryColumnSelector("PERMISSION__NAME", "PERMISSION_NAME")); + enginePermQs + .addExplicitFilter(SimpleQueryFilter.makeColToValFilter("ENGINEPERMISSION__USERID", "==", userId)); + enginePermQs.addGroupBy(new QueryColumnSelector("ENGINEPERMISSION__ENGINEID")); + enginePermQs.addGroupBy(new QueryColumnSelector("ENGINEPERMISSION__PERMISSION")); + enginePermQs.addGroupBy(new QueryColumnSelector("PERMISSION__NAME")); + + SubqueryRelationship enginePermRel = new SubqueryRelationship(enginePermQs, "EP", "left.outer.join", + new String[] { "EP__ENGINEID", "ENGINE__ENGINEID", "=" }); + qs.addRelation(enginePermRel); + + // PROJECT permissions sub-query + SelectQueryStruct projectPermQs = new SelectQueryStruct(); + projectPermQs.addSelector(new QueryColumnSelector("PROJECTPERMISSION__PROJECTID", "PROJECTID")); + projectPermQs.addSelector(new QueryColumnSelector("PROJECTPERMISSION__PERMISSION", "PERMISSION")); + projectPermQs.addRelation("PROJECTPERMISSION__PERMISSION", "PERMISSION__ID", "inner.join"); + projectPermQs.addSelector(new QueryColumnSelector("PERMISSION__NAME", "PERMISSION_NAME")); + projectPermQs + .addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECTPERMISSION__USERID", "==", userId)); + projectPermQs.addGroupBy(new QueryColumnSelector("PROJECTPERMISSION__PROJECTID")); + projectPermQs.addGroupBy(new QueryColumnSelector("PROJECTPERMISSION__PERMISSION")); + projectPermQs.addGroupBy(new QueryColumnSelector("PERMISSION__NAME")); + + SubqueryRelationship projectPermRel = new SubqueryRelationship(projectPermQs, "PP", "left.outer.join", + new String[] { "PP__PROJECTID", "PROJECT__PROJECTID", "=" }); + qs.addRelation(projectPermRel); + + // Use conditional selectors for permissions + QueryIfSelector permissionSelector = QueryIfSelector.makeQueryIfSelector( + isProjectDependency(), + new QueryColumnSelector("PP__PERMISSION"), new QueryColumnSelector("EP__PERMISSION"), "permission"); + qs.addSelector(permissionSelector); + + QueryIfSelector permissionNameSelector = QueryIfSelector.makeQueryIfSelector( + isProjectDependency(), + new QueryColumnSelector("PP__PERMISSION_NAME"), new QueryColumnSelector("EP__PERMISSION_NAME"), + "permission_name"); + qs.addSelector(permissionNameSelector); + } + + // GROUP PERMISSION sub-query - conditional based on type (GROUPENGINEPERMISSION + // vs + // GROUPPROJECTPERMISSION) + { + // Build the group filter once for reuse + OrQueryFilter groupOrFilters = new OrQueryFilter(); + if (user != null) { + List logins = user.getLogins(); + for (AuthProvider login : logins) { + AccessToken accessToken = user.getAccessToken(login); + Collection userGroups = accessToken.getUserGroups(); + String userGroupType = accessToken.getUserGroupType(); + Collection userCustomGroups = AdminSecurityGroupUtils.getUserCustomGroups(accessToken); + if (!userCustomGroups.isEmpty()) { + AndQueryFilter customAndFilter = new AndQueryFilter(); + customAndFilter.addFilter( + SimpleQueryFilter.makeColToValFilter("GROUPENGINEPERMISSION__TYPE", "==", "CUSTOM")); + customAndFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPENGINEPERMISSION__ID", + "==", userCustomGroups)); + groupOrFilters.addFilter(customAndFilter); + } + if (!userGroups.isEmpty()) { + AndQueryFilter andFilter = new AndQueryFilter(); + andFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPENGINEPERMISSION__TYPE", "==", + userGroupType)); + andFilter.addFilter( + SimpleQueryFilter.makeColToValFilter("GROUPENGINEPERMISSION__ID", "==", userGroups)); + groupOrFilters.addFilter(andFilter); + } + } + } + + // ENGINE group permissions sub-query + SelectQueryStruct engineGroupPermQs = new SelectQueryStruct(); + engineGroupPermQs.addSelector(new QueryColumnSelector("GROUPENGINEPERMISSION__ENGINEID", "ENGINEID")); + engineGroupPermQs.addSelector(QueryFunctionSelector.makeFunctionSelector(QueryFunctionHelper.MIN, + "GROUPENGINEPERMISSION__PERMISSION", "PERMISSION")); + engineGroupPermQs.addGroupBy(new QueryColumnSelector("GROUPENGINEPERMISSION__ENGINEID")); + if (!groupOrFilters.isEmpty()) { + engineGroupPermQs.addExplicitFilter(groupOrFilters); + } else { + AndQueryFilter nullFilter = new AndQueryFilter(); + nullFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPENGINEPERMISSION__TYPE", "==", null)); + nullFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPENGINEPERMISSION__ID", "==", null)); + engineGroupPermQs.addExplicitFilter(nullFilter); + } + + SubqueryRelationship engineGroupPermRel = new SubqueryRelationship(engineGroupPermQs, "EGP", + "left.outer.join", new String[] { "EGP__ENGINEID", "ENGINE__ENGINEID", "=" }); + qs.addRelation(engineGroupPermRel); + + // PROJECT group permissions sub-query + OrQueryFilter groupProjectOrFilters = new OrQueryFilter(); + if (user != null) { + List logins = user.getLogins(); + for (AuthProvider login : logins) { + AccessToken accessToken = user.getAccessToken(login); + Collection userGroups = accessToken.getUserGroups(); + String userGroupType = accessToken.getUserGroupType(); + Collection userCustomGroups = AdminSecurityGroupUtils.getUserCustomGroups(accessToken); + if (!userCustomGroups.isEmpty()) { + AndQueryFilter customAndFilter = new AndQueryFilter(); + customAndFilter.addFilter( + SimpleQueryFilter.makeColToValFilter("GROUPPROJECTPERMISSION__TYPE", "==", "CUSTOM")); + customAndFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPPROJECTPERMISSION__ID", + "==", userCustomGroups)); + groupProjectOrFilters.addFilter(customAndFilter); + } + if (!userGroups.isEmpty()) { + AndQueryFilter andFilter = new AndQueryFilter(); + andFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPPROJECTPERMISSION__TYPE", "==", + userGroupType)); + andFilter.addFilter( + SimpleQueryFilter.makeColToValFilter("GROUPPROJECTPERMISSION__ID", "==", userGroups)); + groupProjectOrFilters.addFilter(andFilter); + } + } + } + + SelectQueryStruct projectGroupPermQs = new SelectQueryStruct(); + projectGroupPermQs.addSelector(new QueryColumnSelector("GROUPPROJECTPERMISSION__PROJECTID", "PROJECTID")); + projectGroupPermQs.addSelector(QueryFunctionSelector.makeFunctionSelector(QueryFunctionHelper.MIN, + "GROUPPROJECTPERMISSION__PERMISSION", "PERMISSION")); + projectGroupPermQs.addGroupBy(new QueryColumnSelector("GROUPPROJECTPERMISSION__PROJECTID")); + if (!groupProjectOrFilters.isEmpty()) { + projectGroupPermQs.addExplicitFilter(groupProjectOrFilters); + } else { + AndQueryFilter nullFilter = new AndQueryFilter(); + nullFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPPROJECTPERMISSION__TYPE", "==", null)); + nullFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPPROJECTPERMISSION__ID", "==", null)); + projectGroupPermQs.addExplicitFilter(nullFilter); + } + + SubqueryRelationship projectGroupPermRel = new SubqueryRelationship(projectGroupPermQs, "PGP", + "left.outer.join", new String[] { "PGP__PROJECTID", "PROJECT__PROJECTID", "=" }); + qs.addRelation(projectGroupPermRel); + + // Use conditional selector for group permission based on engine type + QueryIfSelector groupPermissionSelector = QueryIfSelector.makeQueryIfSelector( + isProjectDependency(), + new QueryColumnSelector("PGP__PERMISSION"), new QueryColumnSelector("EGP__PERMISSION"), + "group_permission"); + qs.addSelector(groupPermissionSelector); + } + + // ACCESS REQUEST sub-query - conditional based on type (ENGINEACCESSREQUEST vs + // PROJECTACCESSREQUEST) + { + // ENGINE access requests sub-query + SelectQueryStruct engineAccReqQs = new SelectQueryStruct(); + engineAccReqQs.addSelector(new QueryColumnSelector("ENGINEACCESSREQUEST__PERMISSION", "PERMISSION")); + engineAccReqQs.addSelector(new QueryColumnSelector("ENGINEACCESSREQUEST__ENGINEID", "ENGINEID")); + engineAccReqQs.addRelation("ENGINEACCESSREQUEST__ENGINEID", "ENGINE__ENGINEID", "inner.join"); + engineAccReqQs.addExplicitFilter( + SimpleQueryFilter.makeColToValFilter("ENGINEACCESSREQUEST__REQUEST_USERID", "==", userId)); + engineAccReqQs.addExplicitFilter(SimpleQueryFilter + .makeColToValFilter("ENGINEACCESSREQUEST__APPROVER_DECISION", "==", "NEW_REQUEST")); + + SubqueryRelationship engineAReqRel = new SubqueryRelationship(engineAccReqQs, "EAR", "left.outer.join", + new String[] { "EAR__ENGINEID", "ENGINE__ENGINEID", "=" }); + qs.addRelation(engineAReqRel); + + // PROJECT access requests sub-query + SelectQueryStruct projectAccReqQs = new SelectQueryStruct(); + projectAccReqQs.addSelector(new QueryColumnSelector("PROJECTACCESSREQUEST__PERMISSION", "PERMISSION")); + projectAccReqQs.addSelector(new QueryColumnSelector("PROJECTACCESSREQUEST__PROJECTID", "PROJECTID")); + projectAccReqQs.addRelation("PROJECTACCESSREQUEST__PROJECTID", "PROJECT__PROJECTID", "inner.join"); + projectAccReqQs.addExplicitFilter( + SimpleQueryFilter.makeColToValFilter("PROJECTACCESSREQUEST__REQUEST_USERID", "==", userId)); + projectAccReqQs.addExplicitFilter(SimpleQueryFilter + .makeColToValFilter("PROJECTACCESSREQUEST__APPROVER_DECISION", "==", "NEW_REQUEST")); + + SubqueryRelationship projectAReqRel = new SubqueryRelationship(projectAccReqQs, "PAR", "left.outer.join", + new String[] { "PAR__PROJECTID", "PROJECT__PROJECTID", "=" }); + qs.addRelation(projectAReqRel); + + // Use conditional selector for access permission + QueryIfSelector accessPermissionSelector = QueryIfSelector.makeQueryIfSelector( + isProjectDependency(), + new QueryColumnSelector("PAR__PERMISSION"), new QueryColumnSelector("EAR__PERMISSION"), + "access_permission"); + qs.addSelector(accessPermissionSelector); + } + + return QueryExecutionUtility.flushRsToMap(securityDb, qs); + } + + /** + * Gives a person the requested access to the engines and projects a project + * depends on, or asks their owners for it. On a model, a person added gets no + * usage limit, and a person whose access changes keeps theirs. + * + * @param requester the user asking + * @param projectId the project + * @param newUserId the person + * @param newUserType the person's login type + * @param requestedPermission the level, by name + * @param endDate when the access ends, or null + * @return the engines and projects by what was done for each + */ + public static Map propagatePermission(User requester, String projectId, String newUserId, + String newUserType, String requestedPermission, String endDate) { + return propagate(requester, projectId, newUserId, newUserType, requestedPermission, endDate, null); + } + + /** + * Gives a person the requested access to the engines and projects a project + * depends on, or asks their owners for it. Only a model's owners set a limit + * that differs from the current one. + * + * @param requester the user asking + * @param projectId the project + * @param newUserId the person + * @param newUserType the person's login type + * @param requestedPermission the level, by name + * @param endDate when the access ends, or null + * @param usageLimit the person's model usage limit on each model given + * or changed, or null for no limit defined + * @return the engines and projects by what was done for each + */ + public static Map propagatePermission(User requester, String projectId, String newUserId, + String newUserType, String requestedPermission, String endDate, ModelUsageLimit usageLimit) { + return propagate(requester, projectId, newUserId, newUserType, requestedPermission, endDate, + new PermissionGrant().withUsageLimit(usageLimit)); + } + + /** + * Whether only admins can give people access to an engine or project a project + * depends on. A dependency whose setting cannot be read counts as admin-only. + * + * @param isEngine whether the dependency is an engine rather than a project + * @param id the dependency's id + * @return whether its admin-only add setting is on + */ + private static boolean dependencyAddsAreAdminOnly(boolean isEngine, String id) { + try { + return isEngine ? adminOnlyEngineAddAccess(id) : adminOnlyProjectAddAccess(id); + } catch (IllegalArgumentException e) { + classLogger.warn("Could not read the admin-only add setting of {}", id, e); + return true; + } + } + + /** + * Does the work of both propagatePermission methods: for each engine and + * project the project depends on, it gives the person the requested level, or + * files an access request for its owners when the requester is Read-Only or has + * no access there. + * + * @param limit the person's model usage limit on the models: a grant that gives + * {@code usageLimit} + * ({@link PermissionGrant#isUsageLimitGiven()}), or null for none, + * so a person whose access changes keeps theirs + */ + private static Map propagate(User requester, String projectId, String newUserId, String newUserType, + String requestedPermission, String endDate, PermissionGrant limit) { + Map ret = new HashMap(); + + // get the requested permission as a numeric -- it was passed as a string + Integer requestedPermissionNumeric = AccessPermissionEnum.getIdByPermission(requestedPermission); + boolean requesterIsAdmin = SecurityAdminUtils.userIsAdmin(requester); + + List alreadyHaveAccess = new ArrayList<>(); + List requestAlreadyExists = new ArrayList<>(); + List newRequestAdded = new ArrayList<>(); + List accessGranted = new ArrayList<>(); + List couldNotAddRequest = new ArrayList<>(); + + // loop through the dependencies and process request according to the + // requestor's permissions on each engine. + List> dependentEngines = getDependencies(projectId); + for (int i = 0; i < dependentEngines.size(); i++) { + Map dependentEngine = dependentEngines.get(i); + String dependentEngineId = (String) dependentEngine.get("catalog_id"); + String dependentEngineType = (String) dependentEngine.get("catalog_type"); + + Integer currentPendingUserPermission; + Integer requesterEnginePermission; + Integer currentNewUserPermission; + boolean isEngine = false; + // only a model has usage limits + PermissionGrant engineLimit = IEngine.CATALOG_TYPE.MODEL.name().equals(dependentEngineType) ? limit : null; + + if (dependentEngineType == null || !CatalogTypes.isProjectType(dependentEngineType)) { + isEngine = true; + currentPendingUserPermission = SecurityEngineUtils.getUserAccessRequestEnginePermission(newUserId, + dependentEngineId); + requesterEnginePermission = SecurityEngineUtils + .getUserEnginePermission(User.getSingleLogginName(requester), dependentEngineId); + currentNewUserPermission = SecurityEngineUtils.getUserEnginePermission(newUserId, dependentEngineId); + } else { + currentPendingUserPermission = SecurityProjectUtils.getUserAccessRequestProjectPermission(newUserId, + dependentEngineId); + requesterEnginePermission = SecurityProjectUtils + .getUserProjectPermission(User.getSingleLogginName(requester), dependentEngineId); + currentNewUserPermission = SecurityProjectUtils.getUserProjectPermission(newUserId, dependentEngineId); + } + + // if newUser is requesting permission which he/she already has access, take no + // action + if (currentNewUserPermission == requestedPermissionNumeric) { + alreadyHaveAccess.add(dependentEngineId); + classLogger.info("User already has {} access to {}", requestedPermission, dependentEngineId); + // if newUser has already requested this access and it is still pending, take no + // action + } else if (currentPendingUserPermission != null + && requestedPermissionNumeric == currentPendingUserPermission) { + requestAlreadyExists.add(dependentEngineId); + classLogger.info("user has already requested {} access to {} and the request is pending.", + requestedPermission, dependentEngineId); + // if requester has insufficient privileges on the engine so forward request to + // engine owner + } else if (requesterEnginePermission == null || requesterEnginePermission == 3) { + try { + if (isEngine) { + SecurityEngineUtils.setUserAccessRequest(newUserId, newUserType, dependentEngineId, + "No Comment at this time", requestedPermissionNumeric, requester); + } else { + SecurityProjectUtils.setUserAccessRequest(newUserId, newUserType, dependentEngineId, + "No Comment at this time", requestedPermissionNumeric, requester); + } + newRequestAdded.add(dependentEngineId); + classLogger.info("User has forwarded {}'s request to the owner of engine {}", newUserId, + dependentEngineId); + } catch (Exception e) { + couldNotAddRequest.add(dependentEngineId); + classLogger.error("Failed to propagate project permissions to related artifacts", e); + } + // if the newUser has permissions on the engine but not to the level requested, + // edit the existing record + } else if (!requesterIsAdmin && dependencyAddsAreAdminOnly(isEngine, dependentEngineId)) { + // these grants skip the endpoints, so each dependency's own setting is checked + couldNotAddRequest.add(dependentEngineId); + classLogger.info("Only admins can give {} access to {}", newUserId, dependentEngineId); + } else if (requesterEnginePermission < 3 && currentNewUserPermission != null + && currentNewUserPermission > requestedPermissionNumeric) { + try { + if (isEngine) { + editDependentEngineUser(requester, newUserId, newUserType, dependentEngineId, + requestedPermission, endDate, engineLimit); + } else { + SecurityProjectUtils.editProjectUserPermission(requester, newUserId, newUserType, + dependentEngineId, requestedPermission, endDate); + } + + accessGranted.add(dependentEngineId); + classLogger.info("User has updated permission for {} to {}", newUserId, dependentEngineId); + } catch (IllegalAccessException | IllegalArgumentException e) { + couldNotAddRequest.add(dependentEngineId); + classLogger.error("Failed to propagate project permissions to related artifacts", e); + } + // if none of the above and requestor has proper permission, add user to the + // engine permission database + } else if (requesterEnginePermission < 3 && currentNewUserPermission == null) { + try { + if (isEngine) { + addDependentEngineUser(requester, newUserId, dependentEngineId, requestedPermission, endDate, + engineLimit); + } else { + SecurityProjectUtils.addProjectUser(requester, newUserId, dependentEngineId, + requestedPermission, endDate); + } + + accessGranted.add(dependentEngineId); + classLogger.info("User has added {} to {}", newUserId, dependentEngineId); + } catch (IllegalAccessException | IllegalArgumentException e) { + couldNotAddRequest.add(dependentEngineId); + classLogger.error("Failed to propagate project permissions to related artifacts", e); + } + } else { + couldNotAddRequest.add(dependentEngineId); + classLogger.info("User could not add or forward {}'s request for engine {}", newUserId, + dependentEngineId); + } + } + + ret.put("Successfully processed permission propagation", true); + ret.put("alreadyHaveAccess", alreadyHaveAccess); + ret.put("requestAlreadyExists", requestAlreadyExists); + ret.put("newRequestAdded", newRequestAdded); + ret.put("accessGranted", accessGranted); + ret.put("couldNotAddRequest", couldNotAddRequest); + return ret; + } + + /** + * Gives a person access to an engine a project depends on, with the usage limit + * given, or none. + * + * @param limit on a model, the limit the propagation gives; null for none + */ + private static void addDependentEngineUser(User requester, String newUserId, String engineId, String level, + String endDate, PermissionGrant limit) throws IllegalAccessException { + SecurityEngineUtils.addEngineUser(requester, newUserId, engineId, level, endDate, + limit == null ? null : limit.getUsageLimit()); + } + + /** + * Changes a person's access to an engine a project depends on. Their usage + * limit is kept unless one is given. + * + * @param limit on a model, the limit the propagation gives; null for none + */ + private static void editDependentEngineUser(User requester, String newUserId, String newUserType, String engineId, + String level, String endDate, PermissionGrant limit) throws IllegalAccessException { + if (limit != null && limit.isUsageLimitGiven()) { + SecurityEngineUtils.editEngineUserPermission(requester, newUserId, newUserType, engineId, level, endDate, + limit.getUsageLimit()); + } else { + SecurityEngineUtils.editEngineUserPermission(requester, newUserId, newUserType, engineId, level, endDate); + } + } +} diff --git a/src/prerna/auth/utils/SecurityEngineUtils.java b/src/prerna/auth/utils/SecurityEngineUtils.java index 8ab68add218..508060aaf54 100644 --- a/src/prerna/auth/utils/SecurityEngineUtils.java +++ b/src/prerna/auth/utils/SecurityEngineUtils.java @@ -1141,6 +1141,8 @@ public static void deleteEngine(String engineId) { deletes.add("DELETE FROM ENGINE WHERE ENGINEID=?"); deletes.add("DELETE FROM ENGINEPERMISSION WHERE ENGINEID=?"); deletes.add("DELETE FROM PROJECTENGINEPERMISSION WHERE ENGINEID=?"); + // the dependencies the engine owns; others that depend on it keep theirs + deletes.add("DELETE FROM CATALOGDEPENDENCIES WHERE CATALOGID=?"); deletes.add("DELETE FROM USERENGINEPREFERENCE WHERE ENGINEID=?"); deletes.add("DELETE FROM ENGINEMETA WHERE ENGINEID=?"); deletes.add("DELETE FROM MODELMETADATA WHERE ENGINEID=?"); diff --git a/src/prerna/auth/utils/SecurityOwlCreator.java b/src/prerna/auth/utils/SecurityOwlCreator.java index 406d48599ef..c365e168b18 100644 --- a/src/prerna/auth/utils/SecurityOwlCreator.java +++ b/src/prerna/auth/utils/SecurityOwlCreator.java @@ -206,10 +206,11 @@ public void createColumnsAndTypes(AbstractSqlQueryUtil queryUtil) { Pair.with("METAVALUE", CLOB_DATATYPE_NAME), Pair.with("METAORDER", INTEGER_DATATYPE_NAME))); - addTable("PROJECTDEPENDENCIES", Arrays.asList( - Pair.with("PROJECTID", VARCHAR_255), - Pair.with("ENGINEID", VARCHAR_255), - Pair.with("ENGINETYPE", VARCHAR_255), + addTable("CATALOGDEPENDENCIES", Arrays.asList( + Pair.with("CATALOGID", VARCHAR_255), + Pair.with("CATALOGTYPE", VARCHAR_255), + Pair.with("DEPENDENCYID", VARCHAR_255), + Pair.with("DEPENDENCYTYPE", VARCHAR_255), Pair.with("USERID", VARCHAR_255), Pair.with("TYPE", VARCHAR_255), Pair.with("DATEADDED", TIMESTAMP_DATATYPE_NAME))); diff --git a/src/prerna/auth/utils/SecurityProjectUtils.java b/src/prerna/auth/utils/SecurityProjectUtils.java index 209ea66b958..d1549f2bde4 100644 --- a/src/prerna/auth/utils/SecurityProjectUtils.java +++ b/src/prerna/auth/utils/SecurityProjectUtils.java @@ -574,6 +574,36 @@ private static void updateProject(Connection connection, AbstractSqlQueryUtil qu ps.setBoolean(parameterIndex++, global); ps.setString(parameterIndex++, projectId); }); + // keep the project's type current where it owns or is a catalog dependency + String catalogType = catalogTypeOrNull(projectType); + if (catalogType != null) { + QueryExecutionUtility.executeUpdate(connection, + "UPDATE CATALOGDEPENDENCIES SET CATALOGTYPE=? WHERE CATALOGID=?", ps -> { + ps.setString(1, catalogType); + ps.setString(2, projectId); + }); + QueryExecutionUtility.executeUpdate(connection, + "UPDATE CATALOGDEPENDENCIES SET DEPENDENCYTYPE=? WHERE DEPENDENCYID=?", ps -> { + ps.setString(1, catalogType); + ps.setString(2, projectId); + }); + } + } + + /** + * A project type as CATALOGDEPENDENCIES keeps it, or null when it is not a + * project type + */ + private static String catalogTypeOrNull(String projectType) { + if (projectType == null || projectType.isBlank()) { + return null; + } + try { + String type = CatalogTypes.normalize(projectType); + return CatalogTypes.isProjectType(type) ? type : null; + } catch (IllegalArgumentException e) { + return null; + } } /** @@ -1596,7 +1626,7 @@ public static void deleteProject(String projectId) { deletes.add("DELETE FROM PROJECTMETA WHERE PROJECTID=?"); deletes.add("DELETE FROM ASSETENGINE WHERE PROJECTID=?"); deletes.add("DELETE FROM PROJECTACCESSREQUEST WHERE PROJECTID=?"); - deletes.add("DELETE FROM PROJECTDEPENDENCIES WHERE PROJECTID=?"); + deletes.add("DELETE FROM CATALOGDEPENDENCIES WHERE CATALOGID=?"); deletes.add("DELETE FROM PROJECTENGINEPERMISSION WHERE PROJECTID=?"); for (String deleteQuery : deletes) { try { @@ -1844,1019 +1874,6 @@ public static boolean setProjectName(User user, String projectId, String newProj return true; } - /* - * Project Dependencies - */ - - /** - * Update the project dependencies Will delete existing values and then perform - * a bulk insert - * - * @param user - * @param projectId - * @param dependentEngineIds - */ - @Deprecated - public static void updateProjectDependenciesWithoutType(User user, String projectId, - Collection dependentEngineIds) { - List> depEngines = new ArrayList<>(); - for (String depEngineId : dependentEngineIds) { - Map depEngine = new HashMap<>(); - depEngine.put("ENGINEID", depEngineId); - IEngine engine = null; - try { - engine = Utility.getEngine(depEngineId); - depEngine.put("ENGINETYPE", engine.getCatalogType().name()); - } catch (Exception ex) { - // ignore - } - if (engine == null) { - engine = Utility.getProject(depEngineId); - depEngine.put("ENGINETYPE", IEngine.CATALOG_TYPE.PROJECT.name()); - } - depEngines.add(depEngine); - } - updateProjectDependencies(user, projectId, depEngines); - } - - /** - * Update the project dependencies Will delete existing values and then perform - * a bulk insert - * - * @param user - * @param projectId - * @param dependentEngineIds - */ - public static void updateProjectDependencies(User user, String projectId, - List> dependentEngines) { - IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); - try { - QueryExecutionUtility.write(securityDb, connection -> { - // first do a delete - String deleteQ = "DELETE FROM PROJECTDEPENDENCIES WHERE PROJECTID=?"; - - QueryExecutionUtility.executeUpdate(connection, deleteQ, deletePs -> { - int parameterIndex = 1; - deletePs.setString(parameterIndex++, projectId); - }); - - if (dependentEngines != null && !dependentEngines.isEmpty()) { - AccessToken token = user.getPrimaryLoginToken(); - java.sql.Timestamp timestamp = Utility.getCurrentSqlTimestampUTC(); - // now we do the new insert with the order of the tags - String query = securityDb.getQueryUtil().createInsertPreparedStatementString("PROJECTDEPENDENCIES", - new String[] { "PROJECTID", "ENGINEID", "ENGINETYPE", "USERID", "TYPE", "DATEADDED" }); - - QueryExecutionUtility.executeBatch(connection, query, dependentEngines, (ps, depEngine) -> { - int parameterIndex = 1; - ps.setString(parameterIndex++, projectId); - ps.setString(parameterIndex++, (String) depEngine.get("ENGINEID")); - ps.setString(parameterIndex++, (String) depEngine.get("ENGINETYPE")); - ps.setString(parameterIndex++, token.getId()); - ps.setString(parameterIndex++, token.getProvider().getLabel()); - ps.setTimestamp(parameterIndex++, timestamp); - }); - - } - return null; - }); - } catch (Exception e) { - classLogger.error("Failed to update project dependency mappings", e); - } - } - - /** - * Remove dependency from project - * - * @param user - * @param projectId - * @param dependentEngineId - */ - public static void removeProjectDependency(User user, String projectId, String dependentEngineId) - throws IllegalAccessException { - IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); - - if (!SecurityUserProjectUtils.userCanEditProject(user, projectId)) { - throw new IllegalAccessException("User does not have permissions to remove dependencies"); - } - - String deleteQ = "DELETE FROM PROJECTDEPENDENCIES WHERE PROJECTID=? AND ENGINEID=?"; - try { - QueryExecutionUtility.executeUpdate(securityDb, deleteQ, deletePs -> { - int parameterIndex = 1; - deletePs.setString(parameterIndex++, projectId); - deletePs.setString(parameterIndex++, dependentEngineId); - }); - } catch (Exception e) { - classLogger.error("Failed to remove project dependency mappings", e); - } - } - - /** - * Get project dependencies - * - * @param projectId - * @return - */ - public static List> getProjectDependencies(String projectId) { - return getProjectDependencies(projectId, false); - } - - /** - * Get project dependencies with optional subdependencies - * - * @param projectId - * @param subdependencies if true, recursively fetch subdependencies - * @return - */ - public static List> getProjectDependencies(String projectId, boolean subdependencies) { - IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); - if (subdependencies) { - Set visited = new HashSet<>(); - List> allDependencies = new ArrayList<>(); - getProjectDependenciesRecursive(projectId, visited, allDependencies); - return allDependencies; - } else { - SelectQueryStruct qs = new SelectQueryStruct(); - qs.addSelector(new QueryColumnSelector("PROJECTDEPENDENCIES__PROJECTID", "parent_id")); - qs.addSelector(new QueryColumnSelector("PROJECTDEPENDENCIES__ENGINEID", "engine_id")); - qs.addSelector(new QueryColumnSelector("PROJECTDEPENDENCIES__ENGINETYPE", "engine_type")); - qs.addExplicitFilter( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__PROJECTID", "==", projectId)); - return QueryExecutionUtility.flushRsToMap(securityDb, qs); - } - } - - /** - * Helper method to recursively fetch project dependencies - * - * @param projectId - * @param visited Set to track visited projects to avoid circular - * dependencies - * @param allDependencies Accumulated list of all dependencies - */ - private static void getProjectDependenciesRecursive(String projectId, Set visited, - List> allDependencies) { - IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); - // Avoid circular dependencies - if (visited.contains(projectId)) { - return; - } - visited.add(projectId); - - // Query direct dependencies - SelectQueryStruct qs = new SelectQueryStruct(); - qs.addSelector(new QueryColumnSelector("PROJECTDEPENDENCIES__PROJECTID", "parent_id")); - qs.addSelector(new QueryColumnSelector("PROJECTDEPENDENCIES__ENGINEID", "engine_id")); - qs.addSelector(new QueryColumnSelector("PROJECTDEPENDENCIES__ENGINETYPE", "engine_type")); - qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__PROJECTID", "==", projectId)); - - List> directDependencies = QueryExecutionUtility.flushRsToMap(securityDb, qs); - - // Add direct dependencies and recurse for PROJECT type dependencies - for (Map dependency : directDependencies) { - allDependencies.add(dependency); - String engineId = (String) dependency.get("engine_id"); - getProjectDependenciesRecursive(engineId, visited, allDependencies); - } - } - - /** - * Get project dependency details - * - * @param projectId - * @return - */ - public static List> getProjectDependencyDetails(String projectId) { - return getProjectDependencyDetails(projectId, false); - } - - /** - * Get project dependency details with optional subdependencies - * - * @param projectId - * @param subdependencies if true, recursively fetch subdependencies - * @return - */ - public static List> getProjectDependencyDetails(String projectId, boolean subdependencies) { - if (subdependencies) { - Set visited = new HashSet<>(); - List> allDependencies = new ArrayList<>(); - getProjectDependencyDetailsRecursive(projectId, visited, allDependencies); - return allDependencies; - } else { - return getProjectDependencyDetailsQuery(projectId); - } - } - - /** - * Helper method to recursively fetch project dependency details - * - * @param projectId - * @param visited Set to track visited projects to avoid circular - * dependencies - * @param allDependencies Accumulated list of all dependencies - */ - private static void getProjectDependencyDetailsRecursive(String projectId, Set visited, - List> allDependencies) { - // Avoid circular dependencies - if (visited.contains(projectId)) { - return; - } - visited.add(projectId); - - // Query direct dependencies - List> directDependencies = getProjectDependencyDetailsQuery(projectId); - - // Add direct dependencies and recurse for PROJECT type dependencies - for (Map dependency : directDependencies) { - allDependencies.add(dependency); - - String engineId = (String) dependency.get("engine_id"); - getProjectDependencyDetailsRecursive(engineId, visited, allDependencies); - } - } - - /** - * Query to get project dependency details for a single project - * - * @param projectId - * @return - */ - private static List> getProjectDependencyDetailsQuery(String projectId) { - IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); - SelectQueryStruct qs = new SelectQueryStruct(); - qs.addSelector(new QueryColumnSelector("PROJECTDEPENDENCIES__PROJECTID", "parent_id")); - qs.addSelector(new QueryColumnSelector("PROJECTDEPENDENCIES__ENGINEID", "engine_id")); - qs.addSelector(new QueryColumnSelector("PROJECTDEPENDENCIES__ENGINETYPE", "engine_type")); - - // Use conditional selectors based on engine type - QueryIfSelector engineNameSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PROJECT__PROJECTNAME"), new QueryColumnSelector("ENGINE__ENGINENAME"), - "engine_name"); - qs.addSelector(engineNameSelector); - - QueryIfSelector engineSubtypeSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PROJECT__TYPE"), new QueryColumnSelector("ENGINE__ENGINESUBTYPE"), - "engine_subtype"); - qs.addSelector(engineSubtypeSelector); - - QueryIfSelector engineDateCreatedSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PROJECT__DATECREATED"), new QueryColumnSelector("ENGINE__DATECREATED"), - "engine_date_created"); - qs.addSelector(engineDateCreatedSelector); - - QueryIfSelector engineDiscoverableSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PROJECT__DISCOVERABLE"), new QueryColumnSelector("ENGINE__DISCOVERABLE"), - "engine_discoverable"); - qs.addSelector(engineDiscoverableSelector); - - QueryIfSelector engineGlobalSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PROJECT__GLOBAL"), new QueryColumnSelector("ENGINE__GLOBAL"), "engine_global"); - qs.addSelector(engineGlobalSelector); - - // Add joins with proper join conditions - qs.addRelation("PROJECTDEPENDENCIES__ENGINEID", "ENGINE__ENGINEID", "left.outer.join"); - qs.addRelation("PROJECTDEPENDENCIES__ENGINEID", "PROJECT__PROJECTID", "left.outer.join"); - - qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__PROJECTID", "==", projectId)); - - return QueryExecutionUtility.flushRsToMap(securityDb, qs); - } - - /** - * Get project dependency details with user and group permissions - * - * @param projectId - * @param user - * @return - */ - public static List> getProjectDependencyDetails(String projectId, User user) { - return getProjectDependencyDetails(projectId, user, false); - } - - /** - * Get project dependency details with user and group permissions and optional - * subdependencies - * - * @param projectId - * @param user - * @param subdependencies if true, recursively fetch subdependencies - * @return - */ - public static List> getProjectDependencyDetails(String projectId, User user, - boolean subdependencies) { - if (subdependencies) { - Set visited = new HashSet<>(); - List> allDependencies = new ArrayList<>(); - getProjectDependencyDetailsWithUserRecursive(projectId, user, visited, allDependencies); - - // Calculate can_view_dependencies for each dependency - calculateCanViewDependencies(allDependencies); - - return allDependencies; - } else { - return getProjectDependencyDetailsWithUserQuery(projectId, user); - } - } - - /** - * Calculate can_view_dependencies field for each dependency by checking if user - * has view access to all subdependencies. Works from leaf nodes up the tree. - * Now accounts for both user permissions and group permissions. - * - * @param allDependencies List of all dependencies (flat structure) - */ - private static void calculateCanViewDependencies(List> allDependencies) { - // Build a map of engineId -> dependency for quick lookup - Map> dependencyMap = new HashMap<>(); - for (Map dep : allDependencies) { - String engineId = (String) dep.get("engine_id"); - dependencyMap.put(engineId, dep); - } - - // Build a map of parent -> list of children directly from allDependencies - // Since we already recursively fetched everything, we have all the parent-child - // relationships - Map> childrenMap = new HashMap<>(); - - for (Map dep : allDependencies) { - String parentId = (String) dep.get("parent_id"); - String engineId = (String) dep.get("engine_id"); - - // Add this engine as a child of its parent (skip self-references to prevent - // infinite loops) - if (parentId != null && !parentId.equals(engineId)) { - childrenMap.computeIfAbsent(parentId, k -> new ArrayList<>()).add(engineId); - } - } - - // Calculate can_view_dependencies from leaf nodes up - Map canViewCache = new HashMap<>(); - Set visiting = new HashSet<>(); - for (Map dep : allDependencies) { - String engineId = (String) dep.get("engine_id"); - boolean canView = calculateCanViewRecursive(engineId, dependencyMap, childrenMap, canViewCache, visiting); - dep.put("can_view_dependencies", canView); - } - } - - /** - * Recursively calculate if user can view all subdependencies for a given engine - * - * @param engineId The engine ID to check - * @param dependencyMap Map of engineId -> dependency data - * @param childrenMap Map of engineId -> list of child engine IDs - * @param canViewCache Cache to avoid recalculating - * @param visiting Set of engine IDs currently being processed (to detect - * circular dependencies) - * @return true if user has view access to this engine and all its - * subdependencies - */ - private static boolean calculateCanViewRecursive(String engineId, Map> dependencyMap, - Map> childrenMap, Map canViewCache, Set visiting) { - // Check cache first - if (canViewCache.containsKey(engineId)) { - return canViewCache.get(engineId); - } - - // Detect circular dependency - if we're already visiting this node, there's a - // cycle. Every node in the visiting set has already had its own - // hasViewPermission - // checked, so the back-edge doesn't introduce any new permission requirement. - // Return true to avoid poisoning the result for all nodes in the cycle. - if (visiting.contains(engineId)) { - return true; - } - - Map dependency = dependencyMap.get(engineId); - if (dependency == null) { - canViewCache.put(engineId, false); - return false; - } - - // Check if user has view permission for this engine - // Account for both user permissions and group permissions - boolean hasViewPermission = false; - Integer permission = (Integer) dependency.get("permission"); - Integer groupPermission = (Integer) dependency.get("group_permission"); - Boolean isGlobal = (Boolean) dependency.get("engine_global"); - - // User has view permission if they have any user permission, group permission, - // or if engine is global - hasViewPermission = (permission != null) || (groupPermission != null) || (isGlobal != null && isGlobal); - - // If this is a leaf node (no children), return the permission status - List children = childrenMap.get(engineId); - if (children == null || children.isEmpty()) { - canViewCache.put(engineId, hasViewPermission); - return hasViewPermission; - } - - // Mark this node as being visited to detect cycles - visiting.add(engineId); - - try { - // If this has children, check all subdependencies - boolean allChildrenViewable = true; - for (String childId : children) { - if (!calculateCanViewRecursive(childId, dependencyMap, childrenMap, canViewCache, visiting)) { - allChildrenViewable = false; - break; - } - } - - // User can view dependencies if they have permission for this node AND all - // children are viewable - boolean result = hasViewPermission && allChildrenViewable; - canViewCache.put(engineId, result); - return result; - } finally { - // Remove from visiting set after processing - visiting.remove(engineId); - } - } - - /** - * Helper method to recursively fetch project dependency details with user - * permissions - * - * @param projectId - * @param user - * @param visited Set to track visited projects to avoid circular - * dependencies - * @param allDependencies Accumulated list of all dependencies - */ - private static void getProjectDependencyDetailsWithUserRecursive(String projectId, User user, Set visited, - List> allDependencies) { - // Avoid circular dependencies - if (visited.contains(projectId)) { - return; - } - visited.add(projectId); - - // Query direct dependencies - List> directDependencies = getProjectDependencyDetailsWithUserQuery(projectId, user); - - // Add direct dependencies and recurse for PROJECT type dependencies - for (Map dependency : directDependencies) { - allDependencies.add(dependency); - String engineId = (String) dependency.get("engine_id"); - getProjectDependencyDetailsWithUserRecursive(engineId, user, visited, allDependencies); - } - } - - /** - * Query to get project dependency details with user and group permissions for a - * single project - * - * @param projectId - * @param user - * @return - */ - private static List> getProjectDependencyDetailsWithUserQuery(String projectId, User user) { - IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); - String userId = user.getPrimaryLoginToken().getId(); - SelectQueryStruct qs = new SelectQueryStruct(); - qs.addSelector(new QueryColumnSelector("PROJECTDEPENDENCIES__PROJECTID", "parent_id")); - qs.addSelector(new QueryColumnSelector("PROJECTDEPENDENCIES__ENGINEID", "engine_id")); - qs.addSelector(new QueryColumnSelector("PROJECTDEPENDENCIES__ENGINETYPE", "engine_type")); - - // Use conditional selectors based on engine type - QueryIfSelector engineNameSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PROJECT__PROJECTNAME"), new QueryColumnSelector("ENGINE__ENGINENAME"), - "engine_name"); - qs.addSelector(engineNameSelector); - - QueryIfSelector engineSubtypeSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PROJECT__TYPE"), new QueryColumnSelector("ENGINE__ENGINESUBTYPE"), - "engine_subtype"); - qs.addSelector(engineSubtypeSelector); - - QueryIfSelector engineDateCreatedSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PROJECT__DATECREATED"), new QueryColumnSelector("ENGINE__DATECREATED"), - "engine_date_created"); - qs.addSelector(engineDateCreatedSelector); - - QueryIfSelector engineDiscoverableSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PROJECT__DISCOVERABLE"), new QueryColumnSelector("ENGINE__DISCOVERABLE"), - "engine_discoverable"); - qs.addSelector(engineDiscoverableSelector); - - QueryIfSelector engineGlobalSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PROJECT__GLOBAL"), new QueryColumnSelector("ENGINE__GLOBAL"), "engine_global"); - qs.addSelector(engineGlobalSelector); - - // Add joins with proper join conditions - qs.addRelation("PROJECTDEPENDENCIES__ENGINEID", "ENGINE__ENGINEID", "left.outer.join"); - qs.addRelation("PROJECTDEPENDENCIES__ENGINEID", "PROJECT__PROJECTID", "left.outer.join"); - - qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__PROJECTID", "==", projectId)); - - // METADATA sub-query - conditional based on type (ENGINEMETA vs PROJECTMETA) - { - // ENGINE metadata sub-query for description - SelectQueryStruct engineMetaQs = new SelectQueryStruct(); - engineMetaQs.addSelector(new QueryColumnSelector("ENGINEMETA__ENGINEID", "ENGINEID")); - engineMetaQs.addSelector(new QueryColumnSelector("ENGINEMETA__METAVALUE", "DESCRIPTION")); - engineMetaQs.addExplicitFilter( - SimpleQueryFilter.makeColToValFilter("ENGINEMETA__METAKEY", "==", "description")); - engineMetaQs.addGroupBy(new QueryColumnSelector("ENGINEMETA__ENGINEID")); - engineMetaQs.addGroupBy(new QueryColumnSelector("ENGINEMETA__METAVALUE")); - - SubqueryRelationship engineMetaRel = new SubqueryRelationship(engineMetaQs, "EM", "left.outer.join", - new String[] { "EM__ENGINEID", "ENGINE__ENGINEID", "=" }); - qs.addRelation(engineMetaRel); - - // PROJECT metadata sub-query for description - SelectQueryStruct projectMetaQs = new SelectQueryStruct(); - projectMetaQs.addSelector(new QueryColumnSelector("PROJECTMETA__PROJECTID", "PROJECTID")); - projectMetaQs.addSelector(new QueryColumnSelector("PROJECTMETA__METAVALUE", "DESCRIPTION")); - projectMetaQs.addExplicitFilter( - SimpleQueryFilter.makeColToValFilter("PROJECTMETA__METAKEY", "==", "description")); - projectMetaQs.addGroupBy(new QueryColumnSelector("PROJECTMETA__PROJECTID")); - projectMetaQs.addGroupBy(new QueryColumnSelector("PROJECTMETA__METAVALUE")); - - SubqueryRelationship projectMetaRel = new SubqueryRelationship(projectMetaQs, "PM", "left.outer.join", - new String[] { "PM__PROJECTID", "PROJECT__PROJECTID", "=" }); - qs.addRelation(projectMetaRel); - - // Use conditional selector for description - QueryIfSelector descriptionSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PM__DESCRIPTION"), new QueryColumnSelector("EM__DESCRIPTION"), - "description"); - qs.addSelector(descriptionSelector); - - // ENGINE metadata sub-query for tags - aggregated since there can be multiple - SelectQueryStruct engineTagsQs = new SelectQueryStruct(); - engineTagsQs.addSelector(new QueryColumnSelector("ENGINEMETA__ENGINEID", "ENGINEID")); - QueryFunctionSelector engineTagsAggregator = new QueryFunctionSelector(); - engineTagsAggregator.setFunction(QueryFunctionHelper.GROUP_CONCAT); - engineTagsAggregator.addInnerSelector(new QueryColumnSelector("ENGINEMETA__METAVALUE")); - engineTagsAggregator.setAlias("TAGS"); - engineTagsQs.addSelector(engineTagsAggregator); - engineTagsQs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("ENGINEMETA__METAKEY", "==", "tag")); - engineTagsQs.addGroupBy(new QueryColumnSelector("ENGINEMETA__ENGINEID")); - - SubqueryRelationship engineTagsRel = new SubqueryRelationship(engineTagsQs, "ET", "left.outer.join", - new String[] { "ET__ENGINEID", "ENGINE__ENGINEID", "=" }); - qs.addRelation(engineTagsRel); - - // PROJECT metadata sub-query for tags - aggregated since there can be multiple - SelectQueryStruct projectTagsQs = new SelectQueryStruct(); - projectTagsQs.addSelector(new QueryColumnSelector("PROJECTMETA__PROJECTID", "PROJECTID")); - QueryFunctionSelector projectTagsAggregator = new QueryFunctionSelector(); - projectTagsAggregator.setFunction(QueryFunctionHelper.GROUP_CONCAT); - projectTagsAggregator.addInnerSelector(new QueryColumnSelector("PROJECTMETA__METAVALUE")); - projectTagsAggregator.setAlias("TAGS"); - projectTagsQs.addSelector(projectTagsAggregator); - projectTagsQs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECTMETA__METAKEY", "==", "tag")); - projectTagsQs.addGroupBy(new QueryColumnSelector("PROJECTMETA__PROJECTID")); - - SubqueryRelationship projectTagsRel = new SubqueryRelationship(projectTagsQs, "PT", "left.outer.join", - new String[] { "PT__PROJECTID", "PROJECT__PROJECTID", "=" }); - qs.addRelation(projectTagsRel); - - // Use conditional selector for tags - QueryIfSelector tagsSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PT__TAGS"), new QueryColumnSelector("ET__TAGS"), "tags"); - qs.addSelector(tagsSelector); - } - - // PERMISSION sub-query - conditional based on type (ENGINEPERMISSION vs - // PROJECTPERMISSION) - { - // ENGINE permissions sub-query - SelectQueryStruct enginePermQs = new SelectQueryStruct(); - enginePermQs.addSelector(new QueryColumnSelector("ENGINEPERMISSION__ENGINEID", "ENGINEID")); - enginePermQs.addSelector(new QueryColumnSelector("ENGINEPERMISSION__PERMISSION", "PERMISSION")); - enginePermQs.addRelation("ENGINEPERMISSION__PERMISSION", "PERMISSION__ID", "inner.join"); - enginePermQs.addSelector(new QueryColumnSelector("PERMISSION__NAME", "PERMISSION_NAME")); - enginePermQs - .addExplicitFilter(SimpleQueryFilter.makeColToValFilter("ENGINEPERMISSION__USERID", "==", userId)); - enginePermQs.addGroupBy(new QueryColumnSelector("ENGINEPERMISSION__ENGINEID")); - enginePermQs.addGroupBy(new QueryColumnSelector("ENGINEPERMISSION__PERMISSION")); - enginePermQs.addGroupBy(new QueryColumnSelector("PERMISSION__NAME")); - - SubqueryRelationship enginePermRel = new SubqueryRelationship(enginePermQs, "EP", "left.outer.join", - new String[] { "EP__ENGINEID", "ENGINE__ENGINEID", "=" }); - qs.addRelation(enginePermRel); - - // PROJECT permissions sub-query - SelectQueryStruct projectPermQs = new SelectQueryStruct(); - projectPermQs.addSelector(new QueryColumnSelector("PROJECTPERMISSION__PROJECTID", "PROJECTID")); - projectPermQs.addSelector(new QueryColumnSelector("PROJECTPERMISSION__PERMISSION", "PERMISSION")); - projectPermQs.addRelation("PROJECTPERMISSION__PERMISSION", "PERMISSION__ID", "inner.join"); - projectPermQs.addSelector(new QueryColumnSelector("PERMISSION__NAME", "PERMISSION_NAME")); - projectPermQs - .addExplicitFilter(SimpleQueryFilter.makeColToValFilter("PROJECTPERMISSION__USERID", "==", userId)); - projectPermQs.addGroupBy(new QueryColumnSelector("PROJECTPERMISSION__PROJECTID")); - projectPermQs.addGroupBy(new QueryColumnSelector("PROJECTPERMISSION__PERMISSION")); - projectPermQs.addGroupBy(new QueryColumnSelector("PERMISSION__NAME")); - - SubqueryRelationship projectPermRel = new SubqueryRelationship(projectPermQs, "PP", "left.outer.join", - new String[] { "PP__PROJECTID", "PROJECT__PROJECTID", "=" }); - qs.addRelation(projectPermRel); - - // Use conditional selectors for permissions - QueryIfSelector permissionSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PP__PERMISSION"), new QueryColumnSelector("EP__PERMISSION"), "permission"); - qs.addSelector(permissionSelector); - - QueryIfSelector permissionNameSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PP__PERMISSION_NAME"), new QueryColumnSelector("EP__PERMISSION_NAME"), - "permission_name"); - qs.addSelector(permissionNameSelector); - } - - // GROUP PERMISSION sub-query - conditional based on type (GROUPENGINEPERMISSION - // vs - // GROUPPROJECTPERMISSION) - { - // Build the group filter once for reuse - OrQueryFilter groupOrFilters = new OrQueryFilter(); - if (user != null) { - List logins = user.getLogins(); - for (AuthProvider login : logins) { - AccessToken accessToken = user.getAccessToken(login); - Collection userGroups = accessToken.getUserGroups(); - String userGroupType = accessToken.getUserGroupType(); - Collection userCustomGroups = AdminSecurityGroupUtils.getUserCustomGroups(accessToken); - if (!userCustomGroups.isEmpty()) { - AndQueryFilter customAndFilter = new AndQueryFilter(); - customAndFilter.addFilter( - SimpleQueryFilter.makeColToValFilter("GROUPENGINEPERMISSION__TYPE", "==", "CUSTOM")); - customAndFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPENGINEPERMISSION__ID", - "==", userCustomGroups)); - groupOrFilters.addFilter(customAndFilter); - } - if (!userGroups.isEmpty()) { - AndQueryFilter andFilter = new AndQueryFilter(); - andFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPENGINEPERMISSION__TYPE", "==", - userGroupType)); - andFilter.addFilter( - SimpleQueryFilter.makeColToValFilter("GROUPENGINEPERMISSION__ID", "==", userGroups)); - groupOrFilters.addFilter(andFilter); - } - } - } - - // ENGINE group permissions sub-query - SelectQueryStruct engineGroupPermQs = new SelectQueryStruct(); - engineGroupPermQs.addSelector(new QueryColumnSelector("GROUPENGINEPERMISSION__ENGINEID", "ENGINEID")); - engineGroupPermQs.addSelector(QueryFunctionSelector.makeFunctionSelector(QueryFunctionHelper.MIN, - "GROUPENGINEPERMISSION__PERMISSION", "PERMISSION")); - engineGroupPermQs.addGroupBy(new QueryColumnSelector("GROUPENGINEPERMISSION__ENGINEID")); - if (!groupOrFilters.isEmpty()) { - engineGroupPermQs.addExplicitFilter(groupOrFilters); - } else { - AndQueryFilter nullFilter = new AndQueryFilter(); - nullFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPENGINEPERMISSION__TYPE", "==", null)); - nullFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPENGINEPERMISSION__ID", "==", null)); - engineGroupPermQs.addExplicitFilter(nullFilter); - } - - SubqueryRelationship engineGroupPermRel = new SubqueryRelationship(engineGroupPermQs, "EGP", - "left.outer.join", new String[] { "EGP__ENGINEID", "ENGINE__ENGINEID", "=" }); - qs.addRelation(engineGroupPermRel); - - // PROJECT group permissions sub-query - OrQueryFilter groupProjectOrFilters = new OrQueryFilter(); - if (user != null) { - List logins = user.getLogins(); - for (AuthProvider login : logins) { - AccessToken accessToken = user.getAccessToken(login); - Collection userGroups = accessToken.getUserGroups(); - String userGroupType = accessToken.getUserGroupType(); - Collection userCustomGroups = AdminSecurityGroupUtils.getUserCustomGroups(accessToken); - if (!userCustomGroups.isEmpty()) { - AndQueryFilter customAndFilter = new AndQueryFilter(); - customAndFilter.addFilter( - SimpleQueryFilter.makeColToValFilter("GROUPPROJECTPERMISSION__TYPE", "==", "CUSTOM")); - customAndFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPPROJECTPERMISSION__ID", - "==", userCustomGroups)); - groupProjectOrFilters.addFilter(customAndFilter); - } - if (!userGroups.isEmpty()) { - AndQueryFilter andFilter = new AndQueryFilter(); - andFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPPROJECTPERMISSION__TYPE", "==", - userGroupType)); - andFilter.addFilter( - SimpleQueryFilter.makeColToValFilter("GROUPPROJECTPERMISSION__ID", "==", userGroups)); - groupProjectOrFilters.addFilter(andFilter); - } - } - } - - SelectQueryStruct projectGroupPermQs = new SelectQueryStruct(); - projectGroupPermQs.addSelector(new QueryColumnSelector("GROUPPROJECTPERMISSION__PROJECTID", "PROJECTID")); - projectGroupPermQs.addSelector(QueryFunctionSelector.makeFunctionSelector(QueryFunctionHelper.MIN, - "GROUPPROJECTPERMISSION__PERMISSION", "PERMISSION")); - projectGroupPermQs.addGroupBy(new QueryColumnSelector("GROUPPROJECTPERMISSION__PROJECTID")); - if (!groupProjectOrFilters.isEmpty()) { - projectGroupPermQs.addExplicitFilter(groupProjectOrFilters); - } else { - AndQueryFilter nullFilter = new AndQueryFilter(); - nullFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPPROJECTPERMISSION__TYPE", "==", null)); - nullFilter.addFilter(SimpleQueryFilter.makeColToValFilter("GROUPPROJECTPERMISSION__ID", "==", null)); - projectGroupPermQs.addExplicitFilter(nullFilter); - } - - SubqueryRelationship projectGroupPermRel = new SubqueryRelationship(projectGroupPermQs, "PGP", - "left.outer.join", new String[] { "PGP__PROJECTID", "PROJECT__PROJECTID", "=" }); - qs.addRelation(projectGroupPermRel); - - // Use conditional selector for group permission based on engine type - QueryIfSelector groupPermissionSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PGP__PERMISSION"), new QueryColumnSelector("EGP__PERMISSION"), - "group_permission"); - qs.addSelector(groupPermissionSelector); - } - - // ACCESS REQUEST sub-query - conditional based on type (ENGINEACCESSREQUEST vs - // PROJECTACCESSREQUEST) - { - // ENGINE access requests sub-query - SelectQueryStruct engineAccReqQs = new SelectQueryStruct(); - engineAccReqQs.addSelector(new QueryColumnSelector("ENGINEACCESSREQUEST__PERMISSION", "PERMISSION")); - engineAccReqQs.addSelector(new QueryColumnSelector("ENGINEACCESSREQUEST__ENGINEID", "ENGINEID")); - engineAccReqQs.addRelation("ENGINEACCESSREQUEST__ENGINEID", "ENGINE__ENGINEID", "inner.join"); - engineAccReqQs.addExplicitFilter( - SimpleQueryFilter.makeColToValFilter("ENGINEACCESSREQUEST__REQUEST_USERID", "==", userId)); - engineAccReqQs.addExplicitFilter(SimpleQueryFilter - .makeColToValFilter("ENGINEACCESSREQUEST__APPROVER_DECISION", "==", "NEW_REQUEST")); - - SubqueryRelationship engineAReqRel = new SubqueryRelationship(engineAccReqQs, "EAR", "left.outer.join", - new String[] { "EAR__ENGINEID", "ENGINE__ENGINEID", "=" }); - qs.addRelation(engineAReqRel); - - // PROJECT access requests sub-query - SelectQueryStruct projectAccReqQs = new SelectQueryStruct(); - projectAccReqQs.addSelector(new QueryColumnSelector("PROJECTACCESSREQUEST__PERMISSION", "PERMISSION")); - projectAccReqQs.addSelector(new QueryColumnSelector("PROJECTACCESSREQUEST__PROJECTID", "PROJECTID")); - projectAccReqQs.addRelation("PROJECTACCESSREQUEST__PROJECTID", "PROJECT__PROJECTID", "inner.join"); - projectAccReqQs.addExplicitFilter( - SimpleQueryFilter.makeColToValFilter("PROJECTACCESSREQUEST__REQUEST_USERID", "==", userId)); - projectAccReqQs.addExplicitFilter(SimpleQueryFilter - .makeColToValFilter("PROJECTACCESSREQUEST__APPROVER_DECISION", "==", "NEW_REQUEST")); - - SubqueryRelationship projectAReqRel = new SubqueryRelationship(projectAccReqQs, "PAR", "left.outer.join", - new String[] { "PAR__PROJECTID", "PROJECT__PROJECTID", "=" }); - qs.addRelation(projectAReqRel); - - // Use conditional selector for access permission - QueryIfSelector accessPermissionSelector = QueryIfSelector.makeQueryIfSelector( - SimpleQueryFilter.makeColToValFilter("PROJECTDEPENDENCIES__ENGINETYPE", "==", "PROJECT"), - new QueryColumnSelector("PAR__PERMISSION"), new QueryColumnSelector("EAR__PERMISSION"), - "access_permission"); - qs.addSelector(accessPermissionSelector); - } - - return QueryExecutionUtility.flushRsToMap(securityDb, qs); - } - - /** - * Gives a person the requested access to the engines and projects a project - * depends on, or asks their owners for it. On a model, a person added gets no - * usage limit, and a person whose access changes keeps theirs. - * - * @param requester the user asking - * @param projectId the project - * @param newUserId the person - * @param newUserType the person's login type - * @param requestedPermission the level, by name - * @param endDate when the access ends, or null - * @return the engines and projects by what was done for each - */ - public static Map propagateProjectPermission(User requester, String projectId, String newUserId, - String newUserType, String requestedPermission, String endDate) { - return propagate(requester, projectId, newUserId, newUserType, requestedPermission, endDate, null); - } - - /** - * Gives a person the requested access to the engines and projects a project - * depends on, or asks their owners for it. Only a model's owners set a limit - * that differs from the current one. - * - * @param requester the user asking - * @param projectId the project - * @param newUserId the person - * @param newUserType the person's login type - * @param requestedPermission the level, by name - * @param endDate when the access ends, or null - * @param usageLimit the person's model usage limit on each model given - * or changed, or null for no limit defined - * @return the engines and projects by what was done for each - */ - public static Map propagateProjectPermission(User requester, String projectId, String newUserId, - String newUserType, String requestedPermission, String endDate, ModelUsageLimit usageLimit) { - return propagate(requester, projectId, newUserId, newUserType, requestedPermission, endDate, - new PermissionGrant().withUsageLimit(usageLimit)); - } - - /** - * Whether only admins can give people access to an engine or project a project - * depends on. A dependency whose setting cannot be read counts as admin-only. - * - * @param isEngine whether the dependency is an engine rather than a project - * @param id the dependency's id - * @return whether its admin-only add setting is on - */ - private static boolean dependencyAddsAreAdminOnly(boolean isEngine, String id) { - try { - return isEngine ? adminOnlyEngineAddAccess(id) : adminOnlyProjectAddAccess(id); - } catch (IllegalArgumentException e) { - classLogger.warn("Could not read the admin-only add setting of {}", id, e); - return true; - } - } - - /** - * Does the work of both propagateProjectPermission methods: for each engine and - * project the project depends on, it gives the person the requested level, or - * files an access request for its owners when the requester is Read-Only or has - * no access there. - * - * @param limit the person's model usage limit on the models: a grant that gives - * {@code usageLimit} - * ({@link PermissionGrant#isUsageLimitGiven()}), or null for none, - * so a person whose access changes keeps theirs - */ - private static Map propagate(User requester, String projectId, String newUserId, String newUserType, - String requestedPermission, String endDate, PermissionGrant limit) { - Map ret = new HashMap(); - - // get the requested permission as a numeric -- it was passed as a string - Integer requestedPermissionNumeric = AccessPermissionEnum.getIdByPermission(requestedPermission); - boolean requesterIsAdmin = SecurityAdminUtils.userIsAdmin(requester); - - List alreadyHaveAccess = new ArrayList<>(); - List requestAlreadyExists = new ArrayList<>(); - List newRequestAdded = new ArrayList<>(); - List accessGranted = new ArrayList<>(); - List couldNotAddRequest = new ArrayList<>(); - - // loop through the dependencies and process request according to the - // requestor's permissions on each engine. - List> dependentEngines = SecurityProjectUtils.getProjectDependencies(projectId); - for (int i = 0; i < dependentEngines.size(); i++) { - Map dependentEngine = dependentEngines.get(i); - String dependentEngineId = (String) dependentEngine.get("engine_id"); - String dependentEngineType = (String) dependentEngine.get("engine_type"); - - Integer currentPendingUserPermission; - Integer requesterEnginePermission; - Integer currentNewUserPermission; - boolean isEngine = false; - // only a model has usage limits - PermissionGrant engineLimit = IEngine.CATALOG_TYPE.MODEL.name().equals(dependentEngineType) ? limit : null; - - if (dependentEngineType == null - || IEngine.CATALOG_TYPE.valueOf(dependentEngineType) != IEngine.CATALOG_TYPE.PROJECT) { - isEngine = true; - currentPendingUserPermission = SecurityEngineUtils.getUserAccessRequestEnginePermission(newUserId, - dependentEngineId); - requesterEnginePermission = SecurityEngineUtils - .getUserEnginePermission(User.getSingleLogginName(requester), dependentEngineId); - currentNewUserPermission = SecurityEngineUtils.getUserEnginePermission(newUserId, dependentEngineId); - } else { - currentPendingUserPermission = SecurityProjectUtils.getUserAccessRequestProjectPermission(newUserId, - dependentEngineId); - requesterEnginePermission = SecurityProjectUtils - .getUserProjectPermission(User.getSingleLogginName(requester), dependentEngineId); - currentNewUserPermission = SecurityProjectUtils.getUserProjectPermission(newUserId, dependentEngineId); - } - - // if newUser is requesting permission which he/she already has access, take no - // action - if (currentNewUserPermission == requestedPermissionNumeric) { - alreadyHaveAccess.add(dependentEngineId); - classLogger.info("User already has {} access to {}", requestedPermission, dependentEngineId); - // if newUser has already requested this access and it is still pending, take no - // action - } else if (currentPendingUserPermission != null - && requestedPermissionNumeric == currentPendingUserPermission) { - requestAlreadyExists.add(dependentEngineId); - classLogger.info("user has already requested {} access to {} and the request is pending.", - requestedPermission, dependentEngineId); - // if requester has insufficient privileges on the engine so forward request to - // engine owner - } else if (requesterEnginePermission == null || requesterEnginePermission == 3) { - try { - if (isEngine) { - SecurityEngineUtils.setUserAccessRequest(newUserId, newUserType, dependentEngineId, - "No Comment at this time", requestedPermissionNumeric, requester); - } else { - SecurityProjectUtils.setUserAccessRequest(newUserId, newUserType, dependentEngineId, - "No Comment at this time", requestedPermissionNumeric, requester); - } - newRequestAdded.add(dependentEngineId); - classLogger.info("User has forwarded {}'s request to the owner of engine {}", newUserId, - dependentEngineId); - } catch (Exception e) { - couldNotAddRequest.add(dependentEngineId); - classLogger.error("Failed to propagate project permissions to related artifacts", e); - } - // if the newUser has permissions on the engine but not to the level requested, - // edit the existing record - } else if (!requesterIsAdmin && dependencyAddsAreAdminOnly(isEngine, dependentEngineId)) { - // these grants skip the endpoints, so each dependency's own setting is checked - couldNotAddRequest.add(dependentEngineId); - classLogger.info("Only admins can give {} access to {}", newUserId, dependentEngineId); - } else if (requesterEnginePermission < 3 && currentNewUserPermission != null - && currentNewUserPermission > requestedPermissionNumeric) { - try { - if (isEngine) { - editDependentEngineUser(requester, newUserId, newUserType, dependentEngineId, - requestedPermission, endDate, engineLimit); - } else { - SecurityProjectUtils.editProjectUserPermission(requester, newUserId, newUserType, - dependentEngineId, requestedPermission, endDate); - } - - accessGranted.add(dependentEngineId); - classLogger.info("User has updated permission for {} to {}", newUserId, dependentEngineId); - } catch (IllegalAccessException | IllegalArgumentException e) { - couldNotAddRequest.add(dependentEngineId); - classLogger.error("Failed to propagate project permissions to related artifacts", e); - } - // if none of the above and requestor has proper permission, add user to the - // engine permission database - } else if (requesterEnginePermission < 3 && currentNewUserPermission == null) { - try { - if (isEngine) { - addDependentEngineUser(requester, newUserId, dependentEngineId, requestedPermission, endDate, - engineLimit); - } else { - SecurityProjectUtils.addProjectUser(requester, newUserId, dependentEngineId, - requestedPermission, endDate); - } - - accessGranted.add(dependentEngineId); - classLogger.info("User has added {} to {}", newUserId, dependentEngineId); - } catch (IllegalAccessException | IllegalArgumentException e) { - couldNotAddRequest.add(dependentEngineId); - classLogger.error("Failed to propagate project permissions to related artifacts", e); - } - } else { - couldNotAddRequest.add(dependentEngineId); - classLogger.info("User could not add or forward {}'s request for engine {}", newUserId, - dependentEngineId); - } - } - - ret.put("Successfully processed permission propagation", true); - ret.put("alreadyHaveAccess", alreadyHaveAccess); - ret.put("requestAlreadyExists", requestAlreadyExists); - ret.put("newRequestAdded", newRequestAdded); - ret.put("accessGranted", accessGranted); - ret.put("couldNotAddRequest", couldNotAddRequest); - return ret; - } - - /** - * Gives a person access to an engine a project depends on, with the usage limit - * given, or none. - * - * @param limit on a model, the limit the propagation gives; null for none - */ - private static void addDependentEngineUser(User requester, String newUserId, String engineId, String level, - String endDate, PermissionGrant limit) throws IllegalAccessException { - SecurityEngineUtils.addEngineUser(requester, newUserId, engineId, level, endDate, - limit == null ? null : limit.getUsageLimit()); - } - - /** - * Changes a person's access to an engine a project depends on. Their usage - * limit is kept unless one is given. - * - * @param limit on a model, the limit the propagation gives; null for none - */ - private static void editDependentEngineUser(User requester, String newUserId, String newUserType, String engineId, - String level, String endDate, PermissionGrant limit) throws IllegalAccessException { - if (limit != null && limit.isUsageLimitGiven()) { - SecurityEngineUtils.editEngineUserPermission(requester, newUserId, newUserType, engineId, level, endDate, - limit.getUsageLimit()); - } else { - SecurityEngineUtils.editEngineUserPermission(requester, newUserId, newUserType, engineId, level, endDate); - } - } - /* * Project Metadata */ diff --git a/src/prerna/auth/utils/reactors/admin/AdminExportProjectAppReactor.java b/src/prerna/auth/utils/reactors/admin/AdminExportProjectAppReactor.java index 04403dd8a3b..86c7c46cd67 100644 --- a/src/prerna/auth/utils/reactors/admin/AdminExportProjectAppReactor.java +++ b/src/prerna/auth/utils/reactors/admin/AdminExportProjectAppReactor.java @@ -39,6 +39,7 @@ import prerna.auth.User; import prerna.auth.utils.SecurityAdminUtils; +import prerna.auth.utils.SecurityCatalogDependencyUtils; import prerna.auth.utils.SecurityProjectUtils; import prerna.engine.api.IEngine; import prerna.engine.impl.SmssUtilities; @@ -137,7 +138,7 @@ public NounMetadata execute() { logger.info("Done zipping project metadata..."); logger.info("Grabbing project dependencies to write to temporary file to zip..."); - List> projectDependencies = SecurityProjectUtils.getProjectDependencyDetails(projectId, + List> projectDependencies = SecurityCatalogDependencyUtils.getDependencyDetails(projectId, false); ZipUtils.zipObjectToFile(zos, null, outputDir + "/" + projectName + IProject.DEPENDENCIES_FILE_SUFFIX, projectDependencies); diff --git a/src/prerna/auth/utils/reactors/admin/AdminExportProjectReactor.java b/src/prerna/auth/utils/reactors/admin/AdminExportProjectReactor.java index d8d92c0135b..1214e050a79 100644 --- a/src/prerna/auth/utils/reactors/admin/AdminExportProjectReactor.java +++ b/src/prerna/auth/utils/reactors/admin/AdminExportProjectReactor.java @@ -41,6 +41,7 @@ import prerna.auth.User; import prerna.auth.utils.SecurityAdminUtils; +import prerna.auth.utils.SecurityCatalogDependencyUtils; import prerna.auth.utils.SecurityProjectUtils; import prerna.cluster.util.ClusterUtil; import prerna.engine.api.IEngine; @@ -172,8 +173,8 @@ public NounMetadata execute() { logger.info("Done zipping project metadata..."); logger.info("Grabbing project dependencies to write to temporary file to zip..."); - List> projectDependencies = SecurityProjectUtils - .getProjectDependencyDetails(projectId, false); + List> projectDependencies = SecurityCatalogDependencyUtils + .getDependencyDetails(projectId, false); ZipUtils.zipObjectToFile(zos, projectNameAndId, outputDir + "/" + projectName + IProject.DEPENDENCIES_FILE_SUFFIX, projectDependencies); logger.info("Done zipping project dependencies..."); diff --git a/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/AbstractWorkspaceReactor.java b/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/AbstractWorkspaceReactor.java index 1295deeba4a..7e7be144cdf 100644 --- a/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/AbstractWorkspaceReactor.java +++ b/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/AbstractWorkspaceReactor.java @@ -38,6 +38,9 @@ import org.json.JSONArray; import org.json.JSONObject; +import prerna.auth.utils.CatalogTypes; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; import prerna.auth.User; import prerna.auth.utils.SecurityEngineUtils; import prerna.auth.utils.SecurityProjectUtils; @@ -604,7 +607,7 @@ private static void applyIntegerUpdates(JSONObject cfg, String subObjectKey, Map * *

* {@code existingDependencies} and {@code existingSkills} are the workspace's - * pre-existing attachments - ids already in {@code PROJECTDEPENDENCIES} and + * pre-existing attachments - ids already in {@code CATALOGDEPENDENCIES} and * skill ids already in {@code WORKSPACE_RESOURCE} respectively. They carry the * "existing attachment" escape hatch Edit uses: an id already attached passes * the permission check even if the caller has lost view rights since. Add @@ -613,7 +616,7 @@ private static void applyIntegerUpdates(JSONObject cfg, String subObjectKey, Map */ protected void validateWorkspaceInputs(User user, String workspaceId, Set existingDependencies, Set existingSkills, Set engines, Set projectDependencies, - List> dependencyList, List> workspaceResources, + List dependencyList, List> workspaceResources, Set skillIds) { boolean hasExistingDeps = existingDependencies != null; boolean hasExistingSkills = existingSkills != null; @@ -624,18 +627,23 @@ protected void validateWorkspaceInputs(User user, String workspaceId, Set dependencyEntry = new HashMap<>(); - dependencyEntry.put("ENGINEID", id); - dependencyEntry.put("ENGINETYPE", type); - dependencyList.add(dependencyEntry); + dependencyList.add(new Dependency(id, storedType)); } for (String engine : engines) { @@ -677,10 +685,7 @@ protected void validateWorkspaceInputs(User user, String workspaceId, Set skillDep = new HashMap<>(); - skillDep.put("ENGINEID", skillId); - skillDep.put("ENGINETYPE", CATALOG_TYPE.PROJECT.name()); - dependencyList.add(skillDep); + dependencyList.add(new Dependency(skillId, IProject.PROJECT_TYPE.SKILL.name())); } } diff --git a/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/AddWorkspaceReactor.java b/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/AddWorkspaceReactor.java index ac2aa18726a..45bab6d91a9 100644 --- a/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/AddWorkspaceReactor.java +++ b/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/AddWorkspaceReactor.java @@ -39,6 +39,9 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import prerna.auth.utils.CatalogTypes; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; import prerna.auth.User; import prerna.auth.utils.SecurityProjectUtils; import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils; @@ -91,7 +94,7 @@ public NounMetadata execute() { Set engines = new HashSet<>(); Set projectDependencies = new HashSet<>(); - List> dependencyList = new ArrayList<>(); + List dependencyList = new ArrayList<>(); List> workspaceResources = new ArrayList<>(); Set skillIds = new LinkedHashSet<>(); try { @@ -105,7 +108,8 @@ public NounMetadata execute() { try { workspaceProject = ProjectHelper.createWorkspaceProject(workspaceId, workspaceName, IProject.PROJECT_TYPE.WORKSPACE, false, null, null, user, logger); - SecurityProjectUtils.updateProjectDependencies(user, workspaceId, dependencyList); + SecurityCatalogDependencyUtils.setDependencies(user, workspaceId, IProject.PROJECT_TYPE.WORKSPACE.name(), + dependencyList); ModelInferenceLogsUtils.createNewWorkspaceEntry(workspaceId, user.getPrimaryLoginToken().getId(), workspaceName, workspaceDescription, workspaceSystemPrompt, workspaceResources); try { diff --git a/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/EditWorkspaceReactor.java b/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/EditWorkspaceReactor.java index 6b57e944550..74869053b15 100644 --- a/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/EditWorkspaceReactor.java +++ b/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/EditWorkspaceReactor.java @@ -39,6 +39,10 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import prerna.auth.utils.CatalogTypes; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; +import prerna.project.api.IProject; import prerna.auth.User; import prerna.auth.utils.SecurityProjectUtils; import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils; @@ -142,14 +146,14 @@ public NounMetadata execute() { } } - Set curDepList = SecurityProjectUtils.getProjectDependencies(workspaceId, false).stream() - .map(map -> (String) map.get("engine_id")).collect(Collectors.toSet()); + Set curDepList = SecurityCatalogDependencyUtils.getDependencies(workspaceId).stream() + .map(map -> (String) map.get("catalog_id")).collect(Collectors.toSet()); Set curSkillList = ModelInferenceLogsUtils.getWorkspaceResources(workspaceId, SKILL_RESOURCE_TYPE, null) .stream().map(map -> map.get("resource_id")).collect(Collectors.toSet()); Set engines = new HashSet<>(); Set projectDependencies = new HashSet<>(); - List> dependencyList = new ArrayList<>(); + List dependencyList = new ArrayList<>(); List> workspaceResources = new ArrayList<>(); Set skillIds = new LinkedHashSet<>(); Map budgetUpdates = new HashMap<>(); @@ -178,7 +182,8 @@ public NounMetadata execute() { return getError(e.getMessage()); } - SecurityProjectUtils.updateProjectDependencies(user, workspaceId, dependencyList); + SecurityCatalogDependencyUtils.setDependencies(user, workspaceId, IProject.PROJECT_TYPE.WORKSPACE.name(), + dependencyList); // Default/fallback model engine for the agent. Presence-detected so omitting // the key leaves any existing CONFIG_JSON.model_id untouched; passing it blank diff --git a/src/prerna/project/impl/ProjectHelper.java b/src/prerna/project/impl/ProjectHelper.java index 35e1e0cfde0..f07d0568926 100644 --- a/src/prerna/project/impl/ProjectHelper.java +++ b/src/prerna/project/impl/ProjectHelper.java @@ -62,6 +62,7 @@ import prerna.auth.AuthProvider; import prerna.auth.User; import prerna.auth.utils.AbstractSecurityUtils; +import prerna.auth.utils.CatalogTypes; import prerna.auth.utils.SecurityAdminUtils; import prerna.auth.utils.SecurityEngineUtils; import prerna.auth.utils.SecurityProjectUtils; @@ -677,7 +678,7 @@ public static Map extractEngineIdsFromProjectFolder(File project // extract engineIds from project including project_dependencies.json Map> uuidToFiles = ProjectHelper.countUuidsInProjectFolder(projectFolder); // process engineIds and set project dependencies - Map engineInfo = ProjectHelper.validateProjectDependencies(uuidToFiles.keySet()); + Map engineInfo = ProjectHelper.validateDependencyIds(uuidToFiles.keySet()); Map> successMap = (Map>) engineInfo.get("success"); Set failedSet = (Set) engineInfo.get("failed"); @@ -795,29 +796,30 @@ private static Map> countUuidsInProjectFolder(File f } /** - * Split ids into those in the engine table and those that are not. + * Split ids into the engines and projects in the security database and the + * rest. Reads the security database alone, so nothing is loaded or pulled. * * @param engineIds the ids to check - * @return a "success" map from engine id to its engineType and engineName, and - * a "failed" set of the ids that are not engines + * @return a "success" map from engine or project id to its engineType (its own + * engine type or project type) and engineName, and a "failed" set of + * the ids that are neither */ - private static Map validateProjectDependencies(Collection engineIds) { + private static Map validateDependencyIds(Collection engineIds) { Map> success = new HashMap<>(); Set failed = new HashSet<>(); for (String engineId : engineIds) { - if (SecurityEngineUtils.containsEngineId(engineId)) { - IEngine.CATALOG_TYPE engineType = SecurityEngineUtils.getEngineType(engineId); - String engineName = SecurityEngineUtils.getEngineAliasForId(engineId); - - Map engineInfo = new HashMap<>(); - engineInfo.put("engineType", engineType.toString()); - engineInfo.put("engineName", engineName); - - success.put(engineId, engineInfo); - } else { + String catalogType = CatalogTypes.resolve(engineId); + if (catalogType == null) { failed.add(engineId); + continue; } + String name = CatalogTypes.isProjectType(catalogType) ? SecurityProjectUtils.getProjectAliasForId(engineId) + : SecurityEngineUtils.getEngineAliasForId(engineId); + Map engineInfo = new HashMap<>(); + engineInfo.put("engineType", catalogType); + engineInfo.put("engineName", name); + success.put(engineId, engineInfo); } // build final result map to return diff --git a/src/prerna/reactor/agent/AppBuilderHarnessConfiguration.java b/src/prerna/reactor/agent/AppBuilderHarnessConfiguration.java index dac65e868c0..f49e7372102 100644 --- a/src/prerna/reactor/agent/AppBuilderHarnessConfiguration.java +++ b/src/prerna/reactor/agent/AppBuilderHarnessConfiguration.java @@ -42,6 +42,7 @@ import org.apache.logging.log4j.Logger; import org.json.JSONObject; +import prerna.auth.utils.SecurityCatalogDependencyUtils; import prerna.auth.utils.SecurityProjectUtils; import prerna.project.api.IProject; import prerna.util.EngineUtility; @@ -137,7 +138,7 @@ public static JSONObject getConfigForProject(String projectId) { /** * Builds the "Selected Engines" system prompt block for a project. Reads * the dependency list fresh from the canonical store - * ({@link prerna.auth.utils.SecurityProjectUtils#getProjectDependencyDetails}) + * ({@link prerna.auth.utils.SecurityCatalogDependencyUtils#getDependencyDetails(String)}) * so workbench selections are always current at run time, regardless of * which reactor last mutated them. * @@ -152,7 +153,7 @@ public static String buildSelectedEnginesPrompt(String projectId) { } List> dependencyList; try { - dependencyList = SecurityProjectUtils.getProjectDependencyDetails(projectId); + dependencyList = SecurityCatalogDependencyUtils.getDependencyDetails(projectId); } catch (Exception e) { logger.warn("Failed to load dependency details for selected-engines prompt, project: {}", projectId, e); @@ -174,13 +175,13 @@ private static Map>> bucketEnginesByType( if (dependencyList != null) { for (Map dep : dependencyList) { if (dep == null) continue; - Object idObj = dep.get("engine_id"); - Object typeObj = dep.get("engine_type"); + Object idObj = dep.get("catalog_id"); + Object typeObj = dep.get("catalog_type"); if (idObj == null || typeObj == null) continue; String id = String.valueOf(idObj); String typeKey = String.valueOf(typeObj).toLowerCase() + "_engines"; if (!enginesByType.containsKey(typeKey)) continue; // PROJECT or other - Object nameObj = dep.get("engine_name"); + Object nameObj = dep.get("catalog_name"); String name = nameObj != null ? String.valueOf(nameObj) : id; Map entry = new LinkedHashMap<>(); entry.put(ENGINE_NAME, name); diff --git a/src/prerna/reactor/agent/skill/AttachSkillToWorkspaceReactor.java b/src/prerna/reactor/agent/skill/AttachSkillToWorkspaceReactor.java index 02de17b1c11..f2dee53aef5 100644 --- a/src/prerna/reactor/agent/skill/AttachSkillToWorkspaceReactor.java +++ b/src/prerna/reactor/agent/skill/AttachSkillToWorkspaceReactor.java @@ -38,6 +38,8 @@ import com.github.f4b6a3.uuid.alt.GUID; import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.project.api.IProject; import prerna.auth.utils.SecurityProjectUtils; import prerna.engine.api.IEngine.CATALOG_TYPE; import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils; @@ -140,37 +142,18 @@ private NounMetadata attachSkill(User user, String workspaceId, String skillId) response.put("warning", "Skill attached but CONFIG_JSON sync failed: " + mirrorEx.getMessage()); } - // Mirror the attachment into PROJECTDEPENDENCIES so the skill shows up as a - // project dependency alongside MCP engines/projects. Bulk update via merge: - // read current deps, append the skill if not already present, rewrite. - // Best-effort - WORKSPACE_RESOURCE row is the source of truth. + // Mirror the attachment into CATALOGDEPENDENCIES so the skill shows up as a + // dependency of the workspace alongside MCP engines/projects; one already + // there is kept. Best-effort - WORKSPACE_RESOURCE row is the source of truth. try { - List> current = SecurityProjectUtils.getProjectDependencies(workspaceId, false); - List> merged = new ArrayList<>(); - boolean alreadyPresent = false; - for (Map row : current) { - String existingId = (String) row.get("engine_id"); - String existingType = (String) row.get("engine_type"); - Map entry = new HashMap<>(); - entry.put("ENGINEID", existingId); - entry.put("ENGINETYPE", existingType); - merged.add(entry); - if (skillId.equals(existingId)) { - alreadyPresent = true; - } - } - if (!alreadyPresent) { - Map skillDep = new HashMap<>(); - skillDep.put("ENGINEID", skillId); - skillDep.put("ENGINETYPE", CATALOG_TYPE.PROJECT.name()); - merged.add(skillDep); - SecurityProjectUtils.updateProjectDependencies(user, workspaceId, merged); - } + SecurityCatalogDependencyUtils.addDependencies(user, workspaceId, IProject.PROJECT_TYPE.WORKSPACE.name(), + List.of(new SecurityCatalogDependencyUtils.Dependency(skillId, + IProject.PROJECT_TYPE.SKILL.name()))); } catch (Exception depEx) { - classLogger.warn("Attached skill '{}' to workspace '{}' but failed to record PROJECTDEPENDENCIES entry", + classLogger.warn("Attached skill '{}' to workspace '{}' but failed to record CATALOGDEPENDENCIES entry", skillId, workspaceId, depEx); response.put("dependency_warning", - "Skill attached but PROJECTDEPENDENCIES sync failed: " + depEx.getMessage()); + "Skill attached but CATALOGDEPENDENCIES sync failed: " + depEx.getMessage()); } UserAuditTrailUtils.recordResourceEvent(user, AuditEventType.SKILL_ATTACH, AuditTargetType.SKILL, skillId, diff --git a/src/prerna/reactor/agent/skill/DetachSkillFromWorkspaceReactor.java b/src/prerna/reactor/agent/skill/DetachSkillFromWorkspaceReactor.java index 0779d4fa23d..e456e9e04f2 100644 --- a/src/prerna/reactor/agent/skill/DetachSkillFromWorkspaceReactor.java +++ b/src/prerna/reactor/agent/skill/DetachSkillFromWorkspaceReactor.java @@ -34,6 +34,7 @@ import org.apache.logging.log4j.Logger; import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils; import prerna.auth.utils.SecurityProjectUtils; import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils; import prerna.engine.impl.model.inferencetracking.reactors.workspaces.AbstractWorkspaceReactor; @@ -52,7 +53,7 @@ * Detaches a skill from a workspace. Mirrors * {@link AttachSkillToWorkspaceReactor}: removes the * {@code WORKSPACE_RESOURCE__} row, the matching {@code CONFIG_JSON.skills[]} - * entry, and the {@code PROJECTDEPENDENCIES} entry. + * entry, and the {@code CATALOGDEPENDENCIES} entry. * *

* No-op when the attachment does not exist. Does not delete the skill itself; @@ -120,13 +121,13 @@ public NounMetadata execute() { if (deleted > 0) { try { - SecurityProjectUtils.removeProjectDependency(user, workspaceId, skillId); + SecurityCatalogDependencyUtils.removeDependency(user, workspaceId, skillId); } catch (Exception depEx) { classLogger.warn( - "Detached skill '{}' from workspace '{}' but failed to remove PROJECTDEPENDENCIES entry", + "Detached skill '{}' from workspace '{}' but failed to remove CATALOGDEPENDENCIES entry", skillId, workspaceId, depEx); response.put("dependency_warning", - "Skill detached but PROJECTDEPENDENCIES sync failed: " + depEx.getMessage()); + "Skill detached but CATALOGDEPENDENCIES sync failed: " + depEx.getMessage()); } UserAuditTrailUtils.recordResourceEvent(user, AuditEventType.SKILL_DETACH, AuditTargetType.SKILL, skillId, null, workspaceId, null, null, Map.of("workspaceId", workspaceId)); diff --git a/src/prerna/reactor/project/CreateAppFromTemplateReactor.java b/src/prerna/reactor/project/CreateAppFromTemplateReactor.java index 4c6c4e86236..abe39b42eb1 100644 --- a/src/prerna/reactor/project/CreateAppFromTemplateReactor.java +++ b/src/prerna/reactor/project/CreateAppFromTemplateReactor.java @@ -1,264 +1,265 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.project; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Stream; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.json.JSONObject; - -import prerna.auth.User; -import prerna.auth.utils.SecurityProjectUtils; -import prerna.cluster.util.ClusterUtil; -import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils; -import prerna.project.api.IProject; -import prerna.project.impl.ProjectHelper; -import prerna.reactor.AbstractReactor; -import prerna.reactor.ReactorDefinition; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.PixelOperationType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.usertracking.AuditEventType; -import prerna.usertracking.UserAuditTrailUtils; -import prerna.util.AssetUtility; -import prerna.util.UploadUtilities; -import prerna.util.Utility; - -public class CreateAppFromTemplateReactor extends AbstractReactor { - - private static final Logger classLogger = LogManager.getLogger(CreateAppFromTemplateReactor.class); - - private static final String CLASS_NAME = CreateAppFromTemplateReactor.class.getName(); - - // PROJECTMETA tag marking a project as platform-managed; - // never copied onto a clone - private static final String SYSTEM_TAG = "SYSTEM"; - - /* - * This class is used to construct a new project using an existing project as a - * template. It can be considered a deep copy in that all insights from the - * template are also copied to the new project - */ - - public CreateAppFromTemplateReactor() { - this.keysToGet = new String[] { ReactorKeysEnum.CATALOG_NAME.getKey() + "," + ReactorKeysEnum.PROJECT.getKey(), - ReactorKeysEnum.PROJECT_TEMPLATE.getKey(), - ReactorKeysEnum.GLOBAL.getKey(), ReactorKeysEnum.PROVIDER.getKey(), ReactorKeysEnum.URL.getKey() }; - } - - @Override - public NounMetadata execute() { - Logger logger = getLogger(CLASS_NAME); - - organizeKeys(); - int index = 1; - String newProjectName = this.keyValue.get(ReactorKeysEnum.CATALOG_NAME.getKey()); - String projectTemplateId = this.keyValue.get(this.keysToGet[index++]); - boolean global = Boolean.parseBoolean(this.keyValue.get(this.keysToGet[index++]) + ""); - String gitProvider = this.keyValue.get(this.keysToGet[index++]); - String gitCloneUrl = this.keyValue.get(this.keysToGet[index++]); - - // make sure valid id for user - if (!SecurityProjectUtils.userCanViewProject(this.insight.getUser(), projectTemplateId)) { - // you dont have access - throw new IllegalArgumentException( - "The template you are attempting to use does not exist or user does not have access to the project"); - } - // Instantiate an object using the projectTemplate - IProject templateProject = Utility.getProject(projectTemplateId); - - // Use the template to populate the parameters needed to create the new project - IProject.PROJECT_TYPE projectEnumType = templateProject.getProjectType(); - if (!SecurityProjectUtils.userCanCloneProject(this.insight.getUser(), projectTemplateId)) { - throw new IllegalArgumentException("This project is not a template, so only its owners can clone it."); - } - if (SecurityProjectUtils.isDigitalTwin(projectTemplateId)) { - // the clone would be an ordinary project holding every file of the twin - throw new IllegalArgumentException("A Digital Twin cannot be cloned."); - } - - // Create new project - IProject newProject = ProjectHelper.generateNewProject(newProjectName, projectEnumType, global, gitProvider, - gitCloneUrl, this.insight.getUser(), logger); - - String templateProjectVersionFolder = AssetUtility.getProjectVersionFolder(templateProject.getProjectName(), - projectTemplateId); - String newProjectVersionFolder = AssetUtility.getProjectVersionFolder(newProjectName, - newProject.getProjectId()); - - // now we just need to move over the files for assets - String templateProjectAssetFolder = AssetUtility.getProjectAssetsFolder(projectTemplateId); - String newProjectAssetFolder = AssetUtility.getProjectAssetsFolder(newProject.getProjectId()); - - Path sourceDir = Paths.get(templateProjectAssetFolder); - Path destinationDir = Paths.get(newProjectAssetFolder); - - try { - try (Stream stream = Files.walk(sourceDir)) { - stream.forEach(sourcePath -> { - try { - Path targetPath = destinationDir.resolve(sourceDir.relativize(sourcePath)); - if (sourcePath.toFile().isFile()) { - targetPath.toFile().getParentFile().mkdirs(); - Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); - } - } catch (IOException ex) { - classLogger.error("Failed to copy project template assets: {}", ex.getMessage(), ex); - } - }); - } - - // also see for image - File templateImage = new File(templateProjectVersionFolder, "image.png"); - if (templateImage.exists()) { - Files.copy(templateImage.toPath(), new File(newProjectVersionFolder, "image.png").toPath(), - java.nio.file.StandardCopyOption.REPLACE_EXISTING); - } - - if (ClusterUtil.IS_CLUSTER) { - logger.info("Syncing project for cloud backup"); - ClusterUtil.pushProjectFolder(newProject, newProjectVersionFolder); - } - } catch (IOException e) { - classLogger.error("Failed to copy project template assets: {}", e.getMessage(), e); - throw new IllegalArgumentException( - "New project was created but could not transfer over the assets from the template. Errror = " - + e.getMessage()); - } - - if (IProject.PROJECT_TYPE.WORKSPACE == projectEnumType) { - try { - User user = this.insight.getUser(); - String newProjectId = newProject.getProjectId(); - - Map sourceEntry = ModelInferenceLogsUtils.getWorkspaceEntry(projectTemplateId); - String sourceDescription = sourceEntry != null ? (String) sourceEntry.get("description") : null; - String sourceSystemPrompt = sourceEntry != null ? (String) sourceEntry.get("system_prompt") : null; - JSONObject sourceConfigJson = ModelInferenceLogsUtils.getWorkspaceConfigJson(projectTemplateId); - List> sourceResources = ModelInferenceLogsUtils - .getWorkspaceResourcesByType(projectTemplateId, null); - - List> clonedResources = new ArrayList<>(); - List> dependencyList = new ArrayList<>(); - if (sourceResources != null) { - for (Map r : sourceResources) { - String resourceId = (String) r.get("resource_id"); - String resourceType = (String) r.get("resource_type"); - String resourceSubtype = (String) r.get("resource_subtype"); - Map entry = new HashMap<>(); - entry.put("workspace_resource_id", UUID.randomUUID().toString()); - entry.put("workspace_id", newProjectId); - entry.put("resource_id", resourceId); - entry.put("resource_type", resourceType); - entry.put("resource_subtype", resourceSubtype); - clonedResources.add(entry); - Map dep = new HashMap<>(); - dep.put("ENGINEID", resourceId); - dep.put("ENGINETYPE", resourceType); - dependencyList.add(dep); - } - } - - SecurityProjectUtils.updateProjectDependencies(user, newProjectId, dependencyList); - ModelInferenceLogsUtils.createNewWorkspaceEntry(newProjectId, user.getPrimaryLoginToken().getId(), - newProjectName, sourceDescription, sourceSystemPrompt, clonedResources); - if (sourceConfigJson != null) { - ModelInferenceLogsUtils.updateWorkspaceConfigJson(newProjectId, sourceConfigJson); - } - - Map sourceTagMeta = SecurityProjectUtils.getAggregateProjectMetadata(projectTemplateId, - Arrays.asList("tag"), false); - Object sourceTagValue = sourceTagMeta.get("tag"); - List sourceTags = new ArrayList<>(); - if (sourceTagValue instanceof List) { - sourceTags.addAll((List) sourceTagValue); - } else if (sourceTagValue != null) { - sourceTags.add(sourceTagValue); - } - List clonedTags = new ArrayList<>(); - for (Object tag : sourceTags) { - if (tag != null && !SYSTEM_TAG.equalsIgnoreCase(tag.toString())) { - clonedTags.add(tag); - } - } - if (!clonedTags.isEmpty()) { - Map tagUpdate = new HashMap<>(); - tagUpdate.put("tag", clonedTags); - SecurityProjectUtils.updateProjectMetadata(newProjectId, tagUpdate); - } - } catch (Exception e) { - classLogger.error( - "Failed to clone workspace inference log entry from template '{}' to new project '{}'.", - projectTemplateId, newProject.getProjectId(), e); - try { - newProject.delete(); - } catch (Exception rollbackEx) { - classLogger.error("Failed to roll back project '{}' after workspace entry clone failure.", - newProject.getProjectId(), rollbackEx); - } - throw new IllegalArgumentException( - "Failed to create workspace configuration for cloned agent: " + e.getMessage(), e); - } - } - - Map retMap = UploadUtilities.getProjectReturnData(this.insight.getUser(), - newProject.getProjectId()); - UserAuditTrailUtils.recordProjectLifecycle(this.insight.getUser(), AuditEventType.PROJECT_CREATE, - newProject.getProjectId(), newProjectName, - Map.of("projectType", projectEnumType.name(), "global", global, "creationMethod", "TEMPLATE")); - return new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, PixelOperationType.MARKET_PLACE_ADDITION); - } - - @Override - public ReactorDefinition getReactorDefinition() { - return super.getReactorDefinition().description( - "Creates a new project with the given name as a copy of a template project the user can clone, copying its asset files and image and, for a workspace, its configuration, resources and tags. Returns the new project's details.") - .key(ReactorKeysEnum.GLOBAL, key -> key.type(Boolean.class)) - .key(ReactorKeysEnum.CATALOG_NAME, - "The name for this project. Note: the project ID is randomly generated and is not passed into this method") - .key("projectTemplate", "The id of the existing project that is serving as the template for the copy") - .key(ReactorKeysEnum.PROVIDER, - "The GIT provider - user must be logged in with this provider for credentials") - .key(ReactorKeysEnum.URL, "The GIT repository URL to clone for this project"); - } - -} +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.project; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Stream; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.json.JSONObject; + +import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.auth.utils.SecurityProjectUtils; +import prerna.cluster.util.ClusterUtil; +import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils; +import prerna.project.api.IProject; +import prerna.project.impl.ProjectHelper; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.PixelOperationType; +import prerna.sablecc2.om.ReactorKeysEnum; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.usertracking.AuditEventType; +import prerna.usertracking.UserAuditTrailUtils; +import prerna.util.AssetUtility; +import prerna.util.UploadUtilities; +import prerna.util.Utility; + +public class CreateAppFromTemplateReactor extends AbstractReactor { + + private static final Logger classLogger = LogManager.getLogger(CreateAppFromTemplateReactor.class); + + private static final String CLASS_NAME = CreateAppFromTemplateReactor.class.getName(); + + // PROJECTMETA tag marking a project as platform-managed; + // never copied onto a clone + private static final String SYSTEM_TAG = "SYSTEM"; + + /* + * This class is used to construct a new project using an existing project as a + * template. It can be considered a deep copy in that all insights from the + * template are also copied to the new project + */ + + public CreateAppFromTemplateReactor() { + this.keysToGet = new String[] { ReactorKeysEnum.CATALOG_NAME.getKey() + "," + ReactorKeysEnum.PROJECT.getKey(), + ReactorKeysEnum.PROJECT_TEMPLATE.getKey(), + ReactorKeysEnum.GLOBAL.getKey(), ReactorKeysEnum.PROVIDER.getKey(), ReactorKeysEnum.URL.getKey() }; + } + + @Override + public NounMetadata execute() { + Logger logger = getLogger(CLASS_NAME); + + organizeKeys(); + int index = 1; + String newProjectName = this.keyValue.get(ReactorKeysEnum.CATALOG_NAME.getKey()); + String projectTemplateId = this.keyValue.get(this.keysToGet[index++]); + boolean global = Boolean.parseBoolean(this.keyValue.get(this.keysToGet[index++]) + ""); + String gitProvider = this.keyValue.get(this.keysToGet[index++]); + String gitCloneUrl = this.keyValue.get(this.keysToGet[index++]); + + // make sure valid id for user + if (!SecurityProjectUtils.userCanViewProject(this.insight.getUser(), projectTemplateId)) { + // you dont have access + throw new IllegalArgumentException( + "The template you are attempting to use does not exist or user does not have access to the project"); + } + // Instantiate an object using the projectTemplate + IProject templateProject = Utility.getProject(projectTemplateId); + + // Use the template to populate the parameters needed to create the new project + IProject.PROJECT_TYPE projectEnumType = templateProject.getProjectType(); + if (!SecurityProjectUtils.userCanCloneProject(this.insight.getUser(), projectTemplateId)) { + throw new IllegalArgumentException("This project is not a template, so only its owners can clone it."); + } + if (SecurityProjectUtils.isDigitalTwin(projectTemplateId)) { + // the clone would be an ordinary project holding every file of the twin + throw new IllegalArgumentException("A Digital Twin cannot be cloned."); + } + + // Create new project + IProject newProject = ProjectHelper.generateNewProject(newProjectName, projectEnumType, global, gitProvider, + gitCloneUrl, this.insight.getUser(), logger); + + String templateProjectVersionFolder = AssetUtility.getProjectVersionFolder(templateProject.getProjectName(), + projectTemplateId); + String newProjectVersionFolder = AssetUtility.getProjectVersionFolder(newProjectName, + newProject.getProjectId()); + + // now we just need to move over the files for assets + String templateProjectAssetFolder = AssetUtility.getProjectAssetsFolder(projectTemplateId); + String newProjectAssetFolder = AssetUtility.getProjectAssetsFolder(newProject.getProjectId()); + + Path sourceDir = Paths.get(templateProjectAssetFolder); + Path destinationDir = Paths.get(newProjectAssetFolder); + + try { + try (Stream stream = Files.walk(sourceDir)) { + stream.forEach(sourcePath -> { + try { + Path targetPath = destinationDir.resolve(sourceDir.relativize(sourcePath)); + if (sourcePath.toFile().isFile()) { + targetPath.toFile().getParentFile().mkdirs(); + Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING); + } + } catch (IOException ex) { + classLogger.error("Failed to copy project template assets: {}", ex.getMessage(), ex); + } + }); + } + + // also see for image + File templateImage = new File(templateProjectVersionFolder, "image.png"); + if (templateImage.exists()) { + Files.copy(templateImage.toPath(), new File(newProjectVersionFolder, "image.png").toPath(), + java.nio.file.StandardCopyOption.REPLACE_EXISTING); + } + + if (ClusterUtil.IS_CLUSTER) { + logger.info("Syncing project for cloud backup"); + ClusterUtil.pushProjectFolder(newProject, newProjectVersionFolder); + } + } catch (IOException e) { + classLogger.error("Failed to copy project template assets: {}", e.getMessage(), e); + throw new IllegalArgumentException( + "New project was created but could not transfer over the assets from the template. Errror = " + + e.getMessage()); + } + + if (IProject.PROJECT_TYPE.WORKSPACE == projectEnumType) { + try { + User user = this.insight.getUser(); + String newProjectId = newProject.getProjectId(); + + Map sourceEntry = ModelInferenceLogsUtils.getWorkspaceEntry(projectTemplateId); + String sourceDescription = sourceEntry != null ? (String) sourceEntry.get("description") : null; + String sourceSystemPrompt = sourceEntry != null ? (String) sourceEntry.get("system_prompt") : null; + JSONObject sourceConfigJson = ModelInferenceLogsUtils.getWorkspaceConfigJson(projectTemplateId); + List> sourceResources = ModelInferenceLogsUtils + .getWorkspaceResourcesByType(projectTemplateId, null); + + List> clonedResources = new ArrayList<>(); + List dependencyIds = new ArrayList<>(); + if (sourceResources != null) { + for (Map r : sourceResources) { + String resourceId = (String) r.get("resource_id"); + String resourceType = (String) r.get("resource_type"); + String resourceSubtype = (String) r.get("resource_subtype"); + Map entry = new HashMap<>(); + entry.put("workspace_resource_id", UUID.randomUUID().toString()); + entry.put("workspace_id", newProjectId); + entry.put("resource_id", resourceId); + entry.put("resource_type", resourceType); + entry.put("resource_subtype", resourceSubtype); + clonedResources.add(entry); + dependencyIds.add(resourceId); + } + } + + // each resource is kept with its own engine type or project type, read from + // the security database + SecurityCatalogDependencyUtils.setDependencyIds(user, newProjectId, + SecurityCatalogDependencyUtils.resolveCatalogType(newProjectId, null), dependencyIds); + ModelInferenceLogsUtils.createNewWorkspaceEntry(newProjectId, user.getPrimaryLoginToken().getId(), + newProjectName, sourceDescription, sourceSystemPrompt, clonedResources); + if (sourceConfigJson != null) { + ModelInferenceLogsUtils.updateWorkspaceConfigJson(newProjectId, sourceConfigJson); + } + + Map sourceTagMeta = SecurityProjectUtils.getAggregateProjectMetadata(projectTemplateId, + Arrays.asList("tag"), false); + Object sourceTagValue = sourceTagMeta.get("tag"); + List sourceTags = new ArrayList<>(); + if (sourceTagValue instanceof List) { + sourceTags.addAll((List) sourceTagValue); + } else if (sourceTagValue != null) { + sourceTags.add(sourceTagValue); + } + List clonedTags = new ArrayList<>(); + for (Object tag : sourceTags) { + if (tag != null && !SYSTEM_TAG.equalsIgnoreCase(tag.toString())) { + clonedTags.add(tag); + } + } + if (!clonedTags.isEmpty()) { + Map tagUpdate = new HashMap<>(); + tagUpdate.put("tag", clonedTags); + SecurityProjectUtils.updateProjectMetadata(newProjectId, tagUpdate); + } + } catch (Exception e) { + classLogger.error( + "Failed to clone workspace inference log entry from template '{}' to new project '{}'.", + projectTemplateId, newProject.getProjectId(), e); + try { + newProject.delete(); + } catch (Exception rollbackEx) { + classLogger.error("Failed to roll back project '{}' after workspace entry clone failure.", + newProject.getProjectId(), rollbackEx); + } + throw new IllegalArgumentException( + "Failed to create workspace configuration for cloned agent: " + e.getMessage(), e); + } + } + + Map retMap = UploadUtilities.getProjectReturnData(this.insight.getUser(), + newProject.getProjectId()); + UserAuditTrailUtils.recordProjectLifecycle(this.insight.getUser(), AuditEventType.PROJECT_CREATE, + newProject.getProjectId(), newProjectName, + Map.of("projectType", projectEnumType.name(), "global", global, "creationMethod", "TEMPLATE")); + return new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, PixelOperationType.MARKET_PLACE_ADDITION); + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition().description( + "Creates a new project with the given name as a copy of a template project the user can clone, copying its asset files and image and, for a workspace, its configuration, resources and tags. Returns the new project's details.") + .key(ReactorKeysEnum.GLOBAL, key -> key.type(Boolean.class)) + .key(ReactorKeysEnum.CATALOG_NAME, + "The name for this project. Note: the project ID is randomly generated and is not passed into this method") + .key("projectTemplate", "The id of the existing project that is serving as the template for the copy") + .key(ReactorKeysEnum.PROVIDER, + "The GIT provider - user must be logged in with this provider for credentials") + .key(ReactorKeysEnum.URL, "The GIT repository URL to clone for this project"); + } + +} diff --git a/src/prerna/reactor/project/ExtractAndSetDependenciesReactor.java b/src/prerna/reactor/project/ExtractAndSetDependenciesReactor.java index 40435f83698..f10f53df0c5 100644 --- a/src/prerna/reactor/project/ExtractAndSetDependenciesReactor.java +++ b/src/prerna/reactor/project/ExtractAndSetDependenciesReactor.java @@ -32,6 +32,7 @@ import java.util.Map; import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils; import prerna.auth.utils.SecurityProjectUtils; import prerna.engine.api.IEngine; import prerna.project.api.IProject; @@ -90,7 +91,8 @@ public NounMetadata execute() { // update the project dependencies table only with valid engineIds if (engineIdMap.containsKey("success")) { Map successMap = (Map) engineIdMap.get("success"); - SecurityProjectUtils.updateProjectDependenciesWithoutType(user, projectId, successMap.keySet()); + SecurityCatalogDependencyUtils.setDependencyIds(user, projectId, + SecurityCatalogDependencyUtils.resolveCatalogType(projectId, null), successMap.keySet()); } // sending the success and failed list of engineIds to FE diff --git a/src/prerna/reactor/project/SaveAppBlocksJsonReactor.java b/src/prerna/reactor/project/SaveAppBlocksJsonReactor.java index e14c7faeab4..e7df78c9b51 100644 --- a/src/prerna/reactor/project/SaveAppBlocksJsonReactor.java +++ b/src/prerna/reactor/project/SaveAppBlocksJsonReactor.java @@ -1,184 +1,186 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.project; - -import java.io.File; -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.ZonedDateTime; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.ToNumberPolicy; - -import prerna.auth.User; -import prerna.auth.utils.SecurityProjectUtils; -import prerna.cluster.util.ClusterUtil; -import prerna.project.api.IProject; -import prerna.project.impl.ProjectPortalsHelper; -import prerna.project.impl.notebook.INotebookHelper; -import prerna.reactor.AbstractReactor; -import prerna.reactor.ReactorDefinition; -import prerna.sablecc2.om.GenRowStruct; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.usertracking.AuditEventType; -import prerna.usertracking.UserAuditTrailUtils; -import prerna.util.AssetUtility; -import prerna.util.Utility; -import prerna.util.git.GitRepoUtils; -import prerna.util.gson.GsonUtility; -import prerna.util.gson.LocalDateTimeAdapter; -import prerna.util.gson.ZonedDateTimeAdapter; - -public class SaveAppBlocksJsonReactor extends AbstractReactor { - - protected static final Gson GSON = new GsonBuilder().disableHtmlEscaping() - .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) - .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter()) - .registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeAdapter()) - // we want pretty printing so git diff is readable - .setPrettyPrinting().create(); - - private static final Logger classLogger = LogManager.getLogger(SaveAppBlocksJsonReactor.class); - - private static final String CLASS_NAME = SaveAppBlocksJsonReactor.class.getName(); - - public SaveAppBlocksJsonReactor() { - this.keysToGet = new String[] { ReactorKeysEnum.PROJECT.getKey(), ReactorKeysEnum.JSON.getKey(), - ReactorKeysEnum.COMMENT_KEY.getKey() }; - } - - @Override - public NounMetadata execute() { - Logger logger = getLogger(CLASS_NAME); - - User user = this.insight.getUser(); - organizeKeys(); - String projectId = this.keyValue.get(this.keysToGet[0]); - if (projectId == null || projectId.isEmpty()) { - throw new IllegalArgumentException("Must input an project id"); - } - - if (!SecurityProjectUtils.userCanEditProject(this.insight.getUser(), projectId)) { - throw new IllegalArgumentException("Project does not exist or user does not have access to the project"); - } - - Map json = getBlocksJSON(); - if (json == null || json.isEmpty()) { - throw new IllegalArgumentException("Must provide the blocks JSON"); - } - - String comment = this.keyValue.get(this.keysToGet[2]); - - IProject project = Utility.getProject(projectId); - String portalsFolder = AssetUtility.getProjectPortalsFolder(projectId); - File blocksJsonFile = new File(portalsFolder + "/" + IProject.BLOCK_FILE_NAME); - if (blocksJsonFile.exists() && blocksJsonFile.isFile()) { - blocksJsonFile.delete(); - } - - try { - GsonUtility.writeObjectToJsonFile(blocksJsonFile, GSON, json); - } catch (IOException e) { - classLogger.error("Failed to write the blocks json to {} for project '{}'", blocksJsonFile, projectId, e); - throw new IllegalArgumentException( - "Was unable to save the blocks json to the project folder. Errror = " + e.getMessage()); - } - - // add file to git - List files = new ArrayList<>(); - files.add(blocksJsonFile.getAbsolutePath()); - String projectVersionFolder = AssetUtility.getProjectVersionFolder(project.getProjectName(), projectId); - GitRepoUtils.addSpecificFiles(projectVersionFolder, files); - // commit it - GitRepoUtils.commitAddedFiles(projectVersionFolder, comment, user); - - if (ClusterUtil.IS_CLUSTER) { - logger.info("Syncing project for cloud backup"); - ClusterUtil.pushProjectFolder(project, projectVersionFolder); - } - ProjectPortalsHelper.notePortalChange(user, projectId); - - // auto save the engine dependencies as well - Map engineDependenciesMap = project.getEngineDependencies(); - Set engineDependencyIds = new HashSet<>(engineDependenciesMap.values()); - engineDependencyIds.remove(INotebookHelper.UNDEFINED_VALUE); - SecurityProjectUtils.updateProjectDependenciesWithoutType(user, projectId, engineDependencyIds); - SecurityProjectUtils.updateProjectLastEditedDate(projectId); - UserAuditTrailUtils.recordProjectLifecycle(user, AuditEventType.PROJECT_BLOCKS_UPDATE, projectId, - project.getProjectName(), Map.of("changedFields", List.of("blocks", "dependencies"))); - - return new NounMetadata(true, PixelDataType.MAP); - } - - private Map getBlocksJSON() { - GenRowStruct mapGrs = this.store.getGenRowStruct(ReactorKeysEnum.JSON.getKey()); - if (mapGrs != null && !mapGrs.isEmpty()) { - List mapInputs = mapGrs.getNounsOfType(PixelDataType.MAP); - if (mapInputs != null && !mapInputs.isEmpty()) { - return (Map) mapInputs.get(0).getValue(); - } - - List strGrs = mapGrs.getNounsOfType(PixelDataType.CONST_STRING); - if (strGrs != null && !strGrs.isEmpty()) { - String jsonStr = (String) strGrs.get(0).getValue(); - - // validate this is actually JSON - GsonUtility.validateJsonString(jsonStr); - - return GSON.fromJson(jsonStr, Map.class); - } - } - List mapInputs = this.curRow.getNounsOfType(PixelDataType.MAP); - if (mapInputs != null && !mapInputs.isEmpty()) { - return (Map) mapInputs.get(0).getValue(); - } - - return null; - } - - @Override - public ReactorDefinition getReactorDefinition() { - return super.getReactorDefinition().description( - "Saves the blocks JSON of an app the user can edit, commits it to the app's version history with the given comment, and updates the app's engine dependencies.") - .key(ReactorKeysEnum.COMMENT_KEY, "The commit message for this save in the app's version history.") - .key(ReactorKeysEnum.JSON, - key -> key.type(Map.class).description("The JSON that represents the blocks for the app")); - } - -} +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.project; + +import java.io.File; +import java.io.IOException; +import java.time.LocalDateTime; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.ToNumberPolicy; + +import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.auth.utils.SecurityProjectUtils; +import prerna.cluster.util.ClusterUtil; +import prerna.project.api.IProject; +import prerna.project.impl.ProjectPortalsHelper; +import prerna.project.impl.notebook.INotebookHelper; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.GenRowStruct; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.ReactorKeysEnum; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.usertracking.AuditEventType; +import prerna.usertracking.UserAuditTrailUtils; +import prerna.util.AssetUtility; +import prerna.util.Utility; +import prerna.util.git.GitRepoUtils; +import prerna.util.gson.GsonUtility; +import prerna.util.gson.LocalDateTimeAdapter; +import prerna.util.gson.ZonedDateTimeAdapter; + +public class SaveAppBlocksJsonReactor extends AbstractReactor { + + protected static final Gson GSON = new GsonBuilder().disableHtmlEscaping() + .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE) + .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter()) + .registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeAdapter()) + // we want pretty printing so git diff is readable + .setPrettyPrinting().create(); + + private static final Logger classLogger = LogManager.getLogger(SaveAppBlocksJsonReactor.class); + + private static final String CLASS_NAME = SaveAppBlocksJsonReactor.class.getName(); + + public SaveAppBlocksJsonReactor() { + this.keysToGet = new String[] { ReactorKeysEnum.PROJECT.getKey(), ReactorKeysEnum.JSON.getKey(), + ReactorKeysEnum.COMMENT_KEY.getKey() }; + } + + @Override + public NounMetadata execute() { + Logger logger = getLogger(CLASS_NAME); + + User user = this.insight.getUser(); + organizeKeys(); + String projectId = this.keyValue.get(this.keysToGet[0]); + if (projectId == null || projectId.isEmpty()) { + throw new IllegalArgumentException("Must input an project id"); + } + + if (!SecurityProjectUtils.userCanEditProject(this.insight.getUser(), projectId)) { + throw new IllegalArgumentException("Project does not exist or user does not have access to the project"); + } + + Map json = getBlocksJSON(); + if (json == null || json.isEmpty()) { + throw new IllegalArgumentException("Must provide the blocks JSON"); + } + + String comment = this.keyValue.get(this.keysToGet[2]); + + IProject project = Utility.getProject(projectId); + String portalsFolder = AssetUtility.getProjectPortalsFolder(projectId); + File blocksJsonFile = new File(portalsFolder + "/" + IProject.BLOCK_FILE_NAME); + if (blocksJsonFile.exists() && blocksJsonFile.isFile()) { + blocksJsonFile.delete(); + } + + try { + GsonUtility.writeObjectToJsonFile(blocksJsonFile, GSON, json); + } catch (IOException e) { + classLogger.error("Failed to write the blocks json to {} for project '{}'", blocksJsonFile, projectId, e); + throw new IllegalArgumentException( + "Was unable to save the blocks json to the project folder. Errror = " + e.getMessage()); + } + + // add file to git + List files = new ArrayList<>(); + files.add(blocksJsonFile.getAbsolutePath()); + String projectVersionFolder = AssetUtility.getProjectVersionFolder(project.getProjectName(), projectId); + GitRepoUtils.addSpecificFiles(projectVersionFolder, files); + // commit it + GitRepoUtils.commitAddedFiles(projectVersionFolder, comment, user); + + if (ClusterUtil.IS_CLUSTER) { + logger.info("Syncing project for cloud backup"); + ClusterUtil.pushProjectFolder(project, projectVersionFolder); + } + ProjectPortalsHelper.notePortalChange(user, projectId); + + // auto save the engine dependencies as well + Map engineDependenciesMap = project.getEngineDependencies(); + Set engineDependencyIds = new HashSet<>(engineDependenciesMap.values()); + engineDependencyIds.remove(INotebookHelper.UNDEFINED_VALUE); + SecurityCatalogDependencyUtils.setDependencyIds(user, projectId, IProject.PROJECT_TYPE.BLOCKS.name(), + engineDependencyIds); + SecurityProjectUtils.updateProjectLastEditedDate(projectId); + UserAuditTrailUtils.recordProjectLifecycle(user, AuditEventType.PROJECT_BLOCKS_UPDATE, projectId, + project.getProjectName(), Map.of("changedFields", List.of("blocks", "dependencies"))); + + return new NounMetadata(true, PixelDataType.MAP); + } + + private Map getBlocksJSON() { + GenRowStruct mapGrs = this.store.getGenRowStruct(ReactorKeysEnum.JSON.getKey()); + if (mapGrs != null && !mapGrs.isEmpty()) { + List mapInputs = mapGrs.getNounsOfType(PixelDataType.MAP); + if (mapInputs != null && !mapInputs.isEmpty()) { + return (Map) mapInputs.get(0).getValue(); + } + + List strGrs = mapGrs.getNounsOfType(PixelDataType.CONST_STRING); + if (strGrs != null && !strGrs.isEmpty()) { + String jsonStr = (String) strGrs.get(0).getValue(); + + // validate this is actually JSON + GsonUtility.validateJsonString(jsonStr); + + return GSON.fromJson(jsonStr, Map.class); + } + } + List mapInputs = this.curRow.getNounsOfType(PixelDataType.MAP); + if (mapInputs != null && !mapInputs.isEmpty()) { + return (Map) mapInputs.get(0).getValue(); + } + + return null; + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition().description( + "Saves the blocks JSON of an app the user can edit, commits it to the app's version history with the given comment, and updates the app's engine dependencies.") + .key(ReactorKeysEnum.COMMENT_KEY, "The commit message for this save in the app's version history.") + .key(ReactorKeysEnum.JSON, + key -> key.type(Map.class).description("The JSON that represents the blocks for the app")); + } + +} diff --git a/src/prerna/reactor/project/UploadProjectAppReactor.java b/src/prerna/reactor/project/UploadProjectAppReactor.java index b8b3298b9d5..dcc003995fc 100644 --- a/src/prerna/reactor/project/UploadProjectAppReactor.java +++ b/src/prerna/reactor/project/UploadProjectAppReactor.java @@ -1,452 +1,464 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.project; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.UUID; - -import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import com.google.gson.JsonObject; -import com.google.gson.reflect.TypeToken; - -import prerna.auth.AuthProvider; -import prerna.auth.User; -import prerna.auth.utils.AbstractSecurityUtils; -import prerna.auth.utils.SecurityAdminUtils; -import prerna.auth.utils.SecurityProjectUtils; -import prerna.auth.utils.SecurityQueryUtils; -import prerna.cluster.util.ClusterUtil; -import prerna.engine.api.IEngine; -import prerna.engine.impl.SmssUtilities; -import prerna.project.api.IProject; -import prerna.project.impl.ProjectHelper; -import prerna.reactor.AbstractReactor; -import prerna.reactor.ReactorDefinition; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.PixelOperationType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.execptions.SemossPixelException; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.usertracking.AuditEventType; -import prerna.usertracking.UserAuditTrailUtils; -import prerna.util.AgentProjectArchiveUtils; -import prerna.util.Constants; -import prerna.util.EngineUtility; -import prerna.util.InternalUtility; -import prerna.util.UploadInputUtility; -import prerna.util.UploadUtilities; -import prerna.util.Utility; -import prerna.util.ZipUtils; -import prerna.util.gson.GsonUtility; - -public class UploadProjectAppReactor extends AbstractReactor { - - private static final Logger classLogger = LogManager.getLogger(UploadProjectAppReactor.class); - - private static final String CLASS_NAME = UploadProjectAppReactor.class.getName(); - - public static final String CREATE_MODE = "create"; - public static final String REPLACE_MODE = "replace"; - - public static final String MODE_KEY = "mode"; - - public UploadProjectAppReactor() { - this.keysToGet = new String[] { ReactorKeysEnum.FILE_PATH.getKey(), ReactorKeysEnum.SPACE.getKey(), - ReactorKeysEnum.GLOBAL.getKey(), MODE_KEY }; - } - - @Override - public NounMetadata execute() { - organizeKeys(); - Logger logger = this.getLogger(CLASS_NAME); - int step = 1; - String zipFilePath = UploadInputUtility.getFilePath(this.store, this.insight); - File zipFile = zipFilePath == null ? null : new File(Utility.normalizePath(zipFilePath)); - if (zipFile == null || !zipFile.exists() || !zipFile.isFile()) { - String fileName = zipFile == null ? zipFilePath : zipFile.getName(); - SemossPixelException exception = new SemossPixelException( - NounMetadata.getErrorNounMessage("Unable to find the file to upload: " + fileName)); - exception.setContinueThreadOfExecution(false); - throw exception; - } - // do we want this project to be accessible to everyone - boolean global = Boolean.parseBoolean(this.keyValue.get(ReactorKeysEnum.GLOBAL.getKey()) + ""); - // check security - // Need to check this, will the same methods work/enhanced to check the - // permissions on project? - User user = requireUser(); - - // throw error is user doesn't have rights to publish new apps - if (AbstractSecurityUtils.adminSetPublisher() && !SecurityQueryUtils.userIsPublisher(user)) { - throwUserNotPublisherError(); - } - - // creating a temp folder to unzip project folder and smss - String randomIdAsDir = UUID.randomUUID().toString(); - String randomTempUnzipFolderPath = this.insight.getInsightFolder() + DIR_SEPARATOR + randomIdAsDir; - File randomTempUnzipF = new File(randomTempUnzipFolderPath); - - // gotta keep track of the smssFile and files unzipped - Map> filesAdded = new HashMap<>(); - List fileList = new ArrayList<>(); - String smssFileLoc = null; - File smssFile = null; - Properties projectProperties = null; - JsonObject agentMetadata = null; - // unzip files to temp project folder - boolean error = false; - try { - logger.info(step + ") Unzipping project"); - filesAdded = ZipUtils.unzip(zipFilePath, randomTempUnzipFolderPath); - logger.info(step + ") Done"); - step++; - - // look for smss file - fileList = filesAdded.get("FILE"); - logger.info(step + ") Searching for smss"); - for (String filePath : fileList) { - if (!filePath.startsWith("__MACOSX/") && filePath.endsWith(Constants.SEMOSS_EXTENSION)) { - smssFileLoc = randomTempUnzipFolderPath + DIR_SEPARATOR + filePath; - smssFile = new File(Utility.normalizePath(smssFileLoc)); - // check if the file exists - if (!smssFile.exists()) { - // invalid file need to delete the files unzipped - smssFileLoc = null; - } - break; - } - } - logger.info(step + ") Done"); - step++; - - // delete the files if we were unable to find the smss file - if (smssFileLoc == null) { - throw new SemossPixelException("Unable to find " + Constants.SEMOSS_EXTENSION + " file", false); - } - - projectProperties = Utility.loadProperties(smssFileLoc); - String projectTypeString = projectProperties.getProperty(Constants.PROJECT_ENUM_TYPE); - IProject.PROJECT_TYPE projectType = projectTypeString == null ? IProject.PROJECT_TYPE.INSIGHTS - : IProject.PROJECT_TYPE.valueOf(projectTypeString.trim()); - if (AbstractSecurityUtils.adminOnlyProjectAdd(projectType) && !SecurityAdminUtils.userIsAdmin(user)) { - AbstractReactor.throwFunctionalityOnlyExposedForAdminsError(); - } - if (global && AbstractSecurityUtils.adminOnlyProjectSetPublic(projectType) - && !SecurityAdminUtils.userIsAdmin(user)) { - SemossPixelException exception = new SemossPixelException( - NounMetadata.getErrorNounMessage("User can upload an app but cannot make the app public")); - exception.setContinueThreadOfExecution(false); - throw exception; - } - agentMetadata = AgentProjectArchiveUtils.readAgent(randomTempUnzipF, projectProperties); - } catch (SemossPixelException e) { - error = true; - throw e; - } catch (Exception e) { - error = true; - classLogger.error("Error occurred while unzipping the files", e); - throw new SemossPixelException("Error occurred while unzipping the files", false); - } finally { - if (error) { - cleanUpFolders(randomTempUnzipF); - } - } - - String projectFolderPath = EngineUtility.getLocalEngineBaseDirectory(IEngine.CATALOG_TYPE.PROJECT); - - boolean replace = deleteIfExisting(); - String projectId = null; - String projectName = null; - File finalProjectSmssF = null; - File finalProjectFolderF = null; - File finalProjectVersionF = null; - File finalProjectAssetF = null; - boolean projectAddedToDIHelper = false; - boolean replacingExistingProject = false; - try { - logger.info(step + ") Reading smss"); - Properties prop = projectProperties; - projectId = prop.getProperty(Constants.PROJECT); - projectName = Utility.normalizePath(prop.getProperty(Constants.PROJECT_ALIAS)); - - logger.info(step + ") Done"); - step++; - - finalProjectFolderF = new File(Utility.normalizePath( - projectFolderPath + DIR_SEPARATOR + SmssUtilities.getUniqueName(projectName, projectId))); - finalProjectSmssF = new File(Utility.normalizePath(projectFolderPath + DIR_SEPARATOR - + SmssUtilities.getUniqueName(projectName, projectId) + Constants.SEMOSS_EXTENSION)); - - // is this an update or first time upload - if (SecurityProjectUtils.projectExists(projectId)) { - // this is an update - // do we allow update? - // if yes, do you have access to update? - if (replace) { - if (!SecurityProjectUtils.userIsOwner(user, projectId)) { - cleanUpFolders(randomTempUnzipF); - SemossPixelException exception = new SemossPixelException(NounMetadata.getErrorNounMessage( - "User is not an owner to replace the existing project with id = " + projectId)); - exception.setContinueThreadOfExecution(false); - throw exception; - } else { - replacingExistingProject = true; - // make sure we pull the project from cloud - IProject project = Utility.getProject(projectId); - project.close(); - // now delete the project folder - we will make a new one when we copy from temp - // dir - FileUtils.deleteDirectory(finalProjectFolderF); - // now delete the project smss - we will make a new one when we copy from temp - // dir - FileUtils.delete(finalProjectSmssF); - } - } else { - cleanUpFolders(randomTempUnzipF); - SemossPixelException exception = new SemossPixelException( - NounMetadata.getErrorNounMessage("Project id already exists")); - exception.setContinueThreadOfExecution(false); - throw exception; - } - } else { - // first time upload - // need to ignore file watcher - if (InternalUtility.addProjectId(projectId)) { - projectAddedToDIHelper = true; - } - } - - // create the project folder - // since this assumes we have only the assets - // make the project name / app root / version / asset folder path - finalProjectVersionF = new File(finalProjectFolderF.getAbsolutePath() + DIR_SEPARATOR - + Constants.APP_ROOT_FOLDER + DIR_SEPARATOR + Constants.VERSION_FOLDER); - finalProjectAssetF = new File( - finalProjectVersionF.getAbsolutePath() + DIR_SEPARATOR + Constants.ASSETS_FOLDER); - finalProjectAssetF.mkdirs(); - - // move project folder - logger.info(step + ") Moving project folder"); - File[] allFiles = randomTempUnzipF.listFiles(); - for (File f : allFiles) { - if (f.getName().equals("assets") && f.isDirectory()) { - // we move the assets folder into the version folder - FileUtils.copyDirectory(f, finalProjectAssetF); - } else if (f.isDirectory()) { - FileUtils.copyDirectory(f, finalProjectVersionF); - } else if (f.isFile()) { - // this way the metadata files are in the same location - // if it is UploadProject or UploadProjectApp - FileUtils.copyFileToDirectory(f, finalProjectFolderF, true); - } - } - logger.info(step + ") Done"); - - step++; - // move smss file which would have been already copied into the project folder - logger.info(step + ") Moving smss file"); - File tempUnzippedSmssF = new File(Utility.normalizePath(finalProjectFolderF + DIR_SEPARATOR - + SmssUtilities.getUniqueName(projectName, projectId) + Constants.SEMOSS_EXTENSION)); - FileUtils.moveFile(tempUnzippedSmssF, finalProjectSmssF); - logger.info(step + ") Done"); - step++; - - } catch (Exception e) { - error = true; - classLogger.error("Error copying the files over from the temp zip location to the final project folder", e); - throw new SemossPixelException(e.getMessage(), false); - } finally { - if (error) { - // remove from DIHelper - if (projectAddedToDIHelper) { - UploadUtilities.removeProjectFromDIHelper(projectId); - } - cleanUpFolders(randomTempUnzipF, finalProjectSmssF, finalProjectFolderF); - } else { - // just delete the temp project folder - cleanUpFolders(randomTempUnzipF); - } - } - - try { - InternalUtility.setProjectSmssPath(projectId, - finalProjectSmssF.getAbsolutePath()); - logger.info(step + ") Grabbing project insights"); - if (!replacingExistingProject) { - SecurityProjectUtils.addProject(projectId, global, user); - } - - // ensure PROJECT_DISPLAY_NAME is present in the smss file - // if not present, seed it from PROJECT_ALIAS so the file stays consistent - Properties smssProps = Utility.loadProperties(finalProjectSmssF.getAbsolutePath()); - String displayName = smssProps.getProperty(Constants.PROJECT_DISPLAY_NAME); - if (displayName == null || displayName.trim().isEmpty()) { - try { - InternalUtility.changePropertiesFileValue(finalProjectSmssF.getAbsolutePath(), - Constants.PROJECT_DISPLAY_NAME, projectName); - } catch (IOException e) { - classLogger.error("Failed to write {} into the smss file for project {}", - Constants.PROJECT_DISPLAY_NAME, projectId, e); - } - } - - // see if we have any metadata to load - { - File metadataFile = new File( - finalProjectFolderF.getAbsolutePath() + "/" + projectName + IEngine.METADATA_FILE_SUFFIX); - if (metadataFile.exists() && metadataFile.isFile()) { - Map metadata = (Map) GsonUtility.readJsonFileToObject(metadataFile, - new TypeToken>() { - }.getType()); - SecurityProjectUtils.updateProjectMetadata(projectId, metadata); - // delete this file since values can update and file is dynamically generated on - // export - metadataFile.delete(); - } - } - - // Consume the generated archive file before the final, atomic agent import. - if (agentMetadata != null) { - AgentProjectArchiveUtils.importDependencies(finalProjectFolderF, projectName, projectId, user); - Files.delete( - new File(finalProjectFolderF, projectName + AgentProjectArchiveUtils.FILE_SUFFIX).toPath()); - AgentProjectArchiveUtils.importAgent(projectId, user, agentMetadata, replacingExistingProject); - } - - logger.info(step + ") Done"); - } catch (Exception e) { - error = true; - classLogger.error( - "Failed to restore metadata, insights, or agent configuration for project {} from archive {}", - projectId, zipFilePath, e); - throw new SemossPixelException( - "Error occurred trying to synchronize the metadata and insights for the zip file", false); - } finally { - if (error) { - // delete all the resources - cleanUpFolders(randomTempUnzipF, finalProjectSmssF, finalProjectFolderF); - // remove from DIHelper - if (projectAddedToDIHelper) { - UploadUtilities.removeProjectFromDIHelper(projectId); - } - // delete from security - SecurityProjectUtils.deleteProject(projectId); - } else { - File[] assetsFilesToDelete = finalProjectAssetF - .listFiles((dir, name) -> name.endsWith(IEngine.METADATA_FILE_SUFFIX) - || name.endsWith(IProject.DEPENDENCIES_FILE_SUFFIX) - || name.endsWith(Constants.SEMOSS_EXTENSION)); - cleanUpFolders(assetsFilesToDelete); - } - } - - // add user as engine owner - if (!replacingExistingProject) { - List logins = user.getLogins(); - for (AuthProvider ap : logins) { - SecurityProjectUtils.addProjectOwner(user, projectId, user.getAccessToken(ap).getId()); - } - } - - // push new project to cloud - ClusterUtil.pushProject(projectId); - - Map engineIdMap = ProjectHelper.extractEngineIdsFromProjectFolder(finalProjectFolderF); - // update the project dependencies table only with valid engineIds - if (agentMetadata == null && engineIdMap.containsKey("success")) { - Map successMap = (Map) engineIdMap.get("success"); - SecurityProjectUtils.updateProjectDependenciesWithoutType(user, projectId, successMap.keySet()); - } - - UserAuditTrailUtils.recordProjectLifecycle(user, - replace ? AuditEventType.PROJECT_REPLACE : AuditEventType.PROJECT_UPLOAD, projectId, projectName, - Map.of("global", global, "mode", replace ? REPLACE_MODE : CREATE_MODE)); - - // sending the success and failed list of engineIds to FE - Map retMap = UploadUtilities.getProjectReturnData(this.insight.getUser(), projectId); - retMap.put("engineIds", engineIdMap); - return new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, PixelOperationType.MARKET_PLACE_ADDITION); - } - - /** - * This method is intended to be overridden by other reactors in case we want to - * have different default values if no mode is passed in - * - * @return - */ - protected boolean deleteIfExisting() { - String modeKey = this.keyValue.getOrDefault(MODE_KEY, CREATE_MODE).trim(); - if (REPLACE_MODE.equalsIgnoreCase(modeKey)) { - return true; - } - return false; - } - - /** - * - * @param fileToDelete - */ - private void cleanUpFolders(File... fileToDelete) { - for (File f : fileToDelete) { - if (f != null && f.exists()) { - try { - FileUtils.forceDelete(f); - } catch (IOException e) { - classLogger.error("Error on clean up attempting to delete " + f.getAbsolutePath(), e); - } - } - } - } - - @Override - public ReactorDefinition getReactorDefinition() { - return super.getReactorDefinition().description("Import an app from an exported zip smss-app file").key( - ReactorKeysEnum.FILE_PATH, - "This is a required value containing the relative file path of the single zip file to be imported") - .key(ReactorKeysEnum.SPACE, - "This is an optional field to determine the space in which the relative file path exists (user project space, current insight space, project id space).") - .key(ReactorKeysEnum.GLOBAL, "This is a required value to determine if the app is public or private") - .key(MODE_KEY, """ - Optional paramter that is either 'create' or 'replace'. - 'create' is the default and will break if the app id already exists. - 'replace' will replace if the app id exist but user must be an owner of the app. - Default is 'create' if no value is passed in. - """); - } - -} +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.project; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; + +import org.apache.commons.io.FileUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; + +import prerna.auth.AuthProvider; +import prerna.auth.User; +import prerna.auth.utils.AbstractSecurityUtils; +import prerna.auth.utils.SecurityAdminUtils; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.auth.utils.SecurityProjectUtils; +import prerna.auth.utils.SecurityQueryUtils; +import prerna.cluster.util.ClusterUtil; +import prerna.engine.api.IEngine; +import prerna.engine.impl.SmssUtilities; +import prerna.project.api.IProject; +import prerna.project.impl.ProjectHelper; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.PixelOperationType; +import prerna.sablecc2.om.ReactorKeysEnum; +import prerna.sablecc2.om.execptions.SemossPixelException; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.usertracking.AuditEventType; +import prerna.usertracking.UserAuditTrailUtils; +import prerna.util.AgentProjectArchiveUtils; +import prerna.util.Constants; +import prerna.util.EngineUtility; +import prerna.util.InternalUtility; +import prerna.util.UploadInputUtility; +import prerna.util.UploadUtilities; +import prerna.util.Utility; +import prerna.util.ZipUtils; +import prerna.util.gson.GsonUtility; + +public class UploadProjectAppReactor extends AbstractReactor { + + private static final Logger classLogger = LogManager.getLogger(UploadProjectAppReactor.class); + + private static final String CLASS_NAME = UploadProjectAppReactor.class.getName(); + + public static final String CREATE_MODE = "create"; + public static final String REPLACE_MODE = "replace"; + + public static final String MODE_KEY = "mode"; + + public UploadProjectAppReactor() { + this.keysToGet = new String[] { ReactorKeysEnum.FILE_PATH.getKey(), ReactorKeysEnum.SPACE.getKey(), + ReactorKeysEnum.GLOBAL.getKey(), MODE_KEY }; + } + + @Override + public NounMetadata execute() { + organizeKeys(); + Logger logger = this.getLogger(CLASS_NAME); + int step = 1; + String zipFilePath = UploadInputUtility.getFilePath(this.store, this.insight); + File zipFile = zipFilePath == null ? null : new File(Utility.normalizePath(zipFilePath)); + if (zipFile == null || !zipFile.exists() || !zipFile.isFile()) { + String fileName = zipFile == null ? zipFilePath : zipFile.getName(); + SemossPixelException exception = new SemossPixelException( + NounMetadata.getErrorNounMessage("Unable to find the file to upload: " + fileName)); + exception.setContinueThreadOfExecution(false); + throw exception; + } + // do we want this project to be accessible to everyone + boolean global = Boolean.parseBoolean(this.keyValue.get(ReactorKeysEnum.GLOBAL.getKey()) + ""); + // check security + // Need to check this, will the same methods work/enhanced to check the + // permissions on project? + User user = requireUser(); + + // throw error is user doesn't have rights to publish new apps + if (AbstractSecurityUtils.adminSetPublisher() && !SecurityQueryUtils.userIsPublisher(user)) { + throwUserNotPublisherError(); + } + + // creating a temp folder to unzip project folder and smss + String randomIdAsDir = UUID.randomUUID().toString(); + String randomTempUnzipFolderPath = this.insight.getInsightFolder() + DIR_SEPARATOR + randomIdAsDir; + File randomTempUnzipF = new File(randomTempUnzipFolderPath); + + // gotta keep track of the smssFile and files unzipped + Map> filesAdded = new HashMap<>(); + List fileList = new ArrayList<>(); + String smssFileLoc = null; + File smssFile = null; + Properties projectProperties = null; + JsonObject agentMetadata = null; + // unzip files to temp project folder + boolean error = false; + try { + logger.info(step + ") Unzipping project"); + filesAdded = ZipUtils.unzip(zipFilePath, randomTempUnzipFolderPath); + logger.info(step + ") Done"); + step++; + + // look for smss file + fileList = filesAdded.get("FILE"); + logger.info(step + ") Searching for smss"); + for (String filePath : fileList) { + if (!filePath.startsWith("__MACOSX/") && filePath.endsWith(Constants.SEMOSS_EXTENSION)) { + smssFileLoc = randomTempUnzipFolderPath + DIR_SEPARATOR + filePath; + smssFile = new File(Utility.normalizePath(smssFileLoc)); + // check if the file exists + if (!smssFile.exists()) { + // invalid file need to delete the files unzipped + smssFileLoc = null; + } + break; + } + } + logger.info(step + ") Done"); + step++; + + // delete the files if we were unable to find the smss file + if (smssFileLoc == null) { + throw new SemossPixelException("Unable to find " + Constants.SEMOSS_EXTENSION + " file", false); + } + + projectProperties = Utility.loadProperties(smssFileLoc); + String projectTypeString = projectProperties.getProperty(Constants.PROJECT_ENUM_TYPE); + IProject.PROJECT_TYPE projectType = projectTypeString == null ? IProject.PROJECT_TYPE.INSIGHTS + : IProject.PROJECT_TYPE.valueOf(projectTypeString.trim()); + if (AbstractSecurityUtils.adminOnlyProjectAdd(projectType) && !SecurityAdminUtils.userIsAdmin(user)) { + AbstractReactor.throwFunctionalityOnlyExposedForAdminsError(); + } + if (global && AbstractSecurityUtils.adminOnlyProjectSetPublic(projectType) + && !SecurityAdminUtils.userIsAdmin(user)) { + SemossPixelException exception = new SemossPixelException( + NounMetadata.getErrorNounMessage("User can upload an app but cannot make the app public")); + exception.setContinueThreadOfExecution(false); + throw exception; + } + agentMetadata = AgentProjectArchiveUtils.readAgent(randomTempUnzipF, projectProperties); + } catch (SemossPixelException e) { + error = true; + throw e; + } catch (Exception e) { + error = true; + classLogger.error("Error occurred while unzipping the files", e); + throw new SemossPixelException("Error occurred while unzipping the files", false); + } finally { + if (error) { + cleanUpFolders(randomTempUnzipF); + } + } + + String projectFolderPath = EngineUtility.getLocalEngineBaseDirectory(IEngine.CATALOG_TYPE.PROJECT); + + boolean replace = deleteIfExisting(); + String projectId = null; + String projectName = null; + File finalProjectSmssF = null; + File finalProjectFolderF = null; + File finalProjectVersionF = null; + File finalProjectAssetF = null; + // the dependencies the export listed, read before its file is deleted + List> exportedDependencies = new ArrayList<>(); + boolean projectAddedToDIHelper = false; + boolean replacingExistingProject = false; + try { + logger.info(step + ") Reading smss"); + Properties prop = projectProperties; + projectId = prop.getProperty(Constants.PROJECT); + projectName = Utility.normalizePath(prop.getProperty(Constants.PROJECT_ALIAS)); + + logger.info(step + ") Done"); + step++; + + finalProjectFolderF = new File(Utility.normalizePath( + projectFolderPath + DIR_SEPARATOR + SmssUtilities.getUniqueName(projectName, projectId))); + finalProjectSmssF = new File(Utility.normalizePath(projectFolderPath + DIR_SEPARATOR + + SmssUtilities.getUniqueName(projectName, projectId) + Constants.SEMOSS_EXTENSION)); + + // is this an update or first time upload + if (SecurityProjectUtils.projectExists(projectId)) { + // this is an update + // do we allow update? + // if yes, do you have access to update? + if (replace) { + if (!SecurityProjectUtils.userIsOwner(user, projectId)) { + cleanUpFolders(randomTempUnzipF); + SemossPixelException exception = new SemossPixelException(NounMetadata.getErrorNounMessage( + "User is not an owner to replace the existing project with id = " + projectId)); + exception.setContinueThreadOfExecution(false); + throw exception; + } else { + replacingExistingProject = true; + // make sure we pull the project from cloud + IProject project = Utility.getProject(projectId); + project.close(); + // now delete the project folder - we will make a new one when we copy from temp + // dir + FileUtils.deleteDirectory(finalProjectFolderF); + // now delete the project smss - we will make a new one when we copy from temp + // dir + FileUtils.delete(finalProjectSmssF); + } + } else { + cleanUpFolders(randomTempUnzipF); + SemossPixelException exception = new SemossPixelException( + NounMetadata.getErrorNounMessage("Project id already exists")); + exception.setContinueThreadOfExecution(false); + throw exception; + } + } else { + // first time upload + // need to ignore file watcher + if (InternalUtility.addProjectId(projectId)) { + projectAddedToDIHelper = true; + } + } + + // create the project folder + // since this assumes we have only the assets + // make the project name / app root / version / asset folder path + finalProjectVersionF = new File(finalProjectFolderF.getAbsolutePath() + DIR_SEPARATOR + + Constants.APP_ROOT_FOLDER + DIR_SEPARATOR + Constants.VERSION_FOLDER); + finalProjectAssetF = new File( + finalProjectVersionF.getAbsolutePath() + DIR_SEPARATOR + Constants.ASSETS_FOLDER); + finalProjectAssetF.mkdirs(); + + // move project folder + logger.info(step + ") Moving project folder"); + File[] allFiles = randomTempUnzipF.listFiles(); + for (File f : allFiles) { + if (f.getName().equals("assets") && f.isDirectory()) { + // we move the assets folder into the version folder + FileUtils.copyDirectory(f, finalProjectAssetF); + } else if (f.isDirectory()) { + FileUtils.copyDirectory(f, finalProjectVersionF); + } else if (f.isFile()) { + // this way the metadata files are in the same location + // if it is UploadProject or UploadProjectApp + FileUtils.copyFileToDirectory(f, finalProjectFolderF, true); + } + } + logger.info(step + ") Done"); + + step++; + // move smss file which would have been already copied into the project folder + logger.info(step + ") Moving smss file"); + File tempUnzippedSmssF = new File(Utility.normalizePath(finalProjectFolderF + DIR_SEPARATOR + + SmssUtilities.getUniqueName(projectName, projectId) + Constants.SEMOSS_EXTENSION)); + FileUtils.moveFile(tempUnzippedSmssF, finalProjectSmssF); + logger.info(step + ") Done"); + step++; + + } catch (Exception e) { + error = true; + classLogger.error("Error copying the files over from the temp zip location to the final project folder", e); + throw new SemossPixelException(e.getMessage(), false); + } finally { + if (error) { + // remove from DIHelper + if (projectAddedToDIHelper) { + UploadUtilities.removeProjectFromDIHelper(projectId); + } + cleanUpFolders(randomTempUnzipF, finalProjectSmssF, finalProjectFolderF); + } else { + // just delete the temp project folder + cleanUpFolders(randomTempUnzipF); + } + } + + try { + InternalUtility.setProjectSmssPath(projectId, + finalProjectSmssF.getAbsolutePath()); + logger.info(step + ") Grabbing project insights"); + if (!replacingExistingProject) { + SecurityProjectUtils.addProject(projectId, global, user); + } + + // ensure PROJECT_DISPLAY_NAME is present in the smss file + // if not present, seed it from PROJECT_ALIAS so the file stays consistent + Properties smssProps = Utility.loadProperties(finalProjectSmssF.getAbsolutePath()); + String displayName = smssProps.getProperty(Constants.PROJECT_DISPLAY_NAME); + if (displayName == null || displayName.trim().isEmpty()) { + try { + InternalUtility.changePropertiesFileValue(finalProjectSmssF.getAbsolutePath(), + Constants.PROJECT_DISPLAY_NAME, projectName); + } catch (IOException e) { + classLogger.error("Failed to write {} into the smss file for project {}", + Constants.PROJECT_DISPLAY_NAME, projectId, e); + } + } + + // see if we have any metadata to load + { + File metadataFile = new File( + finalProjectFolderF.getAbsolutePath() + "/" + projectName + IEngine.METADATA_FILE_SUFFIX); + if (metadataFile.exists() && metadataFile.isFile()) { + Map metadata = (Map) GsonUtility.readJsonFileToObject(metadataFile, + new TypeToken>() { + }.getType()); + SecurityProjectUtils.updateProjectMetadata(projectId, metadata); + // delete this file since values can update and file is dynamically generated on + // export + metadataFile.delete(); + } + } + + // Consume the generated archive file before the final, atomic agent import. + if (agentMetadata != null) { + AgentProjectArchiveUtils.importDependencies(finalProjectFolderF, projectName, projectId, user); + Files.delete( + new File(finalProjectFolderF, projectName + AgentProjectArchiveUtils.FILE_SUFFIX).toPath()); + AgentProjectArchiveUtils.importAgent(projectId, user, agentMetadata, replacingExistingProject); + } + + logger.info(step + ") Done"); + } catch (Exception e) { + error = true; + classLogger.error( + "Failed to restore metadata, insights, or agent configuration for project {} from archive {}", + projectId, zipFilePath, e); + throw new SemossPixelException( + "Error occurred trying to synchronize the metadata and insights for the zip file", false); + } finally { + if (error) { + // delete all the resources + cleanUpFolders(randomTempUnzipF, finalProjectSmssF, finalProjectFolderF); + // remove from DIHelper + if (projectAddedToDIHelper) { + UploadUtilities.removeProjectFromDIHelper(projectId); + } + // delete from security + SecurityProjectUtils.deleteProject(projectId); + } else { + exportedDependencies = SecurityCatalogDependencyUtils.readDependencyFile( + new File(finalProjectAssetF, projectName + IProject.DEPENDENCIES_FILE_SUFFIX)); + File[] assetsFilesToDelete = finalProjectAssetF + .listFiles((dir, name) -> name.endsWith(IEngine.METADATA_FILE_SUFFIX) + || name.endsWith(IProject.DEPENDENCIES_FILE_SUFFIX) + || name.endsWith(Constants.SEMOSS_EXTENSION)); + cleanUpFolders(assetsFilesToDelete); + } + } + + // add user as engine owner + if (!replacingExistingProject) { + List logins = user.getLogins(); + for (AuthProvider ap : logins) { + SecurityProjectUtils.addProjectOwner(user, projectId, user.getAccessToken(ap).getId()); + } + } + + // push new project to cloud + ClusterUtil.pushProject(projectId); + + Map engineIdMap = ProjectHelper.extractEngineIdsFromProjectFolder(finalProjectFolderF); + // set the dependencies the export listed, engines and projects with their + // types, and the engines and projects whose ids are in the project's files + if (agentMetadata == null) { + List dependencies = new ArrayList<>( + SecurityCatalogDependencyUtils.fromExported(exportedDependencies)); + if (engineIdMap.containsKey("success")) { + Map successMap = (Map) engineIdMap.get("success"); + dependencies.addAll(SecurityCatalogDependencyUtils.resolveDependencies(successMap.keySet(), null)); + } + SecurityCatalogDependencyUtils.setDependencies(user, projectId, + SecurityCatalogDependencyUtils.resolveCatalogType(projectId, null), dependencies); + } + + UserAuditTrailUtils.recordProjectLifecycle(user, + replace ? AuditEventType.PROJECT_REPLACE : AuditEventType.PROJECT_UPLOAD, projectId, projectName, + Map.of("global", global, "mode", replace ? REPLACE_MODE : CREATE_MODE)); + + // sending the success and failed list of engineIds to FE + Map retMap = UploadUtilities.getProjectReturnData(this.insight.getUser(), projectId); + retMap.put("engineIds", engineIdMap); + return new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, PixelOperationType.MARKET_PLACE_ADDITION); + } + + /** + * This method is intended to be overridden by other reactors in case we want to + * have different default values if no mode is passed in + * + * @return + */ + protected boolean deleteIfExisting() { + String modeKey = this.keyValue.getOrDefault(MODE_KEY, CREATE_MODE).trim(); + if (REPLACE_MODE.equalsIgnoreCase(modeKey)) { + return true; + } + return false; + } + + /** + * + * @param fileToDelete + */ + private void cleanUpFolders(File... fileToDelete) { + for (File f : fileToDelete) { + if (f != null && f.exists()) { + try { + FileUtils.forceDelete(f); + } catch (IOException e) { + classLogger.error("Error on clean up attempting to delete " + f.getAbsolutePath(), e); + } + } + } + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition().description("Import an app from an exported zip smss-app file").key( + ReactorKeysEnum.FILE_PATH, + "This is a required value containing the relative file path of the single zip file to be imported") + .key(ReactorKeysEnum.SPACE, + "This is an optional field to determine the space in which the relative file path exists (user project space, current insight space, project id space).") + .key(ReactorKeysEnum.GLOBAL, "This is a required value to determine if the app is public or private") + .key(MODE_KEY, """ + Optional paramter that is either 'create' or 'replace'. + 'create' is the default and will break if the app id already exists. + 'replace' will replace if the app id exist but user must be an owner of the app. + Default is 'create' if no value is passed in. + """); + } + +} diff --git a/src/prerna/reactor/project/UploadProjectReactor.java b/src/prerna/reactor/project/UploadProjectReactor.java index a851b50b8aa..36be6d542e8 100644 --- a/src/prerna/reactor/project/UploadProjectReactor.java +++ b/src/prerna/reactor/project/UploadProjectReactor.java @@ -1,368 +1,368 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.project; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.UUID; - -import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import com.google.gson.JsonObject; -import com.google.gson.reflect.TypeToken; - -import prerna.auth.AuthProvider; -import prerna.auth.User; -import prerna.auth.utils.AbstractSecurityUtils; -import prerna.auth.utils.SecurityAdminUtils; -import prerna.auth.utils.SecurityProjectUtils; -import prerna.auth.utils.SecurityQueryUtils; -import prerna.cluster.util.ClusterUtil; -import prerna.engine.api.IEngine; -import prerna.engine.impl.SmssUtilities; -import prerna.project.api.IProject; -import prerna.reactor.AbstractReactor; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.PixelOperationType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.execptions.SemossPixelException; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.usertracking.AuditEventType; -import prerna.usertracking.UserAuditTrailUtils; -import prerna.util.AgentProjectArchiveUtils; -import prerna.util.Constants; -import prerna.util.InternalUtility; -import prerna.util.UploadInputUtility; -import prerna.util.UploadUtilities; -import prerna.util.Utility; -import prerna.util.ZipUtils; -import prerna.util.gson.GsonUtility; - -public class UploadProjectReactor extends AbstractReactor { - - private static final Logger classLogger = LogManager.getLogger(UploadProjectReactor.class); - - private static final String CLASS_NAME = UploadProjectReactor.class.getName(); - - public UploadProjectReactor() { - this.keysToGet = new String[] { ReactorKeysEnum.FILE_PATH.getKey(), ReactorKeysEnum.SPACE.getKey(), - ReactorKeysEnum.GLOBAL.getKey() }; - } - - @Override - public NounMetadata execute() { - organizeKeys(); - Logger logger = this.getLogger(CLASS_NAME); - int step = 1; - String zipFilePath = UploadInputUtility.getFilePath(this.store, this.insight); - // do we want this project to be accessible to everyone - boolean global = Boolean.parseBoolean(this.keyValue.get(ReactorKeysEnum.GLOBAL.getKey()) + ""); - // check security - // Need to check this, will the same methods work/enhanced to check the - // permissions on project? - User user = requireUser(); - - // throw error is user doesn't have rights to publish new apps - if (AbstractSecurityUtils.adminSetPublisher() && !SecurityQueryUtils.userIsPublisher(user)) { - throwUserNotPublisherError(); - } - - // creating a temp folder to unzip project folder and smss - String randomIdAsDir = UUID.randomUUID().toString(); - String projectFolderPath = Utility.getDIHelperProperty(Constants.BASE_FOLDER) + DIR_SEPARATOR - + Constants.PROJECT_FOLDER; - String randomTempUnzipFolderPath = projectFolderPath + DIR_SEPARATOR + randomIdAsDir; - File randomTempUnzipF = new File(randomTempUnzipFolderPath); - - // gotta keep track of the smssFile and files unzipped - Map> filesAdded = new HashMap<>(); - List fileList = new ArrayList<>(); - String smssFileLoc = null; - File smssFile = null; - Properties projectProperties = null; - JsonObject agentMetadata = null; - // unzip files to temp project folder - boolean error = false; - try { - logger.info("{}) Unzipping project", step); - filesAdded = ZipUtils.unzip(zipFilePath, randomTempUnzipFolderPath); - logger.info("{}) Done", step); - step++; - - // look for smss file - fileList = filesAdded.get("FILE"); - logger.info("{}) Searching for smss", step); - for (String filePath : fileList) { - if (!filePath.startsWith("__MACOSX/") && filePath.endsWith(Constants.SEMOSS_EXTENSION)) { - smssFileLoc = randomTempUnzipFolderPath + DIR_SEPARATOR + filePath; - smssFile = new File(Utility.normalizePath(smssFileLoc)); - // check if the file exists - if (!smssFile.exists()) { - // invalid file need to delete the files unzipped - smssFileLoc = null; - } - break; - } - } - logger.info("{}) Done", step); - step++; - - // delete the files if we were unable to find the smss file - if (smssFileLoc == null) { - throw new SemossPixelException("Unable to find " + Constants.SEMOSS_EXTENSION + " file", false); - } - - projectProperties = Utility.loadProperties(smssFileLoc); - String projectTypeString = projectProperties.getProperty(Constants.PROJECT_ENUM_TYPE); - IProject.PROJECT_TYPE projectType = projectTypeString == null ? IProject.PROJECT_TYPE.INSIGHTS - : IProject.PROJECT_TYPE.valueOf(projectTypeString.trim()); - if (AbstractSecurityUtils.adminOnlyProjectAdd(projectType) && !SecurityAdminUtils.userIsAdmin(user)) { - AbstractReactor.throwFunctionalityOnlyExposedForAdminsError(); - } - if (global && AbstractSecurityUtils.adminOnlyProjectSetPublic(projectType) - && !SecurityAdminUtils.userIsAdmin(user)) { - SemossPixelException exception = new SemossPixelException(NounMetadata - .getErrorNounMessage("User can upload a project but cannot make the project public")); - exception.setContinueThreadOfExecution(false); - throw exception; - } - agentMetadata = AgentProjectArchiveUtils.readAgent(new File(randomTempUnzipF, - SmssUtilities.getUniqueName(projectProperties.getProperty(Constants.PROJECT_ALIAS), - projectProperties.getProperty(Constants.PROJECT))), - projectProperties); - } catch (SemossPixelException e) { - error = true; - throw e; - } catch (Exception e) { - error = true; - classLogger.error("Error occurred while unzipping the files", e); - throw new SemossPixelException("Error occurred while unzipping the files", false); - } finally { - if (error) { - cleanUpFolders(randomTempUnzipF); - } - } - - String projectId = null; - String projectName = null; - - File finalProjectSmssF = null; - File finalProjectFolderF = null; - boolean projectAddedToDIHelper = false; - try { - logger.info("{}) Reading smss", step); - Properties prop = projectProperties; - projectId = prop.getProperty(Constants.PROJECT); - projectName = prop.getProperty(Constants.PROJECT_ALIAS); - - // check if project id already exists in security db - if (SecurityProjectUtils.projectExists(projectId)) { - cleanUpFolders(randomTempUnzipF); - SemossPixelException exception = new SemossPixelException( - NounMetadata.getErrorNounMessage("Project id already exists")); - exception.setContinueThreadOfExecution(false); - throw exception; - } - - logger.info("{}) Done", step); - step++; - - // zip file has the smss and project folder on the same level - // need to move these files around - String tempUnzippedProjectFolderPath = randomTempUnzipFolderPath + DIR_SEPARATOR - + SmssUtilities.getUniqueName(projectName, projectId); - File tempUnzippedProjectF = new File(Utility.normalizePath(tempUnzippedProjectFolderPath)); - finalProjectFolderF = new File(Utility.normalizePath( - projectFolderPath + DIR_SEPARATOR + SmssUtilities.getUniqueName(projectName, projectId))); - finalProjectSmssF = new File(Utility.normalizePath(projectFolderPath + DIR_SEPARATOR - + SmssUtilities.getUniqueName(projectName, projectId) + Constants.SEMOSS_EXTENSION)); - - // need to ignore file watcher - if (InternalUtility.addProjectId(projectId)) { - projectAddedToDIHelper = true; - } else { - SemossPixelException exception = new SemossPixelException( - NounMetadata.getErrorNounMessage("Project id already exists")); - exception.setContinueThreadOfExecution(false); - throw exception; - } - - // move project folder - logger.info("{}) Moving project folder", step); - FileUtils.copyDirectory(tempUnzippedProjectF, finalProjectFolderF); - logger.info("{}) Done", step); - step++; - // move smss file - logger.info("{}) Moving smss file", step); - File tempUnzippedSmssF = new File(Utility.normalizePath(randomTempUnzipF + DIR_SEPARATOR - + SmssUtilities.getUniqueName(projectName, projectId) + Constants.SEMOSS_EXTENSION)); - FileUtils.copyFile(tempUnzippedSmssF, finalProjectSmssF); - logger.info("{}) Done", step); - step++; - } catch (Exception e) { - error = true; - classLogger.error("Error copying the files over from the temp zip location to the final project folder", e); - throw new SemossPixelException(e.getMessage(), false); - } finally { - if (error) { - // remove from DIHelper - if (projectAddedToDIHelper) { - UploadUtilities.removeProjectFromDIHelper(projectId); - } - cleanUpFolders(randomTempUnzipF, finalProjectSmssF, finalProjectFolderF); - } else { - // just delete the temp project folder - cleanUpFolders(randomTempUnzipF); - } - } - - try { - InternalUtility.setProjectSmssPath(projectId, - finalProjectSmssF.getAbsolutePath()); - - // ensure PROJECT_DISPLAY_NAME is present in the smss file - // if not present, seed it from PROJECT_ALIAS so the file stays consistent - Properties smssProps = Utility.loadProperties(finalProjectSmssF.getAbsolutePath()); - String displayName = smssProps.getProperty(Constants.PROJECT_DISPLAY_NAME); - if (displayName == null || displayName.trim().isEmpty()) { - try { - InternalUtility.changePropertiesFileValue(finalProjectSmssF.getAbsolutePath(), - Constants.PROJECT_DISPLAY_NAME, projectName); - } catch (IOException e) { - classLogger.error("Failed to write {} into the smss file for project {}", - Constants.PROJECT_DISPLAY_NAME, projectId, e); - } - } - - logger.info("{}) Grabbing project insights", step); - SecurityProjectUtils.addProject(projectId, global, user); - - // see if we have any dependencies or metadata to load - { - File metadataFile = new File( - finalProjectFolderF.getAbsolutePath() + "/" + projectName + IEngine.METADATA_FILE_SUFFIX); - if (metadataFile.exists() && metadataFile.isFile()) { - Map metadata = (Map) GsonUtility.readJsonFileToObject(metadataFile, - new TypeToken>() { - }.getType()); - SecurityProjectUtils.updateProjectMetadata(projectId, metadata); - // delete this file since values can update and file is dynamically generated on - // export - metadataFile.delete(); - } - - File dependenciesFile = new File( - finalProjectFolderF.getAbsolutePath() + "/" + projectName + IProject.DEPENDENCIES_FILE_SUFFIX); - if (agentMetadata == null && dependenciesFile.exists() && dependenciesFile.isFile()) { - List> projectDependencies = (List>) GsonUtility - .readJsonFileToObject(dependenciesFile, new TypeToken>>() { - }.getType()); - // List dependentEngineIds = (List) - // GsonUtility.readJsonFileToObject(dependenciesFile, new - // TypeToken>() {}.getType()); - if (projectDependencies != null && !projectDependencies.isEmpty()) { - List dependentEngineIds = new ArrayList<>(); - for (Map dep : projectDependencies) { - dependentEngineIds.add((String) dep.get("engine_id")); - } - SecurityProjectUtils.updateProjectDependenciesWithoutType(user, projectId, dependentEngineIds); - } - // delete this file since values can update and file is dynamically generated on - // export - dependenciesFile.delete(); - } - } - - // Consume the generated archive file before the final, atomic agent import. - if (agentMetadata != null) { - AgentProjectArchiveUtils.importDependencies(finalProjectFolderF, projectName, projectId, user); - Files.delete( - new File(finalProjectFolderF, projectName + AgentProjectArchiveUtils.FILE_SUFFIX).toPath()); - AgentProjectArchiveUtils.importAgent(projectId, user, agentMetadata, false); - } - - logger.info("{}) Done", step); - } catch (Exception e) { - error = true; - classLogger.error( - "Failed to restore metadata, insights, or agent configuration for project {} from archive {}", - projectId, zipFilePath, e); - throw new SemossPixelException( - "Error occurred trying to synchronize the metadata and insights for the zip file", false); - } finally { - if (error) { - // delete all the resources - cleanUpFolders(randomTempUnzipF, finalProjectSmssF, finalProjectFolderF); - // remove from DIHelper - if (projectAddedToDIHelper) { - UploadUtilities.removeProjectFromDIHelper(projectId); - } - // delete from security - SecurityProjectUtils.deleteProject(projectId); - } - } - - // add user as engine owner - List logins = user.getLogins(); - for (AuthProvider ap : logins) { - SecurityProjectUtils.addProjectOwner(user, projectId, user.getAccessToken(ap).getId()); - } - - ClusterUtil.pushProject(projectId); - UserAuditTrailUtils.recordProjectLifecycle(user, AuditEventType.PROJECT_UPLOAD, projectId, projectName, - Map.of("global", global)); - - Map retMap = UploadUtilities.getProjectReturnData(this.insight.getUser(), projectId); - return new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, PixelOperationType.MARKET_PLACE_ADDITION); - } - - /** - * - * @param fileToDelete - */ - private void cleanUpFolders(File... fileToDelete) { - for (File f : fileToDelete) { - if (f != null && f.exists()) { - try { - FileUtils.forceDelete(f); - } catch (IOException e) { - classLogger.error("Error on clean up attempting to delete {}", f.getAbsolutePath(), e); - } - } - } - } - -} +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.project; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; + +import org.apache.commons.io.FileUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; + +import prerna.auth.AuthProvider; +import prerna.auth.User; +import prerna.auth.utils.AbstractSecurityUtils; +import prerna.auth.utils.SecurityAdminUtils; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.auth.utils.SecurityProjectUtils; +import prerna.auth.utils.SecurityQueryUtils; +import prerna.cluster.util.ClusterUtil; +import prerna.engine.api.IEngine; +import prerna.engine.impl.SmssUtilities; +import prerna.project.api.IProject; +import prerna.reactor.AbstractReactor; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.PixelOperationType; +import prerna.sablecc2.om.ReactorKeysEnum; +import prerna.sablecc2.om.execptions.SemossPixelException; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.usertracking.AuditEventType; +import prerna.usertracking.UserAuditTrailUtils; +import prerna.util.AgentProjectArchiveUtils; +import prerna.util.Constants; +import prerna.util.InternalUtility; +import prerna.util.UploadInputUtility; +import prerna.util.UploadUtilities; +import prerna.util.Utility; +import prerna.util.ZipUtils; +import prerna.util.gson.GsonUtility; + +public class UploadProjectReactor extends AbstractReactor { + + private static final Logger classLogger = LogManager.getLogger(UploadProjectReactor.class); + + private static final String CLASS_NAME = UploadProjectReactor.class.getName(); + + public UploadProjectReactor() { + this.keysToGet = new String[] { ReactorKeysEnum.FILE_PATH.getKey(), ReactorKeysEnum.SPACE.getKey(), + ReactorKeysEnum.GLOBAL.getKey() }; + } + + @Override + public NounMetadata execute() { + organizeKeys(); + Logger logger = this.getLogger(CLASS_NAME); + int step = 1; + String zipFilePath = UploadInputUtility.getFilePath(this.store, this.insight); + // do we want this project to be accessible to everyone + boolean global = Boolean.parseBoolean(this.keyValue.get(ReactorKeysEnum.GLOBAL.getKey()) + ""); + // check security + // Need to check this, will the same methods work/enhanced to check the + // permissions on project? + User user = requireUser(); + + // throw error is user doesn't have rights to publish new apps + if (AbstractSecurityUtils.adminSetPublisher() && !SecurityQueryUtils.userIsPublisher(user)) { + throwUserNotPublisherError(); + } + + // creating a temp folder to unzip project folder and smss + String randomIdAsDir = UUID.randomUUID().toString(); + String projectFolderPath = Utility.getDIHelperProperty(Constants.BASE_FOLDER) + DIR_SEPARATOR + + Constants.PROJECT_FOLDER; + String randomTempUnzipFolderPath = projectFolderPath + DIR_SEPARATOR + randomIdAsDir; + File randomTempUnzipF = new File(randomTempUnzipFolderPath); + + // gotta keep track of the smssFile and files unzipped + Map> filesAdded = new HashMap<>(); + List fileList = new ArrayList<>(); + String smssFileLoc = null; + File smssFile = null; + Properties projectProperties = null; + JsonObject agentMetadata = null; + // unzip files to temp project folder + boolean error = false; + try { + logger.info("{}) Unzipping project", step); + filesAdded = ZipUtils.unzip(zipFilePath, randomTempUnzipFolderPath); + logger.info("{}) Done", step); + step++; + + // look for smss file + fileList = filesAdded.get("FILE"); + logger.info("{}) Searching for smss", step); + for (String filePath : fileList) { + if (!filePath.startsWith("__MACOSX/") && filePath.endsWith(Constants.SEMOSS_EXTENSION)) { + smssFileLoc = randomTempUnzipFolderPath + DIR_SEPARATOR + filePath; + smssFile = new File(Utility.normalizePath(smssFileLoc)); + // check if the file exists + if (!smssFile.exists()) { + // invalid file need to delete the files unzipped + smssFileLoc = null; + } + break; + } + } + logger.info("{}) Done", step); + step++; + + // delete the files if we were unable to find the smss file + if (smssFileLoc == null) { + throw new SemossPixelException("Unable to find " + Constants.SEMOSS_EXTENSION + " file", false); + } + + projectProperties = Utility.loadProperties(smssFileLoc); + String projectTypeString = projectProperties.getProperty(Constants.PROJECT_ENUM_TYPE); + IProject.PROJECT_TYPE projectType = projectTypeString == null ? IProject.PROJECT_TYPE.INSIGHTS + : IProject.PROJECT_TYPE.valueOf(projectTypeString.trim()); + if (AbstractSecurityUtils.adminOnlyProjectAdd(projectType) && !SecurityAdminUtils.userIsAdmin(user)) { + AbstractReactor.throwFunctionalityOnlyExposedForAdminsError(); + } + if (global && AbstractSecurityUtils.adminOnlyProjectSetPublic(projectType) + && !SecurityAdminUtils.userIsAdmin(user)) { + SemossPixelException exception = new SemossPixelException(NounMetadata + .getErrorNounMessage("User can upload a project but cannot make the project public")); + exception.setContinueThreadOfExecution(false); + throw exception; + } + agentMetadata = AgentProjectArchiveUtils.readAgent(new File(randomTempUnzipF, + SmssUtilities.getUniqueName(projectProperties.getProperty(Constants.PROJECT_ALIAS), + projectProperties.getProperty(Constants.PROJECT))), + projectProperties); + } catch (SemossPixelException e) { + error = true; + throw e; + } catch (Exception e) { + error = true; + classLogger.error("Error occurred while unzipping the files", e); + throw new SemossPixelException("Error occurred while unzipping the files", false); + } finally { + if (error) { + cleanUpFolders(randomTempUnzipF); + } + } + + String projectId = null; + String projectName = null; + + File finalProjectSmssF = null; + File finalProjectFolderF = null; + boolean projectAddedToDIHelper = false; + try { + logger.info("{}) Reading smss", step); + Properties prop = projectProperties; + projectId = prop.getProperty(Constants.PROJECT); + projectName = prop.getProperty(Constants.PROJECT_ALIAS); + + // check if project id already exists in security db + if (SecurityProjectUtils.projectExists(projectId)) { + cleanUpFolders(randomTempUnzipF); + SemossPixelException exception = new SemossPixelException( + NounMetadata.getErrorNounMessage("Project id already exists")); + exception.setContinueThreadOfExecution(false); + throw exception; + } + + logger.info("{}) Done", step); + step++; + + // zip file has the smss and project folder on the same level + // need to move these files around + String tempUnzippedProjectFolderPath = randomTempUnzipFolderPath + DIR_SEPARATOR + + SmssUtilities.getUniqueName(projectName, projectId); + File tempUnzippedProjectF = new File(Utility.normalizePath(tempUnzippedProjectFolderPath)); + finalProjectFolderF = new File(Utility.normalizePath( + projectFolderPath + DIR_SEPARATOR + SmssUtilities.getUniqueName(projectName, projectId))); + finalProjectSmssF = new File(Utility.normalizePath(projectFolderPath + DIR_SEPARATOR + + SmssUtilities.getUniqueName(projectName, projectId) + Constants.SEMOSS_EXTENSION)); + + // need to ignore file watcher + if (InternalUtility.addProjectId(projectId)) { + projectAddedToDIHelper = true; + } else { + SemossPixelException exception = new SemossPixelException( + NounMetadata.getErrorNounMessage("Project id already exists")); + exception.setContinueThreadOfExecution(false); + throw exception; + } + + // move project folder + logger.info("{}) Moving project folder", step); + FileUtils.copyDirectory(tempUnzippedProjectF, finalProjectFolderF); + logger.info("{}) Done", step); + step++; + // move smss file + logger.info("{}) Moving smss file", step); + File tempUnzippedSmssF = new File(Utility.normalizePath(randomTempUnzipF + DIR_SEPARATOR + + SmssUtilities.getUniqueName(projectName, projectId) + Constants.SEMOSS_EXTENSION)); + FileUtils.copyFile(tempUnzippedSmssF, finalProjectSmssF); + logger.info("{}) Done", step); + step++; + } catch (Exception e) { + error = true; + classLogger.error("Error copying the files over from the temp zip location to the final project folder", e); + throw new SemossPixelException(e.getMessage(), false); + } finally { + if (error) { + // remove from DIHelper + if (projectAddedToDIHelper) { + UploadUtilities.removeProjectFromDIHelper(projectId); + } + cleanUpFolders(randomTempUnzipF, finalProjectSmssF, finalProjectFolderF); + } else { + // just delete the temp project folder + cleanUpFolders(randomTempUnzipF); + } + } + + try { + InternalUtility.setProjectSmssPath(projectId, + finalProjectSmssF.getAbsolutePath()); + + // ensure PROJECT_DISPLAY_NAME is present in the smss file + // if not present, seed it from PROJECT_ALIAS so the file stays consistent + Properties smssProps = Utility.loadProperties(finalProjectSmssF.getAbsolutePath()); + String displayName = smssProps.getProperty(Constants.PROJECT_DISPLAY_NAME); + if (displayName == null || displayName.trim().isEmpty()) { + try { + InternalUtility.changePropertiesFileValue(finalProjectSmssF.getAbsolutePath(), + Constants.PROJECT_DISPLAY_NAME, projectName); + } catch (IOException e) { + classLogger.error("Failed to write {} into the smss file for project {}", + Constants.PROJECT_DISPLAY_NAME, projectId, e); + } + } + + logger.info("{}) Grabbing project insights", step); + SecurityProjectUtils.addProject(projectId, global, user); + + // see if we have any dependencies or metadata to load + { + File metadataFile = new File( + finalProjectFolderF.getAbsolutePath() + "/" + projectName + IEngine.METADATA_FILE_SUFFIX); + if (metadataFile.exists() && metadataFile.isFile()) { + Map metadata = (Map) GsonUtility.readJsonFileToObject(metadataFile, + new TypeToken>() { + }.getType()); + SecurityProjectUtils.updateProjectMetadata(projectId, metadata); + // delete this file since values can update and file is dynamically generated on + // export + metadataFile.delete(); + } + + File dependenciesFile = new File( + finalProjectFolderF.getAbsolutePath() + "/" + projectName + IProject.DEPENDENCIES_FILE_SUFFIX); + if (agentMetadata == null && dependenciesFile.exists() && dependenciesFile.isFile()) { + List> projectDependencies = (List>) GsonUtility + .readJsonFileToObject(dependenciesFile, new TypeToken>>() { + }.getType()); + // List dependentEngineIds = (List) + // GsonUtility.readJsonFileToObject(dependenciesFile, new + // TypeToken>() {}.getType()); + if (projectDependencies != null && !projectDependencies.isEmpty()) { + // reads exports from this release and older ones, with each type + SecurityCatalogDependencyUtils.setDependencies(user, projectId, + SecurityCatalogDependencyUtils.resolveCatalogType(projectId, null), + SecurityCatalogDependencyUtils.fromExported(projectDependencies)); + } + // delete this file since values can update and file is dynamically generated on + // export + dependenciesFile.delete(); + } + } + + // Consume the generated archive file before the final, atomic agent import. + if (agentMetadata != null) { + AgentProjectArchiveUtils.importDependencies(finalProjectFolderF, projectName, projectId, user); + Files.delete( + new File(finalProjectFolderF, projectName + AgentProjectArchiveUtils.FILE_SUFFIX).toPath()); + AgentProjectArchiveUtils.importAgent(projectId, user, agentMetadata, false); + } + + logger.info("{}) Done", step); + } catch (Exception e) { + error = true; + classLogger.error( + "Failed to restore metadata, insights, or agent configuration for project {} from archive {}", + projectId, zipFilePath, e); + throw new SemossPixelException( + "Error occurred trying to synchronize the metadata and insights for the zip file", false); + } finally { + if (error) { + // delete all the resources + cleanUpFolders(randomTempUnzipF, finalProjectSmssF, finalProjectFolderF); + // remove from DIHelper + if (projectAddedToDIHelper) { + UploadUtilities.removeProjectFromDIHelper(projectId); + } + // delete from security + SecurityProjectUtils.deleteProject(projectId); + } + } + + // add user as engine owner + List logins = user.getLogins(); + for (AuthProvider ap : logins) { + SecurityProjectUtils.addProjectOwner(user, projectId, user.getAccessToken(ap).getId()); + } + + ClusterUtil.pushProject(projectId); + UserAuditTrailUtils.recordProjectLifecycle(user, AuditEventType.PROJECT_UPLOAD, projectId, projectName, + Map.of("global", global)); + + Map retMap = UploadUtilities.getProjectReturnData(this.insight.getUser(), projectId); + return new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, PixelOperationType.MARKET_PLACE_ADDITION); + } + + /** + * + * @param fileToDelete + */ + private void cleanUpFolders(File... fileToDelete) { + for (File f : fileToDelete) { + if (f != null && f.exists()) { + try { + FileUtils.forceDelete(f); + } catch (IOException e) { + classLogger.error("Error on clean up attempting to delete {}", f.getAbsolutePath(), e); + } + } + } + } + +} diff --git a/src/prerna/reactor/security/CatalogDependencyKeys.java b/src/prerna/reactor/security/CatalogDependencyKeys.java new file mode 100644 index 00000000000..47ac8a8d44e --- /dev/null +++ b/src/prerna/reactor/security/CatalogDependencyKeys.java @@ -0,0 +1,22 @@ +package prerna.reactor.security; + +/** + * The keys of the catalog dependency reactors + */ +final class CatalogDependencyKeys { + + /** The engine id or project id whose dependencies are read or set */ + static final String CATALOG_ID = "catalogId"; + /** + * Its engine type or project type, such as FUNCTION or SKILL. Optional: it is + * read from the security database when not given, and checked against it when + * given. + */ + static final String CATALOG_TYPE = "catalogType"; + /** The dependencies to set, each as a map of id and type */ + static final String DEPENDENCIES = "dependencies"; + + private CatalogDependencyKeys() { + + } +} diff --git a/src/prerna/reactor/security/GetProjectDependenciesReactor.java b/src/prerna/reactor/security/GetCatalogDependenciesReactor.java similarity index 85% rename from src/prerna/reactor/security/GetProjectDependenciesReactor.java rename to src/prerna/reactor/security/GetCatalogDependenciesReactor.java index c5b5abd9391..6baa821ae0f 100644 --- a/src/prerna/reactor/security/GetProjectDependenciesReactor.java +++ b/src/prerna/reactor/security/GetCatalogDependenciesReactor.java @@ -1,219 +1,221 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.security; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import prerna.auth.AccessPermissionEnum; -import prerna.auth.User; -import prerna.auth.utils.SecurityProjectUtils; -import prerna.reactor.ReactorDefinition; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.util.UploadInputUtility; - -public class GetProjectDependenciesReactor extends AbstractSetMetadataReactor { - - public GetProjectDependenciesReactor() { - this.keysToGet = new String[] { ReactorKeysEnum.PROJECT.getKey() }; - } - - @Override - public NounMetadata execute() { - organizeKeys(); - User user = this.insight.getUser(); - String projectId = UploadInputUtility.getProjectNameOrId(this.store); - if (!SecurityProjectUtils.userCanViewProject(user, projectId)) { - throw new IllegalArgumentException( - "The user does not have access to view this project or project id is invalid"); - } - - // Get all dependencies with subdependencies - List> dependencies = SecurityProjectUtils.getProjectDependencyDetails(projectId, user, - true); - - // Build graph structure with unique nodes and their direct dependencies - Map dependencyGraph = buildDependencyGraph(dependencies, projectId); - - return new NounMetadata(dependencyGraph, PixelDataType.MAP); - } - - /** - * Build a graph structure from flat list of dependencies where each engine - * appears once. Only includes engines that are reachable following access - * rules. - * - * @param dependencies Flat list of all dependencies - * @param rootProjectId The root project ID - * @return Graph structure with unique engines and direct dependency lists - */ - private Map buildDependencyGraph(List> dependencies, String rootProjectId) { - // Build maps for quick lookup - Map> allEnginesMap = new HashMap<>(); - Map> childrenByParent = new HashMap<>(); - - for (Map dep : dependencies) { - String parentId = (String) dep.get("parent_id"); - String engineId = (String) dep.get("engine_id"); - - // Store in engine map (avoid duplicates by using engineId as key) - allEnginesMap.putIfAbsent(engineId, dep); - - // Build parent-child relationships (use Set to avoid duplicates) - if (parentId != null) { - childrenByParent.computeIfAbsent(parentId, k -> new LinkedHashSet<>()).add(engineId); - } - } - - // Traverse from root to find all reachable engines based on access rules - Map> reachableEngines = new HashMap<>(); - Set rootDependencies = childrenByParent.get(rootProjectId); - if (rootDependencies == null) { - rootDependencies = new LinkedHashSet<>(); - } - - // Traverse and collect reachable engines - traverseReachable(rootProjectId, allEnginesMap, childrenByParent, reachableEngines); - - // Build the final engines list with filtered dependencies - List> engines = new ArrayList<>(); - for (Map.Entry> entry : reachableEngines.entrySet()) { - String engineId = entry.getKey(); - Map originalEngine = entry.getValue(); - - // Create engine object with all metadata except parent_id - Map engine = new HashMap<>(originalEngine); - engine.remove("parent_id"); - - // Derive permission_name from the highest permission (lowest integer id) the - // user holds, considering both direct and group permissions - Integer directPerm = (Integer) engine.get("permission"); - Integer groupPerm = (Integer) engine.get("group_permission"); - Integer bestPermission = null; - if (directPerm != null && groupPerm != null) { - bestPermission = Math.min(directPerm, groupPerm); - } else if (directPerm != null) { - bestPermission = directPerm; - } else if (groupPerm != null) { - bestPermission = groupPerm; - } - if (bestPermission != null) { - engine.put("permission_name", AccessPermissionEnum.getPermissionValueById(bestPermission)); - } - - // Check if user has access to this engine - Integer permission = (Integer) originalEngine.get("permission"); - Integer groupPermission = (Integer) originalEngine.get("group_permission"); - Boolean isGlobal = (Boolean) originalEngine.get("engine_global"); - boolean hasAccess = (permission != null) || (groupPermission != null) || (isGlobal != null && isGlobal); - - // Only show dependencies if user has access to this engine - if (hasAccess) { - // Add dependencies - only include children that are reachable - Set allChildren = childrenByParent.get(engineId); - List reachableChildren = new ArrayList<>(); - if (allChildren != null) { - for (String childId : allChildren) { - if (reachableEngines.containsKey(childId)) { - reachableChildren.add(childId); - } - } - } - engine.put("dependencies", reachableChildren); - } - - engines.add(engine); - } - - // Filter root dependencies to only include reachable ones - List filteredRootDeps = new ArrayList<>(); - for (String depId : rootDependencies) { - if (reachableEngines.containsKey(depId)) { - filteredRootDeps.add(depId); - } - } - - // Build result structure - Map result = new HashMap<>(); - result.put("engines", engines); - result.put("dependencies", filteredRootDeps); - - return result; - } - - /** - * Recursively traverse and collect reachable engines based on access rules. - - * Direct children of accessible parents are always visible - Children's - * dependencies are only explored if user has access to the child - * - * @param parentId The current parent engine ID - * @param allEnginesMap Map of all engine IDs to their full data - * @param childrenByParent Map of parent ID to set of child engine IDs - * @param reachableEngines Accumulator for reachable engines - */ - private void traverseReachable(String parentId, Map> allEnginesMap, - Map> childrenByParent, Map> reachableEngines) { - Set children = childrenByParent.get(parentId); - if (children == null || children.isEmpty()) { - return; - } - - for (String childId : children) { - Map childEngine = allEnginesMap.get(childId); - if (childEngine == null || reachableEngines.containsKey(childId)) { - continue; - } - - // Always add direct children (they're visible if parent is accessible) - reachableEngines.put(childId, childEngine); - - // Only traverse into child's dependencies if user has access to the child - Integer permission = (Integer) childEngine.get("permission"); - Integer groupPermission = (Integer) childEngine.get("group_permission"); - Boolean isGlobal = (Boolean) childEngine.get("engine_global"); - boolean hasAccess = (permission != null) || (groupPermission != null) || (isGlobal != null && isGlobal); - - if (hasAccess) { - traverseReachable(childId, allEnginesMap, childrenByParent, reachableEngines); - } - } - } - - @Override - public ReactorDefinition getReactorDefinition() { - return super.getReactorDefinition() - .description("Get project dependencies as a graph with unique engines and their direct dependencies"); - } - +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.security; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import prerna.auth.AccessPermissionEnum; +import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.nounmeta.NounMetadata; + +public class GetCatalogDependenciesReactor extends AbstractReactor { + + public GetCatalogDependenciesReactor() { + this.keysToGet = new String[] { CatalogDependencyKeys.CATALOG_ID, CatalogDependencyKeys.CATALOG_TYPE }; + this.keyRequired = new int[] { 1, 0 }; + } + + @Override + public NounMetadata execute() { + organizeKeys(); + User user = this.insight.getUser(); + String catalogId = this.keyValue.get(CatalogDependencyKeys.CATALOG_ID); + String catalogType = SecurityCatalogDependencyUtils.resolveCatalogType(catalogId, + this.keyValue.get(CatalogDependencyKeys.CATALOG_TYPE)); + if (!SecurityCatalogDependencyUtils.userCanView(user, catalogId, catalogType)) { + throw new IllegalArgumentException("The user does not have access to view " + catalogId); + } + + // Get all dependencies with subdependencies + List> dependencies = SecurityCatalogDependencyUtils.getDependencyDetails(catalogId, user, + true); + + // Build graph structure with unique nodes and their direct dependencies + Map dependencyGraph = buildDependencyGraph(dependencies, catalogId); + + return new NounMetadata(dependencyGraph, PixelDataType.MAP); + } + + /** + * Build a graph structure from flat list of dependencies where each engine + * appears once. Only includes engines that are reachable following access + * rules. + * + * @param dependencies Flat list of all dependencies + * @param rootProjectId The root project ID + * @return Graph structure with unique engines and direct dependency lists + */ + private Map buildDependencyGraph(List> dependencies, String rootProjectId) { + // Build maps for quick lookup + Map> allEnginesMap = new HashMap<>(); + Map> childrenByParent = new HashMap<>(); + + for (Map dep : dependencies) { + String parentId = (String) dep.get("parent_id"); + String engineId = (String) dep.get("catalog_id"); + + // Store in engine map (avoid duplicates by using engineId as key) + allEnginesMap.putIfAbsent(engineId, dep); + + // Build parent-child relationships (use Set to avoid duplicates) + if (parentId != null) { + childrenByParent.computeIfAbsent(parentId, k -> new LinkedHashSet<>()).add(engineId); + } + } + + // Traverse from root to find all reachable engines based on access rules + Map> reachableEngines = new HashMap<>(); + Set rootDependencies = childrenByParent.get(rootProjectId); + if (rootDependencies == null) { + rootDependencies = new LinkedHashSet<>(); + } + + // Traverse and collect reachable engines + traverseReachable(rootProjectId, allEnginesMap, childrenByParent, reachableEngines); + + // Build the final engines list with filtered dependencies + List> engines = new ArrayList<>(); + for (Map.Entry> entry : reachableEngines.entrySet()) { + String engineId = entry.getKey(); + Map originalEngine = entry.getValue(); + + // Create engine object with all metadata except parent_id + Map engine = new HashMap<>(originalEngine); + engine.remove("parent_id"); + + // Derive permission_name from the highest permission (lowest integer id) the + // user holds, considering both direct and group permissions + Integer directPerm = (Integer) engine.get("permission"); + Integer groupPerm = (Integer) engine.get("group_permission"); + Integer bestPermission = null; + if (directPerm != null && groupPerm != null) { + bestPermission = Math.min(directPerm, groupPerm); + } else if (directPerm != null) { + bestPermission = directPerm; + } else if (groupPerm != null) { + bestPermission = groupPerm; + } + if (bestPermission != null) { + engine.put("permission_name", AccessPermissionEnum.getPermissionValueById(bestPermission)); + } + + // Check if user has access to this engine + Integer permission = (Integer) originalEngine.get("permission"); + Integer groupPermission = (Integer) originalEngine.get("group_permission"); + Boolean isGlobal = (Boolean) originalEngine.get("catalog_global"); + boolean hasAccess = (permission != null) || (groupPermission != null) || (isGlobal != null && isGlobal); + + // Only show dependencies if user has access to this engine + if (hasAccess) { + // Add dependencies - only include children that are reachable + Set allChildren = childrenByParent.get(engineId); + List reachableChildren = new ArrayList<>(); + if (allChildren != null) { + for (String childId : allChildren) { + if (reachableEngines.containsKey(childId)) { + reachableChildren.add(childId); + } + } + } + engine.put("dependencies", reachableChildren); + } + + engines.add(engine); + } + + // Filter root dependencies to only include reachable ones + List filteredRootDeps = new ArrayList<>(); + for (String depId : rootDependencies) { + if (reachableEngines.containsKey(depId)) { + filteredRootDeps.add(depId); + } + } + + // Build result structure + Map result = new HashMap<>(); + result.put("dependencies", engines); + result.put("dependencyIds", filteredRootDeps); + + return result; + } + + /** + * Recursively traverse and collect reachable engines based on access rules. - + * Direct children of accessible parents are always visible - Children's + * dependencies are only explored if user has access to the child + * + * @param parentId The current parent engine ID + * @param allEnginesMap Map of all engine IDs to their full data + * @param childrenByParent Map of parent ID to set of child engine IDs + * @param reachableEngines Accumulator for reachable engines + */ + private void traverseReachable(String parentId, Map> allEnginesMap, + Map> childrenByParent, Map> reachableEngines) { + Set children = childrenByParent.get(parentId); + if (children == null || children.isEmpty()) { + return; + } + + for (String childId : children) { + Map childEngine = allEnginesMap.get(childId); + if (childEngine == null || reachableEngines.containsKey(childId)) { + continue; + } + + // Always add direct children (they're visible if parent is accessible) + reachableEngines.put(childId, childEngine); + + // Only traverse into child's dependencies if user has access to the child + Integer permission = (Integer) childEngine.get("permission"); + Integer groupPermission = (Integer) childEngine.get("group_permission"); + Boolean isGlobal = (Boolean) childEngine.get("catalog_global"); + boolean hasAccess = (permission != null) || (groupPermission != null) || (isGlobal != null && isGlobal); + + if (hasAccess) { + traverseReachable(childId, allEnginesMap, childrenByParent, reachableEngines); + } + } + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition() + .description("Get the engines and projects an engine or project depends on, all the way down, each once with " + + "its direct dependencies"); + } + } \ No newline at end of file diff --git a/src/prerna/reactor/security/SetCatalogDependenciesReactor.java b/src/prerna/reactor/security/SetCatalogDependenciesReactor.java new file mode 100644 index 00000000000..c05b40be126 --- /dev/null +++ b/src/prerna/reactor/security/SetCatalogDependenciesReactor.java @@ -0,0 +1,99 @@ +package prerna.reactor.security; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import prerna.auth.User; +import prerna.auth.utils.CatalogTypes; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.GenRowStruct; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.nounmeta.NounMetadata; + +/** + * Replaces the dependencies of an engine or a project with the engines and + * projects given. Each is checked against the security database alone, so this + * works on any server of a cluster. + */ +public class SetCatalogDependenciesReactor extends AbstractReactor { + + public SetCatalogDependenciesReactor() { + this.keysToGet = new String[] { CatalogDependencyKeys.CATALOG_ID, CatalogDependencyKeys.CATALOG_TYPE, + CatalogDependencyKeys.DEPENDENCIES }; + this.keyRequired = new int[] { 1, 0, 0 }; + } + + @Override + public NounMetadata execute() { + organizeKeys(); + User user = this.insight.getUser(); + String catalogId = this.keyValue.get(CatalogDependencyKeys.CATALOG_ID); + String catalogType = SecurityCatalogDependencyUtils.resolveCatalogType(catalogId, + this.keyValue.get(CatalogDependencyKeys.CATALOG_TYPE)); + if (!SecurityCatalogDependencyUtils.userCanEdit(user, catalogId, catalogType)) { + throw new IllegalArgumentException("The user does not have access to edit " + catalogId); + } + + List dependencies = new ArrayList<>(); + for (Map entry : getDependencyMaps()) { + Object id = entry.get("id"); + Object type = entry.get("type"); + if (!(id instanceof String) || !(type instanceof String)) { + throw new IllegalArgumentException("Each dependency needs an id and a type"); + } + String dependencyId = (String) id; + if (dependencyId.equals(catalogId)) { + throw new IllegalArgumentException("An engine or project cannot depend on itself"); + } + String dependencyType = CatalogTypes.normalize((String) type); + String stored = CatalogTypes.resolve(dependencyId); + if (stored == null) { + throw new IllegalArgumentException("No engine or project has the id '" + dependencyId + "'"); + } + if (!stored.equals(dependencyType)) { + throw new IllegalArgumentException( + "'" + dependencyId + "' is a " + stored + ", not a " + dependencyType); + } + dependencies.add(new Dependency(dependencyId, dependencyType)); + } + + SecurityCatalogDependencyUtils.setDependencies(user, catalogId, catalogType, dependencies); + + NounMetadata noun = new NounMetadata(true, PixelDataType.BOOLEAN); + noun.addAdditionalReturn(NounMetadata.getSuccessNounMessage("Successfully set the new dependencies")); + return noun; + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition() + .description("Set the engines and projects an engine or project depends on") + .key(CatalogDependencyKeys.CATALOG_ID, "The engine id or project id") + .key(CatalogDependencyKeys.CATALOG_TYPE, + "Its engine type or project type, such as FUNCTION or SKILL; read when not given") + .key(CatalogDependencyKeys.DEPENDENCIES, + "The engines and projects it depends on, each as {id, type} with its own engine type or " + + "project type. An empty list removes them all."); + } + + @SuppressWarnings("unchecked") + private List> getDependencyMaps() { + List> dependencyList = new ArrayList<>(); + GenRowStruct grs = this.store.getGenRowStruct(CatalogDependencyKeys.DEPENDENCIES); + if (grs != null && !grs.isEmpty()) { + for (int i = 0; i < grs.size(); i++) { + Object value = grs.get(i); + if (!(value instanceof Map)) { + throw new IllegalArgumentException("Each dependency must be a map of id and type"); + } + dependencyList.add((Map) value); + } + } + return dependencyList; + } + +} diff --git a/src/prerna/reactor/security/SetProjectDependenciesReactor.java b/src/prerna/reactor/security/SetProjectDependenciesReactor.java deleted file mode 100644 index 93d6169bac1..00000000000 --- a/src/prerna/reactor/security/SetProjectDependenciesReactor.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.security; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import prerna.auth.User; -import prerna.auth.utils.SecurityEngineUtils; -import prerna.auth.utils.SecurityProjectUtils; -import prerna.engine.api.IEngine; -import prerna.reactor.ReactorDefinition; -import prerna.sablecc2.om.GenRowStruct; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.util.UploadInputUtility; - -public class SetProjectDependenciesReactor extends AbstractSetMetadataReactor { - - private static final Logger classLogger = LogManager.getLogger(SetProjectDependenciesReactor.class); - - public SetProjectDependenciesReactor() { - this.keysToGet = new String[] { ReactorKeysEnum.PROJECT.getKey(), "dependencies" }; - } - - @Override - public NounMetadata execute() { - organizeKeys(); - User user = this.insight.getUser(); - String projectId = UploadInputUtility.getProjectNameOrId(this.store); - if (!SecurityProjectUtils.userCanEditProject(user, projectId)) { - throw new IllegalArgumentException( - "The user does not have access to edit this project or project id is invalid"); - } - - List> depEngines = getDependentEnginesList(); - List> dependencyList = new ArrayList<>(); - for (Map depEngine : depEngines) { - if (depEngine.containsKey("id") && depEngine.containsKey("type")) { - String eType = ((String) depEngine.get("type")).toUpperCase(); - String eId = (String) depEngine.get("id"); - if (IEngine.CATALOG_TYPE.valueOf(eType) != IEngine.CATALOG_TYPE.PROJECT) { - if (!SecurityEngineUtils.containsEngineId(eId)) { - throw new IllegalArgumentException("Engine id = '" + eId + "' does not exist"); - } - } else { - if (!SecurityProjectUtils.containsProjectId(eId)) { - throw new IllegalArgumentException("Project id = '" + eId + "' does not exist"); - } - } - if (eId.equals(projectId)) { - throw new IllegalArgumentException("Cannot add current project as a dependency"); - } - Map dependencyEntry = new HashMap<>(); - dependencyEntry.put("ENGINEID", eId); - dependencyEntry.put("ENGINETYPE", eType); - dependencyList.add(dependencyEntry); - } else { - throw new IllegalArgumentException("Engine is missing id or type"); - } - } - - SecurityProjectUtils.updateProjectDependencies(user, projectId, dependencyList); - - NounMetadata noun = new NounMetadata(true, PixelDataType.BOOLEAN); - noun.addAdditionalReturn(NounMetadata.getSuccessNounMessage("Successfully set the new dependencies")); - return noun; - } - - @Override - public ReactorDefinition getReactorDefinition() { - return super.getReactorDefinition().description("Set the engine dependencies for a project").key("dependencies", - "The list of engineid's that this project depends on for full functionality"); - } - - @SuppressWarnings("unchecked") - private List> getDependentEnginesList() { - List> dependencyList = new ArrayList<>(); - GenRowStruct grs = this.store.getGenRowStruct("dependencies"); - if (grs != null && !grs.isEmpty()) { - int size = grs.size(); - for (int i = 0; i < size; i++) { - dependencyList.add((Map) grs.get(i)); - } - } - return dependencyList; - } - -} diff --git a/src/prerna/reactor/security/ValidateCatalogDependenciesReactor.java b/src/prerna/reactor/security/ValidateCatalogDependenciesReactor.java new file mode 100644 index 00000000000..021eda4b29e --- /dev/null +++ b/src/prerna/reactor/security/ValidateCatalogDependenciesReactor.java @@ -0,0 +1,47 @@ +package prerna.reactor.security; + +import java.util.Map; + +import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.nounmeta.NounMetadata; + +/** + * Whether the user can view each engine and project an engine or project + * depends on, all the way down. Reads the security database alone, so it works + * on any server of a cluster. + */ +public class ValidateCatalogDependenciesReactor extends AbstractReactor { + + public ValidateCatalogDependenciesReactor() { + this.keysToGet = new String[] { CatalogDependencyKeys.CATALOG_ID, CatalogDependencyKeys.CATALOG_TYPE }; + this.keyRequired = new int[] { 1, 0 }; + } + + @Override + public NounMetadata execute() { + organizeKeys(); + User user = this.insight.getUser(); + String catalogId = this.keyValue.get(CatalogDependencyKeys.CATALOG_ID); + String catalogType = SecurityCatalogDependencyUtils.resolveCatalogType(catalogId, + this.keyValue.get(CatalogDependencyKeys.CATALOG_TYPE)); + if (!SecurityCatalogDependencyUtils.userCanView(user, catalogId, catalogType)) { + throw new IllegalArgumentException("The user does not have access to view " + catalogId); + } + Map canView = SecurityCatalogDependencyUtils.validateDependencies(user, catalogId); + return new NounMetadata(canView, PixelDataType.MAP); + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition() + .description("Whether the user can view each engine and project an engine or project depends on") + .key(CatalogDependencyKeys.CATALOG_ID, "The engine id or project id") + .key(CatalogDependencyKeys.CATALOG_TYPE, + "Its engine type or project type, such as FUNCTION or SKILL; read when not given"); + } + +} diff --git a/src/prerna/reactor/security/ValidateProjectDependenciesReactor.java b/src/prerna/reactor/security/ValidateProjectDependenciesReactor.java deleted file mode 100644 index 85f393ba9dc..00000000000 --- a/src/prerna/reactor/security/ValidateProjectDependenciesReactor.java +++ /dev/null @@ -1,96 +0,0 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.security; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import prerna.auth.User; -import prerna.auth.utils.SecurityEngineUtils; -import prerna.auth.utils.SecurityProjectUtils; -import prerna.engine.api.IEngine; -import prerna.project.api.IProject; -import prerna.project.impl.notebook.INotebookHelper; -import prerna.reactor.AbstractReactor; -import prerna.reactor.ReactorDefinition; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.execptions.SemossPixelException; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.util.Utility; - -public class ValidateProjectDependenciesReactor extends AbstractReactor { - - private static final Logger classLogger = LogManager.getLogger(ValidateProjectDependenciesReactor.class); - - public ValidateProjectDependenciesReactor() { - this.keysToGet = new String[] { ReactorKeysEnum.PROJECT.getKey() }; - this.keyRequired = new int[] { 1 }; - } - - @Override - public NounMetadata execute() { - organizeKeys(); - User user = this.insight.getUser(); - String projectId = this.keyValue.get(this.keysToGet[0]); - if (!SecurityProjectUtils.userCanViewProject(this.insight.getUser(), projectId)) { - // you don't have access - throw new IllegalArgumentException( - "Project/App does not exist or user does not have access to the project"); - } - - List> projectDependencies = SecurityProjectUtils.getProjectDependencies(projectId, true); - Map dependencyMap = new HashMap<>(); - for (Map dep : projectDependencies) { - String engineId = (String) dep.get("engine_id"); - String engineType = (String) dep.get("engine_type"); - - boolean canView = false; - if (engineType == null || IEngine.CATALOG_TYPE.valueOf(engineType) != IEngine.CATALOG_TYPE.PROJECT) { - canView = SecurityEngineUtils.userCanViewEngine(user, engineId); - } else { - canView = SecurityProjectUtils.userCanViewProject(user, engineId); - } - dependencyMap.put(engineId, canView); - } - - NounMetadata noun = new NounMetadata(dependencyMap, PixelDataType.MAP); - return noun; - } - - @Override - public ReactorDefinition getReactorDefinition() { - return super.getReactorDefinition() - .description("Return true if the user has access to all engine dependencies listed in this project"); - } - -} diff --git a/src/prerna/reactor/security/ValidateUserProjectDependenciesReactor.java b/src/prerna/reactor/security/ValidateUserProjectDependenciesReactor.java deleted file mode 100644 index 820095decaf..00000000000 --- a/src/prerna/reactor/security/ValidateUserProjectDependenciesReactor.java +++ /dev/null @@ -1,86 +0,0 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.security; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import prerna.auth.User; -import prerna.auth.utils.SecurityEngineUtils; -import prerna.auth.utils.SecurityProjectUtils; -import prerna.engine.api.IEngine; -import prerna.reactor.ReactorDefinition; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.util.UploadInputUtility; - -public class ValidateUserProjectDependenciesReactor extends AbstractSetMetadataReactor { - - public ValidateUserProjectDependenciesReactor() { - this.keysToGet = new String[] { ReactorKeysEnum.PROJECT.getKey() }; - } - - @Override - public NounMetadata execute() { - organizeKeys(); - User user = this.insight.getUser(); - String projectId = UploadInputUtility.getProjectNameOrId(this.store); - if (!SecurityProjectUtils.userCanViewProject(user, projectId)) { - throw new IllegalArgumentException( - "The user does not have access to view this project or project id is invalid"); - } - - Map hasAccess = new HashMap<>(); - - List> dependentEngines = SecurityProjectUtils.getProjectDependencies(projectId, true); - for (Map depEngine : dependentEngines) { - String depEngineId = (String) depEngine.get("engine_id"); - String depEngineType = (String) depEngine.get("engine_type"); - - if (depEngineType == null || IEngine.CATALOG_TYPE.valueOf(depEngineType) != IEngine.CATALOG_TYPE.PROJECT) { - boolean canView = SecurityEngineUtils.userCanViewEngine(user, depEngineId); - hasAccess.put(depEngineId, canView); - } else { - boolean canView = SecurityProjectUtils.userCanViewProject(user, depEngineId); - hasAccess.put(depEngineId, canView); - } - } - - NounMetadata noun = new NounMetadata(hasAccess, PixelDataType.MAP); - return noun; - } - - @Override - public ReactorDefinition getReactorDefinition() { - return super.getReactorDefinition().description( - "Return a map {'engineid':true/false} for the users access to each engine dependency listed in this project"); - } - -} diff --git a/src/prerna/reactor/utils/ExportProjectAppReactor.java b/src/prerna/reactor/utils/ExportProjectAppReactor.java index 3b912e429aa..097c16af861 100644 --- a/src/prerna/reactor/utils/ExportProjectAppReactor.java +++ b/src/prerna/reactor/utils/ExportProjectAppReactor.java @@ -1,224 +1,225 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.utils; - -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.zip.ZipOutputStream; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import prerna.auth.User; -import prerna.auth.utils.SecurityProjectUtils; -import prerna.engine.api.IEngine; -import prerna.engine.impl.SmssUtilities; -import prerna.om.InsightFile; -import prerna.project.api.IProject; -import prerna.reactor.AbstractReactor; -import prerna.reactor.ReactorDefinition; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.PixelOperationType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.execptions.SemossPixelException; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.usertracking.UserAuditTrailUtils; -import prerna.util.AgentProjectArchiveUtils; -import prerna.util.AssetUtility; -import prerna.util.Constants; -import prerna.util.Utility; -import prerna.util.ZipUtils; - -public class ExportProjectAppReactor extends AbstractReactor { - - private static final Logger classLogger = LogManager.getLogger(ExportProjectAppReactor.class); - - private static final String CLASS_NAME = ExportProjectAppReactor.class.getName(); - - public ExportProjectAppReactor() { - this.keysToGet = new String[] { ReactorKeysEnum.PROJECT.getKey() }; - } - - @Override - public NounMetadata execute() { - Logger logger = getLogger(CLASS_NAME); - logger.info("Checking project information and user permissions."); - organizeKeys(); - String projectId = this.keyValue.get(this.keysToGet[0]); - - User user = this.insight.getUser(); - boolean isOwner = SecurityProjectUtils.userIsOwner(user, projectId); - if (!isOwner) { - throw new IllegalArgumentException( - "Project " + projectId + "does not exist or user does not have access to export."); - } - - logger.info("Exporting project now..."); - String baseFolder = Utility.getDIHelperProperty(Constants.BASE_FOLDER).replace("\\", "/"); - if (!baseFolder.endsWith("/")) { - baseFolder += "/"; - } - IProject project = Utility.getProject(projectId); - String projectName = project.getProjectName(); - String projectNameAndId = SmssUtilities.getUniqueName(projectName, projectId); - String baseProjectDir = baseFolder + Constants.PROJECT_FOLDER; - String projectAssetFolder = AssetUtility.getProjectAssetsFolder(projectName, projectId); - - String outputDir = this.insight.getInsightFolder(); - String zipFilePath = outputDir + "/" + getFileName(projectNameAndId); - - // since we do not include the insights database and it is auto generated - // we dont need to lock anymore - - // ReentrantLock lock = null; - // if(project.holdsFileLocks()) { - // lock = ProjectSyncUtility.getProjectLock(projectId); - // lock.lock(); - // } - // boolean closed = false; - try { - // zip project - ZipOutputStream zos = null; - try { - // if(lock != null) { - // logger.info("Stopping the engine... "); - // DIHelper.getInstance().removeProjectProperty(projectId); - // try { - // project.close(); - // closed = true; - // } catch (IOException e) { - // classLogger.error("Failed to close project {} before export", projectId, e); - // } - // } else { - logger.info("Can export this project w/o closing... "); - // } - - // zip project folder - logger.info("Zipping project app files..."); - zos = ZipUtils.zipFolder(projectAssetFolder, zipFilePath, null, null); - logger.info("Done zipping project app files..."); - - // zip up the project metadata - { - logger.info("Grabbing project metadata to write to temporary file to zip..."); - Map projectMeta = SecurityProjectUtils.getAggregateProjectMetadata(projectId, null, - false); - ZipUtils.zipObjectToFile(zos, null, outputDir + "/" + projectName + IEngine.METADATA_FILE_SUFFIX, - projectMeta); - logger.info("Done zipping project metadata..."); - } - - // zip up the project dependencies - { - logger.info("Grabbing project dependencies to write to temporary file to zip..."); - List> projectDependencies = SecurityProjectUtils - .getProjectDependencyDetails(projectId, false); - ZipUtils.zipObjectToFile(zos, null, - outputDir + "/" + projectName + IProject.DEPENDENCIES_FILE_SUFFIX, projectDependencies); - logger.info("Done zipping project dependencies..."); - } - - AgentProjectArchiveUtils.exportAgent(zos, project, null); - - // add smss file - logger.info("Zipping project smss..."); - File smss = new File(baseProjectDir + "/" + projectNameAndId + ".smss"); - ZipUtils.addToZipFile(smss, zos); - logger.info("Done zipping project smss files..."); - logger.info("Zipping Complete"); - } catch (Exception e) { - classLogger.error("Failed to export project {} to archive {}", projectId, zipFilePath, e); - throw new SemossPixelException( - "Error occurred generating zip file. Detailed message = " + e.getMessage()); - } finally { - try { - if (zos != null) { - zos.flush(); - zos.close(); - } - } catch (IOException e) { - classLogger.error("Failed to finish writing the export archive {} for project {}", zipFilePath, - projectId, e); - } - } - } finally { - // since we do not include the insights database and it is auto generated - // we dont need to lock anymore - - // lock.unlock(); - // // open it back up - // try { - // if(closed) { - // logger.info("Opening the project again ... "); - // Utility.getProject(projectId); - // logger.info("Opened the project"); - // } - // } finally { - // if(lock != null) { - // // in case opening up causing an issue - we always want to unlock - // lock.unlock(); - // } - // } - } - - // recorded once the archive is built, so an export that fails records only its - // failure; an app's files never include the version history - IProject.PROJECT_TYPE projectType = project.getProjectType(); - UserAuditTrailUtils.recordProjectExport(user, projectId, projectName, - projectType == null ? null : projectType.name(), getPixelName(), null); - - // Generate a new key for the name of the zip file. - String downloadKey = UUID.randomUUID().toString(); - InsightFile insightFile = new InsightFile(); - insightFile.setFileKey(downloadKey); - insightFile.setDeleteOnInsightClose(true); - insightFile.setFilePath(zipFilePath); - this.insight.addExportFile(downloadKey, insightFile); - return new NounMetadata(downloadKey, PixelDataType.CONST_STRING, PixelOperationType.FILE_DOWNLOAD); - } - - /** - * - * @param projectNameAndId - * @return - */ - protected String getFileName(String projectNameAndId) { - return projectNameAndId + "_app.zip"; - } - - @Override - public ReactorDefinition getReactorDefinition() { - return super.getReactorDefinition().description("Export an app as a single zip file").key( - ReactorKeysEnum.PROJECT, - "This is a required value containing the id of the app that is being exported"); - } - -} +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.utils; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.zip.ZipOutputStream; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.auth.utils.SecurityProjectUtils; +import prerna.engine.api.IEngine; +import prerna.engine.impl.SmssUtilities; +import prerna.om.InsightFile; +import prerna.project.api.IProject; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.PixelOperationType; +import prerna.sablecc2.om.ReactorKeysEnum; +import prerna.sablecc2.om.execptions.SemossPixelException; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.usertracking.UserAuditTrailUtils; +import prerna.util.AgentProjectArchiveUtils; +import prerna.util.AssetUtility; +import prerna.util.Constants; +import prerna.util.Utility; +import prerna.util.ZipUtils; + +public class ExportProjectAppReactor extends AbstractReactor { + + private static final Logger classLogger = LogManager.getLogger(ExportProjectAppReactor.class); + + private static final String CLASS_NAME = ExportProjectAppReactor.class.getName(); + + public ExportProjectAppReactor() { + this.keysToGet = new String[] { ReactorKeysEnum.PROJECT.getKey() }; + } + + @Override + public NounMetadata execute() { + Logger logger = getLogger(CLASS_NAME); + logger.info("Checking project information and user permissions."); + organizeKeys(); + String projectId = this.keyValue.get(this.keysToGet[0]); + + User user = this.insight.getUser(); + boolean isOwner = SecurityProjectUtils.userIsOwner(user, projectId); + if (!isOwner) { + throw new IllegalArgumentException( + "Project " + projectId + "does not exist or user does not have access to export."); + } + + logger.info("Exporting project now..."); + String baseFolder = Utility.getDIHelperProperty(Constants.BASE_FOLDER).replace("\\", "/"); + if (!baseFolder.endsWith("/")) { + baseFolder += "/"; + } + IProject project = Utility.getProject(projectId); + String projectName = project.getProjectName(); + String projectNameAndId = SmssUtilities.getUniqueName(projectName, projectId); + String baseProjectDir = baseFolder + Constants.PROJECT_FOLDER; + String projectAssetFolder = AssetUtility.getProjectAssetsFolder(projectName, projectId); + + String outputDir = this.insight.getInsightFolder(); + String zipFilePath = outputDir + "/" + getFileName(projectNameAndId); + + // since we do not include the insights database and it is auto generated + // we dont need to lock anymore + + // ReentrantLock lock = null; + // if(project.holdsFileLocks()) { + // lock = ProjectSyncUtility.getProjectLock(projectId); + // lock.lock(); + // } + // boolean closed = false; + try { + // zip project + ZipOutputStream zos = null; + try { + // if(lock != null) { + // logger.info("Stopping the engine... "); + // DIHelper.getInstance().removeProjectProperty(projectId); + // try { + // project.close(); + // closed = true; + // } catch (IOException e) { + // classLogger.error("Failed to close project {} before export", projectId, e); + // } + // } else { + logger.info("Can export this project w/o closing... "); + // } + + // zip project folder + logger.info("Zipping project app files..."); + zos = ZipUtils.zipFolder(projectAssetFolder, zipFilePath, null, null); + logger.info("Done zipping project app files..."); + + // zip up the project metadata + { + logger.info("Grabbing project metadata to write to temporary file to zip..."); + Map projectMeta = SecurityProjectUtils.getAggregateProjectMetadata(projectId, null, + false); + ZipUtils.zipObjectToFile(zos, null, outputDir + "/" + projectName + IEngine.METADATA_FILE_SUFFIX, + projectMeta); + logger.info("Done zipping project metadata..."); + } + + // zip up the project dependencies + { + logger.info("Grabbing project dependencies to write to temporary file to zip..."); + List> projectDependencies = SecurityCatalogDependencyUtils + .getDependencyDetails(projectId, false); + ZipUtils.zipObjectToFile(zos, null, + outputDir + "/" + projectName + IProject.DEPENDENCIES_FILE_SUFFIX, projectDependencies); + logger.info("Done zipping project dependencies..."); + } + + AgentProjectArchiveUtils.exportAgent(zos, project, null); + + // add smss file + logger.info("Zipping project smss..."); + File smss = new File(baseProjectDir + "/" + projectNameAndId + ".smss"); + ZipUtils.addToZipFile(smss, zos); + logger.info("Done zipping project smss files..."); + logger.info("Zipping Complete"); + } catch (Exception e) { + classLogger.error("Failed to export project {} to archive {}", projectId, zipFilePath, e); + throw new SemossPixelException( + "Error occurred generating zip file. Detailed message = " + e.getMessage()); + } finally { + try { + if (zos != null) { + zos.flush(); + zos.close(); + } + } catch (IOException e) { + classLogger.error("Failed to finish writing the export archive {} for project {}", zipFilePath, + projectId, e); + } + } + } finally { + // since we do not include the insights database and it is auto generated + // we dont need to lock anymore + + // lock.unlock(); + // // open it back up + // try { + // if(closed) { + // logger.info("Opening the project again ... "); + // Utility.getProject(projectId); + // logger.info("Opened the project"); + // } + // } finally { + // if(lock != null) { + // // in case opening up causing an issue - we always want to unlock + // lock.unlock(); + // } + // } + } + + // recorded once the archive is built, so an export that fails records only its + // failure; an app's files never include the version history + IProject.PROJECT_TYPE projectType = project.getProjectType(); + UserAuditTrailUtils.recordProjectExport(user, projectId, projectName, + projectType == null ? null : projectType.name(), getPixelName(), null); + + // Generate a new key for the name of the zip file. + String downloadKey = UUID.randomUUID().toString(); + InsightFile insightFile = new InsightFile(); + insightFile.setFileKey(downloadKey); + insightFile.setDeleteOnInsightClose(true); + insightFile.setFilePath(zipFilePath); + this.insight.addExportFile(downloadKey, insightFile); + return new NounMetadata(downloadKey, PixelDataType.CONST_STRING, PixelOperationType.FILE_DOWNLOAD); + } + + /** + * + * @param projectNameAndId + * @return + */ + protected String getFileName(String projectNameAndId) { + return projectNameAndId + "_app.zip"; + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition().description("Export an app as a single zip file").key( + ReactorKeysEnum.PROJECT, + "This is a required value containing the id of the app that is being exported"); + } + +} diff --git a/src/prerna/reactor/utils/ExportProjectReactor.java b/src/prerna/reactor/utils/ExportProjectReactor.java index d4ec4398448..a85dfff7a6c 100644 --- a/src/prerna/reactor/utils/ExportProjectReactor.java +++ b/src/prerna/reactor/utils/ExportProjectReactor.java @@ -1,235 +1,236 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.utils; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.zip.ZipOutputStream; - -import org.apache.commons.io.FilenameUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import prerna.auth.User; -import prerna.auth.utils.SecurityProjectUtils; -import prerna.cluster.util.ClusterUtil; -import prerna.engine.api.IEngine; -import prerna.engine.impl.SmssUtilities; -import prerna.om.InsightFile; -import prerna.project.api.IProject; -import prerna.reactor.AbstractReactor; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.PixelOperationType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.execptions.SemossPixelException; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.usertracking.UserAuditTrailUtils; -import prerna.util.AgentProjectArchiveUtils; -import prerna.util.Constants; -import prerna.util.Utility; -import prerna.util.ZipUtils; - -public class ExportProjectReactor extends AbstractReactor { - - private static final Logger classLogger = LogManager.getLogger(ExportProjectReactor.class); - - private static final String CLASS_NAME = ExportProjectReactor.class.getName(); - private String keepGit = "keepGit"; - - public ExportProjectReactor() { - this.keysToGet = new String[] { ReactorKeysEnum.PROJECT.getKey(), keepGit }; - } - - @Override - public NounMetadata execute() { - Logger logger = getLogger(CLASS_NAME); - logger.info("Checking project information and user permissions."); - organizeKeys(); - String projectId = this.keyValue.get(this.keysToGet[0]); - boolean keepGit = Boolean.parseBoolean(this.keyValue.get(this.keysToGet[1])); - - User user = this.insight.getUser(); - boolean isOwner = SecurityProjectUtils.userIsOwner(user, projectId); - if (!isOwner) { - throw new IllegalArgumentException( - "Project " + projectId + "does not exist or user does not have access to export."); - } - - logger.info("Exporting project now..."); - String baseFolder = Utility.getDIHelperProperty(Constants.BASE_FOLDER).replace("\\", "/"); - if (!baseFolder.endsWith("/")) { - baseFolder += "/"; - } - IProject project = Utility.getProject(projectId); - String projectName = project.getProjectName(); - String projectNameAndId = SmssUtilities.getUniqueName(projectName, projectId); - String baseProjectDir = baseFolder + Constants.PROJECT_FOLDER; - String thisProjectDir = baseProjectDir + "/" + projectNameAndId; - - String outputDir = this.insight.getInsightFolder(); - String zipFilePath = outputDir + "/" + projectNameAndId + "_project.zip"; - - // since we do not include the insights database and it is auto generated - // we dont need to lock anymore - - // ReentrantLock lock = null; - // if(project.holdsFileLocks()) { - // lock = ProjectSyncUtility.getProjectLock(projectId); - // lock.lock(); - // } - // boolean closed = false; - try { - // zip project - try { - // if(lock != null) { - // logger.info("Stopping the engine... "); - // DIHelper.getInstance().removeProjectProperty(projectId); - // try { - // project.close(); - // closed = true; - // } catch (IOException e) { - // classLogger.error("Failed to close project {} before export", projectId, e); - // } - // } else { - logger.info("Can export this project w/o closing... "); - // } - - // determine if we keep or ignore the git - List ignoreDirs = new ArrayList<>(); - if (!keepGit) { - ignoreDirs.add(projectNameAndId + "/" + Constants.APP_ROOT_FOLDER + "/" + Constants.VERSION_FOLDER - + "/.git"); - } - - // the metadata files are zipped fresh below, so their copies on disk are left - // out - List ignoreFiles = new ArrayList<>( - Arrays.asList(projectNameAndId + "/" + projectName + IEngine.METADATA_FILE_SUFFIX, - projectNameAndId + "/" + projectName + IProject.DEPENDENCIES_FILE_SUFFIX, - projectNameAndId + "/" + projectName + AgentProjectArchiveUtils.FILE_SUFFIX)); - - File insightsFile = null; - if (ClusterUtil.IS_CLUSTER && project.getProjectType().holdsInsights()) { - logger.info("Creating insight database ..."); - try { - insightsFile = SecurityProjectUtils.createInsightsDatabase(projectId, outputDir); - } catch (Exception e) { - classLogger.error("Failed to generate the insights database for project {} during export", - projectId, e); - throw new IllegalArgumentException( - "Error occurred attemping to generate the insights database for this project"); - } - logger.info("Done creating insight database ..."); - // ignore the current insights database - ignoreFiles.add(projectNameAndId + "/" + FilenameUtils.getName(insightsFile.getAbsolutePath())); - } - - logger.info("Zipping project files..."); - try (ZipOutputStream zos = ZipUtils.zipFolder(thisProjectDir, zipFilePath, ignoreDirs, ignoreFiles)) { - logger.info("Done zipping project files..."); - - if (insightsFile != null) { - logger.info("Zipping insight database ..."); - ZipUtils.addToZipFile(insightsFile, zos, projectNameAndId); - logger.info("Done zipping insight database..."); - } - - // zip up the project metadata - { - logger.info("Grabbing project metadata to write to temporary file to zip..."); - Map projectMeta = SecurityProjectUtils.getAggregateProjectMetadata(projectId, - null, false); - ZipUtils.zipObjectToFile(zos, projectNameAndId, - outputDir + "/" + projectName + IEngine.METADATA_FILE_SUFFIX, projectMeta); - logger.info("Done zipping project metadata..."); - } - - // zip up the project dependencies - { - logger.info("Grabbing project dependencies to write to temporary file to zip..."); - List> projectDependencies = SecurityProjectUtils - .getProjectDependencyDetails(projectId, false); - ZipUtils.zipObjectToFile(zos, projectNameAndId, - outputDir + "/" + projectName + IProject.DEPENDENCIES_FILE_SUFFIX, projectDependencies); - logger.info("Done zipping project dependencies..."); - } - - AgentProjectArchiveUtils.exportAgent(zos, project, projectNameAndId); - - // add smss file - logger.info("Zipping project smss..."); - File smss = new File(baseProjectDir + "/" + projectNameAndId + ".smss"); - ZipUtils.addToZipFile(smss, zos); - logger.info("Done zipping project smss files..."); - logger.info("Zipping Complete"); - } - } catch (Exception e) { - classLogger.error("Failed to export project {} to archive {}", projectId, zipFilePath, e); - throw new SemossPixelException( - "Error occurred generating zip file. Detailed message = " + e.getMessage()); - } - } finally { - // since we do not include the insights database and it is auto generated - // we dont need to lock anymore - - // lock.unlock(); - // // open it back up - // try { - // if(closed) { - // logger.info("Opening the project again ... "); - // Utility.getProject(projectId); - // logger.info("Opened the project"); - // } - // } finally { - // if(lock != null) { - // // in case opening up causing an issue - we always want to unlock - // lock.unlock(); - // } - // } - } - - // recorded once the archive is built, so an export that fails records only its - // failure - IProject.PROJECT_TYPE projectType = project.getProjectType(); - UserAuditTrailUtils.recordProjectExport(user, projectId, projectName, - projectType == null ? null : projectType.name(), getPixelName(), keepGit); - - // Generate a new key for the name of the zip file. - String downloadKey = UUID.randomUUID().toString(); - InsightFile insightFile = new InsightFile(); - insightFile.setFileKey(downloadKey); - insightFile.setDeleteOnInsightClose(true); - insightFile.setFilePath(zipFilePath); - this.insight.addExportFile(downloadKey, insightFile); - return new NounMetadata(downloadKey, PixelDataType.CONST_STRING, PixelOperationType.FILE_DOWNLOAD); - } -} +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.utils; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.zip.ZipOutputStream; + +import org.apache.commons.io.FilenameUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.auth.utils.SecurityProjectUtils; +import prerna.cluster.util.ClusterUtil; +import prerna.engine.api.IEngine; +import prerna.engine.impl.SmssUtilities; +import prerna.om.InsightFile; +import prerna.project.api.IProject; +import prerna.reactor.AbstractReactor; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.PixelOperationType; +import prerna.sablecc2.om.ReactorKeysEnum; +import prerna.sablecc2.om.execptions.SemossPixelException; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.usertracking.UserAuditTrailUtils; +import prerna.util.AgentProjectArchiveUtils; +import prerna.util.Constants; +import prerna.util.Utility; +import prerna.util.ZipUtils; + +public class ExportProjectReactor extends AbstractReactor { + + private static final Logger classLogger = LogManager.getLogger(ExportProjectReactor.class); + + private static final String CLASS_NAME = ExportProjectReactor.class.getName(); + private String keepGit = "keepGit"; + + public ExportProjectReactor() { + this.keysToGet = new String[] { ReactorKeysEnum.PROJECT.getKey(), keepGit }; + } + + @Override + public NounMetadata execute() { + Logger logger = getLogger(CLASS_NAME); + logger.info("Checking project information and user permissions."); + organizeKeys(); + String projectId = this.keyValue.get(this.keysToGet[0]); + boolean keepGit = Boolean.parseBoolean(this.keyValue.get(this.keysToGet[1])); + + User user = this.insight.getUser(); + boolean isOwner = SecurityProjectUtils.userIsOwner(user, projectId); + if (!isOwner) { + throw new IllegalArgumentException( + "Project " + projectId + "does not exist or user does not have access to export."); + } + + logger.info("Exporting project now..."); + String baseFolder = Utility.getDIHelperProperty(Constants.BASE_FOLDER).replace("\\", "/"); + if (!baseFolder.endsWith("/")) { + baseFolder += "/"; + } + IProject project = Utility.getProject(projectId); + String projectName = project.getProjectName(); + String projectNameAndId = SmssUtilities.getUniqueName(projectName, projectId); + String baseProjectDir = baseFolder + Constants.PROJECT_FOLDER; + String thisProjectDir = baseProjectDir + "/" + projectNameAndId; + + String outputDir = this.insight.getInsightFolder(); + String zipFilePath = outputDir + "/" + projectNameAndId + "_project.zip"; + + // since we do not include the insights database and it is auto generated + // we dont need to lock anymore + + // ReentrantLock lock = null; + // if(project.holdsFileLocks()) { + // lock = ProjectSyncUtility.getProjectLock(projectId); + // lock.lock(); + // } + // boolean closed = false; + try { + // zip project + try { + // if(lock != null) { + // logger.info("Stopping the engine... "); + // DIHelper.getInstance().removeProjectProperty(projectId); + // try { + // project.close(); + // closed = true; + // } catch (IOException e) { + // classLogger.error("Failed to close project {} before export", projectId, e); + // } + // } else { + logger.info("Can export this project w/o closing... "); + // } + + // determine if we keep or ignore the git + List ignoreDirs = new ArrayList<>(); + if (!keepGit) { + ignoreDirs.add(projectNameAndId + "/" + Constants.APP_ROOT_FOLDER + "/" + Constants.VERSION_FOLDER + + "/.git"); + } + + // the metadata files are zipped fresh below, so their copies on disk are left + // out + List ignoreFiles = new ArrayList<>( + Arrays.asList(projectNameAndId + "/" + projectName + IEngine.METADATA_FILE_SUFFIX, + projectNameAndId + "/" + projectName + IProject.DEPENDENCIES_FILE_SUFFIX, + projectNameAndId + "/" + projectName + AgentProjectArchiveUtils.FILE_SUFFIX)); + + File insightsFile = null; + if (ClusterUtil.IS_CLUSTER && project.getProjectType().holdsInsights()) { + logger.info("Creating insight database ..."); + try { + insightsFile = SecurityProjectUtils.createInsightsDatabase(projectId, outputDir); + } catch (Exception e) { + classLogger.error("Failed to generate the insights database for project {} during export", + projectId, e); + throw new IllegalArgumentException( + "Error occurred attemping to generate the insights database for this project"); + } + logger.info("Done creating insight database ..."); + // ignore the current insights database + ignoreFiles.add(projectNameAndId + "/" + FilenameUtils.getName(insightsFile.getAbsolutePath())); + } + + logger.info("Zipping project files..."); + try (ZipOutputStream zos = ZipUtils.zipFolder(thisProjectDir, zipFilePath, ignoreDirs, ignoreFiles)) { + logger.info("Done zipping project files..."); + + if (insightsFile != null) { + logger.info("Zipping insight database ..."); + ZipUtils.addToZipFile(insightsFile, zos, projectNameAndId); + logger.info("Done zipping insight database..."); + } + + // zip up the project metadata + { + logger.info("Grabbing project metadata to write to temporary file to zip..."); + Map projectMeta = SecurityProjectUtils.getAggregateProjectMetadata(projectId, + null, false); + ZipUtils.zipObjectToFile(zos, projectNameAndId, + outputDir + "/" + projectName + IEngine.METADATA_FILE_SUFFIX, projectMeta); + logger.info("Done zipping project metadata..."); + } + + // zip up the project dependencies + { + logger.info("Grabbing project dependencies to write to temporary file to zip..."); + List> projectDependencies = SecurityCatalogDependencyUtils + .getDependencyDetails(projectId, false); + ZipUtils.zipObjectToFile(zos, projectNameAndId, + outputDir + "/" + projectName + IProject.DEPENDENCIES_FILE_SUFFIX, projectDependencies); + logger.info("Done zipping project dependencies..."); + } + + AgentProjectArchiveUtils.exportAgent(zos, project, projectNameAndId); + + // add smss file + logger.info("Zipping project smss..."); + File smss = new File(baseProjectDir + "/" + projectNameAndId + ".smss"); + ZipUtils.addToZipFile(smss, zos); + logger.info("Done zipping project smss files..."); + logger.info("Zipping Complete"); + } + } catch (Exception e) { + classLogger.error("Failed to export project {} to archive {}", projectId, zipFilePath, e); + throw new SemossPixelException( + "Error occurred generating zip file. Detailed message = " + e.getMessage()); + } + } finally { + // since we do not include the insights database and it is auto generated + // we dont need to lock anymore + + // lock.unlock(); + // // open it back up + // try { + // if(closed) { + // logger.info("Opening the project again ... "); + // Utility.getProject(projectId); + // logger.info("Opened the project"); + // } + // } finally { + // if(lock != null) { + // // in case opening up causing an issue - we always want to unlock + // lock.unlock(); + // } + // } + } + + // recorded once the archive is built, so an export that fails records only its + // failure + IProject.PROJECT_TYPE projectType = project.getProjectType(); + UserAuditTrailUtils.recordProjectExport(user, projectId, projectName, + projectType == null ? null : projectType.name(), getPixelName(), keepGit); + + // Generate a new key for the name of the zip file. + String downloadKey = UUID.randomUUID().toString(); + InsightFile insightFile = new InsightFile(); + insightFile.setFileKey(downloadKey); + insightFile.setDeleteOnInsightClose(true); + insightFile.setFilePath(zipFilePath); + this.insight.addExportFile(downloadKey, insightFile); + return new NounMetadata(downloadKey, PixelDataType.CONST_STRING, PixelOperationType.FILE_DOWNLOAD); + } +} diff --git a/src/prerna/util/AgentProjectArchiveUtils.java b/src/prerna/util/AgentProjectArchiveUtils.java index 03ef0681dff..9c764594529 100644 --- a/src/prerna/util/AgentProjectArchiveUtils.java +++ b/src/prerna/util/AgentProjectArchiveUtils.java @@ -49,6 +49,7 @@ import com.google.gson.JsonParser; import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils; import prerna.auth.utils.SecurityProjectUtils; import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils; import prerna.project.api.IProject; @@ -153,7 +154,9 @@ public static void importAgent(String projectId, User user, JsonObject metadata, } /** - * Restore the exported dependency types, including non-UUID platform projects. + * Restore the exported dependencies with their types, including non-UUID + * platform projects such as platform skills. Types are read from the security + * database when it has the item. */ public static void importDependencies(File directory, String projectName, String projectId, User user) throws IOException { @@ -161,15 +164,21 @@ public static void importDependencies(File directory, String projectName, String if (!file.isFile()) { return; } - List> dependencies = new ArrayList<>(); + List> rows = new ArrayList<>(); try (Reader reader = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) { for (JsonElement element : JsonParser.parseReader(reader).getAsJsonArray()) { JsonObject dependency = element.getAsJsonObject(); - dependencies.add(Map.of("ENGINEID", string(dependency, "engine_id", true), "ENGINETYPE", - IProject.CATALOG_TYPE.valueOf(string(dependency, "engine_type", true)).name())); + Map row = new HashMap<>(); + // this release exports catalog_id and catalog_type, older ones engine_id and + // engine_type + boolean current = dependency.has("catalog_id"); + row.put("catalog_id", string(dependency, current ? "catalog_id" : "engine_id", true)); + row.put("catalog_type", string(dependency, current ? "catalog_type" : "engine_type", true)); + rows.add(row); } } - SecurityProjectUtils.updateProjectDependencies(user, projectId, dependencies); + SecurityCatalogDependencyUtils.setDependencies(user, projectId, IProject.PROJECT_TYPE.WORKSPACE.name(), + SecurityCatalogDependencyUtils.fromExported(rows)); Files.delete(file.toPath()); } diff --git a/test/prerna/auth/utils/AbstractSecurityUtilsUnitTests.java b/test/prerna/auth/utils/AbstractSecurityUtilsUnitTests.java index 234019ffdb7..b2d13f82e73 100644 --- a/test/prerna/auth/utils/AbstractSecurityUtilsUnitTests.java +++ b/test/prerna/auth/utils/AbstractSecurityUtilsUnitTests.java @@ -462,16 +462,35 @@ void testInitialize_projectBackfillFailureRollsBackTheDisplayNames() throws Exce } @Test - void testInitialize_fillsTheEngineTypesOfProjectDependencies() throws Exception { + void testInitialize_movesProjectDependenciesToCatalogDependenciesWithTheirTypes() throws Exception { + execute("CREATE TABLE PROJECTDEPENDENCIES (PROJECTID VARCHAR(255), ENGINEID VARCHAR(255), " + + "ENGINETYPE VARCHAR(255), USERID VARCHAR(255), TYPE VARCHAR(255), DATEADDED TIMESTAMP)"); execute("INSERT INTO ENGINE (ENGINEID, ENGINENAME, ENGINETYPE) VALUES (?,?,?)", "engine1", "name1", "MODEL"); - execute("INSERT INTO PROJECT (PROJECTID, PROJECTNAME) VALUES (?,?)", "project1", "name1"); + execute("INSERT INTO PROJECT (PROJECTID, PROJECTNAME, TYPE) VALUES (?,?,?)", "app", "app", "CODE"); + execute("INSERT INTO PROJECT (PROJECTID, PROJECTNAME, TYPE) VALUES (?,?,?)", "skill1", "skill1", "SKILL"); + execute("INSERT INTO PROJECT (PROJECTID, PROJECTNAME) VALUES (?,?)", "legacy", "legacy"); + // a missing type, the generic PROJECT type, a repeat, and a dependency that is gone execute("INSERT INTO PROJECTDEPENDENCIES (PROJECTID, ENGINEID) VALUES (?,?)", "app", "engine1"); - execute("INSERT INTO PROJECTDEPENDENCIES (PROJECTID, ENGINEID) VALUES (?,?)", "app", "project1"); + execute("INSERT INTO PROJECTDEPENDENCIES (PROJECTID, ENGINEID, ENGINETYPE) VALUES (?,?,?)", "app", "skill1", + "PROJECT"); + execute("INSERT INTO PROJECTDEPENDENCIES (PROJECTID, ENGINEID, ENGINETYPE) VALUES (?,?,?)", "app", "legacy", + "PROJECT"); + execute("INSERT INTO PROJECTDEPENDENCIES (PROJECTID, ENGINEID, ENGINETYPE) VALUES (?,?,?)", "app", "engine1", + "MODEL"); + execute("INSERT INTO PROJECTDEPENDENCIES (PROJECTID, ENGINEID, ENGINETYPE) VALUES (?,?,?)", "app", "gone", + "MODEL"); AbstractSecurityUtils.initialize(); - assertEquals("MODEL", queryValue("SELECT ENGINETYPE FROM PROJECTDEPENDENCIES WHERE ENGINEID=?", "engine1")); - assertEquals("PROJECT", queryValue("SELECT ENGINETYPE FROM PROJECTDEPENDENCIES WHERE ENGINEID=?", "project1")); + assertEquals(List.of("app|CODE|engine1|MODEL", "app|CODE|legacy|INSIGHTS", "app|CODE|skill1|SKILL"), + strings("SELECT CATALOGID || '|' || CATALOGTYPE || '|' || DEPENDENCYID || '|' || DEPENDENCYTYPE " + + "FROM CATALOGDEPENDENCIES ORDER BY DEPENDENCYID")); + assertFalse(securityDb.getQueryUtil().tableExists(securityDb, "PROJECTDEPENDENCIES", securityDb.getDatabase(), + securityDb.getSchema())); + + // a second start, or another server starting at the same time, moves nothing + AbstractSecurityUtils.initialize(); + assertEquals(3, count("SELECT COUNT(*) FROM CATALOGDEPENDENCIES")); } @Test diff --git a/test/prerna/auth/utils/PermissionBatchUtilsUsageLimitUnitTests.java b/test/prerna/auth/utils/PermissionBatchUtilsUsageLimitUnitTests.java index c4ddda3b165..3b7482748fe 100644 --- a/test/prerna/auth/utils/PermissionBatchUtilsUsageLimitUnitTests.java +++ b/test/prerna/auth/utils/PermissionBatchUtilsUsageLimitUnitTests.java @@ -673,7 +673,7 @@ void propagateProjectPermission_aChangeKeepsTheLimitUnlessOneIsGiven() throws Ex SecurityAccessPermissionBatchUtils.saveBatches(owner, List.of(modelBatch(changeWith("readerid", "READ_ONLY", tokensADay(500))))); - Map noLimit = SecurityProjectUtils.propagateProjectPermission(owner, PROJECT_ID, "readerid", + Map noLimit = SecurityCatalogDependencyUtils.propagatePermission(owner, PROJECT_ID, "readerid", NATIVE, "EDIT", null); assertTrue(strings(noLimit.get("accessGranted")).contains(MODEL_ID)); @@ -690,7 +690,7 @@ void propagateProjectPermission_aGivenLimitReplacesTheCurrentOne() throws Except SecurityAccessPermissionBatchUtils.saveBatches(owner, List.of(modelBatch(changeWith("readerid", "READ_ONLY", twoRules)))); - SecurityProjectUtils.propagateProjectPermission(owner, PROJECT_ID, "readerid", NATIVE, "EDIT", null, + SecurityCatalogDependencyUtils.propagatePermission(owner, PROJECT_ID, "readerid", NATIVE, "EDIT", null, tokensADay(500)); assertEquals(2, SecurityEngineUtils.getUserEnginePermission("readerid", MODEL_ID)); @@ -700,11 +700,12 @@ void propagateProjectPermission_aGivenLimitReplacesTheCurrentOne() throws Except @Test void propagateProjectPermission_aRefusedEngineDoesNotStopTheOthers() throws Exception { dependOnTheModel(); - execute("INSERT INTO PROJECTDEPENDENCIES (PROJECTID, ENGINEID, ENGINETYPE) VALUES (?,?,?)", PROJECT_ID, + execute("INSERT INTO CATALOGDEPENDENCIES (CATALOGID, CATALOGTYPE, DEPENDENCYID, DEPENDENCYTYPE) VALUES (?,?,?,?)", + PROJECT_ID, "CODE", DATABASE_ID, IEngine.CATALOG_TYPE.DATABASE.name()); // a shared rule cannot be a person's limit, so the model refuses the change - Map result = SecurityProjectUtils.propagateProjectPermission(owner, PROJECT_ID, "readerid", + Map result = SecurityCatalogDependencyUtils.propagatePermission(owner, PROJECT_ID, "readerid", NATIVE, "EDIT", null, sharedTokens(10)); assertTrue(strings(result.get("couldNotAddRequest")).contains(MODEL_ID)); @@ -717,7 +718,7 @@ void propagateProjectPermission_aRefusedEngineDoesNotStopTheOthers() throws Exce void propagateProjectPermission_anEditorWhoGivesALimitIsRefusedOnTheModel() throws Exception { dependOnTheModel(); - Map result = SecurityProjectUtils.propagateProjectPermission(editor, PROJECT_ID, "readerid", + Map result = SecurityCatalogDependencyUtils.propagatePermission(editor, PROJECT_ID, "readerid", NATIVE, "EDIT", null, tokensADay(900)); assertTrue(strings(result.get("couldNotAddRequest")).contains(MODEL_ID)); @@ -896,7 +897,8 @@ private static Map validate(User user, PermissionBatch batch) { private void dependOnTheModel() throws Exception { UnitTestSecurityAuthUtils.createProject(PROJECT_ID, "limited project", owner); - execute("INSERT INTO PROJECTDEPENDENCIES (PROJECTID, ENGINEID, ENGINETYPE) VALUES (?,?,?)", PROJECT_ID, + execute("INSERT INTO CATALOGDEPENDENCIES (CATALOGID, CATALOGTYPE, DEPENDENCYID, DEPENDENCYTYPE) VALUES (?,?,?,?)", + PROJECT_ID, "CODE", MODEL_ID, IEngine.CATALOG_TYPE.MODEL.name()); } diff --git a/test/prerna/auth/utils/SecurityCatalogDependencyUtilsUnitTests.java b/test/prerna/auth/utils/SecurityCatalogDependencyUtilsUnitTests.java new file mode 100644 index 00000000000..164929f3b84 --- /dev/null +++ b/test/prerna/auth/utils/SecurityCatalogDependencyUtilsUnitTests.java @@ -0,0 +1,242 @@ +package prerna.auth.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; +import prerna.engine.api.IEngine; +import prerna.engine.api.IRDBMSEngine; +import prerna.util.SystemEngineRegistry; +import prerna.util.Utility; + +/** + * Dependencies of engines and projects, each kept with its own engine type or + * project type. + */ +public class SecurityCatalogDependencyUtilsUnitTests extends AbstractSecurityUtilsUnitTestsSetup { + + private IRDBMSEngine securityDb; + private List tables = new ArrayList<>(); + private User owner; + + @BeforeEach + void setup() { + securityDb = SystemEngineRegistry.getSecurityDb(); + assertTrue(securityDb.getOwlFilePath().contains("junit")); + owner = UnitTestSecurityAuthUtils.createUser("owner", false); + UnitTestSecurityAuthUtils.createEngine("function1", "Function", IEngine.CATALOG_TYPE.FUNCTION, owner); + UnitTestSecurityAuthUtils.createEngine("model1", "Model", IEngine.CATALOG_TYPE.MODEL, owner); + UnitTestSecurityAuthUtils.createEngine("database1", "Database", IEngine.CATALOG_TYPE.DATABASE, owner); + UnitTestSecurityAuthUtils.createProjectOfType("skill1", "Skill", "SKILL", owner); + UnitTestSecurityAuthUtils.createProjectOfType("notebook1", "Notebook", "NOTEBOOK", owner); + UnitTestSecurityAuthUtils.createProjectOfType("automation1", "Automation", "AUTOMATION", owner); + } + + @AfterEach + void cleanup() throws SQLException { + assertTrue(securityDb.getOwlFilePath().contains("junit")); + tables = UnitTestSecurityAuthUtils.clearSecurityDB(securityDb, tables); + } + + @Test + void kindOf_tellsEngineTypesFromProjectTypes() { + for (String type : List.of("FUNCTION", "MODEL", "DATABASE", "VECTOR", "STORAGE", "GUARDRAIL")) { + assertEquals(CatalogTypes.Kind.ENGINE, CatalogTypes.kindOf(type), type); + } + for (String type : List.of("CODE", "BLOCKS", "INSIGHTS", "SKILL", "NOTEBOOK", "AUTOMATION", "WORKSPACE")) { + assertEquals(CatalogTypes.Kind.PROJECT, CatalogTypes.kindOf(type), type); + } + assertEquals("INSIGHTS", CatalogTypes.normalize("insight")); + assertThrows(IllegalArgumentException.class, () -> CatalogTypes.kindOf("PROJECT")); + assertThrows(IllegalArgumentException.class, () -> CatalogTypes.kindOf("VENV")); + } + + @Test + void resolve_readsTheSpecificTypeWithoutLoadingAnything() { + try (MockedStatic utility = Mockito.mockStatic(Utility.class, Mockito.CALLS_REAL_METHODS)) { + assertEquals("FUNCTION", CatalogTypes.resolve("function1")); + assertEquals("SKILL", CatalogTypes.resolve("skill1")); + assertNull(CatalogTypes.resolve("missing")); + // on a cluster, loading would pull the engine or project onto this server + utility.verify(() -> Utility.getEngine(Mockito.anyString()), Mockito.never()); + utility.verify(() -> Utility.getProject(Mockito.anyString()), Mockito.never()); + } + } + + @Test + void anEngineOwnsDependenciesOnEnginesAndProjects() { + SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + List.of(new Dependency("model1", "MODEL"), new Dependency("skill1", "SKILL"))); + + List> details = SecurityCatalogDependencyUtils.getDependencyDetails("function1"); + Map> byId = byCatalogId(details); + assertEquals("MODEL", byId.get("model1").get("catalog_type")); + assertEquals("Model", byId.get("model1").get("catalog_name")); + assertEquals("SKILL", byId.get("skill1").get("catalog_type")); + assertEquals("Skill", byId.get("skill1").get("catalog_name")); + assertEquals("FUNCTION", queryString("SELECT DISTINCT CATALOGTYPE FROM CATALOGDEPENDENCIES")); + } + + @Test + void aProjectOwnsDependenciesOnEnginesAndProjects() { + List failed = SecurityCatalogDependencyUtils.setDependencyIds(owner, "automation1", "AUTOMATION", + List.of("database1", "notebook1", "missing")); + + assertEquals(List.of("missing"), failed); + Map> byId = byCatalogId( + SecurityCatalogDependencyUtils.getDependencies("automation1")); + assertEquals("DATABASE", byId.get("database1").get("catalog_type")); + assertEquals("NOTEBOOK", byId.get("notebook1").get("catalog_type")); + assertEquals(2, byId.size()); + } + + @Test + void setDependencies_replacesAndSkipsTheOwnerAndRepeats() { + SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + List.of(new Dependency("model1", "MODEL"))); + SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + List.of(new Dependency("database1", "DATABASE"), new Dependency("database1", "DATABASE"), + new Dependency("function1", "FUNCTION"))); + + assertEquals(List.of("database1"), ids(SecurityCatalogDependencyUtils.getDependencies("function1"))); + } + + @Test + void addDependencies_keepsTheOnesThere() { + SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + List.of(new Dependency("model1", "MODEL"))); + SecurityCatalogDependencyUtils.addDependencies(owner, "function1", "FUNCTION", + List.of(new Dependency("model1", "MODEL"), new Dependency("skill1", "SKILL"))); + + assertEquals(2, SecurityCatalogDependencyUtils.getDependencies("function1").size()); + } + + @Test + void getDependencies_followsEnginesAndProjectsAndEndsOnACycle() { + SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + List.of(new Dependency("skill1", "SKILL"))); + SecurityCatalogDependencyUtils.setDependencies(owner, "skill1", "SKILL", + List.of(new Dependency("model1", "MODEL"), new Dependency("function1", "FUNCTION"))); + + List> all = SecurityCatalogDependencyUtils.getDependencies("function1", true); + + // each item once: the skill, its model, and the function itself where the cycle + // closes + assertEquals(3, all.size()); + assertEquals(java.util.Set.of("skill1", "model1", "function1"), new java.util.HashSet<>(ids(all))); + } + + @Test + void validateDependencies_checksEachWithItsOwnPermissions() { + User reader = UnitTestSecurityAuthUtils.createUser("reader", false); + UnitTestSecurityAuthUtils.addPermissionsToUserForEngine(owner, "readerid", "model1", "READ_ONLY"); + SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + List.of(new Dependency("model1", "MODEL"), new Dependency("skill1", "SKILL"))); + + Map canView = SecurityCatalogDependencyUtils.validateDependencies(reader, "function1"); + + assertEquals(true, canView.get("model1")); + assertEquals(false, canView.get("skill1")); + } + + @Test + void permissionsBranchOnTheOwnersType() { + User other = UnitTestSecurityAuthUtils.createUser("other", false); + assertTrue(SecurityCatalogDependencyUtils.userCanEdit(owner, "function1", "FUNCTION")); + assertTrue(SecurityCatalogDependencyUtils.userCanEdit(owner, "skill1", "SKILL")); + assertFalse(SecurityCatalogDependencyUtils.userCanEdit(other, "function1", "FUNCTION")); + assertFalse(SecurityCatalogDependencyUtils.userCanView(other, "skill1", "SKILL")); + } + + @Test + void resolveCatalogType_checksAGivenTypeAgainstTheSecurityDatabase() { + assertEquals("FUNCTION", SecurityCatalogDependencyUtils.resolveCatalogType("function1", null)); + assertEquals("SKILL", SecurityCatalogDependencyUtils.resolveCatalogType("skill1", "skill")); + assertThrows(IllegalArgumentException.class, + () -> SecurityCatalogDependencyUtils.resolveCatalogType("skill1", "NOTEBOOK")); + assertThrows(IllegalArgumentException.class, + () -> SecurityCatalogDependencyUtils.resolveCatalogType("skill1", "MODEL")); + // a legacy project type, as the UI sends PROJECT.TYPE, is an INSIGHTS project + UnitTestSecurityAuthUtils.createProject("legacyApp", "Legacy", owner); + assertEquals("INSIGHTS", SecurityCatalogDependencyUtils.resolveCatalogType("legacyApp", "APP")); + assertThrows(IllegalArgumentException.class, + () -> SecurityCatalogDependencyUtils.resolveCatalogType("missing", null)); + } + + @Test + void deletingAnEngineRemovesTheDependenciesItOwned() { + SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + List.of(new Dependency("model1", "MODEL"))); + SecurityCatalogDependencyUtils.setDependencies(owner, "skill1", "SKILL", + List.of(new Dependency("function1", "FUNCTION"))); + + SecurityEngineUtils.deleteEngine("function1"); + + assertTrue(SecurityCatalogDependencyUtils.getDependencies("function1").isEmpty()); + // the skill still lists it, so validating the skill shows it is gone + assertEquals(List.of("function1"), ids(SecurityCatalogDependencyUtils.getDependencies("skill1"))); + } + + @Test + void fromExported_readsOldAndNewExports() { + List dependencies = SecurityCatalogDependencyUtils.fromExported(List.of( + Map.of("engine_id", "skill1", "engine_type", "PROJECT"), + Map.of("catalog_id", "model1", "catalog_type", "MODEL"), + Map.of("engine_id", "platformTool", "engine_type", "FUNCTION"), + Map.of("engine_id", "unknownProject", "engine_type", "PROJECT"))); + + assertEquals(List.of(new Dependency("skill1", "SKILL"), new Dependency("model1", "MODEL"), + new Dependency("platformTool", "FUNCTION")), dependencies); + } + + @Test + void changingAProjectsTypeUpdatesItsDependencyRows() { + SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + List.of(new Dependency("notebook1", "NOTEBOOK"))); + + SecurityProjectUtils.updateProject("notebook1", "Notebook", "CODE", null, false); + + assertEquals("CODE", SecurityCatalogDependencyUtils.getDependencies("function1").get(0).get("catalog_type")); + } + + private static Map> byCatalogId(List> rows) { + Map> byId = new HashMap<>(); + for (Map row : rows) { + byId.put((String) row.get("catalog_id"), row); + } + return byId; + } + + private static List ids(List> rows) { + List ids = new ArrayList<>(); + for (Map row : rows) { + ids.add((String) row.get("catalog_id")); + } + return ids; + } + + private String queryString(String sql) { + try { + return prerna.util.QueryExecutionUtility.queryOne(securityDb, sql, + prerna.util.QueryExecutionUtility.NO_PARAMETERS, rs -> rs.getString(1)); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } +} diff --git a/test/prerna/auth/utils/SecurityProjectUtilsUnitTests.java b/test/prerna/auth/utils/SecurityProjectUtilsUnitTests.java index b40cd6ea0ba..d20b63446e0 100644 --- a/test/prerna/auth/utils/SecurityProjectUtilsUnitTests.java +++ b/test/prerna/auth/utils/SecurityProjectUtilsUnitTests.java @@ -1888,7 +1888,7 @@ void testGetUserProjectList_withFilter() { } /// - /// propagateProjectPermission + /// propagatePermission /// @Test @@ -1898,7 +1898,7 @@ void testPropagateProjectPermission_noDependencies() { UnitTestSecurityAuthUtils.createProject("testProjectId", "testProjectName", user); // Call propagate with no project dependencies - should return empty result maps - Map result = SecurityProjectUtils.propagateProjectPermission(user, "testProjectId", "user2id", + Map result = SecurityCatalogDependencyUtils.propagatePermission(user, "testProjectId", "user2id", "user", "READ_ONLY", null); assertNotNull(result); } @@ -1931,12 +1931,12 @@ void testPropagateProjectPermission_letsAnAdminGrantAnAdminOnlyDependency() { private static Map propagateToAModelWhoseAddsAreAdminOnly(User requester) { UnitTestSecurityAuthUtils.createProject("testProjectId", "testProjectName", requester); UnitTestSecurityAuthUtils.createEngine("model1", "Model One", IEngine.CATALOG_TYPE.MODEL, requester); - SecurityProjectUtils.updateProjectDependencies(requester, "testProjectId", - List.of(Map.of("ENGINEID", "model1", "ENGINETYPE", IEngine.CATALOG_TYPE.MODEL.name()))); + SecurityCatalogDependencyUtils.setDependencies(requester, "testProjectId", "INSIGHTS", + List.of(new SecurityCatalogDependencyUtils.Dependency("model1", IEngine.CATALOG_TYPE.MODEL.name()))); boolean adminOnlyBefore = AbstractSecurityUtils.adminOnlyModelAddAccess; AbstractSecurityUtils.adminOnlyModelAddAccess = true; try { - return SecurityProjectUtils.propagateProjectPermission(requester, "testProjectId", "user2id", "NATIVE", + return SecurityCatalogDependencyUtils.propagatePermission(requester, "testProjectId", "user2id", "NATIVE", "READ_ONLY", null); } finally { AbstractSecurityUtils.adminOnlyModelAddAccess = adminOnlyBefore; @@ -1944,7 +1944,7 @@ private static Map propagateToAModelWhoseAddsAreAdminOnly(User r } /// - /// getProjectDependencies & updateProjectDependencies + /// getDependencies & getDependencyDetails /// @Test @@ -1952,7 +1952,7 @@ void testGetProjectDependencies_empty() { User user = UnitTestSecurityAuthUtils.createUser("admin", true); UnitTestSecurityAuthUtils.createProject("testProjectId", "testProjectName", user); - List> deps = SecurityProjectUtils.getProjectDependencies("testProjectId", true); + List> deps = SecurityCatalogDependencyUtils.getDependencies("testProjectId", true); assertNotNull(deps); assertTrue(deps.isEmpty()); } @@ -1962,7 +1962,7 @@ void testGetProjectDependencyDetails_empty() { User user = UnitTestSecurityAuthUtils.createUser("admin", true); UnitTestSecurityAuthUtils.createProject("testProjectId", "testProjectName", user); - List> deps = SecurityProjectUtils.getProjectDependencyDetails("testProjectId", false); + List> deps = SecurityCatalogDependencyUtils.getDependencyDetails("testProjectId", false); assertNotNull(deps); assertTrue(deps.isEmpty()); } diff --git a/test/prerna/util/AgentProjectArchiveUtilsUnitTests.java b/test/prerna/util/AgentProjectArchiveUtilsUnitTests.java index 5b2af8a8898..0fcb12f6811 100644 --- a/test/prerna/util/AgentProjectArchiveUtilsUnitTests.java +++ b/test/prerna/util/AgentProjectArchiveUtilsUnitTests.java @@ -27,6 +27,10 @@ *******************************************************************************/ package prerna.util; +import static org.mockito.ArgumentMatchers.any; +import org.mockito.Mockito; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.auth.utils.CatalogTypes; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -281,16 +285,23 @@ void agentImportRequiresInferenceDatabase() throws Exception { } @Test - void restoresDependenciesWithExportedTypesIncludingPlatformSkills() throws Exception { + void restoresDependenciesWithTheirTypesIncludingPlatformSkills() throws Exception { Path file = directory.resolve(NAME + IProject.DEPENDENCIES_FILE_SUFFIX); Files.writeString(file, """ [{"engine_id":"python","engine_type":"PROJECT"}, {"engine_id":"tool","engine_type":"FUNCTION"}] """); - try (var projects = mockStatic(SecurityProjectUtils.class)) { + try (var types = mockStatic(CatalogTypes.class, Mockito.CALLS_REAL_METHODS); + var dependencies = mockStatic(SecurityCatalogDependencyUtils.class, Mockito.CALLS_REAL_METHODS)) { + // the platform skill is in the security database; the tool is not, so its + // exported type is kept + types.when(() -> CatalogTypes.resolve("python")).thenReturn("SKILL"); + types.when(() -> CatalogTypes.resolve("tool")).thenReturn(null); + dependencies.when(() -> SecurityCatalogDependencyUtils.setDependencies(any(), any(), any(), any())) + .thenAnswer(invocation -> null); AgentProjectArchiveUtils.importDependencies(directory.toFile(), NAME, ID, user); - projects.verify(() -> SecurityProjectUtils.updateProjectDependencies(user, ID, - List.of(Map.of("ENGINEID", "python", "ENGINETYPE", "PROJECT"), - Map.of("ENGINEID", "tool", "ENGINETYPE", "FUNCTION")))); + dependencies.verify(() -> SecurityCatalogDependencyUtils.setDependencies(user, ID, "WORKSPACE", + List.of(new SecurityCatalogDependencyUtils.Dependency("python", "SKILL"), + new SecurityCatalogDependencyUtils.Dependency("tool", "FUNCTION")))); } assertFalse(Files.exists(file)); } From cdc8bd0771a82a8e21f59f25677fa9555221eab7 Mon Sep 17 00:00:00 2001 From: Neel Date: Thu, 19 Nov 2026 11:53:51 -0500 Subject: [PATCH 2/6] feat: update catalog dependencies to include engine-engine dependencies and automatically sync --- .../auth/utils/AbstractSecurityUtils.java | 12 +- .../utils/CatalogDependenciesMigration.java | 27 + .../utils/CatalogDependencyDerivation.java | 422 ++++++++++++++ .../auth/utils/CatalogDependencyRole.java | 102 ++++ src/prerna/auth/utils/CatalogTypes.java | 27 + .../utils/SecurityCatalogDependencyUtils.java | 504 +++++++++++++--- src/prerna/auth/utils/SecurityOwlCreator.java | 6 +- .../workspaces/AbstractWorkspaceReactor.java | 57 +- .../workspaces/AddWorkspaceReactor.java | 3 +- .../workspaces/EditWorkspaceReactor.java | 5 +- .../skill/AttachSkillToWorkspaceReactor.java | 9 +- .../DetachSkillFromWorkspaceReactor.java | 4 +- .../definition/SaveAutomationReactor.java | 2 + .../UpdateEngineGuardrailConfigReactor.java | 3 + .../upload/CreateFunctionEngineReactor.java | 440 +++++++------- .../CreatePythonFunctionEngineReactor.java | 2 + .../upload/CreateGuardrailEngineReactor.java | 443 ++++++++------- .../model/UpdateModelRouterConfigReactor.java | 3 + .../upload/CreateModelEngineReactor.java | 476 ++++++++-------- .../project/CreateAppFromTemplateReactor.java | 9 +- .../ExtractAndSetDependenciesReactor.java | 6 +- .../project/SaveAppBlocksJsonReactor.java | 5 +- .../project/UploadProjectAppReactor.java | 9 +- .../reactor/project/UploadProjectReactor.java | 2 +- ...minBackfillCatalogDependenciesReactor.java | 290 ++++++++++ .../security/CatalogDependencyKeys.java | 27 + .../GetCatalogDependenciesReactor.java | 34 +- .../security/GetCatalogDependentsReactor.java | 108 ++++ .../SetCatalogDependenciesReactor.java | 52 +- .../ValidateCatalogDependenciesReactor.java | 27 + .../CreateVectorDatabaseEngineReactor.java | 536 +++++++++--------- src/prerna/util/AgentProjectArchiveUtils.java | 13 +- src/prerna/util/EngineCloneUtility.java | 26 + .../CatalogDependencyDerivationUnitTests.java | 154 +++++ ...curityCatalogDependencyUtilsUnitTests.java | 219 ++++++- .../utils/SecurityProjectUtilsUnitTests.java | 2 +- .../BrainTopicVotesUnitTests.java | 27 + .../AgentProjectArchiveUtilsUnitTests.java | 11 +- 38 files changed, 3019 insertions(+), 1085 deletions(-) create mode 100644 src/prerna/auth/utils/CatalogDependencyDerivation.java create mode 100644 src/prerna/auth/utils/CatalogDependencyRole.java create mode 100644 src/prerna/reactor/security/AdminBackfillCatalogDependenciesReactor.java create mode 100644 src/prerna/reactor/security/GetCatalogDependentsReactor.java create mode 100644 test/prerna/auth/utils/CatalogDependencyDerivationUnitTests.java diff --git a/src/prerna/auth/utils/AbstractSecurityUtils.java b/src/prerna/auth/utils/AbstractSecurityUtils.java index 5ca7bcabc81..ca23728c628 100644 --- a/src/prerna/auth/utils/AbstractSecurityUtils.java +++ b/src/prerna/auth/utils/AbstractSecurityUtils.java @@ -724,6 +724,7 @@ public static void initialize() throws Exception { final String VARCHAR_20 = "VARCHAR(20)"; final String VARCHAR_255 = "VARCHAR(255)"; final String VARCHAR_500 = "VARCHAR(500)"; + final String VARCHAR_2000 = "VARCHAR(2000)"; // 2021-08-06 // on h2 when you renmae a column it doens't update/change anything on the index @@ -1600,11 +1601,16 @@ public static void initialize() throws Exception { // CATALOGDEPENDENCIES // an engine or a project (the catalog item) and the engines and projects it - // depends on, each kept with its own engine type or project type + // depends on, each kept with its own engine type or project type. + // IS_AUTOMATIC: written by a save reactor from the item's own configuration + // (true), picked by a user (false), or from before the column (null, read as + // picked). ROLE: why the link exists, MANUAL for a picked one. NAME: a picked + // link's key, unique per item. DESCRIPTION: what the link is for, in words. + // TYPE is the login type of USERID. colNames = new String[] { "CATALOGID", "CATALOGTYPE", "DEPENDENCYID", "DEPENDENCYTYPE", "USERID", "TYPE", - "DATEADDED" }; + "DATEADDED", "IS_AUTOMATIC", "ROLE", "NAME", "DESCRIPTION" }; types = new String[] { VARCHAR_255, VARCHAR_255, VARCHAR_255, VARCHAR_255, VARCHAR_255, VARCHAR_255, - TIMESTAMP_DATATYPE_NAME }; + TIMESTAMP_DATATYPE_NAME, BOOLEAN_DATATYPE_NAME, VARCHAR_255, VARCHAR_255, VARCHAR_2000 }; defaultValues = null; if (allowIfExistsTable) { String sql = queryUtil.createTableIfNotExists(CatalogDependenciesMigration.NEW_TABLE, colNames, types); diff --git a/src/prerna/auth/utils/CatalogDependenciesMigration.java b/src/prerna/auth/utils/CatalogDependenciesMigration.java index 5838ab381a3..501025d2b4f 100644 --- a/src/prerna/auth/utils/CatalogDependenciesMigration.java +++ b/src/prerna/auth/utils/CatalogDependenciesMigration.java @@ -1,3 +1,30 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ package prerna.auth.utils; import java.sql.Connection; diff --git a/src/prerna/auth/utils/CatalogDependencyDerivation.java b/src/prerna/auth/utils/CatalogDependencyDerivation.java new file mode 100644 index 00000000000..2647abb9626 --- /dev/null +++ b/src/prerna/auth/utils/CatalogDependencyDerivation.java @@ -0,0 +1,422 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.auth.utils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.UnaryOperator; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import com.google.gson.Gson; + +import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; +import prerna.engine.api.IEngine; + +/** + * Works out the automatic dependencies of a catalog item from its own + * configuration, and saves them. Each save reactor calls the sync for what it + * saved; the derive methods are pure, given how to read an id's type, so they + * can be tested without a security database. + * + *

+ * A sync never fails the save that calls it: the configuration is the source of + * truth and was saved already, so a dependency that cannot be recorded is + * logged and left for the backfill. + *

+ */ +public final class CatalogDependencyDerivation { + + private static final Logger classLogger = LogManager.getLogger(CatalogDependencyDerivation.class); + + /** The roles read from an engine's smss */ + public static final List SMSS_ROLES = List.of(CatalogDependencyRole.JUDGE_MODEL, + CatalogDependencyRole.TOPIC_VECTOR, CatalogDependencyRole.EMBEDDER, CatalogDependencyRole.FUNCTION_STORAGE); + /** The roles read from a model router's router.json */ + public static final List ROUTER_ROLES = List.of(CatalogDependencyRole.ROUTE_MODEL, + CatalogDependencyRole.ROUTER_CLASSIFIER, CatalogDependencyRole.ROUTER_EMBEDDINGS, + CatalogDependencyRole.ROUTER_FALLBACK); + + /** The smss key of the model a guardrail asks to evaluate the text */ + static final String MODEL_ENGINE_ID = "MODEL_ENGINE_ID"; + /** The smss key of the vector database an On Topic guardrail compares with */ + static final String VECTOR_ENGINE_ID = "VECTOR_ENGINE_ID"; + /** The smss key of the model a vector database embeds with */ + static final String EMBEDDER_ENGINE_ID = "EMBEDDER_ENGINE_ID"; + /** The smss key of the storage engine a Google bucket function reads */ + static final String GOOGLE_BUCKET_ENGINEID = "GOOGLE_BUCKET_ENGINEID"; + + private CatalogDependencyDerivation() { + + } + + /* + * Derive + */ + + /** + * The guardrails an engine's pipeline.json runs, each once with every place it + * checks. + * + * @param pipelines the pipelines map: method name to {input, output}, each a list + * of checks with params.guardrailEngineId + * @param typeOf reads an id's catalog type, or null when it is not known + * @return a GUARDRAIL dependency for each guardrail + */ + public static List fromGuardrailPipelines(Map pipelines, UnaryOperator typeOf) { + Map> places = new LinkedHashMap<>(); + if (pipelines == null) { + return List.of(); + } + for (Map.Entry pipelineEntry : pipelines.entrySet()) { + if (!(pipelineEntry.getValue() instanceof Map pipeline)) { + continue; + } + String method = methodLabel(String.valueOf(pipelineEntry.getKey())); + for (String slot : new String[] { "input", "output" }) { + if (!(pipeline.get(slot) instanceof List checks)) { + continue; + } + for (Object check : checks) { + if (check instanceof Map checkMap && checkMap.get("params") instanceof Map params) { + String id = trimmed(params.get("guardrailEngineId")); + if (id != null) { + places.computeIfAbsent(id, key -> new LinkedHashSet<>()).add(method + " " + slot); + } + } + } + } + } + List dependencies = new ArrayList<>(); + for (Map.Entry> entry : places.entrySet()) { + add(dependencies, typeOf, entry.getKey(), CatalogDependencyRole.GUARDRAIL, + "Guardrail that checks this engine's " + String.join(", ", entry.getValue())); + } + return dependencies; + } + + /** + * The engines an engine's smss names: a guardrail's judge model or vector + * database, a vector database's embedding model, and a Google bucket function's + * storage engine. + * + * @param engineType the engine's type, such as GUARDRAIL + * @param smss its smss properties or creation details + * @param typeOf reads an id's catalog type, or null when it is not known + * @return the dependencies, under {@link #SMSS_ROLES} + */ + public static List fromSmss(String engineType, Map smss, UnaryOperator typeOf) { + List dependencies = new ArrayList<>(); + if (smss == null || engineType == null) { + return dependencies; + } + String type = engineType.trim().toUpperCase(java.util.Locale.ROOT); + if (IEngine.CATALOG_TYPE.GUARDRAIL.name().equals(type)) { + add(dependencies, typeOf, trimmed(smss.get(MODEL_ENGINE_ID)), CatalogDependencyRole.JUDGE_MODEL, + "Model that evaluates text for this guardrail"); + add(dependencies, typeOf, trimmed(smss.get(VECTOR_ENGINE_ID)), CatalogDependencyRole.TOPIC_VECTOR, + "Vector database this guardrail compares text with to stay on topic"); + } else if (IEngine.CATALOG_TYPE.VECTOR.name().equals(type)) { + add(dependencies, typeOf, trimmed(smss.get(EMBEDDER_ENGINE_ID)), CatalogDependencyRole.EMBEDDER, + "Model that creates this vector database's embeddings"); + } else if (IEngine.CATALOG_TYPE.FUNCTION.name().equals(type)) { + add(dependencies, typeOf, trimmed(smss.get(GOOGLE_BUCKET_ENGINEID)), CatalogDependencyRole.FUNCTION_STORAGE, + "Storage engine this function reads its bucket from"); + } + return dependencies; + } + + /** + * The models a model router's router.json sends to. + * + * @param config the router.json map: routes[].engine_id, classifier_engine, + * embeddings_engine and fallbacks + * @param typeOf reads an id's catalog type, or null when it is not known + * @return the dependencies, under {@link #ROUTER_ROLES} + */ + public static List fromRouterConfig(Map config, UnaryOperator typeOf) { + List dependencies = new ArrayList<>(); + if (config == null) { + return dependencies; + } + Map> routesByModel = new LinkedHashMap<>(); + if (config.get("routes") instanceof List routes) { + for (Object route : routes) { + if (route instanceof Map routeMap) { + String id = trimmed(routeMap.get("engine_id")); + if (id != null) { + String name = trimmed(routeMap.get("name")); + routesByModel.computeIfAbsent(id, key -> new LinkedHashSet<>()) + .add(name == null ? "unnamed" : "'" + name + "'"); + } + } + } + } + for (Map.Entry> entry : routesByModel.entrySet()) { + add(dependencies, typeOf, entry.getKey(), CatalogDependencyRole.ROUTE_MODEL, + "Model this router sends the " + String.join(", ", entry.getValue()) + + (entry.getValue().size() == 1 ? " route" : " routes") + " to"); + } + add(dependencies, typeOf, trimmed(config.get("classifier_engine")), CatalogDependencyRole.ROUTER_CLASSIFIER, + "Model this router classifies requests with"); + add(dependencies, typeOf, trimmed(config.get("embeddings_engine")), CatalogDependencyRole.ROUTER_EMBEDDINGS, + "Model this router embeds requests with"); + if (config.get("fallbacks") instanceof List fallbacks) { + for (Object fallback : fallbacks) { + add(dependencies, typeOf, trimmed(fallback), CatalogDependencyRole.ROUTER_FALLBACK, + "Model this router falls back to when a route fails"); + } + } + return dependencies; + } + + /** + * The models a model router's router.json sends to, from its JSON + * + * @param json the router.json text, or null + * @param typeOf reads an id's catalog type, or null when it is not known + * @return the dependencies, or none when the JSON cannot be read + */ + public static List fromRouterConfigJson(String json, UnaryOperator typeOf) { + if (json == null || json.isBlank()) { + return List.of(); + } + try { + return fromRouterConfig(new Gson().fromJson(json, Map.class), typeOf); + } catch (RuntimeException e) { + classLogger.warn("Unable to read the router configuration for its dependencies", e); + return List.of(); + } + } + + /** The node config keys that hold a catalog id */ + private static final String[] AUTOMATION_ID_KEYS = { "engineId", "appId", "workspaceId" }; + + /** + * The engines, apps and agents an automation's nodes use, each once with the + * nodes that use it. + * + * @param nodes the definition's nodes, each with label and config + * @param typeOf reads an id's catalog type, or null when it is not known + * @return an AUTOMATION_NODE dependency for each + */ + public static List fromAutomationNodes(Collection> nodes, + UnaryOperator typeOf) { + Map> nodesById = new LinkedHashMap<>(); + if (nodes == null) { + return List.of(); + } + for (Map node : nodes) { + if (!(node.get("config") instanceof Map config)) { + continue; + } + String label = trimmed(node.get("label")); + if (label == null) { + label = trimmed(node.get("id")); + } + for (String key : AUTOMATION_ID_KEYS) { + String id = trimmed(config.get(key)); + if (id != null) { + nodesById.computeIfAbsent(id, k -> new LinkedHashSet<>()).add(label == null ? "a node" : "'" + label + "'"); + } + } + } + List dependencies = new ArrayList<>(); + for (Map.Entry> entry : nodesById.entrySet()) { + add(dependencies, typeOf, entry.getKey(), CatalogDependencyRole.AUTOMATION_NODE, + "Used by the automation " + (entry.getValue().size() == 1 ? "step " : "steps ") + + String.join(", ", entry.getValue())); + } + return dependencies; + } + + /** + * The automatic dependencies of an agent from what it has saved: its + * resources (tools, knowledge and skills; prompts are not catalog items), and + * the model and subagents in its CONFIG_JSON. For the backfill; a save reads + * the same from the request. + * + * @param resources its WORKSPACE_RESOURCE rows, each with resource_id and + * resource_type + * @param modelId CONFIG_JSON.model_id, or null + * @param subagentIds the workspaceId of each CONFIG_JSON.subagents entry + * @param typeOf reads an id's catalog type, or null when it is not known + * @return the dependencies, under TOOLBOX, KNOWLEDGE, SKILL, AGENT_MODEL and + * SUBAGENT + */ + public static List fromWorkspace(Collection> resources, String modelId, + Collection subagentIds, UnaryOperator typeOf) { + List dependencies = new ArrayList<>(); + if (resources != null) { + for (Map resource : resources) { + String id = trimmed(resource.get("resource_id")); + String resourceType = trimmed(resource.get("resource_type")); + if (id == null || "PROMPT".equalsIgnoreCase(resourceType)) { + continue; + } + String type = typeOf.apply(id); + if ("SKILL".equalsIgnoreCase(resourceType)) { + add(dependencies, typeOf, id, CatalogDependencyRole.SKILL, "Skill attached to this agent"); + } else if (IEngine.CATALOG_TYPE.VECTOR.name().equals(type)) { + add(dependencies, typeOf, id, CatalogDependencyRole.KNOWLEDGE, "Knowledge base this agent searches"); + } else { + add(dependencies, typeOf, id, CatalogDependencyRole.TOOLBOX, "Tool this agent can call"); + } + } + } + add(dependencies, typeOf, trimmed(modelId), CatalogDependencyRole.AGENT_MODEL, "Model this agent runs on"); + if (subagentIds != null) { + for (String subagentId : subagentIds) { + add(dependencies, typeOf, trimmed(subagentId), CatalogDependencyRole.SUBAGENT, + "Subagent this agent can delegate to"); + } + } + return dependencies; + } + + /** The roles {@link #fromWorkspace} derives */ + public static final List WORKSPACE_ROLES = List.of(CatalogDependencyRole.TOOLBOX, + CatalogDependencyRole.KNOWLEDGE, CatalogDependencyRole.SKILL, CatalogDependencyRole.AGENT_MODEL, + CatalogDependencyRole.SUBAGENT); + + /* + * Sync + */ + + /** + * Saves the guardrails an engine's pipeline.json runs as its GUARDRAIL + * dependencies. + * + * @param user who saved the configuration + * @param engineId the guarded engine + * @param engineType its type + * @param pipelines the saved pipelines map + */ + public static void syncGuardrails(User user, String engineId, String engineType, Map pipelines) { + sync(user, engineId, engineType, List.of(CatalogDependencyRole.GUARDRAIL), + () -> fromGuardrailPipelines(pipelines, CatalogTypes::resolve)); + } + + /** + * Saves the engines an engine's smss names as its dependencies. + * + * @param user who created or changed the engine + * @param engineId the engine + * @param engineType its type + * @param smss its smss properties or creation details + */ + public static void syncSmss(User user, String engineId, String engineType, Map smss) { + sync(user, engineId, engineType, SMSS_ROLES, () -> fromSmss(engineType, smss, CatalogTypes::resolve)); + } + + /** + * Saves the models a model router sends to as its dependencies. + * + * @param user who saved the router + * @param engineId the router + * @param config its router.json map + */ + public static void syncRouter(User user, String engineId, Map config) { + sync(user, engineId, IEngine.CATALOG_TYPE.MODEL.name(), ROUTER_ROLES, + () -> fromRouterConfig(config, CatalogTypes::resolve)); + } + + /** + * Saves the models a model router sends to as its dependencies, from its JSON. + * + * @param user who created the router + * @param engineId the router + * @param json its router.json text + */ + public static void syncRouterJson(User user, String engineId, String json) { + sync(user, engineId, IEngine.CATALOG_TYPE.MODEL.name(), ROUTER_ROLES, + () -> fromRouterConfigJson(json, CatalogTypes::resolve)); + } + + /** + * Saves the engines, apps and agents an automation's nodes use as its + * dependencies. + * + * @param user who saved the automation + * @param projectId the automation + * @param nodes the saved definition's nodes + */ + public static void syncAutomation(User user, String projectId, Collection> nodes) { + sync(user, projectId, prerna.project.api.IProject.PROJECT_TYPE.AUTOMATION.name(), + List.of(CatalogDependencyRole.AUTOMATION_NODE), () -> fromAutomationNodes(nodes, CatalogTypes::resolve)); + } + + private static void sync(User user, String catalogId, String catalogType, List roles, + java.util.function.Supplier> derive) { + try { + SecurityCatalogDependencyUtils.syncAutomaticDependencies(user, catalogId, catalogType, roles, + derive.get()); + } catch (RuntimeException e) { + classLogger.warn("Saved {} but could not record its {} dependencies", catalogId, roles, e); + } + } + + /* + * Helpers + */ + + private static void add(List dependencies, UnaryOperator typeOf, String id, + CatalogDependencyRole role, String description) { + if (id == null) { + return; + } + String type = typeOf.apply(id); + if (type == null) { + classLogger.warn("{} is not an engine or a project, so it is not recorded as a {} dependency", id, role); + return; + } + dependencies.add(Dependency.automatic(id, type, role, description)); + } + + private static String methodLabel(String method) { + if (method.isBlank() || "*".equals(method) || "ALL".equalsIgnoreCase(method)) { + return "every method's"; + } + return method; + } + + private static String trimmed(Object value) { + if (!(value instanceof String text)) { + return null; + } + String trimmed = text.trim(); + return trimmed.isEmpty() ? null : trimmed; + } +} diff --git a/src/prerna/auth/utils/CatalogDependencyRole.java b/src/prerna/auth/utils/CatalogDependencyRole.java new file mode 100644 index 00000000000..b06d4de5276 --- /dev/null +++ b/src/prerna/auth/utils/CatalogDependencyRole.java @@ -0,0 +1,102 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.auth.utils; + +import java.util.Locale; + +/** + * Why a catalog item depends on another, kept in CATALOGDEPENDENCIES.ROLE. Every + * role but {@link #MANUAL} is written by a save reactor from the item's own + * configuration, and only that reactor changes it; {@link #MANUAL} is a + * dependency a user picked. + */ +public enum CatalogDependencyRole { + + /** Picked by a user with SetCatalogDependencies */ + MANUAL, + + /** The model an agent runs on */ + AGENT_MODEL, + /** An agent another agent can delegate to */ + SUBAGENT, + /** A skill attached to an agent */ + SKILL, + /** An engine or MCP project an agent can call as a tool */ + TOOLBOX, + /** A vector database an agent searches */ + KNOWLEDGE, + + /** A guardrail that checks calls to an engine */ + GUARDRAIL, + /** The model a guardrail asks to evaluate the text */ + JUDGE_MODEL, + /** The vector database an On Topic guardrail compares the text with */ + TOPIC_VECTOR, + /** The model a vector database embeds with */ + EMBEDDER, + /** The storage engine a function reads its bucket from */ + FUNCTION_STORAGE, + + /** A model a router sends a route to */ + ROUTE_MODEL, + /** The model a router classifies requests with */ + ROUTER_CLASSIFIER, + /** The model a router embeds requests with */ + ROUTER_EMBEDDINGS, + /** A model a router falls back to */ + ROUTER_FALLBACK, + + /** An engine, app or agent a node of an automation uses */ + AUTOMATION_NODE, + /** An engine a block of a blocks app uses */ + BLOCK_ENGINE, + /** An engine id found in an app's files */ + CODE_REFERENCE; + + /** Whether a save reactor writes this role, rather than a user */ + public boolean isAutomatic() { + return this != MANUAL; + } + + /** + * The role of a stored value + * + * @param value the stored ROLE, which may be null for a row from before roles + * @return the role, or {@link #MANUAL} when there is none or it is not known + */ + public static CatalogDependencyRole fromStored(String value) { + if (value == null || value.isBlank()) { + return MANUAL; + } + try { + return valueOf(value.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + return MANUAL; + } + } +} diff --git a/src/prerna/auth/utils/CatalogTypes.java b/src/prerna/auth/utils/CatalogTypes.java index f9c91f1fdff..b1aebd35053 100644 --- a/src/prerna/auth/utils/CatalogTypes.java +++ b/src/prerna/auth/utils/CatalogTypes.java @@ -1,3 +1,30 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ package prerna.auth.utils; import java.util.ArrayList; diff --git a/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java b/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java index 79485932522..b1976aa264f 100644 --- a/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java +++ b/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java @@ -1,3 +1,30 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ package prerna.auth.utils; import java.io.File; @@ -99,23 +126,93 @@ public class SecurityCatalogDependencyUtils extends AbstractSecurityUtils { private static final String TABLE = "CATALOGDEPENDENCIES"; + /** The longest DESCRIPTION kept */ + private static final int MAX_DESCRIPTION = 2000; + /** - * One dependency of a catalog item: the engine or project it depends on, and - * that item's own type. + * One dependency of a catalog item: the engine or project it depends on, that + * item's own type, and what the link is. * - * @param id the engine id or project id - * @param type its engine type or project type, read with - * {@link CatalogTypes#normalize} + * @param id the engine id or project id + * @param type its engine type or project type, read with + * {@link CatalogTypes#normalize} + * @param automatic true when a save reactor derived it from the item's + * configuration, false when a user picked it, null for a row + * from before the column (read as picked) + * @param role why the link exists; {@link CatalogDependencyRole#MANUAL} + * for a picked one + * @param name a picked link's key, unique per item, or null + * @param description what the link is for, in words, or null */ - public record Dependency(String id, String type) { + public record Dependency(String id, String type, Boolean automatic, CatalogDependencyRole role, String name, + String description) { public Dependency { if (id == null || id.isBlank()) { throw new IllegalArgumentException("A dependency id is required"); } type = CatalogTypes.normalize(type); + if (role == null) { + role = CatalogDependencyRole.MANUAL; + } + name = blankToNull(name); + description = blankToNull(description); + if (description != null && description.length() > MAX_DESCRIPTION) { + description = description.substring(0, MAX_DESCRIPTION); + } + } + + /** A dependency a user picked, with no name or description */ + public Dependency(String id, String type) { + this(id, type, false, CatalogDependencyRole.MANUAL, null, null); + } + + /** + * A dependency a user picked + * + * @param id the engine id or project id + * @param type its type + * @param name its key, or null + * @param description what it is for, or null + * @return the dependency + */ + public static Dependency manual(String id, String type, String name, String description) { + return new Dependency(id, type, false, CatalogDependencyRole.MANUAL, name, description); + } + + /** + * A dependency a save reactor derived from the item's configuration + * + * @param id the engine id or project id + * @param type its type + * @param role why the link exists; not MANUAL + * @param description what it is for, in words + * @return the dependency + */ + public static Dependency automatic(String id, String type, CatalogDependencyRole role, String description) { + if (role == null || !role.isAutomatic()) { + throw new IllegalArgumentException("An automatic dependency needs a role other than MANUAL"); + } + return new Dependency(id, type, true, role, null, description); + } + + /** Whether this is a picked dependency, a row from before the column included */ + public boolean isManual() { + return !Boolean.TRUE.equals(automatic); + } + + private String key() { + return isManual() ? id : id + "|" + role.name(); } } + private static String blankToNull(String value) { + if (value == null) { + return null; + } + String trimmed = value.trim(); + return trimmed.isEmpty() ? null : trimmed; + } + SecurityCatalogDependencyUtils() { } @@ -222,133 +319,267 @@ public static List resolveDependencies(Collection ids, Colle /* * Writes + * + * A catalog item has two kinds of dependencies. Picked ones (IS_AUTOMATIC false, + * or null for a row from before the column) are set by a user with + * SetCatalogDependencies. Automatic ones are derived by a save reactor from the + * item's configuration, each under its role, and only that reactor changes + * them. Writing one kind never touches the other, except that an automatic + * dependency replaces a row from before the column on the same item, so an item + * saved again does not list a dependency twice. */ + /** The filter for a picked row, a row from before the column included */ + private static final String MANUAL_ROWS = "(IS_AUTOMATIC IS NULL OR IS_AUTOMATIC = ?)"; + /** - * Replaces all the dependencies of a catalog item, in one transaction. + * Replaces the dependencies a user picked for a catalog item, keeping the + * automatic ones, in one transaction. * * @param user who sets them * @param catalogId the engine id or project id * @param catalogType its engine type or project type - * @param dependencies its dependencies; an empty list removes them all - * @throws IllegalStateException when they cannot be saved; nothing is changed + * @param dependencies the picked dependencies; an empty list removes them all + * @throws IllegalArgumentException when two have the same name + * @throws IllegalStateException when they cannot be saved; nothing is changed */ - public static void setDependencies(User user, String catalogId, String catalogType, + public static void setManualDependencies(User user, String catalogId, String catalogType, Collection dependencies) { String ownerType = CatalogTypes.normalize(catalogType); - IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); - try { - QueryExecutionUtility.write(securityDb, connection -> { - QueryExecutionUtility.executeUpdate(connection, "DELETE FROM " + TABLE + " WHERE CATALOGID=?", - ps -> ps.setString(1, catalogId)); - insert(connection, user, catalogId, ownerType, withoutOwnerAndRepeats(catalogId, dependencies)); - return null; - }); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - classLogger.error("Failed to set the dependencies of {}", catalogId, e); - throw new IllegalStateException("Unable to save the dependencies of " + catalogId, e); + List picked = new ArrayList<>(); + for (Dependency dependency : withoutOwnerAndRepeats(catalogId, dependencies)) { + picked.add(Dependency.manual(dependency.id(), dependency.type(), dependency.name(), + dependency.description())); + } + checkUniqueNames(picked); + write(catalogId, "set the dependencies of", connection -> { + QueryExecutionUtility.executeUpdate(connection, + "DELETE FROM " + TABLE + " WHERE CATALOGID=? AND " + MANUAL_ROWS, ps -> { + ps.setString(1, catalogId); + ps.setBoolean(2, false); + }); + insert(connection, user, catalogId, ownerType, picked); + }); + } + + /** + * Replaces the automatic dependencies of a catalog item under some roles with + * the ones given, in one transaction. Dependencies under other roles, and the + * picked ones, are kept, so each save reactor replaces only the roles it + * derives. + * + * @param user who saved the item + * @param catalogId the engine id or project id + * @param catalogType its engine type or project type + * @param roles the roles the caller derives + * @param dependencies the dependencies it derived now, each under one of the + * roles; an empty list removes them all + * @throws IllegalStateException when they cannot be saved; nothing is changed + */ + public static void syncAutomaticDependencies(User user, String catalogId, String catalogType, + Collection roles, Collection dependencies) { + if (roles == null || roles.isEmpty()) { + return; } + String ownerType = CatalogTypes.normalize(catalogType); + List derived = automaticOnly(catalogId, roles, dependencies); + List roleNames = roles.stream().map(CatalogDependencyRole::name).distinct().toList(); + write(catalogId, "save the automatic dependencies of", connection -> { + deleteAutomatic(connection, catalogId, roleNames); + deleteLegacy(connection, catalogId, derived); + insert(connection, user, catalogId, ownerType, derived); + }); } /** - * Replaces all the dependencies of a catalog item with the engines and projects - * of these ids, reading their types from the security database. Ids that are - * neither are left out. + * Replaces the automatic dependencies of a catalog item under one role with the + * engines and projects of these ids, reading their types from the security + * database. Ids that are neither are left out. * - * @param user who sets them + * @param user who saved the item * @param catalogId the engine id or project id * @param catalogType its engine type or project type + * @param role the role of each + * @param description what each is for, in words * @param ids the engine ids and project ids it depends on * @return the ids left out, which are neither an engine nor a project */ - public static List setDependencyIds(User user, String catalogId, String catalogType, - Collection ids) { + public static List syncAutomaticDependencyIds(User user, String catalogId, String catalogType, + CatalogDependencyRole role, String description, Collection ids) { List failed = new ArrayList<>(); - setDependencies(user, catalogId, catalogType, resolveDependencies(ids, failed)); + List dependencies = new ArrayList<>(); + for (Dependency resolved : resolveDependencies(ids, failed)) { + dependencies.add(Dependency.automatic(resolved.id(), resolved.type(), role, description)); + } + syncAutomaticDependencies(user, catalogId, catalogType, List.of(role), dependencies); return failed; } /** - * Adds dependencies to a catalog item, keeping the ones it has, in one - * transaction. + * Adds automatic dependencies to a catalog item, keeping every one it has, in + * one transaction. * - * @param user who adds them + * @param user who saved the item * @param catalogId the engine id or project id * @param catalogType its engine type or project type - * @param dependencies the dependencies to add; ones it has already are skipped + * @param dependencies the automatic dependencies to add; ones it has already + * under the same role are skipped * @throws IllegalStateException when they cannot be saved; nothing is changed */ - public static void addDependencies(User user, String catalogId, String catalogType, + public static void addAutomaticDependencies(User user, String catalogId, String catalogType, Collection dependencies) { String ownerType = CatalogTypes.normalize(catalogType); - IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); - try { - QueryExecutionUtility.write(securityDb, connection -> { - Set existing = new HashSet<>(QueryExecutionUtility.queryList(connection, - "SELECT DEPENDENCYID FROM " + TABLE + " WHERE CATALOGID=?", ps -> ps.setString(1, catalogId), - rs -> rs.getString(1))); - List toAdd = new ArrayList<>(); - for (Dependency dependency : withoutOwnerAndRepeats(catalogId, dependencies)) { - if (!existing.contains(dependency.id())) { - toAdd.add(dependency); - } - } - insert(connection, user, catalogId, ownerType, toAdd); - return null; - }); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - classLogger.error("Failed to add dependencies to {}", catalogId, e); - throw new IllegalStateException("Unable to save the dependencies of " + catalogId, e); - } + List derived = automaticOnly(catalogId, Arrays.asList(CatalogDependencyRole.values()), + dependencies); + write(catalogId, "add automatic dependencies to", connection -> { + Set existing = new HashSet<>(QueryExecutionUtility.queryList(connection, + "SELECT DEPENDENCYID, ROLE FROM " + TABLE + " WHERE CATALOGID=? AND IS_AUTOMATIC = ?", ps -> { + ps.setString(1, catalogId); + ps.setBoolean(2, true); + }, rs -> rs.getString(1) + "|" + CatalogDependencyRole.fromStored(rs.getString(2)).name())); + List toAdd = derived.stream().filter(d -> !existing.contains(d.key())).toList(); + deleteLegacy(connection, catalogId, toAdd); + insert(connection, user, catalogId, ownerType, toAdd); + }); } /** - * Removes one dependency from a catalog item. + * Removes one automatic dependency of a catalog item, under one role. The + * picked dependencies on the same engine or project are kept. * - * @param user who removes it; they must be able to edit the item * @param catalogId the engine id or project id - * @param dependencyId the engine id or project id it no longer depends on - * @throws IllegalAccessException when the user cannot edit the item + * @param dependencyId the engine id or project id + * @param role the role it no longer has + * @throws IllegalStateException when it cannot be removed */ - public static void removeDependency(User user, String catalogId, String dependencyId) - throws IllegalAccessException { - String catalogType = resolveCatalogType(catalogId, null); - if (!userCanEdit(user, catalogId, catalogType)) { - throw new IllegalAccessException("User does not have permissions to remove dependencies"); - } - IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); - try { - QueryExecutionUtility.executeUpdate(securityDb, - "DELETE FROM " + TABLE + " WHERE CATALOGID=? AND DEPENDENCYID=?", ps -> { + public static void removeAutomaticDependency(String catalogId, String dependencyId, CatalogDependencyRole role) { + write(catalogId, "remove an automatic dependency of", connection -> { + QueryExecutionUtility.executeUpdate(connection, "DELETE FROM " + TABLE + + " WHERE CATALOGID=? AND DEPENDENCYID=? AND IS_AUTOMATIC = ? AND ROLE=?", ps -> { ps.setString(1, catalogId); ps.setString(2, dependencyId); + ps.setBoolean(3, true); + ps.setString(4, role.name()); }); - } catch (Exception e) { - classLogger.error("Failed to remove the dependency of {} on {}", catalogId, dependencyId, e); - throw new IllegalStateException("Unable to remove the dependency on " + dependencyId, e); - } + // a row from before the column was most likely written by the same save + deleteLegacyIds(connection, catalogId, List.of(dependencyId)); + }); } /** - * Removes the dependencies a deleted engine or project owned. The rows of other - * items that depend on it are kept, so validating them shows it is gone. + * Replaces every dependency of a catalog item, picked and automatic, with the + * ones given, as they are, in one transaction. For an item that was just + * imported with its dependency file. * - * @param catalogId the engine id or project id + * @param user who imported it + * @param catalogId the engine id or project id + * @param catalogType its engine type or project type + * @param dependencies its dependencies + * @throws IllegalStateException when they cannot be saved; nothing is changed */ - public static void deleteDependenciesOwnedBy(String catalogId) { + public static void replaceAllDependencies(User user, String catalogId, String catalogType, + Collection dependencies) { + String ownerType = CatalogTypes.normalize(catalogType); + List kept = withoutOwnerAndRepeats(catalogId, dependencies); + List picked = kept.stream().filter(Dependency::isManual).toList(); + checkUniqueNames(picked); + write(catalogId, "set the dependencies of", connection -> { + QueryExecutionUtility.executeUpdate(connection, "DELETE FROM " + TABLE + " WHERE CATALOGID=?", + ps -> ps.setString(1, catalogId)); + insert(connection, user, catalogId, ownerType, kept); + }); + } + + /** Work run in a transaction on the security database */ + @FunctionalInterface + private interface WriteWork { + void run(Connection connection) throws Exception; + } + + private static void write(String catalogId, String action, WriteWork work) { IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); try { - QueryExecutionUtility.executeUpdate(securityDb, "DELETE FROM " + TABLE + " WHERE CATALOGID=?", - ps -> ps.setString(1, catalogId)); + QueryExecutionUtility.write(securityDb, connection -> { + work.run(connection); + return null; + }); + } catch (RuntimeException e) { + throw e; } catch (Exception e) { - classLogger.error("Failed to delete the dependencies of {}", catalogId, e); + classLogger.error("Failed to {} {}", action, catalogId, e); + throw new IllegalStateException("Unable to save the dependencies of " + catalogId, e); + } + } + + private static void checkUniqueNames(Collection picked) { + Set names = new HashSet<>(); + for (Dependency dependency : picked) { + String name = dependency.name(); + if (name != null && !names.add(name.toLowerCase(java.util.Locale.ROOT))) { + throw new IllegalArgumentException("Two dependencies are named '" + name + "'; each name must be unique"); + } } } + private static List automaticOnly(String catalogId, Collection roles, + Collection dependencies) { + List derived = new ArrayList<>(); + if (dependencies == null) { + return derived; + } + Set seen = new HashSet<>(); + for (Dependency dependency : dependencies) { + if (dependency.isManual() || !roles.contains(dependency.role())) { + throw new IllegalArgumentException( + "An automatic dependency must have one of the roles " + roles + ", not " + dependency.role()); + } + if (dependency.id().equals(catalogId)) { + classLogger.warn("{} cannot depend on itself", catalogId); + continue; + } + if (seen.add(dependency.key())) { + derived.add(dependency); + } + } + return derived; + } + + private static void deleteAutomatic(Connection connection, String catalogId, List roleNames) + throws Exception { + String placeholders = String.join(", ", java.util.Collections.nCopies(roleNames.size(), "?")); + QueryExecutionUtility.executeUpdate(connection, "DELETE FROM " + TABLE + + " WHERE CATALOGID=? AND IS_AUTOMATIC = ? AND ROLE IN (" + placeholders + ")", ps -> { + ps.setString(1, catalogId); + ps.setBoolean(2, true); + for (int i = 0; i < roleNames.size(); i++) { + ps.setString(3 + i, roleNames.get(i)); + } + }); + } + + /** Deletes the rows from before IS_AUTOMATIC that the dependencies now stand for */ + private static void deleteLegacy(Connection connection, String catalogId, List dependencies) + throws Exception { + Set ids = new LinkedHashSet<>(); + for (Dependency dependency : dependencies) { + ids.add(dependency.id()); + } + deleteLegacyIds(connection, catalogId, ids); + } + + private static void deleteLegacyIds(Connection connection, String catalogId, Collection ids) + throws Exception { + if (ids.isEmpty()) { + return; + } + QueryExecutionUtility.executeBatch(connection, + "DELETE FROM " + TABLE + " WHERE CATALOGID=? AND DEPENDENCYID=? AND IS_AUTOMATIC IS NULL", ids, + (ps, id) -> { + ps.setString(1, catalogId); + ps.setString(2, id); + }); + } + /* * Export and import */ @@ -409,7 +640,19 @@ public static List fromExported(List> rows) { classLogger.warn("Left out the exported dependency on {}: its type is not known", id); continue; } - dependencies.add(new Dependency(id, type)); + // exports from before roles have no link fields: each is a picked dependency + boolean automatic = Boolean.TRUE.equals(row.get("is_automatic")); + Object role = row.get("role"); + Object name = row.get("dependency_name"); + Object description = row.get("dependency_description"); + CatalogDependencyRole storedRole = CatalogDependencyRole.fromStored(role instanceof String r ? r : null); + if (automatic && storedRole.isAutomatic()) { + dependencies.add(Dependency.automatic(id, type, storedRole, + description instanceof String d ? d : null)); + } else { + dependencies.add(Dependency.manual(id, type, name instanceof String n ? n : null, + description instanceof String d ? d : null)); + } } return dependencies; } @@ -425,7 +668,7 @@ private static List withoutOwnerAndRepeats(String catalogId, Collect classLogger.warn("{} cannot depend on itself", catalogId); continue; } - if (seen.add(dependency.id())) { + if (seen.add(dependency.key())) { kept.add(dependency); } } @@ -442,8 +685,10 @@ private static void insert(Connection connection, User user, String catalogId, S String userType = token == null ? null : token.getProvider().getLabel(); java.sql.Timestamp timestamp = Utility.getCurrentSqlTimestampUTC(); String query = "INSERT INTO " + TABLE - + " (CATALOGID, CATALOGTYPE, DEPENDENCYID, DEPENDENCYTYPE, USERID, TYPE, DATEADDED) VALUES (?, ?, ?, ?, ?, ?, ?)"; + + " (CATALOGID, CATALOGTYPE, DEPENDENCYID, DEPENDENCYTYPE, USERID, TYPE, DATEADDED, IS_AUTOMATIC, ROLE, NAME, DESCRIPTION)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; QueryExecutionUtility.executeBatch(connection, query, dependencies, (ps, dependency) -> { + boolean automatic = !dependency.isManual(); ps.setString(1, catalogId); ps.setString(2, catalogType); ps.setString(3, dependency.id()); @@ -451,6 +696,10 @@ private static void insert(Connection connection, User user, String catalogId, S ps.setString(5, userId); ps.setString(6, userType); ps.setTimestamp(7, timestamp); + ps.setBoolean(8, automatic); + ps.setString(9, automatic ? dependency.role().name() : CatalogDependencyRole.MANUAL.name()); + ps.setString(10, automatic ? null : dependency.name()); + ps.setString(11, dependency.description()); }); } @@ -491,6 +740,8 @@ private static List> getDirectDependencies(String catalogId) qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__DEPENDENCYID", "catalog_id")); qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__DEPENDENCYTYPE", "catalog_type")); qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("CATALOGDEPENDENCIES__CATALOGID", "==", catalogId)); + // a dependency with more than one role has a row for each; it is one dependency + qs.setDistinct(true); return QueryExecutionUtility.flushRsToMap(securityDb, qs); } @@ -507,6 +758,62 @@ private static void collect(String catalogId, boolean subdependencies, Set> getDependents(String dependencyId, boolean recursive) { + List> all = new ArrayList<>(); + Set visited = new HashSet<>(); + java.util.ArrayDeque queue = new java.util.ArrayDeque<>(); + queue.add(dependencyId); + while (!queue.isEmpty()) { + String id = queue.poll(); + if (!visited.add(id)) { + continue; + } + for (Map dependent : getDirectDependents(id)) { + all.add(dependent); + if (recursive) { + queue.add((String) dependent.get("catalog_id")); + } + } + } + return all; + } + + private static List> getDirectDependents(String dependencyId) { + IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); + SimpleQueryFilter ownerIsProject = SimpleQueryFilter.makeColToValFilter("CATALOGDEPENDENCIES__CATALOGTYPE", + "==", new ArrayList<>(CatalogTypes.projectTypes())); + SelectQueryStruct qs = new SelectQueryStruct(); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__DEPENDENCYID", "dependency_id")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__CATALOGID", "catalog_id")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__CATALOGTYPE", "catalog_type")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__IS_AUTOMATIC", "is_automatic")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__ROLE", "role")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__NAME", "dependency_name")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__DESCRIPTION", "dependency_description")); + qs.addSelector(QueryIfSelector.makeQueryIfSelector(ownerIsProject, + new QueryColumnSelector("PROJECT__PROJECTNAME"), new QueryColumnSelector("ENGINE__ENGINENAME"), + "catalog_name")); + qs.addSelector(QueryIfSelector.makeQueryIfSelector(ownerIsProject, new QueryColumnSelector("PROJECT__TYPE"), + new QueryColumnSelector("ENGINE__ENGINESUBTYPE"), "catalog_subtype")); + qs.addRelation("CATALOGDEPENDENCIES__CATALOGID", "ENGINE__ENGINEID", "left.outer.join"); + qs.addRelation("CATALOGDEPENDENCIES__CATALOGID", "PROJECT__PROJECTID", "left.outer.join"); + qs.addExplicitFilter( + SimpleQueryFilter.makeColToValFilter("CATALOGDEPENDENCIES__DEPENDENCYID", "==", dependencyId)); + return normalizeLinks(QueryExecutionUtility.flushRsToMap(securityDb, qs)); + } + /** * Whether a user can view each dependency of a catalog item, all the way down * @@ -565,7 +872,24 @@ private static List> getDependencyDetailsQuery(String catalo IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); SelectQueryStruct qs = new SelectQueryStruct(); addDetailSelectors(qs, catalogId); - return QueryExecutionUtility.flushRsToMap(securityDb, qs); + return normalizeLinks(QueryExecutionUtility.flushRsToMap(securityDb, qs)); + } + + /** + * Reads each row's link as its kind: a row from before IS_AUTOMATIC is a picked + * one with the MANUAL role, and an automatic one never has a name + */ + private static List> normalizeLinks(List> rows) { + for (Map row : rows) { + boolean automatic = Boolean.TRUE.equals(row.get("is_automatic")); + row.put("is_automatic", automatic); + row.put("role", automatic ? CatalogDependencyRole.fromStored((String) row.get("role")).name() + : CatalogDependencyRole.MANUAL.name()); + if (automatic) { + row.put("dependency_name", null); + } + } + return rows; } /** @@ -577,6 +901,11 @@ private static void addDetailSelectors(SelectQueryStruct qs, String catalogId) { qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__CATALOGID", "parent_id")); qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__DEPENDENCYID", "catalog_id")); qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__DEPENDENCYTYPE", "catalog_type")); + // the link itself: one row per role + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__IS_AUTOMATIC", "is_automatic")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__ROLE", "role")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__NAME", "dependency_name")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__DESCRIPTION", "dependency_description")); qs.addSelector(QueryIfSelector.makeQueryIfSelector(isProjectDependency(), new QueryColumnSelector("PROJECT__PROJECTNAME"), new QueryColumnSelector("ENGINE__ENGINENAME"), "catalog_name")); @@ -611,10 +940,11 @@ private static void addDetailSelectors(SelectQueryStruct qs, String catalogId) { public static List> getDependencyDetails(String catalogId, User user, boolean subdependencies) { if (!subdependencies) { - return getDependencyDetailsWithUserQuery(catalogId, user); + return normalizeLinks(getDependencyDetailsWithUserQuery(catalogId, user)); } List> all = new ArrayList<>(); - collect(catalogId, true, new HashSet<>(), all, id -> getDependencyDetailsWithUserQuery(id, user)); + collect(catalogId, true, new HashSet<>(), all, + id -> normalizeLinks(getDependencyDetailsWithUserQuery(id, user))); calculateCanViewDependencies(all); return all; } diff --git a/src/prerna/auth/utils/SecurityOwlCreator.java b/src/prerna/auth/utils/SecurityOwlCreator.java index c365e168b18..cb6ea599bb3 100644 --- a/src/prerna/auth/utils/SecurityOwlCreator.java +++ b/src/prerna/auth/utils/SecurityOwlCreator.java @@ -213,7 +213,11 @@ public void createColumnsAndTypes(AbstractSqlQueryUtil queryUtil) { Pair.with("DEPENDENCYTYPE", VARCHAR_255), Pair.with("USERID", VARCHAR_255), Pair.with("TYPE", VARCHAR_255), - Pair.with("DATEADDED", TIMESTAMP_DATATYPE_NAME))); + Pair.with("DATEADDED", TIMESTAMP_DATATYPE_NAME), + Pair.with("IS_AUTOMATIC", BOOLEAN_DATATYPE_NAME), + Pair.with("ROLE", VARCHAR_255), + Pair.with("NAME", VARCHAR_255), + Pair.with("DESCRIPTION", "VARCHAR(2000)"))); addTable("ASSETENGINE", Arrays.asList( Pair.with("PROJECTID", VARCHAR_255), diff --git a/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/AbstractWorkspaceReactor.java b/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/AbstractWorkspaceReactor.java index 7e7be144cdf..08ecca2a673 100644 --- a/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/AbstractWorkspaceReactor.java +++ b/src/prerna/engine/impl/model/inferencetracking/reactors/workspaces/AbstractWorkspaceReactor.java @@ -38,12 +38,14 @@ import org.json.JSONArray; import org.json.JSONObject; +import prerna.auth.utils.CatalogDependencyRole; import prerna.auth.utils.CatalogTypes; import prerna.auth.utils.SecurityCatalogDependencyUtils; import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; import prerna.auth.User; import prerna.auth.utils.SecurityEngineUtils; import prerna.auth.utils.SecurityProjectUtils; +import prerna.engine.api.IEngine; import prerna.engine.api.IEngine.CATALOG_TYPE; import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils; import prerna.project.api.IProject; @@ -599,6 +601,51 @@ private static void applyIntegerUpdates(JSONObject cfg, String subObjectKey, Map cfg.put(subObjectKey, sub); } + /** + * Saves the automatic dependencies of an agent: its tools, knowledge and + * skills, and its model and subagents when the request gives them. A model or + * subagent list that is not given keeps the dependencies it has. + * + * @param user who saved the agent + * @param workspaceId the agent's id + * @param toolsAndSkills the tool, knowledge and skill dependencies read by + * {@link #validateWorkspaceInputs} + * @param modelProvided whether the request gives the model + * @param modelId the agent's model, or blank for none + * @param subagentsProvided whether the request gives the subagents + * @param subagents the normalized subagents, each with a workspaceId + */ + protected static void syncWorkspaceDependencies(User user, String workspaceId, List toolsAndSkills, + boolean modelProvided, String modelId, boolean subagentsProvided, List> subagents) { + List roles = new ArrayList<>( + List.of(CatalogDependencyRole.TOOLBOX, CatalogDependencyRole.KNOWLEDGE, CatalogDependencyRole.SKILL)); + List dependencies = new ArrayList<>(toolsAndSkills); + if (modelProvided) { + roles.add(CatalogDependencyRole.AGENT_MODEL); + if (modelId != null && !modelId.isBlank()) { + String modelType = CatalogTypes.resolve(modelId.trim()); + if (modelType != null) { + dependencies.add(Dependency.automatic(modelId.trim(), modelType, CatalogDependencyRole.AGENT_MODEL, + "Model this agent runs on")); + } + } + } + if (subagentsProvided) { + roles.add(CatalogDependencyRole.SUBAGENT); + if (subagents != null) { + for (Map subagent : subagents) { + Object target = subagent.get("workspaceId"); + if (target instanceof String targetId && !targetId.isBlank()) { + dependencies.add(Dependency.automatic(targetId, IProject.PROJECT_TYPE.WORKSPACE.name(), + CatalogDependencyRole.SUBAGENT, "Subagent this agent can delegate to")); + } + } + } + } + SecurityCatalogDependencyUtils.syncAutomaticDependencies(user, workspaceId, + IProject.PROJECT_TYPE.WORKSPACE.name(), roles, dependencies); + } + /** * Reads the MCP / prompt / skill nouns from the request, validates them, and * populates the caller-owned accumulators in place. Throws @@ -643,7 +690,12 @@ protected void validateWorkspaceInputs(User user, String workspaceId, Set 0) { try { - SecurityCatalogDependencyUtils.removeDependency(user, workspaceId, skillId); + SecurityCatalogDependencyUtils.removeAutomaticDependency(workspaceId, skillId, + CatalogDependencyRole.SKILL); } catch (Exception depEx) { classLogger.warn( "Detached skill '{}' from workspace '{}' but failed to remove CATALOGDEPENDENCIES entry", diff --git a/src/prerna/reactor/automation/definition/SaveAutomationReactor.java b/src/prerna/reactor/automation/definition/SaveAutomationReactor.java index 1ee61ebc69b..69d8c1cbcb8 100644 --- a/src/prerna/reactor/automation/definition/SaveAutomationReactor.java +++ b/src/prerna/reactor/automation/definition/SaveAutomationReactor.java @@ -27,6 +27,7 @@ *******************************************************************************/ package prerna.reactor.automation.definition; +import prerna.auth.utils.CatalogDependencyDerivation; import java.util.LinkedHashMap; import java.util.Map; @@ -90,6 +91,7 @@ public NounMetadata execute() { "nodeSourceCount", files.nodeSources() == null ? 0 : files.nodeSources().size())); AutomationDefinitionValidator.ValidatedDefinition validated = AutomationDefinitionValidator .parseAndValidateForAuthoring(files.definition()); + CatalogDependencyDerivation.syncAutomation(this.insight.getUser(), projectId, validated.nodes()); result.put(AutomationConstants.DOC_GLOBALS, AutomationRuntime.declaredGlobals(validated)); result.put(AutomationConstants.RESULT_SCOPE_VARIABLES, AutomationScopeCatalog.variablesByNode(validated)); return new NounMetadata(result, PixelDataType.MAP, PixelOperationType.OPERATION); diff --git a/src/prerna/reactor/engine/UpdateEngineGuardrailConfigReactor.java b/src/prerna/reactor/engine/UpdateEngineGuardrailConfigReactor.java index a471e2f59bd..b1306266c9b 100644 --- a/src/prerna/reactor/engine/UpdateEngineGuardrailConfigReactor.java +++ b/src/prerna/reactor/engine/UpdateEngineGuardrailConfigReactor.java @@ -27,6 +27,7 @@ *******************************************************************************/ package prerna.reactor.engine; +import prerna.auth.utils.CatalogDependencyDerivation; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @@ -197,6 +198,8 @@ public NounMetadata execute() { lock.unlock(); } releaseLocksOfRemovedLimits(user, engine, validated.hitLimits()); + CatalogDependencyDerivation.syncGuardrails(user, engine.getEngineId(), engine.getCatalogType().name(), + validated.pipelines()); if (ClusterUtil.IS_CLUSTER) { ClusterUtil.pushEngine(engineId); diff --git a/src/prerna/reactor/function/upload/CreateFunctionEngineReactor.java b/src/prerna/reactor/function/upload/CreateFunctionEngineReactor.java index a403ea11c3e..60221d4641c 100644 --- a/src/prerna/reactor/function/upload/CreateFunctionEngineReactor.java +++ b/src/prerna/reactor/function/upload/CreateFunctionEngineReactor.java @@ -1,219 +1,221 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.function.upload; - -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import prerna.auth.AccessToken; -import prerna.auth.AuthProvider; -import prerna.auth.User; -import prerna.auth.utils.AbstractSecurityUtils; -import prerna.auth.utils.SecurityAdminUtils; -import prerna.auth.utils.SecurityEngineUtils; -import prerna.auth.utils.SecurityQueryUtils; -import prerna.cluster.util.ClusterUtil; -import prerna.engine.api.FunctionTypeEnum; -import prerna.engine.api.IEngine; -import prerna.engine.api.IFunctionEngine; -import prerna.reactor.AbstractReactor; -import prerna.reactor.ReactorDefinition; -import prerna.sablecc2.om.GenRowStruct; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.PixelOperationType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.usertracking.AuditEventType; -import prerna.usertracking.AuditTargetType; -import prerna.usertracking.UserAuditTrailUtils; -import prerna.util.EngineUtility; -import prerna.util.UploadUtilities; -import prerna.util.Utility; -import prerna.util.git.GitRepoUtils; - -public class CreateFunctionEngineReactor extends AbstractReactor { - - private static final Logger classLogger = LogManager.getLogger(CreateFunctionEngineReactor.class); - - public CreateFunctionEngineReactor() { - this.keysToGet = new String[] { ReactorKeysEnum.CATALOG_NAME.getKey() + "," + ReactorKeysEnum.FUNCTION.getKey(), - ReactorKeysEnum.FUNCTION_DETAILS.getKey(), - ReactorKeysEnum.FILE_PATH.getKey() }; - this.keyRequired = new int[] { 1, 1, 0 }; - } - - @Override - public NounMetadata execute() { - User user = requireUser(); - - // throw error is user doesn't have rights to publish new databases - if (AbstractSecurityUtils.adminSetPublisher() && !SecurityQueryUtils.userIsPublisher(this.insight.getUser())) { - throwUserNotPublisherError(); - } - - if (AbstractSecurityUtils.adminOnlyFunctionAdd() && !SecurityAdminUtils.userIsAdmin(user)) { - throwFunctionalityOnlyExposedForAdminsError(); - } - - organizeKeys(); - - String functionName = this.keyValue.get(ReactorKeysEnum.CATALOG_NAME.getKey()); - if (functionName == null || (functionName = functionName.trim()).isEmpty()) { - throw new NullPointerException("Must define the name of the new function engine"); - } - // if function name is not valid, throw error - if (!Utility.validateName(functionName)) { - // error and redirect to try again - throw new IllegalArgumentException( - "Invalid Name: It must start with a letter and can only contain letters, numbers, and spaces."); - } - - Map functionDetails = getMapFromKeyOrCurRow(ReactorKeysEnum.FUNCTION_DETAILS.getKey()); - if (functionDetails == null) { - throw new NullPointerException("Must define the properties for the new function engine"); - } - String functionTypeStr = (String) functionDetails.get(IFunctionEngine.FUNCTION_TYPE); - if (functionTypeStr == null || (functionTypeStr = functionTypeStr.trim()).isEmpty()) { - throw new IllegalArgumentException("Must define the function type"); - } - FunctionTypeEnum functionType = null; - try { - functionType = FunctionTypeEnum.getEnumFromName(functionTypeStr); - } catch (Exception e) { - throw new IllegalArgumentException("Invalid function type " + functionTypeStr); - } - - String functionId = UUID.randomUUID().toString(); - File tempSmss = null; - File smssFile = null; - File specificEngineAssetsFolder = null; - IFunctionEngine function = null; - try { - // validate engine - UploadUtilities.validateEngine(IEngine.CATALOG_TYPE.FUNCTION, user, functionName, functionId); - specificEngineAssetsFolder = UploadUtilities - .generateSpecificEngineAssetsFolder(IEngine.CATALOG_TYPE.FUNCTION, functionId, functionName); - - if (functionType == FunctionTypeEnum.LOCAL_PYTHON) { - moveFilesToEngineFolder(specificEngineAssetsFolder); - } - - String functionClass = functionType.getFunctionClass(); - function = (IFunctionEngine) Class.forName(functionClass).getDeclaredConstructor().newInstance(); - tempSmss = UploadUtilities.createTemporaryFunctionSmss(functionId, functionName, functionClass, - functionDetails); - - // store in DIHelper so that when we move temp smss to smss it doesn't try to - // reload again - UploadUtilities.addEngineToDIHelperToIgnoreEngineWatchers(functionId, tempSmss.getAbsolutePath()); - function.open(tempSmss.getAbsolutePath()); - - smssFile = new File(tempSmss.getAbsolutePath().replace(".temp", ".smss")); - FileUtils.copyFile(tempSmss, smssFile); - tempSmss.delete(); - function.setSmssFilePath(smssFile.getAbsolutePath()); - UploadUtilities.addEngineToDIHelper(functionId, functionName, function, smssFile); - SecurityEngineUtils.addEngine(functionId, false, user); - - List logins = user.getLogins(); - for (AuthProvider ap : logins) { - SecurityEngineUtils.addEngineOwner(functionId, user.getAccessToken(ap).getId()); - } - - // Initialize git and commit initial engine files - try { - String versionFolder = EngineUtility.getSpecificEngineVersionFolder(IEngine.CATALOG_TYPE.FUNCTION, - functionId, functionName); - GitRepoUtils.init(versionFolder); - GitRepoUtils.addAllFiles(versionFolder, false); - AccessToken accessToken = user.getAccessToken(user.getPrimaryLogin()); - GitRepoUtils.commitAddedFiles(versionFolder, "initial: created function engine " + functionName, - accessToken.getUsername(), accessToken.getEmail()); - } catch (Exception e) { - classLogger.warn("Unable to initialize git for function engine {}", functionId, e); - } - - ClusterUtil.pushEngine(functionId); - UserAuditTrailUtils.recordEngineLifecycle(user, AuditEventType.FUNCTION_CREATE, AuditTargetType.FUNCTION, - functionId, functionName, Map.of("functionType", functionType.getFunctionName())); - } catch (Exception e) { - classLogger.error("Unable to create function engine '{}' ({})", functionName, functionId, e); - UploadUtilities.cleanUpCreateNewError(function, functionId, tempSmss, smssFile, specificEngineAssetsFolder); - return new NounMetadata(e.getMessage(), PixelDataType.CONST_STRING, PixelOperationType.ERROR); - } - - Map retMap = UploadUtilities.getEngineReturnData(this.insight.getUser(), functionId); - return new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, PixelOperationType.MARKET_PLACE_ADDITION); - } - - /** - * - * @param specificEngineFolder - * @throws IOException - */ - private void moveFilesToEngineFolder(File specificEngineFolder) throws IOException { - String insightFolder = this.insight.getInsightFolder(); - - // see if added as key - GenRowStruct grs = getGenRowStruct(ReactorKeysEnum.FILE_PATH.getKey()); - if (grs != null && !grs.isEmpty()) { - int size = grs.size(); - for (int i = 0; i < size; i++) { - File file = new File(insightFolder + File.separator + grs.get(i).toString()); - if (file.exists()) { - FileUtils.moveFileToDirectory(file, specificEngineFolder, false); - } - } - } - } - - @Override - public ReactorDefinition getReactorDefinition() { - return super.getReactorDefinition().description(""" - Create and register a function engine from the supplied function metadata. The reactor validates the - engine type, creates its assets and SMSS configuration, assigns the caller as an owner, initializes - version control, and synchronizes the engine to the cluster. - """).key(ReactorKeysEnum.CATALOG_NAME, - "The catalog name for the new function engine. The name must be unique and contain only supported engine-name characters.") - .key(ReactorKeysEnum.FUNCTION_DETAILS, """ - The function-engine SMSS properties. The map must include FUNCTION_TYPE and the configuration - required by that engine type, such as FUNCTION_NAME, FUNCTION_DESCRIPTION, parameters, - credentials, connection settings, or provider-specific options. - """).key(ReactorKeysEnum.FILE_PATH, """ - Optional path to a file in the current insight folder. For LOCAL_PYTHON engines, each supplied - file is moved into the new engine assets folder. - """); - } -} +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.function.upload; + +import prerna.auth.utils.CatalogDependencyDerivation; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.io.FileUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import prerna.auth.AccessToken; +import prerna.auth.AuthProvider; +import prerna.auth.User; +import prerna.auth.utils.AbstractSecurityUtils; +import prerna.auth.utils.SecurityAdminUtils; +import prerna.auth.utils.SecurityEngineUtils; +import prerna.auth.utils.SecurityQueryUtils; +import prerna.cluster.util.ClusterUtil; +import prerna.engine.api.FunctionTypeEnum; +import prerna.engine.api.IEngine; +import prerna.engine.api.IFunctionEngine; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.GenRowStruct; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.PixelOperationType; +import prerna.sablecc2.om.ReactorKeysEnum; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.usertracking.AuditEventType; +import prerna.usertracking.AuditTargetType; +import prerna.usertracking.UserAuditTrailUtils; +import prerna.util.EngineUtility; +import prerna.util.UploadUtilities; +import prerna.util.Utility; +import prerna.util.git.GitRepoUtils; + +public class CreateFunctionEngineReactor extends AbstractReactor { + + private static final Logger classLogger = LogManager.getLogger(CreateFunctionEngineReactor.class); + + public CreateFunctionEngineReactor() { + this.keysToGet = new String[] { ReactorKeysEnum.CATALOG_NAME.getKey() + "," + ReactorKeysEnum.FUNCTION.getKey(), + ReactorKeysEnum.FUNCTION_DETAILS.getKey(), + ReactorKeysEnum.FILE_PATH.getKey() }; + this.keyRequired = new int[] { 1, 1, 0 }; + } + + @Override + public NounMetadata execute() { + User user = requireUser(); + + // throw error is user doesn't have rights to publish new databases + if (AbstractSecurityUtils.adminSetPublisher() && !SecurityQueryUtils.userIsPublisher(this.insight.getUser())) { + throwUserNotPublisherError(); + } + + if (AbstractSecurityUtils.adminOnlyFunctionAdd() && !SecurityAdminUtils.userIsAdmin(user)) { + throwFunctionalityOnlyExposedForAdminsError(); + } + + organizeKeys(); + + String functionName = this.keyValue.get(ReactorKeysEnum.CATALOG_NAME.getKey()); + if (functionName == null || (functionName = functionName.trim()).isEmpty()) { + throw new NullPointerException("Must define the name of the new function engine"); + } + // if function name is not valid, throw error + if (!Utility.validateName(functionName)) { + // error and redirect to try again + throw new IllegalArgumentException( + "Invalid Name: It must start with a letter and can only contain letters, numbers, and spaces."); + } + + Map functionDetails = getMapFromKeyOrCurRow(ReactorKeysEnum.FUNCTION_DETAILS.getKey()); + if (functionDetails == null) { + throw new NullPointerException("Must define the properties for the new function engine"); + } + String functionTypeStr = (String) functionDetails.get(IFunctionEngine.FUNCTION_TYPE); + if (functionTypeStr == null || (functionTypeStr = functionTypeStr.trim()).isEmpty()) { + throw new IllegalArgumentException("Must define the function type"); + } + FunctionTypeEnum functionType = null; + try { + functionType = FunctionTypeEnum.getEnumFromName(functionTypeStr); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid function type " + functionTypeStr); + } + + String functionId = UUID.randomUUID().toString(); + File tempSmss = null; + File smssFile = null; + File specificEngineAssetsFolder = null; + IFunctionEngine function = null; + try { + // validate engine + UploadUtilities.validateEngine(IEngine.CATALOG_TYPE.FUNCTION, user, functionName, functionId); + specificEngineAssetsFolder = UploadUtilities + .generateSpecificEngineAssetsFolder(IEngine.CATALOG_TYPE.FUNCTION, functionId, functionName); + + if (functionType == FunctionTypeEnum.LOCAL_PYTHON) { + moveFilesToEngineFolder(specificEngineAssetsFolder); + } + + String functionClass = functionType.getFunctionClass(); + function = (IFunctionEngine) Class.forName(functionClass).getDeclaredConstructor().newInstance(); + tempSmss = UploadUtilities.createTemporaryFunctionSmss(functionId, functionName, functionClass, + functionDetails); + + // store in DIHelper so that when we move temp smss to smss it doesn't try to + // reload again + UploadUtilities.addEngineToDIHelperToIgnoreEngineWatchers(functionId, tempSmss.getAbsolutePath()); + function.open(tempSmss.getAbsolutePath()); + + smssFile = new File(tempSmss.getAbsolutePath().replace(".temp", ".smss")); + FileUtils.copyFile(tempSmss, smssFile); + tempSmss.delete(); + function.setSmssFilePath(smssFile.getAbsolutePath()); + UploadUtilities.addEngineToDIHelper(functionId, functionName, function, smssFile); + SecurityEngineUtils.addEngine(functionId, false, user); + CatalogDependencyDerivation.syncSmss(user, functionId, IEngine.CATALOG_TYPE.FUNCTION.name(), functionDetails); + + List logins = user.getLogins(); + for (AuthProvider ap : logins) { + SecurityEngineUtils.addEngineOwner(functionId, user.getAccessToken(ap).getId()); + } + + // Initialize git and commit initial engine files + try { + String versionFolder = EngineUtility.getSpecificEngineVersionFolder(IEngine.CATALOG_TYPE.FUNCTION, + functionId, functionName); + GitRepoUtils.init(versionFolder); + GitRepoUtils.addAllFiles(versionFolder, false); + AccessToken accessToken = user.getAccessToken(user.getPrimaryLogin()); + GitRepoUtils.commitAddedFiles(versionFolder, "initial: created function engine " + functionName, + accessToken.getUsername(), accessToken.getEmail()); + } catch (Exception e) { + classLogger.warn("Unable to initialize git for function engine {}", functionId, e); + } + + ClusterUtil.pushEngine(functionId); + UserAuditTrailUtils.recordEngineLifecycle(user, AuditEventType.FUNCTION_CREATE, AuditTargetType.FUNCTION, + functionId, functionName, Map.of("functionType", functionType.getFunctionName())); + } catch (Exception e) { + classLogger.error("Unable to create function engine '{}' ({})", functionName, functionId, e); + UploadUtilities.cleanUpCreateNewError(function, functionId, tempSmss, smssFile, specificEngineAssetsFolder); + return new NounMetadata(e.getMessage(), PixelDataType.CONST_STRING, PixelOperationType.ERROR); + } + + Map retMap = UploadUtilities.getEngineReturnData(this.insight.getUser(), functionId); + return new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, PixelOperationType.MARKET_PLACE_ADDITION); + } + + /** + * + * @param specificEngineFolder + * @throws IOException + */ + private void moveFilesToEngineFolder(File specificEngineFolder) throws IOException { + String insightFolder = this.insight.getInsightFolder(); + + // see if added as key + GenRowStruct grs = getGenRowStruct(ReactorKeysEnum.FILE_PATH.getKey()); + if (grs != null && !grs.isEmpty()) { + int size = grs.size(); + for (int i = 0; i < size; i++) { + File file = new File(insightFolder + File.separator + grs.get(i).toString()); + if (file.exists()) { + FileUtils.moveFileToDirectory(file, specificEngineFolder, false); + } + } + } + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition().description(""" + Create and register a function engine from the supplied function metadata. The reactor validates the + engine type, creates its assets and SMSS configuration, assigns the caller as an owner, initializes + version control, and synchronizes the engine to the cluster. + """).key(ReactorKeysEnum.CATALOG_NAME, + "The catalog name for the new function engine. The name must be unique and contain only supported engine-name characters.") + .key(ReactorKeysEnum.FUNCTION_DETAILS, """ + The function-engine SMSS properties. The map must include FUNCTION_TYPE and the configuration + required by that engine type, such as FUNCTION_NAME, FUNCTION_DESCRIPTION, parameters, + credentials, connection settings, or provider-specific options. + """).key(ReactorKeysEnum.FILE_PATH, """ + Optional path to a file in the current insight folder. For LOCAL_PYTHON engines, each supplied + file is moved into the new engine assets folder. + """); + } +} diff --git a/src/prerna/reactor/function/upload/CreatePythonFunctionEngineReactor.java b/src/prerna/reactor/function/upload/CreatePythonFunctionEngineReactor.java index 73feb02811c..67e36fb6415 100644 --- a/src/prerna/reactor/function/upload/CreatePythonFunctionEngineReactor.java +++ b/src/prerna/reactor/function/upload/CreatePythonFunctionEngineReactor.java @@ -27,6 +27,7 @@ *******************************************************************************/ package prerna.reactor.function.upload; +import prerna.auth.utils.CatalogDependencyDerivation; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -154,6 +155,7 @@ public NounMetadata execute() { function.setSmssFilePath(smssFile.getAbsolutePath()); UploadUtilities.addEngineToDIHelper(functionId, functionName, function, smssFile); SecurityEngineUtils.addEngine(functionId, false, user); + CatalogDependencyDerivation.syncSmss(user, functionId, IEngine.CATALOG_TYPE.FUNCTION.name(), functionDetails); List logins = user.getLogins(); for (AuthProvider ap : logins) { diff --git a/src/prerna/reactor/guardrail/upload/CreateGuardrailEngineReactor.java b/src/prerna/reactor/guardrail/upload/CreateGuardrailEngineReactor.java index c3f2144f04e..fd505f0e997 100644 --- a/src/prerna/reactor/guardrail/upload/CreateGuardrailEngineReactor.java +++ b/src/prerna/reactor/guardrail/upload/CreateGuardrailEngineReactor.java @@ -1,220 +1,223 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.guardrail.upload; - -import java.io.File; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import prerna.auth.AuthProvider; -import prerna.auth.User; -import prerna.auth.utils.AbstractSecurityUtils; -import prerna.auth.utils.SecurityAdminUtils; -import prerna.auth.utils.SecurityEngineUtils; -import prerna.auth.utils.SecurityQueryUtils; -import prerna.cluster.util.ClusterUtil; -import prerna.engine.api.GuardrailTypeEnum; -import prerna.engine.api.IEngine; -import prerna.engine.api.IGuardrailReactorFunctionEngine; -import prerna.reactor.AbstractReactor; -import prerna.reactor.ReactorDefinition; -import prerna.sablecc2.om.GenRowStruct; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.PixelOperationType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.usertracking.AuditEventType; -import prerna.usertracking.AuditTargetType; -import prerna.usertracking.UserAuditTrailUtils; -import prerna.util.UploadUtilities; -import prerna.util.Utility; - -public class CreateGuardrailEngineReactor extends AbstractReactor { - - private static final Logger classLogger = LogManager.getLogger(CreateGuardrailEngineReactor.class); - - private static final String CATALOG_NAME_KEYS = ReactorKeysEnum.CATALOG_NAME.getKey() + "," + ReactorKeysEnum.GUARDRAIL.getKey(); - - public CreateGuardrailEngineReactor() { - this.keysToGet = new String[] { CATALOG_NAME_KEYS, ReactorKeysEnum.GUARDRAIL_DETAILS.getKey(), - ReactorKeysEnum.GLOBAL.getKey() }; - this.keyRequired = new int[] { 1, 1, 0 }; - } - - @Override - public NounMetadata execute() { - User user = requireUser(); - - // throw error is user doesn't have rights to publish new databases - if (AbstractSecurityUtils.adminSetPublisher() && !SecurityQueryUtils.userIsPublisher(this.insight.getUser())) { - throwUserNotPublisherError(); - } - - if (AbstractSecurityUtils.adminOnlyGuardrailAdd() && !SecurityAdminUtils.userIsAdmin(user)) { - throwFunctionalityOnlyExposedForAdminsError(); - } - - organizeKeys(); - - String guardrailName = getGuardrailName(); - // if guardrail name is not valid throw error - if (!Utility.validateName(guardrailName)) { - // error and redirect to try again - throw new IllegalArgumentException( - "Invalid Name: It must start with a letter and can only contain letters, numbers, and spaces."); - } - - Map guardrailDetails = getGuardrailDetails(); - boolean global = Boolean.parseBoolean(this.keyValue.get(ReactorKeysEnum.GLOBAL.getKey()) + ""); - - NounMetadata warning = null; - if (global) { - if (AbstractSecurityUtils.adminOnlyEngineSetPublic(IEngine.CATALOG_TYPE.GUARDRAIL) - && !SecurityAdminUtils.userIsAdmin(user)) { - warning = NounMetadata.getWarningNounMessage( - "Public access can only be enabled by administrators. This item will be created as private."); - global = false; - } - } - - String guardrailTypeStr = (String) guardrailDetails.get(IGuardrailReactorFunctionEngine.GUARDRAIL_TYPE); - if (guardrailTypeStr == null || (guardrailTypeStr = guardrailTypeStr.trim()).isEmpty()) { - throw new IllegalArgumentException("Must define the guardrail type"); - } - GuardrailTypeEnum guardrailType = null; - try { - guardrailType = GuardrailTypeEnum.getEnumFromName(guardrailTypeStr); - } catch (Exception e) { - throw new IllegalArgumentException("Invalid guardrail type " + guardrailTypeStr); - } - - String guardrailId = UUID.randomUUID().toString(); - File tempSmss = null; - File smssFile = null; - File specificEngineFolder = null; - IGuardrailReactorFunctionEngine guardrail = null; - try { - // validate engine - UploadUtilities.validateEngine(IEngine.CATALOG_TYPE.GUARDRAIL, user, guardrailName, guardrailId); - specificEngineFolder = UploadUtilities.generateSpecificEngineFolder(IEngine.CATALOG_TYPE.GUARDRAIL, - guardrailId, guardrailName); - - String guardrailClass = guardrailType.getGuardrailClass(); - guardrail = (IGuardrailReactorFunctionEngine) Class.forName(guardrailClass).getDeclaredConstructor() - .newInstance(); - tempSmss = UploadUtilities.createTemporaryGuardrailSmss(guardrailId, guardrailName, guardrailClass, - guardrailDetails); - - // store in DIHelper so that when we move temp smss to smss it doesn't try to - // reload again - UploadUtilities.addEngineToDIHelperToIgnoreEngineWatchers(guardrailId, tempSmss.getAbsolutePath()); - guardrail.open(tempSmss.getAbsolutePath()); - - smssFile = new File(tempSmss.getAbsolutePath().replace(".temp", ".smss")); - FileUtils.copyFile(tempSmss, smssFile); - tempSmss.delete(); - guardrail.setSmssFilePath(smssFile.getAbsolutePath()); - UploadUtilities.addEngineToDIHelper(guardrailId, guardrailName, guardrail, smssFile); - SecurityEngineUtils.addEngine(guardrailId, global, user); - SecurityEngineUtils.setDefaultEngineMarkdown(guardrailId, guardrail.getDefaultMarkdown()); - - List logins = user.getLogins(); - for (AuthProvider ap : logins) { - SecurityEngineUtils.addEngineOwner(guardrailId, user.getAccessToken(ap).getId()); - } - - ClusterUtil.pushEngine(guardrailId); - UserAuditTrailUtils.recordEngineLifecycle(user, AuditEventType.GUARDRAIL_CREATE, AuditTargetType.GUARDRAIL, - guardrailId, guardrailName, - Map.of("global", global, "guardrailType", guardrailType.getGuardrailName())); - } catch (Exception e) { - classLogger.error("Failed to create guardrail engine '{}' with id '{}' and type '{}': {}", guardrailName, - guardrailId, guardrailTypeStr, e.getMessage(), e); - UploadUtilities.cleanUpCreateNewError(guardrail, guardrailId, tempSmss, smssFile, specificEngineFolder); - throw new IllegalArgumentException("Failed to create guardrail engine. Error: " + e.getMessage()); - } - - Map retMap = UploadUtilities.getEngineReturnData(this.insight.getUser(), guardrailId); - NounMetadata retNoun = new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, - PixelOperationType.MARKET_PLACE_ADDITION); - if (warning != null) { - retNoun.addAdditionalReturn(warning); - } - return retNoun; - } - - /** - * - * @return - */ - private String getGuardrailName() { - List strValues = getListStringForAliasedKey(CATALOG_NAME_KEYS); - if (!strValues.isEmpty()) { - return strValues.get(0).trim(); - } - - strValues = this.curRow.getAllStrValues(); - if (strValues != null && !strValues.isEmpty()) { - return strValues.get(0).trim(); - } - - throw new NullPointerException("Must define the name of the new guardrail engine"); - } - - /** - * - * @return - */ - private Map getGuardrailDetails() { - GenRowStruct grs = this.store.getGenRowStruct(ReactorKeysEnum.GUARDRAIL_DETAILS.getKey()); - if (grs != null && !grs.isEmpty()) { - List mapNouns = grs.getNounsOfType(PixelDataType.MAP); - if (mapNouns != null && !mapNouns.isEmpty()) { - return (Map) mapNouns.get(0).getValue(); - } - } - - List mapNouns = this.curRow.getNounsOfType(PixelDataType.MAP); - if (mapNouns != null && !mapNouns.isEmpty()) { - return (Map) mapNouns.get(0).getValue(); - } - - throw new NullPointerException("Must define the properties for the new guardrail engine"); - } - - @Override - public ReactorDefinition getReactorDefinition() { - return super.getReactorDefinition().description("Create a new guardrail engine"); - } - -} +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.guardrail.upload; + +import prerna.auth.utils.CatalogDependencyDerivation; +import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.io.FileUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import prerna.auth.AuthProvider; +import prerna.auth.User; +import prerna.auth.utils.AbstractSecurityUtils; +import prerna.auth.utils.SecurityAdminUtils; +import prerna.auth.utils.SecurityEngineUtils; +import prerna.auth.utils.SecurityQueryUtils; +import prerna.cluster.util.ClusterUtil; +import prerna.engine.api.GuardrailTypeEnum; +import prerna.engine.api.IEngine; +import prerna.engine.api.IGuardrailReactorFunctionEngine; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.GenRowStruct; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.PixelOperationType; +import prerna.sablecc2.om.ReactorKeysEnum; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.usertracking.AuditEventType; +import prerna.usertracking.AuditTargetType; +import prerna.usertracking.UserAuditTrailUtils; +import prerna.util.UploadUtilities; +import prerna.util.Utility; + +public class CreateGuardrailEngineReactor extends AbstractReactor { + + private static final Logger classLogger = LogManager.getLogger(CreateGuardrailEngineReactor.class); + + private static final String CATALOG_NAME_KEYS = ReactorKeysEnum.CATALOG_NAME.getKey() + "," + ReactorKeysEnum.GUARDRAIL.getKey(); + + public CreateGuardrailEngineReactor() { + this.keysToGet = new String[] { CATALOG_NAME_KEYS, ReactorKeysEnum.GUARDRAIL_DETAILS.getKey(), + ReactorKeysEnum.GLOBAL.getKey() }; + this.keyRequired = new int[] { 1, 1, 0 }; + } + + @Override + public NounMetadata execute() { + User user = requireUser(); + + // throw error is user doesn't have rights to publish new databases + if (AbstractSecurityUtils.adminSetPublisher() && !SecurityQueryUtils.userIsPublisher(this.insight.getUser())) { + throwUserNotPublisherError(); + } + + if (AbstractSecurityUtils.adminOnlyGuardrailAdd() && !SecurityAdminUtils.userIsAdmin(user)) { + throwFunctionalityOnlyExposedForAdminsError(); + } + + organizeKeys(); + + String guardrailName = getGuardrailName(); + // if guardrail name is not valid throw error + if (!Utility.validateName(guardrailName)) { + // error and redirect to try again + throw new IllegalArgumentException( + "Invalid Name: It must start with a letter and can only contain letters, numbers, and spaces."); + } + + Map guardrailDetails = getGuardrailDetails(); + boolean global = Boolean.parseBoolean(this.keyValue.get(ReactorKeysEnum.GLOBAL.getKey()) + ""); + + NounMetadata warning = null; + if (global) { + if (AbstractSecurityUtils.adminOnlyEngineSetPublic(IEngine.CATALOG_TYPE.GUARDRAIL) + && !SecurityAdminUtils.userIsAdmin(user)) { + warning = NounMetadata.getWarningNounMessage( + "Public access can only be enabled by administrators. This item will be created as private."); + global = false; + } + } + + String guardrailTypeStr = (String) guardrailDetails.get(IGuardrailReactorFunctionEngine.GUARDRAIL_TYPE); + if (guardrailTypeStr == null || (guardrailTypeStr = guardrailTypeStr.trim()).isEmpty()) { + throw new IllegalArgumentException("Must define the guardrail type"); + } + GuardrailTypeEnum guardrailType = null; + try { + guardrailType = GuardrailTypeEnum.getEnumFromName(guardrailTypeStr); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid guardrail type " + guardrailTypeStr); + } + + String guardrailId = UUID.randomUUID().toString(); + File tempSmss = null; + File smssFile = null; + File specificEngineFolder = null; + IGuardrailReactorFunctionEngine guardrail = null; + try { + // validate engine + UploadUtilities.validateEngine(IEngine.CATALOG_TYPE.GUARDRAIL, user, guardrailName, guardrailId); + specificEngineFolder = UploadUtilities.generateSpecificEngineFolder(IEngine.CATALOG_TYPE.GUARDRAIL, + guardrailId, guardrailName); + + String guardrailClass = guardrailType.getGuardrailClass(); + guardrail = (IGuardrailReactorFunctionEngine) Class.forName(guardrailClass).getDeclaredConstructor() + .newInstance(); + tempSmss = UploadUtilities.createTemporaryGuardrailSmss(guardrailId, guardrailName, guardrailClass, + guardrailDetails); + + // store in DIHelper so that when we move temp smss to smss it doesn't try to + // reload again + UploadUtilities.addEngineToDIHelperToIgnoreEngineWatchers(guardrailId, tempSmss.getAbsolutePath()); + guardrail.open(tempSmss.getAbsolutePath()); + + smssFile = new File(tempSmss.getAbsolutePath().replace(".temp", ".smss")); + FileUtils.copyFile(tempSmss, smssFile); + tempSmss.delete(); + guardrail.setSmssFilePath(smssFile.getAbsolutePath()); + UploadUtilities.addEngineToDIHelper(guardrailId, guardrailName, guardrail, smssFile); + SecurityEngineUtils.addEngine(guardrailId, global, user); + SecurityEngineUtils.setDefaultEngineMarkdown(guardrailId, guardrail.getDefaultMarkdown()); + CatalogDependencyDerivation.syncSmss(user, guardrailId, IEngine.CATALOG_TYPE.GUARDRAIL.name(), + guardrailDetails); + + List logins = user.getLogins(); + for (AuthProvider ap : logins) { + SecurityEngineUtils.addEngineOwner(guardrailId, user.getAccessToken(ap).getId()); + } + + ClusterUtil.pushEngine(guardrailId); + UserAuditTrailUtils.recordEngineLifecycle(user, AuditEventType.GUARDRAIL_CREATE, AuditTargetType.GUARDRAIL, + guardrailId, guardrailName, + Map.of("global", global, "guardrailType", guardrailType.getGuardrailName())); + } catch (Exception e) { + classLogger.error("Failed to create guardrail engine '{}' with id '{}' and type '{}': {}", guardrailName, + guardrailId, guardrailTypeStr, e.getMessage(), e); + UploadUtilities.cleanUpCreateNewError(guardrail, guardrailId, tempSmss, smssFile, specificEngineFolder); + throw new IllegalArgumentException("Failed to create guardrail engine. Error: " + e.getMessage()); + } + + Map retMap = UploadUtilities.getEngineReturnData(this.insight.getUser(), guardrailId); + NounMetadata retNoun = new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, + PixelOperationType.MARKET_PLACE_ADDITION); + if (warning != null) { + retNoun.addAdditionalReturn(warning); + } + return retNoun; + } + + /** + * + * @return + */ + private String getGuardrailName() { + List strValues = getListStringForAliasedKey(CATALOG_NAME_KEYS); + if (!strValues.isEmpty()) { + return strValues.get(0).trim(); + } + + strValues = this.curRow.getAllStrValues(); + if (strValues != null && !strValues.isEmpty()) { + return strValues.get(0).trim(); + } + + throw new NullPointerException("Must define the name of the new guardrail engine"); + } + + /** + * + * @return + */ + private Map getGuardrailDetails() { + GenRowStruct grs = this.store.getGenRowStruct(ReactorKeysEnum.GUARDRAIL_DETAILS.getKey()); + if (grs != null && !grs.isEmpty()) { + List mapNouns = grs.getNounsOfType(PixelDataType.MAP); + if (mapNouns != null && !mapNouns.isEmpty()) { + return (Map) mapNouns.get(0).getValue(); + } + } + + List mapNouns = this.curRow.getNounsOfType(PixelDataType.MAP); + if (mapNouns != null && !mapNouns.isEmpty()) { + return (Map) mapNouns.get(0).getValue(); + } + + throw new NullPointerException("Must define the properties for the new guardrail engine"); + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition().description("Create a new guardrail engine"); + } + +} diff --git a/src/prerna/reactor/model/UpdateModelRouterConfigReactor.java b/src/prerna/reactor/model/UpdateModelRouterConfigReactor.java index 86dd7d8dbda..c6707849691 100644 --- a/src/prerna/reactor/model/UpdateModelRouterConfigReactor.java +++ b/src/prerna/reactor/model/UpdateModelRouterConfigReactor.java @@ -27,6 +27,7 @@ *******************************************************************************/ package prerna.reactor.model; +import prerna.auth.utils.CatalogDependencyDerivation; import java.io.IOException; import java.util.Map; @@ -83,6 +84,8 @@ public NounMetadata execute() { throw new IllegalStateException("Unable to write the router configuration: " + e.getMessage(), e); } + CatalogDependencyDerivation.syncRouter(this.insight.getUser(), engineId, config); + if (ClusterUtil.IS_CLUSTER) { ClusterUtil.pushEngine(engineId); } diff --git a/src/prerna/reactor/model/upload/CreateModelEngineReactor.java b/src/prerna/reactor/model/upload/CreateModelEngineReactor.java index f345602d652..5158f86b5e1 100644 --- a/src/prerna/reactor/model/upload/CreateModelEngineReactor.java +++ b/src/prerna/reactor/model/upload/CreateModelEngineReactor.java @@ -1,235 +1,241 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.model.upload; - -import java.io.File; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import prerna.auth.AuthProvider; -import prerna.auth.User; -import prerna.auth.utils.AbstractSecurityUtils; -import prerna.auth.utils.SecurityAdminUtils; -import prerna.auth.utils.SecurityEngineUtils; -import prerna.auth.utils.SecurityModelMetadataUtils; -import prerna.auth.utils.SecurityQueryUtils; -import prerna.cluster.util.ClusterUtil; -import prerna.engine.api.IEngine; -import prerna.engine.api.IModelEngine; -import prerna.engine.api.ModelTypeEnum; -import prerna.reactor.AbstractReactor; -import prerna.sablecc2.om.GenRowStruct; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.PixelOperationType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.usertracking.AuditEventType; -import prerna.usertracking.AuditTargetType; -import prerna.usertracking.UserAuditTrailUtils; -import prerna.util.Constants; -import prerna.util.PythonVariableValidator; -import prerna.util.Settings; -import prerna.util.StaticModelMetadataCatalog; -import prerna.util.UploadUtilities; -import prerna.util.Utility; - -public class CreateModelEngineReactor extends AbstractReactor { - - private static final Logger classLogger = LogManager.getLogger(CreateModelEngineReactor.class); - - private static final String CATALOG_NAME_KEYS = ReactorKeysEnum.CATALOG_NAME.getKey() + "," + ReactorKeysEnum.MODEL.getKey(); - - public CreateModelEngineReactor() { - this.keysToGet = new String[] { CATALOG_NAME_KEYS, ReactorKeysEnum.MODEL_DETAILS.getKey(), - ReactorKeysEnum.GLOBAL.getKey() }; - } - - @Override - public NounMetadata execute() { - User user = requireUser(); - - // throw error is user doesn't have rights to publish new databases - if (AbstractSecurityUtils.adminSetPublisher() && !SecurityQueryUtils.userIsPublisher(this.insight.getUser())) { - throwUserNotPublisherError(); - } - - if (AbstractSecurityUtils.adminOnlyModelAdd() && !SecurityAdminUtils.userIsAdmin(user)) { - throwFunctionalityOnlyExposedForAdminsError(); - } - - organizeKeys(); - - String modelName = getModelName(); - // if model name is not valid, throw error - if (!Utility.validateName(modelName)) { - // error and redirect to try again - throw new IllegalArgumentException( - "Invalid Name: It must start with a letter and can only contain letters, numbers, and spaces."); - } - - Map suppliedModelDetails = new LinkedHashMap<>(getModelDetails()); - StaticModelMetadataCatalog.applyStaticDefaults(suppliedModelDetails); - Map modelMetadata = SecurityModelMetadataUtils.normalizeModelDetails(suppliedModelDetails); - String modelDescription = (String) modelMetadata.remove(Constants.DESCR); - Map modelDetails = SecurityModelMetadataUtils.getModelEngineProperties(modelMetadata); - boolean global = Boolean.parseBoolean(this.keyValue.get(ReactorKeysEnum.GLOBAL.getKey()) + ""); - - NounMetadata warning = null; - if (global) { - if (AbstractSecurityUtils.adminOnlyEngineSetPublic(IEngine.CATALOG_TYPE.MODEL) - && !SecurityAdminUtils.userIsAdmin(user)) { - warning = NounMetadata.getWarningNounMessage( - "Public access can only be enabled by administrators. This item will be created as private."); - global = false; - } - } - - String modelTypeStr = (String) modelDetails.get(IModelEngine.MODEL_TYPE); - if (modelTypeStr == null || (modelTypeStr = modelTypeStr.trim()).isEmpty()) { - throw new IllegalArgumentException("Must define the model type"); - } - ModelTypeEnum modelType = null; - try { - modelType = ModelTypeEnum.getEnumFromName(modelTypeStr); - } catch (Exception e) { - throw new IllegalArgumentException("Invalid model type " + modelTypeStr); - } - - if (modelDetails.containsKey(Settings.VAR_NAME)) { - // need to validate this is alphanumeric underscore and does not start with a - // number - String varName = (String) modelDetails.get(Settings.VAR_NAME); - if (!PythonVariableValidator.isValidPythonVariableName(varName)) { - throw new IllegalArgumentException("The variable '" + varName - + "' is not a valid variable name. It must be alphanumeric underscore, cannot start with a digit, and cannot be a reserved word."); - } - } - - String modelId = UUID.randomUUID().toString(); - File tempSmss = null; - File smssFile = null; - File specificEngineFolder = null; - IModelEngine model = null; - try { - // validate engine - UploadUtilities.validateEngine(IEngine.CATALOG_TYPE.MODEL, user, modelName, modelId); - specificEngineFolder = UploadUtilities.generateSpecificEngineFolder(IEngine.CATALOG_TYPE.MODEL, modelId, - modelName); - - String modelClass = modelType.getModelClass(); - model = (IModelEngine) Class.forName(modelClass).newInstance(); - tempSmss = UploadUtilities.createTemporaryModelSmss(modelId, modelName, modelClass, modelDetails); - - // store in DIHelper so that when we move temp smss to smss it doesn't try to - // reload again - UploadUtilities.addEngineToDIHelperToIgnoreEngineWatchers(modelId, tempSmss.getAbsolutePath()); - // Limits are stored only in MODELMETADATA and must exist before open. - SecurityModelMetadataUtils.upsertModelMetadata(modelId, modelMetadata); - model.open(tempSmss.getAbsolutePath()); - - smssFile = new File(tempSmss.getAbsolutePath().replace(".temp", ".smss")); - FileUtils.copyFile(tempSmss, smssFile); - tempSmss.delete(); - model.setSmssFilePath(smssFile.getAbsolutePath()); - UploadUtilities.addEngineToDIHelper(modelId, modelName, model, smssFile); - SecurityEngineUtils.addEngine(modelId, global, user); - if (modelDescription != null) { - SecurityEngineUtils.updateEngineMetadata(modelId, Map.of(Constants.DESCRIPTION, modelDescription)); - } - - List logins = user.getLogins(); - for (AuthProvider ap : logins) { - SecurityEngineUtils.addEngineOwner(modelId, user.getAccessToken(ap).getId()); - } - - ClusterUtil.pushEngine(modelId); - UserAuditTrailUtils.recordEngineLifecycle(user, AuditEventType.MODEL_CREATE, AuditTargetType.MODEL, modelId, - modelName, Map.of("global", global, "modelType", modelType.getModelName())); - } catch (Exception e) { - classLogger.error("Failed to create model engine {} ({})", modelName, modelId, e); - UploadUtilities.cleanUpCreateNewError(model, modelId, tempSmss, smssFile, specificEngineFolder); - SecurityEngineUtils.deleteEngine(modelId); - throw new IllegalArgumentException("Unable to create model engine " + modelName, e); - } - - Map retMap = UploadUtilities.getEngineReturnData(this.insight.getUser(), modelId); - NounMetadata retNoun = new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, - PixelOperationType.MARKET_PLACE_ADDITION); - if (warning != null) { - retNoun.addAdditionalReturn(warning); - } - return retNoun; - - } - - /** - * - * @return - */ - private String getModelName() { - List strValues = getListStringForAliasedKey(CATALOG_NAME_KEYS); - if (!strValues.isEmpty()) { - return strValues.get(0).trim(); - } - - strValues = this.curRow.getAllStrValues(); - if (strValues != null && !strValues.isEmpty()) { - return strValues.get(0).trim(); - } - - throw new NullPointerException("Must define the name of the new model engine"); - } - - /** - * - * @return - */ - private Map getModelDetails() { - GenRowStruct grs = this.store.getGenRowStruct(ReactorKeysEnum.MODEL_DETAILS.getKey()); - if (grs != null && !grs.isEmpty()) { - List mapNouns = grs.getNounsOfType(PixelDataType.MAP); - if (mapNouns != null && !mapNouns.isEmpty()) { - return (Map) mapNouns.get(0).getValue(); - } - } - - List mapNouns = this.curRow.getNounsOfType(PixelDataType.MAP); - if (mapNouns != null && !mapNouns.isEmpty()) { - return (Map) mapNouns.get(0).getValue(); - } - - throw new NullPointerException("Must define the properties for the new model engine"); - } - -} +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.model.upload; + +import prerna.auth.utils.CatalogDependencyDerivation; +import java.io.File; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.io.FileUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import prerna.auth.AuthProvider; +import prerna.auth.User; +import prerna.auth.utils.AbstractSecurityUtils; +import prerna.auth.utils.SecurityAdminUtils; +import prerna.auth.utils.SecurityEngineUtils; +import prerna.auth.utils.SecurityModelMetadataUtils; +import prerna.auth.utils.SecurityQueryUtils; +import prerna.cluster.util.ClusterUtil; +import prerna.engine.api.IEngine; +import prerna.engine.api.IModelEngine; +import prerna.engine.api.ModelTypeEnum; +import prerna.reactor.AbstractReactor; +import prerna.sablecc2.om.GenRowStruct; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.PixelOperationType; +import prerna.sablecc2.om.ReactorKeysEnum; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.usertracking.AuditEventType; +import prerna.usertracking.AuditTargetType; +import prerna.usertracking.UserAuditTrailUtils; +import prerna.util.Constants; +import prerna.util.PythonVariableValidator; +import prerna.util.Settings; +import prerna.util.StaticModelMetadataCatalog; +import prerna.util.UploadUtilities; +import prerna.util.Utility; + +public class CreateModelEngineReactor extends AbstractReactor { + + private static final Logger classLogger = LogManager.getLogger(CreateModelEngineReactor.class); + + private static final String CATALOG_NAME_KEYS = ReactorKeysEnum.CATALOG_NAME.getKey() + "," + ReactorKeysEnum.MODEL.getKey(); + + public CreateModelEngineReactor() { + this.keysToGet = new String[] { CATALOG_NAME_KEYS, ReactorKeysEnum.MODEL_DETAILS.getKey(), + ReactorKeysEnum.GLOBAL.getKey() }; + } + + @Override + public NounMetadata execute() { + User user = requireUser(); + + // throw error is user doesn't have rights to publish new databases + if (AbstractSecurityUtils.adminSetPublisher() && !SecurityQueryUtils.userIsPublisher(this.insight.getUser())) { + throwUserNotPublisherError(); + } + + if (AbstractSecurityUtils.adminOnlyModelAdd() && !SecurityAdminUtils.userIsAdmin(user)) { + throwFunctionalityOnlyExposedForAdminsError(); + } + + organizeKeys(); + + String modelName = getModelName(); + // if model name is not valid, throw error + if (!Utility.validateName(modelName)) { + // error and redirect to try again + throw new IllegalArgumentException( + "Invalid Name: It must start with a letter and can only contain letters, numbers, and spaces."); + } + + Map suppliedModelDetails = new LinkedHashMap<>(getModelDetails()); + StaticModelMetadataCatalog.applyStaticDefaults(suppliedModelDetails); + Map modelMetadata = SecurityModelMetadataUtils.normalizeModelDetails(suppliedModelDetails); + String modelDescription = (String) modelMetadata.remove(Constants.DESCR); + Map modelDetails = SecurityModelMetadataUtils.getModelEngineProperties(modelMetadata); + boolean global = Boolean.parseBoolean(this.keyValue.get(ReactorKeysEnum.GLOBAL.getKey()) + ""); + + NounMetadata warning = null; + if (global) { + if (AbstractSecurityUtils.adminOnlyEngineSetPublic(IEngine.CATALOG_TYPE.MODEL) + && !SecurityAdminUtils.userIsAdmin(user)) { + warning = NounMetadata.getWarningNounMessage( + "Public access can only be enabled by administrators. This item will be created as private."); + global = false; + } + } + + String modelTypeStr = (String) modelDetails.get(IModelEngine.MODEL_TYPE); + if (modelTypeStr == null || (modelTypeStr = modelTypeStr.trim()).isEmpty()) { + throw new IllegalArgumentException("Must define the model type"); + } + ModelTypeEnum modelType = null; + try { + modelType = ModelTypeEnum.getEnumFromName(modelTypeStr); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid model type " + modelTypeStr); + } + + if (modelDetails.containsKey(Settings.VAR_NAME)) { + // need to validate this is alphanumeric underscore and does not start with a + // number + String varName = (String) modelDetails.get(Settings.VAR_NAME); + if (!PythonVariableValidator.isValidPythonVariableName(varName)) { + throw new IllegalArgumentException("The variable '" + varName + + "' is not a valid variable name. It must be alphanumeric underscore, cannot start with a digit, and cannot be a reserved word."); + } + } + + String modelId = UUID.randomUUID().toString(); + File tempSmss = null; + File smssFile = null; + File specificEngineFolder = null; + IModelEngine model = null; + try { + // validate engine + UploadUtilities.validateEngine(IEngine.CATALOG_TYPE.MODEL, user, modelName, modelId); + specificEngineFolder = UploadUtilities.generateSpecificEngineFolder(IEngine.CATALOG_TYPE.MODEL, modelId, + modelName); + + String modelClass = modelType.getModelClass(); + model = (IModelEngine) Class.forName(modelClass).newInstance(); + tempSmss = UploadUtilities.createTemporaryModelSmss(modelId, modelName, modelClass, modelDetails); + + // store in DIHelper so that when we move temp smss to smss it doesn't try to + // reload again + UploadUtilities.addEngineToDIHelperToIgnoreEngineWatchers(modelId, tempSmss.getAbsolutePath()); + // Limits are stored only in MODELMETADATA and must exist before open. + SecurityModelMetadataUtils.upsertModelMetadata(modelId, modelMetadata); + model.open(tempSmss.getAbsolutePath()); + + smssFile = new File(tempSmss.getAbsolutePath().replace(".temp", ".smss")); + FileUtils.copyFile(tempSmss, smssFile); + tempSmss.delete(); + model.setSmssFilePath(smssFile.getAbsolutePath()); + UploadUtilities.addEngineToDIHelper(modelId, modelName, model, smssFile); + SecurityEngineUtils.addEngine(modelId, global, user); + // a model router's router.json names the models it sends to + Object routerConfig = modelDetails.get(prerna.engine.impl.model.ModelRouterEngine.ROUTER_CONFIG_JSON); + if (routerConfig instanceof String routerJson) { + CatalogDependencyDerivation.syncRouterJson(user, modelId, routerJson); + } + if (modelDescription != null) { + SecurityEngineUtils.updateEngineMetadata(modelId, Map.of(Constants.DESCRIPTION, modelDescription)); + } + + List logins = user.getLogins(); + for (AuthProvider ap : logins) { + SecurityEngineUtils.addEngineOwner(modelId, user.getAccessToken(ap).getId()); + } + + ClusterUtil.pushEngine(modelId); + UserAuditTrailUtils.recordEngineLifecycle(user, AuditEventType.MODEL_CREATE, AuditTargetType.MODEL, modelId, + modelName, Map.of("global", global, "modelType", modelType.getModelName())); + } catch (Exception e) { + classLogger.error("Failed to create model engine {} ({})", modelName, modelId, e); + UploadUtilities.cleanUpCreateNewError(model, modelId, tempSmss, smssFile, specificEngineFolder); + SecurityEngineUtils.deleteEngine(modelId); + throw new IllegalArgumentException("Unable to create model engine " + modelName, e); + } + + Map retMap = UploadUtilities.getEngineReturnData(this.insight.getUser(), modelId); + NounMetadata retNoun = new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, + PixelOperationType.MARKET_PLACE_ADDITION); + if (warning != null) { + retNoun.addAdditionalReturn(warning); + } + return retNoun; + + } + + /** + * + * @return + */ + private String getModelName() { + List strValues = getListStringForAliasedKey(CATALOG_NAME_KEYS); + if (!strValues.isEmpty()) { + return strValues.get(0).trim(); + } + + strValues = this.curRow.getAllStrValues(); + if (strValues != null && !strValues.isEmpty()) { + return strValues.get(0).trim(); + } + + throw new NullPointerException("Must define the name of the new model engine"); + } + + /** + * + * @return + */ + private Map getModelDetails() { + GenRowStruct grs = this.store.getGenRowStruct(ReactorKeysEnum.MODEL_DETAILS.getKey()); + if (grs != null && !grs.isEmpty()) { + List mapNouns = grs.getNounsOfType(PixelDataType.MAP); + if (mapNouns != null && !mapNouns.isEmpty()) { + return (Map) mapNouns.get(0).getValue(); + } + } + + List mapNouns = this.curRow.getNounsOfType(PixelDataType.MAP); + if (mapNouns != null && !mapNouns.isEmpty()) { + return (Map) mapNouns.get(0).getValue(); + } + + throw new NullPointerException("Must define the properties for the new model engine"); + } + +} diff --git a/src/prerna/reactor/project/CreateAppFromTemplateReactor.java b/src/prerna/reactor/project/CreateAppFromTemplateReactor.java index abe39b42eb1..3173fa405cb 100644 --- a/src/prerna/reactor/project/CreateAppFromTemplateReactor.java +++ b/src/prerna/reactor/project/CreateAppFromTemplateReactor.java @@ -179,7 +179,6 @@ public NounMetadata execute() { .getWorkspaceResourcesByType(projectTemplateId, null); List> clonedResources = new ArrayList<>(); - List dependencyIds = new ArrayList<>(); if (sourceResources != null) { for (Map r : sourceResources) { String resourceId = (String) r.get("resource_id"); @@ -192,14 +191,16 @@ public NounMetadata execute() { entry.put("resource_type", resourceType); entry.put("resource_subtype", resourceSubtype); clonedResources.add(entry); - dependencyIds.add(resourceId); } } // each resource is kept with its own engine type or project type, read from // the security database - SecurityCatalogDependencyUtils.setDependencyIds(user, newProjectId, - SecurityCatalogDependencyUtils.resolveCatalogType(newProjectId, null), dependencyIds); + // the clone depends on what the template does, each link as it is + SecurityCatalogDependencyUtils.replaceAllDependencies(user, newProjectId, + SecurityCatalogDependencyUtils.resolveCatalogType(newProjectId, null), + SecurityCatalogDependencyUtils.fromExported( + SecurityCatalogDependencyUtils.getDependencyDetails(projectTemplateId))); ModelInferenceLogsUtils.createNewWorkspaceEntry(newProjectId, user.getPrimaryLoginToken().getId(), newProjectName, sourceDescription, sourceSystemPrompt, clonedResources); if (sourceConfigJson != null) { diff --git a/src/prerna/reactor/project/ExtractAndSetDependenciesReactor.java b/src/prerna/reactor/project/ExtractAndSetDependenciesReactor.java index f10f53df0c5..5df043821e2 100644 --- a/src/prerna/reactor/project/ExtractAndSetDependenciesReactor.java +++ b/src/prerna/reactor/project/ExtractAndSetDependenciesReactor.java @@ -32,6 +32,7 @@ import java.util.Map; import prerna.auth.User; +import prerna.auth.utils.CatalogDependencyRole; import prerna.auth.utils.SecurityCatalogDependencyUtils; import prerna.auth.utils.SecurityProjectUtils; import prerna.engine.api.IEngine; @@ -91,8 +92,9 @@ public NounMetadata execute() { // update the project dependencies table only with valid engineIds if (engineIdMap.containsKey("success")) { Map successMap = (Map) engineIdMap.get("success"); - SecurityCatalogDependencyUtils.setDependencyIds(user, projectId, - SecurityCatalogDependencyUtils.resolveCatalogType(projectId, null), successMap.keySet()); + SecurityCatalogDependencyUtils.syncAutomaticDependencyIds(user, projectId, + SecurityCatalogDependencyUtils.resolveCatalogType(projectId, null), CatalogDependencyRole.CODE_REFERENCE, + "Engine referenced in this app's files", successMap.keySet()); } // sending the success and failed list of engineIds to FE diff --git a/src/prerna/reactor/project/SaveAppBlocksJsonReactor.java b/src/prerna/reactor/project/SaveAppBlocksJsonReactor.java index e7df78c9b51..3172444ff4f 100644 --- a/src/prerna/reactor/project/SaveAppBlocksJsonReactor.java +++ b/src/prerna/reactor/project/SaveAppBlocksJsonReactor.java @@ -45,6 +45,7 @@ import com.google.gson.ToNumberPolicy; import prerna.auth.User; +import prerna.auth.utils.CatalogDependencyRole; import prerna.auth.utils.SecurityCatalogDependencyUtils; import prerna.auth.utils.SecurityProjectUtils; import prerna.cluster.util.ClusterUtil; @@ -139,8 +140,8 @@ public NounMetadata execute() { Map engineDependenciesMap = project.getEngineDependencies(); Set engineDependencyIds = new HashSet<>(engineDependenciesMap.values()); engineDependencyIds.remove(INotebookHelper.UNDEFINED_VALUE); - SecurityCatalogDependencyUtils.setDependencyIds(user, projectId, IProject.PROJECT_TYPE.BLOCKS.name(), - engineDependencyIds); + SecurityCatalogDependencyUtils.syncAutomaticDependencyIds(user, projectId, IProject.PROJECT_TYPE.BLOCKS.name(), + CatalogDependencyRole.BLOCK_ENGINE, "Engine a block of this app uses", engineDependencyIds); SecurityProjectUtils.updateProjectLastEditedDate(projectId); UserAuditTrailUtils.recordProjectLifecycle(user, AuditEventType.PROJECT_BLOCKS_UPDATE, projectId, project.getProjectName(), Map.of("changedFields", List.of("blocks", "dependencies"))); diff --git a/src/prerna/reactor/project/UploadProjectAppReactor.java b/src/prerna/reactor/project/UploadProjectAppReactor.java index dcc003995fc..3f11e4ec069 100644 --- a/src/prerna/reactor/project/UploadProjectAppReactor.java +++ b/src/prerna/reactor/project/UploadProjectAppReactor.java @@ -399,9 +399,14 @@ public NounMetadata execute() { SecurityCatalogDependencyUtils.fromExported(exportedDependencies)); if (engineIdMap.containsKey("success")) { Map successMap = (Map) engineIdMap.get("success"); - dependencies.addAll(SecurityCatalogDependencyUtils.resolveDependencies(successMap.keySet(), null)); + for (SecurityCatalogDependencyUtils.Dependency found : SecurityCatalogDependencyUtils + .resolveDependencies(successMap.keySet(), null)) { + dependencies.add(SecurityCatalogDependencyUtils.Dependency.automatic(found.id(), found.type(), + prerna.auth.utils.CatalogDependencyRole.CODE_REFERENCE, + "Engine referenced in this app's files")); + } } - SecurityCatalogDependencyUtils.setDependencies(user, projectId, + SecurityCatalogDependencyUtils.replaceAllDependencies(user, projectId, SecurityCatalogDependencyUtils.resolveCatalogType(projectId, null), dependencies); } diff --git a/src/prerna/reactor/project/UploadProjectReactor.java b/src/prerna/reactor/project/UploadProjectReactor.java index 36be6d542e8..1f475d723c1 100644 --- a/src/prerna/reactor/project/UploadProjectReactor.java +++ b/src/prerna/reactor/project/UploadProjectReactor.java @@ -296,7 +296,7 @@ public NounMetadata execute() { // TypeToken>() {}.getType()); if (projectDependencies != null && !projectDependencies.isEmpty()) { // reads exports from this release and older ones, with each type - SecurityCatalogDependencyUtils.setDependencies(user, projectId, + SecurityCatalogDependencyUtils.replaceAllDependencies(user, projectId, SecurityCatalogDependencyUtils.resolveCatalogType(projectId, null), SecurityCatalogDependencyUtils.fromExported(projectDependencies)); } diff --git a/src/prerna/reactor/security/AdminBackfillCatalogDependenciesReactor.java b/src/prerna/reactor/security/AdminBackfillCatalogDependenciesReactor.java new file mode 100644 index 00000000000..0c9995c130a --- /dev/null +++ b/src/prerna/reactor/security/AdminBackfillCatalogDependenciesReactor.java @@ -0,0 +1,290 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.security; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.json.JSONArray; +import org.json.JSONObject; + +import com.google.gson.Gson; + +import prerna.auth.User; +import prerna.auth.utils.CatalogDependencyDerivation; +import prerna.auth.utils.CatalogDependencyRole; +import prerna.auth.utils.CatalogTypes; +import prerna.auth.utils.SecurityAdminUtils; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; +import prerna.auth.utils.SecurityEngineUtils; +import prerna.engine.api.IEngine; +import prerna.engine.impl.model.ModelRouterEngine; +import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils; +import prerna.engine.impl.pipeline.EngineProxyFactory; +import prerna.project.api.IProject; +import prerna.project.impl.ProjectHelper; +import prerna.project.impl.notebook.INotebookHelper; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.reactor.automation.definition.AutomationDefinitionService; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.util.EngineUtility; +import prerna.util.QueryExecutionUtility; +import prerna.util.SystemEngineRegistry; +import prerna.util.Utility; + +/** + * Works out the automatic dependencies of every engine, agent, automation and app + * from what each has saved, for items saved before dependencies were derived: + * engines' guardrails and smss references, model routers' routes, agents' tools, + * knowledge, skills, model and subagents, automations' nodes, blocks apps' + * engines, and the ids in code apps' files. Picked + * dependencies are kept; a row from before IS_AUTOMATIC that a derived one + * stands for is replaced. Safe to run again. + */ +public class AdminBackfillCatalogDependenciesReactor extends AbstractReactor { + + private static final Logger classLogger = LogManager.getLogger(AdminBackfillCatalogDependenciesReactor.class); + + public AdminBackfillCatalogDependenciesReactor() { + this.keysToGet = new String[0]; + } + + @Override + public NounMetadata execute() { + User user = this.insight.getUser(); + if (!SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalArgumentException("User is not an admin and does not have access. Please login as an admin"); + } + + int engines = 0; + List failed = new ArrayList<>(); + for (String engineId : SecurityEngineUtils.getAllEngineIds()) { + try { + backfillEngine(user, engineId); + engines++; + } catch (Exception e) { + classLogger.warn("Could not backfill the dependencies of engine {}", engineId, e); + failed.add(engineId); + } + } + + int workspaces = 0; + for (String projectId : projectIdsOfType(IProject.PROJECT_TYPE.WORKSPACE.name())) { + try { + backfillWorkspace(user, projectId); + workspaces++; + } catch (Exception e) { + classLogger.warn("Could not backfill the dependencies of agent {}", projectId, e); + failed.add(projectId); + } + } + + int automations = 0; + for (String projectId : projectIdsOfType(IProject.PROJECT_TYPE.AUTOMATION.name())) { + try { + backfillAutomation(user, projectId); + automations++; + } catch (Exception e) { + classLogger.warn("Could not backfill the dependencies of automation {}", projectId, e); + failed.add(projectId); + } + } + + int blocks = 0; + for (String projectId : projectIdsOfType(IProject.PROJECT_TYPE.BLOCKS.name())) { + try { + backfillBlocks(user, projectId); + blocks++; + } catch (Exception e) { + classLogger.warn("Could not backfill the dependencies of blocks app {}", projectId, e); + failed.add(projectId); + } + } + + int code = 0; + for (String projectId : projectIdsOfType(IProject.PROJECT_TYPE.CODE.name())) { + try { + backfillCode(user, projectId); + code++; + } catch (Exception e) { + classLogger.warn("Could not backfill the dependencies of code app {}", projectId, e); + failed.add(projectId); + } + } + + Map result = new LinkedHashMap<>(); + result.put("engines", engines); + result.put("agents", workspaces); + result.put("automations", automations); + result.put("blocks", blocks); + result.put("code", code); + result.put("failed", failed); + return new NounMetadata(result, PixelDataType.MAP); + } + + @SuppressWarnings("unchecked") + private static void backfillEngine(User user, String engineId) throws Exception { + IEngine engine = Utility.getEngine(engineId); + if (engine == null) { + throw new IllegalStateException("Engine " + engineId + " could not be loaded"); + } + String engineType = engine.getCatalogType().name(); + CatalogDependencyDerivation.syncSmss(user, engineId, engineType, engine.getSmssProp()); + + if (engine.getCatalogType() != IEngine.CATALOG_TYPE.GUARDRAIL) { + String pipelineName = engine.getSmssProp().getProperty(IEngine.PIPELINE); + Map pipelines = Map.of(); + if (pipelineName != null && !pipelineName.isBlank()) { + File pipelineFile = EngineProxyFactory.pipelineFile(engine, pipelineName.trim()); + if (pipelineFile.isFile()) { + Map config = new Gson().fromJson( + Files.readString(pipelineFile.toPath(), StandardCharsets.UTF_8), Map.class); + if (config != null && config.get("pipelines") instanceof Map read) { + pipelines = (Map) read; + } + } + } + CatalogDependencyDerivation.syncGuardrails(user, engineId, engineType, pipelines); + } + + if (engine instanceof ModelRouterEngine router) { + File configFile = router.resolveConfigFile(); + if (configFile.isFile()) { + CatalogDependencyDerivation.syncRouterJson(user, engineId, + Files.readString(configFile.toPath(), StandardCharsets.UTF_8)); + } + } + } + + private static void backfillWorkspace(User user, String workspaceId) { + List> resources = ModelInferenceLogsUtils.getWorkspaceResourcesByType(workspaceId, null); + JSONObject config = ModelInferenceLogsUtils.getWorkspaceConfigJson(workspaceId); + String modelId = config == null ? null : config.optString("model_id", null); + List subagentIds = new ArrayList<>(); + JSONArray subagents = config == null ? null : config.optJSONArray("subagents"); + if (subagents != null) { + for (int i = 0; i < subagents.length(); i++) { + JSONObject subagent = subagents.optJSONObject(i); + if (subagent != null) { + subagentIds.add(subagent.optString("workspaceId", null)); + } + } + } + List dependencies = CatalogDependencyDerivation.fromWorkspace(resources, modelId, subagentIds, + CatalogTypes::resolve); + SecurityCatalogDependencyUtils.syncAutomaticDependencies(user, workspaceId, + IProject.PROJECT_TYPE.WORKSPACE.name(), CatalogDependencyDerivation.WORKSPACE_ROLES, dependencies); + } + + @SuppressWarnings("unchecked") + private static void backfillAutomation(User user, String projectId) { + String definition = AutomationDefinitionService.load(projectId).definition(); + List> nodes = new ArrayList<>(); + if (definition != null && !definition.isBlank()) { + Map parsed = new Gson().fromJson(definition, Map.class); + if (parsed != null && parsed.get("nodes") instanceof List list) { + for (Object node : list) { + if (node instanceof Map nodeMap) { + nodes.add((Map) nodeMap); + } + } + } + } + SecurityCatalogDependencyUtils.syncAutomaticDependencies(user, projectId, + IProject.PROJECT_TYPE.AUTOMATION.name(), List.of(CatalogDependencyRole.AUTOMATION_NODE), + CatalogDependencyDerivation.fromAutomationNodes(nodes, CatalogTypes::resolve)); + } + + /** + * A blocks app's BLOCK_ENGINE dependencies, read from its saved blocks json as + * SaveAppBlocksJson records them + */ + private static void backfillBlocks(User user, String projectId) { + IProject project = Utility.getProject(projectId); + if (project == null) { + throw new IllegalStateException("Blocks app " + projectId + " could not be loaded"); + } + Set engineIds = new HashSet<>(project.getEngineDependencies().values()); + engineIds.remove(INotebookHelper.UNDEFINED_VALUE); + SecurityCatalogDependencyUtils.syncAutomaticDependencyIds(user, projectId, IProject.PROJECT_TYPE.BLOCKS.name(), + CatalogDependencyRole.BLOCK_ENGINE, "Engine a block of this app uses", engineIds); + } + + /** + * A code app's CODE_REFERENCE dependencies: the engine and project ids found in + * its files, as ExtractAndSetDependencies records them for the whole app + */ + @SuppressWarnings("unchecked") + private static void backfillCode(User user, String projectId) { + IProject project = Utility.getProject(projectId); + if (project == null) { + throw new IllegalStateException("Code app " + projectId + " could not be loaded"); + } + File assets = new File(EngineUtility.getSpecificEngineAssetsFolder(IEngine.CATALOG_TYPE.PROJECT, + project.getProjectId(), project.getProjectName())); + Map found = ProjectHelper.extractEngineIdsFromProjectFolder(assets); + Set ids = found.get("success") instanceof Map success + ? ((Map) success).keySet() + : Set.of(); + SecurityCatalogDependencyUtils.syncAutomaticDependencyIds(user, projectId, IProject.PROJECT_TYPE.CODE.name(), + CatalogDependencyRole.CODE_REFERENCE, "Engine referenced in this app's files", ids); + } + + private static List projectIdsOfType(String type) { + try { + return QueryExecutionUtility.queryList(SystemEngineRegistry.getSecurityDb(), + "SELECT PROJECTID FROM PROJECT WHERE TYPE=?", ps -> ps.setString(1, type), rs -> rs.getString(1)); + } catch (Exception e) { + classLogger.error("Could not list the {} projects", type, e); + return List.of(); + } + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition().noKeys() + .description("Admin Only: Works out the automatic dependencies of every engine, agent, automation and app " + + "from its saved configuration: guardrails, judge models, vector databases, embedders, router " + + "models, agent tools, knowledge, skills, models and subagents, automation steps, blocks app engines " + + "and the ids in code apps' files. " + + "Picked dependencies are kept. Safe to run again.") + .output(Map.class, "How many engines, agents, automations, blocks apps and code apps were read, and the ids that failed"); + } +} diff --git a/src/prerna/reactor/security/CatalogDependencyKeys.java b/src/prerna/reactor/security/CatalogDependencyKeys.java index 47ac8a8d44e..6f8be7559f8 100644 --- a/src/prerna/reactor/security/CatalogDependencyKeys.java +++ b/src/prerna/reactor/security/CatalogDependencyKeys.java @@ -1,3 +1,30 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ package prerna.reactor.security; /** diff --git a/src/prerna/reactor/security/GetCatalogDependenciesReactor.java b/src/prerna/reactor/security/GetCatalogDependenciesReactor.java index 6baa821ae0f..da724e7d14e 100644 --- a/src/prerna/reactor/security/GetCatalogDependenciesReactor.java +++ b/src/prerna/reactor/security/GetCatalogDependenciesReactor.java @@ -44,6 +44,10 @@ public class GetCatalogDependenciesReactor extends AbstractReactor { + /** The fields of a link, kept on each entry of links and not on the items */ + private static final String[] LINK_KEYS = { "is_automatic", "role", "dependency_name", + "dependency_description" }; + public GetCatalogDependenciesReactor() { this.keysToGet = new String[] { CatalogDependencyKeys.CATALOG_ID, CatalogDependencyKeys.CATALOG_TYPE }; this.keyRequired = new int[] { 1, 0 }; @@ -113,9 +117,13 @@ private Map buildDependencyGraph(List> depen String engineId = entry.getKey(); Map originalEngine = entry.getValue(); - // Create engine object with all metadata except parent_id + // Create engine object with all metadata except parent_id and the link, + // which belongs to an edge and is in links Map engine = new HashMap<>(originalEngine); engine.remove("parent_id"); + for (String linkKey : LINK_KEYS) { + engine.remove(linkKey); + } // Derive permission_name from the highest permission (lowest integer id) the // user holds, considering both direct and group permissions @@ -165,10 +173,31 @@ private Map buildDependencyGraph(List> depen } } + // Every link between reachable items, one per role: the root's own + // dependencies are the links whose parent_id is the root + List> links = new ArrayList<>(); + for (Map dep : dependencies) { + String parentId = (String) dep.get("parent_id"); + String childId = (String) dep.get("catalog_id"); + boolean parentReachable = parentId != null + && (parentId.equals(rootProjectId) || reachableEngines.containsKey(parentId)); + if (!parentReachable || !reachableEngines.containsKey(childId)) { + continue; + } + Map link = new HashMap<>(); + link.put("parent_id", parentId); + link.put("catalog_id", childId); + for (String linkKey : LINK_KEYS) { + link.put(linkKey, dep.get(linkKey)); + } + links.add(link); + } + // Build result structure Map result = new HashMap<>(); result.put("dependencies", engines); result.put("dependencyIds", filteredRootDeps); + result.put("links", links); return result; } @@ -215,7 +244,8 @@ private void traverseReachable(String parentId, Map> public ReactorDefinition getReactorDefinition() { return super.getReactorDefinition() .description("Get the engines and projects an engine or project depends on, all the way down, each once with " - + "its direct dependencies"); + + "its direct dependencies, and links: each link between them as parent_id, catalog_id, " + + "is_automatic, role, dependency_name and dependency_description, one per role"); } } \ No newline at end of file diff --git a/src/prerna/reactor/security/GetCatalogDependentsReactor.java b/src/prerna/reactor/security/GetCatalogDependentsReactor.java new file mode 100644 index 00000000000..947572127e1 --- /dev/null +++ b/src/prerna/reactor/security/GetCatalogDependentsReactor.java @@ -0,0 +1,108 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.security; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.nounmeta.NounMetadata; + +/** + * The engines and projects that depend on an engine or a project: what deleting + * or changing it would affect. Only the ones the user can view are listed; the + * rest are counted. + */ +public class GetCatalogDependentsReactor extends AbstractReactor { + + private static final String RECURSIVE = "recursive"; + + public GetCatalogDependentsReactor() { + this.keysToGet = new String[] { CatalogDependencyKeys.CATALOG_ID, CatalogDependencyKeys.CATALOG_TYPE, + RECURSIVE }; + this.keyRequired = new int[] { 1, 0, 0 }; + } + + @Override + public NounMetadata execute() { + organizeKeys(); + User user = this.insight.getUser(); + String catalogId = this.keyValue.get(CatalogDependencyKeys.CATALOG_ID); + String catalogType = SecurityCatalogDependencyUtils.resolveCatalogType(catalogId, + this.keyValue.get(CatalogDependencyKeys.CATALOG_TYPE)); + if (!SecurityCatalogDependencyUtils.userCanView(user, catalogId, catalogType)) { + throw new IllegalArgumentException("The user does not have access to view " + catalogId); + } + boolean recursive = Boolean.parseBoolean(this.keyValue.get(RECURSIVE)); + + List> visible = new ArrayList<>(); + Set hidden = new HashSet<>(); + Map canView = new HashMap<>(); + for (Map dependent : SecurityCatalogDependencyUtils.getDependents(catalogId, recursive)) { + String id = (String) dependent.get("catalog_id"); + String type = (String) dependent.get("catalog_type"); + boolean viewable = canView.computeIfAbsent(id, key -> { + try { + return SecurityCatalogDependencyUtils.userCanView(user, key, type); + } catch (IllegalArgumentException e) { + // a type no longer known + return false; + } + }); + if (viewable) { + visible.add(dependent); + } else { + hidden.add(id); + } + } + + Map result = new HashMap<>(); + result.put("dependents", visible); + result.put("hiddenCount", hidden.size()); + return new NounMetadata(result, PixelDataType.MAP); + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition() + .description("Get the engines and projects that depend on an engine or project, one row per link with " + + "is_automatic, role, dependency_name and dependency_description, and how many the user " + + "cannot view") + .key(CatalogDependencyKeys.CATALOG_ID, "The engine id or project id") + .key(CatalogDependencyKeys.CATALOG_TYPE, "Its engine type or project type; read when not given") + .key(RECURSIVE, "Whether to add the items that depend on those, all the way up; false by default"); + } +} diff --git a/src/prerna/reactor/security/SetCatalogDependenciesReactor.java b/src/prerna/reactor/security/SetCatalogDependenciesReactor.java index c05b40be126..8b6509af359 100644 --- a/src/prerna/reactor/security/SetCatalogDependenciesReactor.java +++ b/src/prerna/reactor/security/SetCatalogDependenciesReactor.java @@ -1,3 +1,30 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ package prerna.reactor.security; import java.util.ArrayList; @@ -15,9 +42,11 @@ import prerna.sablecc2.om.nounmeta.NounMetadata; /** - * Replaces the dependencies of an engine or a project with the engines and - * projects given. Each is checked against the security database alone, so this - * works on any server of a cluster. + * Replaces the dependencies a user picked for an engine or a project with the + * engines and projects given, each with an optional name and description. The + * automatic dependencies, which save reactors derive from the item's own + * configuration, are kept. Each is checked against the security database alone, + * so this works on any server of a cluster. */ public class SetCatalogDependenciesReactor extends AbstractReactor { @@ -58,10 +87,15 @@ public NounMetadata execute() { throw new IllegalArgumentException( "'" + dependencyId + "' is a " + stored + ", not a " + dependencyType); } - dependencies.add(new Dependency(dependencyId, dependencyType)); + Object name = entry.get("name"); + Object description = entry.get("description"); + if ((name != null && !(name instanceof String)) || (description != null && !(description instanceof String))) { + throw new IllegalArgumentException("A dependency's name and description must be text"); + } + dependencies.add(Dependency.manual(dependencyId, dependencyType, (String) name, (String) description)); } - SecurityCatalogDependencyUtils.setDependencies(user, catalogId, catalogType, dependencies); + SecurityCatalogDependencyUtils.setManualDependencies(user, catalogId, catalogType, dependencies); NounMetadata noun = new NounMetadata(true, PixelDataType.BOOLEAN); noun.addAdditionalReturn(NounMetadata.getSuccessNounMessage("Successfully set the new dependencies")); @@ -71,13 +105,15 @@ public NounMetadata execute() { @Override public ReactorDefinition getReactorDefinition() { return super.getReactorDefinition() - .description("Set the engines and projects an engine or project depends on") + .description("Set the engines and projects a user picked for an engine or project to depend on; " + + "the automatic dependencies derived from its configuration are kept") .key(CatalogDependencyKeys.CATALOG_ID, "The engine id or project id") .key(CatalogDependencyKeys.CATALOG_TYPE, "Its engine type or project type, such as FUNCTION or SKILL; read when not given") .key(CatalogDependencyKeys.DEPENDENCIES, - "The engines and projects it depends on, each as {id, type} with its own engine type or " - + "project type. An empty list removes them all."); + "The engines and projects it depends on, each as {id, type, name?, description?} with its " + + "own engine type or project type. A name is a key unique for the item. An empty list " + + "removes every picked dependency."); } @SuppressWarnings("unchecked") diff --git a/src/prerna/reactor/security/ValidateCatalogDependenciesReactor.java b/src/prerna/reactor/security/ValidateCatalogDependenciesReactor.java index 021eda4b29e..b49d3c0b696 100644 --- a/src/prerna/reactor/security/ValidateCatalogDependenciesReactor.java +++ b/src/prerna/reactor/security/ValidateCatalogDependenciesReactor.java @@ -1,3 +1,30 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ package prerna.reactor.security; import java.util.Map; diff --git a/src/prerna/reactor/vector/upload/CreateVectorDatabaseEngineReactor.java b/src/prerna/reactor/vector/upload/CreateVectorDatabaseEngineReactor.java index 3e6a8857dec..458e9690b99 100644 --- a/src/prerna/reactor/vector/upload/CreateVectorDatabaseEngineReactor.java +++ b/src/prerna/reactor/vector/upload/CreateVectorDatabaseEngineReactor.java @@ -1,267 +1,269 @@ -/******************************************************************************* - * Copyright 2015 Defense Health Agency (DHA) - * - * If your use of this software does not include any GPLv2 components: - * Licensed 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. - * ---------------------------------------------------------------------------- - * If your use of this software includes any GPLv2 components: - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - *******************************************************************************/ -package prerna.reactor.vector.upload; - -import java.io.File; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.apache.commons.io.FileUtils; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import prerna.auth.AuthProvider; -import prerna.auth.User; -import prerna.auth.utils.AbstractSecurityUtils; -import prerna.auth.utils.SecurityAdminUtils; -import prerna.auth.utils.SecurityEngineUtils; -import prerna.auth.utils.SecurityQueryUtils; -import prerna.cluster.util.ClusterUtil; -import prerna.engine.api.IEngine; -import prerna.engine.api.IModelEngine; -import prerna.engine.api.IVectorDatabaseEngine; -import prerna.engine.api.VectorDatabaseTypeEnum; -import prerna.engine.impl.vector.FaissDatabaseEngine; -import prerna.engine.impl.vector.OpenSearchRestVectorDatabaseEngine; -import prerna.reactor.AbstractReactor; -import prerna.sablecc2.om.GenRowStruct; -import prerna.sablecc2.om.PixelDataType; -import prerna.sablecc2.om.PixelOperationType; -import prerna.sablecc2.om.ReactorKeysEnum; -import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.usertracking.AuditEventType; -import prerna.usertracking.AuditTargetType; -import prerna.usertracking.UserAuditTrailUtils; -import prerna.util.Constants; -import prerna.util.UploadUtilities; -import prerna.util.Utility; - -public class CreateVectorDatabaseEngineReactor extends AbstractReactor { - - private static final Logger classLogger = LogManager.getLogger(CreateVectorDatabaseEngineReactor.class); - - private static final String CATALOG_NAME_KEYS = ReactorKeysEnum.CATALOG_NAME.getKey() + "," + ReactorKeysEnum.DATABASE.getKey(); - - public CreateVectorDatabaseEngineReactor() { - this.keysToGet = new String[] { CATALOG_NAME_KEYS, ReactorKeysEnum.CONNECTION_DETAILS.getKey(), - ReactorKeysEnum.GLOBAL.getKey() }; - this.keyRequired = new int[] { 1, 1, 0 }; - } - - @Override - public NounMetadata execute() { - User user = requireUser(); - - // throw error is user doesn't have rights to publish new databases - if (AbstractSecurityUtils.adminSetPublisher() && !SecurityQueryUtils.userIsPublisher(this.insight.getUser())) { - throwUserNotPublisherError(); - } - - if (AbstractSecurityUtils.adminOnlyVectorAdd() && !SecurityAdminUtils.userIsAdmin(user)) { - throwFunctionalityOnlyExposedForAdminsError(); - } - - organizeKeys(); - - String vectorDbName = getVectorDatabaseName(); - // if vector db name is not valid throw error - if (!Utility.validateName(vectorDbName)) { - // error and redirect to try again - throw new IllegalArgumentException( - "Invalid Name: It must start with a letter and can only contain letters, numbers, and spaces."); - } - - // String vectorDbName = getVectorDatabaseName(); - Map vectorDbDetails = getVectorDatabaseDetails(); - boolean global = Boolean.parseBoolean(this.keyValue.get(ReactorKeysEnum.GLOBAL.getKey()) + ""); - - NounMetadata warning = null; - if (global) { - if (AbstractSecurityUtils.adminOnlyEngineSetPublic(IEngine.CATALOG_TYPE.VECTOR) - && !SecurityAdminUtils.userIsAdmin(user)) { - warning = NounMetadata.getWarningNounMessage( - "Public access can only be enabled by administrators. This item will be created as private."); - global = false; - } - } - - String vectorDbTypeStr = (String) vectorDbDetails.get(IVectorDatabaseEngine.VECTOR_TYPE); - if (vectorDbTypeStr == null || (vectorDbTypeStr = vectorDbTypeStr.trim()).isEmpty()) { - throw new IllegalArgumentException("Must define the vector db type"); - } - - VectorDatabaseTypeEnum vectorDbType = null; - try { - vectorDbType = VectorDatabaseTypeEnum.getEnumFromName(vectorDbTypeStr); - } catch (Exception e) { - throw new IllegalArgumentException("Invalid vector db type " + vectorDbTypeStr); - } - // TODO - // IF IT IS TYPE PROXY THEN I DONT NEED THE EMBEDDER ENGINE NAME - if (vectorDbType != VectorDatabaseTypeEnum.PROXY - && !vectorDbDetails.containsKey(Constants.EMBEDDER_ENGINE_NAME)) { - String embedderEngineId = (String) vectorDbDetails.getOrDefault(Constants.EMBEDDER_ENGINE_ID, null); - if (embedderEngineId == null) { - throw new IllegalArgumentException("EMBEDDER_ENGINE_ID must be defined for FAISS database"); - } - - IModelEngine embeddingModel = Utility.getModel(embedderEngineId); - if (embeddingModel == null) { - throw new IllegalArgumentException("EMBEDDER_ENGINE_ID " + embeddingModel + " could not be found"); - } - String embeddingModelAlias = embeddingModel.getSmssProp().getProperty(Constants.ENGINE_ALIAS); - vectorDbDetails.put(Constants.EMBEDDER_ENGINE_NAME, embeddingModelAlias); - } - - if (vectorDbType == VectorDatabaseTypeEnum.FAISS - && !vectorDbDetails.containsKey(FaissDatabaseEngine.ENABLE_HYBRID_SEARCH)) { - vectorDbDetails.put(FaissDatabaseEngine.ENABLE_HYBRID_SEARCH, true); - } - - if (!vectorDbDetails.containsKey(Constants.INDEX_CLASSES)) { - vectorDbDetails.put(Constants.INDEX_CLASSES, "default"); - } - - if (vectorDbType == VectorDatabaseTypeEnum.OPEN_SEARCH) { - if (vectorDbDetails.get(Constants.USERNAME) == null) { - throw new IllegalArgumentException(Constants.USERNAME + " is not provided."); - } - if (vectorDbDetails.get(Constants.PASSWORD) == null) { - throw new IllegalArgumentException(Constants.PASSWORD + " is not provided."); - } - if (vectorDbDetails.get(Constants.HOSTNAME) == null) { - throw new IllegalArgumentException(Constants.HOSTNAME + " is not provided."); - } - if (vectorDbDetails.get(OpenSearchRestVectorDatabaseEngine.INDEX_NAME) == null) { - throw new IllegalArgumentException(OpenSearchRestVectorDatabaseEngine.INDEX_NAME + " is not provided."); - } - } - if (vectorDbType == VectorDatabaseTypeEnum.WEAVIATE) { - if (vectorDbDetails.get(Constants.API_KEY) == null) { - throw new IllegalArgumentException(Constants.API_KEY + " is not provided."); - } - if (vectorDbDetails.get(Constants.HOSTNAME) == null) { - throw new IllegalArgumentException(Constants.HOSTNAME + " is not provided."); - } - } - - // vectorDbDetails.put(Constants.PIPELINE,"PIPELINE.json"); - - String vectorDbId = UUID.randomUUID().toString(); - File tempSmss = null; - File smssFile = null; - File specificEngineFolder = null; - IVectorDatabaseEngine vectorDb = null; - try { - // validate engine - UploadUtilities.validateEngine(IEngine.CATALOG_TYPE.VECTOR, user, vectorDbName, vectorDbId); - specificEngineFolder = UploadUtilities.generateSpecificEngineFolder(IEngine.CATALOG_TYPE.VECTOR, vectorDbId, - vectorDbName); - - String vectorDbClass = vectorDbType.getVectorDatabaseClass(); - vectorDb = (IVectorDatabaseEngine) Class.forName(vectorDbClass).getDeclaredConstructor().newInstance(); - tempSmss = UploadUtilities.createTemporaryVectorDatabaseSmss(vectorDbId, vectorDbName, vectorDbClass, - vectorDbDetails); - - // store in DIHelper so that when we move temp smss to smss it doesn't try to - // reload again - UploadUtilities.addEngineToDIHelperToIgnoreEngineWatchers(vectorDbId, tempSmss.getAbsolutePath()); - vectorDb.open(tempSmss.getAbsolutePath()); - - smssFile = new File(tempSmss.getAbsolutePath().replace(".temp", ".smss")); - FileUtils.copyFile(tempSmss, smssFile); - tempSmss.delete(); - vectorDb.setSmssFilePath(smssFile.getAbsolutePath()); - UploadUtilities.addEngineToDIHelper(vectorDbId, vectorDbName, vectorDb, smssFile); - SecurityEngineUtils.addEngine(vectorDbId, global, user); - - List logins = user.getLogins(); - for (AuthProvider ap : logins) { - SecurityEngineUtils.addEngineOwner(vectorDbId, user.getAccessToken(ap).getId()); - } - - ClusterUtil.pushEngine(vectorDbId); - UserAuditTrailUtils.recordEngineLifecycle(user, AuditEventType.VECTOR_CREATE, AuditTargetType.VECTOR, - vectorDbId, vectorDbName, - Map.of("global", global, "vectorType", vectorDbType.getVectorDatabaseName())); - } catch (Exception e) { - classLogger.error("Failed to create vector database engine {} ({})", vectorDbName, vectorDbId, e); - UploadUtilities.cleanUpCreateNewError(vectorDb, vectorDbId, tempSmss, smssFile, specificEngineFolder); - return new NounMetadata(e.getMessage(), PixelDataType.CONST_STRING, PixelOperationType.ERROR); - } - - Map retMap = UploadUtilities.getEngineReturnData(this.insight.getUser(), vectorDbId); - NounMetadata retNoun = new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, - PixelOperationType.MARKET_PLACE_ADDITION); - if (warning != null) { - retNoun.addAdditionalReturn(warning); - } - return retNoun; - } - - /** - * - * @return - */ - private String getVectorDatabaseName() { - List strValues = getListStringForAliasedKey(CATALOG_NAME_KEYS); - if (!strValues.isEmpty()) { - return strValues.get(0).trim(); - } - - strValues = this.curRow.getAllStrValues(); - if (strValues != null && !strValues.isEmpty()) { - return strValues.get(0).trim(); - } - - throw new NullPointerException("Must define the name of the new vector database engine"); - } - - /** - * - * @return - */ - private Map getVectorDatabaseDetails() { - GenRowStruct grs = this.store.getGenRowStruct(ReactorKeysEnum.CONNECTION_DETAILS.getKey()); - if (grs != null && !grs.isEmpty()) { - List mapNouns = grs.getNounsOfType(PixelDataType.MAP); - if (mapNouns != null && !mapNouns.isEmpty()) { - return (Map) mapNouns.get(0).getValue(); - } - } - - List mapNouns = this.curRow.getNounsOfType(PixelDataType.MAP); - if (mapNouns != null && !mapNouns.isEmpty()) { - return (Map) mapNouns.get(0).getValue(); - } - - throw new NullPointerException("Must define the properties for the new vector database engine"); - } - -} +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.vector.upload; + +import prerna.auth.utils.CatalogDependencyDerivation; +import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.io.FileUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import prerna.auth.AuthProvider; +import prerna.auth.User; +import prerna.auth.utils.AbstractSecurityUtils; +import prerna.auth.utils.SecurityAdminUtils; +import prerna.auth.utils.SecurityEngineUtils; +import prerna.auth.utils.SecurityQueryUtils; +import prerna.cluster.util.ClusterUtil; +import prerna.engine.api.IEngine; +import prerna.engine.api.IModelEngine; +import prerna.engine.api.IVectorDatabaseEngine; +import prerna.engine.api.VectorDatabaseTypeEnum; +import prerna.engine.impl.vector.FaissDatabaseEngine; +import prerna.engine.impl.vector.OpenSearchRestVectorDatabaseEngine; +import prerna.reactor.AbstractReactor; +import prerna.sablecc2.om.GenRowStruct; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.PixelOperationType; +import prerna.sablecc2.om.ReactorKeysEnum; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.usertracking.AuditEventType; +import prerna.usertracking.AuditTargetType; +import prerna.usertracking.UserAuditTrailUtils; +import prerna.util.Constants; +import prerna.util.UploadUtilities; +import prerna.util.Utility; + +public class CreateVectorDatabaseEngineReactor extends AbstractReactor { + + private static final Logger classLogger = LogManager.getLogger(CreateVectorDatabaseEngineReactor.class); + + private static final String CATALOG_NAME_KEYS = ReactorKeysEnum.CATALOG_NAME.getKey() + "," + ReactorKeysEnum.DATABASE.getKey(); + + public CreateVectorDatabaseEngineReactor() { + this.keysToGet = new String[] { CATALOG_NAME_KEYS, ReactorKeysEnum.CONNECTION_DETAILS.getKey(), + ReactorKeysEnum.GLOBAL.getKey() }; + this.keyRequired = new int[] { 1, 1, 0 }; + } + + @Override + public NounMetadata execute() { + User user = requireUser(); + + // throw error is user doesn't have rights to publish new databases + if (AbstractSecurityUtils.adminSetPublisher() && !SecurityQueryUtils.userIsPublisher(this.insight.getUser())) { + throwUserNotPublisherError(); + } + + if (AbstractSecurityUtils.adminOnlyVectorAdd() && !SecurityAdminUtils.userIsAdmin(user)) { + throwFunctionalityOnlyExposedForAdminsError(); + } + + organizeKeys(); + + String vectorDbName = getVectorDatabaseName(); + // if vector db name is not valid throw error + if (!Utility.validateName(vectorDbName)) { + // error and redirect to try again + throw new IllegalArgumentException( + "Invalid Name: It must start with a letter and can only contain letters, numbers, and spaces."); + } + + // String vectorDbName = getVectorDatabaseName(); + Map vectorDbDetails = getVectorDatabaseDetails(); + boolean global = Boolean.parseBoolean(this.keyValue.get(ReactorKeysEnum.GLOBAL.getKey()) + ""); + + NounMetadata warning = null; + if (global) { + if (AbstractSecurityUtils.adminOnlyEngineSetPublic(IEngine.CATALOG_TYPE.VECTOR) + && !SecurityAdminUtils.userIsAdmin(user)) { + warning = NounMetadata.getWarningNounMessage( + "Public access can only be enabled by administrators. This item will be created as private."); + global = false; + } + } + + String vectorDbTypeStr = (String) vectorDbDetails.get(IVectorDatabaseEngine.VECTOR_TYPE); + if (vectorDbTypeStr == null || (vectorDbTypeStr = vectorDbTypeStr.trim()).isEmpty()) { + throw new IllegalArgumentException("Must define the vector db type"); + } + + VectorDatabaseTypeEnum vectorDbType = null; + try { + vectorDbType = VectorDatabaseTypeEnum.getEnumFromName(vectorDbTypeStr); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid vector db type " + vectorDbTypeStr); + } + // TODO + // IF IT IS TYPE PROXY THEN I DONT NEED THE EMBEDDER ENGINE NAME + if (vectorDbType != VectorDatabaseTypeEnum.PROXY + && !vectorDbDetails.containsKey(Constants.EMBEDDER_ENGINE_NAME)) { + String embedderEngineId = (String) vectorDbDetails.getOrDefault(Constants.EMBEDDER_ENGINE_ID, null); + if (embedderEngineId == null) { + throw new IllegalArgumentException("EMBEDDER_ENGINE_ID must be defined for FAISS database"); + } + + IModelEngine embeddingModel = Utility.getModel(embedderEngineId); + if (embeddingModel == null) { + throw new IllegalArgumentException("EMBEDDER_ENGINE_ID " + embeddingModel + " could not be found"); + } + String embeddingModelAlias = embeddingModel.getSmssProp().getProperty(Constants.ENGINE_ALIAS); + vectorDbDetails.put(Constants.EMBEDDER_ENGINE_NAME, embeddingModelAlias); + } + + if (vectorDbType == VectorDatabaseTypeEnum.FAISS + && !vectorDbDetails.containsKey(FaissDatabaseEngine.ENABLE_HYBRID_SEARCH)) { + vectorDbDetails.put(FaissDatabaseEngine.ENABLE_HYBRID_SEARCH, true); + } + + if (!vectorDbDetails.containsKey(Constants.INDEX_CLASSES)) { + vectorDbDetails.put(Constants.INDEX_CLASSES, "default"); + } + + if (vectorDbType == VectorDatabaseTypeEnum.OPEN_SEARCH) { + if (vectorDbDetails.get(Constants.USERNAME) == null) { + throw new IllegalArgumentException(Constants.USERNAME + " is not provided."); + } + if (vectorDbDetails.get(Constants.PASSWORD) == null) { + throw new IllegalArgumentException(Constants.PASSWORD + " is not provided."); + } + if (vectorDbDetails.get(Constants.HOSTNAME) == null) { + throw new IllegalArgumentException(Constants.HOSTNAME + " is not provided."); + } + if (vectorDbDetails.get(OpenSearchRestVectorDatabaseEngine.INDEX_NAME) == null) { + throw new IllegalArgumentException(OpenSearchRestVectorDatabaseEngine.INDEX_NAME + " is not provided."); + } + } + if (vectorDbType == VectorDatabaseTypeEnum.WEAVIATE) { + if (vectorDbDetails.get(Constants.API_KEY) == null) { + throw new IllegalArgumentException(Constants.API_KEY + " is not provided."); + } + if (vectorDbDetails.get(Constants.HOSTNAME) == null) { + throw new IllegalArgumentException(Constants.HOSTNAME + " is not provided."); + } + } + + // vectorDbDetails.put(Constants.PIPELINE,"PIPELINE.json"); + + String vectorDbId = UUID.randomUUID().toString(); + File tempSmss = null; + File smssFile = null; + File specificEngineFolder = null; + IVectorDatabaseEngine vectorDb = null; + try { + // validate engine + UploadUtilities.validateEngine(IEngine.CATALOG_TYPE.VECTOR, user, vectorDbName, vectorDbId); + specificEngineFolder = UploadUtilities.generateSpecificEngineFolder(IEngine.CATALOG_TYPE.VECTOR, vectorDbId, + vectorDbName); + + String vectorDbClass = vectorDbType.getVectorDatabaseClass(); + vectorDb = (IVectorDatabaseEngine) Class.forName(vectorDbClass).getDeclaredConstructor().newInstance(); + tempSmss = UploadUtilities.createTemporaryVectorDatabaseSmss(vectorDbId, vectorDbName, vectorDbClass, + vectorDbDetails); + + // store in DIHelper so that when we move temp smss to smss it doesn't try to + // reload again + UploadUtilities.addEngineToDIHelperToIgnoreEngineWatchers(vectorDbId, tempSmss.getAbsolutePath()); + vectorDb.open(tempSmss.getAbsolutePath()); + + smssFile = new File(tempSmss.getAbsolutePath().replace(".temp", ".smss")); + FileUtils.copyFile(tempSmss, smssFile); + tempSmss.delete(); + vectorDb.setSmssFilePath(smssFile.getAbsolutePath()); + UploadUtilities.addEngineToDIHelper(vectorDbId, vectorDbName, vectorDb, smssFile); + SecurityEngineUtils.addEngine(vectorDbId, global, user); + CatalogDependencyDerivation.syncSmss(user, vectorDbId, IEngine.CATALOG_TYPE.VECTOR.name(), vectorDbDetails); + + List logins = user.getLogins(); + for (AuthProvider ap : logins) { + SecurityEngineUtils.addEngineOwner(vectorDbId, user.getAccessToken(ap).getId()); + } + + ClusterUtil.pushEngine(vectorDbId); + UserAuditTrailUtils.recordEngineLifecycle(user, AuditEventType.VECTOR_CREATE, AuditTargetType.VECTOR, + vectorDbId, vectorDbName, + Map.of("global", global, "vectorType", vectorDbType.getVectorDatabaseName())); + } catch (Exception e) { + classLogger.error("Failed to create vector database engine {} ({})", vectorDbName, vectorDbId, e); + UploadUtilities.cleanUpCreateNewError(vectorDb, vectorDbId, tempSmss, smssFile, specificEngineFolder); + return new NounMetadata(e.getMessage(), PixelDataType.CONST_STRING, PixelOperationType.ERROR); + } + + Map retMap = UploadUtilities.getEngineReturnData(this.insight.getUser(), vectorDbId); + NounMetadata retNoun = new NounMetadata(retMap, PixelDataType.UPLOAD_RETURN_MAP, + PixelOperationType.MARKET_PLACE_ADDITION); + if (warning != null) { + retNoun.addAdditionalReturn(warning); + } + return retNoun; + } + + /** + * + * @return + */ + private String getVectorDatabaseName() { + List strValues = getListStringForAliasedKey(CATALOG_NAME_KEYS); + if (!strValues.isEmpty()) { + return strValues.get(0).trim(); + } + + strValues = this.curRow.getAllStrValues(); + if (strValues != null && !strValues.isEmpty()) { + return strValues.get(0).trim(); + } + + throw new NullPointerException("Must define the name of the new vector database engine"); + } + + /** + * + * @return + */ + private Map getVectorDatabaseDetails() { + GenRowStruct grs = this.store.getGenRowStruct(ReactorKeysEnum.CONNECTION_DETAILS.getKey()); + if (grs != null && !grs.isEmpty()) { + List mapNouns = grs.getNounsOfType(PixelDataType.MAP); + if (mapNouns != null && !mapNouns.isEmpty()) { + return (Map) mapNouns.get(0).getValue(); + } + } + + List mapNouns = this.curRow.getNounsOfType(PixelDataType.MAP); + if (mapNouns != null && !mapNouns.isEmpty()) { + return (Map) mapNouns.get(0).getValue(); + } + + throw new NullPointerException("Must define the properties for the new vector database engine"); + } + +} diff --git a/src/prerna/util/AgentProjectArchiveUtils.java b/src/prerna/util/AgentProjectArchiveUtils.java index 9c764594529..d91e7a8dbbb 100644 --- a/src/prerna/util/AgentProjectArchiveUtils.java +++ b/src/prerna/util/AgentProjectArchiveUtils.java @@ -174,10 +174,21 @@ public static void importDependencies(File directory, String projectName, String boolean current = dependency.has("catalog_id"); row.put("catalog_id", string(dependency, current ? "catalog_id" : "engine_id", true)); row.put("catalog_type", string(dependency, current ? "catalog_type" : "engine_type", true)); + // the link, from exports that have it + for (String key : new String[] { "role", "dependency_name", "dependency_description" }) { + JsonElement value = dependency.get(key); + if (value != null && !value.isJsonNull()) { + row.put(key, value.getAsString()); + } + } + JsonElement automatic = dependency.get("is_automatic"); + if (automatic != null && !automatic.isJsonNull()) { + row.put("is_automatic", automatic.getAsBoolean()); + } rows.add(row); } } - SecurityCatalogDependencyUtils.setDependencies(user, projectId, IProject.PROJECT_TYPE.WORKSPACE.name(), + SecurityCatalogDependencyUtils.replaceAllDependencies(user, projectId, IProject.PROJECT_TYPE.WORKSPACE.name(), SecurityCatalogDependencyUtils.fromExported(rows)); Files.delete(file.toPath()); } diff --git a/src/prerna/util/EngineCloneUtility.java b/src/prerna/util/EngineCloneUtility.java index 42263613db5..933c88c4cd1 100644 --- a/src/prerna/util/EngineCloneUtility.java +++ b/src/prerna/util/EngineCloneUtility.java @@ -53,6 +53,7 @@ import jakarta.ws.rs.core.Response; import prerna.auth.AuthProvider; import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils; import prerna.auth.utils.SecurityEngineUtils; import prerna.auth.utils.SecurityModelMetadataUtils; import prerna.cluster.util.ClusterUtil; @@ -211,9 +212,34 @@ public static String cloneEngine(User user, String sourceEngineId, String cloneN cloneSmss, cloneImage, couchImageCopied); } } + copyDependencies(user, sourceEngineId, cloneId, engineType); return cloneId; } + /** + * Gives the clone the source's dependencies, each link as it is. The clone's + * configuration is a copy of the source's, so its automatic links are the same, + * and the manual ones a user picked come along. Like a recorded dependency + * elsewhere, a failure here never fails the clone: it is logged and left for + * the backfill. + * + * @param user the user who owns the clone + * @param sourceEngineId the engine cloned + * @param cloneId the clone + * @param engineType their type + */ + private static void copyDependencies(User user, String sourceEngineId, String cloneId, + IEngine.CATALOG_TYPE engineType) { + try { + SecurityCatalogDependencyUtils.replaceAllDependencies(user, cloneId, engineType.name(), + SecurityCatalogDependencyUtils + .fromExported(SecurityCatalogDependencyUtils.getDependencyDetails(sourceEngineId))); + } catch (RuntimeException e) { + classLogger.warn("Cloned engine {} into {} but could not copy its dependencies", + Utility.cleanLogString(sourceEngineId), cloneId, e); + } + } + /** * Copies the engine folder and smss file of the source. A source that holds * file locks is closed under its engine lock for the copy and opened again diff --git a/test/prerna/auth/utils/CatalogDependencyDerivationUnitTests.java b/test/prerna/auth/utils/CatalogDependencyDerivationUnitTests.java new file mode 100644 index 00000000000..133891508e1 --- /dev/null +++ b/test/prerna/auth/utils/CatalogDependencyDerivationUnitTests.java @@ -0,0 +1,154 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.auth.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; +import java.util.function.UnaryOperator; + +import org.junit.jupiter.api.Test; + +import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; + +/** + * Working out the automatic dependencies of catalog items from their saved + * configuration, without a security database. + */ +public class CatalogDependencyDerivationUnitTests { + + /** Every id names a model, except guardrails, vectors, storage and projects named so */ + private static final UnaryOperator TYPES = id -> switch (id) { + case "missing" -> null; + case "guard1", "guard2" -> "GUARDRAIL"; + case "kb1" -> "VECTOR"; + case "bucket1" -> "STORAGE"; + case "agent2" -> "WORKSPACE"; + case "skill1" -> "SKILL"; + case "app1" -> "CODE"; + default -> "MODEL"; + }; + + @Test + void guardrailPipelines_giveEachGuardrailOnceWithEveryPlaceItChecks() { + Map pipelines = Map.of("chat", + Map.of("input", List.of(check("guard1"), check("guard2")), "output", List.of(check("guard1")))); + + List dependencies = CatalogDependencyDerivation.fromGuardrailPipelines(pipelines, TYPES); + + assertEquals(2, dependencies.size()); + Dependency first = dependencies.stream().filter(d -> d.id().equals("guard1")).findFirst().orElseThrow(); + assertEquals(CatalogDependencyRole.GUARDRAIL, first.role()); + assertEquals("GUARDRAIL", first.type()); + assertTrue(first.description().contains("chat input")); + assertTrue(first.description().contains("chat output")); + assertTrue(CatalogDependencyDerivation.fromGuardrailPipelines(Map.of(), TYPES).isEmpty()); + } + + @Test + void smss_givesAGuardrailsJudgeAndVectorAndAVectorsEmbedder() { + List guardrail = CatalogDependencyDerivation.fromSmss("GUARDRAIL", + Map.of("MODEL_ENGINE_ID", " judge1 ", "VECTOR_ENGINE_ID", "kb1"), TYPES); + assertEquals(List.of(CatalogDependencyRole.JUDGE_MODEL, CatalogDependencyRole.TOPIC_VECTOR), + guardrail.stream().map(Dependency::role).toList()); + assertEquals("judge1", guardrail.get(0).id()); + + List vector = CatalogDependencyDerivation.fromSmss("VECTOR", + Map.of("EMBEDDER_ENGINE_ID", "embedder1"), TYPES); + assertEquals(CatalogDependencyRole.EMBEDDER, vector.get(0).role()); + + List function = CatalogDependencyDerivation.fromSmss("FUNCTION", + Map.of("GOOGLE_BUCKET_ENGINEID", "bucket1"), TYPES); + assertEquals("STORAGE", function.get(0).type()); + + // a key that names nothing, or a key of another engine type, is no dependency + assertTrue(CatalogDependencyDerivation.fromSmss("GUARDRAIL", Map.of("MODEL_ENGINE_ID", "missing"), TYPES) + .isEmpty()); + assertTrue(CatalogDependencyDerivation.fromSmss("MODEL", Map.of("EMBEDDER_ENGINE_ID", "embedder1"), TYPES) + .isEmpty()); + } + + @Test + void routerConfig_givesRoutesClassifierEmbeddingsAndFallbacks() { + String json = """ + {"mode":"llm","classifier_engine":"classifier1","embeddings_engine":"embed1", + "fallbacks":["fallback1"], + "routes":[{"name":"code","engine_id":"model1"},{"name":"math","engine_id":"model1"}, + {"name":"chat","engine_id":"model2"}]} + """; + + List dependencies = CatalogDependencyDerivation.fromRouterConfigJson(json, TYPES); + + assertEquals(5, dependencies.size()); + Dependency model1 = dependencies.get(0); + assertEquals(CatalogDependencyRole.ROUTE_MODEL, model1.role()); + assertTrue(model1.description().contains("'code', 'math' routes")); + assertTrue(dependencies.stream().anyMatch(d -> d.role() == CatalogDependencyRole.ROUTER_CLASSIFIER)); + assertTrue(dependencies.stream().anyMatch(d -> d.role() == CatalogDependencyRole.ROUTER_EMBEDDINGS)); + assertTrue(dependencies.stream().anyMatch(d -> d.role() == CatalogDependencyRole.ROUTER_FALLBACK)); + assertTrue(CatalogDependencyDerivation.fromRouterConfigJson("not json", TYPES).isEmpty()); + } + + @Test + void automationNodes_giveEachEngineAppAndAgentOnce() { + List> nodes = List.of( + Map.of("id", "n1", "label", "Summarize", "config", Map.of("engineId", "model1")), + Map.of("id", "n2", "label", "Classify", "config", Map.of("engineId", "model1")), + Map.of("id", "n3", "label", "Ask agent", "config", Map.of("workspaceId", "agent2", "engineId", "")), + Map.of("id", "n4", "config", Map.of("appId", "app1")), Map.of("id", "n5", "type", "start")); + + List dependencies = CatalogDependencyDerivation.fromAutomationNodes(nodes, TYPES); + + assertEquals(List.of("model1", "agent2", "app1"), dependencies.stream().map(Dependency::id).toList()); + assertTrue(dependencies.get(0).description().contains("'Summarize', 'Classify'")); + assertEquals("WORKSPACE", dependencies.get(1).type()); + assertTrue(dependencies.get(2).description().contains("'n4'")); + } + + @Test + void workspace_givesToolsKnowledgeSkillsModelAndSubagents() { + List> resources = List.of(Map.of("resource_id", "kb1", "resource_type", "ENGINE"), + Map.of("resource_id", "tool1", "resource_type", "ENGINE"), + Map.of("resource_id", "skill1", "resource_type", "SKILL"), + Map.of("resource_id", "prompt1", "resource_type", "PROMPT")); + + List dependencies = CatalogDependencyDerivation.fromWorkspace(resources, "model9", + List.of("agent2"), TYPES); + + assertEquals(List.of(CatalogDependencyRole.KNOWLEDGE, CatalogDependencyRole.TOOLBOX, CatalogDependencyRole.SKILL, + CatalogDependencyRole.AGENT_MODEL, CatalogDependencyRole.SUBAGENT), + dependencies.stream().map(Dependency::role).toList()); + assertTrue(dependencies.stream().allMatch(d -> Boolean.TRUE.equals(d.automatic()))); + } + + private static Map check(String guardrailId) { + return Map.of("reactorClass", "Guardrail", "params", Map.of("guardrailEngineId", guardrailId)); + } +} diff --git a/test/prerna/auth/utils/SecurityCatalogDependencyUtilsUnitTests.java b/test/prerna/auth/utils/SecurityCatalogDependencyUtilsUnitTests.java index 164929f3b84..493252b1534 100644 --- a/test/prerna/auth/utils/SecurityCatalogDependencyUtilsUnitTests.java +++ b/test/prerna/auth/utils/SecurityCatalogDependencyUtilsUnitTests.java @@ -1,3 +1,30 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ package prerna.auth.utils; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -81,7 +108,7 @@ void resolve_readsTheSpecificTypeWithoutLoadingAnything() { @Test void anEngineOwnsDependenciesOnEnginesAndProjects() { - SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + SecurityCatalogDependencyUtils.setManualDependencies(owner, "function1", "FUNCTION", List.of(new Dependency("model1", "MODEL"), new Dependency("skill1", "SKILL"))); List> details = SecurityCatalogDependencyUtils.getDependencyDetails("function1"); @@ -95,7 +122,8 @@ void anEngineOwnsDependenciesOnEnginesAndProjects() { @Test void aProjectOwnsDependenciesOnEnginesAndProjects() { - List failed = SecurityCatalogDependencyUtils.setDependencyIds(owner, "automation1", "AUTOMATION", + List failed = SecurityCatalogDependencyUtils.syncAutomaticDependencyIds(owner, "automation1", + "AUTOMATION", CatalogDependencyRole.AUTOMATION_NODE, "Used by the automation", List.of("database1", "notebook1", "missing")); assertEquals(List.of("missing"), failed); @@ -108,9 +136,9 @@ void aProjectOwnsDependenciesOnEnginesAndProjects() { @Test void setDependencies_replacesAndSkipsTheOwnerAndRepeats() { - SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + SecurityCatalogDependencyUtils.setManualDependencies(owner, "function1", "FUNCTION", List.of(new Dependency("model1", "MODEL"))); - SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + SecurityCatalogDependencyUtils.setManualDependencies(owner, "function1", "FUNCTION", List.of(new Dependency("database1", "DATABASE"), new Dependency("database1", "DATABASE"), new Dependency("function1", "FUNCTION"))); @@ -118,20 +146,177 @@ void setDependencies_replacesAndSkipsTheOwnerAndRepeats() { } @Test - void addDependencies_keepsTheOnesThere() { - SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + void addAutomaticDependencies_keepsTheOnesThere() { + SecurityCatalogDependencyUtils.addAutomaticDependencies(owner, "function1", "FUNCTION", + List.of(automatic("model1", "MODEL", CatalogDependencyRole.TOOLBOX))); + SecurityCatalogDependencyUtils.addAutomaticDependencies(owner, "function1", "FUNCTION", + List.of(automatic("model1", "MODEL", CatalogDependencyRole.TOOLBOX), + automatic("skill1", "SKILL", CatalogDependencyRole.SKILL))); + + assertEquals(2, SecurityCatalogDependencyUtils.getDependencyDetails("function1").size()); + } + + @Test + void manualAndAutomaticDependenciesAreSavedApart() { + SecurityCatalogDependencyUtils.setManualDependencies(owner, "automation1", "AUTOMATION", + List.of(Dependency.manual("database1", "DATABASE", "salesDb", "Sales numbers"))); + SecurityCatalogDependencyUtils.syncAutomaticDependencies(owner, "automation1", "AUTOMATION", + List.of(CatalogDependencyRole.AUTOMATION_NODE), + List.of(automatic("model1", "MODEL", CatalogDependencyRole.AUTOMATION_NODE))); + + // saving the automation again keeps the picked one + SecurityCatalogDependencyUtils.syncAutomaticDependencies(owner, "automation1", "AUTOMATION", + List.of(CatalogDependencyRole.AUTOMATION_NODE), + List.of(automatic("function1", "FUNCTION", CatalogDependencyRole.AUTOMATION_NODE))); + Map> byId = byCatalogId( + SecurityCatalogDependencyUtils.getDependencyDetails("automation1")); + assertEquals(java.util.Set.of("database1", "function1"), byId.keySet()); + assertEquals(false, byId.get("database1").get("is_automatic")); + assertEquals("MANUAL", byId.get("database1").get("role")); + assertEquals("salesDb", byId.get("database1").get("dependency_name")); + assertEquals("Sales numbers", byId.get("database1").get("dependency_description")); + assertEquals(true, byId.get("function1").get("is_automatic")); + assertEquals("AUTOMATION_NODE", byId.get("function1").get("role")); + assertNull(byId.get("function1").get("dependency_name")); + + // and setting the picked ones keeps the automatic one + SecurityCatalogDependencyUtils.setManualDependencies(owner, "automation1", "AUTOMATION", List.of()); + assertEquals(List.of("function1"), ids(SecurityCatalogDependencyUtils.getDependencies("automation1"))); + } + + @Test + void syncAutomaticDependencies_replacesOnlyItsOwnRoles() { + UnitTestSecurityAuthUtils.createEngine("guardrail1", "Guardrail", IEngine.CATALOG_TYPE.GUARDRAIL, owner); + SecurityCatalogDependencyUtils.syncAutomaticDependencies(owner, "model1", "MODEL", + List.of(CatalogDependencyRole.GUARDRAIL), + List.of(automatic("guardrail1", "GUARDRAIL", CatalogDependencyRole.GUARDRAIL))); + SecurityCatalogDependencyUtils.syncAutomaticDependencies(owner, "model1", "MODEL", + CatalogDependencyDerivation.ROUTER_ROLES, + List.of(automatic("function1", "FUNCTION", CatalogDependencyRole.ROUTE_MODEL))); + + assertEquals(java.util.Set.of("guardrail1", "function1"), + new java.util.HashSet<>(ids(SecurityCatalogDependencyUtils.getDependencies("model1")))); + assertThrows(IllegalArgumentException.class, + () -> SecurityCatalogDependencyUtils.syncAutomaticDependencies(owner, "model1", "MODEL", + List.of(CatalogDependencyRole.GUARDRAIL), + List.of(automatic("function1", "FUNCTION", CatalogDependencyRole.ROUTE_MODEL)))); + } + + @Test + void aDependencyWithTwoRolesIsTwoLinksAndOneDependency() { + SecurityCatalogDependencyUtils.syncAutomaticDependencies(owner, "model1", "MODEL", + CatalogDependencyDerivation.ROUTER_ROLES, + List.of(automatic("function1", "FUNCTION", CatalogDependencyRole.ROUTE_MODEL), + automatic("function1", "FUNCTION", CatalogDependencyRole.ROUTER_FALLBACK))); + + assertEquals(2, SecurityCatalogDependencyUtils.getDependencyDetails("model1").size()); + assertEquals(List.of("function1"), ids(SecurityCatalogDependencyUtils.getDependencies("model1"))); + } + + @Test + void anAutomaticDependencyReplacesARowFromBeforeTheColumn() throws Exception { + prerna.util.QueryExecutionUtility.executeUpdate(securityDb, + "INSERT INTO CATALOGDEPENDENCIES (CATALOGID, CATALOGTYPE, DEPENDENCYID, DEPENDENCYTYPE) " + + "VALUES ('automation1', 'AUTOMATION', 'model1', 'MODEL')", + prerna.util.QueryExecutionUtility.NO_PARAMETERS); + Map legacy = SecurityCatalogDependencyUtils.getDependencyDetails("automation1").get(0); + assertEquals(false, legacy.get("is_automatic")); + assertEquals("MANUAL", legacy.get("role")); + + SecurityCatalogDependencyUtils.syncAutomaticDependencies(owner, "automation1", "AUTOMATION", + List.of(CatalogDependencyRole.AUTOMATION_NODE), + List.of(automatic("model1", "MODEL", CatalogDependencyRole.AUTOMATION_NODE))); + + List> rows = SecurityCatalogDependencyUtils.getDependencyDetails("automation1"); + assertEquals(1, rows.size()); + assertEquals(true, rows.get(0).get("is_automatic")); + } + + @Test + void setManualDependencies_rejectsTwoWithOneName() { + assertThrows(IllegalArgumentException.class, + () -> SecurityCatalogDependencyUtils.setManualDependencies(owner, "automation1", "AUTOMATION", + List.of(Dependency.manual("model1", "MODEL", "llm", null), + Dependency.manual("database1", "DATABASE", "LLM", null)))); + assertTrue(SecurityCatalogDependencyUtils.getDependencies("automation1").isEmpty()); + } + + @Test + void removeAutomaticDependency_keepsAPickedOneOnTheSameItem() { + SecurityCatalogDependencyUtils.setManualDependencies(owner, "automation1", "AUTOMATION", + List.of(new Dependency("skill1", "SKILL"))); + SecurityCatalogDependencyUtils.addAutomaticDependencies(owner, "automation1", "AUTOMATION", + List.of(automatic("skill1", "SKILL", CatalogDependencyRole.SKILL))); + + SecurityCatalogDependencyUtils.removeAutomaticDependency("automation1", "skill1", CatalogDependencyRole.SKILL); + + List> rows = SecurityCatalogDependencyUtils.getDependencyDetails("automation1"); + assertEquals(1, rows.size()); + assertEquals("MANUAL", rows.get(0).get("role")); + } + + @Test + void getDependents_listsWhoDependsOnAnItem() { + SecurityCatalogDependencyUtils.syncAutomaticDependencies(owner, "automation1", "AUTOMATION", + List.of(CatalogDependencyRole.AUTOMATION_NODE), + List.of(automatic("function1", "FUNCTION", CatalogDependencyRole.AUTOMATION_NODE))); + SecurityCatalogDependencyUtils.setManualDependencies(owner, "function1", "FUNCTION", List.of(new Dependency("model1", "MODEL"))); - SecurityCatalogDependencyUtils.addDependencies(owner, "function1", "FUNCTION", - List.of(new Dependency("model1", "MODEL"), new Dependency("skill1", "SKILL"))); - assertEquals(2, SecurityCatalogDependencyUtils.getDependencies("function1").size()); + List> direct = SecurityCatalogDependencyUtils.getDependents("model1", false); + assertEquals(List.of("function1"), ids(direct)); + List> all = SecurityCatalogDependencyUtils.getDependents("model1", true); + assertEquals(List.of("function1", "automation1"), ids(all)); + assertEquals("AUTOMATION_NODE", all.get(1).get("role")); + assertEquals("Automation", all.get(1).get("catalog_name")); + } + + @Test + void exportsKeepTheLink() { + SecurityCatalogDependencyUtils.setManualDependencies(owner, "automation1", "AUTOMATION", + List.of(Dependency.manual("database1", "DATABASE", "salesDb", "Sales numbers"))); + SecurityCatalogDependencyUtils.addAutomaticDependencies(owner, "automation1", "AUTOMATION", + List.of(automatic("model1", "MODEL", CatalogDependencyRole.AUTOMATION_NODE))); + + List exported = SecurityCatalogDependencyUtils + .fromExported(SecurityCatalogDependencyUtils.getDependencyDetails("automation1")); + + assertTrue(exported.contains(Dependency.manual("database1", "DATABASE", "salesDb", "Sales numbers"))); + assertTrue(exported.contains(automatic("model1", "MODEL", CatalogDependencyRole.AUTOMATION_NODE))); + } + + @Test + void aCloneGetsTheSourcesLinksAsTheyAre() { + // as EngineCloneUtility copies them: every link, automatic and picked + UnitTestSecurityAuthUtils.createEngine("guardrail1", "Guardrail", IEngine.CATALOG_TYPE.GUARDRAIL, owner); + UnitTestSecurityAuthUtils.createEngine("guardrail2", "Guardrail Copy", IEngine.CATALOG_TYPE.GUARDRAIL, owner); + SecurityCatalogDependencyUtils.syncAutomaticDependencies(owner, "guardrail1", "GUARDRAIL", + CatalogDependencyDerivation.SMSS_ROLES, + List.of(automatic("model1", "MODEL", CatalogDependencyRole.JUDGE_MODEL))); + SecurityCatalogDependencyUtils.setManualDependencies(owner, "guardrail1", "GUARDRAIL", + List.of(Dependency.manual("database1", "DATABASE", "policies", "Policy tables"))); + + SecurityCatalogDependencyUtils.replaceAllDependencies(owner, "guardrail2", "GUARDRAIL", + SecurityCatalogDependencyUtils + .fromExported(SecurityCatalogDependencyUtils.getDependencyDetails("guardrail1"))); + + Map> byId = byCatalogId( + SecurityCatalogDependencyUtils.getDependencyDetails("guardrail2")); + assertEquals(java.util.Set.of("model1", "database1"), byId.keySet()); + assertEquals("JUDGE_MODEL", byId.get("model1").get("role")); + assertEquals(true, byId.get("model1").get("is_automatic")); + assertEquals("MANUAL", byId.get("database1").get("role")); + assertEquals("policies", byId.get("database1").get("dependency_name")); + assertEquals("Policy tables", byId.get("database1").get("dependency_description")); + // the source keeps its own + assertEquals(2, SecurityCatalogDependencyUtils.getDependencyDetails("guardrail1").size()); } @Test void getDependencies_followsEnginesAndProjectsAndEndsOnACycle() { - SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + SecurityCatalogDependencyUtils.setManualDependencies(owner, "function1", "FUNCTION", List.of(new Dependency("skill1", "SKILL"))); - SecurityCatalogDependencyUtils.setDependencies(owner, "skill1", "SKILL", + SecurityCatalogDependencyUtils.setManualDependencies(owner, "skill1", "SKILL", List.of(new Dependency("model1", "MODEL"), new Dependency("function1", "FUNCTION"))); List> all = SecurityCatalogDependencyUtils.getDependencies("function1", true); @@ -146,7 +331,7 @@ void getDependencies_followsEnginesAndProjectsAndEndsOnACycle() { void validateDependencies_checksEachWithItsOwnPermissions() { User reader = UnitTestSecurityAuthUtils.createUser("reader", false); UnitTestSecurityAuthUtils.addPermissionsToUserForEngine(owner, "readerid", "model1", "READ_ONLY"); - SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + SecurityCatalogDependencyUtils.setManualDependencies(owner, "function1", "FUNCTION", List.of(new Dependency("model1", "MODEL"), new Dependency("skill1", "SKILL"))); Map canView = SecurityCatalogDependencyUtils.validateDependencies(reader, "function1"); @@ -181,9 +366,9 @@ void resolveCatalogType_checksAGivenTypeAgainstTheSecurityDatabase() { @Test void deletingAnEngineRemovesTheDependenciesItOwned() { - SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + SecurityCatalogDependencyUtils.setManualDependencies(owner, "function1", "FUNCTION", List.of(new Dependency("model1", "MODEL"))); - SecurityCatalogDependencyUtils.setDependencies(owner, "skill1", "SKILL", + SecurityCatalogDependencyUtils.setManualDependencies(owner, "skill1", "SKILL", List.of(new Dependency("function1", "FUNCTION"))); SecurityEngineUtils.deleteEngine("function1"); @@ -207,7 +392,7 @@ void fromExported_readsOldAndNewExports() { @Test void changingAProjectsTypeUpdatesItsDependencyRows() { - SecurityCatalogDependencyUtils.setDependencies(owner, "function1", "FUNCTION", + SecurityCatalogDependencyUtils.setManualDependencies(owner, "function1", "FUNCTION", List.of(new Dependency("notebook1", "NOTEBOOK"))); SecurityProjectUtils.updateProject("notebook1", "Notebook", "CODE", null, false); @@ -215,6 +400,10 @@ void changingAProjectsTypeUpdatesItsDependencyRows() { assertEquals("CODE", SecurityCatalogDependencyUtils.getDependencies("function1").get(0).get("catalog_type")); } + private static Dependency automatic(String id, String type, CatalogDependencyRole role) { + return Dependency.automatic(id, type, role, "Derived for the test"); + } + private static Map> byCatalogId(List> rows) { Map> byId = new HashMap<>(); for (Map row : rows) { diff --git a/test/prerna/auth/utils/SecurityProjectUtilsUnitTests.java b/test/prerna/auth/utils/SecurityProjectUtilsUnitTests.java index d20b63446e0..d8b5ab0f9e9 100644 --- a/test/prerna/auth/utils/SecurityProjectUtilsUnitTests.java +++ b/test/prerna/auth/utils/SecurityProjectUtilsUnitTests.java @@ -1931,7 +1931,7 @@ void testPropagateProjectPermission_letsAnAdminGrantAnAdminOnlyDependency() { private static Map propagateToAModelWhoseAddsAreAdminOnly(User requester) { UnitTestSecurityAuthUtils.createProject("testProjectId", "testProjectName", requester); UnitTestSecurityAuthUtils.createEngine("model1", "Model One", IEngine.CATALOG_TYPE.MODEL, requester); - SecurityCatalogDependencyUtils.setDependencies(requester, "testProjectId", "INSIGHTS", + SecurityCatalogDependencyUtils.setManualDependencies(requester, "testProjectId", "INSIGHTS", List.of(new SecurityCatalogDependencyUtils.Dependency("model1", IEngine.CATALOG_TYPE.MODEL.name()))); boolean adminOnlyBefore = AbstractSecurityUtils.adminOnlyModelAddAccess; AbstractSecurityUtils.adminOnlyModelAddAccess = true; diff --git a/test/prerna/collaboration/BrainTopicVotesUnitTests.java b/test/prerna/collaboration/BrainTopicVotesUnitTests.java index d7e85defdc7..6f2be05b89a 100644 --- a/test/prerna/collaboration/BrainTopicVotesUnitTests.java +++ b/test/prerna/collaboration/BrainTopicVotesUnitTests.java @@ -1,3 +1,30 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ package prerna.collaboration; import static org.junit.jupiter.api.Assertions.assertEquals; diff --git a/test/prerna/util/AgentProjectArchiveUtilsUnitTests.java b/test/prerna/util/AgentProjectArchiveUtilsUnitTests.java index 0fcb12f6811..df6ac8705c0 100644 --- a/test/prerna/util/AgentProjectArchiveUtilsUnitTests.java +++ b/test/prerna/util/AgentProjectArchiveUtilsUnitTests.java @@ -290,18 +290,21 @@ void restoresDependenciesWithTheirTypesIncludingPlatformSkills() throws Exceptio Files.writeString(file, """ [{"engine_id":"python","engine_type":"PROJECT"}, {"engine_id":"tool","engine_type":"FUNCTION"}] """); + // built before the static mock, whose verify would count the record's own calls + List expected = List.of( + new SecurityCatalogDependencyUtils.Dependency("python", "SKILL"), + new SecurityCatalogDependencyUtils.Dependency("tool", "FUNCTION")); try (var types = mockStatic(CatalogTypes.class, Mockito.CALLS_REAL_METHODS); var dependencies = mockStatic(SecurityCatalogDependencyUtils.class, Mockito.CALLS_REAL_METHODS)) { // the platform skill is in the security database; the tool is not, so its // exported type is kept types.when(() -> CatalogTypes.resolve("python")).thenReturn("SKILL"); types.when(() -> CatalogTypes.resolve("tool")).thenReturn(null); - dependencies.when(() -> SecurityCatalogDependencyUtils.setDependencies(any(), any(), any(), any())) + dependencies.when(() -> SecurityCatalogDependencyUtils.replaceAllDependencies(any(), any(), any(), any())) .thenAnswer(invocation -> null); AgentProjectArchiveUtils.importDependencies(directory.toFile(), NAME, ID, user); - dependencies.verify(() -> SecurityCatalogDependencyUtils.setDependencies(user, ID, "WORKSPACE", - List.of(new SecurityCatalogDependencyUtils.Dependency("python", "SKILL"), - new SecurityCatalogDependencyUtils.Dependency("tool", "FUNCTION")))); + dependencies.verify(() -> SecurityCatalogDependencyUtils.replaceAllDependencies(user, ID, "WORKSPACE", + expected)); } assertFalse(Files.exists(file)); } From 208ef442a6f105891d35724d1d20fa7393551077 Mon Sep 17 00:00:00 2001 From: Neel Date: Thu, 19 Nov 2026 19:32:33 -0500 Subject: [PATCH 3/6] feat: dependency graph --- .../utils/CatalogDependencyGraphLayout.java | 627 ++++++++++++++++++ src/prerna/auth/utils/SecurityAdminUtils.java | 163 ++++- .../AdminGetUserCatalogAccessReactor.java | 83 +++ .../definition/SaveAutomationReactor.java | 2 - .../project/AutomationProjectService.java | 17 +- .../util/GenerateMetamodelLayout.java | 2 +- ...AdminGetCatalogDependencyGraphReactor.java | 450 +++++++++++++ .../AdminCatalogDependencyMapUnitTests.java | 265 ++++++++ ...CatalogDependencyGraphLayoutUnitTests.java | 340 ++++++++++ .../AutomationProjectServiceUnitTests.java | 110 +++ 10 files changed, 2044 insertions(+), 15 deletions(-) create mode 100644 src/prerna/auth/utils/CatalogDependencyGraphLayout.java create mode 100644 src/prerna/auth/utils/reactors/admin/AdminGetUserCatalogAccessReactor.java create mode 100644 src/prerna/reactor/security/AdminGetCatalogDependencyGraphReactor.java create mode 100644 test/prerna/auth/utils/AdminCatalogDependencyMapUnitTests.java create mode 100644 test/prerna/auth/utils/CatalogDependencyGraphLayoutUnitTests.java diff --git a/src/prerna/auth/utils/CatalogDependencyGraphLayout.java b/src/prerna/auth/utils/CatalogDependencyGraphLayout.java new file mode 100644 index 00000000000..c41f4293fcd --- /dev/null +++ b/src/prerna/auth/utils/CatalogDependencyGraphLayout.java @@ -0,0 +1,627 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.auth.utils; + +import java.awt.geom.Rectangle2D; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Random; +import java.util.Set; +import java.util.TreeMap; + +import org.graphstream.algorithm.ConnectedComponents; +import org.graphstream.algorithm.ConnectedComponents.ConnectedComponent; +import org.graphstream.algorithm.TarjanStronglyConnectedComponents; +import org.graphstream.algorithm.Toolkit; +import org.graphstream.graph.Graph; +import org.graphstream.graph.Node; +import org.graphstream.graph.implementations.MultiGraph; +import org.graphstream.ui.layout.Layout; +import org.graphstream.ui.layout.springbox.implementations.SpringBox; + +import prerna.reactor.masterdatabase.util.GenerateMetamodelLayout; +import prerna.reactor.masterdatabase.util.Rectangles; + +/** + * Lays out the catalog dependency graph for the admin dependency map: a position + * in pixels for every engine and project, which weakly connected component each + * belongs to, and which links are part of a cycle. Pure: it reads no database, + * and the same nodes and links always give the same result, whatever order they + * come in, as long as the force layout settles within its step and time limits. + * + *

+ * Each component of two or more nodes is laid out on its own with a seeded + * SpringBox, scaled to pixels and separated so no two boxes overlap. The + * components are then shelf packed, largest first, to roughly a 16:9 area, and + * the nodes without any link follow below as one block, grouped by type. + */ +public final class CatalogDependencyGraphLayout { + + /** The width of a node's box, in pixels */ + public static final double NODE_WIDTH = 240; + /** The height of a node's box, in pixels */ + public static final double NODE_HEIGHT = 64; + /** The space kept between the boxes of one component */ + static final double NODE_GAP = 40; + /** The space kept between two components, and before the isolated block */ + static final double COMPONENT_GAP = 200; + /** Pixels per SpringBox unit across */ + static final double SCALE_X = 320; + /** Pixels per SpringBox unit down */ + static final double SCALE_Y = 160; + /** The width to height ratio the packing aims for */ + static final double ASPECT = 16.0 / 9.0; + /** + * Above this many nodes a component is snapped to a grid rather than separated + * with {@link Rectangles}, which compares every pair + */ + public static final int DEFAULT_GRID_THRESHOLD = 2_500; + + private static final double CELL_WIDTH = NODE_WIDTH + NODE_GAP; + private static final double CELL_HEIGHT = NODE_HEIGHT + NODE_GAP; + + private CatalogDependencyGraphLayout() { + + } + + /** A node to place: its id, its type to group isolated nodes by, and its name */ + public record LayoutNode(String id, String type, String name) { + } + + /** A link from the item that depends (source) to what it depends on (target) */ + public record LayoutEdge(String id, String source, String target) { + } + + /** A node's top left corner, in pixels */ + public record Position(double x, double y) { + } + + /** Which way to follow the links from a node */ + public enum Direction { + /** What it depends on, and what those depend on */ + DEPENDENCIES, + /** What depends on it, and what depends on those */ + DEPENDENTS, + /** Both */ + BOTH; + + /** + * @param value the direction, in any case; null or blank for BOTH + * @return the direction + * @throws IllegalArgumentException when it is none of them + */ + public static Direction parse(String value) { + if (value == null || value.isBlank()) { + return BOTH; + } + try { + return valueOf(value.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException( + "Unknown direction '" + value + "'. Use DEPENDENCIES, DEPENDENTS or BOTH"); + } + } + } + + /** The laid out graph */ + public static final class Result { + private final Map positions; + private final Map components; + private final Set inCycleEdges; + private final int cycles; + private final int componentCount; + private final int isolatedCount; + private final double width; + private final double height; + + Result(Map positions, Map components, Set inCycleEdges, + int cycles, int componentCount, int isolatedCount, double width, double height) { + this.positions = Collections.unmodifiableMap(positions); + this.components = Collections.unmodifiableMap(components); + this.inCycleEdges = Collections.unmodifiableSet(inCycleEdges); + this.cycles = cycles; + this.componentCount = componentCount; + this.isolatedCount = isolatedCount; + this.width = width; + this.height = height; + } + + /** Each node's top left corner, by id */ + public Map positions() { + return positions; + } + + /** + * Each node's component, by id: 0 for the largest, in the order they are + * packed, and -1 for a node without any link + */ + public Map components() { + return components; + } + + /** The ids of the links that are part of a cycle, a link to itself included */ + public Set inCycleEdges() { + return inCycleEdges; + } + + /** + * How many cycles there are: each set of two or more nodes that all reach + * each other, and each node that links to itself outside such a set + */ + public int cycles() { + return cycles; + } + + /** How many components have at least one link */ + public int componentCount() { + return componentCount; + } + + /** How many nodes have no link */ + public int isolatedCount() { + return isolatedCount; + } + + /** The width of the whole layout, in pixels */ + public double width() { + return width; + } + + /** The height of the whole layout, in pixels */ + public double height() { + return height; + } + } + + /** + * Lays out a graph, snapping components above + * {@value #DEFAULT_GRID_THRESHOLD} nodes to a grid + * + * @param nodes the nodes; a repeated id is kept once + * @param edges the links; a repeated id is kept once, and one whose ends are + * not both nodes is left out + * @return the layout + */ + public static Result layout(Collection nodes, Collection edges) { + return layout(nodes, edges, DEFAULT_GRID_THRESHOLD); + } + + /** + * Lays out a graph + * + * @param nodes the nodes; a repeated id is kept once + * @param edges the links; a repeated id is kept once, and one whose + * ends are not both nodes is left out + * @param gridThreshold above this many nodes a component is snapped to a grid + * @return the layout + */ + static Result layout(Collection nodes, Collection edges, int gridThreshold) { + // sorted so the graph is built the same way whatever order they came in + TreeMap byId = new TreeMap<>(); + for (LayoutNode node : nodes) { + byId.putIfAbsent(node.id(), node); + } + TreeMap edgesById = new TreeMap<>(); + for (LayoutEdge edge : edges) { + if (byId.containsKey(edge.source()) && byId.containsKey(edge.target())) { + edgesById.putIfAbsent(edge.id(), edge); + } + } + + Graph graph = new MultiGraph("catalog-dependencies"); + for (String id : byId.keySet()) { + graph.addNode(id); + } + for (LayoutEdge edge : edgesById.values()) { + graph.addEdge(edge.id(), edge.source(), edge.target(), true); + } + + // cycles + TarjanStronglyConnectedComponents tarjan = new TarjanStronglyConnectedComponents(); + tarjan.init(graph); + tarjan.compute(); + Map sccOf = new HashMap<>(); + Map sccSize = new HashMap<>(); + for (String id : byId.keySet()) { + Object scc = graph.getNode(id).getAttribute(tarjan.getSCCIndexAttribute()); + sccOf.put(id, scc); + sccSize.merge(scc, 1, Integer::sum); + } + Set inCycle = new LinkedHashSet<>(); + Set cyclicSccs = new HashSet<>(); + Set selfLoopNodes = new HashSet<>(); + for (LayoutEdge edge : edgesById.values()) { + if (edge.source().equals(edge.target())) { + inCycle.add(edge.id()); + selfLoopNodes.add(edge.source()); + continue; + } + Object scc = sccOf.get(edge.source()); + if (scc != null && scc.equals(sccOf.get(edge.target())) && sccSize.get(scc) > 1) { + inCycle.add(edge.id()); + cyclicSccs.add(scc); + } + } + int cycles = cyclicSccs.size(); + for (String id : selfLoopNodes) { + if (sccSize.get(sccOf.get(id)) <= 1) { + cycles++; + } + } + + // components, by the links in either direction + Set linked = new HashSet<>(); + for (LayoutEdge edge : edgesById.values()) { + linked.add(edge.source()); + linked.add(edge.target()); + } + ConnectedComponents connected = new ConnectedComponents(graph); + connected.compute(); + List> components = new ArrayList<>(); + for (ConnectedComponent component : connected) { + List ids = new ArrayList<>(); + for (Node node : component.getNodeSet()) { + ids.add(node.getId()); + } + if (ids.size() == 1 && !linked.contains(ids.get(0))) { + continue; + } + Collections.sort(ids); + components.add(ids); + } + connected.terminate(); + components.sort(Comparator.comparingInt((List ids) -> -ids.size()).thenComparing(ids -> ids.get(0))); + + List> placedComponents = new ArrayList<>(); + for (List ids : components) { + placedComponents.add(layoutComponent(ids, edgesById.values(), gridThreshold)); + } + + Map positions = new LinkedHashMap<>(); + Map componentOf = new LinkedHashMap<>(); + + // shelf pack the components, largest first + double totalArea = 0; + double widest = 0; + List sizes = new ArrayList<>(); + for (Map placed : placedComponents) { + double[] size = extent(placed); + sizes.add(size); + totalArea += (size[0] + COMPONENT_GAP) * (size[1] + COMPONENT_GAP); + widest = Math.max(widest, size[0]); + } + double targetWidth = Math.max(widest, Math.sqrt(totalArea * ASPECT)); + double x = 0; + double y = 0; + double shelfHeight = 0; + double packedWidth = 0; + for (int i = 0; i < placedComponents.size(); i++) { + double[] size = sizes.get(i); + if (x > 0 && x + size[0] > targetWidth) { + y += shelfHeight + COMPONENT_GAP; + x = 0; + shelfHeight = 0; + } + for (Map.Entry entry : placedComponents.get(i).entrySet()) { + positions.put(entry.getKey(), new Position(x + entry.getValue().x(), y + entry.getValue().y())); + componentOf.put(entry.getKey(), i); + } + packedWidth = Math.max(packedWidth, x + size[0]); + x += size[0] + COMPONENT_GAP; + shelfHeight = Math.max(shelfHeight, size[1]); + } + double packedBottom = placedComponents.isEmpty() ? 0 : y + shelfHeight; + + // the nodes without links, as one block grouped by type + List isolated = new ArrayList<>(); + for (LayoutNode node : byId.values()) { + if (!linked.contains(node.id())) { + isolated.add(node); + } + } + isolated.sort(Comparator.comparing((LayoutNode node) -> Objects.toString(node.type(), "")) + .thenComparing(node -> node.name() == null ? node.id() : node.name(), String.CASE_INSENSITIVE_ORDER) + .thenComparing(LayoutNode::id)); + if (!isolated.isEmpty()) { + double blockWidth = placedComponents.isEmpty() + ? Math.sqrt(isolated.size() * CELL_WIDTH * CELL_HEIGHT * ASPECT) + : Math.max(packedWidth, CELL_WIDTH); + int columns = Math.max(1, (int) Math.floor((blockWidth + NODE_GAP) / CELL_WIDTH)); + double top = placedComponents.isEmpty() ? 0 : packedBottom + COMPONENT_GAP; + int row = 0; + int column = 0; + String type = null; + boolean first = true; + for (LayoutNode node : isolated) { + String nodeType = Objects.toString(node.type(), ""); + // each type starts its own row + if (!first && (column >= columns || !nodeType.equals(type))) { + row++; + column = 0; + } + first = false; + type = nodeType; + positions.put(node.id(), new Position(column * CELL_WIDTH, top + row * CELL_HEIGHT)); + componentOf.put(node.id(), -1); + column++; + } + } + + // normalized so the top left is 0, 0 + double minX = Double.POSITIVE_INFINITY; + double minY = Double.POSITIVE_INFINITY; + for (Position position : positions.values()) { + minX = Math.min(minX, position.x()); + minY = Math.min(minY, position.y()); + } + double width = 0; + double height = 0; + if (!positions.isEmpty()) { + for (Map.Entry entry : positions.entrySet()) { + Position moved = new Position(entry.getValue().x() - minX, entry.getValue().y() - minY); + entry.setValue(moved); + width = Math.max(width, moved.x() + NODE_WIDTH); + height = Math.max(height, moved.y() + NODE_HEIGHT); + } + } + graph.clear(); + return new Result(positions, componentOf, inCycle, cycles, components.size(), isolated.size(), width, + height); + } + + /** + * Lays out one component with a seeded SpringBox and separates its boxes + * + * @return each node's top left corner, with the component's top left at 0, 0 + */ + private static Map layoutComponent(List ids, Collection allEdges, + int gridThreshold) { + Map placed = new LinkedHashMap<>(); + if (ids.size() == 1) { + placed.put(ids.get(0), new Position(0, 0)); + return placed; + } + Set members = new HashSet<>(ids); + Graph graph = new MultiGraph("component"); + Layout layout = new SpringBox(false, new Random(seedOf(ids))); + graph.addSink(layout); + layout.addAttributeSink(graph); + for (String id : ids) { + graph.addNode(id); + } + for (LayoutEdge edge : allEdges) { + if (!edge.source().equals(edge.target()) && members.contains(edge.source())) { + graph.addEdge(edge.id(), edge.source(), edge.target()); + } + } + GenerateMetamodelLayout.computeLayout(layout); + + Map scaled = new LinkedHashMap<>(); + for (String id : ids) { + double[] position = Toolkit.nodePosition(graph.getNode(id)); + // SpringBox's y grows upwards, the page's downwards + scaled.put(id, new double[] { position[0] * SCALE_X, -position[1] * SCALE_Y }); + } + graph.removeSink(layout); + layout.removeAttributeSink(graph); + graph.clear(); + + if (ids.size() > gridThreshold) { + placed.putAll(snapToGrid(scaled)); + } else { + Map rectangles = new LinkedHashMap<>(); + for (Map.Entry entry : scaled.entrySet()) { + rectangles.put(entry.getKey(), new Rectangle2D.Double(entry.getValue()[0], entry.getValue()[1], + CELL_WIDTH, CELL_HEIGHT)); + } + Map fixed = new Rectangles().fix(rectangles); + for (String id : ids) { + Rectangle2D rectangle = fixed.get(id); + placed.put(id, new Position(rectangle.getX(), rectangle.getY())); + } + } + return normalize(placed); + } + + /** + * Snaps each node to the nearest cell of a grid of node sized cells, moving one + * whose cell is taken to the nearest free one. Nodes are placed from the top + * left, so the result does not depend on the map's order. + */ + static Map snapToGrid(Map scaled) { + List> order = new ArrayList<>(scaled.entrySet()); + order.sort(Comparator.comparingDouble((Map.Entry entry) -> entry.getValue()[1]) + .thenComparingDouble(entry -> entry.getValue()[0]).thenComparing(Map.Entry::getKey)); + Set taken = new HashSet<>(); + Map placed = new LinkedHashMap<>(); + for (Map.Entry entry : order) { + double column = entry.getValue()[0] / CELL_WIDTH; + double row = entry.getValue()[1] / CELL_HEIGHT; + long baseColumn = Math.round(column); + long baseRow = Math.round(row); + long[] cell = null; + if (taken.add(cellKey(baseRow, baseColumn))) { + cell = new long[] { baseRow, baseColumn }; + } + for (int ring = 1; cell == null; ring++) { + double best = Double.POSITIVE_INFINITY; + for (int dr = -ring; dr <= ring; dr++) { + for (int dc = -ring; dc <= ring; dc++) { + if (Math.max(Math.abs(dr), Math.abs(dc)) != ring) { + continue; + } + long r = baseRow + dr; + long c = baseColumn + dc; + if (taken.contains(cellKey(r, c))) { + continue; + } + double distance = (r - row) * (r - row) + (c - column) * (c - column); + if (distance < best) { + best = distance; + cell = new long[] { r, c }; + } + } + } + if (cell != null) { + taken.add(cellKey(cell[0], cell[1])); + } + } + placed.put(entry.getKey(), new Position(cell[1] * CELL_WIDTH, cell[0] * CELL_HEIGHT)); + } + return placed; + } + + private static long cellKey(long row, long column) { + return (row << 32) ^ (column & 0xffffffffL); + } + + private static Map normalize(Map placed) { + double minX = Double.POSITIVE_INFINITY; + double minY = Double.POSITIVE_INFINITY; + for (Position position : placed.values()) { + minX = Math.min(minX, position.x()); + minY = Math.min(minY, position.y()); + } + Map normalized = new LinkedHashMap<>(); + for (Map.Entry entry : placed.entrySet()) { + normalized.put(entry.getKey(), + new Position(entry.getValue().x() - minX, entry.getValue().y() - minY)); + } + return normalized; + } + + /** The width and height of a component's boxes, from 0, 0 */ + private static double[] extent(Map placed) { + double width = 0; + double height = 0; + for (Position position : placed.values()) { + width = Math.max(width, position.x() + NODE_WIDTH); + height = Math.max(height, position.y() + NODE_HEIGHT); + } + return new double[] { width, height }; + } + + /** A seed from a component's sorted ids (64 bit FNV-1a), the same on every run */ + static long seedOf(List sortedIds) { + long hash = 0xcbf29ce484222325L; + for (String id : sortedIds) { + for (byte b : id.getBytes(StandardCharsets.UTF_8)) { + hash ^= b & 0xff; + hash *= 0x100000001b3L; + } + hash ^= '\n'; + hash *= 0x100000001b3L; + } + return hash; + } + + /** + * The nodes reached from a root by following the links: what it depends on, + * what depends on it, or both, each followed on its own so BOTH does not wander + * from a dependency up to its other dependents. + * + * @param edges the links + * @param root the node to start from, always in the result + * @param direction which way to follow the links + * @param depth how many links to follow at most; null for no limit + * @return the root and the nodes reached, in the order they were reached + */ + public static Set trace(Collection edges, String root, Direction direction, Integer depth) { + if (depth != null && depth < 0) { + throw new IllegalArgumentException("The depth cannot be negative"); + } + Map> dependencies = new TreeMap<>(); + Map> dependents = new TreeMap<>(); + for (LayoutEdge edge : edges) { + dependencies.computeIfAbsent(edge.source(), key -> new ArrayList<>()).add(edge.target()); + dependents.computeIfAbsent(edge.target(), key -> new ArrayList<>()).add(edge.source()); + } + Set reached = new LinkedHashSet<>(); + reached.add(root); + if (direction != Direction.DEPENDENTS) { + reached.addAll(breadthFirst(dependencies, root, depth)); + } + if (direction != Direction.DEPENDENCIES) { + reached.addAll(breadthFirst(dependents, root, depth)); + } + return reached; + } + + private static Set breadthFirst(Map> next, String root, Integer depth) { + Map distance = new LinkedHashMap<>(); + distance.put(root, 0); + ArrayDeque queue = new ArrayDeque<>(); + queue.add(root); + while (!queue.isEmpty()) { + String id = queue.poll(); + int at = distance.get(id); + if (depth != null && at >= depth) { + continue; + } + List neighbours = new ArrayList<>(next.getOrDefault(id, List.of())); + Collections.sort(neighbours); + for (String neighbour : neighbours) { + if (!distance.containsKey(neighbour)) { + distance.put(neighbour, at + 1); + queue.add(neighbour); + } + } + } + return distance.keySet(); + } + + /** + * The links among a set of nodes + * + * @param edges the links + * @param nodes the node ids to keep + * @return the links whose ends are both kept + */ + public static List edgesAmong(Collection edges, Set nodes) { + List among = new ArrayList<>(); + for (LayoutEdge edge : edges) { + if (nodes.contains(edge.source()) && nodes.contains(edge.target())) { + among.add(edge); + } + } + return among; + } + +} diff --git a/src/prerna/auth/utils/SecurityAdminUtils.java b/src/prerna/auth/utils/SecurityAdminUtils.java index e50f8fc79b2..f2f00196e3f 100644 --- a/src/prerna/auth/utils/SecurityAdminUtils.java +++ b/src/prerna/auth/utils/SecurityAdminUtils.java @@ -1794,9 +1794,45 @@ private static void addPermissionUserFilters(SelectQueryStruct qs, String resour } return; } - String userId = Utility.inputSQLSanitizer(permissionUser.trim()); String userAlias = "PERMISSION_USER_GRANTS"; String groupAlias = "PERMISSION_USER_GROUP_GRANTS"; + addUserGrantJoins(qs, resourceIdCol, permissionTable, groupPermissionTable, idColumn, permissionUser.trim(), + userAlias, groupAlias); + + qs.addSelector(new QueryColumnSelector(userAlias + "__PERMISSION", "permission_user_permission")); + qs.addSelector(new QueryColumnSelector(groupAlias + "__PERMISSION", "permission_user_group_permission")); + + if (hasLevels) { + qs.addExplicitFilter(getEffectivePermissionFilter(userAlias + "__PERMISSION", groupAlias + "__PERMISSION", + globalCol, effectivePermissions)); + } + } + + /** + * Left joins one user's grants onto a resource query: the user's best direct + * grant per resource as {@code __PERMISSION} and the best grant of + * the custom groups the user belongs to as {@code __PERMISSION}. + * Either is null where the user has no such grant. Identity provider groups are + * only known while that user is signed in, so they are not counted. Together + * with {@link #getEffectivePermissionFilter} these give the user's effective + * permission on each resource. + * + * @param qs the resource query + * @param resourceIdCol the resource id column, such as + * {@code PROJECT__PROJECTID} + * @param permissionTable the user grant table, such as + * {@code PROJECTPERMISSION} + * @param groupPermissionTable the group grant table, such as + * {@code GROUPPROJECTPERMISSION} + * @param idColumn the resource id column in both grant tables, such + * as {@code PROJECTID} + * @param userId the user whose grants to join; sanitized here + * @param userAlias the alias of the direct grant subquery + * @param groupAlias the alias of the group grant subquery + */ + static void addUserGrantJoins(SelectQueryStruct qs, String resourceIdCol, String permissionTable, + String groupPermissionTable, String idColumn, String userId, String userAlias, String groupAlias) { + String sanitizedUserId = Utility.inputSQLSanitizer(userId); // the user's best direct grant per resource { @@ -1805,7 +1841,8 @@ private static void addPermissionUserFilters(SelectQueryStruct qs, String resour userQs.addSelector(QueryFunctionSelector.makeFunctionSelector(QueryFunctionHelper.MIN, permissionTable + "__PERMISSION", "PERMISSION")); userQs.addGroupBy(new QueryColumnSelector(permissionTable + "__" + idColumn, idColumn)); - userQs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter(permissionTable + "__USERID", "==", userId)); + userQs.addExplicitFilter( + SimpleQueryFilter.makeColToValFilter(permissionTable + "__USERID", "==", sanitizedUserId)); qs.addRelation(new SubqueryRelationship(userQs, userAlias, "left.outer.join", new String[] { userAlias + "__" + idColumn, resourceIdCol, "=" })); } @@ -1815,7 +1852,7 @@ private static void addPermissionUserFilters(SelectQueryStruct qs, String resour SelectQueryStruct membershipQs = new SelectQueryStruct(); membershipQs.addSelector(new QueryColumnSelector("CUSTOMGROUPASSIGNMENT__GROUPID")); membershipQs.addExplicitFilter( - SimpleQueryFilter.makeColToValFilter("CUSTOMGROUPASSIGNMENT__USERID", "==", userId)); + SimpleQueryFilter.makeColToValFilter("CUSTOMGROUPASSIGNMENT__USERID", "==", sanitizedUserId)); SelectQueryStruct groupQs = new SelectQueryStruct(); groupQs.addSelector(new QueryColumnSelector(groupPermissionTable + "__" + idColumn, idColumn)); @@ -1829,14 +1866,124 @@ private static void addPermissionUserFilters(SelectQueryStruct qs, String resour qs.addRelation(new SubqueryRelationship(groupQs, groupAlias, "left.outer.join", new String[] { groupAlias + "__" + idColumn, resourceIdCol, "=" })); } + } - qs.addSelector(new QueryColumnSelector(userAlias + "__PERMISSION", "permission_user_permission")); - qs.addSelector(new QueryColumnSelector(groupAlias + "__PERMISSION", "permission_user_group_permission")); + /** Where a user's effective permission on a catalog item comes from */ + public enum CatalogAccessSource { + /** The user's own grant */ + DIRECT, + /** A grant to a custom team the user belongs to */ + TEAM, + /** The item is public, which gives everyone read only access */ + PUBLIC + } - if (hasLevels) { - qs.addExplicitFilter(getEffectivePermissionFilter(userAlias + "__PERMISSION", groupAlias + "__PERMISSION", - globalCol, effectivePermissions)); + /** + * Every engine and project a user can use, with the user's effective permission + * on each and where it comes from. The permission is the best (lowest) of the + * user's own grant, their custom teams' best grant, and read only for a public + * item, by the same rules as the admin lists' permission filter; a tie goes to + * the user's own grant, then the team grant, then public. Identity provider + * groups are only known while the user is signed in, so they are not counted. + * + * @param userId the user's id + * @return each as id, kind (ENGINE or PROJECT), permission (1 owner, 2 edit, 3 + * read only) and source (DIRECT, TEAM or PUBLIC), engines first, each + * kind by id + */ + public static List> getUserCatalogAccess(String userId) { + if (userId == null || userId.isBlank()) { + throw new IllegalArgumentException("A user id is required"); + } + List> access = new ArrayList<>(); + access.addAll(readUserCatalogAccess("ENGINE", "ENGINE__ENGINEID", "ENGINE__GLOBAL", "ENGINEPERMISSION", + "GROUPENGINEPERMISSION", "ENGINEID", userId.trim())); + access.addAll(readUserCatalogAccess("PROJECT", "PROJECT__PROJECTID", "PROJECT__GLOBAL", "PROJECTPERMISSION", + "GROUPPROJECTPERMISSION", "PROJECTID", userId.trim())); + return access; + } + + private static List> readUserCatalogAccess(String kind, String resourceIdCol, + String globalCol, String permissionTable, String groupPermissionTable, String idColumn, String userId) { + String userAlias = "ACCESS_USER_GRANTS"; + String groupAlias = "ACCESS_USER_GROUP_GRANTS"; + SelectQueryStruct qs = new SelectQueryStruct(); + qs.addSelector(new QueryColumnSelector(resourceIdCol, "resource_id")); + qs.addSelector(new QueryColumnSelector(globalCol, "is_global")); + qs.addSelector(new QueryColumnSelector(userAlias + "__PERMISSION", "user_permission")); + qs.addSelector(new QueryColumnSelector(groupAlias + "__PERMISSION", "group_permission")); + addUserGrantJoins(qs, resourceIdCol, permissionTable, groupPermissionTable, idColumn, userId, userAlias, + groupAlias); + qs.addExplicitFilter(getEffectivePermissionFilter(userAlias + "__PERMISSION", groupAlias + "__PERMISSION", + globalCol, List.of(AccessPermissionEnum.OWNER.getId(), AccessPermissionEnum.EDIT.getId(), + AccessPermissionEnum.READ_ONLY.getId()))); + qs.addOrderBy(new QueryColumnOrderBySelector(resourceIdCol)); + + List> rows = QueryExecutionUtility.flushRsToMap(SystemEngineRegistry.getSecurityDb(), qs); + List> access = new ArrayList<>(rows.size()); + for (Map row : rows) { + Map.Entry best = effectiveAccess(toLevel(row.get("user_permission")), + toLevel(row.get("group_permission")), isTrue(row.get("is_global"))); + if (best == null) { + continue; + } + Map item = new LinkedHashMap<>(); + item.put("id", row.get("resource_id")); + item.put("kind", kind); + item.put("permission", best.getKey()); + item.put("source", best.getValue().name()); + access.add(item); + } + return access; + } + + private static Integer toLevel(Object value) { + if (value instanceof Number number) { + return number.intValue(); + } + if (value instanceof String text && !text.isBlank()) { + return Integer.valueOf(text.trim()); + } + return null; + } + + private static boolean isTrue(Object value) { + if (value instanceof Boolean bool) { + return bool; } + if (value instanceof Number number) { + return number.intValue() != 0; + } + return value != null && Boolean.parseBoolean(value.toString()); + } + + /** + * The effective permission from a user's own grant, their teams' best grant and + * whether the item is public: the lowest level, a tie going to the own grant, + * then the team grant, then public. + * + * @param direct the user's own grant, or null + * @param team the user's teams' best grant, or null + * @param global whether the item is public + * @return the level and its source, or null when the user has no access + */ + static Map.Entry effectiveAccess(Integer direct, Integer team, boolean global) { + Integer level = null; + CatalogAccessSource source = null; + if (direct != null) { + level = direct; + source = CatalogAccessSource.DIRECT; + } + if (team != null && (level == null || team < level)) { + level = team; + source = CatalogAccessSource.TEAM; + } + int publicLevel = AccessPermissionEnum.READ_ONLY.getId(); + if (global && (level == null || publicLevel < level)) { + level = publicLevel; + source = CatalogAccessSource.PUBLIC; + } + return level == null ? null : Map.entry(level, source); } /** diff --git a/src/prerna/auth/utils/reactors/admin/AdminGetUserCatalogAccessReactor.java b/src/prerna/auth/utils/reactors/admin/AdminGetUserCatalogAccessReactor.java new file mode 100644 index 00000000000..5d3405b3932 --- /dev/null +++ b/src/prerna/auth/utils/reactors/admin/AdminGetUserCatalogAccessReactor.java @@ -0,0 +1,83 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.auth.utils.reactors.admin; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import prerna.auth.User; +import prerna.auth.utils.SecurityAdminUtils; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.nounmeta.NounMetadata; + +/** + * Admin only: every engine and project a user can use, with the user's + * effective permission on each and whether it comes from their own grant, a + * custom team's grant, or the item being public. + */ +public class AdminGetUserCatalogAccessReactor extends AbstractReactor { + + private static final String USER_ID = "userId"; + + public AdminGetUserCatalogAccessReactor() { + this.keysToGet = new String[] { USER_ID }; + this.keyRequired = new int[] { 1 }; + } + + @Override + public NounMetadata execute() { + organizeKeys(); + User user = this.insight.getUser(); + if (!SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalArgumentException("User is not an admin and does not have access. Please login as an admin"); + } + String userId = this.keyValue.get(USER_ID); + if (userId == null || userId.isBlank()) { + throw new IllegalArgumentException("Must provide the user id"); + } + List> access = SecurityAdminUtils.getUserCatalogAccess(userId.trim()); + Map result = new LinkedHashMap<>(); + result.put("userId", userId.trim()); + result.put("access", access); + return new NounMetadata(result, PixelDataType.MAP); + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition() + .description("Admin Only: Every engine and project a user can use, each with id, kind (ENGINE or " + + "PROJECT), the user's effective permission (1 owner, 2 edit, 3 read only) and its source: " + + "DIRECT for the user's own grant, TEAM for a custom team's grant, PUBLIC for a public item. " + + "The best permission wins; a tie goes to DIRECT, then TEAM, then PUBLIC.") + .key(USER_ID, "The user's id") + .output(Map.class, "userId and access"); + } +} diff --git a/src/prerna/reactor/automation/definition/SaveAutomationReactor.java b/src/prerna/reactor/automation/definition/SaveAutomationReactor.java index 69d8c1cbcb8..1ee61ebc69b 100644 --- a/src/prerna/reactor/automation/definition/SaveAutomationReactor.java +++ b/src/prerna/reactor/automation/definition/SaveAutomationReactor.java @@ -27,7 +27,6 @@ *******************************************************************************/ package prerna.reactor.automation.definition; -import prerna.auth.utils.CatalogDependencyDerivation; import java.util.LinkedHashMap; import java.util.Map; @@ -91,7 +90,6 @@ public NounMetadata execute() { "nodeSourceCount", files.nodeSources() == null ? 0 : files.nodeSources().size())); AutomationDefinitionValidator.ValidatedDefinition validated = AutomationDefinitionValidator .parseAndValidateForAuthoring(files.definition()); - CatalogDependencyDerivation.syncAutomation(this.insight.getUser(), projectId, validated.nodes()); result.put(AutomationConstants.DOC_GLOBALS, AutomationRuntime.declaredGlobals(validated)); result.put(AutomationConstants.RESULT_SCOPE_VARIABLES, AutomationScopeCatalog.variablesByNode(validated)); return new NounMetadata(result, PixelDataType.MAP, PixelOperationType.OPERATION); diff --git a/src/prerna/reactor/automation/project/AutomationProjectService.java b/src/prerna/reactor/automation/project/AutomationProjectService.java index 375b530a3b2..4013f120491 100644 --- a/src/prerna/reactor/automation/project/AutomationProjectService.java +++ b/src/prerna/reactor/automation/project/AutomationProjectService.java @@ -51,6 +51,7 @@ import prerna.auth.AccessToken; import prerna.auth.User; +import prerna.auth.utils.CatalogDependencyDerivation; import prerna.auth.utils.SecurityEngineUtils; import prerna.auth.utils.SecurityProjectUtils; import prerna.cluster.util.ClusterUtil; @@ -255,6 +256,8 @@ static AutomationDefinitionService.DefinitionFiles saveDefinition(String project if (commitMessage == null || commitMessage.isBlank()) { throw new IllegalArgumentException("Automation version commit message must be provided."); } + AutomationDefinitionValidator.ValidatedDefinition validated; + AutomationDefinitionService.DefinitionFiles saved; ReentrantLock projectLock = ProjectSyncUtility.getProjectLock(projectId); projectLock.lock(); try { @@ -267,18 +270,24 @@ static AutomationDefinitionService.DefinitionFiles saveDefinition(String project "Automation changed since it was loaded. Refresh and reapply your changes."); } } - validateDefinitionReferences(AutomationDefinitionValidator.parseAndValidateForAuthoring(definitionJson), - user); + validated = AutomationDefinitionValidator.parseAndValidateForAuthoring(definitionJson); + validateDefinitionReferences(validated, user); AutomationDefinitionService.DefinitionFiles files = AutomationDefinitionService.save(projectId, definitionJson, nodeSources); AutomationMcpSync.sync(projectId, files.definition(), user); syncDefinitionAssets(projectId, user, commitMessage); - // Return the same normalized aggregate a subsequent GetAutomation call will + // Read back the same normalized aggregate a subsequent GetAutomation call will // read. This keeps the optimistic-concurrency token stable after Save. - return AutomationDefinitionService.load(projectId); + saved = AutomationDefinitionService.load(projectId); } finally { projectLock.unlock(); } + // Every save path funnels through here, so the dependency map follows granular + // step edits and version restores as well as a full save. allNodes carries the + // nodes nested in a loop body, and the sync logs rather than throws, so it can + // neither fail nor delay the save it records. + CatalogDependencyDerivation.syncAutomation(user, projectId, AutomationRuntime.allNodes(validated)); + return saved; } /** diff --git a/src/prerna/reactor/masterdatabase/util/GenerateMetamodelLayout.java b/src/prerna/reactor/masterdatabase/util/GenerateMetamodelLayout.java index 9186b01084c..1e506d02089 100644 --- a/src/prerna/reactor/masterdatabase/util/GenerateMetamodelLayout.java +++ b/src/prerna/reactor/masterdatabase/util/GenerateMetamodelLayout.java @@ -394,7 +394,7 @@ public static Map> generateMetamodelLayoutForExterna * * @param layout the layout the graph sends its nodes and edges to */ - private static void computeLayout(Layout layout) { + public static void computeLayout(Layout layout) { long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(LAYOUT_TIME_LIMIT_MS); int steps = 0; while (steps < MAX_LAYOUT_STEPS && layout.getStabilization() < LAYOUT_STABILIZATION) { diff --git a/src/prerna/reactor/security/AdminGetCatalogDependencyGraphReactor.java b/src/prerna/reactor/security/AdminGetCatalogDependencyGraphReactor.java new file mode 100644 index 00000000000..f5ffbac7ecb --- /dev/null +++ b/src/prerna/reactor/security/AdminGetCatalogDependencyGraphReactor.java @@ -0,0 +1,450 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.security; + +import java.sql.Timestamp; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import prerna.auth.User; +import prerna.auth.utils.CatalogDependencyGraphLayout; +import prerna.auth.utils.CatalogDependencyGraphLayout.Direction; +import prerna.auth.utils.CatalogDependencyGraphLayout.LayoutEdge; +import prerna.auth.utils.CatalogDependencyGraphLayout.LayoutNode; +import prerna.auth.utils.CatalogDependencyGraphLayout.Position; +import prerna.auth.utils.CatalogDependencyRole; +import prerna.auth.utils.CatalogTypes; +import prerna.auth.utils.SecurityAdminUtils; +import prerna.auth.utils.SecurityEngineUtils; +import prerna.auth.utils.SecurityProjectUtils; +import prerna.engine.api.IRDBMSEngine; +import prerna.engine.api.IRawSelectWrapper; +import prerna.query.querystruct.SelectQueryStruct; +import prerna.query.querystruct.selectors.QueryColumnSelector; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.util.Constants; +import prerna.util.QueryExecutionUtility; +import prerna.util.SystemEngineRegistry; + +/** + * Admin only: the catalog dependency graph of the whole platform, every engine + * and project with every link between them, laid out for the dependency map. + * With a catalog id, only what that item reaches in the given direction, up to + * the given depth. + * + *

+ * Reads the security database in a fixed number of queries whatever the size of + * the graph: every link, every engine, every project, and the descriptions of the + * items shown in chunks. + */ +public class AdminGetCatalogDependencyGraphReactor extends AbstractReactor { + + private static final Logger classLogger = LogManager.getLogger(AdminGetCatalogDependencyGraphReactor.class); + + private static final String DIRECTION = "direction"; + private static final String DEPTH = "depth"; + + private static final String ENGINE = "ENGINE"; + private static final String PROJECT = "PROJECT"; + /** How many ids one metadata query filters on */ + private static final int METADATA_CHUNK = 500; + private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + public AdminGetCatalogDependencyGraphReactor() { + this.keysToGet = new String[] { CatalogDependencyKeys.CATALOG_ID, DIRECTION, DEPTH }; + this.keyRequired = new int[] { 0, 0, 0 }; + } + + @Override + public NounMetadata execute() { + organizeKeys(); + User user = this.insight.getUser(); + if (!SecurityAdminUtils.userIsAdmin(user)) { + throw new IllegalArgumentException("User is not an admin and does not have access. Please login as an admin"); + } + String catalogId = this.keyValue.get(CatalogDependencyKeys.CATALOG_ID); + if (catalogId != null && catalogId.isBlank()) { + catalogId = null; + } + Direction direction = Direction.BOTH; + Integer depth = null; + if (catalogId != null) { + direction = Direction.parse(this.keyValue.get(DIRECTION)); + depth = parseDepth(this.keyValue.get(DEPTH)); + } + return new NounMetadata(buildGraph(catalogId == null ? null : catalogId.trim(), direction, depth), + PixelDataType.MAP); + } + + private static Integer parseDepth(String value) { + if (value == null || value.isBlank()) { + return null; + } + try { + int depth = (int) Double.parseDouble(value.trim()); + if (depth < 0) { + throw new IllegalArgumentException("The depth cannot be negative"); + } + return depth; + } catch (NumberFormatException e) { + throw new IllegalArgumentException("The depth must be a whole number, not '" + value + "'"); + } + } + + /** A row of CATALOGDEPENDENCIES */ + private record Link(String catalogId, String catalogType, String dependencyId, String dependencyType, + String userId, String dateAdded, boolean automatic, String role, String name, String description) { + + String edgeId() { + return catalogId + "|" + dependencyId + "|" + role; + } + } + + /** A row of ENGINE or PROJECT */ + private record Item(String id, String kind, String type, String subtype, String name, boolean discoverable, + boolean global, String createdBy, String dateCreated) { + } + + /** + * The graph, laid out + * + * @param catalogId the item to start from, or null for the whole platform + * @param direction which way to follow its links + * @param depth how many links to follow at most; null for no limit + * @return nodes, edges, stats, bounds and nodeSize + */ + public static Map buildGraph(String catalogId, Direction direction, Integer depth) { + IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); + List links = readLinks(securityDb); + Map items = new HashMap<>(); + for (Item item : readItems(securityDb, ENGINE)) { + items.put(item.id(), item); + } + for (Item item : readItems(securityDb, PROJECT)) { + items.putIfAbsent(item.id(), item); + } + + // one link per owner, target and role + Map linksById = new TreeMap<>(); + for (Link link : links) { + if (link.catalogId() == null || link.dependencyId() == null) { + continue; + } + linksById.putIfAbsent(link.edgeId(), link); + } + List allEdges = new ArrayList<>(linksById.size()); + for (Map.Entry entry : linksById.entrySet()) { + allEdges.add(new LayoutEdge(entry.getKey(), entry.getValue().catalogId(), + entry.getValue().dependencyId())); + } + + // counts across the whole platform, whatever is shown + Map> dependenciesOf = new HashMap<>(); + Map> dependentsOf = new HashMap<>(); + // the kind and type of an id that is in neither ENGINE nor PROJECT, from a link + Map linkedType = new HashMap<>(); + for (Link link : linksById.values()) { + dependenciesOf.computeIfAbsent(link.catalogId(), key -> new HashSet<>()).add(link.dependencyId()); + dependentsOf.computeIfAbsent(link.dependencyId(), key -> new HashSet<>()).add(link.catalogId()); + linkedType.putIfAbsent(link.dependencyId(), link.dependencyType()); + linkedType.putIfAbsent(link.catalogId(), link.catalogType()); + } + + Set nodeIds; + List edges; + if (catalogId == null) { + nodeIds = new TreeSet<>(items.keySet()); + nodeIds.addAll(linkedType.keySet()); + edges = allEdges; + } else { + if (!items.containsKey(catalogId) && !linkedType.containsKey(catalogId)) { + throw new IllegalArgumentException("No engine or project has the id " + catalogId); + } + nodeIds = new TreeSet<>(CatalogDependencyGraphLayout.trace(allEdges, catalogId, direction, depth)); + edges = CatalogDependencyGraphLayout.edgesAmong(allEdges, nodeIds); + } + + Map nodeItems = new LinkedHashMap<>(); + for (String id : nodeIds) { + Item item = items.get(id); + if (item == null) { + String type = linkedType.get(id); + item = new Item(id, kindOfType(type), normalizedType(type), null, id, false, false, null, null); + } + nodeItems.put(id, item); + } + + List layoutNodes = new ArrayList<>(nodeItems.size()); + for (Item item : nodeItems.values()) { + layoutNodes.add(new LayoutNode(item.id(), item.kind() + ":" + item.type(), item.name())); + } + CatalogDependencyGraphLayout.Result layout = CatalogDependencyGraphLayout.layout(layoutNodes, edges); + + Map descriptions = readDescriptions(nodeItems.values(), items.keySet()); + + List> nodes = new ArrayList<>(nodeItems.size()); + int missing = 0; + for (Item item : nodeItems.values()) { + boolean isMissing = !items.containsKey(item.id()); + if (isMissing) { + missing++; + } + Position position = layout.positions().get(item.id()); + Map node = new LinkedHashMap<>(); + node.put("id", item.id()); + node.put("kind", item.kind()); + node.put("type", item.type()); + node.put("subtype", item.subtype()); + node.put("name", item.name()); + node.put("description", descriptions.get(item.id())); + node.put("discoverable", item.discoverable()); + node.put("global", item.global()); + node.put("createdBy", item.createdBy()); + node.put("dateCreated", item.dateCreated()); + node.put("missing", isMissing); + node.put("x", position.x()); + node.put("y", position.y()); + node.put("component", layout.components().get(item.id())); + node.put("dependencyCount", dependenciesOf.getOrDefault(item.id(), Set.of()).size()); + node.put("dependentCount", dependentsOf.getOrDefault(item.id(), Set.of()).size()); + nodes.add(node); + } + + List> edgeRows = new ArrayList<>(edges.size()); + int automatic = 0; + for (LayoutEdge edge : edges) { + Link link = linksById.get(edge.id()); + if (link.automatic()) { + automatic++; + } + Map row = new LinkedHashMap<>(); + row.put("id", edge.id()); + row.put("source", link.catalogId()); + row.put("target", link.dependencyId()); + row.put("role", link.role()); + row.put("isAutomatic", link.automatic()); + row.put("name", link.name()); + row.put("description", link.description()); + row.put("dateAdded", link.dateAdded()); + row.put("addedBy", link.userId()); + row.put("inCycle", layout.inCycleEdges().contains(edge.id())); + edgeRows.add(row); + } + + Map stats = new LinkedHashMap<>(); + stats.put("nodes", nodes.size()); + stats.put("edges", edgeRows.size()); + stats.put("automatic", automatic); + stats.put("manual", edgeRows.size() - automatic); + stats.put("missing", missing); + stats.put("isolated", layout.isolatedCount()); + stats.put("cycles", layout.cycles()); + stats.put("components", layout.componentCount()); + + Map bounds = new LinkedHashMap<>(); + bounds.put("width", layout.width()); + bounds.put("height", layout.height()); + Map nodeSize = new LinkedHashMap<>(); + nodeSize.put("width", (int) CatalogDependencyGraphLayout.NODE_WIDTH); + nodeSize.put("height", (int) CatalogDependencyGraphLayout.NODE_HEIGHT); + + Map result = new LinkedHashMap<>(); + result.put("nodes", nodes); + result.put("edges", edgeRows); + result.put("stats", stats); + result.put("bounds", bounds); + result.put("nodeSize", nodeSize); + return result; + } + + /** + * ENGINE or PROJECT for a stored type, guessed for an id no longer in either + * table: a project type is a project, anything else an engine + */ + static String kindOfType(String type) { + if (type == null || type.isBlank()) { + return ENGINE; + } + if (PROJECT.equalsIgnoreCase(type.trim())) { + return PROJECT; + } + try { + return CatalogTypes.kindOf(type).name(); + } catch (IllegalArgumentException e) { + return ENGINE; + } + } + + private static String normalizedType(String type) { + if (type == null || type.isBlank()) { + return null; + } + try { + return CatalogTypes.normalize(type); + } catch (IllegalArgumentException e) { + return type.trim(); + } + } + + private static List readLinks(IRDBMSEngine securityDb) { + SelectQueryStruct qs = new SelectQueryStruct(); + for (String column : new String[] { "CATALOGID", "CATALOGTYPE", "DEPENDENCYID", "DEPENDENCYTYPE", "USERID", + "DATEADDED", "IS_AUTOMATIC", "ROLE", "NAME", "DESCRIPTION" }) { + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__" + column)); + } + try { + return QueryExecutionUtility.queryList(securityDb, qs, rs -> { + boolean automatic = rs.getBoolean(7); + // as SecurityCatalogDependencyUtils reads a link: a row from before + // IS_AUTOMATIC is a picked one, and an automatic one has no name + String role = automatic ? CatalogDependencyRole.fromStored(rs.getString(8)).name() + : CatalogDependencyRole.MANUAL.name(); + return new Link(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), + format(rs.getTimestamp(6)), automatic, role, automatic ? null : rs.getString(9), + rs.getString(10)); + }); + } catch (Exception e) { + throw new IllegalStateException("Unable to read the catalog dependencies", e); + } + } + + private static List readItems(IRDBMSEngine securityDb, String table) { + boolean engine = ENGINE.equals(table); + String prefix = table + "__"; + SelectQueryStruct qs = new SelectQueryStruct(); + List columns = engine + ? List.of("ENGINEID", "ENGINENAME", "ENGINEDISPLAYNAME", "ENGINETYPE", "DISCOVERABLE", "GLOBAL", + "CREATEDBY", "DATECREATED", "ENGINESUBTYPE") + // a project has no subtype + : List.of("PROJECTID", "PROJECTNAME", "PROJECTDISPLAYNAME", "TYPE", "DISCOVERABLE", "GLOBAL", + "CREATEDBY", "DATECREATED"); + for (String column : columns) { + qs.addSelector(new QueryColumnSelector(prefix + column)); + } + try { + return QueryExecutionUtility.queryList(securityDb, qs, rs -> { + String name = rs.getString(3); + if (name == null || name.isBlank()) { + name = rs.getString(2); + } + String type = engine ? rs.getString(4) : CatalogTypes.projectTypeOf(rs.getString(4)); + String subtype = engine ? rs.getString(9) : null; + return new Item(rs.getString(1), table, type, subtype, name, rs.getBoolean(5), rs.getBoolean(6), + rs.getString(7), format(rs.getTimestamp(8))); + }); + } catch (Exception e) { + throw new IllegalStateException("Unable to read the " + table.toLowerCase() + " catalog", e); + } + } + + /** + * The description of each item shown, from ENGINEMETA or PROJECTMETA, read a + * chunk of ids at a time. An item with several takes the first by METAORDER. + */ + private static Map readDescriptions(Collection shown, Set known) { + List engineIds = new ArrayList<>(); + List projectIds = new ArrayList<>(); + for (Item item : shown) { + if (!known.contains(item.id())) { + continue; + } + (ENGINE.equals(item.kind()) ? engineIds : projectIds).add(item.id()); + } + Map descriptions = new HashMap<>(); + Map orders = new HashMap<>(); + for (int start = 0; start < engineIds.size(); start += METADATA_CHUNK) { + List chunk = engineIds.subList(start, Math.min(engineIds.size(), start + METADATA_CHUNK)); + try (IRawSelectWrapper wrapper = SecurityEngineUtils.getEngineMetadataWrapper(chunk, + List.of(Constants.DESCRIPTION), true)) { + collectDescriptions(wrapper, descriptions, orders); + } catch (Exception e) { + classLogger.warn("Could not read the descriptions of {} engines", chunk.size(), e); + } + } + for (int start = 0; start < projectIds.size(); start += METADATA_CHUNK) { + List chunk = projectIds.subList(start, Math.min(projectIds.size(), start + METADATA_CHUNK)); + try (IRawSelectWrapper wrapper = SecurityProjectUtils.getProjectMetadataWrapper(chunk, + List.of(Constants.DESCRIPTION), true)) { + collectDescriptions(wrapper, descriptions, orders); + } catch (Exception e) { + classLogger.warn("Could not read the descriptions of {} projects", chunk.size(), e); + } + } + return descriptions; + } + + private static void collectDescriptions(IRawSelectWrapper wrapper, Map descriptions, + Map orders) { + while (wrapper.hasNext()) { + Object[] values = wrapper.next().getValues(); + if (values[0] == null || values[2] == null) { + continue; + } + String id = values[0].toString(); + double order = values[3] instanceof Number number ? number.doubleValue() : Double.MAX_VALUE; + Double previous = orders.get(id); + if (previous == null || order < previous) { + orders.put(id, order); + descriptions.put(id, values[2].toString()); + } + } + } + + private static String format(Timestamp timestamp) { + return timestamp == null ? null : timestamp.toLocalDateTime().format(DATE_FORMAT); + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition() + .description("Admin Only: The catalog dependency graph, laid out for the dependency map. With no " + + "catalog id, every engine and project on the platform, linked or not, and every link; with " + + "one, the items it reaches in the given direction up to the given depth, and the links " + + "among them. Each node has its top left x and y in pixels and its component; each link " + + "whether it is part of a cycle.") + .key(CatalogDependencyKeys.CATALOG_ID, "Optional: the engine id or project id to start from") + .key(DIRECTION, "Optional, with a catalog id: DEPENDENCIES, DEPENDENTS or BOTH (the default)") + .key(DEPTH, "Optional, with a catalog id: how many links to follow at most; no limit by default") + .output(Map.class, "nodes, edges, stats, bounds and nodeSize"); + } +} diff --git a/test/prerna/auth/utils/AdminCatalogDependencyMapUnitTests.java b/test/prerna/auth/utils/AdminCatalogDependencyMapUnitTests.java new file mode 100644 index 00000000000..e8f7bd60884 --- /dev/null +++ b/test/prerna/auth/utils/AdminCatalogDependencyMapUnitTests.java @@ -0,0 +1,265 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.auth.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import prerna.auth.AuthProvider; +import prerna.auth.User; +import prerna.auth.utils.CatalogDependencyGraphLayout.Direction; +import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; +import prerna.engine.api.IEngine; +import prerna.engine.api.IRDBMSEngine; +import prerna.reactor.security.AdminGetCatalogDependencyGraphReactor; +import prerna.util.QueryExecutionUtility; +import prerna.util.SystemEngineRegistry; + +/** + * The admin dependency map's reads against a disposable security database: the + * whole graph and a traced one, and a user's effective access to every item. + */ +public class AdminCatalogDependencyMapUnitTests extends AbstractSecurityUtilsUnitTestsSetup { + + private IRDBMSEngine securityDb; + private List tables = new ArrayList<>(); + private User admin; + + @BeforeEach + void setup() { + securityDb = SystemEngineRegistry.getSecurityDb(); + assertTrue(securityDb.getOwlFilePath().contains("junit")); + admin = UnitTestSecurityAuthUtils.createUser("admin", true); + } + + @AfterEach + void cleanup() throws Exception { + assertTrue(securityDb.getOwlFilePath().contains("junit")); + tables = UnitTestSecurityAuthUtils.clearSecurityDB(securityDb, tables); + } + + /// + /// AdminGetCatalogDependencyGraph + /// + + private void createGraph() throws Exception { + UnitTestSecurityAuthUtils.createEngine("model1", "Model", IEngine.CATALOG_TYPE.MODEL, admin); + UnitTestSecurityAuthUtils.createEngine("vector1", "Vector", IEngine.CATALOG_TYPE.VECTOR, admin); + UnitTestSecurityAuthUtils.createEngine("lonely", "Lonely", IEngine.CATALOG_TYPE.DATABASE, admin); + UnitTestSecurityAuthUtils.createProjectOfType("agent1", "Agent", "WORKSPACE", admin); + SecurityEngineUtils.updateEngineMetadata(admin, "vector1", Map.of("description", "Some vectors")); + // agent1 -> vector1 -> model1, agent1 -> model1 (automatic), agent1 -> gone (a deleted skill) + SecurityCatalogDependencyUtils.setManualDependencies(admin, "agent1", "WORKSPACE", + List.of(new Dependency("vector1", "VECTOR"))); + SecurityCatalogDependencyUtils.addAutomaticDependencies(admin, "vector1", "VECTOR", + List.of(new Dependency("model1", "MODEL", true, CatalogDependencyRole.EMBEDDER, null, "Embeds"))); + SecurityCatalogDependencyUtils.addAutomaticDependencies(admin, "agent1", "WORKSPACE", + List.of(new Dependency("model1", "MODEL", true, CatalogDependencyRole.AGENT_MODEL, null, null))); + QueryExecutionUtility.executeUpdate(securityDb, + "INSERT INTO CATALOGDEPENDENCIES (CATALOGID, CATALOGTYPE, DEPENDENCYID, DEPENDENCYTYPE, USERID, " + + "IS_AUTOMATIC, ROLE) VALUES (?, ?, ?, ?, ?, ?, ?)", + ps -> { + ps.setString(1, "agent1"); + ps.setString(2, "WORKSPACE"); + ps.setString(3, "gone"); + ps.setString(4, "SKILL"); + ps.setString(5, "adminid"); + ps.setBoolean(6, true); + ps.setString(7, CatalogDependencyRole.SKILL.name()); + }); + } + + @SuppressWarnings("unchecked") + private static Map> byId(Object rows) { + Map> byId = new LinkedHashMap<>(); + for (Object row : (List) rows) { + Map map = (Map) row; + byId.put((String) map.get("id"), map); + } + return byId; + } + + @Test + @SuppressWarnings("unchecked") + void theWholeGraphHasEveryItemAndLink() throws Exception { + createGraph(); + Map graph = AdminGetCatalogDependencyGraphReactor.buildGraph(null, Direction.BOTH, null); + + Map> nodes = byId(graph.get("nodes")); + assertEquals(Set.of("model1", "vector1", "lonely", "agent1", "gone"), nodes.keySet()); + Map vector = nodes.get("vector1"); + assertEquals("ENGINE", vector.get("kind")); + assertEquals("VECTOR", vector.get("type")); + assertEquals("Vector", vector.get("name")); + assertEquals("Some vectors", vector.get("description")); + assertEquals(false, vector.get("missing")); + assertEquals(1, vector.get("dependencyCount")); + assertEquals(1, vector.get("dependentCount")); + assertTrue(vector.get("dateCreated") instanceof String); + assertEquals("adminid", vector.get("createdBy")); + + Map agent = nodes.get("agent1"); + assertEquals("PROJECT", agent.get("kind")); + assertEquals("WORKSPACE", agent.get("type")); + assertNull(agent.get("subtype")); + assertEquals(3, agent.get("dependencyCount")); + + Map gone = nodes.get("gone"); + assertEquals(true, gone.get("missing")); + assertEquals("PROJECT", gone.get("kind")); + assertEquals("SKILL", gone.get("type")); + assertEquals("gone", gone.get("name")); + + assertEquals(-1, nodes.get("lonely").get("component")); + assertEquals(0, nodes.get("agent1").get("component")); + + Map> edges = byId(graph.get("edges")); + assertEquals(Set.of("agent1|vector1|MANUAL", "vector1|model1|EMBEDDER", "agent1|model1|AGENT_MODEL", + "agent1|gone|SKILL"), edges.keySet()); + Map embedder = edges.get("vector1|model1|EMBEDDER"); + assertEquals("vector1", embedder.get("source")); + assertEquals("model1", embedder.get("target")); + assertEquals(true, embedder.get("isAutomatic")); + assertEquals("Embeds", embedder.get("description")); + assertEquals(false, embedder.get("inCycle")); + assertEquals("adminid", embedder.get("addedBy")); + assertEquals(false, edges.get("agent1|vector1|MANUAL").get("isAutomatic")); + + Map stats = (Map) graph.get("stats"); + assertEquals(5, stats.get("nodes")); + assertEquals(4, stats.get("edges")); + assertEquals(3, stats.get("automatic")); + assertEquals(1, stats.get("manual")); + assertEquals(1, stats.get("missing")); + assertEquals(1, stats.get("isolated")); + assertEquals(0, stats.get("cycles")); + assertEquals(1, stats.get("components")); + assertEquals(Map.of("width", 240, "height", 64), graph.get("nodeSize")); + Map bounds = (Map) graph.get("bounds"); + assertTrue(((Number) bounds.get("width")).doubleValue() >= 240); + } + + @Test + void aTracedGraphHasOnlyWhatTheItemReaches() throws Exception { + createGraph(); + Map dependents = AdminGetCatalogDependencyGraphReactor.buildGraph("model1", + Direction.DEPENDENTS, 1); + assertEquals(Set.of("model1", "vector1", "agent1"), byId(dependents.get("nodes")).keySet()); + assertEquals(Set.of("vector1|model1|EMBEDDER", "agent1|model1|AGENT_MODEL", "agent1|vector1|MANUAL"), + byId(dependents.get("edges")).keySet()); + + Map dependencies = AdminGetCatalogDependencyGraphReactor.buildGraph("vector1", + Direction.DEPENDENCIES, null); + assertEquals(Set.of("vector1", "model1"), byId(dependencies.get("nodes")).keySet()); + + assertThrows(IllegalArgumentException.class, + () -> AdminGetCatalogDependencyGraphReactor.buildGraph("nothing", Direction.BOTH, null)); + } + + /// + /// getUserCatalogAccess + /// + + @Test + void effectiveAccessTakesTheBestGrantAndNamesItsSource() throws Exception { + User member = UnitTestSecurityAuthUtils.createUser("member", false); + AdminSecurityGroupUtils groups = AdminSecurityGroupUtils.getInstance(admin); + groups.addGroup(admin, "team", "CUSTOM", "catalog access team"); + groups.addUserToGroup(admin, "team", "memberid", AuthProvider.NATIVE.getLabel(), null); + + // direct edit + UnitTestSecurityAuthUtils.createEngine("direct", "Direct", admin); + UnitTestSecurityAuthUtils.addPermissionsToUserForEngine(admin, "memberid", "direct", "EDIT"); + // team owner beats direct read only + UnitTestSecurityAuthUtils.createEngine("team", "Team", admin); + UnitTestSecurityAuthUtils.addPermissionsToUserForEngine(admin, "memberid", "team", "READ_ONLY"); + groups.addGroupEnginePermission(admin, "team", "CUSTOM", "team", 1, null); + // direct wins a tie with the team + UnitTestSecurityAuthUtils.createEngine("tie", "Tie", admin); + UnitTestSecurityAuthUtils.addPermissionsToUserForEngine(admin, "memberid", "tie", "EDIT"); + groups.addGroupEnginePermission(admin, "team", "CUSTOM", "tie", 2, null); + // public, nothing else + UnitTestSecurityAuthUtils.createEngineGlobal("public", "Public", admin); + // public with a direct read only: direct wins the tie + UnitTestSecurityAuthUtils.createEngineGlobal("publicdirect", "Public Direct", admin); + UnitTestSecurityAuthUtils.addPermissionsToUserForEngine(admin, "memberid", "publicdirect", "READ_ONLY"); + // no access + UnitTestSecurityAuthUtils.createEngine("hidden", "Hidden", admin); + // a project through the team + UnitTestSecurityAuthUtils.createProject("teamproject", "Team Project", admin); + groups.addGroupProjectPermission(admin, "team", "CUSTOM", "teamproject", 3, null); + + Map> access = byId(SecurityAdminUtils.getUserCatalogAccess("memberid")); + assertEquals(Set.of("direct", "team", "tie", "public", "publicdirect", "teamproject"), access.keySet()); + assertAccess(access.get("direct"), "ENGINE", 2, "DIRECT"); + assertAccess(access.get("team"), "ENGINE", 1, "TEAM"); + assertAccess(access.get("tie"), "ENGINE", 2, "DIRECT"); + assertAccess(access.get("public"), "ENGINE", 3, "PUBLIC"); + assertAccess(access.get("publicdirect"), "ENGINE", 3, "DIRECT"); + assertAccess(access.get("teamproject"), "PROJECT", 3, "TEAM"); + assertFalse(access.containsKey("hidden")); + + // the owner of everything + Map> adminAccess = byId(SecurityAdminUtils.getUserCatalogAccess("adminid")); + assertAccess(adminAccess.get("hidden"), "ENGINE", 1, "DIRECT"); + assertTrue(member != null); + } + + @Test + void effectiveAccessRules() { + assertNull(SecurityAdminUtils.effectiveAccess(null, null, false)); + assertEquals(Map.entry(3, SecurityAdminUtils.CatalogAccessSource.PUBLIC), + SecurityAdminUtils.effectiveAccess(null, null, true)); + assertEquals(Map.entry(2, SecurityAdminUtils.CatalogAccessSource.TEAM), + SecurityAdminUtils.effectiveAccess(3, 2, true)); + assertEquals(Map.entry(1, SecurityAdminUtils.CatalogAccessSource.DIRECT), + SecurityAdminUtils.effectiveAccess(1, 1, true)); + assertEquals(Map.entry(3, SecurityAdminUtils.CatalogAccessSource.TEAM), + SecurityAdminUtils.effectiveAccess(null, 3, true)); + assertThrows(IllegalArgumentException.class, () -> SecurityAdminUtils.getUserCatalogAccess(" ")); + } + + private static void assertAccess(Map row, String kind, int permission, String source) { + assertEquals(kind, row.get("kind")); + assertEquals(permission, row.get("permission")); + assertEquals(source, row.get("source")); + } +} diff --git a/test/prerna/auth/utils/CatalogDependencyGraphLayoutUnitTests.java b/test/prerna/auth/utils/CatalogDependencyGraphLayoutUnitTests.java new file mode 100644 index 00000000000..d279902ea88 --- /dev/null +++ b/test/prerna/auth/utils/CatalogDependencyGraphLayoutUnitTests.java @@ -0,0 +1,340 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.auth.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import prerna.auth.utils.CatalogDependencyGraphLayout.Direction; +import prerna.auth.utils.CatalogDependencyGraphLayout.LayoutEdge; +import prerna.auth.utils.CatalogDependencyGraphLayout.LayoutNode; +import prerna.auth.utils.CatalogDependencyGraphLayout.Position; +import prerna.auth.utils.CatalogDependencyGraphLayout.Result; + +/** The admin dependency map's layout, cycle detection and tracing, without a database. */ +public class CatalogDependencyGraphLayoutUnitTests { + + private static final double W = CatalogDependencyGraphLayout.NODE_WIDTH; + private static final double H = CatalogDependencyGraphLayout.NODE_HEIGHT; + + private static LayoutNode node(String id) { + return new LayoutNode(id, "ENGINE:MODEL", id); + } + + private static LayoutNode node(String id, String type, String name) { + return new LayoutNode(id, type, name); + } + + private static LayoutEdge edge(String source, String target) { + return new LayoutEdge(source + "|" + target + "|MANUAL", source, target); + } + + /** Two components (a chain of 5 and a star of 4), a 2 node cycle, a self loop, and isolated nodes */ + private static List sampleNodes() { + List nodes = new ArrayList<>(); + for (String id : List.of("a1", "a2", "a3", "a4", "a5", "b1", "b2", "b3", "b4", "c1", "c2", "d1")) { + nodes.add(node(id)); + } + nodes.add(node("i1", "PROJECT:SKILL", "Zeta")); + nodes.add(node("i2", "ENGINE:DATABASE", "Beta")); + nodes.add(node("i3", "ENGINE:DATABASE", "Alpha")); + nodes.add(node("i4", "PROJECT:SKILL", "Eta")); + return nodes; + } + + private static List sampleEdges() { + return List.of(edge("a1", "a2"), edge("a2", "a3"), edge("a3", "a4"), edge("a4", "a5"), edge("b1", "b2"), + edge("b1", "b3"), edge("b1", "b4"), edge("c1", "c2"), edge("c2", "c1"), edge("d1", "d1")); + } + + private static boolean overlaps(Position a, Position b) { + return a.x() < b.x() + W && b.x() < a.x() + W && a.y() < b.y() + H && b.y() < a.y() + H; + } + + private static void assertNoOverlaps(Map positions) { + List> entries = new ArrayList<>(positions.entrySet()); + for (int i = 0; i < entries.size(); i++) { + for (int j = i + 1; j < entries.size(); j++) { + assertFalse(overlaps(entries.get(i).getValue(), entries.get(j).getValue()), + entries.get(i).getKey() + " overlaps " + entries.get(j).getKey()); + } + } + } + + /** The bounding box of each component's boxes, as minX, minY, maxX, maxY */ + private static Map componentBoxes(Result result) { + Map boxes = new LinkedHashMap<>(); + for (Map.Entry entry : result.positions().entrySet()) { + int component = result.components().get(entry.getKey()); + Position p = entry.getValue(); + double[] box = boxes.computeIfAbsent(component, key -> new double[] { Double.MAX_VALUE, + Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE }); + box[0] = Math.min(box[0], p.x()); + box[1] = Math.min(box[1], p.y()); + box[2] = Math.max(box[2], p.x() + W); + box[3] = Math.max(box[3], p.y() + H); + } + return boxes; + } + + @Test + void sameInputInAnyOrderGivesTheSameLayout() { + Result first = CatalogDependencyGraphLayout.layout(sampleNodes(), sampleEdges()); + List shuffledNodes = new ArrayList<>(sampleNodes()); + List shuffledEdges = new ArrayList<>(sampleEdges()); + Collections.reverse(shuffledNodes); + Collections.reverse(shuffledEdges); + Result second = CatalogDependencyGraphLayout.layout(shuffledNodes, shuffledEdges); + + assertEquals(first.positions(), second.positions()); + assertEquals(first.components(), second.components()); + assertEquals(first.inCycleEdges(), second.inCycleEdges()); + assertEquals(first.width(), second.width()); + assertEquals(first.height(), second.height()); + } + + @Test + void everyNodeIsPlacedWithoutOverlapsAndNormalizedToZero() { + Result result = CatalogDependencyGraphLayout.layout(sampleNodes(), sampleEdges()); + assertEquals(16, result.positions().size()); + assertNoOverlaps(result.positions()); + double minX = result.positions().values().stream().mapToDouble(Position::x).min().orElseThrow(); + double minY = result.positions().values().stream().mapToDouble(Position::y).min().orElseThrow(); + assertEquals(0, minX); + assertEquals(0, minY); + for (Position p : result.positions().values()) { + assertTrue(p.x() + W <= result.width()); + assertTrue(p.y() + H <= result.height()); + } + } + + @Test + void componentsAreNumberedLargestFirstAndDoNotOverlap() { + Result result = CatalogDependencyGraphLayout.layout(sampleNodes(), sampleEdges()); + // a chain, b star, c cycle, d self loop + assertEquals(4, result.componentCount()); + assertEquals(0, result.components().get("a1")); + assertEquals(1, result.components().get("b1")); + assertEquals(2, result.components().get("c1")); + assertEquals(3, result.components().get("d1")); + for (String id : List.of("a2", "a3", "a4", "a5")) { + assertEquals(0, result.components().get(id)); + } + + Map boxes = componentBoxes(result); + boxes.remove(-1); + List list = new ArrayList<>(boxes.values()); + for (int i = 0; i < list.size(); i++) { + for (int j = i + 1; j < list.size(); j++) { + double[] a = list.get(i); + double[] b = list.get(j); + boolean apart = a[2] <= b[0] || b[2] <= a[0] || a[3] <= b[1] || b[3] <= a[1]; + assertTrue(apart, "components " + i + " and " + j + " overlap"); + } + } + } + + @Test + void isolatedNodesComeLastGroupedByTypeThenName() { + Result result = CatalogDependencyGraphLayout.layout(sampleNodes(), sampleEdges()); + assertEquals(4, result.isolatedCount()); + for (String id : List.of("i1", "i2", "i3", "i4")) { + assertEquals(-1, result.components().get(id)); + } + double lowestLinked = 0; + for (Map.Entry entry : result.positions().entrySet()) { + if (result.components().get(entry.getKey()) >= 0) { + lowestLinked = Math.max(lowestLinked, entry.getValue().y() + H); + } + } + for (String id : List.of("i1", "i2", "i3", "i4")) { + assertTrue(result.positions().get(id).y() >= lowestLinked, id + " is not below the components"); + } + // ENGINE:DATABASE before PROJECT:SKILL, each by name, each type on its own row + Position alpha = result.positions().get("i3"); + Position beta = result.positions().get("i2"); + Position eta = result.positions().get("i4"); + Position zeta = result.positions().get("i1"); + assertEquals(alpha.y(), beta.y()); + assertTrue(alpha.x() < beta.x()); + assertEquals(eta.y(), zeta.y()); + assertTrue(eta.x() < zeta.x()); + assertTrue(eta.y() > alpha.y()); + } + + @Test + void onlyIsolatedNodesFormAGridFromZero() { + List nodes = new ArrayList<>(); + for (int i = 0; i < 30; i++) { + nodes.add(node(String.format("n%02d", i), "ENGINE:MODEL", String.format("n%02d", i))); + } + Result result = CatalogDependencyGraphLayout.layout(nodes, List.of()); + assertEquals(30, result.isolatedCount()); + assertEquals(0, result.componentCount()); + assertNoOverlaps(result.positions()); + assertEquals(new Position(0, 0), result.positions().get("n00")); + // wider than tall + assertTrue(result.width() > result.height()); + } + + @Test + void twoNodeCyclesAndSelfLoopsAreFlagged() { + Result result = CatalogDependencyGraphLayout.layout(sampleNodes(), sampleEdges()); + assertEquals(Set.of("c1|c2|MANUAL", "c2|c1|MANUAL", "d1|d1|MANUAL"), result.inCycleEdges()); + assertEquals(2, result.cycles()); + } + + @Test + void aLongerCycleFlagsOnlyItsOwnLinks() { + List nodes = List.of(node("x"), node("y"), node("z"), node("tail")); + List edges = List.of(edge("x", "y"), edge("y", "z"), edge("z", "x"), edge("z", "tail")); + Result result = CatalogDependencyGraphLayout.layout(nodes, edges); + assertEquals(Set.of("x|y|MANUAL", "y|z|MANUAL", "z|x|MANUAL"), result.inCycleEdges()); + assertEquals(1, result.cycles()); + } + + @Test + void linksToUnknownNodesAreLeftOut() { + Result result = CatalogDependencyGraphLayout.layout(List.of(node("a")), List.of(edge("a", "ghost"))); + assertEquals(Set.of("a"), result.positions().keySet()); + assertEquals(1, result.isolatedCount()); + } + + @Test + void aComponentAboveTheThresholdIsSnappedToAGrid() { + List nodes = new ArrayList<>(); + List edges = new ArrayList<>(); + for (int i = 0; i < 40; i++) { + nodes.add(node(String.format("g%02d", i))); + if (i > 0) { + edges.add(edge(String.format("g%02d", i), String.format("g%02d", (i - 1) / 3))); + } + } + Result grid = CatalogDependencyGraphLayout.layout(nodes, edges, 10); + assertNoOverlaps(grid.positions()); + double cellWidth = W + CatalogDependencyGraphLayout.NODE_GAP; + double cellHeight = H + CatalogDependencyGraphLayout.NODE_GAP; + for (Position p : grid.positions().values()) { + assertEquals(0, Math.IEEEremainder(p.x(), cellWidth), 1e-6); + assertEquals(0, Math.IEEEremainder(p.y(), cellHeight), 1e-6); + } + assertEquals(grid.positions(), CatalogDependencyGraphLayout.layout(nodes, edges, 10).positions()); + + // below the threshold the same graph is separated with Rectangles instead + Result separated = CatalogDependencyGraphLayout.layout(nodes, edges, 1_000); + assertNoOverlaps(separated.positions()); + } + + @Test + void snapToGridMovesCollisionsToTheNearestFreeCell() { + Map scaled = new LinkedHashMap<>(); + scaled.put("a", new double[] { 0, 0 }); + scaled.put("b", new double[] { 1, 1 }); + scaled.put("c", new double[] { 2, 2 }); + Map placed = CatalogDependencyGraphLayout.snapToGrid(scaled); + assertEquals(new Position(0, 0), placed.get("a")); + assertEquals(3, new HashSet<>(placed.values()).size()); + assertNoOverlaps(placed); + } + + @Test + void seedDependsOnlyOnTheIds() { + assertEquals(CatalogDependencyGraphLayout.seedOf(List.of("a", "b")), + CatalogDependencyGraphLayout.seedOf(List.of("a", "b"))); + assertFalse(CatalogDependencyGraphLayout.seedOf(List.of("a", "b")) == CatalogDependencyGraphLayout + .seedOf(List.of("ab"))); + } + + /// + /// trace + /// + + /** root depends on d1, d1 on d2; u1 depends on root, u2 on u1; u1 also depends on side */ + private static List traceEdges() { + return List.of(edge("root", "d1"), edge("d1", "d2"), edge("u1", "root"), edge("u2", "u1"), + edge("u1", "side"), edge("other", "unrelated")); + } + + @Test + void traceFollowsDependencies() { + assertEquals(Set.of("root", "d1", "d2"), + CatalogDependencyGraphLayout.trace(traceEdges(), "root", Direction.DEPENDENCIES, null)); + assertEquals(Set.of("root", "d1"), + CatalogDependencyGraphLayout.trace(traceEdges(), "root", Direction.DEPENDENCIES, 1)); + assertEquals(Set.of("root"), + CatalogDependencyGraphLayout.trace(traceEdges(), "root", Direction.DEPENDENCIES, 0)); + } + + @Test + void traceFollowsDependents() { + assertEquals(Set.of("root", "u1", "u2"), + CatalogDependencyGraphLayout.trace(traceEdges(), "root", Direction.DEPENDENTS, null)); + assertEquals(Set.of("root", "u1"), + CatalogDependencyGraphLayout.trace(traceEdges(), "root", Direction.DEPENDENTS, 1)); + } + + @Test + void traceBothFollowsEachDirectionOnItsOwn() { + // side is a dependency of a dependent, so it is not reached + assertEquals(Set.of("root", "d1", "d2", "u1", "u2"), + CatalogDependencyGraphLayout.trace(traceEdges(), "root", Direction.BOTH, null)); + assertEquals(Set.of("root", "d1", "u1"), + CatalogDependencyGraphLayout.trace(traceEdges(), "root", Direction.BOTH, 1)); + } + + @Test + void traceHandlesCyclesAndKeepsTheLinksAmongTheNodes() { + List edges = List.of(edge("a", "b"), edge("b", "a"), edge("b", "c")); + Set reached = CatalogDependencyGraphLayout.trace(edges, "a", Direction.DEPENDENCIES, null); + assertEquals(Set.of("a", "b", "c"), reached); + assertEquals(3, CatalogDependencyGraphLayout.edgesAmong(edges, reached).size()); + assertEquals(List.of(edge("a", "b"), edge("b", "a")), + CatalogDependencyGraphLayout.edgesAmong(edges, Set.of("a", "b"))); + } + + @Test + void directionParsing() { + assertEquals(Direction.BOTH, Direction.parse(null)); + assertEquals(Direction.DEPENDENTS, Direction.parse(" dependents ")); + assertThrows(IllegalArgumentException.class, () -> Direction.parse("UP")); + assertThrows(IllegalArgumentException.class, + () -> CatalogDependencyGraphLayout.trace(traceEdges(), "root", Direction.BOTH, -1)); + } +} diff --git a/test/prerna/reactor/automation/project/AutomationProjectServiceUnitTests.java b/test/prerna/reactor/automation/project/AutomationProjectServiceUnitTests.java index 4086f40c9c3..0abc468865e 100644 --- a/test/prerna/reactor/automation/project/AutomationProjectServiceUnitTests.java +++ b/test/prerna/reactor/automation/project/AutomationProjectServiceUnitTests.java @@ -34,11 +34,15 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.when; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -46,17 +50,23 @@ import org.eclipse.jgit.api.Git; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; import prerna.auth.AccessToken; import prerna.auth.AuthProvider; import prerna.auth.User; +import prerna.auth.utils.CatalogDependencyDerivation; import prerna.auth.utils.SecurityEngineUtils; import prerna.auth.utils.SecurityProjectUtils; import prerna.engine.api.IEngine; +import prerna.project.api.IProject; import prerna.reactor.automation.AutomationConstants; +import prerna.reactor.automation.definition.AutomationDefinitionService; import prerna.reactor.automation.definition.AutomationDefinitionValidator; import prerna.reactor.automation.utils.AutomationRuntimeUtils; +import prerna.util.AssetUtility; +import prerna.util.Utility; /** Covers the owner-scoped run scope used by runs of inline definition JSON. */ public class AutomationProjectServiceUnitTests { @@ -186,6 +196,106 @@ void reportsGitFailureInsteadOfSilentlySavingWithoutHistory() throws Exception { assertEquals("Unable to commit Automation definition assets to version history.", error.getMessage()); } + /** + * Every definition mutation enters through saveDefinition, so the dependency + * sync belongs there rather than in one reactor: a granular step edit or a + * version restore records the same engines a full save does, and the nodes of a + * loop body count as much as the steps beside it. + */ + @Test + void saveRecordsTheEnginesOfNestedStepsAsAutomaticDependencies() throws Exception { + Path versionFolder = repositoryFolder.resolve("automation-version"); + Files.createDirectories(versionFolder); + Git.init().setDirectory(versionFolder.toFile()).call().close(); + User owner = user("owner"); + String definitionJson = loopDefinition(); + Path definitionFile = versionFolder.resolve("assets/automation-workflow.json"); + Files.createDirectories(definitionFile.getParent()); + Files.writeString(definitionFile, definitionJson); + AutomationDefinitionService.DefinitionFiles files = new AutomationDefinitionService.DefinitionFiles( + definitionJson, Map.of()); + IProject project = mock(IProject.class); + when(project.getProjectName()).thenReturn("Automation"); + + try (MockedStatic definitions = mockStatic(AutomationDefinitionService.class); + MockedStatic mcp = mockStatic(AutomationMcpSync.class); + MockedStatic utility = mockStatic(Utility.class); + MockedStatic assets = mockStatic(AssetUtility.class); + MockedStatic security = mockStatic(SecurityProjectUtils.class); + MockedStatic engines = mockStatic(SecurityEngineUtils.class); + MockedStatic dependencies = mockStatic( + CatalogDependencyDerivation.class)) { + definitions.when(() -> AutomationDefinitionService.load("automation-1")).thenReturn(files); + definitions.when(() -> AutomationDefinitionService.save("automation-1", definitionJson, Map.of())) + .thenReturn(files); + definitions.when(() -> AutomationDefinitionService.getArtifactPaths("automation-1")) + .thenReturn(List.of(definitionFile)); + utility.when(() -> Utility.getProject("automation-1")).thenReturn(project); + assets.when(() -> AssetUtility.getProjectAssetsFolder("automation-1")) + .thenReturn(repositoryFolder.toString()); + assets.when(() -> AssetUtility.getProjectVersionFolder("Automation", "automation-1")) + .thenReturn(versionFolder.toString()); + engines.when(() -> SecurityEngineUtils.userCanViewEngine(owner, "engine-1")).thenReturn(true); + engines.when(() -> SecurityEngineUtils.getEngineType("engine-1")).thenReturn(IEngine.CATALOG_TYPE.DATABASE); + + AutomationProjectService.saveDefinition("automation-1", definitionJson, Map.of(), null, owner); + + @SuppressWarnings("unchecked") + ArgumentCaptor>> synced = ArgumentCaptor.forClass(Collection.class); + dependencies.verify(() -> CatalogDependencyDerivation.syncAutomation(eq(owner), eq("automation-1"), + synced.capture())); + assertEquals(List.of("start", "work", "body-query"), + synced.getValue().stream() + .map(node -> String.valueOf(node.get(AutomationConstants.NODE_FIELD_ID))).toList()); + } + } + + /** A trigger, a for-each loop, and a database query inside the loop's body. */ + private static String loopDefinition() { + Map bodyNode = new LinkedHashMap<>(); + bodyNode.put(AutomationConstants.NODE_FIELD_ID, "body-query"); + bodyNode.put(AutomationConstants.NODE_FIELD_TYPE, AutomationConstants.NODE_DATABASE_QUERY); + bodyNode.put(AutomationConstants.NODE_FIELD_LABEL, "Read claims"); + bodyNode.put(AutomationConstants.NODE_FIELD_OUTPUT_VAR, "claims"); + bodyNode.put(AutomationConstants.NODE_FIELD_CODE_MODE, AutomationConstants.NODE_CODE_MODE_GENERATED); + bodyNode.put(AutomationConstants.NODE_FIELD_CONFIG, + Map.of(AutomationConstants.CONFIG_ENGINE_ID, "engine-1", "query", + "SELECT * FROM CLAIMS ORDER BY ID", AutomationConstants.CONFIG_LIMIT, 100)); + + Map loop = new LinkedHashMap<>(); + loop.put(AutomationConstants.NODE_FIELD_ID, "work"); + loop.put(AutomationConstants.NODE_FIELD_TYPE, AutomationConstants.NODE_CONTROL_LOOP); + loop.put(AutomationConstants.NODE_FIELD_LABEL, "For each claim"); + loop.put(AutomationConstants.NODE_FIELD_OUTPUT_VAR, "work_1"); + loop.put(AutomationConstants.NODE_FIELD_CODE_MODE, AutomationConstants.NODE_CODE_MODE_GENERATED); + loop.put(AutomationConstants.NODE_FIELD_CONFIG, + Map.of(AutomationConstants.CONFIG_LOOP_MODE, AutomationConstants.LOOP_MODE_FOR_EACH, + AutomationConstants.CONFIG_LOOP_ITEMS, List.of(1, 2), + AutomationConstants.CONFIG_LOOP_BATCH_SIZE, 1, + AutomationConstants.CONFIG_LOOP_MAX_ITERATIONS, 10)); + loop.put(AutomationConstants.NODE_FIELD_BODY, + Map.of(AutomationConstants.DOC_NODES, List.of(bodyNode), AutomationConstants.DOC_EDGES, List.of())); + + Map start = new LinkedHashMap<>(); + start.put(AutomationConstants.NODE_FIELD_ID, "start"); + start.put(AutomationConstants.NODE_FIELD_TYPE, AutomationConstants.NODE_START); + start.put(AutomationConstants.NODE_FIELD_LABEL, "Start"); + start.put(AutomationConstants.NODE_FIELD_CODE_MODE, AutomationConstants.NODE_CODE_MODE_GENERATED); + start.put(AutomationConstants.NODE_FIELD_CONFIG, Map.of()); + + Map edge = Map.of(AutomationConstants.NODE_FIELD_ID, "e-start-work", + AutomationConstants.EDGE_FIELD_KIND, AutomationConstants.EDGE_KIND_CONTROL, + AutomationConstants.EDGE_FIELD_SOURCE, "start", AutomationConstants.EDGE_FIELD_SOURCE_PORT, + AutomationConstants.CONTROL_PORT_OUT, AutomationConstants.EDGE_FIELD_TARGET, "work", + AutomationConstants.EDGE_FIELD_TARGET_PORT, AutomationConstants.CONTROL_PORT_IN); + + return AutomationRuntimeUtils.GSON.toJson(Map.of(AutomationConstants.DOC_FORMAT_VERSION, + AutomationConstants.PYTHON_DOC_CURRENT_VERSION, AutomationConstants.DOC_TRIGGER_BINDINGS, + List.of(Map.of("id", "manual", "type", "manual")), AutomationConstants.DOC_GRAPH, + Map.of(AutomationConstants.DOC_NODES, List.of(start, loop), AutomationConstants.DOC_EDGES, + List.of(edge)))); + } + @Test void agentRunWithoutAWorkspaceSkipsOnlyTheWorkspaceCheck() { User owner = user("owner"); From fd624fe40c7d9632a156c64dd2ccc5b698b0b278 Mon Sep 17 00:00:00 2001 From: Neel Date: Fri, 20 Nov 2026 13:47:21 -0500 Subject: [PATCH 4/6] feat: loading dependencies in an app --- .../utils/SecurityCatalogDependencyUtils.java | 27 +++++++++++++++++++ .../reactor/project/LoadAppReactor.java | 15 ++++++++--- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java b/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java index b1976aa264f..ac554c6ba69 100644 --- a/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java +++ b/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java @@ -745,6 +745,33 @@ private static List> getDirectDependencies(String catalogId) return QueryExecutionUtility.flushRsToMap(securityDb, qs); } + /** + * The named dependencies of a catalog item: its manual links that have a + * dependency name, so an app's code can find a dependency by that name. + * Automatic links have no name and are left out. + * + * @param catalogId the engine id or project id + * @return each dependency id keyed by its dependency name + */ + public static Map getNamedDependencies(String catalogId) { + IRDBMSEngine securityDb = SystemEngineRegistry.getSecurityDb(); + SelectQueryStruct qs = new SelectQueryStruct(); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__NAME", "dependency_name")); + qs.addSelector(new QueryColumnSelector("CATALOGDEPENDENCIES__DEPENDENCYID", "catalog_id")); + qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("CATALOGDEPENDENCIES__CATALOGID", "==", catalogId)); + qs.addExplicitFilter(SimpleQueryFilter.makeColToValFilter("CATALOGDEPENDENCIES__ROLE", "==", + CatalogDependencyRole.MANUAL.name())); + Map named = new HashMap<>(); + for (Map row : QueryExecutionUtility.flushRsToMap(securityDb, qs)) { + Object name = row.get("dependency_name"); + Object id = row.get("catalog_id"); + if (name instanceof String && !((String) name).trim().isEmpty() && id instanceof String) { + named.put(((String) name).trim(), (String) id); + } + } + return named; + } + private static void collect(String catalogId, boolean subdependencies, Set visited, List> all, java.util.function.Function>> direct) { if (!visited.add(catalogId)) { diff --git a/src/prerna/reactor/project/LoadAppReactor.java b/src/prerna/reactor/project/LoadAppReactor.java index 84dfd268332..c0da0d47ea2 100644 --- a/src/prerna/reactor/project/LoadAppReactor.java +++ b/src/prerna/reactor/project/LoadAppReactor.java @@ -27,6 +27,10 @@ *******************************************************************************/ package prerna.reactor.project; +import java.util.HashMap; +import java.util.Map; + +import prerna.auth.utils.SecurityCatalogDependencyUtils; import prerna.reactor.AbstractReactor; import prerna.reactor.ReactorDefinition; import prerna.sablecc2.om.PixelDataType; @@ -63,14 +67,19 @@ public NounMetadata execute() { return getError("User does not have access to load the app " + context); } - return new NounMetadata("Successfully set app context to '" + context, PixelDataType.CONST_STRING, - PixelOperationType.OPERATION); + // the app's named dependencies, so its code can look an engine up by the + // name its owner gave the dependency rather than hardcoding the id + Map result = new HashMap<>(); + result.put("message", "Successfully set app context to '" + context + "'"); + result.put("dependencies", SecurityCatalogDependencyUtils.getNamedDependencies(context)); + return new NounMetadata(result, PixelDataType.MAP, PixelOperationType.OPERATION); } @Override public ReactorDefinition getReactorDefinition() { return super.getReactorDefinition().description( - "Set the context for the insight in order to have access to app assets including custom reactors and python scripts"); + "Set the context for the insight in order to have access to app assets including custom reactors and python scripts. " + + "Returns message and dependencies: the app's named dependencies, each dependency name mapped to its engine or project id"); } } From c2a499ee956663cc8a1ddbd1d44d6d6c511e2479 Mon Sep 17 00:00:00 2001 From: Neel Date: Mon, 23 Nov 2026 09:19:03 -0500 Subject: [PATCH 5/6] feat: cleaning up dependencies --- .../utils/SecurityCatalogDependencyUtils.java | 38 ++++++++++++++++ .../GetCatalogDependenciesReactor.java | 2 + ...curityCatalogDependencyUtilsUnitTests.java | 43 +++++++++++++++++++ test/prerna/util/SignedInTasksUnitTests.java | 27 ++++++++++++ 4 files changed, 110 insertions(+) diff --git a/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java b/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java index ac554c6ba69..b3566132431 100644 --- a/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java +++ b/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java @@ -841,6 +841,44 @@ private static List> getDirectDependents(String dependencyId return normalizeLinks(QueryExecutionUtility.flushRsToMap(securityDb, qs)); } + /** The fields of an item a user who cannot see it must not be sent */ + private static final String[] PRIVATE_DEPENDENCY_KEYS = { "catalog_name", "description", "tags", + "catalog_subtype", "catalog_date_created" }; + + /** + * Whether a dependency is private to the user: they have no permission on it, + * directly or through a team, and it is neither public nor discoverable. + * + * @param node a dependency as {@link #getDependencyDetails(String, User, boolean)} + * returns it + * @return true when the user may not see what it is + */ + public static boolean isPrivateDependency(Map node) { + return node.get("permission") == null && node.get("group_permission") == null + && !Boolean.TRUE.equals(node.get("catalog_global")) + && !Boolean.TRUE.equals(node.get("catalog_discoverable")); + } + + /** + * Removes what a dependency is (its name, description, tags, subtype and date + * created) when it is private to the user, and marks every dependency with + * is_private. Its id and type stay, since the owner's links name them and a + * save of the owner's manual dependencies sends them back. + * + * @param node a dependency, changed in place + * @return the same map + */ + public static Map redactPrivateDependency(Map node) { + boolean isPrivate = isPrivateDependency(node); + if (isPrivate) { + for (String key : PRIVATE_DEPENDENCY_KEYS) { + node.remove(key); + } + } + node.put("is_private", isPrivate); + return node; + } + /** * Whether a user can view each dependency of a catalog item, all the way down * diff --git a/src/prerna/reactor/security/GetCatalogDependenciesReactor.java b/src/prerna/reactor/security/GetCatalogDependenciesReactor.java index da724e7d14e..42489f03ab5 100644 --- a/src/prerna/reactor/security/GetCatalogDependenciesReactor.java +++ b/src/prerna/reactor/security/GetCatalogDependenciesReactor.java @@ -162,6 +162,8 @@ private Map buildDependencyGraph(List> depen engine.put("dependencies", reachableChildren); } + // a dependency the user cannot see is sent as its id and type only + SecurityCatalogDependencyUtils.redactPrivateDependency(engine); engines.add(engine); } diff --git a/test/prerna/auth/utils/SecurityCatalogDependencyUtilsUnitTests.java b/test/prerna/auth/utils/SecurityCatalogDependencyUtilsUnitTests.java index 3a3bde9b54c..c169a42a538 100644 --- a/test/prerna/auth/utils/SecurityCatalogDependencyUtilsUnitTests.java +++ b/test/prerna/auth/utils/SecurityCatalogDependencyUtilsUnitTests.java @@ -184,6 +184,49 @@ void manualAndAutomaticDependenciesAreSavedApart() { assertEquals(List.of("function1"), ids(SecurityCatalogDependencyUtils.getDependencies("automation1"))); } + private static Map dependencyNode(Integer permission, Integer groupPermission, Boolean global, + Boolean discoverable) { + Map node = new HashMap<>(); + node.put("catalog_id", "db1"); + node.put("catalog_type", "DATABASE"); + node.put("catalog_name", "Payroll"); + node.put("description", "Salaries"); + node.put("tags", "hr"); + node.put("catalog_subtype", "H2_DB"); + node.put("catalog_date_created", "2026-01-01"); + node.put("permission", permission); + node.put("group_permission", groupPermission); + node.put("catalog_global", global); + node.put("catalog_discoverable", discoverable); + return node; + } + + @Test + void redactPrivateDependency_removesWhatAPrivateItemIs() { + Map node = SecurityCatalogDependencyUtils + .redactPrivateDependency(dependencyNode(null, null, false, false)); + assertEquals(Boolean.TRUE, node.get("is_private")); + assertEquals("db1", node.get("catalog_id")); + assertEquals("DATABASE", node.get("catalog_type")); + for (String key : List.of("catalog_name", "description", "tags", "catalog_subtype", + "catalog_date_created")) { + assertFalse(node.containsKey(key), key); + } + } + + @Test + void redactPrivateDependency_keepsItemsTheUserCanSee() { + List> visible = List.of(dependencyNode(null, null, false, true), + dependencyNode(null, null, true, false), dependencyNode(3, null, false, false), + dependencyNode(null, 2, false, false)); + for (Map node : visible) { + SecurityCatalogDependencyUtils.redactPrivateDependency(node); + assertEquals(Boolean.FALSE, node.get("is_private")); + assertEquals("Payroll", node.get("catalog_name")); + assertEquals("Salaries", node.get("description")); + } + } + @Test void syncAutomaticDependencies_replacesOnlyItsOwnRoles() { UnitTestSecurityAuthUtils.createEngine("guardrail1", "Guardrail", IEngine.CATALOG_TYPE.GUARDRAIL, owner); diff --git a/test/prerna/util/SignedInTasksUnitTests.java b/test/prerna/util/SignedInTasksUnitTests.java index e204a1563fb..6fa8f34cd75 100644 --- a/test/prerna/util/SignedInTasksUnitTests.java +++ b/test/prerna/util/SignedInTasksUnitTests.java @@ -1,3 +1,30 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ package prerna.util; import static org.junit.jupiter.api.Assertions.assertEquals; From 9d1af601bfaf915700d0c720df3083ea69cbdc47 Mon Sep 17 00:00:00 2001 From: Neel Date: Mon, 23 Nov 2026 11:52:23 -0500 Subject: [PATCH 6/6] feat: re-sync catalog dependencies per item and read more SMSS keys - SyncCatalogDependencies re-derives one engine's or project's automatic dependencies from its configuration, for its editors, and returns how many it has. The admin backfill shares the same per-item code (CatalogDependencyResync). - A re-sync throws instead of clearing links when an agent's, automation's, blocks app's or router's configuration can't be read, and an engine's dependencies are written in one transaction. - The guardrail config save records guardrails before releasing locks that can fail; an uploaded engine records its dependencies from its files without loading it. - fromSmss also reads KEYWORD_ENGINE_ID, CUSTOM_DOCUMENT_PROCESSOR_FUNCTION_ID, the proxy TARGET_ENGINE_ID, IMAGE_ENGINE_ID, S3BUCKETENGINEID and the ENCODER_ID fallback, with the roles KEYWORD_ENGINE, DOCUMENT_PROCESSOR, PROXY_TARGET and IMAGE_MODEL. Co-Authored-By: Claude Opus 5.5 --- .../utils/CatalogDependencyDerivation.java | 52 ++- .../auth/utils/CatalogDependencyResync.java | 434 ++++++++++++++++++ .../auth/utils/CatalogDependencyRole.java | 8 + .../utils/SecurityCatalogDependencyUtils.java | 21 + .../vector/ProxyVectorDatabaseEngine.java | 2 +- .../UpdateEngineGuardrailConfigReactor.java | 4 +- .../reactor/engine/UploadEngineReactor.java | 12 + ...minBackfillCatalogDependenciesReactor.java | 145 +----- .../SyncCatalogDependenciesReactor.java | 103 +++++ .../CatalogDependencyDerivationUnitTests.java | 73 ++- .../CatalogDependencyResyncUnitTests.java | 326 +++++++++++++ ...ncCatalogDependenciesReactorUnitTests.java | 93 ++++ 12 files changed, 1127 insertions(+), 146 deletions(-) create mode 100644 src/prerna/auth/utils/CatalogDependencyResync.java create mode 100644 src/prerna/reactor/security/SyncCatalogDependenciesReactor.java create mode 100644 test/prerna/auth/utils/CatalogDependencyResyncUnitTests.java create mode 100644 test/prerna/reactor/security/SyncCatalogDependenciesReactorUnitTests.java diff --git a/src/prerna/auth/utils/CatalogDependencyDerivation.java b/src/prerna/auth/utils/CatalogDependencyDerivation.java index 2647abb9626..aad2d76f2cf 100644 --- a/src/prerna/auth/utils/CatalogDependencyDerivation.java +++ b/src/prerna/auth/utils/CatalogDependencyDerivation.java @@ -44,6 +44,8 @@ import prerna.auth.User; import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; import prerna.engine.api.IEngine; +import prerna.engine.impl.vector.ProxyVectorDatabaseEngine; +import prerna.util.Constants; /** * Works out the automatic dependencies of a catalog item from its own @@ -63,7 +65,9 @@ public final class CatalogDependencyDerivation { /** The roles read from an engine's smss */ public static final List SMSS_ROLES = List.of(CatalogDependencyRole.JUDGE_MODEL, - CatalogDependencyRole.TOPIC_VECTOR, CatalogDependencyRole.EMBEDDER, CatalogDependencyRole.FUNCTION_STORAGE); + CatalogDependencyRole.TOPIC_VECTOR, CatalogDependencyRole.EMBEDDER, CatalogDependencyRole.FUNCTION_STORAGE, + CatalogDependencyRole.KEYWORD_ENGINE, CatalogDependencyRole.DOCUMENT_PROCESSOR, + CatalogDependencyRole.PROXY_TARGET, CatalogDependencyRole.IMAGE_MODEL); /** The roles read from a model router's router.json */ public static final List ROUTER_ROLES = List.of(CatalogDependencyRole.ROUTE_MODEL, CatalogDependencyRole.ROUTER_CLASSIFIER, CatalogDependencyRole.ROUTER_EMBEDDINGS, @@ -74,9 +78,26 @@ public final class CatalogDependencyDerivation { /** The smss key of the vector database an On Topic guardrail compares with */ static final String VECTOR_ENGINE_ID = "VECTOR_ENGINE_ID"; /** The smss key of the model a vector database embeds with */ - static final String EMBEDDER_ENGINE_ID = "EMBEDDER_ENGINE_ID"; + static final String EMBEDDER_ENGINE_ID = Constants.EMBEDDER_ENGINE_ID; + /** + * The legacy smss key of a vector database's embedding model, read only when + * {@link #EMBEDDER_ENGINE_ID} is not set, as the vector database reads it + */ + static final String ENCODER_ID = "ENCODER_ID"; + /** The smss key of the model a vector database generates keywords with */ + static final String KEYWORD_ENGINE_ID = Constants.KEYWORD_ENGINE_ID; + /** The smss key that turns on a vector database's custom document processor */ + static final String CUSTOM_DOCUMENT_PROCESSOR = Constants.CUSTOM_DOCUMENT_PROCESSOR; + /** The smss key of the function a vector database processes its documents with */ + static final String CUSTOM_DOCUMENT_PROCESSOR_FUNCTION_ID = Constants.CUSTOM_DOCUMENT_PROCESSOR_FUNCTION_ID; + /** The smss key of the vector database a proxy vector database calls */ + static final String TARGET_ENGINE_ID = ProxyVectorDatabaseEngine.TARGET_ENGINE_ID; /** The smss key of the storage engine a Google bucket function reads */ static final String GOOGLE_BUCKET_ENGINEID = "GOOGLE_BUCKET_ENGINEID"; + /** The smss key of the storage engine an AWS Textract or Transcribe function reads */ + static final String S3BUCKETENGINEID = "S3BUCKETENGINEID"; + /** The smss key of the model an image description function describes images with */ + static final String IMAGE_ENGINE_ID = Constants.IMAGE_ENGINE_ID; private CatalogDependencyDerivation() { @@ -129,8 +150,9 @@ public static List fromGuardrailPipelines(Map pipelines, Unary /** * The engines an engine's smss names: a guardrail's judge model or vector - * database, a vector database's embedding model, and a Google bucket function's - * storage engine. + * database; a vector database's embedding model, keyword model, document + * processor function, or a proxy's target vector database; and a function's + * Google or S3 bucket storage engine or image description model. * * @param engineType the engine's type, such as GUARDRAIL * @param smss its smss properties or creation details @@ -149,11 +171,31 @@ public static List fromSmss(String engineType, Map smss, Unary add(dependencies, typeOf, trimmed(smss.get(VECTOR_ENGINE_ID)), CatalogDependencyRole.TOPIC_VECTOR, "Vector database this guardrail compares text with to stay on topic"); } else if (IEngine.CATALOG_TYPE.VECTOR.name().equals(type)) { - add(dependencies, typeOf, trimmed(smss.get(EMBEDDER_ENGINE_ID)), CatalogDependencyRole.EMBEDDER, + // the vector database falls back to the legacy key only when the current one + // is not set + String embedderId = trimmed(smss.get(EMBEDDER_ENGINE_ID)); + if (embedderId == null) { + embedderId = trimmed(smss.get(ENCODER_ID)); + } + add(dependencies, typeOf, embedderId, CatalogDependencyRole.EMBEDDER, "Model that creates this vector database's embeddings"); + add(dependencies, typeOf, trimmed(smss.get(KEYWORD_ENGINE_ID)), CatalogDependencyRole.KEYWORD_ENGINE, + "Model that generates keywords for this vector database's documents"); + // the processor function is called only when the custom processor is on + if (Boolean.parseBoolean(trimmed(smss.get(CUSTOM_DOCUMENT_PROCESSOR)))) { + add(dependencies, typeOf, trimmed(smss.get(CUSTOM_DOCUMENT_PROCESSOR_FUNCTION_ID)), + CatalogDependencyRole.DOCUMENT_PROCESSOR, + "Function that processes this vector database's documents"); + } + add(dependencies, typeOf, trimmed(smss.get(TARGET_ENGINE_ID)), CatalogDependencyRole.PROXY_TARGET, + "Vector database this proxy sends its calls to"); } else if (IEngine.CATALOG_TYPE.FUNCTION.name().equals(type)) { add(dependencies, typeOf, trimmed(smss.get(GOOGLE_BUCKET_ENGINEID)), CatalogDependencyRole.FUNCTION_STORAGE, "Storage engine this function reads its bucket from"); + add(dependencies, typeOf, trimmed(smss.get(S3BUCKETENGINEID)), CatalogDependencyRole.FUNCTION_STORAGE, + "Storage engine this function reads its bucket from"); + add(dependencies, typeOf, trimmed(smss.get(IMAGE_ENGINE_ID)), CatalogDependencyRole.IMAGE_MODEL, + "Model that describes the images this function finds in documents"); } return dependencies; } diff --git a/src/prerna/auth/utils/CatalogDependencyResync.java b/src/prerna/auth/utils/CatalogDependencyResync.java new file mode 100644 index 00000000000..2b998880c3a --- /dev/null +++ b/src/prerna/auth/utils/CatalogDependencyResync.java @@ -0,0 +1,434 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.auth.utils; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import com.google.gson.Gson; +import com.google.gson.JsonParseException; + +import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; +import prerna.engine.api.IEngine; +import prerna.engine.impl.model.ModelRouterEngine; +import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils; +import prerna.engine.impl.pipeline.EngineProxyFactory; +import prerna.project.api.IProject; +import prerna.project.impl.ProjectHelper; +import prerna.project.impl.notebook.INotebookHelper; +import prerna.project.impl.notebook.NotebookHelperFactory; +import prerna.reactor.automation.AutomationConstants; +import prerna.reactor.automation.definition.AutomationDefinitionService; +import prerna.util.AssetUtility; +import prerna.util.Constants; +import prerna.util.EngineUtility; +import prerna.util.Utility; + +/** + * Works out the automatic dependencies of one catalog item again from what it + * has saved, and records them: an engine's smss references, guardrails and model + * router routes; an agent's tools, knowledge, skills, model and subagents; an + * automation's nodes; a blocks app's engines; and the ids in a code app's files. + * Picked dependencies are kept. + * + *

+ * Unlike the syncs a save runs in {@link CatalogDependencyDerivation}, which only + * log, a resync throws when the item cannot be read or its dependencies cannot be + * recorded, so the caller can report it. A resync never clears an item's + * dependencies because its configuration could not be read: an item that is + * missing, or whose saved configuration is present but cannot be parsed (an + * agent's config json, an automation's definition, a blocks app's blocks json, + * an engine's pipeline.json or router.json), throws before anything is written. + * Only an item that has genuinely saved nothing, such as an agent with no config + * json or a blocks app with no blocks json, has the dependencies it derives + * cleared. + *

+ * + *

+ * An engine's smss, guardrail and router dependencies are worked out first and + * then recorded in one transaction, so a malformed pipeline.json or router.json + * leaves all of them as they were. + *

+ */ +public final class CatalogDependencyResync { + + private CatalogDependencyResync() { + + } + + /** + * Works out and records the automatic dependencies of a catalog item. A project + * type with nothing to derive, such as SKILL or INSIGHTS, is left as it is. + * + * @param user who asks, recorded on each row + * @param catalogId the engine id or project id + * @param catalogType its engine type or project type, or null to read it from + * the security database + * @throws IllegalArgumentException when no engine or project has the id + * @throws IllegalStateException when the item, or its saved configuration, + * cannot be read; nothing is written then + * @throws Exception when the item cannot be read or its + * dependencies cannot be recorded + */ + public static void resync(User user, String catalogId, String catalogType) throws Exception { + String type = catalogType == null || catalogType.isBlank() ? CatalogTypes.resolve(catalogId) + : CatalogTypes.normalize(catalogType); + if (type == null) { + throw new IllegalArgumentException("No engine or project has the id " + catalogId); + } + if (!CatalogTypes.isProjectType(type)) { + resyncEngine(user, catalogId); + return; + } + IProject.PROJECT_TYPE projectType = IProject.PROJECT_TYPE.valueOf(type); + switch (projectType) { + case WORKSPACE -> resyncWorkspace(user, catalogId); + case AUTOMATION -> resyncAutomation(user, catalogId); + case BLOCKS -> resyncBlocks(user, catalogId); + case CODE -> resyncCode(user, catalogId); + default -> { + // nothing is derived from its configuration + } + } + } + + /** + * An engine's smss references, the guardrails its pipeline.json runs (but for + * a guardrail's own), and a model router's routes, recorded in one transaction + */ + public static void resyncEngine(User user, String engineId) throws Exception { + IEngine engine = Utility.getEngine(engineId); + if (engine == null) { + throw new IllegalStateException("Engine " + engineId + " could not be loaded"); + } + resyncEngine(user, engine); + } + + /** {@link #resyncEngine(User, String)} for an engine already loaded */ + static void resyncEngine(User user, IEngine engine) throws IOException { + Properties smss = engine.getSmssProp(); + String pipelineName = pipelineFileName(smss); + File pipelineFile = pipelineName == null ? null : EngineProxyFactory.pipelineFile(engine, pipelineName); + File routerConfigFile = engine instanceof ModelRouterEngine router ? router.resolveConfigFile() : null; + record(user, engine.getEngineId(), engine.getCatalogType(), smss, pipelineFile, routerConfigFile); + } + + /** + * Records an engine's automatic dependencies from its smss and the files in its + * folder, without loading the engine, as an upload has them: its smss + * references, the guardrails its pipeline.json runs and, for a model router, + * the routes in its router.json. + * + * @param user who uploads, recorded on each row + * @param engineId the engine id + * @param engineName the engine name, which names its folder + * @param engineType its catalog type + * @param smss its smss properties + * @throws IOException when its pipeline.json or router.json cannot + * be read + * @throws IllegalStateException when its pipeline.json or router.json cannot be + * parsed; nothing is written then + */ + public static void resyncEngineFromFiles(User user, String engineId, String engineName, + IEngine.CATALOG_TYPE engineType, Properties smss) throws IOException { + if (engineType == null || smss == null) { + return; + } + // the same files EngineProxyFactory.pipelineFile and + // ModelRouterEngine.resolveConfigFile find for the loaded engine + String assetsFolder = EngineUtility.getSpecificEngineAssetsFolder(engineType, engineId, engineName); + String pipelineName = pipelineFileName(smss); + File pipelineFile = pipelineName == null ? null + : new File((assetsFolder + "/" + pipelineName).replace("\\", "/")); + File routerConfigFile = null; + if (isModelRouter(smss)) { + String configName = smss.getProperty(ModelRouterEngine.ROUTER_CONFIG); + if (configName == null || configName.isBlank()) { + configName = ModelRouterEngine.DEFAULT_CONFIG_FILE; + } + String routerAssetsFolder = EngineUtility.getSpecificEngineAssetsFolder(IEngine.CATALOG_TYPE.MODEL, + engineId, engineName); + routerConfigFile = new File((routerAssetsFolder + "/" + configName.trim()).replace("\\", "/")); + } + record(user, engineId, engineType, smss, pipelineFile, routerConfigFile); + } + + /** + * Works out every automatic dependency of an engine, then writes them once. The + * guardrail role applies to every engine but a guardrail; the router roles + * apply only to a model router whose router.json exists. + */ + private static void record(User user, String engineId, IEngine.CATALOG_TYPE catalogType, Properties smss, + File pipelineFile, File routerConfigFile) throws IOException { + String engineType = catalogType.name(); + Set roles = new LinkedHashSet<>(CatalogDependencyDerivation.SMSS_ROLES); + List dependencies = new ArrayList<>( + CatalogDependencyDerivation.fromSmss(engineType, smss, CatalogTypes::resolve)); + + if (catalogType != IEngine.CATALOG_TYPE.GUARDRAIL) { + roles.add(CatalogDependencyRole.GUARDRAIL); + dependencies.addAll(CatalogDependencyDerivation.fromGuardrailPipelines(readPipelines(engineId, pipelineFile), + CatalogTypes::resolve)); + } + + if (routerConfigFile != null && routerConfigFile.isFile()) { + roles.addAll(CatalogDependencyDerivation.ROUTER_ROLES); + dependencies.addAll(CatalogDependencyDerivation.fromRouterConfig(readRouterConfig(engineId, routerConfigFile), + CatalogTypes::resolve)); + } + + SecurityCatalogDependencyUtils.syncAutomaticDependencies(user, engineId, engineType, roles, dependencies); + } + + /** The pipeline.json an engine's smss names, or null for none */ + private static String pipelineFileName(Properties smss) { + String name = smss == null ? null : smss.getProperty(IEngine.PIPELINE); + return name == null || name.isBlank() ? null : name.trim(); + } + + /** Whether an engine's smss names a model router class, without loading the engine */ + private static boolean isModelRouter(Properties smss) { + String className = smss.getProperty(Constants.ENGINE_TYPE); + if (className == null || className.isBlank()) { + return false; + } + try { + Class engineClass = Class.forName(className.trim(), false, CatalogDependencyResync.class.getClassLoader()); + return ModelRouterEngine.class.isAssignableFrom(engineClass); + } catch (ClassNotFoundException | LinkageError e) { + return false; + } + } + + /** + * The pipelines a pipeline.json holds. An engine without one, or whose named + * file does not exist, runs no guardrails. + */ + @SuppressWarnings("unchecked") + private static Map readPipelines(String engineId, File pipelineFile) throws IOException { + if (pipelineFile == null || !pipelineFile.isFile()) { + return Map.of(); + } + Map config; + try { + config = new Gson().fromJson(Files.readString(pipelineFile.toPath(), StandardCharsets.UTF_8), Map.class); + } catch (JsonParseException e) { + throw new IllegalStateException( + "The pipeline configuration of engine " + engineId + " could not be parsed: " + e.getMessage(), e); + } + if (config != null && config.get("pipelines") instanceof Map read) { + return (Map) read; + } + return Map.of(); + } + + /** A model router's router.json, which the router cannot run without */ + @SuppressWarnings("unchecked") + private static Map readRouterConfig(String engineId, File configFile) throws IOException { + Map config; + try { + config = new Gson().fromJson(Files.readString(configFile.toPath(), StandardCharsets.UTF_8), Map.class); + } catch (JsonParseException e) { + throw new IllegalStateException( + "The router configuration of engine " + engineId + " could not be parsed: " + e.getMessage(), e); + } + if (config == null) { + throw new IllegalStateException("The router configuration of engine " + engineId + " is empty"); + } + return config; + } + + /** + * An agent's tools, knowledge, skills, model and subagents. An agent with no + * config json records no model or subagents. + * + * @throws IllegalStateException when the agent has no workspace row, or its + * config json cannot be parsed + */ + public static void resyncWorkspace(User user, String workspaceId) { + JSONObject config = readWorkspaceConfig(workspaceId); + List> resources = ModelInferenceLogsUtils.getWorkspaceResourcesByType(workspaceId, null); + String modelId = config == null ? null : config.optString("model_id", null); + List subagentIds = new ArrayList<>(); + JSONArray subagents = config == null ? null : config.optJSONArray("subagents"); + if (subagents != null) { + for (int i = 0; i < subagents.length(); i++) { + JSONObject subagent = subagents.optJSONObject(i); + if (subagent != null) { + subagentIds.add(subagent.optString("workspaceId", null)); + } + } + } + List dependencies = CatalogDependencyDerivation.fromWorkspace(resources, modelId, subagentIds, + CatalogTypes::resolve); + SecurityCatalogDependencyUtils.syncAutomaticDependencies(user, workspaceId, + IProject.PROJECT_TYPE.WORKSPACE.name(), CatalogDependencyDerivation.WORKSPACE_ROLES, dependencies); + } + + /** + * An agent's saved config json, or null when it has none. Read from the row + * itself, since ModelInferenceLogsUtils.getWorkspaceConfigJson gives null for + * a missing row and an unparseable value too. + */ + private static JSONObject readWorkspaceConfig(String workspaceId) { + Map row = ModelInferenceLogsUtils.getWorkspaceEntry(workspaceId); + if (row == null) { + throw new IllegalStateException("Agent " + workspaceId + " could not be read"); + } + Object raw = row.get("config_json"); + String text = raw == null ? null : String.valueOf(raw).trim(); + if (text == null || text.isEmpty()) { + return null; + } + try { + return new JSONObject(text); + } catch (JSONException e) { + throw new IllegalStateException( + "The configuration of agent " + workspaceId + " could not be parsed: " + e.getMessage(), e); + } + } + + /** + * The engines, apps and agents an automation's nodes use. A workflow with no + * nodes records none. + * + * @throws IllegalStateException when the automation, or its saved definition, + * cannot be found or parsed + */ + @SuppressWarnings("unchecked") + public static void resyncAutomation(User user, String projectId) { + IProject project = Utility.getProject(projectId); + if (project == null) { + throw new IllegalStateException("Automation " + projectId + " could not be loaded"); + } + // AutomationDefinitionService.load gives an empty workflow when the file is + // missing, which would clear the nodes + File definitionFile = new File(AssetUtility.getProjectAssetsFolder(project.getProjectName(), projectId), + AutomationConstants.AUTOMATION_PYTHON_DEFINITION_FILE_NAME); + if (!definitionFile.isFile()) { + throw new IllegalStateException("Automation " + projectId + " has no saved definition"); + } + String definition; + Map parsed; + try { + definition = AutomationDefinitionService.load(projectId).definition(); + parsed = definition == null || definition.isBlank() ? null : new Gson().fromJson(definition, Map.class); + } catch (IllegalArgumentException | JsonParseException e) { + throw new IllegalStateException( + "The definition of automation " + projectId + " could not be parsed: " + e.getMessage(), e); + } + if (parsed == null) { + throw new IllegalStateException("The definition of automation " + projectId + " is empty"); + } + List> nodes = new ArrayList<>(); + if (parsed.get("nodes") instanceof List list) { + for (Object node : list) { + if (node instanceof Map nodeMap) { + nodes.add((Map) nodeMap); + } + } + } + SecurityCatalogDependencyUtils.syncAutomaticDependencies(user, projectId, + IProject.PROJECT_TYPE.AUTOMATION.name(), List.of(CatalogDependencyRole.AUTOMATION_NODE), + CatalogDependencyDerivation.fromAutomationNodes(nodes, CatalogTypes::resolve)); + } + + /** + * A blocks app's BLOCK_ENGINE dependencies, read from its saved blocks json as + * SaveAppBlocksJson records them. An app with no blocks json records none. + * + * @throws IllegalStateException when the app cannot be loaded, or its blocks + * json cannot be read or parsed + */ + public static void resyncBlocks(User user, String projectId) { + IProject project = Utility.getProject(projectId); + if (project == null) { + throw new IllegalStateException("Blocks app " + projectId + " could not be loaded"); + } + // read the file here: Project.getEngineDependencies gives null both for no + // blocks json and for one it cannot read + File blocksFile = new File(AssetUtility.getProjectPortalsFolder(project.getProjectName(), projectId), + IProject.BLOCK_FILE_NAME); + Set engineIds = new HashSet<>(); + if (blocksFile.isFile()) { + Map engines; + try { + engines = NotebookHelperFactory.getNotebookHelper(blocksFile).getBlocksEngineDependencies(); + } catch (IOException | RuntimeException e) { + throw new IllegalStateException( + "The blocks of app " + projectId + " could not be read: " + e.getMessage(), e); + } + if (engines != null) { + engineIds.addAll(engines.values()); + } + } + engineIds.remove(INotebookHelper.UNDEFINED_VALUE); + SecurityCatalogDependencyUtils.syncAutomaticDependencyIds(user, projectId, IProject.PROJECT_TYPE.BLOCKS.name(), + CatalogDependencyRole.BLOCK_ENGINE, "Engine a block of this app uses", engineIds); + } + + /** + * A code app's CODE_REFERENCE dependencies: the engine and project ids found in + * its files, as ExtractAndSetDependencies records them for the whole app + * + * @throws IllegalStateException when the app cannot be loaded or has no assets + * folder + */ + @SuppressWarnings("unchecked") + public static void resyncCode(User user, String projectId) { + IProject project = Utility.getProject(projectId); + if (project == null) { + throw new IllegalStateException("Code app " + projectId + " could not be loaded"); + } + File assets = new File(EngineUtility.getSpecificEngineAssetsFolder(IEngine.CATALOG_TYPE.PROJECT, + project.getProjectId(), project.getProjectName())); + if (!assets.isDirectory()) { + throw new IllegalStateException("The files of code app " + projectId + " could not be found"); + } + Map found = ProjectHelper.extractEngineIdsFromProjectFolder(assets); + Set ids = found.get("success") instanceof Map success + ? ((Map) success).keySet() + : Set.of(); + SecurityCatalogDependencyUtils.syncAutomaticDependencyIds(user, projectId, IProject.PROJECT_TYPE.CODE.name(), + CatalogDependencyRole.CODE_REFERENCE, "Engine referenced in this app's files", ids); + } +} diff --git a/src/prerna/auth/utils/CatalogDependencyRole.java b/src/prerna/auth/utils/CatalogDependencyRole.java index b06d4de5276..1be01bcd9c5 100644 --- a/src/prerna/auth/utils/CatalogDependencyRole.java +++ b/src/prerna/auth/utils/CatalogDependencyRole.java @@ -61,6 +61,14 @@ public enum CatalogDependencyRole { EMBEDDER, /** The storage engine a function reads its bucket from */ FUNCTION_STORAGE, + /** The model a vector database generates keywords with */ + KEYWORD_ENGINE, + /** The function a vector database processes its documents with */ + DOCUMENT_PROCESSOR, + /** The vector database a proxy vector database sends its calls to */ + PROXY_TARGET, + /** The model a function describes images with */ + IMAGE_MODEL, /** A model a router sends a route to */ ROUTE_MODEL, diff --git a/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java b/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java index b3566132431..6097be54039 100644 --- a/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java +++ b/src/prerna/auth/utils/SecurityCatalogDependencyUtils.java @@ -466,6 +466,27 @@ public static void removeAutomaticDependency(String catalogId, String dependency }); } + /** + * How many automatic dependency rows a catalog item has, one for each + * dependency and role + * + * @param catalogId the engine id or project id + * @return the count of its automatic rows + * @throws IllegalStateException when they cannot be counted + */ + public static int countAutomaticDependencies(String catalogId) { + try { + Integer count = QueryExecutionUtility.queryOne(SystemEngineRegistry.getSecurityDb(), + "SELECT COUNT(*) FROM " + TABLE + " WHERE CATALOGID=? AND IS_AUTOMATIC = ?", ps -> { + ps.setString(1, catalogId); + ps.setBoolean(2, true); + }, rs -> rs.getInt(1)); + return count == null ? 0 : count; + } catch (Exception e) { + throw new IllegalStateException("Unable to count the automatic dependencies of " + catalogId, e); + } + } + /** * Replaces every dependency of a catalog item, picked and automatic, with the * ones given, as they are, in one transaction. For an item that was just diff --git a/src/prerna/engine/impl/vector/ProxyVectorDatabaseEngine.java b/src/prerna/engine/impl/vector/ProxyVectorDatabaseEngine.java index 44cd31a72ff..0b1806a1223 100644 --- a/src/prerna/engine/impl/vector/ProxyVectorDatabaseEngine.java +++ b/src/prerna/engine/impl/vector/ProxyVectorDatabaseEngine.java @@ -64,7 +64,7 @@ public class ProxyVectorDatabaseEngine extends AbstractVectorDatabaseEngine { private static final Logger classLogger = LogManager.getLogger(ProxyVectorDatabaseEngine.class); - private static final String TARGET_ENGINE_ID = "TARGET_ENGINE_ID"; + public static final String TARGET_ENGINE_ID = "TARGET_ENGINE_ID"; private static final String TARGET_INTERCEPTOR = "TARGET_INTERCEPTOR"; private static final String TARGET_PARAMETERS = "TARGET_PARAMETERS"; diff --git a/src/prerna/reactor/engine/UpdateEngineGuardrailConfigReactor.java b/src/prerna/reactor/engine/UpdateEngineGuardrailConfigReactor.java index f47c1d5127e..31d5976b06e 100644 --- a/src/prerna/reactor/engine/UpdateEngineGuardrailConfigReactor.java +++ b/src/prerna/reactor/engine/UpdateEngineGuardrailConfigReactor.java @@ -193,9 +193,11 @@ public NounMetadata execute() { } finally { lock.unlock(); } - releaseLocksOfRemovedLimits(user, engine, validated.hitLimits()); + // record the guardrails before anything that can fail, since the configuration + // is saved already CatalogDependencyDerivation.syncGuardrails(user, engine.getEngineId(), engine.getCatalogType().name(), validated.pipelines()); + releaseLocksOfRemovedLimits(user, engine, validated.hitLimits()); if (ClusterUtil.IS_CLUSTER) { ClusterUtil.pushEngine(engineId); diff --git a/src/prerna/reactor/engine/UploadEngineReactor.java b/src/prerna/reactor/engine/UploadEngineReactor.java index 45ab68c7c79..397a0b70c63 100644 --- a/src/prerna/reactor/engine/UploadEngineReactor.java +++ b/src/prerna/reactor/engine/UploadEngineReactor.java @@ -44,6 +44,7 @@ import prerna.auth.User; import prerna.auth.utils.AbstractSecurityUtils; +import prerna.auth.utils.CatalogDependencyResync; import prerna.auth.utils.SecurityAdminUtils; import prerna.auth.utils.SecurityEngineUtils; import prerna.auth.utils.SecurityModelMetadataUtils; @@ -366,6 +367,17 @@ public NounMetadata execute() { // add user as engine owner SecurityEngineUtils.addEngineOwner(user, engineId); + // record what the imported engine's configuration depends on from its smss + // and the pipeline.json / router.json in its folder, without loading the + // engine; the upload succeeds without it, and SyncCatalogDependencies or the + // admin backfill can record it later + try { + CatalogDependencyResync.resyncEngineFromFiles(user, engineId, engineName, engineType, prop); + } catch (Exception e) { + classLogger.warn("Uploaded engine {} but could not record its dependencies", + Utility.cleanLogString(engineId), e); + } + ClusterUtil.pushEngine(engineId); UserAuditTrailUtils.recordEngineLifecycle(user, AuditEventType.ENGINE_CREATE, AuditTargetType.ofEngine(engineType), engineId, engineName, Map.of("global", global)); diff --git a/src/prerna/reactor/security/AdminBackfillCatalogDependenciesReactor.java b/src/prerna/reactor/security/AdminBackfillCatalogDependenciesReactor.java index 0c9995c130a..06be0836233 100644 --- a/src/prerna/reactor/security/AdminBackfillCatalogDependenciesReactor.java +++ b/src/prerna/reactor/security/AdminBackfillCatalogDependenciesReactor.java @@ -27,47 +27,25 @@ *******************************************************************************/ package prerna.reactor.security; -import java.io.File; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; import java.util.ArrayList; -import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import java.util.Set; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.json.JSONArray; -import org.json.JSONObject; - -import com.google.gson.Gson; import prerna.auth.User; -import prerna.auth.utils.CatalogDependencyDerivation; -import prerna.auth.utils.CatalogDependencyRole; -import prerna.auth.utils.CatalogTypes; +import prerna.auth.utils.CatalogDependencyResync; import prerna.auth.utils.SecurityAdminUtils; -import prerna.auth.utils.SecurityCatalogDependencyUtils; -import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; import prerna.auth.utils.SecurityEngineUtils; -import prerna.engine.api.IEngine; -import prerna.engine.impl.model.ModelRouterEngine; -import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils; -import prerna.engine.impl.pipeline.EngineProxyFactory; import prerna.project.api.IProject; -import prerna.project.impl.ProjectHelper; -import prerna.project.impl.notebook.INotebookHelper; import prerna.reactor.AbstractReactor; import prerna.reactor.ReactorDefinition; -import prerna.reactor.automation.definition.AutomationDefinitionService; import prerna.sablecc2.om.PixelDataType; import prerna.sablecc2.om.nounmeta.NounMetadata; -import prerna.util.EngineUtility; import prerna.util.QueryExecutionUtility; import prerna.util.SystemEngineRegistry; -import prerna.util.Utility; /** * Works out the automatic dependencies of every engine, agent, automation and app @@ -76,7 +54,8 @@ * knowledge, skills, model and subagents, automations' nodes, blocks apps' * engines, and the ids in code apps' files. Picked * dependencies are kept; a row from before IS_AUTOMATIC that a derived one - * stands for is replaced. Safe to run again. + * stands for is replaced. Safe to run again. Each item is read by + * {@link CatalogDependencyResync}, as SyncCatalogDependencies reads one. */ public class AdminBackfillCatalogDependenciesReactor extends AbstractReactor { @@ -97,7 +76,7 @@ public NounMetadata execute() { List failed = new ArrayList<>(); for (String engineId : SecurityEngineUtils.getAllEngineIds()) { try { - backfillEngine(user, engineId); + CatalogDependencyResync.resyncEngine(user, engineId); engines++; } catch (Exception e) { classLogger.warn("Could not backfill the dependencies of engine {}", engineId, e); @@ -108,7 +87,7 @@ public NounMetadata execute() { int workspaces = 0; for (String projectId : projectIdsOfType(IProject.PROJECT_TYPE.WORKSPACE.name())) { try { - backfillWorkspace(user, projectId); + CatalogDependencyResync.resyncWorkspace(user, projectId); workspaces++; } catch (Exception e) { classLogger.warn("Could not backfill the dependencies of agent {}", projectId, e); @@ -119,7 +98,7 @@ public NounMetadata execute() { int automations = 0; for (String projectId : projectIdsOfType(IProject.PROJECT_TYPE.AUTOMATION.name())) { try { - backfillAutomation(user, projectId); + CatalogDependencyResync.resyncAutomation(user, projectId); automations++; } catch (Exception e) { classLogger.warn("Could not backfill the dependencies of automation {}", projectId, e); @@ -130,7 +109,7 @@ public NounMetadata execute() { int blocks = 0; for (String projectId : projectIdsOfType(IProject.PROJECT_TYPE.BLOCKS.name())) { try { - backfillBlocks(user, projectId); + CatalogDependencyResync.resyncBlocks(user, projectId); blocks++; } catch (Exception e) { classLogger.warn("Could not backfill the dependencies of blocks app {}", projectId, e); @@ -141,7 +120,7 @@ public NounMetadata execute() { int code = 0; for (String projectId : projectIdsOfType(IProject.PROJECT_TYPE.CODE.name())) { try { - backfillCode(user, projectId); + CatalogDependencyResync.resyncCode(user, projectId); code++; } catch (Exception e) { classLogger.warn("Could not backfill the dependencies of code app {}", projectId, e); @@ -159,114 +138,6 @@ public NounMetadata execute() { return new NounMetadata(result, PixelDataType.MAP); } - @SuppressWarnings("unchecked") - private static void backfillEngine(User user, String engineId) throws Exception { - IEngine engine = Utility.getEngine(engineId); - if (engine == null) { - throw new IllegalStateException("Engine " + engineId + " could not be loaded"); - } - String engineType = engine.getCatalogType().name(); - CatalogDependencyDerivation.syncSmss(user, engineId, engineType, engine.getSmssProp()); - - if (engine.getCatalogType() != IEngine.CATALOG_TYPE.GUARDRAIL) { - String pipelineName = engine.getSmssProp().getProperty(IEngine.PIPELINE); - Map pipelines = Map.of(); - if (pipelineName != null && !pipelineName.isBlank()) { - File pipelineFile = EngineProxyFactory.pipelineFile(engine, pipelineName.trim()); - if (pipelineFile.isFile()) { - Map config = new Gson().fromJson( - Files.readString(pipelineFile.toPath(), StandardCharsets.UTF_8), Map.class); - if (config != null && config.get("pipelines") instanceof Map read) { - pipelines = (Map) read; - } - } - } - CatalogDependencyDerivation.syncGuardrails(user, engineId, engineType, pipelines); - } - - if (engine instanceof ModelRouterEngine router) { - File configFile = router.resolveConfigFile(); - if (configFile.isFile()) { - CatalogDependencyDerivation.syncRouterJson(user, engineId, - Files.readString(configFile.toPath(), StandardCharsets.UTF_8)); - } - } - } - - private static void backfillWorkspace(User user, String workspaceId) { - List> resources = ModelInferenceLogsUtils.getWorkspaceResourcesByType(workspaceId, null); - JSONObject config = ModelInferenceLogsUtils.getWorkspaceConfigJson(workspaceId); - String modelId = config == null ? null : config.optString("model_id", null); - List subagentIds = new ArrayList<>(); - JSONArray subagents = config == null ? null : config.optJSONArray("subagents"); - if (subagents != null) { - for (int i = 0; i < subagents.length(); i++) { - JSONObject subagent = subagents.optJSONObject(i); - if (subagent != null) { - subagentIds.add(subagent.optString("workspaceId", null)); - } - } - } - List dependencies = CatalogDependencyDerivation.fromWorkspace(resources, modelId, subagentIds, - CatalogTypes::resolve); - SecurityCatalogDependencyUtils.syncAutomaticDependencies(user, workspaceId, - IProject.PROJECT_TYPE.WORKSPACE.name(), CatalogDependencyDerivation.WORKSPACE_ROLES, dependencies); - } - - @SuppressWarnings("unchecked") - private static void backfillAutomation(User user, String projectId) { - String definition = AutomationDefinitionService.load(projectId).definition(); - List> nodes = new ArrayList<>(); - if (definition != null && !definition.isBlank()) { - Map parsed = new Gson().fromJson(definition, Map.class); - if (parsed != null && parsed.get("nodes") instanceof List list) { - for (Object node : list) { - if (node instanceof Map nodeMap) { - nodes.add((Map) nodeMap); - } - } - } - } - SecurityCatalogDependencyUtils.syncAutomaticDependencies(user, projectId, - IProject.PROJECT_TYPE.AUTOMATION.name(), List.of(CatalogDependencyRole.AUTOMATION_NODE), - CatalogDependencyDerivation.fromAutomationNodes(nodes, CatalogTypes::resolve)); - } - - /** - * A blocks app's BLOCK_ENGINE dependencies, read from its saved blocks json as - * SaveAppBlocksJson records them - */ - private static void backfillBlocks(User user, String projectId) { - IProject project = Utility.getProject(projectId); - if (project == null) { - throw new IllegalStateException("Blocks app " + projectId + " could not be loaded"); - } - Set engineIds = new HashSet<>(project.getEngineDependencies().values()); - engineIds.remove(INotebookHelper.UNDEFINED_VALUE); - SecurityCatalogDependencyUtils.syncAutomaticDependencyIds(user, projectId, IProject.PROJECT_TYPE.BLOCKS.name(), - CatalogDependencyRole.BLOCK_ENGINE, "Engine a block of this app uses", engineIds); - } - - /** - * A code app's CODE_REFERENCE dependencies: the engine and project ids found in - * its files, as ExtractAndSetDependencies records them for the whole app - */ - @SuppressWarnings("unchecked") - private static void backfillCode(User user, String projectId) { - IProject project = Utility.getProject(projectId); - if (project == null) { - throw new IllegalStateException("Code app " + projectId + " could not be loaded"); - } - File assets = new File(EngineUtility.getSpecificEngineAssetsFolder(IEngine.CATALOG_TYPE.PROJECT, - project.getProjectId(), project.getProjectName())); - Map found = ProjectHelper.extractEngineIdsFromProjectFolder(assets); - Set ids = found.get("success") instanceof Map success - ? ((Map) success).keySet() - : Set.of(); - SecurityCatalogDependencyUtils.syncAutomaticDependencyIds(user, projectId, IProject.PROJECT_TYPE.CODE.name(), - CatalogDependencyRole.CODE_REFERENCE, "Engine referenced in this app's files", ids); - } - private static List projectIdsOfType(String type) { try { return QueryExecutionUtility.queryList(SystemEngineRegistry.getSecurityDb(), diff --git a/src/prerna/reactor/security/SyncCatalogDependenciesReactor.java b/src/prerna/reactor/security/SyncCatalogDependenciesReactor.java new file mode 100644 index 00000000000..5c7962068ed --- /dev/null +++ b/src/prerna/reactor/security/SyncCatalogDependenciesReactor.java @@ -0,0 +1,103 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.security; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import prerna.auth.User; +import prerna.auth.utils.CatalogDependencyResync; +import prerna.auth.utils.SecurityCatalogDependencyUtils; +import prerna.reactor.AbstractReactor; +import prerna.reactor.ReactorDefinition; +import prerna.sablecc2.om.PixelDataType; +import prerna.sablecc2.om.nounmeta.NounMetadata; +import prerna.util.Utility; + +/** + * Works out the automatic dependencies of one engine or project again from what + * it has saved, and records them, as AdminBackfillCatalogDependencies does for + * every item: an engine's smss references, guardrails and model router routes, + * an agent's tools, knowledge, skills, model and subagents, an automation's + * nodes, a blocks app's engines, and the ids in a code app's files. Picked + * dependencies are kept. A project type with nothing to derive is left as it is. + * Fails when the item cannot be read or its dependencies cannot be recorded. + */ +public class SyncCatalogDependenciesReactor extends AbstractReactor { + + private static final Logger classLogger = LogManager.getLogger(SyncCatalogDependenciesReactor.class); + + public SyncCatalogDependenciesReactor() { + this.keysToGet = new String[] { CatalogDependencyKeys.CATALOG_ID, CatalogDependencyKeys.CATALOG_TYPE }; + this.keyRequired = new int[] { 1, 0 }; + } + + @Override + public NounMetadata execute() { + organizeKeys(); + User user = this.insight.getUser(); + String catalogId = this.keyValue.get(CatalogDependencyKeys.CATALOG_ID); + String catalogType = SecurityCatalogDependencyUtils.resolveCatalogType(catalogId, + this.keyValue.get(CatalogDependencyKeys.CATALOG_TYPE)); + if (!SecurityCatalogDependencyUtils.userCanEdit(user, catalogId, catalogType)) { + throw new IllegalArgumentException("The user does not have access to edit " + catalogId); + } + + try { + CatalogDependencyResync.resync(user, catalogId, catalogType); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + classLogger.error("Could not sync the dependencies of {}", Utility.cleanLogString(catalogId), e); + throw new IllegalStateException("Could not sync the dependencies of " + catalogId + ": " + e.getMessage(), + e); + } + + Map result = new LinkedHashMap<>(); + result.put("catalogId", catalogId); + result.put("catalogType", catalogType); + result.put("automatic", SecurityCatalogDependencyUtils.countAutomaticDependencies(catalogId)); + NounMetadata noun = new NounMetadata(result, PixelDataType.MAP); + noun.addAdditionalReturn(NounMetadata.getSuccessNounMessage("Successfully synced the dependencies")); + return noun; + } + + @Override + public ReactorDefinition getReactorDefinition() { + return super.getReactorDefinition() + .description("Work out the automatic dependencies of an engine or project again from its saved " + + "configuration and record them; the dependencies a user picked are kept") + .key(CatalogDependencyKeys.CATALOG_ID, "The engine id or project id") + .key(CatalogDependencyKeys.CATALOG_TYPE, + "Its engine type or project type, such as FUNCTION or SKILL; read when not given") + .output(Map.class, "The catalogId, its catalogType, and how many automatic dependencies it has now"); + } +} diff --git a/test/prerna/auth/utils/CatalogDependencyDerivationUnitTests.java b/test/prerna/auth/utils/CatalogDependencyDerivationUnitTests.java index 133891508e1..aededaa88a2 100644 --- a/test/prerna/auth/utils/CatalogDependencyDerivationUnitTests.java +++ b/test/prerna/auth/utils/CatalogDependencyDerivationUnitTests.java @@ -48,8 +48,9 @@ public class CatalogDependencyDerivationUnitTests { private static final UnaryOperator TYPES = id -> switch (id) { case "missing" -> null; case "guard1", "guard2" -> "GUARDRAIL"; - case "kb1" -> "VECTOR"; - case "bucket1" -> "STORAGE"; + case "kb1", "kb2" -> "VECTOR"; + case "bucket1", "s3bucket1" -> "STORAGE"; + case "processor1" -> "FUNCTION"; case "agent2" -> "WORKSPACE"; case "skill1" -> "SKILL"; case "app1" -> "CODE"; @@ -95,6 +96,74 @@ void smss_givesAGuardrailsJudgeAndVectorAndAVectorsEmbedder() { .isEmpty()); } + @Test + void smss_givesAVectorsKeywordModelDocumentProcessorAndProxyTarget() { + List vector = CatalogDependencyDerivation.fromSmss("VECTOR", + Map.of("EMBEDDER_ENGINE_ID", "embedder1", "KEYWORD_ENGINE_ID", "keywords1", + "CUSTOM_DOCUMENT_PROCESSOR", "true", "CUSTOM_DOCUMENT_PROCESSOR_FUNCTION_ID", "processor1", + "TARGET_ENGINE_ID", "kb2"), + TYPES); + assertEquals(List.of(CatalogDependencyRole.EMBEDDER, CatalogDependencyRole.KEYWORD_ENGINE, + CatalogDependencyRole.DOCUMENT_PROCESSOR, CatalogDependencyRole.PROXY_TARGET), + vector.stream().map(Dependency::role).toList()); + assertEquals("FUNCTION", vector.get(2).type()); + assertEquals("VECTOR", vector.get(3).type()); + assertTrue(CatalogDependencyDerivation.SMSS_ROLES.containsAll(vector.stream().map(Dependency::role).toList())); + + // the processor function is used only when the custom processor is on, and an + // empty keyword model, as the vector database writes back, is none + List processorOff = CatalogDependencyDerivation.fromSmss("VECTOR", + Map.of("EMBEDDER_ENGINE_ID", "embedder1", "KEYWORD_ENGINE_ID", "", + "CUSTOM_DOCUMENT_PROCESSOR_FUNCTION_ID", "processor1"), + TYPES); + assertEquals(List.of(CatalogDependencyRole.EMBEDDER), processorOff.stream().map(Dependency::role).toList()); + } + + @Test + void smss_skipsTheDocumentProcessorWhenTheCustomProcessorIsTurnedOff() { + List vector = CatalogDependencyDerivation.fromSmss("VECTOR", + Map.of("EMBEDDER_ENGINE_ID", "embedder1", "CUSTOM_DOCUMENT_PROCESSOR", "false", + "CUSTOM_DOCUMENT_PROCESSOR_FUNCTION_ID", "processor1"), + TYPES); + assertEquals(List.of(CatalogDependencyRole.EMBEDDER), vector.stream().map(Dependency::role).toList()); + } + + @Test + void smss_readsTheLegacyEncoderOnlyWithoutAnEmbedder() { + List legacy = CatalogDependencyDerivation.fromSmss("VECTOR", Map.of("ENCODER_ID", " encoder1 "), + TYPES); + assertEquals(1, legacy.size()); + assertEquals(CatalogDependencyRole.EMBEDDER, legacy.get(0).role()); + assertEquals("encoder1", legacy.get(0).id()); + + List both = CatalogDependencyDerivation.fromSmss("VECTOR", + Map.of("EMBEDDER_ENGINE_ID", "embedder1", "ENCODER_ID", "encoder1"), TYPES); + assertEquals(List.of("embedder1"), both.stream().map(Dependency::id).toList()); + + List blankEmbedder = CatalogDependencyDerivation.fromSmss("VECTOR", + Map.of("EMBEDDER_ENGINE_ID", " ", "ENCODER_ID", "encoder1"), TYPES); + assertEquals(List.of("encoder1"), blankEmbedder.stream().map(Dependency::id).toList()); + } + + @Test + void smss_givesAFunctionsS3BucketAndImageModel() { + List textract = CatalogDependencyDerivation.fromSmss("FUNCTION", + Map.of("S3BUCKETENGINEID", "s3bucket1"), TYPES); + assertEquals(1, textract.size()); + assertEquals(CatalogDependencyRole.FUNCTION_STORAGE, textract.get(0).role()); + assertEquals("STORAGE", textract.get(0).type()); + + List image = CatalogDependencyDerivation.fromSmss("FUNCTION", + Map.of("IMAGE_ENGINE_ID", "vision1"), TYPES); + assertEquals(1, image.size()); + assertEquals(CatalogDependencyRole.IMAGE_MODEL, image.get(0).role()); + assertEquals("MODEL", image.get(0).type()); + + // a vector key on a function is no dependency + assertTrue(CatalogDependencyDerivation.fromSmss("FUNCTION", Map.of("KEYWORD_ENGINE_ID", "keywords1"), TYPES) + .isEmpty()); + } + @Test void routerConfig_givesRoutesClassifierEmbeddingsAndFallbacks() { String json = """ diff --git a/test/prerna/auth/utils/CatalogDependencyResyncUnitTests.java b/test/prerna/auth/utils/CatalogDependencyResyncUnitTests.java new file mode 100644 index 00000000000..14eb1d66dc6 --- /dev/null +++ b/test/prerna/auth/utils/CatalogDependencyResyncUnitTests.java @@ -0,0 +1,326 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.auth.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.ArgumentCaptor; +import org.mockito.MockedStatic; + +import prerna.auth.User; +import prerna.auth.utils.SecurityCatalogDependencyUtils.Dependency; +import prerna.engine.api.IEngine; +import prerna.engine.impl.CaseInsensitiveProperties; +import prerna.engine.impl.model.ModelRouterEngine; +import prerna.engine.impl.model.inferencetracking.ModelInferenceLogsUtils; +import prerna.engine.impl.pipeline.EngineProxyFactory; +import prerna.project.api.IProject; +import prerna.reactor.automation.AutomationConstants; +import prerna.util.AssetUtility; +import prerna.util.Utility; + +/** + * Resyncing an item's automatic dependencies never clears them because its + * saved configuration could not be read, and an engine's are written once. + */ +class CatalogDependencyResyncUnitTests { + + private final User user = mock(User.class); + private MockedStatic writes; + private MockedStatic types; + + @BeforeEach + void mockTheSecurityDatabase() { + writes = mockStatic(SecurityCatalogDependencyUtils.class); + types = mockStatic(CatalogTypes.class); + types.when(() -> CatalogTypes.resolve(anyString())).thenAnswer(call -> switch ((String) call.getArgument(0)) { + case "guard1" -> "GUARDRAIL"; + case "kb1" -> "VECTOR"; + default -> "MODEL"; + }); + } + + @AfterEach + void closeMocks() { + types.close(); + writes.close(); + } + + private void verifyNothingWritten() { + writes.verify(() -> SecurityCatalogDependencyUtils.syncAutomaticDependencies(any(), any(), any(), + anyCollection(), anyCollection()), never()); + writes.verify(() -> SecurityCatalogDependencyUtils.syncAutomaticDependencyIds(any(), any(), any(), any(), + any(), anyCollection()), never()); + } + + // ---------------------------------------------------------------- agents + + @Test + void anAgentWhoseConfigCannotBeParsedThrowsAndWritesNothing() { + try (MockedStatic logs = mockStatic(ModelInferenceLogsUtils.class)) { + logs.when(() -> ModelInferenceLogsUtils.getWorkspaceEntry("agent1")) + .thenReturn(Map.of("workspace_id", "agent1", "config_json", "{not json")); + logs.when(() -> ModelInferenceLogsUtils.getWorkspaceResourcesByType("agent1", null)) + .thenReturn(List.of(Map.of("resource_id", "kb1", "resource_type", "VECTOR"))); + + IllegalStateException e = assertThrows(IllegalStateException.class, + () -> CatalogDependencyResync.resyncWorkspace(user, "agent1")); + assertTrue(e.getMessage().contains("agent1"), e.getMessage()); + } + verifyNothingWritten(); + } + + @Test + void anAgentWithNoWorkspaceRowThrowsAndWritesNothing() { + try (MockedStatic logs = mockStatic(ModelInferenceLogsUtils.class)) { + logs.when(() -> ModelInferenceLogsUtils.getWorkspaceEntry("agent1")).thenReturn(null); + + assertThrows(IllegalStateException.class, () -> CatalogDependencyResync.resyncWorkspace(user, "agent1")); + } + verifyNothingWritten(); + } + + @Test + @SuppressWarnings("unchecked") + void anAgentWithNoConfigRecordsOnlyItsResources() { + Map row = new HashMap<>(); + row.put("workspace_id", "agent1"); + row.put("config_json", null); + try (MockedStatic logs = mockStatic(ModelInferenceLogsUtils.class)) { + logs.when(() -> ModelInferenceLogsUtils.getWorkspaceEntry("agent1")).thenReturn(row); + logs.when(() -> ModelInferenceLogsUtils.getWorkspaceResourcesByType("agent1", null)) + .thenReturn(List.of(Map.of("resource_id", "kb1", "resource_type", "VECTOR"))); + + CatalogDependencyResync.resyncWorkspace(user, "agent1"); + } + ArgumentCaptor> written = ArgumentCaptor.forClass(Collection.class); + writes.verify(() -> SecurityCatalogDependencyUtils.syncAutomaticDependencies(eq(user), eq("agent1"), + eq("WORKSPACE"), eq(CatalogDependencyDerivation.WORKSPACE_ROLES), written.capture()), times(1)); + assertEquals(List.of(CatalogDependencyRole.KNOWLEDGE), + written.getValue().stream().map(Dependency::role).toList()); + } + + // ----------------------------------------------------------- automations + + @Test + void anAutomationWhoseDefinitionCannotBeParsedThrowsAndWritesNothing(@TempDir Path assets) throws Exception { + Files.writeString(assets.resolve(AutomationConstants.AUTOMATION_PYTHON_DEFINITION_FILE_NAME), "{not json"); + try (MockedStatic utility = mockStatic(Utility.class); + MockedStatic folders = mockStatic(AssetUtility.class)) { + stubAutomation(utility, folders, assets); + + IllegalStateException e = assertThrows(IllegalStateException.class, + () -> CatalogDependencyResync.resyncAutomation(user, "auto1")); + assertTrue(e.getMessage().contains("auto1"), e.getMessage()); + } + verifyNothingWritten(); + } + + @Test + void anAutomationWithNoSavedDefinitionThrowsAndWritesNothing(@TempDir Path assets) { + try (MockedStatic utility = mockStatic(Utility.class); + MockedStatic folders = mockStatic(AssetUtility.class)) { + stubAutomation(utility, folders, assets); + + assertThrows(IllegalStateException.class, () -> CatalogDependencyResync.resyncAutomation(user, "auto1")); + } + verifyNothingWritten(); + } + + @Test + void aMissingAutomationThrowsAndWritesNothing() { + try (MockedStatic utility = mockStatic(Utility.class)) { + utility.when(() -> Utility.getProject("auto1")).thenReturn(null); + + assertThrows(IllegalStateException.class, () -> CatalogDependencyResync.resyncAutomation(user, "auto1")); + } + verifyNothingWritten(); + } + + private static void stubAutomation(MockedStatic utility, MockedStatic folders, + Path assets) { + IProject project = mock(IProject.class); + when(project.getProjectName()).thenReturn("Flow"); + utility.when(() -> Utility.getProject("auto1")).thenReturn(project); + folders.when(() -> AssetUtility.getProjectAssetsFolder("auto1")).thenReturn(assets.toString()); + folders.when(() -> AssetUtility.getProjectAssetsFolder("Flow", "auto1")).thenReturn(assets.toString()); + } + + // ----------------------------------------------------------- blocks apps + + @Test + void aBlocksAppWhoseBlocksCannotBeParsedThrowsAndWritesNothing(@TempDir Path portals) throws Exception { + Files.writeString(portals.resolve(IProject.BLOCK_FILE_NAME), "{not json"); + IProject project = mock(IProject.class); + when(project.getProjectName()).thenReturn("Blocks"); + try (MockedStatic utility = mockStatic(Utility.class); + MockedStatic folders = mockStatic(AssetUtility.class)) { + utility.when(() -> Utility.getProject("app1")).thenReturn(project); + folders.when(() -> AssetUtility.getProjectPortalsFolder("Blocks", "app1")).thenReturn(portals.toString()); + + assertThrows(IllegalStateException.class, () -> CatalogDependencyResync.resyncBlocks(user, "app1")); + } + verifyNothingWritten(); + } + + // ---------------------------------------------------------------- engines + + @Test + @SuppressWarnings("unchecked") + void anEngineIsWrittenOnceWithItsSmssAndGuardrailRoles(@TempDir Path folder) throws Exception { + File pipeline = folder.resolve("pipeline.json").toFile(); + Files.writeString(pipeline.toPath(), """ + {"pipelines":{"chat":{"input":[{"reactorClass":"Guardrail","params":{"guardrailEngineId":"guard1"}}]}}} + """); + Properties smss = new Properties(); + smss.setProperty("EMBEDDER_ENGINE_ID", "embedder1"); + smss.setProperty(IEngine.PIPELINE, "pipeline.json"); + IEngine engine = engine(IEngine.class, "vector1", IEngine.CATALOG_TYPE.VECTOR, smss); + + try (MockedStatic proxies = mockStatic(EngineProxyFactory.class)) { + proxies.when(() -> EngineProxyFactory.pipelineFile(engine, "pipeline.json")).thenReturn(pipeline); + CatalogDependencyResync.resyncEngine(user, engine); + } + + ArgumentCaptor> roles = ArgumentCaptor.forClass(Collection.class); + ArgumentCaptor> written = ArgumentCaptor.forClass(Collection.class); + writes.verify(() -> SecurityCatalogDependencyUtils.syncAutomaticDependencies(eq(user), eq("vector1"), + eq("VECTOR"), roles.capture(), written.capture()), times(1)); + Set expected = new java.util.LinkedHashSet<>(CatalogDependencyDerivation.SMSS_ROLES); + expected.add(CatalogDependencyRole.GUARDRAIL); + assertEquals(expected, Set.copyOf(roles.getValue())); + assertEquals(List.of(CatalogDependencyRole.EMBEDDER, CatalogDependencyRole.GUARDRAIL), + written.getValue().stream().map(Dependency::role).toList()); + } + + @Test + @SuppressWarnings("unchecked") + void aModelRouterIsWrittenOnceWithItsSmssGuardrailAndRouterRoles(@TempDir Path folder) throws Exception { + File router = folder.resolve("router.json").toFile(); + Files.writeString(router.toPath(), """ + {"mode":"llm","classifier_engine":"classifier1","routes":[{"name":"code","engine_id":"model1"}]} + """); + ModelRouterEngine engine = engine(ModelRouterEngine.class, "router1", IEngine.CATALOG_TYPE.MODEL, + new CaseInsensitiveProperties()); + when(engine.resolveConfigFile()).thenReturn(router); + + CatalogDependencyResync.resyncEngine(user, engine); + + ArgumentCaptor> roles = ArgumentCaptor.forClass(Collection.class); + writes.verify(() -> SecurityCatalogDependencyUtils.syncAutomaticDependencies(eq(user), eq("router1"), + eq("MODEL"), roles.capture(), anyCollection()), times(1)); + assertTrue(roles.getValue().containsAll(CatalogDependencyDerivation.SMSS_ROLES)); + assertTrue(roles.getValue().containsAll(CatalogDependencyDerivation.ROUTER_ROLES)); + assertTrue(roles.getValue().contains(CatalogDependencyRole.GUARDRAIL)); + } + + @Test + void aGuardrailLeavesTheGuardrailRoleAlone() throws Exception { + Properties smss = new Properties(); + smss.setProperty("MODEL_ENGINE_ID", "judge1"); + IEngine engine = engine(IEngine.class, "guard1", IEngine.CATALOG_TYPE.GUARDRAIL, smss); + + CatalogDependencyResync.resyncEngine(user, engine); + + ArgumentCaptor> roles = rolesCaptor(); + writes.verify(() -> SecurityCatalogDependencyUtils.syncAutomaticDependencies(eq(user), eq("guard1"), + eq("GUARDRAIL"), roles.capture(), anyCollection()), times(1)); + // only the smss roles: a guardrail's own pipeline is not a guardrail it depends on + assertEquals(Set.copyOf(CatalogDependencyDerivation.SMSS_ROLES), Set.copyOf(roles.getValue())); + } + + @Test + void aMalformedPipelineThrowsBeforeAnythingIsWritten(@TempDir Path folder) throws Exception { + File pipeline = folder.resolve("pipeline.json").toFile(); + Files.writeString(pipeline.toPath(), "{\"pipelines\": [not json"); + Properties smss = new Properties(); + smss.setProperty("EMBEDDER_ENGINE_ID", "embedder1"); + smss.setProperty(IEngine.PIPELINE, "pipeline.json"); + IEngine engine = engine(IEngine.class, "vector1", IEngine.CATALOG_TYPE.VECTOR, smss); + + try (MockedStatic proxies = mockStatic(EngineProxyFactory.class)) { + proxies.when(() -> EngineProxyFactory.pipelineFile(engine, "pipeline.json")).thenReturn(pipeline); + IllegalStateException e = assertThrows(IllegalStateException.class, + () -> CatalogDependencyResync.resyncEngine(user, engine)); + assertTrue(e.getMessage().contains("vector1"), e.getMessage()); + } + verifyNothingWritten(); + } + + @Test + void aMalformedRouterConfigThrowsBeforeAnythingIsWritten(@TempDir Path folder) throws Exception { + File router = folder.resolve("router.json").toFile(); + Files.writeString(router.toPath(), "not json {"); + ModelRouterEngine engine = engine(ModelRouterEngine.class, "router1", IEngine.CATALOG_TYPE.MODEL, + new CaseInsensitiveProperties()); + when(engine.resolveConfigFile()).thenReturn(router); + + assertThrows(IllegalStateException.class, () -> CatalogDependencyResync.resyncEngine(user, engine)); + verifyNothingWritten(); + } + + @SuppressWarnings("unchecked") + private static ArgumentCaptor> rolesCaptor() { + return ArgumentCaptor.forClass(Collection.class); + } + + private static T engine(Class kind, String id, IEngine.CATALOG_TYPE type, + Properties smss) { + T engine = mock(kind); + when(engine.getEngineId()).thenReturn(id); + when(engine.getEngineName()).thenReturn(id); + when(engine.getCatalogType()).thenReturn(type); + when(engine.getSmssProp()).thenReturn(smss); + return engine; + } +} diff --git a/test/prerna/reactor/security/SyncCatalogDependenciesReactorUnitTests.java b/test/prerna/reactor/security/SyncCatalogDependenciesReactorUnitTests.java new file mode 100644 index 00000000000..66458f1e0c9 --- /dev/null +++ b/test/prerna/reactor/security/SyncCatalogDependenciesReactorUnitTests.java @@ -0,0 +1,93 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed 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. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.reactor.security; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import prerna.auth.utils.AbstractReactorPermissionUnitTestsSetup; +import prerna.auth.utils.CatalogTypes; + +/** + * Who SyncCatalogDependencies works for: a user who can edit the engine or + * project, as SetCatalogDependencies. + */ +class SyncCatalogDependenciesReactorUnitTests extends AbstractReactorPermissionUnitTestsSetup { + + private static final String CANNOT_EDIT = "does not have access to edit"; + + /** + * Being an admin does not stand in for being able to edit the engine. + */ + @Test + void refusesAnAdminWhoHoldsNoPermissionOnTheEngine() { + IllegalArgumentException refusal = assertThrows(IllegalArgumentException.class, + () -> run(new SyncCatalogDependenciesReactor(), anAdminWhoHoldsNothing(), Map.of("catalogId", ENGINE))); + + assertTrue(refusal.getMessage().contains(CANNOT_EDIT), refusal.getMessage()); + } + + /** + * A user with no permission on the project cannot sync it. + */ + @Test + void refusesAUserWithNoPermissionOnTheProject() { + IllegalArgumentException refusal = assertThrows(IllegalArgumentException.class, + () -> run(new SyncCatalogDependenciesReactor(), this.requester, Map.of("catalogId", PROJECT))); + + assertTrue(refusal.getMessage().contains(CANNOT_EDIT), refusal.getMessage()); + } + + /** + * An editor can sync; a project type with nothing to derive is left as it is. + */ + @Test + @SuppressWarnings("unchecked") + void syncsForAnEditorAndCountsTheAutomaticDependencies() { + Map result = (Map) run(new SyncCatalogDependenciesReactor(), + anEditorWhoIsNotAnAdmin(), Map.of("catalogId", PROJECT)).getValue(); + + assertEquals(PROJECT, result.get("catalogId")); + assertEquals(CatalogTypes.resolve(PROJECT), result.get("catalogType")); + assertEquals(0, result.get("automatic")); + } + + /** + * A type that is not the item's is refused before anything is read. + */ + @Test + void refusesATypeThatIsNotTheItems() { + assertThrows(IllegalArgumentException.class, () -> run(new SyncCatalogDependenciesReactor(), + anOwnerWhoIsNotAnAdmin(), Map.of("catalogId", ENGINE, "catalogType", "MODEL"))); + } +}