You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "VladaZakharova (via GitHub)" <gi...@apache.org> on 2023/07/05 08:25:44 UTC

[GitHub] [airflow] VladaZakharova opened a new pull request, #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

VladaZakharova opened a new pull request, #32365:
URL: https://github.com/apache/airflow/pull/32365

   This PR fixes https://github.com/apache/airflow/issues/29258
   
   The problem was caused by multiple processes updating metadata of the Compute Engine instance when running in parallel: methods _authorize_compute_engine_instance_metadata() and import_ssh_public_key() are used to upload metadata and import ssh keys. Both of them included making API requests to update information inside the instance. When making such requests in parallel all the processes were updating the same data simultaneously, that caused those problems listed in the issue.
   
   The solution here is to use some kind of lock to prevent execution of critical part of the code by several processes at one time. As the Composer is a distributed system, all the processes are running separately, making connection between them hard.
   As the solution in this case i have implemented a logic of creation separate GCS bucket that will hold a file that will be used as a lock for the processes: if the file exists and there is a string inside it - the lock is acquired. After the execution is finished, the lock will be released, so next process could take this lock next. The last process running will delete the bucket.
   
   Note: when establishing connection using os_login, make sure that you have enabled such option for your instance in instance keys and that all of the connections you are trying to establish use the same value for the parameter: once you have enabled os_login for your instance, it will wait the exact type of keys to authenticate correctly. There is no option to mix different types of authentication for one instance.
   <!--
    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.
    -->
   
   <!--
   Thank you for contributing! Please make sure that your code changes
   are covered with tests. And in case of new features or big changes
   remember to adjust the documentation.
   
   Feel free to ping committers for the review!
   
   In case of an existing issue, reference it using one of the following:
   
   closes: #ISSUE
   related: #ISSUE
   
   How to write a good git commit message:
   http://chris.beams.io/posts/git-commit/
   -->
   
   ---
   **^ Add meaningful description above**
   
   Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/CONTRIBUTING.rst#pull-request-guidelines)** for more information.
   In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
   In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [newsfragments](https://github.com/apache/airflow/tree/main/newsfragments).
   


-- 
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: commits-unsubscribe@airflow.apache.org

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


[GitHub] [airflow] VladaZakharova commented on a diff in pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

Posted by "VladaZakharova (via GitHub)" <gi...@apache.org>.
VladaZakharova commented on code in PR #32365:
URL: https://github.com/apache/airflow/pull/32365#discussion_r1274937414


##########
tests/system/providers/google/cloud/compute/example_compute_ssh_os_login.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.
+
+"""
+Example Airflow DAG that starts, stops and sets the machine type of a Google Compute
+Engine instance.
+
+"""
+
+from __future__ import annotations
+
+import os
+from datetime import datetime
+
+from airflow import models
+from airflow.models.baseoperator import chain
+from airflow.providers.google.cloud.hooks.compute_ssh import ComputeEngineSSHHook
+from airflow.providers.google.cloud.operators.compute import (
+    ComputeEngineDeleteInstanceOperator,
+    ComputeEngineInsertInstanceOperator,
+)
+from airflow.providers.ssh.operators.ssh import SSHOperator
+from airflow.utils.trigger_rule import TriggerRule
+
+# [START howto_operator_gce_args_common]
+ENV_ID = os.environ.get("SYSTEM_TESTS_ENV_ID")
+PROJECT_ID = os.environ.get("SYSTEM_TESTS_GCP_PROJECT")
+
+DAG_ID = "cloud_compute_ssh_os_login"
+LOCATION = "europe-west1-b"
+REGION = "europe-west1"
+GCE_INSTANCE_NAME = "instance-ssh-test-oslogin"
+SHORT_MACHINE_TYPE_NAME = "n1-standard-1"
+GCE_INSTANCE_BODY = {
+    "name": GCE_INSTANCE_NAME,
+    "machine_type": f"zones/{LOCATION}/machineTypes/{SHORT_MACHINE_TYPE_NAME}",
+    "metadata": {
+        "items": [
+            {
+                "key": "enable-oslogin",
+                "value": "TRUE",
+            }
+        ]
+    },
+    "disks": [
+        {
+            "boot": True,
+            "device_name": GCE_INSTANCE_NAME,
+            "initialize_params": {
+                "disk_size_gb": "10",
+                "disk_type": f"zones/{LOCATION}/diskTypes/pd-balanced",
+                "source_image": "projects/debian-cloud/global/images/debian-11-bullseye-v20220621",
+            },
+        }
+    ],
+    "network_interfaces": [
+        {
+            "access_configs": [{"name": "External NAT", "network_tier": "PREMIUM"}],
+            "stack_type": "IPV4_ONLY",
+            "subnetwork": f"regions/{REGION}/subnetworks/default",
+        }
+    ],
+}
+# [END howto_operator_gce_args_common]
+
+with models.DAG(
+    DAG_ID,
+    schedule_interval="@once",
+    start_date=datetime(2021, 1, 1),
+    catchup=False,
+    tags=["example", "compute-ssh", "os-login"],
+) as dag:
+    # [START howto_operator_gce_insert]
+    gce_instance_insert = ComputeEngineInsertInstanceOperator(
+        task_id="gcp_compute_create_instance_task",
+        project_id=PROJECT_ID,
+        zone=LOCATION,
+        body=GCE_INSTANCE_BODY,
+    )
+    # [END howto_operator_gce_insert]
+
+    # [START howto_execute_command_on_remote_1]
+    os_login_task1 = SSHOperator(
+        task_id="os_login_task1",
+        ssh_hook=ComputeEngineSSHHook(
+            user="username",
+            instance_name=GCE_INSTANCE_NAME,
+            zone=LOCATION,
+            project_id=PROJECT_ID,
+            use_oslogin=True,
+            use_iap_tunnel=False,
+            cmd_timeout=1,
+        ),
+        command="echo os_login1",
+    )
+    # [END howto_execute_command_on_remote_1]
+
+    # [START howto_execute_command_on_remote_2]
+    os_login_task2 = SSHOperator(
+        task_id="os_login_task2",
+        ssh_hook=ComputeEngineSSHHook(
+            user="username",
+            instance_name=GCE_INSTANCE_NAME,
+            zone=LOCATION,
+            use_oslogin=True,
+            use_iap_tunnel=False,
+            cmd_timeout=1,
+        ),
+        command="echo os_login2",
+    )
+    # [END howto_execute_command_on_remote_2]
+
+    # [START howto_operator_gce_delete_no_project_id]
+    gce_instance_delete = ComputeEngineDeleteInstanceOperator(
+        task_id="gcp_compute_delete_instance_task",
+        zone=LOCATION,
+        resource_id=GCE_INSTANCE_NAME,
+    )
+    # [END howto_operator_gce_delete_no_project_id]
+    gce_instance_delete.trigger_rule = TriggerRule.ALL_DONE
+
+    chain(
+        gce_instance_insert,
+        os_login_task1,
+        os_login_task2,

Review Comment:
   This test is supposed to be the example of just normal running and establishing connections one after another. This PR actually adds a possibility to run in parallel, so there is another system test `tests/system/providers/google/cloud/compute/example_compute_ssh_parallel.py` that shows actual possibility to SSH to instance in parallel. 



-- 
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: commits-unsubscribe@airflow.apache.org

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


[GitHub] [airflow] VladaZakharova commented on pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

Posted by "VladaZakharova (via GitHub)" <gi...@apache.org>.
VladaZakharova commented on PR #32365:
URL: https://github.com/apache/airflow/pull/32365#issuecomment-1653305846

   @kaxil @uranusjr 
   Hi there! Could you also please take a look on the changes? Thanks :)


-- 
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: commits-unsubscribe@airflow.apache.org

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


[GitHub] [airflow] VladaZakharova commented on pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

Posted by "VladaZakharova (via GitHub)" <gi...@apache.org>.
VladaZakharova commented on PR #32365:
URL: https://github.com/apache/airflow/pull/32365#issuecomment-1621447736

   > I am afraid this is going to introduce more problems than it solves.
   > 
   > There are few problems with it:
   > 
   > * you need ot be able to have service account that can create buckets - that's a new capability
   > * bucket is deleted immediately when lock is released, which means that other tasks will have the bucket deleted while they are waiting for the lock. This will cause failures
   > * this is very brittle and not self-healing. If you have one task abruptly killed while it holds the lock (happens when you have hardware failure for example) - your lock will remain and it will hold the whole DAG from re-running until you manually remove the lock
   > * In the future when we have AIP-44 implemented, tasks won't be able to query the DB of Airflow directly so your query about parallel tasks will fail (when AIP-44 is complete we are going to forbid built-in operators in all providers to run any DB query).
   > 
   > So there are many things wrong here. I Cannot propose a different solution, but I think it should be based on the state of metadata - and metadata should be queried before they are updated. That might at least mitigate part of the problem. Ideally some kind of optiistic lock strategy on metadata would be great (i.e automatically updating version number that you can use to get optimisitc lock strategy - but I am afraid metadata API does not support it, maybe some other mechanism that provides a lock - but not based on manually managed GCS lock, something that will automatically release lock when the client gets killed. Not sure what it could be - but the solution proposed here is going IMHO to cause more problems than it solves.
   
   Thank you for the ideas! Yes, looks like i was trying to solve the problem, but there are a lot of unpredictable problems that could happen during DAG execution. I will try to find something else here using the metadata you mentioned :)


-- 
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: commits-unsubscribe@airflow.apache.org

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


[GitHub] [airflow] VladaZakharova commented on a diff in pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

Posted by "VladaZakharova (via GitHub)" <gi...@apache.org>.
VladaZakharova commented on code in PR #32365:
URL: https://github.com/apache/airflow/pull/32365#discussion_r1270573218


##########
airflow/providers/google/cloud/hooks/compute_ssh.py:
##########
@@ -225,40 +227,58 @@ def get_conn(self) -> paramiko.SSHClient:
             hostname = self.hostname
 
         privkey, pubkey = self._generate_ssh_key(self.user)
-        if self.use_oslogin:
-            user = self._authorize_os_login(pubkey)
-        else:
-            user = self.user
-            self._authorize_compute_engine_instance_metadata(pubkey)
-
-        proxy_command = None
-        if self.use_iap_tunnel:
-            proxy_command_args = [
-                "gcloud",
-                "compute",
-                "start-iap-tunnel",
-                str(self.instance_name),
-                "22",
-                "--listen-on-stdin",
-                f"--project={self.project_id}",
-                f"--zone={self.zone}",
-                "--verbosity=warning",
-            ]
-            proxy_command = " ".join(shlex.quote(arg) for arg in proxy_command_args)
-
-        sshclient = self._connect_to_instance(user, hostname, privkey, proxy_command)
+
+        max_retries = 10
+        max_delay = 10
+        sshclient = None
+        for retry in range(max_retries + 1):
+            try:
+                if self.use_oslogin:
+                    user = self._authorize_os_login(pubkey)
+                else:
+                    user = self.user
+                    self._authorize_compute_engine_instance_metadata(pubkey)
+                proxy_command = None
+                if self.use_iap_tunnel:
+                    proxy_command_args = [
+                        "gcloud",
+                        "compute",
+                        "start-iap-tunnel",
+                        str(self.instance_name),
+                        "22",
+                        "--listen-on-stdin",
+                        f"--project={self.project_id}",
+                        f"--zone={self.zone}",
+                        "--verbosity=warning",
+                    ]
+                    proxy_command = " ".join(shlex.quote(arg) for arg in proxy_command_args)
+                sshclient = self._connect_to_instance(user, hostname, privkey, proxy_command)
+                break
+            except (HttpError, AirflowException, SSHException) as exc:
+                if (isinstance(exc, HttpError) and exc.resp.status == 412) or (
+                    isinstance(exc, AirflowException) and "412 PRECONDITION FAILED" in str(exc)
+                ):
+                    self.log.info("Error occurred when trying to update instance metadata: %s", exc)
+                elif isinstance(exc, SSHException):
+                    self.log.info("Error occurred when establishing SSH connection using Paramiko: %s", exc)

Review Comment:
   Sure, good idea, thank you!



-- 
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: commits-unsubscribe@airflow.apache.org

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


[GitHub] [airflow] VladaZakharova closed pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

Posted by "VladaZakharova (via GitHub)" <gi...@apache.org>.
VladaZakharova closed pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections
URL: https://github.com/apache/airflow/pull/32365


-- 
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: commits-unsubscribe@airflow.apache.org

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


[GitHub] [airflow] ahidalgob commented on a diff in pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

Posted by "ahidalgob (via GitHub)" <gi...@apache.org>.
ahidalgob commented on code in PR #32365:
URL: https://github.com/apache/airflow/pull/32365#discussion_r1269369494


##########
airflow/providers/google/cloud/hooks/compute_ssh.py:
##########
@@ -225,40 +227,58 @@ def get_conn(self) -> paramiko.SSHClient:
             hostname = self.hostname
 
         privkey, pubkey = self._generate_ssh_key(self.user)
-        if self.use_oslogin:
-            user = self._authorize_os_login(pubkey)
-        else:
-            user = self.user
-            self._authorize_compute_engine_instance_metadata(pubkey)
-
-        proxy_command = None
-        if self.use_iap_tunnel:
-            proxy_command_args = [
-                "gcloud",
-                "compute",
-                "start-iap-tunnel",
-                str(self.instance_name),
-                "22",
-                "--listen-on-stdin",
-                f"--project={self.project_id}",
-                f"--zone={self.zone}",
-                "--verbosity=warning",
-            ]
-            proxy_command = " ".join(shlex.quote(arg) for arg in proxy_command_args)
-
-        sshclient = self._connect_to_instance(user, hostname, privkey, proxy_command)
+
+        max_retries = 10
+        max_delay = 10
+        sshclient = None
+        for retry in range(max_retries + 1):
+            try:
+                if self.use_oslogin:
+                    user = self._authorize_os_login(pubkey)
+                else:
+                    user = self.user
+                    self._authorize_compute_engine_instance_metadata(pubkey)
+                proxy_command = None
+                if self.use_iap_tunnel:
+                    proxy_command_args = [
+                        "gcloud",
+                        "compute",
+                        "start-iap-tunnel",
+                        str(self.instance_name),
+                        "22",
+                        "--listen-on-stdin",
+                        f"--project={self.project_id}",
+                        f"--zone={self.zone}",
+                        "--verbosity=warning",
+                    ]
+                    proxy_command = " ".join(shlex.quote(arg) for arg in proxy_command_args)
+                sshclient = self._connect_to_instance(user, hostname, privkey, proxy_command)
+                break
+            except (HttpError, AirflowException, SSHException) as exc:
+                if (isinstance(exc, HttpError) and exc.resp.status == 412) or (
+                    isinstance(exc, AirflowException) and "412 PRECONDITION FAILED" in str(exc)
+                ):
+                    self.log.info("Error occurred when trying to update instance metadata: %s", exc)
+                elif isinstance(exc, SSHException):
+                    self.log.info("Error occurred when establishing SSH connection using Paramiko: %s", exc)
+                if retry == max_retries:
+                    raise AirflowException("Maximum retries exceeded. Aborting operation.")
+                delay = random.randint(0, max_delay)
+                self.log.info(f"Failed establish SSH connection, waiting {delay} seconds to retry...")
+                time.sleep(delay)
+        if not sshclient:
+            raise AirflowException("Unable to establish SSH connection.")

Review Comment:
   Nit: This case never happens, does it?



##########
airflow/providers/google/cloud/hooks/compute_ssh.py:
##########
@@ -225,40 +227,58 @@ def get_conn(self) -> paramiko.SSHClient:
             hostname = self.hostname
 
         privkey, pubkey = self._generate_ssh_key(self.user)
-        if self.use_oslogin:
-            user = self._authorize_os_login(pubkey)
-        else:
-            user = self.user
-            self._authorize_compute_engine_instance_metadata(pubkey)
-
-        proxy_command = None
-        if self.use_iap_tunnel:
-            proxy_command_args = [
-                "gcloud",
-                "compute",
-                "start-iap-tunnel",
-                str(self.instance_name),
-                "22",
-                "--listen-on-stdin",
-                f"--project={self.project_id}",
-                f"--zone={self.zone}",
-                "--verbosity=warning",
-            ]
-            proxy_command = " ".join(shlex.quote(arg) for arg in proxy_command_args)
-
-        sshclient = self._connect_to_instance(user, hostname, privkey, proxy_command)
+
+        max_retries = 10

Review Comment:
   Should we make this parameterizable? If a user creates many ssh connections at the same time 10 might not be enough.



##########
airflow/providers/google/cloud/hooks/compute_ssh.py:
##########
@@ -225,40 +227,58 @@ def get_conn(self) -> paramiko.SSHClient:
             hostname = self.hostname
 
         privkey, pubkey = self._generate_ssh_key(self.user)
-        if self.use_oslogin:
-            user = self._authorize_os_login(pubkey)
-        else:
-            user = self.user
-            self._authorize_compute_engine_instance_metadata(pubkey)
-
-        proxy_command = None
-        if self.use_iap_tunnel:
-            proxy_command_args = [
-                "gcloud",
-                "compute",
-                "start-iap-tunnel",
-                str(self.instance_name),
-                "22",
-                "--listen-on-stdin",
-                f"--project={self.project_id}",
-                f"--zone={self.zone}",
-                "--verbosity=warning",
-            ]
-            proxy_command = " ".join(shlex.quote(arg) for arg in proxy_command_args)
-
-        sshclient = self._connect_to_instance(user, hostname, privkey, proxy_command)
+
+        max_retries = 10
+        max_delay = 10
+        sshclient = None
+        for retry in range(max_retries + 1):
+            try:
+                if self.use_oslogin:
+                    user = self._authorize_os_login(pubkey)
+                else:
+                    user = self.user
+                    self._authorize_compute_engine_instance_metadata(pubkey)
+                proxy_command = None
+                if self.use_iap_tunnel:
+                    proxy_command_args = [
+                        "gcloud",
+                        "compute",
+                        "start-iap-tunnel",
+                        str(self.instance_name),
+                        "22",
+                        "--listen-on-stdin",
+                        f"--project={self.project_id}",
+                        f"--zone={self.zone}",
+                        "--verbosity=warning",
+                    ]
+                    proxy_command = " ".join(shlex.quote(arg) for arg in proxy_command_args)
+                sshclient = self._connect_to_instance(user, hostname, privkey, proxy_command)
+                break
+            except (HttpError, AirflowException, SSHException) as exc:
+                if (isinstance(exc, HttpError) and exc.resp.status == 412) or (
+                    isinstance(exc, AirflowException) and "412 PRECONDITION FAILED" in str(exc)
+                ):
+                    self.log.info("Error occurred when trying to update instance metadata: %s", exc)
+                elif isinstance(exc, SSHException):
+                    self.log.info("Error occurred when establishing SSH connection using Paramiko: %s", exc)

Review Comment:
   We could have an `else` to just raise the exception in case the exception was `HttpError` or `AirflowException` that doesn't match the identified errors we want to retry.



-- 
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: commits-unsubscribe@airflow.apache.org

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


[GitHub] [airflow] VladaZakharova commented on pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

Posted by "VladaZakharova (via GitHub)" <gi...@apache.org>.
VladaZakharova commented on PR #32365:
URL: https://github.com/apache/airflow/pull/32365#issuecomment-1642001444

   Hi @potiuk !
   Thank you for your ideas. I have rechecked the flow and changed the logic in the code:
   now, when catching specific types of exceptions, the code will retry specified action once again until the maximum number of retries will be reached.
   The decision about specific types of exceptions to be caught was made by investigating behavior of the connection in different cases:
   
   - if os_login=False, then the instance metadata is used for authentication. In this case, when multiple parallel connections are trying to retrieve/change the metadata in API calls, the 412 error is thrown (either Airflow exception with 412 error message or HttpError(412) )
   
   - if os_login=True, then the os_login is used for authentication. Multiple connections at the same time lead to SSHException trying to connect, the SSHException from paramiko library is thrown.
   
   I have also modified method `_connect_to_instance()` to follow current logic. It was running infinitive loop until the connection was actually established. Now this logic is changed to use only 5 retries at a time. Then, if the connection is still not established, the process of generating and importing ssh public key will be repeated. It will ensure that no process is not stuck with the same public key trying to authenticate and failing.


-- 
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: commits-unsubscribe@airflow.apache.org

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


[GitHub] [airflow] VladaZakharova commented on a diff in pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

Posted by "VladaZakharova (via GitHub)" <gi...@apache.org>.
VladaZakharova commented on code in PR #32365:
URL: https://github.com/apache/airflow/pull/32365#discussion_r1270574725


##########
airflow/providers/google/cloud/hooks/compute_ssh.py:
##########
@@ -225,40 +227,58 @@ def get_conn(self) -> paramiko.SSHClient:
             hostname = self.hostname
 
         privkey, pubkey = self._generate_ssh_key(self.user)
-        if self.use_oslogin:
-            user = self._authorize_os_login(pubkey)
-        else:
-            user = self.user
-            self._authorize_compute_engine_instance_metadata(pubkey)
-
-        proxy_command = None
-        if self.use_iap_tunnel:
-            proxy_command_args = [
-                "gcloud",
-                "compute",
-                "start-iap-tunnel",
-                str(self.instance_name),
-                "22",
-                "--listen-on-stdin",
-                f"--project={self.project_id}",
-                f"--zone={self.zone}",
-                "--verbosity=warning",
-            ]
-            proxy_command = " ".join(shlex.quote(arg) for arg in proxy_command_args)
-
-        sshclient = self._connect_to_instance(user, hostname, privkey, proxy_command)
+
+        max_retries = 10

Review Comment:
   Done!



-- 
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: commits-unsubscribe@airflow.apache.org

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


[GitHub] [airflow] potiuk merged pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk merged PR #32365:
URL: https://github.com/apache/airflow/pull/32365


-- 
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: commits-unsubscribe@airflow.apache.org

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


[GitHub] [airflow] ahidalgob commented on a diff in pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

Posted by "ahidalgob (via GitHub)" <gi...@apache.org>.
ahidalgob commented on code in PR #32365:
URL: https://github.com/apache/airflow/pull/32365#discussion_r1274887823


##########
tests/system/providers/google/cloud/compute/example_compute_ssh_os_login.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.
+
+"""
+Example Airflow DAG that starts, stops and sets the machine type of a Google Compute
+Engine instance.
+
+"""
+
+from __future__ import annotations
+
+import os
+from datetime import datetime
+
+from airflow import models
+from airflow.models.baseoperator import chain
+from airflow.providers.google.cloud.hooks.compute_ssh import ComputeEngineSSHHook
+from airflow.providers.google.cloud.operators.compute import (
+    ComputeEngineDeleteInstanceOperator,
+    ComputeEngineInsertInstanceOperator,
+)
+from airflow.providers.ssh.operators.ssh import SSHOperator
+from airflow.utils.trigger_rule import TriggerRule
+
+# [START howto_operator_gce_args_common]
+ENV_ID = os.environ.get("SYSTEM_TESTS_ENV_ID")
+PROJECT_ID = os.environ.get("SYSTEM_TESTS_GCP_PROJECT")
+
+DAG_ID = "cloud_compute_ssh_os_login"
+LOCATION = "europe-west1-b"
+REGION = "europe-west1"
+GCE_INSTANCE_NAME = "instance-ssh-test-oslogin"
+SHORT_MACHINE_TYPE_NAME = "n1-standard-1"
+GCE_INSTANCE_BODY = {
+    "name": GCE_INSTANCE_NAME,
+    "machine_type": f"zones/{LOCATION}/machineTypes/{SHORT_MACHINE_TYPE_NAME}",
+    "metadata": {
+        "items": [
+            {
+                "key": "enable-oslogin",
+                "value": "TRUE",
+            }
+        ]
+    },
+    "disks": [
+        {
+            "boot": True,
+            "device_name": GCE_INSTANCE_NAME,
+            "initialize_params": {
+                "disk_size_gb": "10",
+                "disk_type": f"zones/{LOCATION}/diskTypes/pd-balanced",
+                "source_image": "projects/debian-cloud/global/images/debian-11-bullseye-v20220621",
+            },
+        }
+    ],
+    "network_interfaces": [
+        {
+            "access_configs": [{"name": "External NAT", "network_tier": "PREMIUM"}],
+            "stack_type": "IPV4_ONLY",
+            "subnetwork": f"regions/{REGION}/subnetworks/default",
+        }
+    ],
+}
+# [END howto_operator_gce_args_common]
+
+with models.DAG(
+    DAG_ID,
+    schedule_interval="@once",
+    start_date=datetime(2021, 1, 1),
+    catchup=False,
+    tags=["example", "compute-ssh", "os-login"],
+) as dag:
+    # [START howto_operator_gce_insert]
+    gce_instance_insert = ComputeEngineInsertInstanceOperator(
+        task_id="gcp_compute_create_instance_task",
+        project_id=PROJECT_ID,
+        zone=LOCATION,
+        body=GCE_INSTANCE_BODY,
+    )
+    # [END howto_operator_gce_insert]
+
+    # [START howto_execute_command_on_remote_1]
+    os_login_task1 = SSHOperator(
+        task_id="os_login_task1",
+        ssh_hook=ComputeEngineSSHHook(
+            user="username",
+            instance_name=GCE_INSTANCE_NAME,
+            zone=LOCATION,
+            project_id=PROJECT_ID,
+            use_oslogin=True,
+            use_iap_tunnel=False,
+            cmd_timeout=1,
+        ),
+        command="echo os_login1",
+    )
+    # [END howto_execute_command_on_remote_1]
+
+    # [START howto_execute_command_on_remote_2]
+    os_login_task2 = SSHOperator(
+        task_id="os_login_task2",
+        ssh_hook=ComputeEngineSSHHook(
+            user="username",
+            instance_name=GCE_INSTANCE_NAME,
+            zone=LOCATION,
+            use_oslogin=True,
+            use_iap_tunnel=False,
+            cmd_timeout=1,
+        ),
+        command="echo os_login2",
+    )
+    # [END howto_execute_command_on_remote_2]
+
+    # [START howto_operator_gce_delete_no_project_id]
+    gce_instance_delete = ComputeEngineDeleteInstanceOperator(
+        task_id="gcp_compute_delete_instance_task",
+        zone=LOCATION,
+        resource_id=GCE_INSTANCE_NAME,
+    )
+    # [END howto_operator_gce_delete_no_project_id]
+    gce_instance_delete.trigger_rule = TriggerRule.ALL_DONE
+
+    chain(
+        gce_instance_insert,
+        os_login_task1,
+        os_login_task2,

Review Comment:
   Since these two don't depend on each other, we can run them in parallel, right?



-- 
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: commits-unsubscribe@airflow.apache.org

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


[GitHub] [airflow] potiuk commented on pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #32365:
URL: https://github.com/apache/airflow/pull/32365#issuecomment-1661841492

   Way better approach with optimisitic update strategy and retries when it fails ! 


-- 
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: commits-unsubscribe@airflow.apache.org

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


[GitHub] [airflow] VladaZakharova commented on a diff in pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

Posted by "VladaZakharova (via GitHub)" <gi...@apache.org>.
VladaZakharova commented on code in PR #32365:
URL: https://github.com/apache/airflow/pull/32365#discussion_r1270572979


##########
airflow/providers/google/cloud/hooks/compute_ssh.py:
##########
@@ -225,40 +227,58 @@ def get_conn(self) -> paramiko.SSHClient:
             hostname = self.hostname
 
         privkey, pubkey = self._generate_ssh_key(self.user)
-        if self.use_oslogin:
-            user = self._authorize_os_login(pubkey)
-        else:
-            user = self.user
-            self._authorize_compute_engine_instance_metadata(pubkey)
-
-        proxy_command = None
-        if self.use_iap_tunnel:
-            proxy_command_args = [
-                "gcloud",
-                "compute",
-                "start-iap-tunnel",
-                str(self.instance_name),
-                "22",
-                "--listen-on-stdin",
-                f"--project={self.project_id}",
-                f"--zone={self.zone}",
-                "--verbosity=warning",
-            ]
-            proxy_command = " ".join(shlex.quote(arg) for arg in proxy_command_args)
-
-        sshclient = self._connect_to_instance(user, hostname, privkey, proxy_command)
+
+        max_retries = 10
+        max_delay = 10
+        sshclient = None
+        for retry in range(max_retries + 1):
+            try:
+                if self.use_oslogin:
+                    user = self._authorize_os_login(pubkey)
+                else:
+                    user = self.user
+                    self._authorize_compute_engine_instance_metadata(pubkey)
+                proxy_command = None
+                if self.use_iap_tunnel:
+                    proxy_command_args = [
+                        "gcloud",
+                        "compute",
+                        "start-iap-tunnel",
+                        str(self.instance_name),
+                        "22",
+                        "--listen-on-stdin",
+                        f"--project={self.project_id}",
+                        f"--zone={self.zone}",
+                        "--verbosity=warning",
+                    ]
+                    proxy_command = " ".join(shlex.quote(arg) for arg in proxy_command_args)
+                sshclient = self._connect_to_instance(user, hostname, privkey, proxy_command)
+                break
+            except (HttpError, AirflowException, SSHException) as exc:
+                if (isinstance(exc, HttpError) and exc.resp.status == 412) or (
+                    isinstance(exc, AirflowException) and "412 PRECONDITION FAILED" in str(exc)
+                ):
+                    self.log.info("Error occurred when trying to update instance metadata: %s", exc)
+                elif isinstance(exc, SSHException):
+                    self.log.info("Error occurred when establishing SSH connection using Paramiko: %s", exc)
+                if retry == max_retries:
+                    raise AirflowException("Maximum retries exceeded. Aborting operation.")
+                delay = random.randint(0, max_delay)
+                self.log.info(f"Failed establish SSH connection, waiting {delay} seconds to retry...")
+                time.sleep(delay)
+        if not sshclient:
+            raise AirflowException("Unable to establish SSH connection.")

Review Comment:
   This check should be here for linter (i have static check errors without 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: commits-unsubscribe@airflow.apache.org

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


[GitHub] [airflow] VladaZakharova commented on pull request #32365: Fix ComputeEngineSSHHook to handle multiple parallel connections

Posted by "VladaZakharova (via GitHub)" <gi...@apache.org>.
VladaZakharova commented on PR #32365:
URL: https://github.com/apache/airflow/pull/32365#issuecomment-1651703743

   @eladkal 
   Could you check the changes when you have time? Thanks!


-- 
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: commits-unsubscribe@airflow.apache.org

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