-
-
Save peter279k/fee05442bfc164817fa3f62bef6515b2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import re | |
| import json | |
| import platform | |
| import subprocess | |
| from datetime import datetime, timezone | |
| from nifiapi.flowfiletransform import FlowFileTransform, FlowFileTransformResult | |
| from nifiapi.properties import PropertyDescriptor, StandardValidators, ExpressionLanguageScope | |
| class PingHost(FlowFileTransform): | |
| class Java: | |
| implements = ['org.apache.nifi.python.processor.FlowFileTransform'] | |
| class ProcessorDetails: | |
| version = '0.0.5-SNAPSHOT' | |
| description = '讀取 FlowFile 屬性中的 IP 與 ping 次數,執行 ping 後將結果以 JSON 輸出。' | |
| tags = ['ping', 'network', 'icmp', 'monitoring', 'python'] | |
| dependencies = [] | |
| def __init__(self, **kwargs): | |
| super().__init__() # ← 必須呼叫,先前拿掉是錯的 | |
| self.target = PropertyDescriptor( | |
| name='Target IP Address', | |
| description='要 ping 的 IP;預設讀取 FlowFile 的 target.ip 屬性。', | |
| required=True, | |
| default_value='${target.ip}', | |
| validators=[StandardValidators.NON_EMPTY_VALIDATOR], | |
| expression_language_scope=ExpressionLanguageScope.FLOWFILE_ATTRIBUTES | |
| ) | |
| self.count = PropertyDescriptor( | |
| name='Ping Count', | |
| description='ICMP 封包數量;預設讀取 FlowFile 的 ping.count 屬性。', | |
| required=True, | |
| default_value='${ping.count}', | |
| validators=[StandardValidators.NON_EMPTY_VALIDATOR], | |
| expression_language_scope=ExpressionLanguageScope.FLOWFILE_ATTRIBUTES | |
| ) | |
| self.timeout = PropertyDescriptor( | |
| name='Timeout (seconds)', | |
| description='每個封包等待逾時秒數。', | |
| required=True, | |
| default_value='2', | |
| validators=[StandardValidators.POSITIVE_INTEGER_VALIDATOR] | |
| ) | |
| self.descriptors = [self.target, self.count, self.timeout] | |
| def getPropertyDescriptors(self): | |
| return self.descriptors | |
| def transform(self, context, flowfile): | |
| target = context.getProperty('Target IP Address').evaluateAttributeExpressions(flowfile).getValue() | |
| if not target or not target.strip(): | |
| self.logger.warn('未取得目標 IP,路由至 failure') | |
| return FlowFileTransformResult(relationship='failure', | |
| attributes={'ping.error': 'missing target ip'}) | |
| count_str = context.getProperty('Ping Count').evaluateAttributeExpressions(flowfile).getValue() | |
| count = int(count_str) if count_str and count_str.strip().isdigit() else 4 | |
| timeout = context.getProperty('Timeout (seconds)').asInteger() | |
| cmd = self._build_command(target, count, timeout) | |
| try: | |
| proc = subprocess.run(cmd, capture_output=True, text=True, | |
| timeout=(timeout * count) + 5) | |
| raw = proc.stdout | |
| reachable = proc.returncode == 0 | |
| except subprocess.TimeoutExpired: | |
| raw, reachable = 'ping command timed out', False | |
| except Exception as e: | |
| self.logger.error(f'執行 ping 失敗: {e}') | |
| raw, reachable = str(e), False | |
| stats = self._parse_output(raw) | |
| record = { | |
| 'target': target, | |
| 'reachable': reachable, | |
| 'packet_loss_percent': self._to_float(stats.get('loss')), | |
| 'rtt_min_ms': self._to_float(stats.get('min')), | |
| 'rtt_avg_ms': self._to_float(stats.get('avg')), | |
| 'rtt_max_ms': self._to_float(stats.get('max')), | |
| 'ping_count': count, | |
| 'checked_at': datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S'), | |
| } | |
| relationship = 'success' if reachable else 'failure' | |
| self.logger.info(f'Ping {target} -> {relationship} (loss={stats.get("loss")})') | |
| return FlowFileTransformResult( | |
| relationship=relationship, | |
| contents=json.dumps(record), | |
| attributes={'mime.type': 'application/json', | |
| 'ping.reachable': str(reachable).lower()} | |
| ) | |
| def _build_command(self, target, count, timeout): | |
| if platform.system().lower() == 'windows': | |
| return ['ping', '-n', str(count), '-w', str(timeout * 1000), target] | |
| return ['ping', '-c', str(count), '-W', str(timeout), target] | |
| def _parse_output(self, output): | |
| stats = {} | |
| loss = re.search(r'(\d+(?:\.\d+)?)%\s*packet loss', output) | |
| if loss: | |
| stats['loss'] = loss.group(1) | |
| rtt = re.search(r'=\s*([\d.]+)/([\d.]+)/([\d.]+)', output) | |
| if rtt: | |
| stats['min'], stats['avg'], stats['max'] = rtt.group(1), rtt.group(2), rtt.group(3) | |
| return stats | |
| def _to_float(self, val): | |
| try: | |
| return float(val) if val is not None else None | |
| except (ValueError, TypeError): | |
| return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment