Alarm.php 3.0 KB

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