nz-talon首次提交

This commit is contained in:
hyx
2021-07-09 17:01:27 +08:00
parent 2db96629a7
commit e725329063
31 changed files with 3714 additions and 0 deletions

View File

@@ -0,0 +1,101 @@
package net.geedge.confagent.controller;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.hutool.log.Log;
import net.geedge.confagent.annotation.UnCheckToken;
import net.geedge.confagent.entity.AuthEntity;
import net.geedge.confagent.util.R;
import net.geedge.confagent.util.RCode;
import net.geedge.confagent.util.Tool;
@RestController
@RequestMapping(value={"/auth"})
public class AuthController extends BaseController{
private final static Log log = Log.get();
@Value("${confagent.authFile:auth.yml}")
private String authFile;
private static String rootPath = Tool.WebPathUtil.getRootPath();
/**
* @Description 每次请求auth接口重新生成 token并记录到文件
* @Author rui
* @Date 2021/3/23
*/
@RequestMapping
@UnCheckToken
public R auth(AuthEntity auth){
if(Tool.StrUtil.isBlank(auth.getName())||Tool.StrUtil.isBlank(auth.getPin())){
return R.error(RCode.AUTH_NAME_PIN_ISNULL);
}
File af = Tool.FileUtil.file(rootPath, authFile);
log.debug("auth file path : {}" ,af.getAbsolutePath());
Properties properties = Tool.YamlUtil.yamlToProperties(af.getAbsolutePath());
String name = properties.getProperty("auth.name","nezha");
String pin = properties.getProperty("auth.pin","nezha");
if(Tool.StrUtil.equals(name,auth.getName())&& Tool.StrUtil.equals(pin,auth.getPin())){
String token = Tool.IdUtil.fastShortUUID();
log.debug("write token {} to {}",token,af.getAbsolutePath());
writeToken(token);
Map<String,String> map = new HashMap<>();
map.put("token", token);
return R.ok(map);
}
return R.error(RCode.AUTH_NAME_PIN_INVALID);
}
/**
* @Description 验证当前token是否和文件记录一致一致后重新生成则更新文件并返回最新token
* @Author rui
* @Date 2021/3/24
*/
@GetMapping("/refresh")
public R refresh(){
String t = Tool.IdUtil.fastShortUUID();
writeToken(t);
Map<String,String> map = new HashMap<>();
map.put("token", t);
return R.ok(map);
}
/**
* @Description 注销当前 token
* @Author rui
* @Date 2021/3/24
*/
@GetMapping("logout")
public R logout(){
File tf = Tool.FileUtil.file(rootPath, tokenFile);
log.debug("token file path : {}" ,tf.getAbsolutePath());
if(Tool.FileUtil.exist(tf)){
Tool.FileUtil.del(tf);
}
if(Tool.FileUtil.exist(promtailConfPath)){
Tool.YamlUtil.writeAsMap(null,promtailConfPath);
}
return R.ok();
}
private void writeToken(String token){
File tf = Tool.FileUtil.file(rootPath, tokenFile);
log.debug("token file path : {}" ,tf.getAbsolutePath());
Tool.FileUtil.writeUtf8String(token, tf);
}
}

View File

@@ -0,0 +1,45 @@
package net.geedge.confagent.controller;
import cn.hutool.log.Log;
import org.springframework.beans.factory.annotation.Value;
public abstract class BaseController {
private Log log = Log.get();
protected static final String PROMTAIL_LISTEN_SERVER = "server";
protected static final String PROMTAIL_LISTEN_PORT = "http_listen_port";
@Value("${confagent.tokenFile:config/token.auth}")
protected String tokenFile; //token文件位置
@Value("${confagent.promtail.cmdLine}")
protected String promtailCmdLinePath; // promtail config.conf 启动参数文件存放位置
@Value("${confagent.promtail.defaultIP:127.0.0.1}")
protected String defaultPromtailIP; //promtail 默认监听ip
protected static final int DEFAULT_PROMTAIL_PORT=9080; //prometheus 默认监听端口
@Value("${confagent.promtail.config}")
protected String promtailConfPath;
/**
* 调用 /-/reload 接口,热加载 server 配置文件,
*
* @param cmdLinePath
* @param serverListenAddr
* @param defaultServerPort
* @param defaultServerIP
* @return
*/
// public boolean reloadServerConfiguration(String cmdLinePath, String serverListenAddr, int defaultServerPort, String defaultServerIP) {
// UrlBuilder serverReloadUrl = new UrlBuilder();
// int serverPort = ConfagentUtil.getConfFilePort(cmdLinePath, serverListenAddr, defaultServerPort);
// serverReloadUrl.setScheme("http").setHost(defaultServerIP).setPort(serverPort).addPath("/-/reload");
//
// String url = serverReloadUrl.toString();
// HttpRequest post = Tool.HttpUtil.createPost(url);
// HttpResponse response = post.execute();
// return 200 == response.getStatus();
// }
}

View File

@@ -0,0 +1,102 @@
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.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,String> 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");
}
}
return R.ok(result);
}
public void buildHealthyURL(Map<String,String> 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;
}
}
}
}

View File

@@ -0,0 +1,138 @@
package net.geedge.confagent.controller;
import cn.hutool.log.Log;
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.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.io.File;
import java.util.*;
@RestController
@RequestMapping("/promtail")
public class PromtailController extends BaseController{
private final static Log log = Log.get();
@Autowired
private ConfagentUtil confagentUtil;
@Value("${confagent.promtail.query.auth:true}")
private Boolean queryAuth;
private final String[] QUERY_API_SUFFIX = {"query","query_range","series","labels","values"};
@Value("${confagent.promtail.restart:systemctl restart promtail}")
private String restartCmd;
@Value("${confagent.versionFile:promtail.version}")
private String versionFile;
private static String rootPath = Tool.WebPathUtil.getRootPath();
/**
* @Description 获取promtail相关配置
* @Author rui
* @Date 2021/3/24
*/
@GetMapping("/config")
public R queryConfig(){
Map<String,String> cmdLine = ConfagentUtil.loadServiceConfigFile(promtailCmdLinePath);
Map<String,Object> promtailConf = Tool.YamlUtil.readAsMap(promtailConfPath);
String version = confagentUtil.readVersion();
Map<String,Object> result = new LinkedHashMap<>();
result.put("version",version);
result.put("cmdline",cmdLine);
result.put("config",promtailConf);
return R.ok(result);
}
/**
* @Description 写入promtail配置文件
* @Author rui
* @Date 2021/3/25
*/
@PostMapping("/config")
public R overwriteConfig( @RequestBody Map<String,Object> configs){
Object version = configs.get("version");
File tf = Tool.FileUtil.file(rootPath, versionFile);
log.debug("version file path : {}" ,tf.getAbsolutePath());
if(version==null){
return R.error(RCode.PROMTAIL_CONFIG_VERSION_ISNULL);
}else {
Tool.FileUtil.writeUtf8String(version.toString(), tf);
}
Map<String,String> cmdLine =(Map<String,String>) configs.get("cmdline");
Map<String,Object> promtailConf =(Map<String,Object>) configs.get("config");
// boolean reload = false;
// boolean restart = false;
if(!Tool.MapUtil.isEmpty(cmdLine)){
log.info("write promtail cmdLine conf:{}", Tool.JSONUtil.toJsonStr(cmdLine));
writeServiceConfigFile(cmdLine,promtailCmdLinePath);
// restart = true;
}
if(!Tool.MapUtil.isEmpty(promtailConf)){
log.info("write promtail conf:{}", Tool.JSONUtil.toJsonStr(promtailConf));
Tool.YamlUtil.writeAsMap(promtailConf,promtailConfPath);
// reload = true;
}
return R.ok();
}
/**
* @Description 获取promtail相关配置版本
* @Author rui
* @Date 2021/3/24
*/
@GetMapping("/config/version")
public R queryVersion(){
Map<String,Object> result = new HashMap<>();
String version = confagentUtil.readVersion();
result.put("version",version);
return R.ok(result);
}
/**
* @Description 写 promtail config.conf 启动参数配置文件
* @Author rui
* @Date 2021/3/25
*/
private void writeServiceConfigFile(Map<String,String> conf,String path){
StringBuffer sb = new StringBuffer();
sb.append("OPTION=\"");
for (Map.Entry<String,String> entry:conf.entrySet()){
String key = entry.getKey();
String value = entry.getValue();
sb.append("--"+key+"=");
sb.append("'"+value+"' ");
}
sb.append("\"");
Tool.FileUtil.writeUtf8String(sb.toString(),path);
}
// private boolean reloadPromtail(){
//
// UrlBuilder promtailReload = new UrlBuilder();
// int promtailPort = ConfagentUtil.getConfFilePort(promtailCmdLinePath, PROMTAIL_LISTEN_ADDR, DEFAULT_PROMTAIL_PORT);
// promtailReload.setScheme("http").setHost(defaultPromtailIP).setPort(promtailPort).addPath("/-/reload");
//
// String url = promtailReload.toString();
// HttpRequest post = Tool.HttpUtil.createPost(url);
// HttpResponse response = post.execute();
// return 200 == response.getStatus();
// }
}