Alarm.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. public static function reportAlarm($message)
  10. {
  11. // 业务环境白名单
  12. // $allowPlatform = \Yii::$app->params['allowPlatform'];
  13. // 是否开启预警信息推送
  14. $reportAlarmOpen = Cache::getSystemConfig()['reportAlarmOpen']['VALUE'];
  15. // 业务平台token
  16. $message['platform-id'] = \Yii::$app->params['alarmAccessToken'];
  17. // 级别
  18. $message['stance'] = $message['stance'] ?? 2;
  19. // 类型
  20. $message['brand'] = $message['brand'] ?? 'OTA';
  21. // 日志入库
  22. // Tool::alarmCall($message);
  23. // 日志写文件
  24. LoggerTool::error($message);
  25. // 业务环境过滤
  26. if ($reportAlarmOpen /**&& (count($allowPlatform) == 0 || in_array($_SERVER['HTTP_HOST'], $allowPlatform))*/) {
  27. $result = self::curl(json_encode($message));
  28. if ($result['code'] != 200) {
  29. // 重新推送一次,如果失败,写错误日志
  30. $result = self::curl(json_encode($message));
  31. if ($result['code'] != 200) {
  32. LoggerTool::error(['预警信息上报平台失败. traceId【' . $message['trace-id'] . '】', $result]);
  33. }
  34. }
  35. } else {
  36. $reason = '';
  37. if ($reportAlarmOpen == '0') {
  38. $reason = '上报预警平台状态不允许(reportAlarmOpen=关闭)';
  39. }
  40. // if (!count($allowPlatform)) {
  41. // $reason = '主机地址不在白名单中(host=' . $_SERVER['HTTP_HOST'] . ')';
  42. // }
  43. LoggerTool::error('预警信息上报平台取消. traceId【' . $message['trace-id'] . '】. 原因:' . $reason);
  44. }
  45. }
  46. private static function curl($post_string)
  47. {
  48. $ch = curl_init();
  49. curl_setopt($ch, CURLOPT_URL, self::$url . self::$reportApi);
  50. curl_setopt($ch, CURLOPT_POST, 1);
  51. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  52. curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
  53. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
  54. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  55. // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
  56. curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
  57. curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
  58. $response = curl_exec($ch);
  59. curl_close($ch);
  60. if (curl_errno($ch)) {
  61. // 请求失败,返回错误信息
  62. return ['code' => 500, 'message' => curl_error($ch)];
  63. }
  64. return ['code' => 200, 'message' => json_decode($response, true)];
  65. }
  66. }