mik-laj commented on a change in pull request #9879: URL: https://github.com/apache/airflow/pull/9879#discussion_r458455540
########## File path: airflow/providers/google/cloud/hooks/compute_ssh.py ########## @@ -0,0 +1,250 @@ +# 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 paramiko +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 Oslogin 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 + """ + + 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 + self.conn = None + + def get_conn(self) -> Any: + """ + Connects to Oslogin API + """ + if self.conn is None: + http_authorized = self._authorize() + self.conn = build("oslogin", self.api_version, + http=http_authorized, cache_discovery=False) + return self.conn + + def get_sshclient(self, + private_key_file: str, + hostname: str, + username: str, + strict_host_checking: bool = True + ) -> paramiko.SSHClient: + """ + Get SSHClient + + :param private_key_file: The filename of the private key + :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 + :param strict_host_checking: Whether to verify key + :type strict_host_checking: bool + """ + + self.log.info("Creating remote connection to host") + client = paramiko.SSHClient() + if not strict_host_checking: + self.log.warning('No Host Key Verification. This wont protect ' + 'against Man-In-The-Middle attacks') + # Default is RejectPolicy + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + + client.connect(hostname=hostname, + username=username, + key_filename=private_key_file) + return client + + def get_service_account(self) -> str: + """ + Get the service account id + """ + account: str = self._get_credentials().service_account_email + if not account.startswith('users/'): + account = 'users/' + account + return account + + def get_username(self) -> str: + """ + Using the OS Login API, get the POSIX username from the login profile + for the service account. + + """ + conn = self.get_conn() + account = self.get_service_account() + profile = conn.users().getLoginProfile(name=account).execute_in_compute() # pylint: disable=no-member + username: str = profile.get('posixAccounts')[0].get('username') + return username + + @GoogleBaseHook.fallback_to_default_project_id + def get_hostname(self, project_id: Optional[str], instance: str, zone: str, + hostname: Optional[str] = None) -> str: + """ + Create the target instance hostname + + :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 not provided, + it is generated from zone, instance name and project id + :type hostname: str + """ + if not hostname: + hostname = f'{instance}.{zone}.c.{project_id}.internal' + 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, + account: str, + expire_time: int = 300) -> str: + """ + Generate a temporary SSH key and apply it to the specified account + + :param account: The service account id + :type account: str + :param expire_time: The maximum amount of time before the private key is expired + :type expire_time: int + """ + try: + self.log.info("Generating ssh keys...") + private_key_file = '/tmp/key-' + str(uuid.uuid4()) Review comment: You can also read key from .key attribute and serialize it to string. https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/#key-serialization ---------------------------------------------------------------- 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]
