Skip to content

Commit

Permalink
init v1 script (#8)
Browse files Browse the repository at this point in the history
* init v1 script

* .

* complete dashboard script

* init agent script (posix)

* complete agent script (posix)
  • Loading branch information
uubulb authored Nov 30, 2024
1 parent 7eb6a3a commit 7132b6d
Show file tree
Hide file tree
Showing 22 changed files with 2,394 additions and 2,638 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*~
.DS_Store
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ LOCALES := zh_CN en_US

run:
@for locale in $(LOCALES); do \
go run ./cmd/scriptgen/main.go locale.json $$locale; \
go run ./cmd/scriptgen/main.go nezha/translations $$locale; \
done
22 changes: 1 addition & 21 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1 @@
这里存放着所有关于哪吒监控官方安装脚本的文件。

如何贡献:
1. 仅更新 `template.sh`,不要编辑 `install.sh` 或者 `install_en.sh`,因为它们是生成的文件。如果你需要文本输出,请使用 Go 模板(比如 `{{.Placeholder}}`)。
2. `template.sh` 必须兼容 POSIX sh,可以使用 <https://www.shellcheck.net/> 确认。
2. 如果你在 `template.sh` 添加了任何模板,请同步更新 `locale.json`
3. 运行 `make`。如果不能运行,请检查是否安装了 `go``make`

对于其它没有本地化的脚本(比如 Windows 和 macOS 的),请直接更改。

---

Here lies everything related to the official Nezha installation script.

How to contribute:
1. Update `template.sh` only. Do not edit `install.sh` or `install_en.sh`, for they're generated files. Use Go templates (e.g. `{{.Placeholder}}`) if printing text is needed.
2. `template.sh` must be POSIX-compliant. To confirm it, you can use <https://www.shellcheck.net/>.
3. Update `locale.json` if any template is added in `template.sh`.
4. Run `make`. Remember to have `go` and `make` installed.

For other scripts that don't have localization (like the Windows or macOS one), edit them directly.
Nezha Installation scripts (updated for v1)
File renamed without changes.
165 changes: 165 additions & 0 deletions agent/install.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
#!/bin/sh

NZ_BASE_PATH="/opt/nezha"
NZ_AGENT_PATH="${NZ_BASE_PATH}/agent"

red='\033[0;31m'
green='\033[0;32m'
plain='\033[0m'

err() {
printf "${red}%s${plain}\n" "$*" >&2
}

success() {
printf "${green}%s${plain}\n" "$*"
}

sudo() {
myEUID=$(id -ru)
if [ "$myEUID" -ne 0 ]; then
if command -v sudo > /dev/null 2>&1; then
command sudo "$@"
else
err "ERROR: sudo is not installed on the system, the action cannot be proceeded."
exit 1
fi
else
"$@"
fi
}

deps_check() {
deps="wget unzip grep"
set -- "$api_list"
for dep in $deps; do
if ! command -v "$dep" >/dev/null 2>&1; then
err "$dep not found, please install it first."
exit 1
fi
done
}

geo_check() {
api_list="https://blog.cloudflare.com/cdn-cgi/trace https://developers.cloudflare.com/cdn-cgi/trace"
ua="Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/81.0"
set -- "$api_list"
for url in $api_list; do
text="$(curl -A "$ua" -m 10 -s "$url")"
endpoint="$(echo "$text" | sed -n 's/.*h=\([^ ]*\).*/\1/p')"
if echo "$text" | grep -qw 'CN'; then
isCN=true
break
elif echo "$url" | grep -q "$endpoint"; then
break
fi
done
}

env_check() {
mach=$(uname -m)
case "$mach" in
amd64)
os_arch="amd64"
;;
i386|i686)
os_arch="386"
;;
aarch64|arm64)
os_arch="arm64"
;;
*arm*)
os_arch="arm"
;;
s390x)
os_arch="s390x"
;;
riscv64)
os_arch="riscv64"
;;
mips)
os_arch="mips"
;;
mipsel|mipsle)
os_arch="mipsle"
;;
*)
err "Unknown architecture: $uname"
exit 1
;;
esac

system=$(uname)
case "$system" in
*Linux*)
os="linux"
;;
*Darwin*)
os="darwin"
;;
*FreeBSD*)
os="freebsd"
;;
*)
err "Unknown architecture: $system"
exit 1
;;
esac
}

init() {
deps_check
env_check

## China_IP
if [ -z "$CN" ]; then
geo_check
if [ -n "$isCN" ]; then
CN=true
fi
fi

if [ -z "$CN" ]; then
GITHUB_URL="github.com"
else
GITHUB_URL="gitee.com"
fi
}

install() {
echo "Installing..."

if [ -z "$CN" ]; then
NZ_AGENT_URL="https://${GITHUB_URL}/nezhahq/agent/releases/latest/download/nezha-agent_linux_${os_arch}.zip"
else
NZ_AGENT_URL="https://${GITHUB_URL}/naibahq/agent/releases/latest/download/nezha-agent_linux_${os_arch}.zip"
fi

_cmd="wget -t 2 -T 60 -O /tmp/nezha-agent_${os}_${os_arch}.zip $NZ_AGENT_URL >/dev/null 2>&1"
if ! eval "$_cmd"; then
err "Download nezha-agent release failed, check your network connectivity"
exit 1
fi

sudo unzip -qo /tmp/nezha-agent_${os}_${os_arch}.zip -d $NZ_AGENT_PATH &&
sudo rm -rf /tmp/nezha-agent_${os}_${os_arch}.zip

path="$NZ_AGENT_PATH/config.yml"
if [ -f "$path" ]; then
random=$(LC_ALL=C tr -dc a-z0-9 </dev/urandom | head -c 5)
path=$(printf "%s" "$NZ_AGENT_PATH/config-$random.yml")
fi

env="NZ_SERVER=$NZ_SERVER NZ_CLIENT_SECRET=$NZ_CLIENT_SECRET NZ_TLS=$NZ_TLS NZ_DISABLE_AUTO_UPDATE=$NZ_DISABLE_AUTO_UPDATE NZ_DISABLE_FORCE_UPDATE=$DISABLE_FORCE_UPDATE NZ_DISABLE_COMMAND_EXECUTE=$NZ_DISABLE_COMMAND_EXECUTE NZ_SKIP_CONNECTION_COUNT=$NZ_SKIP_CONNECTION_COUNT"

_cmd="sudo $env $NZ_AGENT_PATH/nezha-agent service -c "$path" install"
if ! eval "$_cmd"; then
err "Install nezha-agent service failed"
exit 1
fi

success "nezha-agent successfully installed"
}

init
install
72 changes: 49 additions & 23 deletions cmd/scriptgen/main.go
Original file line number Diff line number Diff line change
@@ -1,74 +1,100 @@
package main

import (
"encoding/json"
"bufio"
"fmt"
"os"
"text/template"
"regexp"
"strings"

"github.com/chai2010/gettext-go"
)

const (
zh_CN = "zh_CN"
en_US = "en_US"
)

var localeMap map[string]map[string]interface{}

func main() {
if len(os.Args) != 3 {
printUsage()
exitWithError("Error: Need exactly 2 arguments")
}

if err := readLocalesFromFile(os.Args[1]); err != nil {
exitWithError(fmt.Sprintf("readLocalesFromFile: %v", err))
}
readLocalesFromDir(os.Args[1])

if err := parseTemplate(os.Args[2]); err != nil {
exitWithError(fmt.Sprintf("parseTemplate: %v", err))
}
}

func printUsage() {
fmt.Printf("usage: %s [locale-file] [locale]\n", os.Args[0])
fmt.Printf("usage: %s [localedir] [locale]\n", os.Args[0])
}

func exitWithError(message string) {
fmt.Fprintln(os.Stderr, message)
os.Exit(1)
}

func readLocalesFromFile(file string) error {
b, err := os.ReadFile(file)
if err != nil {
return err
}

return json.Unmarshal(b, &localeMap)
func readLocalesFromDir(dir string) {
gettext.BindLocale(gettext.New("nezha", dir))
}

func parseTemplate(lang string) error {
tmpl, err := template.ParseFiles("template.sh")
if err != nil {
return err
}
gettext.SetLanguage(lang)
regex := regexp.MustCompile(`_\("([^"]+)"\)`)

var file *os.File
var err error
switch lang {
case zh_CN:
file, err := os.Create("install.sh")
file, err = os.Create("install.sh")
if err != nil {
return err
}
defer file.Close()
return tmpl.Execute(file, localeMap[zh_CN])
case en_US:
file, err := os.Create("install_en.sh")
file, err = os.Create("install_en.sh")
if err != nil {
return err
}
defer file.Close()
return tmpl.Execute(file, localeMap[en_US])
default:
return fmt.Errorf("unsupported locale: %s", lang)
}

template, err := os.Open("nezha/template.sh")
if err != nil {
return err
}

var newline string
scanner := bufio.NewScanner(template)
buf := make([]byte, 1024*1024)
scanner.Buffer(buf, len(buf))

writer := bufio.NewWriter(file)
defer writer.Flush()

for scanner.Scan() {
line := scanner.Text()
matches := regex.FindAllStringSubmatch(line, -1)

if len(matches) > 0 {
orig := matches[0][0]
translated := fmt.Sprintf("\"%s\"", gettext.PGettext("", matches[0][1]))
newline = strings.ReplaceAll(line, orig, translated)
} else {
newline = line
}

_, err := writer.WriteString(fmt.Sprintln(newline))
if err != nil {
fmt.Println("Error writing to file:", err)
return err
}
}

return nil
}
14 changes: 2 additions & 12 deletions extras/config.yaml
Original file line number Diff line number Diff line change
@@ -1,14 +1,4 @@
debug: false
httpport: 80
listenport: nz_port
language: nz_language
grpcport: nz_grpc_port
oauth2:
type: "nz_oauth2_type" #Oauth2 登录接入类型,github/gitlab/jihulab/gitee/gitea
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"
endpoint: "" # 如gitea自建需要设置
site:
brand: "nz_site_title"
cookiename: "nezha-dashboard" #浏览器 Cookie 字段名,可不改
theme: "default"
sitename: "nz_site_title"
9 changes: 2 additions & 7 deletions extras/docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
version: "3.3"

services:
dashboard:
image: nz_image_url
container_name: nezha-dashboard
restart: always
volumes:
- ./data:/dashboard/data
- ./static-custom/static:/dashboard/resource/static/custom:ro
- ./theme-custom/template:/dashboard/resource/template/theme-custom:ro
- ./dashboard-custom/template:/dashboard/resource/template/dashboard-custom:ro
ports:
- nz_site_port:80
- nz_grpc_port:nz_grpc_port
- nz_port:nz_port
Loading

0 comments on commit 7132b6d

Please sign in to comment.