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



##########
File path: airflow/providers/google/cloud/hooks/compute_engine_ssh.py
##########
@@ -0,0 +1,211 @@
+# 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 subprocess
+import time
+import uuid
+from typing import Any, List, Optional, Union
+
+import requests
+from googleapiclient.discovery import build
+
+from airflow.providers.google.common.hooks.base_google import GoogleBaseHook
+
+SERVICE_ACCOUNT_METADATA_URL = (
+    'http://metadata.google.internal/computeMetadata/v1/instance/'
+    'service-accounts/default/email')
+HEADERS = {'Metadata-Flavor': 'Google'}
+
+
+class ComputeEngineSSHHook(GoogleBaseHook):
+    """
+    Hook to connect to a remote instance in compute engine
+
+    :param api_version:
+    :param gcp_conn_id:
+    :param delegate_to:
+    :param oslogin:
+    :param account:
+    """
+
+    def __init__(self,
+                 api_version: str = "v1",
+                 gcp_conn_id: str = "google_cloud_default",
+                 delegate_to: Optional[str] = None,
+                 oslogin=None,
+                 account=None
+                 ) -> None:
+        super().__init__(gcp_conn_id, delegate_to)
+        self.api_version = api_version
+        self.oslogin = oslogin
+        self.account = account
+
+    def get_oslogin(self) -> Any:
+        """
+        Connects to Oslogin API
+        """
+        if self.oslogin is None:
+            http_authorized = self._authorize()
+            self.oslogin = build("oslogin", self.api_version,
+                                 http=http_authorized, cache_discovery=False)
+        return self.oslogin
+
+    def get_service_account(self) -> str:
+        """
+        Get the service account id
+        :return:
+        """
+        if self.account is None:
+            self.account = requests.get(
+                SERVICE_ACCOUNT_METADATA_URL, headers=HEADERS).text
+        if not self.account.startswith('users/'):
+            self.account = 'users/' + self.account
+        return self.account
+
+    def get_username(self):
+        """
+        Using the OS Login API, get the POSIX username from the login profile
+        for the service account.
+
+        """
+        oslogin = self.get_oslogin()
+        account = self.get_service_account()
+        profile = oslogin.users().getLoginProfile(  # pylint: disable=no-member
+            name=account).execute_in_compute()
+        username = profile.get('posixAccounts')[0].get('username')
+        return username
+
+    @GoogleBaseHook.fallback_to_default_project_id
+    def get_hostname(self, project_id, instance, zone, hostname=None):
+        """
+        Create the target instance hostname
+        :param project_id:
+        :param instance:
+        :param zone:
+        :param hostname:
+        :return:
+        """
+        hostname = hostname or f'{instance}.{zone}.c.{project_id}.internal'
+        return hostname
+
+    def execute_in_compute(self, cmd: Union[str, List[str]]) -> None:
+        """
+        Executes command in Compute Engine instance
+        :param cmd: The command to execute_in_compute
+        :type cmd: union[str, List[str]]
+        """
+        self.log.info('Executing command: %s', str(cmd))
+        process = subprocess.Popen(cmd)
+        output = process.communicate()[0]
+        returncode = process.returncode
+        if returncode:
+            # Error
+            self.log.error('Command returned error status %s', returncode)
+        if output:
+            self.log.info(output)
+
+    def create_ssh_key(self,
+                       oslogin: Any,
+                       account: str,
+                       private_key_file: Optional[str] = None,
+                       expire_time: int = 300) -> str:
+        """
+        Generate a temporary SSH key and apply it to the specified account
+
+        :param oslogin:
+        :param account:
+        :param private_key_file:
+        :param expire_time:
+        """
+        private_key_file = private_key_file or '/tmp/key-' + str(uuid.uuid4())
+        self.execute_in_compute(['ssh-keygen', '-t', 'rsa', '-N', '', '-f', 
private_key_file])
+
+        with open(private_key_file + '.pub', 'r') as original:
+            public_key = original.read().strip()
+
+        # Expiration time is in microseconds.
+        expiration = int((time.time() + expire_time) * 1000000)
+
+        body = {
+            'key': public_key,
+            'expirationTimeUsec': expiration,
+        }
+        oslogin.users().importSshPublicKey(parent=account, 
body=body).execute_in_compute()
+        return private_key_file
+
+    @GoogleBaseHook.fallback_to_default_project_id
+    def run(self,
+            cmd: str, project_id: str, instance: str, zone: str,
+            private_key_file: Optional[str] = None, expire_time: int = 300,
+            hostname: Optional[str] = None, tunnel: bool = False,
+            clean_up_private_key: bool = True):
+        """
+        Run a command on a remote system.
+
+        :param cmd:
+        :param project_id:
+        :param instance:
+        :param zone:
+        :param private_key_file:
+        :param expire_time:
+        :param hostname:
+        :param tunnel:
+        :param clean_up_private_key:
+        :return:
+        """
+
+        hostname = self.get_hostname(project_id=project_id,
+                                     instance=instance,
+                                     zone=zone,
+                                     hostname=zone)
+
+        account = self.get_service_account()
+        oslogin = self.get_oslogin()
+
+        private_key_file = self.create_ssh_key(oslogin=oslogin,
+                                               account=account,
+                                               
private_key_file=private_key_file,
+                                               expire_time=expire_time)
+
+        username = self.get_username()
+
+        if tunnel and "--tunnel-through-iap" not in cmd:
+            cmd = cmd + " " + "--tunnel-through-iap"
+
+        ssh_command = [

Review comment:
       We should try to do it with paramiko. We can then use more advanced 
features. Although I know it will be a bit more difficult then.




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