This repository has been archived on 2025-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
nezha-nz-talon/src/main/java/net/geedge/confagent/controller/HealthyController.java

107 lines
3.1 KiB
Java

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<String,Object> 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<String,Object> result){
Map<String,Object> promtailConf = Tool.YamlUtil.readAsMap(promtailConfPath);
if(promtailConf==null) {
result.put("promtail","DOWN");
return ;
}
Map<String,Integer> promtailPortMap = (Map<String,Integer>)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;
}
}
}
}