接入 Gitee 登录,v0.4.11 之前的用户需要更新配置文件

This commit is contained in:
naiba 2021-03-02 23:08:40 +08:00
parent 8f7346141a
commit 01f99a8c2c
12 changed files with 105 additions and 106 deletions

View File

@ -1,6 +1,6 @@
# 哪吒监控
![GitHub Workflow Status](https://img.shields.io/github/workflow/status/naiba/nezha/Dashboard%20image?label=管理面板%20v0.4.11&logo=github&style=for-the-badge) ![Agent release](https://img.shields.io/github/v/release/naiba/nezha?color=brightgreen&label=Agent&style=for-the-badge&logo=github) ![GitHub Workflow Status](https://img.shields.io/github/workflow/status/naiba/nezha/Agent%20release?label=Agent%20CI&logo=github&style=for-the-badge) ![shell](https://img.shields.io/badge/安装脚本-v0.4.7-brightgreen?style=for-the-badge&logo=linux)
![GitHub Workflow Status](https://img.shields.io/github/workflow/status/naiba/nezha/Dashboard%20image?label=管理面板%20v0.4.12&logo=github&style=for-the-badge) ![Agent release](https://img.shields.io/github/v/release/naiba/nezha?color=brightgreen&label=Agent&style=for-the-badge&logo=github) ![GitHub Workflow Status](https://img.shields.io/github/workflow/status/naiba/nezha/Agent%20release?label=Agent%20CI&logo=github&style=for-the-badge) ![shell](https://img.shields.io/badge/安装脚本-v0.4.7-brightgreen?style=for-the-badge&logo=linux)
:trollface: 哪吒监控 一站式轻监控轻运维系统。支持系统状态、HTTP(SSL 证书变更、即将到期、到期)、TCP、Ping 监控报警,命令批量执行和计划任务。
@ -14,14 +14,14 @@
## 安装脚本
建议使用 WatchTower 自动更新面板Windows 终端可以使用 nssm 配置自启动(见尾部教程)
**推荐配置:** 安装前解析 _两个域名_ 到面板服务器,一个作为 _公开访问_ ,可以 **接入CDN**,比如 (status.nai.ba);另外一个作为安装 Agent 时连接 Dashboard 使用,**不能接入CDN** 直接暴露面板主机IP比如randomdashboard.nai.ba
```shell
curl -L https://raw.githubusercontent.com/naiba/nezha/master/script/install.sh -o nezha.sh && chmod +x nezha.sh
./nezha.sh
```
_\* 目前安装脚本仅支持 CentOS 7+ / Debian 8+ / Ubuntu 16+Windows 及 其他 Linux 发行版请在 Release 处下载对应二进制文件。_
_\* 使用 WatchTower 可以自动更新面板Windows 终端可以使用 nssm 配置自启动(见尾部教程)_
<details>
<summary>国内镜像加速:(有缓存,版本更新不及时,能不用尽量不用,非作者维护)</summary>
@ -97,7 +97,7 @@ URL 里面也可放置占位符,请求时会进行简单的字符串替换。
- cpu、memory、swap、diskMin/Max 数值为占用百分比
- net_in_speed(入站网速)、net_out_speed(出站网速)、net_all_speed(双向网速)、transfer_in(入站流量)、transfer_out(出站流量)、transfer_all(双向流量)Min/Max 数值为字节1kb=10241mb = 1024\*1024
- offline不支持 Min/Max 参数
- Duration持续秒数监控比较简陋取持续时间内的 70 采样结果
- Duration持续秒数监控比较简陋取持续时间内的 70% 采样结果
- Ignore: `{"1": true, "2":false}` 忽略此规则的服务器 ID 列表
</details>

View File

@ -4,6 +4,7 @@ import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/naiba/nezha/model"
"github.com/naiba/nezha/pkg/mygin"
"github.com/naiba/nezha/service/dao"
"golang.org/x/oauth2"
@ -26,12 +27,23 @@ func (gp *guestPage) serve() {
gr.GET("/login", gp.login)
var endPoint oauth2.Endpoint
if dao.Conf.Oauth2.Type == model.ConfigTypeGitee {
endPoint = oauth2.Endpoint{
AuthURL: "https://gitee.com/oauth/authorize",
TokenURL: "https://gitee.com/oauth/token",
}
} else {
endPoint = github.Endpoint
}
oauth := &oauth2controller{
oauth2Config: &oauth2.Config{
ClientID: dao.Conf.GitHub.ClientID,
ClientSecret: dao.Conf.GitHub.ClientSecret,
ClientID: dao.Conf.Oauth2.ClientID,
ClientSecret: dao.Conf.Oauth2.ClientSecret,
Scopes: []string{},
Endpoint: github.Endpoint,
Endpoint: endPoint,
},
r: gr,
}

View File

@ -447,6 +447,7 @@ type settingForm struct {
CustomCode string
ViewPassword string
EnableIPChangeNotification string
Oauth2Type string
}
func (ma *memberAPI) updateSetting(c *gin.Context) {
@ -463,7 +464,8 @@ func (ma *memberAPI) updateSetting(c *gin.Context) {
dao.Conf.Site.Theme = sf.Theme
dao.Conf.Site.CustomCode = sf.CustomCode
dao.Conf.Site.ViewPassword = sf.ViewPassword
dao.Conf.GitHub.Admin = sf.Admin
dao.Conf.Oauth2.Type = sf.Oauth2Type
dao.Conf.Oauth2.Admin = sf.Admin
if err := dao.Conf.Save(); err != nil {
c.JSON(http.StatusOK, model.Response{
Code: http.StatusBadRequest,

View File

@ -2,11 +2,14 @@ package controller
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/google/go-github/github"
GitHubAPI "github.com/google/go-github/github"
"golang.org/x/oauth2"
@ -26,7 +29,16 @@ func (oa *oauth2controller) serve() {
oa.r.GET("/oauth2/callback", oa.callback)
}
func (oa *oauth2controller) fillRedirectURL(c *gin.Context) {
schame := "http://"
if strings.HasPrefix(c.Request.Referer(), "https://") {
schame = "https://"
}
oa.oauth2Config.RedirectURL = schame + c.Request.Host + "/oauth2/callback"
}
func (oa *oauth2controller) login(c *gin.Context) {
oa.fillRedirectURL(c)
state := utils.RandStringBytesMaskImprSrcUnsafe(6)
dao.Cache.Set(fmt.Sprintf("%s%s", model.CacheKeyOauth2State, c.ClientIP()), state, 0)
url := oa.oauth2Config.AuthCodeURL(state, oauth2.AccessTypeOnline)
@ -34,30 +46,32 @@ func (oa *oauth2controller) login(c *gin.Context) {
}
func (oa *oauth2controller) callback(c *gin.Context) {
oa.fillRedirectURL(c)
var err error
// 验证登录跳转时的 State
state, ok := dao.Cache.Get(fmt.Sprintf("%s%s", model.CacheKeyOauth2State, c.ClientIP()))
if !ok || state.(string) != c.Query("state") {
mygin.ShowErrorPage(c, mygin.ErrInfo{
Code: http.StatusBadRequest,
Title: "登录失败",
Msg: fmt.Sprintf("错误信息:%s", "非法的登录方式"),
}, true)
return
err = errors.New("非法的登录方式")
}
// 拉取验证用户信息
ctx := context.Background()
otk, err := oa.oauth2Config.Exchange(ctx, c.Query("code"))
if err != nil {
mygin.ShowErrorPage(c, mygin.ErrInfo{
Code: http.StatusBadRequest,
Title: "登录失败",
Msg: fmt.Sprintf("错误信息:%s", err),
}, true)
return
var otk *oauth2.Token
if err == nil {
otk, err = oa.oauth2Config.Exchange(ctx, c.Query("code"))
}
oc := oa.oauth2Config.Client(ctx, otk)
client := GitHubAPI.NewClient(oc)
gu, _, err := client.Users.Get(ctx, "")
var client *GitHubAPI.Client
if err == nil {
oc := oa.oauth2Config.Client(ctx, otk)
if dao.Conf.Oauth2.Type == "gitee" {
client, err = GitHubAPI.NewEnterpriseClient("https://gitee.com/api/v5/", "https://gitee.com/api/v5/", oc)
} else {
client = GitHubAPI.NewClient(oc)
}
}
var gu *github.User
if err == nil {
gu, _, err = client.Users.Get(ctx, "")
}
log.Printf("%+v", gu)
if err != nil {
mygin.ShowErrorPage(c, mygin.ErrInfo{
Code: http.StatusBadRequest,
@ -67,12 +81,10 @@ func (oa *oauth2controller) callback(c *gin.Context) {
return
}
var isAdmin bool
if gu.GetID() > 0 {
for _, admin := range strings.Split(dao.Conf.GitHub.Admin, ",") {
if fmt.Sprintf("%d", gu.GetID()) == admin {
isAdmin = true
break
}
for _, admin := range strings.Split(dao.Conf.Oauth2.Admin, ",") {
if admin != "" && gu.GetLogin() == admin {
isAdmin = true
break
}
}
if !isAdmin {

View File

@ -17,11 +17,11 @@ const (
type Rule struct {
// 指标类型cpu、memory、swap、disk、net_in_speed、net_out_speed
// net_all_speed、transfer_in、transfer_out、transfer_all、offline
Type string
Min uint64 // 最小阈值 (百分比、字节 kb ÷ 1024)
Max uint64 // 最大阈值 (百分比、字节 kb ÷ 1024)
Duration uint64 // 持续时间 (秒)
Ignore map[uint64]bool //忽略此规则的ID列表
Type string `json:"type,omitempty"`
Min uint64 `json:"min,omitempty"` // 最小阈值 (百分比、字节 kb ÷ 1024)
Max uint64 `json:"max,omitempty"` // 最大阈值 (百分比、字节 kb ÷ 1024)
Duration uint64 `json:"duration,omitempty"` // 持续时间 (秒)
Ignore map[uint64]bool `json:"ignore,omitempty"` //忽略此规则的ID列表
}
func percentage(used, total uint64) uint64 {
@ -123,7 +123,7 @@ func (r *AlertRule) Check(points [][]interface{}) (int, string) {
fail++
}
}
if fail/total > 0.5 {
if fail/total > 0.7 {
count++
dist.WriteString(fmt.Sprintf("%+v\n", r.Rules[i]))
}

View File

@ -10,6 +10,11 @@ import (
"gopkg.in/yaml.v2"
)
const (
ConfigTypeGitHub = "github"
ConfigTypeGitee = "gitee"
)
type Config struct {
Debug bool
Site struct {
@ -19,8 +24,9 @@ type Config struct {
CustomCode string
ViewPassword string // 前台查看密码
}
GitHub struct {
Admin string // 管理员ID列表
Oauth2 struct {
Type string
Admin string // 管理员用户名列表
ClientID string
ClientSecret string
}

View File

@ -5,16 +5,16 @@
<img src="/static/logo.png">
</div>
{{if .IsAdminPage}}
<a class="item{{if eq .MatchedPath " /server"}} active{{end}}" href="/server"><i class="server icon"></i>资产</a>
<a class="item{{if eq .MatchedPath " /monitor"}} active{{end}}" href="/monitor"><i class="rss icon"></i>服务</a>
<a class="item{{if eq .MatchedPath " /cron"}} active{{end}}" href="/cron"><i class="clock icon"></i>任务</a>
<a class="item{{if eq .MatchedPath " /notification"}} active{{end}}" href="/notification"><i class="bell icon"></i>报警</a>
<a class="item{{if eq .MatchedPath " /setting"}} active{{end}}" href="/setting">
<a class='item{{if eq .MatchedPath "/server"}} active{{end}}' href="/server"><i class="server icon"></i>资产</a>
<a class='item{{if eq .MatchedPath "/monitor"}} active{{end}}' href="/monitor"><i class="rss icon"></i>服务</a>
<a class='item{{if eq .MatchedPath "/cron"}} active{{end}}' href="/cron"><i class="clock icon"></i>任务</a>
<a class='item{{if eq .MatchedPath "/notification"}} active{{end}}' href="/notification"><i class="bell icon"></i>报警</a>
<a class='item{{if eq .MatchedPath "/setting"}} active{{end}}' href="/setting">
<i class="settings icon"></i>设置
</a>
{{else}}
<a class="item{{if eq .MatchedPath " /"}} active{{end}}" href="/"><i class="home icon"></i>首页</a>
<a class="item{{if eq .MatchedPath " /service"}} active{{end}}" href="/service"><i class="rss icon"></i>服务状态</a>
<a class='item{{if eq .MatchedPath "/"}} active{{end}}' href="/"><i class="home icon"></i>首页</a>
<a class='item{{if eq .MatchedPath "/service"}} active{{end}}' href="/service"><i class="rss icon"></i>服务状态</a>
{{end}}
<div class="right menu">
<div class="item">

View File

@ -10,7 +10,7 @@
</div>
<div class="field">
<label>管理员列表</label>
<input type="text" name="Admin" placeholder="1010,2020" value="{{.Conf.GitHub.Admin}}">
<input type="text" name="Admin" placeholder="1010,2020" value="{{.Conf.Oauth2.Admin}}">
</div>
<div class="field">
<select name="Theme">
@ -56,4 +56,4 @@
$('.checkbox').checkbox('set checked')
{{end}}
</script>
{{end}}
{{end}}

View File

@ -1,7 +1,8 @@
debug: true
httpport: 80
github:
admin: "nz_admin_ids" #管理员 GitHub ID复制自己GitHub头像图片地址/[ID].png 多个用英文逗号隔开
oauth2:
type: "nz_oauth2_type" #Oauth2 登录接入类型gitee/github
admin: "nz_admin_logins" #管理员列表,半角逗号隔开
clientid: "nz_github_oauth_client_id" # 在 https://github.com/settings/developers 创建,无需审核 Callback 填 http(s)://域名或IP/oauth2/callback
clientsecret: "nz_github_oauth_client_secret"
site:

View File

@ -1,16 +1,17 @@
#!/bin/bash
#======================================================
# System Required: CentOS 7+ / Debian 8+ / Ubuntu 16+
#========================================================
# System Required: CentOS 7+ / Debian 8+ / Ubuntu 16+ /
# Arch 未测试
# Description: 哪吒监控安装脚本
# Github: https://github.com/naiba/nezha
#======================================================
#========================================================
NZ_BASE_PATH="/opt/nezha"
NZ_DASHBOARD_PATH="${NZ_BASE_PATH}/dashboard"
NZ_AGENT_PATH="${NZ_BASE_PATH}/agent"
NZ_AGENT_SERVICE="/etc/systemd/system/nezha-agent.service"
NZ_VERSION="v0.4.7"
NZ_VERSION="v0.4.8"
red='\033[0;31m'
green='\033[0;32m'
@ -18,7 +19,6 @@ yellow='\033[0;33m'
plain='\033[0m'
export PATH=$PATH:/usr/local/bin
os_version=""
os_arch=""
pre_check() {
@ -31,47 +31,6 @@ pre_check() {
# check root
[[ $EUID -ne 0 ]] && echo -e "${red}错误: ${plain} 必须使用root用户运行此脚本\n" && exit 1
# check os
if [[ -f /etc/redhat-release ]]; then
release="centos"
elif cat /etc/issue | grep -Eqi "debian"; then
release="debian"
elif cat /etc/issue | grep -Eqi "ubuntu"; then
release="ubuntu"
elif cat /etc/issue | grep -Eqi "centos|red hat|redhat"; then
release="centos"
elif cat /proc/version | grep -Eqi "debian"; then
release="debian"
elif cat /proc/version | grep -Eqi "ubuntu"; then
release="ubuntu"
elif cat /proc/version | grep -Eqi "centos|red hat|redhat"; then
release="centos"
else
echo -e "${red}未检测到系统版本,请联系脚本作者!${plain}\n" && exit 1
fi
# os version
if [[ -f /etc/os-release ]]; then
os_version=$(awk -F'[= ."]' '/VERSION_ID/{print $3}' /etc/os-release)
fi
if [[ -z "$os_version" && -f /etc/lsb-release ]]; then
os_version=$(awk -F'[= ."]+' '/DISTRIB_RELEASE/{print $2}' /etc/lsb-release)
fi
if [[ x"${release}" == x"centos" ]]; then
if [[ ${os_version} -le 6 ]]; then
echo -e "${red}请使用 CentOS 7 或更高版本的系统!${plain}\n" && exit 1
fi
elif [[ x"${release}" == x"ubuntu" ]]; then
if [[ ${os_version} -lt 16 ]]; then
echo -e "${red}请使用 Ubuntu 16 或更高版本的系统!${plain}\n" && exit 1
fi
elif [[ x"${release}" == x"debian" ]]; then
if [[ ${os_version} -lt 8 ]]; then
echo -e "${red}请使用 Debian 8 或更高版本的系统!${plain}\n" && exit 1
fi
fi
## os_arch
if [[ $(uname -m | grep 'x86_64') != "" ]]; then
os_arch="amd64"
@ -121,6 +80,7 @@ install_base() {
install_soft() {
(command -v yum >/dev/null 2>&1 && yum install $* -y) ||
(command -v apt >/dev/null 2>&1 && apt install $* -y) ||
(command -v pacman >/dev/null 2>&1 && pacman -Syu $*) ||
(command -v apt-get >/dev/null 2>&1 && apt-get install $* -y)
}
@ -248,14 +208,16 @@ modify_dashboard_config() {
fi
echo "关于管理员 GitHub ID复制自己GitHub头像图片地址里面的数字/87123.png 多个用英文逗号隔开 87123,id2,id3" &&
read -p "请输入 ID 列表: " nz_admin_ids &&
echo "关于 GitHub Oauth2 应用:在 https://github.com/settings/developers 创建,无需审核 Callback 填 http(s)://域名或IP/oauth2/callback" &&
read -p "请输入 GitHub Oauth2 应用的 Client ID: " nz_github_oauth_client_id &&
read -p "请输入 GitHub Oauth2 应用的 Client Secret: " nz_github_oauth_client_secret &&
echo "关于 GitHub Oauth2 应用:在 https://github.com/settings/developers 创建无需审核Callback 填 http(s)://域名或IP/oauth2/callback" &&
echo "关于 Gitee Oauth2 应用:在 https://gitee.com/oauth/applications 创建无需审核Callback 填 http(s)://域名或IP/oauth2/callback" &&
read -p "请输入 OAuth2 提供商(gitee/github默认 github): " nz_oauth2_type &&
read -p "请输入 Oauth2 应用的 Client ID: " nz_github_oauth_client_id &&
read -p "请输入 Oauth2 应用的 Client Secret: " nz_github_oauth_client_secret &&
read -p "请输入 GitHub/Gitee 登录名作为管理员,多个以逗号隔开: " nz_admin_logins &&
read -p "请输入站点标题: " nz_site_title &&
read -p "请输入站点访问端口: (8008)" nz_site_port &&
read -p "请输入用于 Agent 接入的 RPC 端口: (5555)" nz_grpc_port
if [[ -z "${nz_admin_ids}" || -z "${nz_github_oauth_client_id}" || -z "${nz_github_oauth_client_secret}" || -z "${nz_site_title}" ]]; then
if [[ -z "${nz_admin_logins}" || -z "${nz_github_oauth_client_id}" || -z "${nz_github_oauth_client_secret}" || -z "${nz_site_title}" ]]; then
echo -e "${red}所有选项都不能为空${plain}"
before_show_menu
return 1
@ -267,8 +229,12 @@ modify_dashboard_config() {
if [[ -z "${nz_grpc_port}" ]]; then
nz_grpc_port=5555
fi
if [[ -z "${nz_oauth2_type}" ]]; then
nz_oauth2_type=github
fi
sed -i "s/nz_admin_ids/${nz_admin_ids}/" ${NZ_DASHBOARD_PATH}/data/config.yaml
sed -i "s/nz_oauth2_type/${nz_oauth2_type}/" ${NZ_DASHBOARD_PATH}/data/config.yaml
sed -i "s/nz_admin_logins/${nz_admin_logins}/" ${NZ_DASHBOARD_PATH}/data/config.yaml
sed -i "s/nz_github_oauth_client_id/${nz_github_oauth_client_id}/" ${NZ_DASHBOARD_PATH}/data/config.yaml
sed -i "s/nz_github_oauth_client_secret/${nz_github_oauth_client_secret}/" ${NZ_DASHBOARD_PATH}/data/config.yaml
sed -i "s/nz_site_title/${nz_site_title}/" ${NZ_DASHBOARD_PATH}/data/config.yaml

View File

@ -13,7 +13,7 @@ import (
pb "github.com/naiba/nezha/proto"
)
var Version = "v0.4.11" // !!记得修改 README 重的 badge 版本!!
var Version = "v0.4.12" // !!记得修改 README 重的 badge 版本!!
const (
SnapshotDelay = 3

View File

@ -25,8 +25,8 @@ func (s *NezhaHandler) ReportTask(c context.Context, r *pb.TaskResult) (*pb.Rece
// SSL 证书报警
var errMsg string
if strings.HasPrefix(r.GetData(), "SSL证书错误") {
// 排除超时错误
if !strings.HasSuffix(r.GetData(), "timeout") {
// 排除 i/o timeont、connection timeout、EOF 错误
if !strings.HasSuffix(r.GetData(), "timeout") && r.GetData() != "EOF" {
errMsg = r.GetData()
}
} else {