mik-laj commented on a change in pull request #9879:
URL: https://github.com/apache/airflow/pull/9879#discussion_r459459626



##########
File path: airflow/providers/google/cloud/hooks/compute_ssh.py
##########
@@ -0,0 +1,327 @@
+# 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 pprint
+import subprocess
+import time
+import uuid
+from io import StringIO
+from typing import Any, List, Optional, Tuple, Union
+
+import paramiko
+from google.cloud.oslogin_v1 import OsLoginServiceClient
+from googleapiclient.discovery import build
+from paramiko import SSHException
+
+from airflow import AirflowException
+from airflow.providers.google.common.hooks.base_google import GoogleBaseHook
+
+
+class ComputeEngineSshHook(GoogleBaseHook):
+    """
+    Hook to connect to a remote instance in compute engine
+
+    :param api_version: The Compute Engine discovery API version
+    :type api_version: str
+    :param gcp_conn_id: The connection id to use when fetching connection info
+    :type gcp_conn_id: str
+    :param delegate_to: The account to impersonate, if any.
+        For this to work, the service account making the request must have
+        domain-wide delegation enabled.
+    :type delegate_to: str
+    """
+    _oslogin_conn: Optional[OsLoginServiceClient] = None
+    _sshclient: Optional[paramiko.SSHClient] = None
+    _conn: Optional[Any] = None
+
+    def __init__(
+        self,
+        api_version: str = 'v1',
+        gcp_conn_id: str = 'google_cloud_default',
+        delegate_to: Optional[str] = None
+    ) -> None:
+        super().__init__(gcp_conn_id, delegate_to)
+        self.api_version = api_version
+
+    def get_conn(self) -> Any:
+        """
+        Retrieves connection to Google Compute Engine.
+
+        :return: Google Compute Engine services object
+        :rtype: dict
+        """
+        if not self._conn:
+            http_authorized = self._authorize()
+            self._conn = build('compute', self.api_version,
+                               http=http_authorized, cache_discovery=False)
+        return self._conn
+
+    def get_oslogin_conn(self) -> OsLoginServiceClient:
+        """
+        Connects to Oslogin API
+        """
+        if not self._oslogin_conn:
+            self._oslogin_conn = OsLoginServiceClient(
+                credentials=self._get_credentials(), 
client_info=self.client_info
+            )
+
+        return self._oslogin_conn
+
+    def get_sshclient(self,
+                      private_key_file: str,
+                      hostname: str,
+                      username: str
+                      ) -> paramiko.SSHClient:
+        """
+        Get SSHClient
+
+        :param private_key_file: The private key filename
+        :type private_key_file: str
+        :param hostname: The hostname of the target instance
+        :type hostname: str
+        :param username: The POXIS username from the login profile of the user 
account
+        :type username: str
+        """
+
+        if not self._sshclient:
+            self._sshclient = paramiko.SSHClient()
+            # Default is RejectPolicy
+            # No knownhost checking since we are not storing pkey
+            
self._sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
+
+            self._sshclient.connect(hostname=hostname,
+                                    username=username,
+                                    key_filename=private_key_file,
+                                    look_for_keys=False)
+        return self._sshclient
+
+    def get_service_account(self) -> str:
+        """
+        Get the service account id
+        """
+        account: str = self._get_credentials().service_account_email
+        os_login_client = self.get_oslogin_conn()
+        return os_login_client.user_path(user=account)
+
+    def get_username(self, oslogin=True) -> str:
+        """
+        Get the account username
+        """
+        account = self._get_credentials().service_account_email
+        if oslogin:
+            profile = 
self.get_oslogin_conn().get_login_profile(name=self.get_service_account())
+            account = profile.posix_accounts[0]
+            return account.username
+        return account.split("@")[0]
+
+    @GoogleBaseHook.fallback_to_default_project_id
+    def get_connection_type(self, project_id: Optional[str], instance: str, 
zone: str,
+                            hostname: Optional[str] = None,
+                            use_iap_tunnel: bool = False,
+                            use_internal_ip: bool = False
+                            ) -> str:
+        """
+        Selects how to connect to the target instance
+
+        :param project_id: The project ID of the instance
+        :type project_id: Optional[str]
+        :param instance: The name of the target instance to connect to
+        :type instance: str
+        :param zone: The zone of the target instance
+        :param zone: str
+        :param hostname: The hostname of the target instance. If provided, 
this would
+            be used, regardless of the setting for use_iap_tunnel and 
use_internal_ip
+        :type hostname: str
+        :param use_iap_tunnel: Whether to connect through IAP tunnel
+        :type use_iap_tunnel: bool
+        :param use_internal_ip: Whether to connect using internal IP
+        :type use_internal_ip: bool
+        """
+        if not hostname:
+            instance_info = self.get_conn() \
+                .instances().get(project=project_id,
+                                 zone=zone,
+                                 instance=instance).execute()
+            if use_iap_tunnel or use_internal_ip:
+                return instance_info["networkInterfaces"][0] \
+                    .get("networkIP")
+            else:
+                external_ip = instance_info \
+                    .get("networkInterfaces")[0] \
+                    .get("accessConfigs")
+                if external_ip:
+                    return external_ip[0].get("natIP")

Review comment:
       When natIP is empty, we should look at the access configuration.




----------------------------------------------------------------
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.

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to