1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
| from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults import requests import json
class SlackNotificationOperator(BaseOperator): """自定义Slack通知操作符""" @apply_defaults def __init__(self, slack_webhook_url, message, channel='#general', username='Airflow', *args, **kwargs): super().__init__(*args, **kwargs) self.slack_webhook_url = slack_webhook_url self.message = message self.channel = channel self.username = username def execute(self, context): slack_message = { 'channel': self.channel, 'username': self.username, 'text': self.message, 'attachments': [ { 'color': 'good' if context.get('task_instance').state == 'success' else 'danger', 'fields': [ { 'title': 'DAG', 'value': context['dag'].dag_id, 'short': True }, { 'title': 'Task', 'value': context['task'].task_id, 'short': True }, { 'title': 'Execution Date', 'value': str(context['execution_date']), 'short': True } ] } ] } response = requests.post( self.slack_webhook_url, data=json.dumps(slack_message), headers={'Content-Type': 'application/json'} ) if response.status_code != 200: raise Exception(f"Slack通知失败: {response.text}") self.log.info("Slack通知发送成功")
class DatabaseBackupOperator(BaseOperator): """数据库备份操作符""" @apply_defaults def __init__(self, connection_id, backup_path, tables=None, *args, **kwargs): super().__init__(*args, **kwargs) self.connection_id = connection_id self.backup_path = backup_path self.tables = tables or [] def execute(self, context): from airflow.hooks.postgres_hook import PostgresHook import subprocess import os hook = PostgresHook(postgres_conn_id=self.connection_id) connection = hook.get_connection(self.connection_id) backup_file = f"{self.backup_path}/backup_{context['ds']}.sql" cmd = [ 'pg_dump', '-h', connection.host, '-p', str(connection.port), '-U', connection.login, '-d', connection.schema, '-f', backup_file, '--verbose' ] if self.tables: for table in self.tables: cmd.extend(['-t', table]) env = os.environ.copy() env['PGPASSWORD'] = connection.password result = subprocess.run(cmd, env=env, capture_output=True, text=True) if result.returncode != 0: raise Exception(f"数据库备份失败: {result.stderr}") self.log.info(f"数据库备份成功: {backup_file}") return backup_file
backup_task = DatabaseBackupOperator( task_id='backup_database', connection_id='postgres_default', backup_path='/backups', tables=['users', 'orders', 'products'], dag=dag )
notify_task = SlackNotificationOperator( task_id='notify_completion', slack_webhook_url='https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK', message='数据处理流水线执行完成!', channel='#data-team', dag=dag )
|