Skip to content

Commit 0ec5189

Browse files
committed
fix report API, and a few translations
1 parent 9308d58 commit 0ec5189

File tree

11 files changed

+60
-65
lines changed

11 files changed

+60
-65
lines changed

cluster/cluster.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ var (
4242
reFileHashMismatchError = regexp.MustCompile(` hash mismatch, expected ([0-9a-f]+), got ([0-9a-f]+)`)
4343
)
4444

45+
const DefaultBMCLAPIServer = "https://openbmclapi.bangbang93.com"
46+
4547
type Cluster struct {
4648
name string
4749
opts config.ClusterOptions
@@ -77,7 +79,11 @@ func NewCluster(
7779
for i, name := range opts.Storages {
7880
storages[i] = storageManager.GetIndex(name)
7981
}
82+
if opts.Server == "" {
83+
opts.Server = DefaultBMCLAPIServer
84+
}
8085
cr = &Cluster{
86+
name: name,
8187
opts: opts,
8288
gcfg: gcfg,
8389

cluster/requests.go

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import (
2626
"crypto/hmac"
2727
"encoding/hex"
2828
"encoding/json"
29+
"errors"
2930
"fmt"
3031
"net/http"
3132
"net/url"
@@ -261,12 +262,18 @@ func (cr *Cluster) RequestCert(ctx context.Context) (ckp *CertKeyPair, err error
261262
}
262263

263264
func (cr *Cluster) ReportDownload(ctx context.Context, response *http.Response, err error) error {
265+
if errors.Is(err, context.Canceled) {
266+
return nil
267+
}
268+
264269
type ReportPayload struct {
265-
Urls []string `json:"urls"`
266-
Error utils.EmbedJSON[struct{ Message string }] `json:"error"`
270+
Urls []string `json:"urls"`
271+
Error utils.EmbedJSON[struct {
272+
Message string `json:"message"`
273+
}] `json:"error"`
267274
}
268275
var payload ReportPayload
269-
redirects := utils.GetRedirects(response.Request)
276+
redirects := utils.GetRedirects(response)
270277
payload.Urls = make([]string, len(redirects))
271278
for i, u := range redirects {
272279
payload.Urls[i] = u.String()
@@ -280,6 +287,7 @@ func (cr *Cluster) ReportDownload(ctx context.Context, response *http.Response,
280287
if err != nil {
281288
return err
282289
}
290+
req.Header.Set("Content-Type", "application/json")
283291
resp, err := cr.client.Do(req)
284292
if err != nil {
285293
return err

cluster/socket.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ func (cr *Cluster) Connect(ctx context.Context) error {
6868
})
6969
}
7070
engio.OnConnect(func(s *engine.Socket) {
71-
log.Info("Engine.IO %s connected for cluster %s", s.ID(), cr.ID())
71+
log.Infof("Engine.IO %s connected for cluster %s", s.ID(), cr.ID())
7272
})
7373
engio.OnDisconnect(cr.onDisconnected)
7474
engio.OnDialError(func(s *engine.Socket, err *engine.DialErrorContext) {
@@ -102,7 +102,7 @@ func (cr *Cluster) Connect(ctx context.Context) error {
102102
log.Infof("[remote]: %v", data[0])
103103
}
104104
})
105-
log.Info("Connecting to socket.io namespace")
105+
log.Infof("Cluster %s is connecting to socket.io namespace", cr.Name())
106106
if err := cr.socket.Connect(""); err != nil {
107107
return fmt.Errorf("Namespace connect error: %w", err)
108108
}

cluster/storage.go

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -174,23 +174,6 @@ func storageIdSortFunc(a, b storage.Storage) int {
174174
return 1
175175
}
176176

177-
// func SyncFiles(ctx context.Context, manager *storage.Manager, files map[string]*StorageFileInfo, heavyCheck bool) bool {
178-
// log.TrInfof("info.sync.prepare", len(files))
179-
180-
// slices.SortFunc(files, func(a, b *StorageFileInfo) int { return a.Size - b.Size })
181-
// if cr.syncFiles(ctx, files, heavyCheck) != nil {
182-
// return false
183-
// }
184-
185-
// cr.filesetMux.Lock()
186-
// for _, f := range files {
187-
// cr.fileset[f.Hash] = f.Size
188-
// }
189-
// cr.filesetMux.Unlock()
190-
191-
// return true
192-
// }
193-
194177
var emptyStr string
195178

196179
func checkFile(
@@ -393,12 +376,15 @@ func (c *HTTPClient) SyncFiles(
393376
return err
394377
}
395378

396-
totalFiles := len(files)
379+
totalFiles := len(missingMap)
397380

398381
var stats syncStats
399382
stats.pg = pg
400383
stats.slots = limited.NewBufSlots(slots)
401384
stats.totalFiles = totalFiles
385+
for _, f := range missingMap {
386+
stats.totalSize += f.Size
387+
}
402388

403389
var barUnit decor.SizeB1024
404390
stats.lastInc.Store(time.Now().UnixNano())
@@ -620,7 +606,8 @@ func (c *HTTPClient) fetchFile(ctx context.Context, stats *syncStats, f *Storage
620606
return utils.ProxyPBReader(r, bar, stats.totalBar, &stats.lastInc)
621607
}); err != nil {
622608
reqInd = (reqInd + 1) % len(reqs)
623-
if rerr, ok := err.(*utils.RedirectError); ok {
609+
var rerr *utils.RedirectError
610+
if errors.As(err, &rerr) {
624611
go func() {
625612
if err := rp.Cluster.ReportDownload(context.WithoutCancel(ctx), rerr.GetResponse(), rerr.Unwrap()); err != nil {
626613
log.Warnf("Report API error: %v", err)
@@ -642,7 +629,7 @@ func (c *HTTPClient) fetchFile(ctx context.Context, stats *syncStats, f *Storage
642629
bar.SetRefill(bar.Current())
643630

644631
c := tried.Add(1)
645-
if c > maxRetryCount {
632+
if c > maxRetryCount || errors.Is(err, context.Canceled) {
646633
log.TrErrorf("error.sync.download.failed", f.Hash, err)
647634
stats.failCount.Add(1)
648635
return

config.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,13 @@ import (
3333
"gopkg.in/yaml.v3"
3434

3535
"github.com/LiterMC/go-openbmclapi/api"
36+
"github.com/LiterMC/go-openbmclapi/cluster"
3637
"github.com/LiterMC/go-openbmclapi/config"
3738
"github.com/LiterMC/go-openbmclapi/log"
3839
"github.com/LiterMC/go-openbmclapi/storage"
3940
"github.com/LiterMC/go-openbmclapi/utils"
4041
)
4142

42-
const DefaultBMCLAPIServer = "https://openbmclapi.bangbang93.com"
43-
4443
func migrateConfig(data []byte, cfg *config.Config) {
4544
var oldConfig map[string]any
4645
if err := yaml.Unmarshal(data, &oldConfig); err != nil {
@@ -97,7 +96,7 @@ func readAndRewriteConfig() (cfg *config.Config, err error) {
9796
Id: "${CLUSTER_ID}",
9897
Secret: "${CLUSTER_SECRET}",
9998
PublicHosts: []string{},
100-
Server: DefaultBMCLAPIServer,
99+
Server: cluster.DefaultBMCLAPIServer,
101100
SkipSignatureCheck: false,
102101
},
103102
}

lang/en/us.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ var areaUS = map[string]string{
1010
"warn.exit.detected.windows.open.browser": "Detected that you are in windows environment, we are helping you to open the browser",
1111
"warn.cluster.detected.hash.mismatch": "Detected hash mismatch error, removing bad file %s",
1212

13-
"info.filelist.fetching": "Fetching file list",
13+
"info.filelist.fetching": "Fetching file list for %s",
1414
"error.filelist.fetch.failed": "Cannot fetch cluster file list: %v",
1515

1616
"error.address.listen.failed": "Cannot listen address %s: %v",
1717

18-
"info.cert.requesting": "Requesting certificates, please wait ...",
18+
"info.cert.requesting": "Requesting certificates for %s, please wait ...",
1919
"info.cert.requested": "Requested certificate for %s",
2020
"error.cert.not.set": "No certificates was set in the config",
2121
"error.cert.parse.failed": "Cannot parse certificate key pair[%d]: %v",
@@ -27,7 +27,7 @@ var areaUS = map[string]string{
2727
"info.wait.first.sync": "Waiting for the first sync ...",
2828
"info.cluster.enable.sending": "Sending enable packet",
2929
"info.cluster.enabled": "Cluster enabled",
30-
"error.cluster.enable.failed": "Cannot enable cluster: %v",
30+
"error.cluster.enable.failed": "Cannot enable cluster %s: %v",
3131
"error.cluster.disconnected": "Cluster disconnected from remote. exit.",
3232
"info.cluster.reconnect.keepalive": "Reconnecting due to keepalive failed",
3333
"info.cluster.reconnecting": "Reconnecting ...",
@@ -49,8 +49,8 @@ var areaUS = map[string]string{
4949
"warn.cluster.disabled": "Cluster disabled",
5050
"warn.httpserver.closing": "Closing HTTP server ...",
5151

52-
"info.check.start": "Start checking files for %s, heavy = %v",
53-
"info.check.done": "File check finished for %s, missing %d files",
52+
"info.check.start": "Start checking files, heavy = %v",
53+
"info.check.done": "File check finished, missing %d files",
5454
"error.check.failed": "Failed to check %s: %v",
5555
"hint.check.checking": "> Checking ",
5656
"warn.check.modified.size": "Found modified file: size of %q is %d, expect %d",

lang/zh/cn.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ var areaCN = map[string]string{
1010
"warn.exit.detected.windows.open.browser": "检测到您是新手 Windows 用户. 我们正在帮助您打开浏览器 ...",
1111
"warn.cluster.detected.hash.mismatch": "检测到文件哈希值不匹配, 正在删除 %s",
1212

13-
"info.filelist.fetching": "获取文件列表中",
13+
"info.filelist.fetching": "为 %s 获取文件列表中",
1414
"error.filelist.fetch.failed": "文件列表获取失败: %v",
1515

1616
"error.address.listen.failed": "无法监听地址 %s: %v",
1717

18-
"info.cert.requesting": "请求证书中, 请稍候 ...",
18+
"info.cert.requesting": "正在为 %s 请求证书, 请稍候 ...",
1919
"info.cert.requested": "证书请求完毕, 域名为 %s",
2020
"error.cert.not.set": "配置文件内没有提供证书",
2121
"error.cert.parse.failed": "无法解析证书密钥对[%d]: %v",
@@ -27,7 +27,7 @@ var areaCN = map[string]string{
2727
"info.wait.first.sync": "正在等待第一次同步 ...",
2828
"info.cluster.enable.sending": "正在发送启用数据包",
2929
"info.cluster.enabled": "节点已启用",
30-
"error.cluster.enable.failed": "无法启用节点: %v",
30+
"error.cluster.enable.failed": "无法启用节点 %s: %v",
3131
"error.cluster.disconnected": "节点从主控断开. exit.",
3232
"info.cluster.reconnect.keepalive": "保活失败, 重连中 ...",
3333
"info.cluster.reconnecting": "重连中 ...",
@@ -49,8 +49,8 @@ var areaCN = map[string]string{
4949
"warn.cluster.disabled": "节点已禁用",
5050
"warn.httpserver.closing": "正在关闭 HTTP 服务器 ...",
5151

52-
"info.check.start": "开始在 %s 检测文件. 强检查 = %v",
53-
"info.check.done": "文件在 %s 检查完毕, 缺失 %d 个文件",
52+
"info.check.start": "开始检测文件. 强检查 = %v",
53+
"info.check.done": "文件检查完毕, 缺失 %d 个文件",
5454
"error.check.failed": "无法检查 %s: %v",
5555
"hint.check.checking": "> 检查中 ",
5656
"warn.check.modified.size": "找到修改过的文件: %q 的大小为 %d, 预期 %d",

main.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,9 @@ func main() {
167167

168168
log.TrInfof("info.wait.first.sync")
169169
r.InitSynchronizer(ctx)
170+
if ctx.Err() != nil {
171+
return
172+
}
170173

171174
r.EnableClusterAll(ctx)
172175
}(ctx)

runner.go

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ func NewRunner(cfg *config.Config) *Runner {
158158
log.Errorf("Stat load failed: %v", err)
159159
}
160160
r.apiRateLimiter = limited.NewAPIRateMiddleWare(api.RealAddrCtxKey, "go-openbmclapi.cluster.logged.user" /* api/v0.loggedUserKey */)
161+
r.certificates = make(map[string]*tls.Certificate)
161162
return r
162163
}
163164

@@ -227,25 +228,11 @@ func (r *Runner) InitClusters(ctx context.Context) {
227228
for name, opts := range r.Config.Clusters {
228229
cr := cluster.NewCluster(name, opts, gcfg, r.storageManager, r.statManager, r.client)
229230
if err := cr.Init(ctx); err != nil {
230-
log.TrErrorf("error.init.failed", err)
231-
} else {
232-
r.clusters[name] = cr
231+
log.TrErrorf("error.init.failed", cr.Name(), err)
232+
continue
233233
}
234+
r.clusters[name] = cr
234235
}
235-
236-
// r.cluster = NewCluster(ctx,
237-
// ClusterServerURL,
238-
// baseDir,
239-
// config.PublicHost, r.getPublicPort(),
240-
// config.ClusterId, config.ClusterSecret,
241-
// config.Byoc, dialer,
242-
// config.Storages,
243-
// cache,
244-
// )
245-
// if err := r.cluster.Init(ctx); err != nil {
246-
// log.TrErrorf("error.init.failed"), err)
247-
// os.Exit(1)
248-
// }
249236
}
250237

251238
func (r *Runner) ListenSignals(ctx context.Context, cancel context.CancelFunc) int {
@@ -363,7 +350,6 @@ func (r *Runner) SetupLogger(ctx context.Context) error {
363350
}
364351

365352
func (r *Runner) StopServer(ctx context.Context) {
366-
r.tunnelCancel()
367353
shutCtx, cancelShut := context.WithTimeout(context.Background(), time.Second*15)
368354
defer cancelShut()
369355
log.TrWarnf("warn.server.closing")
@@ -373,6 +359,7 @@ func (r *Runner) StopServer(ctx context.Context) {
373359
defer cancelShut()
374360
var wg sync.WaitGroup
375361
for _, cr := range r.clusters {
362+
wg.Add(1)
376363
go func() {
377364
defer wg.Done()
378365
cr.Disable(shutCtx)
@@ -381,6 +368,9 @@ func (r *Runner) StopServer(ctx context.Context) {
381368
wg.Wait()
382369
log.TrWarnf("warn.httpserver.closing")
383370
r.server.Shutdown(shutCtx)
371+
if r.tunnelCancel != nil {
372+
r.tunnelCancel()
373+
}
384374
r.listener.Close()
385375
r.listener = nil
386376
}()

utils/error.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ func NewHTTPStatusErrorFromResponse(res *http.Response) (e *HTTPStatusError) {
3838
e.URL = res.Request.URL.String()
3939
}
4040
if res.Body != nil {
41-
var buf [512]byte
41+
var buf [1024]byte
4242
n, _ := res.Body.Read(buf[:])
4343
msg := (string)(buf[:n])
4444
for _, b := range msg {

utils/http.go

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ package utils
2222
import (
2323
"bufio"
2424
"bytes"
25+
"context"
2526
"crypto/tls"
2627
"errors"
2728
"io"
@@ -506,15 +507,16 @@ func (c *connHeadReader) Read(buf []byte) (n int, err error) {
506507
return c.Conn.Read(buf)
507508
}
508509

509-
func GetRedirects(req *http.Request) []*url.URL {
510+
func GetRedirects(resp *http.Response) []*url.URL {
510511
redirects := make([]*url.URL, 0, 5)
511-
for req != nil {
512-
redirects = append(redirects, req.URL)
513-
resp := req.Response
514-
if resp == nil {
515-
break
516-
}
512+
if u, _ := resp.Location(); u != nil {
513+
redirects = append(redirects, u)
514+
}
515+
var req *http.Request
516+
for resp != nil {
517517
req = resp.Request
518+
redirects = append(redirects, req.URL)
519+
resp = req.Response
518520
}
519521
if len(redirects) == 0 {
520522
return nil
@@ -531,7 +533,7 @@ type RedirectError struct {
531533

532534
func ErrorFromRedirect(err error, resp *http.Response) *RedirectError {
533535
return &RedirectError{
534-
Redirects: GetRedirects(resp.Request),
536+
Redirects: GetRedirects(resp),
535537
Response: resp,
536538
Err: err,
537539
}

0 commit comments

Comments
 (0)