package net.geedge.confagent.controller; import cn.hutool.core.net.url.UrlBuilder; import cn.hutool.http.HttpConnection; import cn.hutool.log.Log; import net.geedge.confagent.annotation.UnCheckToken; import net.geedge.confagent.util.ConfagentUtil; import net.geedge.confagent.util.R; import net.geedge.confagent.util.RCode; import net.geedge.confagent.util.Tool; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Date; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("healthy") public class HealthyController extends BaseController{ @Autowired private ConfagentUtil confagentUtil; private final static Log log = Log.get(); private UrlBuilder promtailHealthy; @GetMapping @UnCheckToken public R checkHealthy(@RequestHeader(value="Authorization",required = false) String token) { Map result = new HashMap<>(); buildHealthyURL(result); if(Tool.StrUtil.isNotBlank(token)){ if(confagentUtil.checkToken(token).getCode() == RCode.SUCCESS.getCode()){ result.put("auth","TRUE"); }else{ result.put("auth","FALSE"); } } String version = confagentUtil.readVersion(); result.put("version", version); result.put("ts", new Date().getTime()); return R.ok(result); } public void buildHealthyURL(Map result){ Map promtailConf = Tool.YamlUtil.readAsMap(promtailConfPath); if(promtailConf==null) { result.put("promtail","DOWN"); return ; } Map promtailPortMap = (Map)promtailConf.get(PROMTAIL_LISTEN_SERVER); if(promtailPortMap==null) { result.put("promtail","DOWN"); return ; } Integer promtailPort = promtailPortMap.get(PROMTAIL_LISTEN_PORT); if(promtailPort==null) { promtailPort = DEFAULT_PROMTAIL_PORT; } promtailHealthy = new UrlBuilder(); promtailHealthy.setScheme("http").setHost(defaultPromtailIP).setPort(promtailPort).addPath("/ready"); result.put("promtail",checkState(promtailHealthy.toString())); } private String checkState(String url){ HttpURLConnection conn = null; try{ conn = HttpConnection.create(url,null).getHttpURLConnection(); log.debug("connect to {}",url); conn.connect(); int responseCode = conn.getResponseCode(); if(200 == responseCode){ return "UP"; } return "DOWN"; }catch (IOException e){ log.error("failed connect ",e); return "DOWN"; }finally { if (conn != null) { conn.disconnect(); conn = null; } } } }