process.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. package xray
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "runtime"
  11. "sort"
  12. "strings"
  13. "sync"
  14. "sync/atomic"
  15. "syscall"
  16. "time"
  17. "github.com/mhsanaei/3x-ui/v3/internal/config"
  18. "github.com/mhsanaei/3x-ui/v3/internal/logger"
  19. "github.com/mhsanaei/3x-ui/v3/internal/util/common"
  20. )
  21. // GetBinaryName returns the Xray binary filename for the current OS and architecture.
  22. func GetBinaryName() string {
  23. arch := runtime.GOARCH
  24. if arch == "arm" {
  25. arch = "arm32"
  26. }
  27. return fmt.Sprintf("xray-%s-%s", runtime.GOOS, arch)
  28. }
  29. // GetBinaryPath returns the full path to the Xray binary executable.
  30. func GetBinaryPath() string {
  31. return config.GetBinFolderPath() + "/" + GetBinaryName()
  32. }
  33. // GetConfigPath returns the path to the Xray configuration file in the binary folder.
  34. func GetConfigPath() string {
  35. return config.GetBinFolderPath() + "/config.json"
  36. }
  37. // GetGeositePath returns the path to the geosite data file used by Xray.
  38. func GetGeositePath() string {
  39. return config.GetBinFolderPath() + "/geosite.dat"
  40. }
  41. // GetGeoipPath returns the path to the geoip data file used by Xray.
  42. func GetGeoipPath() string {
  43. return config.GetBinFolderPath() + "/geoip.dat"
  44. }
  45. // GetIPLimitLogPath returns the path to the IP limit log file.
  46. func GetIPLimitLogPath() string {
  47. return config.GetLogFolder() + "/3xipl.log"
  48. }
  49. // GetIPLimitBannedLogPath returns the path to the banned IP log file.
  50. func GetIPLimitBannedLogPath() string {
  51. return config.GetLogFolder() + "/3xipl-banned.log"
  52. }
  53. // GetIPLimitBannedPrevLogPath returns the path to the previous banned IP log file.
  54. func GetIPLimitBannedPrevLogPath() string {
  55. return config.GetLogFolder() + "/3xipl-banned.prev.log"
  56. }
  57. // GetAccessPersistentLogPath returns the path to the persistent access log file.
  58. func GetAccessPersistentLogPath() string {
  59. return config.GetLogFolder() + "/3xipl-ap.log"
  60. }
  61. // GetAccessPersistentPrevLogPath returns the path to the previous persistent access log file.
  62. func GetAccessPersistentPrevLogPath() string {
  63. return config.GetLogFolder() + "/3xipl-ap.prev.log"
  64. }
  65. // GetAccessLogPath reads the Xray config and returns the access log file path.
  66. func GetAccessLogPath() (string, error) {
  67. config, err := os.ReadFile(GetConfigPath())
  68. if err != nil {
  69. logger.Warningf("Failed to read configuration file: %s", err)
  70. return "", err
  71. }
  72. jsonConfig := map[string]any{}
  73. err = json.Unmarshal([]byte(config), &jsonConfig)
  74. if err != nil {
  75. logger.Warningf("Failed to parse JSON configuration: %s", err)
  76. return "", err
  77. }
  78. if jsonConfig["log"] != nil {
  79. jsonLog := jsonConfig["log"].(map[string]any)
  80. if jsonLog["access"] != nil {
  81. accessLogPath := jsonLog["access"].(string)
  82. return accessLogPath, nil
  83. }
  84. }
  85. return "", err
  86. }
  87. // stopProcess calls Stop on the given Process instance.
  88. func stopProcess(p *Process) {
  89. p.Stop()
  90. }
  91. // Process wraps an Xray process instance and provides management methods.
  92. type Process struct {
  93. *process
  94. }
  95. // NewProcess creates a new Xray process and sets up cleanup on garbage collection.
  96. func NewProcess(xrayConfig *Config) *Process {
  97. p := &Process{newProcess(xrayConfig)}
  98. runtime.SetFinalizer(p, stopProcess)
  99. return p
  100. }
  101. // NewTestProcess creates a new Xray process that uses a specific config file path.
  102. // Used for test runs (e.g. outbound test) so the main config.json is not overwritten.
  103. // The config file at configPath is removed when the process is stopped.
  104. func NewTestProcess(xrayConfig *Config, configPath string) *Process {
  105. p := &Process{newTestProcess(xrayConfig, configPath)}
  106. runtime.SetFinalizer(p, stopProcess)
  107. return p
  108. }
  109. type process struct {
  110. cmd *exec.Cmd
  111. done chan struct{}
  112. version string
  113. apiPort int
  114. // onlineClients is the set of emails active on THIS panel's own xray
  115. // within the online grace window. It is derived only from local xray
  116. // traffic polls (see RefreshLocalOnline) — never from remote-node
  117. // snapshots — so a client connected solely to a remote node is not
  118. // reported online on local inbounds.
  119. onlineClients []string
  120. // localActiveInbounds is the set of THIS panel's inbound tags that
  121. // carried traffic within the same grace window. Xray's user>>>email
  122. // stat aggregates across every inbound a client is attached to, so an
  123. // online email alone can't say which inbound it actually used. Pairing
  124. // it with the inbound>>>tag stat lets the per-inbound view drop a
  125. // multi-inbound client from inbounds that saw no traffic this window.
  126. localActiveInbounds []string
  127. // localLastOnline records, per email, the last time this panel's own
  128. // xray reported traffic for it. RefreshLocalOnline rebuilds
  129. // onlineClients from this map each tick, keeping the local online set
  130. // independent of the shared client_traffics.last_online column — that
  131. // column is bumped by remote-node syncs too and would otherwise leak
  132. // remote-only clients into the local set.
  133. localLastOnline map[string]int64
  134. // localInboundLastActive mirrors localLastOnline for inbound tags: the
  135. // last tick this panel's xray reported traffic through each tag.
  136. // Rebuilt into localActiveInbounds under the same grace window so the
  137. // two signals stay aligned — an email within grace always has the
  138. // inbound it used within grace too.
  139. localInboundLastActive map[string]int64
  140. // nodeOnlineTrees holds, per direct remote node (keyed by that node's
  141. // panel-local id), the GUID-keyed online-emails subtree that node
  142. // reported — its own clients under its panelGuid plus every descendant
  143. // under theirs. Keying the stored value by GUID (not node id) lets the
  144. // master attribute a deeply nested client to the node that physically
  145. // hosts it across a chain (#4983); the outer node-id key is only so a
  146. // failed probe can drop that whole branch's contribution. NodeTrafficSyncJob
  147. // populates entries per cron tick and clears them when a probe fails. The
  148. // mutex guards this map, onlineClients, and localLastOnline above so the
  149. // online getters never see a torn read.
  150. nodeOnlineTrees map[int]map[string][]string
  151. onlineMu sync.RWMutex
  152. // onlineAPISupport caches whether the running core implements the
  153. // online-stats RPCs (GetUsersStats). A new process is created on every
  154. // restart/version switch, so the flag resets to Unknown and is re-probed
  155. // lazily by the first caller.
  156. onlineAPISupport atomic.Int32
  157. config *Config
  158. configPath string // if set, use this path instead of GetConfigPath() and remove on Stop
  159. logWriter *LogWriter
  160. exitErr error
  161. startTime time.Time
  162. intentionalStop atomic.Bool
  163. }
  164. // OnlineAPISupport describes whether the running Xray core implements the
  165. // online-stats API (statsUserOnline + GetUsersStats).
  166. type OnlineAPISupport int32
  167. const (
  168. // OnlineAPIUnknown means support has not been probed yet for this process.
  169. OnlineAPIUnknown OnlineAPISupport = iota
  170. // OnlineAPISupported means the core answered the online-stats RPC.
  171. OnlineAPISupported
  172. // OnlineAPIUnsupported means the core returned Unimplemented (older binary).
  173. OnlineAPIUnsupported
  174. )
  175. // OnlineAPISupport returns the cached online-stats capability of this process.
  176. func (p *process) OnlineAPISupport() OnlineAPISupport {
  177. return OnlineAPISupport(p.onlineAPISupport.Load())
  178. }
  179. // SetOnlineAPISupport records the probed online-stats capability of this process.
  180. func (p *process) SetOnlineAPISupport(v OnlineAPISupport) {
  181. p.onlineAPISupport.Store(int32(v))
  182. }
  183. var (
  184. xrayGracefulStopTimeout = 5 * time.Second
  185. xrayForceStopTimeout = 2 * time.Second
  186. // OnCrash is called when xray crashes unexpectedly. Set from web layer.
  187. OnCrash func(err error)
  188. )
  189. // newProcess creates a new internal process struct for Xray.
  190. func newProcess(config *Config) *process {
  191. return &process{
  192. version: "Unknown",
  193. config: config,
  194. logWriter: NewLogWriter(),
  195. startTime: time.Now(),
  196. }
  197. }
  198. // newTestProcess creates a process that writes and runs with a specific config path.
  199. func newTestProcess(config *Config, configPath string) *process {
  200. p := newProcess(config)
  201. p.configPath = configPath
  202. return p
  203. }
  204. // IsRunning returns true if the Xray process is currently running.
  205. func (p *process) IsRunning() bool {
  206. if p.cmd == nil || p.cmd.Process == nil {
  207. return false
  208. }
  209. if p.done != nil {
  210. select {
  211. case <-p.done:
  212. return false
  213. default:
  214. }
  215. }
  216. if p.cmd.ProcessState == nil {
  217. return true
  218. }
  219. return false
  220. }
  221. // GetErr returns the last error encountered by the Xray process.
  222. func (p *process) GetErr() error {
  223. return p.exitErr
  224. }
  225. // GetResult returns the last log line or error from the Xray process.
  226. func (p *process) GetResult() string {
  227. if len(p.logWriter.lastLine) == 0 && p.exitErr != nil {
  228. return p.exitErr.Error()
  229. }
  230. return p.logWriter.lastLine
  231. }
  232. // GetVersion returns the version string of the Xray process.
  233. func (p *process) GetVersion() string {
  234. return p.version
  235. }
  236. // GetAPIPort returns the API port used by the Xray process.
  237. func (p *Process) GetAPIPort() int {
  238. return p.apiPort
  239. }
  240. // GetConfig returns the configuration used by the Xray process.
  241. func (p *Process) GetConfig() *Config {
  242. return p.config
  243. }
  244. // SetConfig replaces the stored configuration snapshot after the running
  245. // process has been reconciled with it through the gRPC API (hot apply), so
  246. // later change detection compares against what is actually running.
  247. func (p *Process) SetConfig(config *Config) {
  248. p.config = config
  249. }
  250. // GetOnlineClients returns the union of locally-online clients and
  251. // node-online clients from every registered remote panel. Dedupes by
  252. // email so a client connected to both a local and a node-managed inbound
  253. // surfaces once. Cheap allocation — typical online sets are small and
  254. // the union is recomputed on demand.
  255. func (p *Process) GetOnlineClients() []string {
  256. p.onlineMu.RLock()
  257. defer p.onlineMu.RUnlock()
  258. if len(p.nodeOnlineTrees) == 0 {
  259. // Hot path for single-panel deployments: avoid the map+dedupe
  260. // work entirely and return the local slice as-is.
  261. return p.onlineClients
  262. }
  263. seen := make(map[string]struct{}, len(p.onlineClients))
  264. out := make([]string, 0, len(p.onlineClients))
  265. add := func(emails []string) {
  266. for _, email := range emails {
  267. if _, dup := seen[email]; dup {
  268. continue
  269. }
  270. seen[email] = struct{}{}
  271. out = append(out, email)
  272. }
  273. }
  274. add(p.onlineClients)
  275. for _, tree := range p.nodeOnlineTrees {
  276. for _, emails := range tree {
  277. add(emails)
  278. }
  279. }
  280. return out
  281. }
  282. // GetLocalOnlineClients returns a copy of the emails online on THIS panel's own
  283. // xray within the grace window. The service layer keys these under the panel's
  284. // own GUID when assembling the per-node online view.
  285. func (p *Process) GetLocalOnlineClients() []string {
  286. p.onlineMu.RLock()
  287. defer p.onlineMu.RUnlock()
  288. if len(p.onlineClients) == 0 {
  289. return nil
  290. }
  291. out := make([]string, len(p.onlineClients))
  292. copy(out, p.onlineClients)
  293. return out
  294. }
  295. // GetMergedNodeTrees returns the union of every direct node's reported subtree,
  296. // keyed by the panelGuid of the node that physically hosts each client set.
  297. // Because each child already reports its descendants under their own GUIDs,
  298. // merging the direct children yields the whole tree at any depth (#4983), so a
  299. // client three hops down is attributed to its real node, not the intermediate
  300. // one. GUIDs are globally unique, but a set reported under the same GUID by more
  301. // than one path is deduped per key; empty sets are omitted.
  302. func (p *Process) GetMergedNodeTrees() map[string][]string {
  303. p.onlineMu.RLock()
  304. defer p.onlineMu.RUnlock()
  305. if len(p.nodeOnlineTrees) == 0 {
  306. return map[string][]string{}
  307. }
  308. out := make(map[string][]string)
  309. seen := make(map[string]map[string]struct{})
  310. for _, tree := range p.nodeOnlineTrees {
  311. for guid, emails := range tree {
  312. if guid == "" || len(emails) == 0 {
  313. continue
  314. }
  315. dedup := seen[guid]
  316. if dedup == nil {
  317. dedup = make(map[string]struct{}, len(emails))
  318. seen[guid] = dedup
  319. }
  320. for _, email := range emails {
  321. if _, ok := dedup[email]; ok {
  322. continue
  323. }
  324. dedup[email] = struct{}{}
  325. out[guid] = append(out[guid], email)
  326. }
  327. }
  328. }
  329. return out
  330. }
  331. // GetLocalActiveInbounds returns a copy of THIS panel's inbound tags that
  332. // carried traffic within the grace window. Only the local xray reports
  333. // per-inbound activity; remote-node snapshots don't carry it, so the service
  334. // layer keys these under the panel's own GUID and a node missing from the
  335. // active-inbounds map means "don't gate" (fall back to the email-only signal).
  336. func (p *Process) GetLocalActiveInbounds() []string {
  337. p.onlineMu.RLock()
  338. defer p.onlineMu.RUnlock()
  339. if len(p.localActiveInbounds) == 0 {
  340. return nil
  341. }
  342. out := make([]string, len(p.localActiveInbounds))
  343. copy(out, p.localActiveInbounds)
  344. return out
  345. }
  346. // RefreshLocalOnline records that each email in activeEmails and each tag in
  347. // activeInboundTags had local xray traffic at now, then rebuilds onlineClients
  348. // and localActiveInbounds from every entry seen within graceMs, pruning older
  349. // ones. Called by the local XrayTrafficJob after each xray gRPC stats poll.
  350. // Pass nil/empty slices to only prune — NodeTrafficSyncJob does this so a
  351. // stopped local xray's clients and inbounds still age out between local polls.
  352. func (p *Process) RefreshLocalOnline(activeEmails, activeInboundTags []string, now, graceMs int64) {
  353. p.onlineMu.Lock()
  354. defer p.onlineMu.Unlock()
  355. if p.localLastOnline == nil {
  356. p.localLastOnline = make(map[string]int64, len(activeEmails))
  357. }
  358. for _, email := range activeEmails {
  359. p.localLastOnline[email] = now
  360. }
  361. online := make([]string, 0, len(p.localLastOnline))
  362. for email, ts := range p.localLastOnline {
  363. if now-ts < graceMs {
  364. online = append(online, email)
  365. } else {
  366. delete(p.localLastOnline, email)
  367. }
  368. }
  369. p.onlineClients = online
  370. if p.localInboundLastActive == nil {
  371. p.localInboundLastActive = make(map[string]int64, len(activeInboundTags))
  372. }
  373. for _, tag := range activeInboundTags {
  374. p.localInboundLastActive[tag] = now
  375. }
  376. activeInbounds := make([]string, 0, len(p.localInboundLastActive))
  377. for tag, ts := range p.localInboundLastActive {
  378. if now-ts < graceMs {
  379. activeInbounds = append(activeInbounds, tag)
  380. } else {
  381. delete(p.localInboundLastActive, tag)
  382. }
  383. }
  384. p.localActiveInbounds = activeInbounds
  385. }
  386. // SetNodeOnlineTree records the GUID-keyed online subtree one direct remote
  387. // node reported (its own clients under its panelGuid plus every descendant
  388. // under theirs). Replaces any previous entry for that node — NodeTrafficSyncJob
  389. // always sends the full subtree per tick.
  390. func (p *Process) SetNodeOnlineTree(nodeID int, tree map[string][]string) {
  391. p.onlineMu.Lock()
  392. defer p.onlineMu.Unlock()
  393. if p.nodeOnlineTrees == nil {
  394. p.nodeOnlineTrees = map[int]map[string][]string{}
  395. }
  396. p.nodeOnlineTrees[nodeID] = tree
  397. }
  398. // ClearNodeOnlineClients drops a direct node's whole subtree contribution.
  399. // Called when a probe fails so a downed node — and everything behind it — doesn't
  400. // keep its clients listed as "online" until the next successful probe.
  401. func (p *Process) ClearNodeOnlineClients(nodeID int) {
  402. p.onlineMu.Lock()
  403. defer p.onlineMu.Unlock()
  404. delete(p.nodeOnlineTrees, nodeID)
  405. }
  406. // GetUptime returns the uptime of the Xray process in seconds.
  407. func (p *Process) GetUptime() uint64 {
  408. return uint64(time.Since(p.startTime).Seconds())
  409. }
  410. // refreshAPIPort updates the API port from the inbound configs.
  411. func (p *process) refreshAPIPort() {
  412. for _, inbound := range p.config.InboundConfigs {
  413. if inbound.Tag == "api" {
  414. p.apiPort = inbound.Port
  415. break
  416. }
  417. }
  418. }
  419. // refreshVersion updates the version string by running the Xray binary with -version.
  420. func (p *process) refreshVersion() {
  421. cmd := exec.Command(GetBinaryPath(), "-version")
  422. data, err := cmd.Output()
  423. if err != nil {
  424. p.version = "Unknown"
  425. } else {
  426. datas := bytes.Split(data, []byte(" "))
  427. if len(datas) <= 1 {
  428. p.version = "Unknown"
  429. } else {
  430. p.version = string(datas[1])
  431. }
  432. }
  433. }
  434. // Start launches the Xray process with the current configuration.
  435. func (p *process) Start() (err error) {
  436. if p.IsRunning() {
  437. return errors.New("xray is already running")
  438. }
  439. defer func() {
  440. if err != nil {
  441. logger.Error("Failure in running xray-core process: ", err)
  442. p.exitErr = err
  443. }
  444. }()
  445. data, err := json.MarshalIndent(p.config, "", " ")
  446. if err != nil {
  447. return common.NewErrorf("Failed to generate XRAY configuration files: %v", err)
  448. }
  449. err = os.MkdirAll(config.GetLogFolder(), 0o770)
  450. if err != nil {
  451. logger.Warningf("Failed to create log folder: %s", err)
  452. }
  453. configPath := GetConfigPath()
  454. if p.configPath != "" {
  455. configPath = p.configPath
  456. }
  457. err = os.WriteFile(configPath, data, 0644)
  458. if err != nil {
  459. return common.NewErrorf("Failed to write configuration file: %v", err)
  460. }
  461. cmd := exec.Command(GetBinaryPath(), "-c", configPath)
  462. cmd.Stdout = p.logWriter
  463. cmd.Stderr = p.logWriter
  464. err = p.startCommand(cmd)
  465. if err != nil {
  466. return err
  467. }
  468. p.refreshVersion()
  469. p.refreshAPIPort()
  470. return nil
  471. }
  472. func (p *process) startCommand(cmd *exec.Cmd) error {
  473. p.cmd = cmd
  474. p.done = make(chan struct{})
  475. p.exitErr = nil
  476. p.intentionalStop.Store(false)
  477. if err := cmd.Start(); err != nil {
  478. close(p.done)
  479. p.cmd = nil
  480. return err
  481. }
  482. attachChildLifetime(cmd)
  483. go p.waitForCommand(cmd)
  484. return nil
  485. }
  486. func (p *process) waitForCommand(cmd *exec.Cmd) {
  487. defer close(p.done)
  488. err := cmd.Wait()
  489. if err == nil || p.intentionalStop.Load() {
  490. return
  491. }
  492. // On Windows, killing the process results in "exit status 1" which isn't an error for us.
  493. if runtime.GOOS == "windows" {
  494. errStr := strings.ToLower(err.Error())
  495. if strings.Contains(errStr, "exit status 1") {
  496. p.exitErr = err
  497. return
  498. }
  499. }
  500. logger.Error("Failure in running xray-core:", err)
  501. p.exitErr = err
  502. if OnCrash != nil {
  503. OnCrash(err)
  504. }
  505. }
  506. // Stop terminates the running Xray process.
  507. func (p *process) Stop() error {
  508. if !p.IsRunning() {
  509. return errors.New("xray is not running")
  510. }
  511. p.intentionalStop.Store(true)
  512. // Remove temporary config file used for test runs so main config is never touched
  513. if p.configPath != "" {
  514. if p.configPath != GetConfigPath() {
  515. // Check if file exists before removing
  516. if _, err := os.Stat(p.configPath); err == nil {
  517. _ = os.Remove(p.configPath)
  518. }
  519. }
  520. }
  521. if runtime.GOOS == "windows" {
  522. if err := p.cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  523. return err
  524. }
  525. return p.waitForExit(xrayForceStopTimeout)
  526. }
  527. if err := p.cmd.Process.Signal(syscall.SIGTERM); err != nil {
  528. if errors.Is(err, os.ErrProcessDone) {
  529. return p.waitForExit(xrayForceStopTimeout)
  530. }
  531. return err
  532. }
  533. if err := p.waitForExit(xrayGracefulStopTimeout); err == nil {
  534. return nil
  535. }
  536. logger.Warning("xray-core did not stop after SIGTERM, killing process")
  537. if err := p.cmd.Process.Kill(); err != nil && !errors.Is(err, os.ErrProcessDone) {
  538. return err
  539. }
  540. return p.waitForExit(xrayForceStopTimeout)
  541. }
  542. func (p *process) waitForExit(timeout time.Duration) error {
  543. if p.done == nil {
  544. return nil
  545. }
  546. timer := time.NewTimer(timeout)
  547. defer timer.Stop()
  548. select {
  549. case <-p.done:
  550. return nil
  551. case <-timer.C:
  552. return common.NewErrorf("timed out waiting for xray-core process to stop after %s", timeout)
  553. }
  554. }
  555. const (
  556. crashReportPrefix = "core_crash_"
  557. crashReportSuffix = ".log"
  558. maxCrashReports = 10
  559. )
  560. // writeCrashReport persists a captured xray crash chunk to the log folder
  561. // with nanosecond-precision filename so restart-loop bursts don't overwrite
  562. // each other, and prunes old reports to keep the folder bounded.
  563. func writeCrashReport(m []byte) error {
  564. dir := config.GetLogFolder()
  565. if err := os.MkdirAll(dir, 0o770); err != nil {
  566. return err
  567. }
  568. pruneOldCrashReports(dir, maxCrashReports-1)
  569. name := crashReportPrefix + time.Now().Format("20060102_150405_000000000") + crashReportSuffix
  570. return os.WriteFile(filepath.Join(dir, name), m, 0o640)
  571. }
  572. func pruneOldCrashReports(dir string, keep int) {
  573. entries, err := os.ReadDir(dir)
  574. if err != nil {
  575. return
  576. }
  577. var reports []string
  578. for _, e := range entries {
  579. n := e.Name()
  580. if !e.IsDir() && strings.HasPrefix(n, crashReportPrefix) && strings.HasSuffix(n, crashReportSuffix) {
  581. reports = append(reports, n)
  582. }
  583. }
  584. if len(reports) <= keep {
  585. return
  586. }
  587. sort.Strings(reports)
  588. for _, old := range reports[:len(reports)-keep] {
  589. _ = os.Remove(filepath.Join(dir, old))
  590. }
  591. }