Alarm.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace common\helpers;
  3. class Alarm
  4. {
  5. // 预警平台Domain
  6. private static $url = 'http://ibs-cn.elken.com:8017';
  7. // 推送预警信息API
  8. private static $reportApi = '/api/report';
  9. // 业务环境白名单
  10. private static $allowPlatform = ['ng-frontend-api.elken.com', 'ng-backend-api.elken.com'];
  11. public static function reportAlarm($message)
  12. {
  13. // 是否开启预警信息推送
  14. $reportAlarmOpen = Cache::getSystemConfig()['reportAlarmOpen']['VALUE'];
  15. // 业务平台token
  16. $message['platform-id'] = \Yii::$app->params['alarmAccessToken'];
  17. // 日志入库
  18. Tool::alarmCall($message);
  19. LoggerTool::error($message);
  20. // 业务环境过滤
  21. if ($reportAlarmOpen && (count(self::$allowPlatform) == 0 || in_array($_SERVER['HTTP_HOST'], self::$allowPlatform))) {
  22. $result = self::curl(json_encode($message));
  23. if ($result['code'] != 200) {
  24. // 重新推送一次,如果失败,写错误日志
  25. $result = self::curl(json_encode($message));
  26. if ($result['code'] != 200) {
  27. LoggerTool::error('预警信息上报平台失败. traceId【' . $message['trace-id'] . '】');
  28. }
  29. }
  30. } else {
  31. if ($reportAlarmOpen == '0') {
  32. $reason = '上报预警平台状态不允许(reportAlarmOpen=关闭)';
  33. } else {
  34. $reason = '主机地址不在白名单中(host=' . $_SERVER['HTTP_HOST'] . ')';
  35. }
  36. LoggerTool::error('预警信息上报平台取消. traceId【' . $message['trace-id'] . '】. 原因:' . $reason);
  37. }
  38. }
  39. private static function curl($post_string)
  40. {
  41. $ch = curl_init();
  42. curl_setopt($ch, CURLOPT_URL, self::$url . self::$reportApi);
  43. curl_setopt($ch, CURLOPT_POST, 1);
  44. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  45. curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
  46. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
  47. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  48. // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
  49. curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
  50. curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
  51. $response = curl_exec($ch);
  52. curl_close($ch);
  53. return json_decode($response, true);
  54. }
  55. }