You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@polaris.apache.org by "MonkeyCanCode (via GitHub)" <gi...@apache.org> on 2025/04/27 22:58:37 UTC

[PR] Add setup CLI command for entities bootstrap [polaris]

MonkeyCanCode opened a new pull request, #1474:
URL: https://github.com/apache/polaris/pull/1474

   Sample output for bring up entities used by quickstart guild:
   ```
   $ ./polaris --profile dev setup create getting-started/assets/polaris/simple-setup-config.yaml
   2025-04-27 17:54:05,636 INFO === Starting Setup Process ===
   2025-04-27 17:54:05,636 INFO === Step 1: Creating Principals ===
   2025-04-27 17:54:05,702 INFO Creating principal: quickstart_user
   {"clientId": "dab51e37e5728954", "clientSecret": "c1c6d51a802d8614f94c3ac229ef676d"}
   2025-04-27 17:54:05,726 INFO Principal 'quickstart_user' created successfully.
   2025-04-27 17:54:05,726 INFO Step 1 completed: Principals creation process finished.
   2025-04-27 17:54:05,726 INFO === Step 2: Creating Principal Roles ===
   2025-04-27 17:54:05,734 INFO Creating principal role: quickstart_user_role
   2025-04-27 17:54:05,742 INFO Principal role 'quickstart_user_role' created successfully.
   2025-04-27 17:54:05,742 INFO Step 2 completed: Principal roles creation process finished.
   2025-04-27 17:54:05,742 INFO === Step 3: Assigning Principal Roles ===
   2025-04-27 17:54:05,747 INFO Assigning principal 'quickstart_user' to role 'quickstart_user_role'
   2025-04-27 17:54:05,755 INFO Assigned principal 'quickstart_user' to role 'quickstart_user_role' successfully.
   2025-04-27 17:54:05,755 INFO Step 3 completed: Principal roles assignment process finished.
   2025-04-27 17:54:05,755 INFO === Step 4: Creating Catalogs ===
   2025-04-27 17:54:05,765 INFO Creating catalog: quickstart_catalog
   2025-04-27 17:54:05,787 INFO Catalog 'quickstart_catalog' created successfully.
   2025-04-27 17:54:05,787 INFO Step 4 completed: Catalogs creation process finished.
   2025-04-27 17:54:05,787 INFO === Step 5: Creating Catalog Roles ===
   2025-04-27 17:54:05,803 INFO Creating catalog role: quickstart_catalog_role
   2025-04-27 17:54:05,810 INFO Catalog role 'quickstart_catalog_role' created successfully.
   2025-04-27 17:54:05,810 INFO Step 5 completed: Catalog roles creation process finished.
   2025-04-27 17:54:05,810 INFO === Step 6: Assigning Catalog Roles ===
   2025-04-27 17:54:05,823 INFO Assigning principal role 'quickstart_user_role' to catalog role 'quickstart_catalog_role' in catalog 'quickstart_catalog'
   2025-04-27 17:54:05,830 INFO Assigned principal role 'quickstart_user_role' to catalog role 'quickstart_catalog_role' in catalog 'quickstart_catalog' successfully.
   2025-04-27 17:54:05,830 INFO Step 6 completed: Catalog roles assignment process finished.
   2025-04-27 17:54:05,830 INFO === Step 7: Creating Namespaces ===
   2025-04-27 17:54:05,867 WARNING No valid namespaces found in the configuration.
   2025-04-27 17:54:05,867 INFO Step 7 completed: Namespaces creation process finished.
   2025-04-27 17:54:05,867 INFO === Step 8: Creating Privileges ===
   2025-04-27 17:54:05,877 INFO Assigning privilege 'CATALOG_MANAGE_CONTENT' at level 'catalog' for catalog 'quickstart_catalog' to catalog role 'quickstart_catalog_role'
   2025-04-27 17:54:05,889 INFO Privilege 'CATALOG_MANAGE_CONTENT' assigned successfully to catalog role 'quickstart_catalog_role'
   2025-04-27 17:54:05,889 INFO Step 8 completed: Privileges creation process finished.
   2025-04-27 17:54:05,889 INFO === Setup Process Completed Successfully ===
   ```
   
   Full example:
   ```
   $ ./polaris --profile dev setup create getting-started/assets/polaris/sample-setup-config.yaml
   2025-04-27 17:53:20,213 INFO === Starting Setup Process ===
   2025-04-27 17:53:20,213 INFO === Step 1: Creating Principals ===
   2025-04-27 17:53:20,282 INFO Creating principal: quickstart_user
   {"clientId": "19d7ca94533f1270", "clientSecret": "fef7b2f46c755a261b12067874bbfc47"}
   2025-04-27 17:53:20,305 INFO Principal 'quickstart_user' created successfully.
   2025-04-27 17:53:20,305 INFO Creating principal: readonly_user
   {"clientId": "a5d71d3dbe2076bb", "clientSecret": "219fd4dd39291f1ea936e413c86b538a"}
   2025-04-27 17:53:20,311 INFO Principal 'readonly_user' created successfully.
   2025-04-27 17:53:20,311 INFO Creating principal: dev_user
   {"clientId": "6bac51ac90242df6", "clientSecret": "1ae73686a3655023388dc274c79cfa72"}
   2025-04-27 17:53:20,318 INFO Principal 'dev_user' created successfully.
   2025-04-27 17:53:20,318 INFO Step 1 completed: Principals creation process finished.
   2025-04-27 17:53:20,318 INFO === Step 2: Creating Principal Roles ===
   2025-04-27 17:53:20,326 INFO Creating principal role: quickstart_user_role
   2025-04-27 17:53:20,334 INFO Principal role 'quickstart_user_role' created successfully.
   2025-04-27 17:53:20,334 INFO Creating principal role: readonly_user_role
   2025-04-27 17:53:20,339 INFO Principal role 'readonly_user_role' created successfully.
   2025-04-27 17:53:20,339 INFO Creating principal role: dev_user_role
   2025-04-27 17:53:20,344 INFO Principal role 'dev_user_role' created successfully.
   2025-04-27 17:53:20,344 INFO Step 2 completed: Principal roles creation process finished.
   2025-04-27 17:53:20,344 INFO === Step 3: Assigning Principal Roles ===
   2025-04-27 17:53:20,351 INFO Assigning principal 'quickstart_user' to role 'quickstart_user_role'
   2025-04-27 17:53:20,359 INFO Assigned principal 'quickstart_user' to role 'quickstart_user_role' successfully.
   2025-04-27 17:53:20,359 INFO Assigning principal 'readonly_user' to role 'readonly_user_role'
   2025-04-27 17:53:20,364 INFO Assigned principal 'readonly_user' to role 'readonly_user_role' successfully.
   2025-04-27 17:53:20,364 INFO Assigning principal 'dev_user' to role 'dev_user_role'
   2025-04-27 17:53:20,369 INFO Assigned principal 'dev_user' to role 'dev_user_role' successfully.
   2025-04-27 17:53:20,369 INFO Step 3 completed: Principal roles assignment process finished.
   2025-04-27 17:53:20,369 INFO === Step 4: Creating Catalogs ===
   2025-04-27 17:53:20,378 INFO Creating catalog: quickstart_catalog
   2025-04-27 17:53:20,400 INFO Catalog 'quickstart_catalog' created successfully.
   2025-04-27 17:53:20,400 INFO Creating catalog: quickstart_catalog_external
   2025-04-27 17:53:20,411 INFO Catalog 'quickstart_catalog_external' created successfully.
   2025-04-27 17:53:20,411 INFO Creating catalog: quickstart_catalog_s3
   2025-04-27 17:53:20,592 INFO Catalog 'quickstart_catalog_s3' created successfully.
   2025-04-27 17:53:20,592 INFO Creating catalog: quickstart_catalog_azure
   2025-04-27 17:53:20,647 INFO Catalog 'quickstart_catalog_azure' created successfully.
   2025-04-27 17:53:20,647 INFO Step 4 completed: Catalogs creation process finished.
   2025-04-27 17:53:20,647 INFO === Step 5: Creating Catalog Roles ===
   2025-04-27 17:53:20,675 INFO Creating catalog role: quickstart_catalog_role
   2025-04-27 17:53:20,681 INFO Catalog role 'quickstart_catalog_role' created successfully.
   2025-04-27 17:53:20,681 INFO Creating catalog role: readonly_catalog_role
   2025-04-27 17:53:20,685 INFO Catalog role 'readonly_catalog_role' created successfully.
   2025-04-27 17:53:20,685 INFO Creating catalog role: dev_catalog_role
   2025-04-27 17:53:20,690 INFO Catalog role 'dev_catalog_role' created successfully.
   2025-04-27 17:53:20,690 INFO Step 5 completed: Catalog roles creation process finished.
   2025-04-27 17:53:20,690 INFO === Step 6: Assigning Catalog Roles ===
   2025-04-27 17:53:20,717 INFO Assigning principal role 'quickstart_user_role' to catalog role 'quickstart_catalog_role' in catalog 'quickstart_catalog'
   2025-04-27 17:53:20,724 INFO Assigned principal role 'quickstart_user_role' to catalog role 'quickstart_catalog_role' in catalog 'quickstart_catalog' successfully.
   2025-04-27 17:53:20,724 INFO Assigning principal role 'readonly_user_role' to catalog role 'readonly_catalog_role' in catalog 'quickstart_catalog'
   2025-04-27 17:53:20,728 INFO Assigned principal role 'readonly_user_role' to catalog role 'readonly_catalog_role' in catalog 'quickstart_catalog' successfully.
   2025-04-27 17:53:20,728 INFO Assigning principal role 'dev_user_role' to catalog role 'dev_catalog_role' in catalog 'quickstart_catalog'
   2025-04-27 17:53:20,732 INFO Assigned principal role 'dev_user_role' to catalog role 'dev_catalog_role' in catalog 'quickstart_catalog' successfully.
   2025-04-27 17:53:20,732 INFO Step 6 completed: Catalog roles assignment process finished.
   2025-04-27 17:53:20,732 INFO === Step 7: Creating Namespaces ===
   2025-04-27 17:53:20,779 INFO Creating namespace: 'dev_namespace' in catalog: 'quickstart_catalog'
   2025-04-27 17:53:20,794 INFO Namespace 'dev_namespace' created successfully in catalog 'quickstart_catalog'.
   2025-04-27 17:53:20,794 INFO Creating namespace: 'dev_namespace.sub_namespace' in catalog: 'quickstart_catalog'
   2025-04-27 17:53:20,802 INFO Namespace 'dev_namespace.sub_namespace' created successfully in catalog 'quickstart_catalog'.
   2025-04-27 17:53:20,802 INFO Step 7 completed: Namespaces creation process finished.
   2025-04-27 17:53:20,802 INFO === Step 8: Creating Privileges ===
   2025-04-27 17:53:20,820 INFO Assigning privilege 'CATALOG_MANAGE_CONTENT' at level 'catalog' for catalog 'quickstart_catalog' to catalog role 'quickstart_catalog_role'
   2025-04-27 17:53:20,830 INFO Privilege 'CATALOG_MANAGE_CONTENT' assigned successfully to catalog role 'quickstart_catalog_role'
   2025-04-27 17:53:20,830 INFO Assigning privilege 'TABLE_READ_DATA' at level 'catalog' for catalog 'quickstart_catalog' to catalog role 'readonly_catalog_role'
   2025-04-27 17:53:20,834 INFO Privilege 'TABLE_READ_DATA' assigned successfully to catalog role 'readonly_catalog_role'
   2025-04-27 17:53:20,834 INFO Assigning privilege 'TABLE_FULL_METADATA' at level 'catalog' for catalog 'quickstart_catalog' to catalog role 'readonly_catalog_role'
   2025-04-27 17:53:20,838 INFO Privilege 'TABLE_FULL_METADATA' assigned successfully to catalog role 'readonly_catalog_role'
   2025-04-27 17:53:20,838 INFO Assigning privilege 'VIEW_FULL_METADATA' at level 'catalog' for catalog 'quickstart_catalog' to catalog role 'readonly_catalog_role'
   2025-04-27 17:53:20,843 INFO Privilege 'VIEW_FULL_METADATA' assigned successfully to catalog role 'readonly_catalog_role'
   2025-04-27 17:53:20,843 INFO Assigning privilege 'NAMESPACE_FULL_METADATA' at level 'catalog' for catalog 'quickstart_catalog' to catalog role 'readonly_catalog_role'
   2025-04-27 17:53:20,848 INFO Privilege 'NAMESPACE_FULL_METADATA' assigned successfully to catalog role 'readonly_catalog_role'
   2025-04-27 17:53:20,848 INFO Assigning privilege 'CATALOG_READ_PROPERTIES' at level 'catalog' for catalog 'quickstart_catalog' to catalog role 'readonly_catalog_role'
   2025-04-27 17:53:20,851 INFO Privilege 'CATALOG_READ_PROPERTIES' assigned successfully to catalog role 'readonly_catalog_role'
   2025-04-27 17:53:20,851 INFO Assigning privilege 'TABLE_READ_DATA' at level 'namespace' for catalog 'quickstart_catalog' to catalog role 'dev_catalog_role'
   2025-04-27 17:53:20,857 INFO Privilege 'TABLE_READ_DATA' assigned successfully to catalog role 'dev_catalog_role'
   2025-04-27 17:53:20,857 INFO Assigning privilege 'TABLE_WRITE_DATA' at level 'namespace' for catalog 'quickstart_catalog' to catalog role 'dev_catalog_role'
   2025-04-27 17:53:20,860 INFO Privilege 'TABLE_WRITE_DATA' assigned successfully to catalog role 'dev_catalog_role'
   2025-04-27 17:53:20,860 INFO Assigning privilege 'TABLE_FULL_METADATA' at level 'namespace' for catalog 'quickstart_catalog' to catalog role 'dev_catalog_role'
   2025-04-27 17:53:20,864 INFO Privilege 'TABLE_FULL_METADATA' assigned successfully to catalog role 'dev_catalog_role'
   2025-04-27 17:53:20,864 INFO Step 8 completed: Privileges creation process finished.
   2025-04-27 17:53:20,864 INFO === Setup Process Completed Successfully ===
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "MonkeyCanCode (via GitHub)" <gi...@apache.org>.
MonkeyCanCode commented on code in PR #1474:
URL: https://github.com/apache/polaris/pull/1474#discussion_r2065246539


##########
client/python/cli/command/setup.py:
##########
@@ -0,0 +1,1035 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+import os
+import logging
+import yaml
+from dataclasses import dataclass
+from typing import Dict, Optional, List, Any, Set
+
+from cli.command import Command
+from cli.constants import Subcommands, StorageType, UNIT_SEPARATOR, Actions, PrincipalType, CatalogType
+
+from polaris.management import PolarisDefaultApi
+from cli.command.principals import PrincipalsCommand
+from cli.command.principal_roles import PrincipalRolesCommand
+from cli.command.catalogs import CatalogsCommand
+from cli.command.catalog_roles import CatalogRolesCommand
+from cli.command.namespaces import NamespacesCommand
+from cli.command.privileges import PrivilegesCommand
+
+logging.basicConfig(
+    format='%(asctime)s %(levelname)s %(message)s',
+    level=logging.INFO
+)
+logger = logging.getLogger(__name__)
+
+@dataclass
+class SetupCommand(Command):
+    setup_subcommand: str
+    setup_config: str
+    _config_cache: Optional[Dict[str, Any]] = None
+
+    def _load_setup_config(self) -> Dict[str, Any]:
+        """
+        Load and cache the setup configuration from a YAML file.
+        """
+        if self._config_cache is not None:
+            return self._config_cache
+
+        if not os.path.isfile(self.setup_config):
+            raise FileNotFoundError(f"Config file not found: {self.setup_config}")
+
+        try:
+            with open(self.setup_config, 'r') as file:
+                self._config_cache = yaml.safe_load(file)
+                if not isinstance(self._config_cache, dict):
+                    raise ValueError("Invalid configuration format: Expected a dictionary at the root level.")
+                return self._config_cache
+        except (yaml.YAMLError, ValueError) as e:
+            raise ValueError(f"Failed to parse YAML configuration: {e}")
+
+    def _extract_principals(self) -> List[Dict[str, Any]]:
+        """
+        Extract principal information from the setup configuration.
+        """
+        config = self._load_setup_config()
+        principals = config.get('principals', [])
+        extracted = []
+        seen = set()
+
+        # Get allowed principal types from PrincipalType
+        allowed_principal_types = {pt.value for pt in PrincipalType}
+
+        for principal in principals:
+            name = principal.get('name')
+            principal_type = principal.get('type', PrincipalType.SERVICE.value).lower()  # Default to 'service' and normalize to lowercase
+            properties = principal.get('properties', {})
+
+            # Validate required fields
+            missing_fields = [field for field, value in {
+                "name": name
+            }.items() if not value]
+
+            if missing_fields:
+                logger.warning(f"Skipping principal due to missing required fields: {', '.join(missing_fields)}. Principal: {principal}")
+                continue
+
+            # Validate principal type
+            if principal_type not in allowed_principal_types:
+                logger.warning(f"Skipping principal '{name}' due to invalid type '{principal_type}'. Allowed types: {', '.join(allowed_principal_types)}")
+                continue
+
+            # Check for duplicate principals
+            if name in seen:
+                logger.warning(f"Skipping duplicate principal: '{name}'")
+                continue
+
+            seen.add(name)
+            extracted.append({
+                'name': name,
+                'type': principal_type.upper(),
+                'properties': properties,
+            })
+
+        if not extracted:
+            logger.warning("No valid principals found in the configuration.")
+
+        return extracted
+
+    def _get_current_principals(self, api: PolarisDefaultApi) -> Set[str]:
+        """
+        Get the current principals from the API.
+        Returns a set of principal names.
+        """
+        try:
+            # Fetch principals from the API
+            principals = api.list_principals().principals
+            return {principal.name for principal in principals}
+        except Exception as e:
+            logger.error(f"Failed to fetch existing principals: {e}")
+            return set()
+
+    def _create_principals(self, api: PolarisDefaultApi):
+        """
+        Create principals based on the setup configuration.
+        """
+        try:
+            # Fetch existing principals from the API
+            existed_principals = self._get_current_principals(api)
+
+            # Extract principals from the configuration
+            extracted_principals = self._extract_principals()
+
+            # Separate new and skipped principals
+            new_principals = [
+                principal for principal in extracted_principals
+                if principal['name'] not in existed_principals
+            ]
+            skipped_principals = [
+                principal['name'] for principal in extracted_principals
+                if principal['name'] in existed_principals
+            ]
+
+            # Log skipped principals
+            if skipped_principals:
+                logger.warning(f"Skipping creation for already existing principals: {', '.join(skipped_principals)}")
+
+            # Create new principals
+            for principal in new_principals:
+                try:
+                    logger.info(f"Creating principal: {principal['name']}")
+                    principal_command = PrincipalsCommand(
+                        principals_subcommand=Subcommands.CREATE,
+                        type=principal['type'].upper(),
+                        principal_name=principal['name'],
+                        client_id='',  # Default value
+                        principal_role='',  # Default value
+                        properties=principal['properties'],
+                        set_properties={},  # Default value
+                        remove_properties=[]  # Default value
+                    )
+                    principal_command.execute(api)
+                    logger.info(f"Principal '{principal['name']}' created successfully.")
+                except Exception as e:
+                    logger.error(f"Failed to create principal '{principal['name']}': {e}")
+
+        except Exception as e:
+            logger.error(f"Failed to create principals: {e}")
+    
+    def _extract_principals_role(self) -> List[Dict[str, Any]]:
+        """
+        Extract principal role information from the setup configuration.
+        """
+        config = self._load_setup_config()
+        principal_roles = config.get('principal_roles', [])
+        extracted = []
+        seen = set()
+
+        for role in principal_roles:
+            name = role.get('name')
+            properties = role.get('properties', {})
+
+            # Validate required fields
+            missing_fields = [field for field, value in {
+                "name": name
+            }.items() if not value]
+
+            if missing_fields:
+                logger.warning(f"Skipping principal role due to missing required fields: {', '.join(missing_fields)}. Role: {role}")
+                continue
+
+            # Check for duplicate principal roles
+            if name in seen:
+                logger.warning(f"Skipping duplicate principal role: '{name}'")
+                continue
+
+            seen.add(name)
+            extracted.append({
+                'name': name,
+                'properties': properties,
+            })
+
+        if not extracted:
+            logger.warning("No valid principal roles found in the configuration.")
+
+        return extracted
+
+    def _get_current_principal_roles(self, api: PolarisDefaultApi) -> Set[str]:
+        """
+        Get the current principal roles from the API.
+        Returns a set of principal role names.
+        """
+        try:
+            # Fetch principal roles from the API
+            principal_roles = api.list_principal_roles().roles
+            return {role.name for role in principal_roles}
+        except Exception as e:
+            logger.error(f"Failed to fetch existing principal roles: {e}")
+            return set()
+
+    def _create_principal_roles(self, api: PolarisDefaultApi):
+        """
+        Create principal roles based on the setup configuration.
+        """
+        try:
+            # Fetch existing principal roles from the API
+            existed_principal_roles = self._get_current_principal_roles(api)
+
+            # Extract principal roles from the configuration
+            extracted_principal_roles = self._extract_principals_role()
+
+            # Separate new and existing principal roles
+            new_principal_roles = [
+                role for role in extracted_principal_roles
+                if role['name'] not in existed_principal_roles
+            ]
+            skipped_principal_roles = [
+                role['name'] for role in extracted_principal_roles
+                if role['name'] in existed_principal_roles
+            ]
+
+            # Log skipped principal roles
+            if skipped_principal_roles:
+                logger.warning(f"Skipping creation for already existing principal roles: {', '.join(skipped_principal_roles)}")
+
+            # Create new principal roles
+            for role in new_principal_roles:
+                try:
+                    logger.info(f"Creating principal role: {role['name']}")
+                    principal_role_command = PrincipalRolesCommand(
+                        principal_roles_subcommand=Subcommands.CREATE,
+                        principal_role_name=role['name'],
+                        principal_name='',  # Default value
+                        catalog_name='',  # Default value
+                        catalog_role_name='',  # Default value
+                        properties=role['properties'],
+                        set_properties={},  # Default value
+                        remove_properties=[]  # Default value
+                    )
+                    principal_role_command.execute(api)
+                    logger.info(f"Principal role '{role['name']}' created successfully.")
+                except Exception as e:
+                    logger.error(f"Failed to create principal role '{role['name']}': {e}")
+        except Exception as e:
+            logger.error(f"Failed to create principal roles: {e}")
+
+    def _extract_principals_role_assignments(self) -> List[Dict[str, str]]:
+        """
+        Extract principal-to-principal-role assignments from the setup configuration.
+        """
+        config = self._load_setup_config()
+        principals = config.get('principals', [])
+        assignments = []
+        seen = set()
+
+        for principal in principals:
+            name = principal.get('name')
+            if not name:
+                logger.warning(f"Skipping principal with missing 'name': {principal}")
+                continue
+
+            for assignment in principal.get('assignments', []):
+                principal_role = assignment.get('principal_role')
+
+                # Validate required fields
+                missing_fields = [field for field, value in {
+                    "principal": name,
+                    "principal_role": principal_role
+                }.items() if not value]
+
+                if missing_fields:
+                    logger.warning(f"Skipping assignment due to missing required fields: {', '.join(missing_fields)}. Assignment: {assignment}")
+                    continue
+
+                # Check for duplicate assignments
+                assignment_key = (name, principal_role)
+                if assignment_key in seen:
+                    logger.warning(f"Skipping duplicate assignment of role '{principal_role}' to principal '{name}'")
+                    continue
+
+                seen.add(assignment_key)
+                assignments.append({
+                    'principal': name,
+                    'principal_role': principal_role,
+                })
+
+        if not assignments:
+            logger.warning("No valid principal-to-principal-role assignments found in the configuration.")
+
+        return assignments
+
+    def _create_principal_role_assignments(self, api: PolarisDefaultApi):
+        """
+        Create principal-to-principal-role assignments based on the setup configuration.
+        """
+        try:
+            # Fetch existing principal roles from the API
+            existed_principal_role_names = self._get_current_principal_roles(api)
+
+            # Extract assignments from the configuration
+            extracted_assignments = self._extract_principals_role_assignments()
+
+            # Process each assignment
+            for assignment in extracted_assignments:
+                principal_name = assignment['principal']
+                principal_role = assignment['principal_role']
+
+                # Validate that the principal role exists
+                if principal_role not in existed_principal_role_names:
+                    logger.warning(f"Skipping assignment for non-existing principal role '{principal_role}' for principal '{principal_name}'")
+                    continue
+
+                # Assign the principal role
+                try:
+                    logger.info(f"Assigning principal '{principal_name}' to role '{principal_role}'")
+                    principal_role_command = PrincipalRolesCommand(
+                        principal_roles_subcommand=Subcommands.GRANT,
+                        principal_name=principal_name,
+                        principal_role_name=principal_role,
+                        catalog_name='',  # Default value
+                        catalog_role_name='',  # Default value
+                        properties='',  # Default value
+                        set_properties={},  # Default value
+                        remove_properties=[]  # Default value
+                    )
+                    principal_role_command.execute(api)
+                    logger.info(f"Assigned principal '{principal_name}' to role '{principal_role}' successfully.")
+                except Exception as e:
+                    logger.error(f"Failed to assign principal '{principal_name}' to role '{principal_role}': {e}")
+        except Exception as e:
+            logger.error(f"Failed to create principal role assignments: {e}")
+
+    def _extract_catalogs(self) -> List[Dict[str, Any]]:
+        """
+        Extract catalog information from the setup configuration.
+        """
+        config = self._load_setup_config()
+        catalogs = config.get('catalogs', [])
+        extracted = []
+        seen = set()
+
+        # Get allowed catalog types from CatalogType
+        allowed_catalog_types = {ct.value for ct in CatalogType}
+
+        # Get allowed storage types from StorageType
+        allowed_storage_types = {st.value for st in StorageType}
+
+        for catalog in catalogs:
+            name = catalog.get('name')
+            storage_type = catalog.get('storage_type').lower() # Normalize to lowercase
+            default_base_location = catalog.get('default_base_location')
+            role_arn = catalog.get('role_arn')
+            tenant_id = catalog.get('tenant_id')
+            service_account = catalog.get('service_account')
+            catalog_type = catalog.get('type', CatalogType.INTERNAL.value).lower()  # Default to 'internal' and normalize to lowercase
+            remote_url = catalog.get('remote_url')
+
+            # Validate required fields
+            missing_fields = [field for field, value in {
+                "name": name,
+                "storage_type": storage_type,
+                "default_base_location": default_base_location
+            }.items() if not value]
+
+            if missing_fields:
+                logger.warning(f"Skipping catalog due to missing required fields: {', '.join(missing_fields)}. Catalog: {catalog}")
+                continue
+
+            # Validate catalog type
+            if catalog_type not in allowed_catalog_types:
+                logger.warning(f"Skipping catalog '{name}' due to invalid type '{catalog_type}'. Allowed types: {', '.join(allowed_catalog_types)}")
+                continue
+
+            # Validate storage type
+            if storage_type not in allowed_storage_types:
+                logger.warning(f"Skipping catalog '{name}' due to invalid storage type '{storage_type}'. Allowed types: {', '.join(allowed_storage_types)}")
+                continue
+
+            # Additional validation for specific catalog/storage types
+            if catalog_type == CatalogType.EXTERNAL.value and not remote_url:
+                logger.warning(f"Skipping external catalog with missing 'remote_url': {catalog}")
+                continue
+            if storage_type == StorageType.S3.value and not role_arn:
+                logger.warning(f"Skipping S3 catalog with missing 'role_arn': {catalog}")
+                continue
+            if storage_type == StorageType.AZURE.value and not tenant_id:
+                logger.warning(f"Skipping Azure catalog with missing 'tenant_id': {catalog}")
+                continue
+            if storage_type == StorageType.GCS.value and not service_account:

Review Comment:
   Got it. This is very good to know. Thanks for the info. I will remove this if we plan to move forward with implementing this within this PR and not move to sync tool. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "adnanhemani (via GitHub)" <gi...@apache.org>.
adnanhemani commented on code in PR #1474:
URL: https://github.com/apache/polaris/pull/1474#discussion_r2065171368


##########
client/python/cli/command/setup.py:
##########
@@ -0,0 +1,1035 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+import os
+import logging
+import yaml
+from dataclasses import dataclass
+from typing import Dict, Optional, List, Any, Set
+
+from cli.command import Command
+from cli.constants import Subcommands, StorageType, UNIT_SEPARATOR, Actions, PrincipalType, CatalogType
+
+from polaris.management import PolarisDefaultApi
+from cli.command.principals import PrincipalsCommand
+from cli.command.principal_roles import PrincipalRolesCommand
+from cli.command.catalogs import CatalogsCommand
+from cli.command.catalog_roles import CatalogRolesCommand
+from cli.command.namespaces import NamespacesCommand
+from cli.command.privileges import PrivilegesCommand
+
+logging.basicConfig(
+    format='%(asctime)s %(levelname)s %(message)s',
+    level=logging.INFO
+)
+logger = logging.getLogger(__name__)
+
+@dataclass
+class SetupCommand(Command):
+    setup_subcommand: str
+    setup_config: str
+    _config_cache: Optional[Dict[str, Any]] = None
+
+    def _load_setup_config(self) -> Dict[str, Any]:
+        """
+        Load and cache the setup configuration from a YAML file.
+        """
+        if self._config_cache is not None:
+            return self._config_cache
+
+        if not os.path.isfile(self.setup_config):
+            raise FileNotFoundError(f"Config file not found: {self.setup_config}")
+
+        try:
+            with open(self.setup_config, 'r') as file:
+                self._config_cache = yaml.safe_load(file)
+                if not isinstance(self._config_cache, dict):
+                    raise ValueError("Invalid configuration format: Expected a dictionary at the root level.")
+                return self._config_cache
+        except (yaml.YAMLError, ValueError) as e:
+            raise ValueError(f"Failed to parse YAML configuration: {e}")
+
+    def _extract_principals(self) -> List[Dict[str, Any]]:
+        """
+        Extract principal information from the setup configuration.
+        """
+        config = self._load_setup_config()
+        principals = config.get('principals', [])
+        extracted = []
+        seen = set()
+
+        # Get allowed principal types from PrincipalType
+        allowed_principal_types = {pt.value for pt in PrincipalType}
+
+        for principal in principals:
+            name = principal.get('name')
+            principal_type = principal.get('type', PrincipalType.SERVICE.value).lower()  # Default to 'service' and normalize to lowercase
+            properties = principal.get('properties', {})
+
+            # Validate required fields
+            missing_fields = [field for field, value in {
+                "name": name
+            }.items() if not value]
+
+            if missing_fields:
+                logger.warning(f"Skipping principal due to missing required fields: {', '.join(missing_fields)}. Principal: {principal}")
+                continue
+
+            # Validate principal type
+            if principal_type not in allowed_principal_types:
+                logger.warning(f"Skipping principal '{name}' due to invalid type '{principal_type}'. Allowed types: {', '.join(allowed_principal_types)}")
+                continue
+
+            # Check for duplicate principals
+            if name in seen:
+                logger.warning(f"Skipping duplicate principal: '{name}'")
+                continue
+
+            seen.add(name)
+            extracted.append({
+                'name': name,
+                'type': principal_type.upper(),
+                'properties': properties,
+            })
+
+        if not extracted:
+            logger.warning("No valid principals found in the configuration.")
+
+        return extracted
+
+    def _get_current_principals(self, api: PolarisDefaultApi) -> Set[str]:
+        """
+        Get the current principals from the API.
+        Returns a set of principal names.
+        """
+        try:
+            # Fetch principals from the API
+            principals = api.list_principals().principals
+            return {principal.name for principal in principals}
+        except Exception as e:
+            logger.error(f"Failed to fetch existing principals: {e}")
+            return set()
+
+    def _create_principals(self, api: PolarisDefaultApi):
+        """
+        Create principals based on the setup configuration.
+        """
+        try:
+            # Fetch existing principals from the API
+            existed_principals = self._get_current_principals(api)
+
+            # Extract principals from the configuration
+            extracted_principals = self._extract_principals()
+
+            # Separate new and skipped principals
+            new_principals = [
+                principal for principal in extracted_principals
+                if principal['name'] not in existed_principals
+            ]
+            skipped_principals = [
+                principal['name'] for principal in extracted_principals
+                if principal['name'] in existed_principals
+            ]
+
+            # Log skipped principals
+            if skipped_principals:
+                logger.warning(f"Skipping creation for already existing principals: {', '.join(skipped_principals)}")
+
+            # Create new principals
+            for principal in new_principals:
+                try:
+                    logger.info(f"Creating principal: {principal['name']}")
+                    principal_command = PrincipalsCommand(
+                        principals_subcommand=Subcommands.CREATE,
+                        type=principal['type'].upper(),
+                        principal_name=principal['name'],
+                        client_id='',  # Default value
+                        principal_role='',  # Default value
+                        properties=principal['properties'],
+                        set_properties={},  # Default value
+                        remove_properties=[]  # Default value
+                    )
+                    principal_command.execute(api)
+                    logger.info(f"Principal '{principal['name']}' created successfully.")
+                except Exception as e:
+                    logger.error(f"Failed to create principal '{principal['name']}': {e}")
+
+        except Exception as e:
+            logger.error(f"Failed to create principals: {e}")
+    
+    def _extract_principals_role(self) -> List[Dict[str, Any]]:
+        """
+        Extract principal role information from the setup configuration.
+        """
+        config = self._load_setup_config()
+        principal_roles = config.get('principal_roles', [])
+        extracted = []
+        seen = set()
+
+        for role in principal_roles:
+            name = role.get('name')
+            properties = role.get('properties', {})
+
+            # Validate required fields
+            missing_fields = [field for field, value in {
+                "name": name
+            }.items() if not value]
+
+            if missing_fields:
+                logger.warning(f"Skipping principal role due to missing required fields: {', '.join(missing_fields)}. Role: {role}")
+                continue
+
+            # Check for duplicate principal roles
+            if name in seen:
+                logger.warning(f"Skipping duplicate principal role: '{name}'")
+                continue
+
+            seen.add(name)
+            extracted.append({
+                'name': name,
+                'properties': properties,
+            })
+
+        if not extracted:
+            logger.warning("No valid principal roles found in the configuration.")
+
+        return extracted
+
+    def _get_current_principal_roles(self, api: PolarisDefaultApi) -> Set[str]:
+        """
+        Get the current principal roles from the API.
+        Returns a set of principal role names.
+        """
+        try:
+            # Fetch principal roles from the API
+            principal_roles = api.list_principal_roles().roles
+            return {role.name for role in principal_roles}
+        except Exception as e:
+            logger.error(f"Failed to fetch existing principal roles: {e}")
+            return set()
+
+    def _create_principal_roles(self, api: PolarisDefaultApi):
+        """
+        Create principal roles based on the setup configuration.
+        """
+        try:
+            # Fetch existing principal roles from the API
+            existed_principal_roles = self._get_current_principal_roles(api)
+
+            # Extract principal roles from the configuration
+            extracted_principal_roles = self._extract_principals_role()
+
+            # Separate new and existing principal roles
+            new_principal_roles = [
+                role for role in extracted_principal_roles
+                if role['name'] not in existed_principal_roles
+            ]
+            skipped_principal_roles = [
+                role['name'] for role in extracted_principal_roles
+                if role['name'] in existed_principal_roles
+            ]
+
+            # Log skipped principal roles
+            if skipped_principal_roles:
+                logger.warning(f"Skipping creation for already existing principal roles: {', '.join(skipped_principal_roles)}")
+
+            # Create new principal roles
+            for role in new_principal_roles:
+                try:
+                    logger.info(f"Creating principal role: {role['name']}")
+                    principal_role_command = PrincipalRolesCommand(
+                        principal_roles_subcommand=Subcommands.CREATE,
+                        principal_role_name=role['name'],
+                        principal_name='',  # Default value
+                        catalog_name='',  # Default value
+                        catalog_role_name='',  # Default value
+                        properties=role['properties'],
+                        set_properties={},  # Default value
+                        remove_properties=[]  # Default value
+                    )
+                    principal_role_command.execute(api)
+                    logger.info(f"Principal role '{role['name']}' created successfully.")
+                except Exception as e:
+                    logger.error(f"Failed to create principal role '{role['name']}': {e}")
+        except Exception as e:
+            logger.error(f"Failed to create principal roles: {e}")
+
+    def _extract_principals_role_assignments(self) -> List[Dict[str, str]]:
+        """
+        Extract principal-to-principal-role assignments from the setup configuration.
+        """
+        config = self._load_setup_config()
+        principals = config.get('principals', [])
+        assignments = []
+        seen = set()
+
+        for principal in principals:
+            name = principal.get('name')
+            if not name:
+                logger.warning(f"Skipping principal with missing 'name': {principal}")
+                continue
+
+            for assignment in principal.get('assignments', []):
+                principal_role = assignment.get('principal_role')
+
+                # Validate required fields
+                missing_fields = [field for field, value in {
+                    "principal": name,
+                    "principal_role": principal_role
+                }.items() if not value]
+
+                if missing_fields:
+                    logger.warning(f"Skipping assignment due to missing required fields: {', '.join(missing_fields)}. Assignment: {assignment}")
+                    continue
+
+                # Check for duplicate assignments
+                assignment_key = (name, principal_role)
+                if assignment_key in seen:
+                    logger.warning(f"Skipping duplicate assignment of role '{principal_role}' to principal '{name}'")
+                    continue
+
+                seen.add(assignment_key)
+                assignments.append({
+                    'principal': name,
+                    'principal_role': principal_role,
+                })
+
+        if not assignments:
+            logger.warning("No valid principal-to-principal-role assignments found in the configuration.")
+
+        return assignments
+
+    def _create_principal_role_assignments(self, api: PolarisDefaultApi):
+        """
+        Create principal-to-principal-role assignments based on the setup configuration.
+        """
+        try:
+            # Fetch existing principal roles from the API
+            existed_principal_role_names = self._get_current_principal_roles(api)
+
+            # Extract assignments from the configuration
+            extracted_assignments = self._extract_principals_role_assignments()
+
+            # Process each assignment
+            for assignment in extracted_assignments:
+                principal_name = assignment['principal']
+                principal_role = assignment['principal_role']
+
+                # Validate that the principal role exists
+                if principal_role not in existed_principal_role_names:
+                    logger.warning(f"Skipping assignment for non-existing principal role '{principal_role}' for principal '{principal_name}'")
+                    continue
+
+                # Assign the principal role
+                try:
+                    logger.info(f"Assigning principal '{principal_name}' to role '{principal_role}'")
+                    principal_role_command = PrincipalRolesCommand(
+                        principal_roles_subcommand=Subcommands.GRANT,
+                        principal_name=principal_name,
+                        principal_role_name=principal_role,
+                        catalog_name='',  # Default value
+                        catalog_role_name='',  # Default value
+                        properties='',  # Default value
+                        set_properties={},  # Default value
+                        remove_properties=[]  # Default value
+                    )
+                    principal_role_command.execute(api)
+                    logger.info(f"Assigned principal '{principal_name}' to role '{principal_role}' successfully.")
+                except Exception as e:
+                    logger.error(f"Failed to assign principal '{principal_name}' to role '{principal_role}': {e}")
+        except Exception as e:
+            logger.error(f"Failed to create principal role assignments: {e}")
+
+    def _extract_catalogs(self) -> List[Dict[str, Any]]:
+        """
+        Extract catalog information from the setup configuration.
+        """
+        config = self._load_setup_config()
+        catalogs = config.get('catalogs', [])
+        extracted = []
+        seen = set()
+
+        # Get allowed catalog types from CatalogType
+        allowed_catalog_types = {ct.value for ct in CatalogType}
+
+        # Get allowed storage types from StorageType
+        allowed_storage_types = {st.value for st in StorageType}
+
+        for catalog in catalogs:
+            name = catalog.get('name')
+            storage_type = catalog.get('storage_type').lower() # Normalize to lowercase
+            default_base_location = catalog.get('default_base_location')
+            role_arn = catalog.get('role_arn')
+            tenant_id = catalog.get('tenant_id')
+            service_account = catalog.get('service_account')
+            catalog_type = catalog.get('type', CatalogType.INTERNAL.value).lower()  # Default to 'internal' and normalize to lowercase
+            remote_url = catalog.get('remote_url')
+
+            # Validate required fields
+            missing_fields = [field for field, value in {
+                "name": name,
+                "storage_type": storage_type,
+                "default_base_location": default_base_location
+            }.items() if not value]
+
+            if missing_fields:
+                logger.warning(f"Skipping catalog due to missing required fields: {', '.join(missing_fields)}. Catalog: {catalog}")
+                continue
+
+            # Validate catalog type
+            if catalog_type not in allowed_catalog_types:
+                logger.warning(f"Skipping catalog '{name}' due to invalid type '{catalog_type}'. Allowed types: {', '.join(allowed_catalog_types)}")
+                continue
+
+            # Validate storage type
+            if storage_type not in allowed_storage_types:
+                logger.warning(f"Skipping catalog '{name}' due to invalid storage type '{storage_type}'. Allowed types: {', '.join(allowed_storage_types)}")
+                continue
+
+            # Additional validation for specific catalog/storage types
+            if catalog_type == CatalogType.EXTERNAL.value and not remote_url:
+                logger.warning(f"Skipping external catalog with missing 'remote_url': {catalog}")
+                continue
+            if storage_type == StorageType.S3.value and not role_arn:
+                logger.warning(f"Skipping S3 catalog with missing 'role_arn': {catalog}")
+                continue
+            if storage_type == StorageType.AZURE.value and not tenant_id:
+                logger.warning(f"Skipping Azure catalog with missing 'tenant_id': {catalog}")
+                continue
+            if storage_type == StorageType.GCS.value and not service_account:

Review Comment:
   Same as you, I'm not great with GCP - but I did manage to make it work with the Getting Started experience and did not need the Service Account: https://github.com/apache/polaris/blob/main/getting-started/assets/polaris/create-catalog.sh
   
   It may have to do with your GCP VM setup, it might help to follow this? https://polaris.apache.org/in-dev/unreleased/getting-started/deploying-polaris/quickstart-deploy-gcp/



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "eric-maynard (via GitHub)" <gi...@apache.org>.
eric-maynard commented on PR #1474:
URL: https://github.com/apache/polaris/pull/1474#issuecomment-2837005155

   cc @sfc-gh-tjones / @mansehajsingh for comments on overlap / integration with the sync tool as well


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "MonkeyCanCode (via GitHub)" <gi...@apache.org>.
MonkeyCanCode commented on code in PR #1474:
URL: https://github.com/apache/polaris/pull/1474#discussion_r2064973704


##########
client/python/cli/command/setup.py:
##########
@@ -0,0 +1,1035 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+import os
+import logging
+import yaml
+from dataclasses import dataclass
+from typing import Dict, Optional, List, Any, Set
+
+from cli.command import Command
+from cli.constants import Subcommands, StorageType, UNIT_SEPARATOR, Actions, PrincipalType, CatalogType
+
+from polaris.management import PolarisDefaultApi
+from cli.command.principals import PrincipalsCommand
+from cli.command.principal_roles import PrincipalRolesCommand
+from cli.command.catalogs import CatalogsCommand
+from cli.command.catalog_roles import CatalogRolesCommand
+from cli.command.namespaces import NamespacesCommand
+from cli.command.privileges import PrivilegesCommand
+
+logging.basicConfig(
+    format='%(asctime)s %(levelname)s %(message)s',
+    level=logging.INFO
+)
+logger = logging.getLogger(__name__)
+
+@dataclass
+class SetupCommand(Command):
+    setup_subcommand: str
+    setup_config: str
+    _config_cache: Optional[Dict[str, Any]] = None
+
+    def _load_setup_config(self) -> Dict[str, Any]:
+        """
+        Load and cache the setup configuration from a YAML file.
+        """
+        if self._config_cache is not None:
+            return self._config_cache
+
+        if not os.path.isfile(self.setup_config):
+            raise FileNotFoundError(f"Config file not found: {self.setup_config}")
+
+        try:
+            with open(self.setup_config, 'r') as file:
+                self._config_cache = yaml.safe_load(file)
+                if not isinstance(self._config_cache, dict):
+                    raise ValueError("Invalid configuration format: Expected a dictionary at the root level.")
+                return self._config_cache
+        except (yaml.YAMLError, ValueError) as e:
+            raise ValueError(f"Failed to parse YAML configuration: {e}")
+
+    def _extract_principals(self) -> List[Dict[str, Any]]:
+        """
+        Extract principal information from the setup configuration.
+        """
+        config = self._load_setup_config()
+        principals = config.get('principals', [])
+        extracted = []
+        seen = set()
+
+        # Get allowed principal types from PrincipalType
+        allowed_principal_types = {pt.value for pt in PrincipalType}
+
+        for principal in principals:
+            name = principal.get('name')
+            principal_type = principal.get('type', PrincipalType.SERVICE.value).lower()  # Default to 'service' and normalize to lowercase
+            properties = principal.get('properties', {})
+
+            # Validate required fields
+            missing_fields = [field for field, value in {
+                "name": name
+            }.items() if not value]
+
+            if missing_fields:
+                logger.warning(f"Skipping principal due to missing required fields: {', '.join(missing_fields)}. Principal: {principal}")
+                continue
+
+            # Validate principal type
+            if principal_type not in allowed_principal_types:
+                logger.warning(f"Skipping principal '{name}' due to invalid type '{principal_type}'. Allowed types: {', '.join(allowed_principal_types)}")
+                continue
+
+            # Check for duplicate principals
+            if name in seen:
+                logger.warning(f"Skipping duplicate principal: '{name}'")
+                continue
+
+            seen.add(name)
+            extracted.append({
+                'name': name,
+                'type': principal_type.upper(),
+                'properties': properties,
+            })
+
+        if not extracted:
+            logger.warning("No valid principals found in the configuration.")
+
+        return extracted
+
+    def _get_current_principals(self, api: PolarisDefaultApi) -> Set[str]:
+        """
+        Get the current principals from the API.
+        Returns a set of principal names.
+        """
+        try:
+            # Fetch principals from the API
+            principals = api.list_principals().principals
+            return {principal.name for principal in principals}
+        except Exception as e:
+            logger.error(f"Failed to fetch existing principals: {e}")
+            return set()
+
+    def _create_principals(self, api: PolarisDefaultApi):
+        """
+        Create principals based on the setup configuration.
+        """
+        try:
+            # Fetch existing principals from the API
+            existed_principals = self._get_current_principals(api)
+
+            # Extract principals from the configuration
+            extracted_principals = self._extract_principals()
+
+            # Separate new and skipped principals
+            new_principals = [
+                principal for principal in extracted_principals
+                if principal['name'] not in existed_principals
+            ]
+            skipped_principals = [
+                principal['name'] for principal in extracted_principals
+                if principal['name'] in existed_principals
+            ]
+
+            # Log skipped principals
+            if skipped_principals:
+                logger.warning(f"Skipping creation for already existing principals: {', '.join(skipped_principals)}")
+
+            # Create new principals
+            for principal in new_principals:
+                try:
+                    logger.info(f"Creating principal: {principal['name']}")
+                    principal_command = PrincipalsCommand(
+                        principals_subcommand=Subcommands.CREATE,
+                        type=principal['type'].upper(),
+                        principal_name=principal['name'],
+                        client_id='',  # Default value
+                        principal_role='',  # Default value
+                        properties=principal['properties'],
+                        set_properties={},  # Default value
+                        remove_properties=[]  # Default value
+                    )
+                    principal_command.execute(api)
+                    logger.info(f"Principal '{principal['name']}' created successfully.")
+                except Exception as e:
+                    logger.error(f"Failed to create principal '{principal['name']}': {e}")
+
+        except Exception as e:
+            logger.error(f"Failed to create principals: {e}")
+    
+    def _extract_principals_role(self) -> List[Dict[str, Any]]:
+        """
+        Extract principal role information from the setup configuration.
+        """
+        config = self._load_setup_config()
+        principal_roles = config.get('principal_roles', [])
+        extracted = []
+        seen = set()
+
+        for role in principal_roles:
+            name = role.get('name')
+            properties = role.get('properties', {})
+
+            # Validate required fields
+            missing_fields = [field for field, value in {
+                "name": name
+            }.items() if not value]
+
+            if missing_fields:
+                logger.warning(f"Skipping principal role due to missing required fields: {', '.join(missing_fields)}. Role: {role}")
+                continue
+
+            # Check for duplicate principal roles
+            if name in seen:
+                logger.warning(f"Skipping duplicate principal role: '{name}'")
+                continue
+
+            seen.add(name)
+            extracted.append({
+                'name': name,
+                'properties': properties,
+            })
+
+        if not extracted:
+            logger.warning("No valid principal roles found in the configuration.")
+
+        return extracted
+
+    def _get_current_principal_roles(self, api: PolarisDefaultApi) -> Set[str]:
+        """
+        Get the current principal roles from the API.
+        Returns a set of principal role names.
+        """
+        try:
+            # Fetch principal roles from the API
+            principal_roles = api.list_principal_roles().roles
+            return {role.name for role in principal_roles}
+        except Exception as e:
+            logger.error(f"Failed to fetch existing principal roles: {e}")
+            return set()
+
+    def _create_principal_roles(self, api: PolarisDefaultApi):
+        """
+        Create principal roles based on the setup configuration.
+        """
+        try:
+            # Fetch existing principal roles from the API
+            existed_principal_roles = self._get_current_principal_roles(api)
+
+            # Extract principal roles from the configuration
+            extracted_principal_roles = self._extract_principals_role()
+
+            # Separate new and existing principal roles
+            new_principal_roles = [
+                role for role in extracted_principal_roles
+                if role['name'] not in existed_principal_roles
+            ]
+            skipped_principal_roles = [
+                role['name'] for role in extracted_principal_roles
+                if role['name'] in existed_principal_roles
+            ]
+
+            # Log skipped principal roles
+            if skipped_principal_roles:
+                logger.warning(f"Skipping creation for already existing principal roles: {', '.join(skipped_principal_roles)}")
+
+            # Create new principal roles
+            for role in new_principal_roles:
+                try:
+                    logger.info(f"Creating principal role: {role['name']}")
+                    principal_role_command = PrincipalRolesCommand(
+                        principal_roles_subcommand=Subcommands.CREATE,
+                        principal_role_name=role['name'],
+                        principal_name='',  # Default value
+                        catalog_name='',  # Default value
+                        catalog_role_name='',  # Default value
+                        properties=role['properties'],
+                        set_properties={},  # Default value
+                        remove_properties=[]  # Default value
+                    )
+                    principal_role_command.execute(api)
+                    logger.info(f"Principal role '{role['name']}' created successfully.")
+                except Exception as e:
+                    logger.error(f"Failed to create principal role '{role['name']}': {e}")
+        except Exception as e:
+            logger.error(f"Failed to create principal roles: {e}")
+
+    def _extract_principals_role_assignments(self) -> List[Dict[str, str]]:
+        """
+        Extract principal-to-principal-role assignments from the setup configuration.
+        """
+        config = self._load_setup_config()
+        principals = config.get('principals', [])
+        assignments = []
+        seen = set()
+
+        for principal in principals:
+            name = principal.get('name')
+            if not name:
+                logger.warning(f"Skipping principal with missing 'name': {principal}")
+                continue
+
+            for assignment in principal.get('assignments', []):
+                principal_role = assignment.get('principal_role')
+
+                # Validate required fields
+                missing_fields = [field for field, value in {
+                    "principal": name,
+                    "principal_role": principal_role
+                }.items() if not value]
+
+                if missing_fields:
+                    logger.warning(f"Skipping assignment due to missing required fields: {', '.join(missing_fields)}. Assignment: {assignment}")
+                    continue
+
+                # Check for duplicate assignments
+                assignment_key = (name, principal_role)
+                if assignment_key in seen:
+                    logger.warning(f"Skipping duplicate assignment of role '{principal_role}' to principal '{name}'")
+                    continue
+
+                seen.add(assignment_key)
+                assignments.append({
+                    'principal': name,
+                    'principal_role': principal_role,
+                })
+
+        if not assignments:
+            logger.warning("No valid principal-to-principal-role assignments found in the configuration.")
+
+        return assignments
+
+    def _create_principal_role_assignments(self, api: PolarisDefaultApi):
+        """
+        Create principal-to-principal-role assignments based on the setup configuration.
+        """
+        try:
+            # Fetch existing principal roles from the API
+            existed_principal_role_names = self._get_current_principal_roles(api)
+
+            # Extract assignments from the configuration
+            extracted_assignments = self._extract_principals_role_assignments()
+
+            # Process each assignment
+            for assignment in extracted_assignments:
+                principal_name = assignment['principal']
+                principal_role = assignment['principal_role']
+
+                # Validate that the principal role exists
+                if principal_role not in existed_principal_role_names:
+                    logger.warning(f"Skipping assignment for non-existing principal role '{principal_role}' for principal '{principal_name}'")
+                    continue
+
+                # Assign the principal role
+                try:
+                    logger.info(f"Assigning principal '{principal_name}' to role '{principal_role}'")
+                    principal_role_command = PrincipalRolesCommand(
+                        principal_roles_subcommand=Subcommands.GRANT,
+                        principal_name=principal_name,
+                        principal_role_name=principal_role,
+                        catalog_name='',  # Default value
+                        catalog_role_name='',  # Default value
+                        properties='',  # Default value
+                        set_properties={},  # Default value
+                        remove_properties=[]  # Default value
+                    )
+                    principal_role_command.execute(api)
+                    logger.info(f"Assigned principal '{principal_name}' to role '{principal_role}' successfully.")
+                except Exception as e:
+                    logger.error(f"Failed to assign principal '{principal_name}' to role '{principal_role}': {e}")
+        except Exception as e:
+            logger.error(f"Failed to create principal role assignments: {e}")
+
+    def _extract_catalogs(self) -> List[Dict[str, Any]]:
+        """
+        Extract catalog information from the setup configuration.
+        """
+        config = self._load_setup_config()
+        catalogs = config.get('catalogs', [])
+        extracted = []
+        seen = set()
+
+        # Get allowed catalog types from CatalogType
+        allowed_catalog_types = {ct.value for ct in CatalogType}
+
+        # Get allowed storage types from StorageType
+        allowed_storage_types = {st.value for st in StorageType}
+
+        for catalog in catalogs:
+            name = catalog.get('name')
+            storage_type = catalog.get('storage_type').lower() # Normalize to lowercase
+            default_base_location = catalog.get('default_base_location')
+            role_arn = catalog.get('role_arn')
+            tenant_id = catalog.get('tenant_id')
+            service_account = catalog.get('service_account')
+            catalog_type = catalog.get('type', CatalogType.INTERNAL.value).lower()  # Default to 'internal' and normalize to lowercase
+            remote_url = catalog.get('remote_url')
+
+            # Validate required fields
+            missing_fields = [field for field, value in {
+                "name": name,
+                "storage_type": storage_type,
+                "default_base_location": default_base_location
+            }.items() if not value]
+
+            if missing_fields:
+                logger.warning(f"Skipping catalog due to missing required fields: {', '.join(missing_fields)}. Catalog: {catalog}")
+                continue
+
+            # Validate catalog type
+            if catalog_type not in allowed_catalog_types:
+                logger.warning(f"Skipping catalog '{name}' due to invalid type '{catalog_type}'. Allowed types: {', '.join(allowed_catalog_types)}")
+                continue
+
+            # Validate storage type
+            if storage_type not in allowed_storage_types:
+                logger.warning(f"Skipping catalog '{name}' due to invalid storage type '{storage_type}'. Allowed types: {', '.join(allowed_storage_types)}")
+                continue
+
+            # Additional validation for specific catalog/storage types
+            if catalog_type == CatalogType.EXTERNAL.value and not remote_url:
+                logger.warning(f"Skipping external catalog with missing 'remote_url': {catalog}")
+                continue
+            if storage_type == StorageType.S3.value and not role_arn:
+                logger.warning(f"Skipping S3 catalog with missing 'role_arn': {catalog}")
+                continue
+            if storage_type == StorageType.AZURE.value and not tenant_id:
+                logger.warning(f"Skipping Azure catalog with missing 'tenant_id': {catalog}")
+                continue
+            if storage_type == StorageType.GCS.value and not service_account:

Review Comment:
   Yes, I found that was the case as well from the code. But the example we have all seems to tie to a SA at the end. I don't have much exp with GCP setup...I am assuming something will be needed for the service to be able to talk to GCP in the first place. Thus add the check for SA here.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "MonkeyCanCode (via GitHub)" <gi...@apache.org>.
MonkeyCanCode commented on code in PR #1474:
URL: https://github.com/apache/polaris/pull/1474#discussion_r2064974690


##########
getting-started/assets/polaris/sample-setup-config.yaml:
##########
@@ -0,0 +1,174 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+catalogs:
+  - name: "quickstart_catalog"
+    type: internal
+    storage_type: "file"
+    default_base_location: "file:///var/tmp/quickstart_catalog/"
+    allowed_locations:
+      - "file:///var/tmp/quickstart_catalog/"
+    properties:
+      catalog: quickstart_catalog
+  - name: "quickstart_catalog_external"
+    type: external
+    storage_type: "file"
+    default_base_location: "file:///var/tmp/quickstart_catalog_external/"
+    allowed_locations:
+      - "file:///var/tmp/quickstart_catalog_external/"
+    remote_url: "https://example.com/quickstart_catalog_external"
+    properties:
+      catalog: quickstart_catalog_external
+  - name: "quickstart_catalog_s3"
+    type: internal
+    storage_type: "s3"
+    default_base_location: "s3://quickstart-bucket/quickstart_catalog/"
+    allowed_locations:
+      - "s3://quickstart-bucket/quickstart_catalog/"
+    role_arn: "arn:aws:iam::123456789012:role/QuickstartS3Role"
+    external_id: "12345678-1234-1234-1234-123456789abc"
+    user_arn: "arn:aws:iam::123456789012:user/QuickstartUser"
+    region: "us-west-2"
+    properties:
+      catalog: quickstart_catalog_s3
+  - name: "quickstart_catalog_azure"
+    type: internal
+    storage_type: "azure"
+    default_base_location: "abfss://container@storageaccount.blob.core.windows.net/quickstart_catalog/"
+    allowed_locations:
+      - "abfss://container@storageaccount.blob.core.windows.net/quickstart_catalog/"
+    tenant_id: "12345678-1234-1234-1234-123456789abc"
+    multi_tenant_app_name: "QuickstartAzureApp"
+    consent_url: "https://login.microsoftonline.com/consent"
+    properties:
+      catalog: quickstart_catalog_azure
+  ## commented out as implicitly gcs auth is needed

Review Comment:
   I noticed when I run the command with SA, it will actually throw an auth error (implicitly auth during catalog creation?). I am not seeing this for AWS/Azure which i have a lot more exp with as any of the dummy value will work and no implicitly auth invoked during polaris catalog creation. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "MonkeyCanCode (via GitHub)" <gi...@apache.org>.
MonkeyCanCode commented on PR #1474:
URL: https://github.com/apache/polaris/pull/1474#issuecomment-2833730469

   > Overall I think the idea here is pretty cool. One thing I would like to see is the ability to "extract" a setup from an existing deployment. That doesn't necessarily have to happen in the first iteration.
   > 
   > One thing I _do_ think we need to examine more closely is how principal creation will happen and how the secrets will be managed.
   > 
   > This also sort of gets into the same territory as using the [sync tool](https://github.com/apache/polaris-tools/tree/main/polaris-synchronizer) to dump to a file and then load from the file.
   
   So the sync tool is mainly for migration purpose I think where a end-user will need to have the setup first to be able to use that. And yes, I do plan to get a `dump` option to dump existed entities into a setup config (assuming we will proceed with this route). The main purpose for this PR is to allow people to define and bootstrap their environments via a config. For example, assuming I have dev, stage, and prod and I want the basic entities (e.g. principal, principal role, catalog role, and privileges to be the same), I can easily copy/paste the config and change the location refs for catalog. Then for adding in new entities, I will then be able to do this via PR then have github action to continue run this setup command (as if the entities already existed, it will just skip). 
   
   The one thing I am debating myself is support update/delete operations. For update, it is mainly we will need to run a bit more commands to check status then update each of them accordingly (do-able but maybe a bit costly?). For delete, the only catches I can think about we can't delete default catalog admin role and we can't safely drop a catalog as it may have tables/views refs as well other entities that are created outside this command. What do you think?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "MonkeyCanCode (via GitHub)" <gi...@apache.org>.
MonkeyCanCode commented on code in PR #1474:
URL: https://github.com/apache/polaris/pull/1474#discussion_r2062814184


##########
site/content/in-dev/unreleased/command-line-interface.md:
##########
@@ -1169,6 +1172,32 @@ This section outlines example code for a few common operations as well as for so
 
 For especially complex operations, you may wish to instead directly use the Python API.
 
+### setup
+
+The `setup` command is used to automate the creation of various entities in Polaris, such as principals, roles, catalogs, namespaces, and privileges, based on a configuration file. This simplifies the process of setting up a Polaris environment.
+
+`setup` supports the following subcommands:
+
+1. create
+
+#### create
+

Review Comment:
   Updated with `apply` for the sub-command.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "MonkeyCanCode (via GitHub)" <gi...@apache.org>.
MonkeyCanCode commented on PR #1474:
URL: https://github.com/apache/polaris/pull/1474#issuecomment-2836764827

   Got it. Thanks for confirmation. Yes, if the tool will support export/import, then yes. In this case, an end-user can prep the input file for refresh env as well. Alright, let me know how it goes and I should add more code to this PR.
   
   > > So the sync tool is mainly for migration purpose I think where a end-user will need to have the setup first to be able to use that.
   > 
   > Conceptually I agree. However [something that came up](https://lists.apache.org/thread/5p96vdvj5x68kfhk8f8vxo51v0y5x769) during design/review of the sync tool is exactly this. Dump one Polaris to a file, then apply that file to another Polaris. If implemented, that seems identical to the functionality we'd have here for `setup`s. So we should probably figure out which direction we want to go with this.
   > 
   > > For example, assuming I have dev, stage, and prod and I want the basic entities ... to be the same
   > 
   > You could do this with the sync tool right? Also, with both the setup and the sync tool, the Principal credentials would potentially be different. And in the case of the setup as it's currently implemented, how do you even get the principal secrets in a structured way?
   > 
   > > The one thing I am debating myself is support update/delete operations.
   > 
   > The sync tool has the concept of different [modes](https://github.com/apache/polaris-tools/commit/46fe5e057e617eecee4da41bc36791736e3c55de)
   
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "eric-maynard (via GitHub)" <gi...@apache.org>.
eric-maynard commented on code in PR #1474:
URL: https://github.com/apache/polaris/pull/1474#discussion_r2062757656


##########
site/content/in-dev/unreleased/command-line-interface.md:
##########
@@ -1169,6 +1172,32 @@ This section outlines example code for a few common operations as well as for so
 
 For especially complex operations, you may wish to instead directly use the Python API.
 
+### setup
+
+The `setup` command is used to automate the creation of various entities in Polaris, such as principals, roles, catalogs, namespaces, and privileges, based on a configuration file. This simplifies the process of setting up a Polaris environment.
+
+`setup` supports the following subcommands:
+
+1. create
+
+#### create
+

Review Comment:
   When I first saw this, I thought `create` would "create" a setup. Maybe [apply](https://developer.hashicorp.com/terraform/cli/commands/apply) or [deploy](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/) would be more intuitive?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "MonkeyCanCode (via GitHub)" <gi...@apache.org>.
MonkeyCanCode commented on code in PR #1474:
URL: https://github.com/apache/polaris/pull/1474#discussion_r2062761819


##########
site/content/in-dev/unreleased/command-line-interface.md:
##########
@@ -1169,6 +1172,32 @@ This section outlines example code for a few common operations as well as for so
 
 For especially complex operations, you may wish to instead directly use the Python API.
 
+### setup
+
+The `setup` command is used to automate the creation of various entities in Polaris, such as principals, roles, catalogs, namespaces, and privileges, based on a configuration file. This simplifies the process of setting up a Polaris environment.
+
+`setup` supports the following subcommands:
+
+1. create
+
+#### create
+

Review Comment:
   Yes. Was try to avoid a sub-command. but I think that is good to create it.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "adnanhemani (via GitHub)" <gi...@apache.org>.
adnanhemani commented on code in PR #1474:
URL: https://github.com/apache/polaris/pull/1474#discussion_r2064827447


##########
getting-started/assets/polaris/sample-setup-config.yaml:
##########
@@ -0,0 +1,174 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+
+catalogs:
+  - name: "quickstart_catalog"
+    type: internal
+    storage_type: "file"
+    default_base_location: "file:///var/tmp/quickstart_catalog/"
+    allowed_locations:
+      - "file:///var/tmp/quickstart_catalog/"
+    properties:
+      catalog: quickstart_catalog
+  - name: "quickstart_catalog_external"
+    type: external
+    storage_type: "file"
+    default_base_location: "file:///var/tmp/quickstart_catalog_external/"
+    allowed_locations:
+      - "file:///var/tmp/quickstart_catalog_external/"
+    remote_url: "https://example.com/quickstart_catalog_external"
+    properties:
+      catalog: quickstart_catalog_external
+  - name: "quickstart_catalog_s3"
+    type: internal
+    storage_type: "s3"
+    default_base_location: "s3://quickstart-bucket/quickstart_catalog/"
+    allowed_locations:
+      - "s3://quickstart-bucket/quickstart_catalog/"
+    role_arn: "arn:aws:iam::123456789012:role/QuickstartS3Role"
+    external_id: "12345678-1234-1234-1234-123456789abc"
+    user_arn: "arn:aws:iam::123456789012:user/QuickstartUser"
+    region: "us-west-2"
+    properties:
+      catalog: quickstart_catalog_s3
+  - name: "quickstart_catalog_azure"
+    type: internal
+    storage_type: "azure"
+    default_base_location: "abfss://container@storageaccount.blob.core.windows.net/quickstart_catalog/"
+    allowed_locations:
+      - "abfss://container@storageaccount.blob.core.windows.net/quickstart_catalog/"
+    tenant_id: "12345678-1234-1234-1234-123456789abc"
+    multi_tenant_app_name: "QuickstartAzureApp"
+    consent_url: "https://login.microsoftonline.com/consent"
+    properties:
+      catalog: quickstart_catalog_azure
+  ## commented out as implicitly gcs auth is needed

Review Comment:
   Can you expand more on why this is the case for GCS, specifically? IIRC, AWS and Azure have their own auth processes that users would need to set up in order to use those platforms (most of these are listed in the "Getting Started - Deploy on xxx" pages for each cloud provider).



##########
client/python/cli/command/setup.py:
##########
@@ -0,0 +1,1035 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+import os
+import logging
+import yaml
+from dataclasses import dataclass
+from typing import Dict, Optional, List, Any, Set
+
+from cli.command import Command
+from cli.constants import Subcommands, StorageType, UNIT_SEPARATOR, Actions, PrincipalType, CatalogType
+
+from polaris.management import PolarisDefaultApi
+from cli.command.principals import PrincipalsCommand
+from cli.command.principal_roles import PrincipalRolesCommand
+from cli.command.catalogs import CatalogsCommand
+from cli.command.catalog_roles import CatalogRolesCommand
+from cli.command.namespaces import NamespacesCommand
+from cli.command.privileges import PrivilegesCommand
+
+logging.basicConfig(
+    format='%(asctime)s %(levelname)s %(message)s',
+    level=logging.INFO
+)
+logger = logging.getLogger(__name__)
+
+@dataclass
+class SetupCommand(Command):
+    setup_subcommand: str
+    setup_config: str
+    _config_cache: Optional[Dict[str, Any]] = None
+
+    def _load_setup_config(self) -> Dict[str, Any]:
+        """
+        Load and cache the setup configuration from a YAML file.
+        """
+        if self._config_cache is not None:
+            return self._config_cache
+
+        if not os.path.isfile(self.setup_config):
+            raise FileNotFoundError(f"Config file not found: {self.setup_config}")
+
+        try:
+            with open(self.setup_config, 'r') as file:
+                self._config_cache = yaml.safe_load(file)
+                if not isinstance(self._config_cache, dict):
+                    raise ValueError("Invalid configuration format: Expected a dictionary at the root level.")
+                return self._config_cache
+        except (yaml.YAMLError, ValueError) as e:
+            raise ValueError(f"Failed to parse YAML configuration: {e}")
+
+    def _extract_principals(self) -> List[Dict[str, Any]]:
+        """
+        Extract principal information from the setup configuration.
+        """
+        config = self._load_setup_config()
+        principals = config.get('principals', [])
+        extracted = []
+        seen = set()
+
+        # Get allowed principal types from PrincipalType
+        allowed_principal_types = {pt.value for pt in PrincipalType}
+
+        for principal in principals:
+            name = principal.get('name')
+            principal_type = principal.get('type', PrincipalType.SERVICE.value).lower()  # Default to 'service' and normalize to lowercase
+            properties = principal.get('properties', {})
+
+            # Validate required fields
+            missing_fields = [field for field, value in {
+                "name": name
+            }.items() if not value]
+
+            if missing_fields:
+                logger.warning(f"Skipping principal due to missing required fields: {', '.join(missing_fields)}. Principal: {principal}")
+                continue
+
+            # Validate principal type
+            if principal_type not in allowed_principal_types:
+                logger.warning(f"Skipping principal '{name}' due to invalid type '{principal_type}'. Allowed types: {', '.join(allowed_principal_types)}")
+                continue
+
+            # Check for duplicate principals
+            if name in seen:
+                logger.warning(f"Skipping duplicate principal: '{name}'")
+                continue
+
+            seen.add(name)
+            extracted.append({
+                'name': name,
+                'type': principal_type.upper(),
+                'properties': properties,
+            })
+
+        if not extracted:
+            logger.warning("No valid principals found in the configuration.")
+
+        return extracted
+
+    def _get_current_principals(self, api: PolarisDefaultApi) -> Set[str]:
+        """
+        Get the current principals from the API.
+        Returns a set of principal names.
+        """
+        try:
+            # Fetch principals from the API
+            principals = api.list_principals().principals
+            return {principal.name for principal in principals}
+        except Exception as e:
+            logger.error(f"Failed to fetch existing principals: {e}")
+            return set()
+
+    def _create_principals(self, api: PolarisDefaultApi):
+        """
+        Create principals based on the setup configuration.
+        """
+        try:
+            # Fetch existing principals from the API
+            existed_principals = self._get_current_principals(api)
+
+            # Extract principals from the configuration
+            extracted_principals = self._extract_principals()
+
+            # Separate new and skipped principals
+            new_principals = [
+                principal for principal in extracted_principals
+                if principal['name'] not in existed_principals
+            ]
+            skipped_principals = [
+                principal['name'] for principal in extracted_principals
+                if principal['name'] in existed_principals
+            ]
+
+            # Log skipped principals
+            if skipped_principals:
+                logger.warning(f"Skipping creation for already existing principals: {', '.join(skipped_principals)}")
+
+            # Create new principals
+            for principal in new_principals:
+                try:
+                    logger.info(f"Creating principal: {principal['name']}")
+                    principal_command = PrincipalsCommand(
+                        principals_subcommand=Subcommands.CREATE,
+                        type=principal['type'].upper(),
+                        principal_name=principal['name'],
+                        client_id='',  # Default value
+                        principal_role='',  # Default value
+                        properties=principal['properties'],
+                        set_properties={},  # Default value
+                        remove_properties=[]  # Default value
+                    )
+                    principal_command.execute(api)
+                    logger.info(f"Principal '{principal['name']}' created successfully.")
+                except Exception as e:
+                    logger.error(f"Failed to create principal '{principal['name']}': {e}")
+
+        except Exception as e:
+            logger.error(f"Failed to create principals: {e}")
+    
+    def _extract_principals_role(self) -> List[Dict[str, Any]]:
+        """
+        Extract principal role information from the setup configuration.
+        """
+        config = self._load_setup_config()
+        principal_roles = config.get('principal_roles', [])
+        extracted = []
+        seen = set()
+
+        for role in principal_roles:
+            name = role.get('name')
+            properties = role.get('properties', {})
+
+            # Validate required fields
+            missing_fields = [field for field, value in {
+                "name": name
+            }.items() if not value]
+
+            if missing_fields:
+                logger.warning(f"Skipping principal role due to missing required fields: {', '.join(missing_fields)}. Role: {role}")
+                continue
+
+            # Check for duplicate principal roles
+            if name in seen:
+                logger.warning(f"Skipping duplicate principal role: '{name}'")
+                continue
+
+            seen.add(name)
+            extracted.append({
+                'name': name,
+                'properties': properties,
+            })
+
+        if not extracted:
+            logger.warning("No valid principal roles found in the configuration.")
+
+        return extracted
+
+    def _get_current_principal_roles(self, api: PolarisDefaultApi) -> Set[str]:
+        """
+        Get the current principal roles from the API.
+        Returns a set of principal role names.
+        """
+        try:
+            # Fetch principal roles from the API
+            principal_roles = api.list_principal_roles().roles
+            return {role.name for role in principal_roles}
+        except Exception as e:
+            logger.error(f"Failed to fetch existing principal roles: {e}")
+            return set()
+
+    def _create_principal_roles(self, api: PolarisDefaultApi):
+        """
+        Create principal roles based on the setup configuration.
+        """
+        try:
+            # Fetch existing principal roles from the API
+            existed_principal_roles = self._get_current_principal_roles(api)
+
+            # Extract principal roles from the configuration
+            extracted_principal_roles = self._extract_principals_role()
+
+            # Separate new and existing principal roles
+            new_principal_roles = [
+                role for role in extracted_principal_roles
+                if role['name'] not in existed_principal_roles
+            ]
+            skipped_principal_roles = [
+                role['name'] for role in extracted_principal_roles
+                if role['name'] in existed_principal_roles
+            ]
+
+            # Log skipped principal roles
+            if skipped_principal_roles:
+                logger.warning(f"Skipping creation for already existing principal roles: {', '.join(skipped_principal_roles)}")
+
+            # Create new principal roles
+            for role in new_principal_roles:
+                try:
+                    logger.info(f"Creating principal role: {role['name']}")
+                    principal_role_command = PrincipalRolesCommand(
+                        principal_roles_subcommand=Subcommands.CREATE,
+                        principal_role_name=role['name'],
+                        principal_name='',  # Default value
+                        catalog_name='',  # Default value
+                        catalog_role_name='',  # Default value
+                        properties=role['properties'],
+                        set_properties={},  # Default value
+                        remove_properties=[]  # Default value
+                    )
+                    principal_role_command.execute(api)
+                    logger.info(f"Principal role '{role['name']}' created successfully.")
+                except Exception as e:
+                    logger.error(f"Failed to create principal role '{role['name']}': {e}")
+        except Exception as e:
+            logger.error(f"Failed to create principal roles: {e}")
+
+    def _extract_principals_role_assignments(self) -> List[Dict[str, str]]:
+        """
+        Extract principal-to-principal-role assignments from the setup configuration.
+        """
+        config = self._load_setup_config()
+        principals = config.get('principals', [])
+        assignments = []
+        seen = set()
+
+        for principal in principals:
+            name = principal.get('name')
+            if not name:
+                logger.warning(f"Skipping principal with missing 'name': {principal}")
+                continue
+
+            for assignment in principal.get('assignments', []):
+                principal_role = assignment.get('principal_role')
+
+                # Validate required fields
+                missing_fields = [field for field, value in {
+                    "principal": name,
+                    "principal_role": principal_role
+                }.items() if not value]
+
+                if missing_fields:
+                    logger.warning(f"Skipping assignment due to missing required fields: {', '.join(missing_fields)}. Assignment: {assignment}")
+                    continue
+
+                # Check for duplicate assignments
+                assignment_key = (name, principal_role)
+                if assignment_key in seen:
+                    logger.warning(f"Skipping duplicate assignment of role '{principal_role}' to principal '{name}'")
+                    continue
+
+                seen.add(assignment_key)
+                assignments.append({
+                    'principal': name,
+                    'principal_role': principal_role,
+                })
+
+        if not assignments:
+            logger.warning("No valid principal-to-principal-role assignments found in the configuration.")
+
+        return assignments
+
+    def _create_principal_role_assignments(self, api: PolarisDefaultApi):
+        """
+        Create principal-to-principal-role assignments based on the setup configuration.
+        """
+        try:
+            # Fetch existing principal roles from the API
+            existed_principal_role_names = self._get_current_principal_roles(api)
+
+            # Extract assignments from the configuration
+            extracted_assignments = self._extract_principals_role_assignments()
+
+            # Process each assignment
+            for assignment in extracted_assignments:
+                principal_name = assignment['principal']
+                principal_role = assignment['principal_role']
+
+                # Validate that the principal role exists
+                if principal_role not in existed_principal_role_names:
+                    logger.warning(f"Skipping assignment for non-existing principal role '{principal_role}' for principal '{principal_name}'")
+                    continue
+
+                # Assign the principal role
+                try:
+                    logger.info(f"Assigning principal '{principal_name}' to role '{principal_role}'")
+                    principal_role_command = PrincipalRolesCommand(
+                        principal_roles_subcommand=Subcommands.GRANT,
+                        principal_name=principal_name,
+                        principal_role_name=principal_role,
+                        catalog_name='',  # Default value
+                        catalog_role_name='',  # Default value
+                        properties='',  # Default value
+                        set_properties={},  # Default value
+                        remove_properties=[]  # Default value
+                    )
+                    principal_role_command.execute(api)
+                    logger.info(f"Assigned principal '{principal_name}' to role '{principal_role}' successfully.")
+                except Exception as e:
+                    logger.error(f"Failed to assign principal '{principal_name}' to role '{principal_role}': {e}")
+        except Exception as e:
+            logger.error(f"Failed to create principal role assignments: {e}")
+
+    def _extract_catalogs(self) -> List[Dict[str, Any]]:
+        """
+        Extract catalog information from the setup configuration.
+        """
+        config = self._load_setup_config()
+        catalogs = config.get('catalogs', [])
+        extracted = []
+        seen = set()
+
+        # Get allowed catalog types from CatalogType
+        allowed_catalog_types = {ct.value for ct in CatalogType}
+
+        # Get allowed storage types from StorageType
+        allowed_storage_types = {st.value for st in StorageType}
+
+        for catalog in catalogs:
+            name = catalog.get('name')
+            storage_type = catalog.get('storage_type').lower() # Normalize to lowercase
+            default_base_location = catalog.get('default_base_location')
+            role_arn = catalog.get('role_arn')
+            tenant_id = catalog.get('tenant_id')
+            service_account = catalog.get('service_account')
+            catalog_type = catalog.get('type', CatalogType.INTERNAL.value).lower()  # Default to 'internal' and normalize to lowercase
+            remote_url = catalog.get('remote_url')
+
+            # Validate required fields
+            missing_fields = [field for field, value in {
+                "name": name,
+                "storage_type": storage_type,
+                "default_base_location": default_base_location
+            }.items() if not value]
+
+            if missing_fields:
+                logger.warning(f"Skipping catalog due to missing required fields: {', '.join(missing_fields)}. Catalog: {catalog}")
+                continue
+
+            # Validate catalog type
+            if catalog_type not in allowed_catalog_types:
+                logger.warning(f"Skipping catalog '{name}' due to invalid type '{catalog_type}'. Allowed types: {', '.join(allowed_catalog_types)}")
+                continue
+
+            # Validate storage type
+            if storage_type not in allowed_storage_types:
+                logger.warning(f"Skipping catalog '{name}' due to invalid storage type '{storage_type}'. Allowed types: {', '.join(allowed_storage_types)}")
+                continue
+
+            # Additional validation for specific catalog/storage types
+            if catalog_type == CatalogType.EXTERNAL.value and not remote_url:
+                logger.warning(f"Skipping external catalog with missing 'remote_url': {catalog}")
+                continue
+            if storage_type == StorageType.S3.value and not role_arn:
+                logger.warning(f"Skipping S3 catalog with missing 'role_arn': {catalog}")
+                continue
+            if storage_type == StorageType.AZURE.value and not tenant_id:
+                logger.warning(f"Skipping Azure catalog with missing 'tenant_id': {catalog}")
+                continue
+            if storage_type == StorageType.GCS.value and not service_account:

Review Comment:
   According to https://github.com/apache/polaris/blob/main/polaris-core/src/main/java/org/apache/polaris/core/storage/gcp/GcpStorageConfigurationInfo.java#L33, Service Account is not a required field.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "MonkeyCanCode (via GitHub)" <gi...@apache.org>.
MonkeyCanCode closed pull request #1474: Add setup CLI command for entities bootstrap
URL: https://github.com/apache/polaris/pull/1474


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "eric-maynard (via GitHub)" <gi...@apache.org>.
eric-maynard commented on code in PR #1474:
URL: https://github.com/apache/polaris/pull/1474#discussion_r2062757830


##########
getting-started/assets/polaris/simple-setup-config.yaml:
##########


Review Comment:
   It's not super obvious to me what the difference between `simple-setup-config` and `sample-setup-config` is meant to be (and they sound really similar!). Is one the quickstart?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "MonkeyCanCode (via GitHub)" <gi...@apache.org>.
MonkeyCanCode commented on code in PR #1474:
URL: https://github.com/apache/polaris/pull/1474#discussion_r2062761630


##########
getting-started/assets/polaris/simple-setup-config.yaml:
##########


Review Comment:
   So the `simple-setup-config` is the basic setup (in this case getting start example) where the `sample-setup-config` contains all options that are supported (ref guide in this case)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "eric-maynard (via GitHub)" <gi...@apache.org>.
eric-maynard commented on PR #1474:
URL: https://github.com/apache/polaris/pull/1474#issuecomment-2835911526

   > So the sync tool is mainly for migration purpose I think where a end-user will need to have the setup first to be able to use that. 
   
   Conceptually I agree. However [something that came up](https://lists.apache.org/thread/5p96vdvj5x68kfhk8f8vxo51v0y5x769) during design/review of the sync tool is exactly this. Dump one Polaris to a file, then apply that file to another Polaris. If implemented, that seems identical to the functionality we'd have here for `setup`s. So we should probably figure out which direction we want to go with this.
   
   > For example, assuming I have dev, stage, and prod and I want the basic entities ... to be the same
   
   You could do this with the sync tool right? Also, with both the setup and the sync tool, the Principal credentials would potentially be different. And in the case of the setup as it's currently implemented, how do you even get the principal secrets in a structured way?
   
   
   > The one thing I am debating myself is support update/delete operations. 
   
   The sync tool has the concept of different [modes](https://github.com/apache/polaris-tools/commit/46fe5e057e617eecee4da41bc36791736e3c55de)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "MonkeyCanCode (via GitHub)" <gi...@apache.org>.
MonkeyCanCode commented on PR #1474:
URL: https://github.com/apache/polaris/pull/1474#issuecomment-2836958208

   > This is a super cool idea - I really like this ability to add the setup to a configuration file! A few questions/comments from me below.
   > 
   > But one thing I'd like to point out is in the `command/setup.py` file, there's quite a bit of code that could be made DRY by parameterizing what is being required (such as entity general validations and API call scaffoldings, amongst other things). I'd personally like to see some refactoring, which will add significantly to the maintainability and readability of the script. I understand that will not be possible for all entities or functions, but most entities are affected by this comment.
   
   For sure. This is more likes POC code to answer couple questions from community around how they can spin up x number of entities for their setup as the current CLI can only do one at a time and custom code is needed to support those. What I have locally is a bash script wrapper to invoke the CLI. While tried to share that bash script, I ended up writing this one as a new command last weekend. Before I spend time on refactor, I think we should check if this utility has overlap with sycn tool @eric-maynard refs to and see where we would want to head for those tooling. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "travis-bowen (via GitHub)" <gi...@apache.org>.
travis-bowen commented on PR #1474:
URL: https://github.com/apache/polaris/pull/1474#issuecomment-2840339845

   Sorry for the delay in reviewing (I'll be able to respond to comments quicker though).
   
   I do think that it would be better to integrate this into the sync tool (at the very least a standalone tool in the tool repo).
   The sync tool should already have a lot of the complexity and nuances implemented to make things easier (different modes such as overwrite, cascading drops, etc.).
   
   It was also restructured to better support things like an import / export scenario after feedback from the [mailing list](https://lists.apache.org/thread/bpflv1plchbq63rll66z607d8jsngf5r).
   
   Basically you'd just update some CLI options to be able to say your source is this setup yaml.
   And then you could create a `PolarisService` [here](https://github.com/apache/polaris-tools/blob/46fe5e057e617eecee4da41bc36791736e3c55de/polaris-synchronizer/cli/src/main/java/org/apache/polaris/tools/sync/polaris/SyncPolarisCommand.java#L134) of a different service type that can implement the interface by just using the file.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add setup CLI command for entities bootstrap [polaris]

Posted by "MonkeyCanCode (via GitHub)" <gi...@apache.org>.
MonkeyCanCode commented on PR #1474:
URL: https://github.com/apache/polaris/pull/1474#issuecomment-2840395822

   > Sorry for the delay in reviewing (I'll be able to respond to comments quicker though).
   > 
   > I do think that it would be better to integrate this into the sync tool (at the very least a standalone tool in the tool repo). The sync tool should already have a lot of the complexity and nuances implemented to make things easier (different modes such as overwrite, cascading drops, etc.).
   > 
   > It was also restructured to better support things like an import / export scenario after feedback from the [mailing list](https://lists.apache.org/thread/bpflv1plchbq63rll66z607d8jsngf5r).
   > 
   > Basically you'd just update some CLI options to be able to say your source is this setup yaml. And then you could create a `PolarisService` [here](https://github.com/apache/polaris-tools/blob/46fe5e057e617eecee4da41bc36791736e3c55de/polaris-synchronizer/cli/src/main/java/org/apache/polaris/tools/sync/polaris/SyncPolarisCommand.java#L134) of a different service type that can implement the interface by just using the file.
   
   All good @travis-bowen. Thanks for the confirmation. In that case, I will close this PR for now. 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@polaris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org