ephraimbuddy commented on a change in pull request #9879: URL: https://github.com/apache/airflow/pull/9879#discussion_r459367980
########## 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") + else: + raise AirflowException("The target instance does not have external IP," + "consider specifying use_internal_ip or use_iap_tunnel") + + return hostname + + def execute_local(self, cmd: Union[str, List[str]]) -> None: + """ + Executes command in local machine + + :param cmd: The command to execute + :type cmd: Union[str, List[str]] + """ + self.log.info('Executing command: %s', str(cmd)) + process = subprocess.Popen(cmd) + output = process.communicate()[0] + return_code = process.returncode + if return_code: + # Error + raise AirflowException(f'The Command {cmd} returned error status {return_code}') + if output: + self.log.info(output) + + def _create_ssh_key(self, + instance: str, + zone: str, + project_id: Optional[str], + expire_time: int = 300, + use_oslogin: bool = True) -> str: + """ + Generate a temporary SSH key and apply it to the specified account + + :param expire_time: The maximum amount of time before the private key is expired + :type expire_time: int + :param use_oslogin: Whether to use OsLogin to manage key + """ + username = self.get_username(oslogin=use_oslogin) + try: + self.log.info("Generating ssh keys...") + # private_key_file = StringIO() + # private_key_obj = paramiko.RSAKey.generate(2048) + # private_key_obj.write_private_key(private_key_file) + + # public_key = f"{private_key_obj.get_name()} {private_key_obj.get_base64()}" \ + # f" {username}" + private_key_file = '/tmp/key-' + str(uuid.uuid4()) + self.execute_local(['ssh-keygen', '-t', 'rsa', '-N', '', '-f', private_key_file]) + + with open(private_key_file + '.pub', 'r') as original: + public_key = original.read().strip() + + except (IOError, SSHException) as err: + raise AirflowException(f"Error encountered creating ssh keys, {err}") + + if use_oslogin: + # Expiration time is in microseconds. + expiration = int((time.time() + expire_time) * 1000000) + + body = { + "key": public_key, + "expiration_time_usec": expiration + } + os_login_client = self.get_oslogin_conn() + os_login_client.import_ssh_public_key( + parent=self.get_service_account(), + ssh_public_key=body + ) + else: + # using instance metadata to manage keys + + instance_info = self.get_conn().instances().get( + project=project_id, + instance=instance, + zone=zone).execute() + + new_keys = [username + ":" + public_key + "\n"] + metadata = instance_info['metadata'] + items = metadata.get("items") + if items: + key_vals = items[0].get("value") + for val in key_vals: + new_keys.append(val + "\n") + new_dict = {"key": "ssh-keys", "value": str(new_keys)} + metadata.update(new_dict) + self.get_conn().instances().setMetadata( + project=project_id, + zone=zone, + instance=instance, + body=metadata + ).execute() Review comment: This is not being set ---------------------------------------------------------------- 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]
