rohdesamuel commented on a change in pull request #16691: URL: https://github.com/apache/beam/pull/16691#discussion_r798953195
########## File path: sdks/python/apache_beam/runners/interactive/dataproc/dataproc_cluster_manager.py ########## @@ -0,0 +1,155 @@ +# +# 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. +# + +# pytype: skip-file + +import logging + +try: + from google.cloud import dataproc_v1 +except ImportError: + raise ImportError( + 'Google Cloud Dataproc not supported for this execution environment.') + +_LOGGER = logging.getLogger(__name__) + + +class DataprocClusterManager(): Review comment: Extraneous parentheses, please remove ########## File path: sdks/python/apache_beam/runners/interactive/dataproc/dataproc_cluster_manager.py ########## @@ -0,0 +1,155 @@ +# +# 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. +# + +# pytype: skip-file + +import logging + +try: + from google.cloud import dataproc_v1 +except ImportError: + raise ImportError( + 'Google Cloud Dataproc not supported for this execution environment.') + +_LOGGER = logging.getLogger(__name__) + + +class DataprocClusterManager(): + """The DataprocClusterManager object simplifies the operations + required for creating and deleting Dataproc clusters for use + under Interactive Beam. + """ + DEFAULT_NAME = 'interactive-beam-cluster' + + def __init__(self, project_id=None, region=None, cluster_name=None): + """Initializes the DataprocClusterManager with properties required + to interface with the Dataproc ClusterControllerClient. + """ + + self.project_id = project_id + if region == 'global': + # The global region is unsupported as it will be eventually deprecated. + raise ValueError('Clusters in the global region are not supported.') + elif region: + self.region = region + else: + _LOGGER.warning( + 'No region information was detected, defaulting Dataproc cluster ' + 'region to: us-central1.') + self.region = 'us-central1' + + if cluster_name: + _LOGGER.warning( + 'A user-specified cluster_name has been detected. ' + 'Please note that you will have to manually delete the Dataproc ' + 'cluster that will be created under the name: %s', + cluster_name) + self.cluster_name = cluster_name + else: + self.cluster_name = self.DEFAULT_NAME + + self.cluster_client = dataproc_v1.ClusterControllerClient( + client_options={ + 'api_endpoint': f'{self.region}-dataproc.googleapis.com:443' + }) + + def _create_cluster(self, cluster): + """Attempts to create a cluster using attributes that were + initialized with the DataprocClusterManager instance. + + Args: + cluster: Dictionary representing Dataproc cluster + """ + try: + self.cluster_client.create_cluster( + request={ + 'project_id': self.project_id, + 'region': self.region, + 'cluster': cluster + }) + _LOGGER.info('Cluster created successfully: %s', self.cluster_name) + except Exception as e: + if e.code == 409: + if self.cluster_name == self.DEFAULT_NAME: + _LOGGER.info( + 'Cluster %s already exists. Continuing...', self.DEFAULT_NAME) + else: + _LOGGER.error( + 'Cluster already exists - unable to create cluster: %s', + self.cluster_name) + raise ValueError( + 'Cluster {} already exists!'.format(self.cluster_name)) + elif e.code == 403: + _LOGGER.error( + 'Due to insufficient project permissions, ' + 'unable to create cluster: %s', + self.cluster_name) + raise ValueError( + 'You cannot create a cluster in project: {}'.format( + self.project_id)) + elif e.code == 501: + _LOGGER.error('Invalid region provided: %s', self.region) + raise ValueError('Region {} does not exist!'.format(self.region)) + else: + _LOGGER.error('Unable to create cluster: %s', self.cluster_name) + raise ValueError( + 'Unable to create cluster: {}'.format(self.cluster_name)) + + def create_flink_cluster(self): + """Calls _create_cluster with a configuration that enables FlinkRunner""" + cluster = { + 'project_id': self.project_id, + 'cluster_name': self.cluster_name, + 'config': { + 'software_config': { + 'optional_components': ['DOCKER', 'FLINK'] + } + } + } + self._create_cluster(cluster) + + def cleanup(self): + """Deletes the cluster that uses the attributes initialized + with the DataprocClusterManager instance if the default + cluster_name is used.""" + if self.cluster_name != self.DEFAULT_NAME: + return + + try: + self.cluster_client.delete_cluster( + request={ + 'project_id': self.project_id, + 'region': self.region, + 'cluster_name': self.cluster_name, + }) + + except Exception as e: + if e.code == 403: + _LOGGER.error( + 'Due to insufficient project permissions, ' + 'unable to delete cluster: %s', + self.cluster_name) + raise ValueError( + 'You cannot delete a cluster in project: {}'.format( + self.project_id)) + elif e.code == 404: + _LOGGER.error('Cluster does not exist: %s', self.cluster_name) + raise ValueError('Cluster was not found: {}'.format(self.cluster_name)) + else: + _LOGGER.error('Failed to delete cluster: %s', self.cluster_name) + raise ValueError( + 'Unable to delete cluster: {}'.format(self.cluster_name)) Review comment: Same here ########## File path: sdks/python/apache_beam/runners/interactive/dataproc/dataproc_cluster_manager.py ########## @@ -0,0 +1,155 @@ +# +# 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. +# + +# pytype: skip-file + +import logging + +try: + from google.cloud import dataproc_v1 +except ImportError: + raise ImportError( + 'Google Cloud Dataproc not supported for this execution environment.') + +_LOGGER = logging.getLogger(__name__) + + +class DataprocClusterManager(): + """The DataprocClusterManager object simplifies the operations + required for creating and deleting Dataproc clusters for use + under Interactive Beam. + """ + DEFAULT_NAME = 'interactive-beam-cluster' + + def __init__(self, project_id=None, region=None, cluster_name=None): + """Initializes the DataprocClusterManager with properties required + to interface with the Dataproc ClusterControllerClient. + """ + + self.project_id = project_id + if region == 'global': + # The global region is unsupported as it will be eventually deprecated. + raise ValueError('Clusters in the global region are not supported.') + elif region: + self.region = region + else: + _LOGGER.warning( + 'No region information was detected, defaulting Dataproc cluster ' + 'region to: us-central1.') + self.region = 'us-central1' + + if cluster_name: + _LOGGER.warning( + 'A user-specified cluster_name has been detected. ' + 'Please note that you will have to manually delete the Dataproc ' + 'cluster that will be created under the name: %s', + cluster_name) + self.cluster_name = cluster_name + else: + self.cluster_name = self.DEFAULT_NAME + + self.cluster_client = dataproc_v1.ClusterControllerClient( + client_options={ + 'api_endpoint': f'{self.region}-dataproc.googleapis.com:443' + }) + + def _create_cluster(self, cluster): + """Attempts to create a cluster using attributes that were + initialized with the DataprocClusterManager instance. + + Args: + cluster: Dictionary representing Dataproc cluster + """ + try: + self.cluster_client.create_cluster( + request={ + 'project_id': self.project_id, + 'region': self.region, + 'cluster': cluster + }) + _LOGGER.info('Cluster created successfully: %s', self.cluster_name) + except Exception as e: + if e.code == 409: + if self.cluster_name == self.DEFAULT_NAME: + _LOGGER.info( + 'Cluster %s already exists. Continuing...', self.DEFAULT_NAME) + else: + _LOGGER.error( + 'Cluster already exists - unable to create cluster: %s', + self.cluster_name) + raise ValueError( + 'Cluster {} already exists!'.format(self.cluster_name)) + elif e.code == 403: + _LOGGER.error( + 'Due to insufficient project permissions, ' + 'unable to create cluster: %s', + self.cluster_name) + raise ValueError( + 'You cannot create a cluster in project: {}'.format( + self.project_id)) + elif e.code == 501: + _LOGGER.error('Invalid region provided: %s', self.region) + raise ValueError('Region {} does not exist!'.format(self.region)) + else: + _LOGGER.error('Unable to create cluster: %s', self.cluster_name) + raise ValueError( + 'Unable to create cluster: {}'.format(self.cluster_name)) Review comment: In the cases of unknown errors, it's best to bubble up the original exception instead of hiding it. ########## File path: sdks/python/apache_beam/runners/interactive/dataproc/dataproc_cluster_manager.py ########## @@ -0,0 +1,155 @@ +# +# 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. +# + +# pytype: skip-file + +import logging + +try: + from google.cloud import dataproc_v1 +except ImportError: + raise ImportError( + 'Google Cloud Dataproc not supported for this execution environment.') + +_LOGGER = logging.getLogger(__name__) + + +class DataprocClusterManager(): + """The DataprocClusterManager object simplifies the operations + required for creating and deleting Dataproc clusters for use + under Interactive Beam. + """ + DEFAULT_NAME = 'interactive-beam-cluster' + + def __init__(self, project_id=None, region=None, cluster_name=None): + """Initializes the DataprocClusterManager with properties required + to interface with the Dataproc ClusterControllerClient. + """ + + self.project_id = project_id + if region == 'global': + # The global region is unsupported as it will be eventually deprecated. + raise ValueError('Clusters in the global region are not supported.') + elif region: + self.region = region + else: + _LOGGER.warning( + 'No region information was detected, defaulting Dataproc cluster ' + 'region to: us-central1.') + self.region = 'us-central1' + + if cluster_name: + _LOGGER.warning( + 'A user-specified cluster_name has been detected. ' + 'Please note that you will have to manually delete the Dataproc ' + 'cluster that will be created under the name: %s', + cluster_name) + self.cluster_name = cluster_name + else: + self.cluster_name = self.DEFAULT_NAME + + self.cluster_client = dataproc_v1.ClusterControllerClient( + client_options={ + 'api_endpoint': f'{self.region}-dataproc.googleapis.com:443' + }) + + def _create_cluster(self, cluster): + """Attempts to create a cluster using attributes that were + initialized with the DataprocClusterManager instance. + + Args: + cluster: Dictionary representing Dataproc cluster + """ + try: + self.cluster_client.create_cluster( Review comment: Wdyt about writing a todo mentioning adding in pip package support when creating a cluster here? ########## File path: sdks/python/apache_beam/runners/interactive/dataproc/dataproc_cluster_manager_test.py ########## @@ -0,0 +1,159 @@ +# +# 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. +# + +# pytype: skip-file + +import unittest +from unittest.mock import patch + +try: + from google.cloud import dataproc_v1 + from apache_beam.runners.interactive.dataproc import dataproc_cluster_manager +except ImportError: + _dataproc_imported = False +else: + _dataproc_imported = True + + +class MockException(Exception): + def __init__(self, code=-1): + self.code = code + + [email protected](not _dataproc_imported, 'dataproc package was not imported.') +class DataprocClusterManagerTest(unittest.TestCase): + """Unit test for DataprocClusterManager""" + @patch( + 'google.cloud.dataproc_v1.ClusterControllerClient.create_cluster', + side_effect=MockException(409)) + def test_create_cluster_default_already_exists(self, mock_cluster_client): + """ + Tests that no exception is thrown when a cluster already exists, + but is using DataprocClusterManager.DEFAULT_NAME. + """ + cluster_manager = dataproc_cluster_manager.DataprocClusterManager() + from apache_beam.runners.interactive.dataproc.dataproc_cluster_manager import _LOGGER + with self.assertLogs(_LOGGER, level='INFO') as context_manager: + cluster_manager._create_cluster({}) + self.assertTrue( + 'Cluster {} already exists'.format(cluster_manager.DEFAULT_NAME) in + context_manager.output[0]) Review comment: The "with ... as ..." statement calls the __exit__ method on the target -- context_manager in this code -- at the end of the block. Usually this is used for cleanup, so it's best to use the object within the with statement rather than outside 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
