model.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package model
  16. import (
  17. "bufio"
  18. "crypto/tls"
  19. "errors"
  20. "fmt"
  21. "io"
  22. "io/ioutil"
  23. "net"
  24. "os"
  25. "path/filepath"
  26. "strconv"
  27. "strings"
  28. "sync"
  29. "time"
  30. "github.com/syncthing/syncthing/internal/config"
  31. "github.com/syncthing/syncthing/internal/events"
  32. "github.com/syncthing/syncthing/internal/files"
  33. "github.com/syncthing/syncthing/internal/ignore"
  34. "github.com/syncthing/syncthing/internal/lamport"
  35. "github.com/syncthing/syncthing/internal/osutil"
  36. "github.com/syncthing/syncthing/internal/protocol"
  37. "github.com/syncthing/syncthing/internal/scanner"
  38. "github.com/syncthing/syncthing/internal/stats"
  39. "github.com/syncthing/syncthing/internal/versioner"
  40. "github.com/syndtr/goleveldb/leveldb"
  41. )
  42. type folderState int
  43. const (
  44. FolderIdle folderState = iota
  45. FolderScanning
  46. FolderSyncing
  47. FolderCleaning
  48. )
  49. func (s folderState) String() string {
  50. switch s {
  51. case FolderIdle:
  52. return "idle"
  53. case FolderScanning:
  54. return "scanning"
  55. case FolderCleaning:
  56. return "cleaning"
  57. case FolderSyncing:
  58. return "syncing"
  59. default:
  60. return "unknown"
  61. }
  62. }
  63. // How many files to send in each Index/IndexUpdate message.
  64. const (
  65. indexTargetSize = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed)
  66. indexPerFileSize = 250 // Each FileInfo is approximately this big, in bytes, excluding BlockInfos
  67. IndexPerBlockSize = 40 // Each BlockInfo is approximately this big
  68. indexBatchSize = 1000 // Either way, don't include more files than this
  69. )
  70. type service interface {
  71. Serve()
  72. Stop()
  73. }
  74. type Model struct {
  75. cfg *config.ConfigWrapper
  76. db *leveldb.DB
  77. finder *files.BlockFinder
  78. deviceName string
  79. clientName string
  80. clientVersion string
  81. folderCfgs map[string]config.FolderConfiguration // folder -> cfg
  82. folderFiles map[string]*files.Set // folder -> files
  83. folderDevices map[string][]protocol.DeviceID // folder -> deviceIDs
  84. deviceFolders map[protocol.DeviceID][]string // deviceID -> folders
  85. deviceStatRefs map[protocol.DeviceID]*stats.DeviceStatisticsReference // deviceID -> statsRef
  86. folderIgnores map[string]*ignore.Matcher // folder -> matcher object
  87. folderRunners map[string]service // folder -> puller or scanner
  88. fmut sync.RWMutex // protects the above
  89. folderState map[string]folderState // folder -> state
  90. folderStateChanged map[string]time.Time // folder -> time when state changed
  91. smut sync.RWMutex
  92. protoConn map[protocol.DeviceID]protocol.Connection
  93. rawConn map[protocol.DeviceID]io.Closer
  94. deviceVer map[protocol.DeviceID]string
  95. pmut sync.RWMutex // protects protoConn and rawConn
  96. addedFolder bool
  97. started bool
  98. }
  99. var (
  100. ErrNoSuchFile = errors.New("no such file")
  101. ErrInvalid = errors.New("file is invalid")
  102. )
  103. // NewModel creates and starts a new model. The model starts in read-only mode,
  104. // where it sends index information to connected peers and responds to requests
  105. // for file data without altering the local folder in any way.
  106. func NewModel(cfg *config.ConfigWrapper, deviceName, clientName, clientVersion string, db *leveldb.DB) *Model {
  107. m := &Model{
  108. cfg: cfg,
  109. db: db,
  110. deviceName: deviceName,
  111. clientName: clientName,
  112. clientVersion: clientVersion,
  113. folderCfgs: make(map[string]config.FolderConfiguration),
  114. folderFiles: make(map[string]*files.Set),
  115. folderDevices: make(map[string][]protocol.DeviceID),
  116. deviceFolders: make(map[protocol.DeviceID][]string),
  117. deviceStatRefs: make(map[protocol.DeviceID]*stats.DeviceStatisticsReference),
  118. folderIgnores: make(map[string]*ignore.Matcher),
  119. folderRunners: make(map[string]service),
  120. folderState: make(map[string]folderState),
  121. folderStateChanged: make(map[string]time.Time),
  122. protoConn: make(map[protocol.DeviceID]protocol.Connection),
  123. rawConn: make(map[protocol.DeviceID]io.Closer),
  124. deviceVer: make(map[protocol.DeviceID]string),
  125. finder: files.NewBlockFinder(db, cfg),
  126. }
  127. var timeout = 20 * 60 // seconds
  128. if t := os.Getenv("STDEADLOCKTIMEOUT"); len(t) > 0 {
  129. it, err := strconv.Atoi(t)
  130. if err == nil {
  131. timeout = it
  132. }
  133. }
  134. deadlockDetect(&m.fmut, time.Duration(timeout)*time.Second)
  135. deadlockDetect(&m.smut, time.Duration(timeout)*time.Second)
  136. deadlockDetect(&m.pmut, time.Duration(timeout)*time.Second)
  137. return m
  138. }
  139. // StartRW starts read/write processing on the current model. When in
  140. // read/write mode the model will attempt to keep in sync with the cluster by
  141. // pulling needed files from peer devices.
  142. func (m *Model) StartFolderRW(folder string) {
  143. m.fmut.Lock()
  144. cfg, ok := m.folderCfgs[folder]
  145. if !ok {
  146. panic("cannot start nonexistent folder " + folder)
  147. }
  148. _, ok = m.folderRunners[folder]
  149. if ok {
  150. panic("cannot start already running folder " + folder)
  151. }
  152. p := &Puller{
  153. folder: folder,
  154. dir: cfg.Path,
  155. scanIntv: time.Duration(cfg.RescanIntervalS) * time.Second,
  156. model: m,
  157. ignorePerms: cfg.IgnorePerms,
  158. lenientMtimes: cfg.LenientMtimes,
  159. }
  160. m.folderRunners[folder] = p
  161. m.fmut.Unlock()
  162. if len(cfg.Versioning.Type) > 0 {
  163. factory, ok := versioner.Factories[cfg.Versioning.Type]
  164. if !ok {
  165. l.Fatalf("Requested versioning type %q that does not exist", cfg.Versioning.Type)
  166. }
  167. p.versioner = factory(folder, cfg.Path, cfg.Versioning.Params)
  168. }
  169. if cfg.LenientMtimes {
  170. l.Infof("Folder %q is running with LenientMtimes workaround. Syncing may not work properly.", folder)
  171. }
  172. go p.Serve()
  173. }
  174. // StartRO starts read only processing on the current model. When in
  175. // read only mode the model will announce files to the cluster but not
  176. // pull in any external changes.
  177. func (m *Model) StartFolderRO(folder string) {
  178. m.fmut.Lock()
  179. cfg, ok := m.folderCfgs[folder]
  180. if !ok {
  181. panic("cannot start nonexistent folder " + folder)
  182. }
  183. _, ok = m.folderRunners[folder]
  184. if ok {
  185. panic("cannot start already running folder " + folder)
  186. }
  187. s := &Scanner{
  188. folder: folder,
  189. intv: time.Duration(cfg.RescanIntervalS) * time.Second,
  190. model: m,
  191. }
  192. m.folderRunners[folder] = s
  193. m.fmut.Unlock()
  194. go s.Serve()
  195. }
  196. type ConnectionInfo struct {
  197. protocol.Statistics
  198. Address string
  199. ClientVersion string
  200. }
  201. // ConnectionStats returns a map with connection statistics for each connected device.
  202. func (m *Model) ConnectionStats() map[string]ConnectionInfo {
  203. type remoteAddrer interface {
  204. RemoteAddr() net.Addr
  205. }
  206. m.pmut.RLock()
  207. m.fmut.RLock()
  208. var res = make(map[string]ConnectionInfo)
  209. for device, conn := range m.protoConn {
  210. ci := ConnectionInfo{
  211. Statistics: conn.Statistics(),
  212. ClientVersion: m.deviceVer[device],
  213. }
  214. if nc, ok := m.rawConn[device].(remoteAddrer); ok {
  215. ci.Address = nc.RemoteAddr().String()
  216. }
  217. res[device.String()] = ci
  218. }
  219. m.fmut.RUnlock()
  220. m.pmut.RUnlock()
  221. in, out := protocol.TotalInOut()
  222. res["total"] = ConnectionInfo{
  223. Statistics: protocol.Statistics{
  224. At: time.Now(),
  225. InBytesTotal: in,
  226. OutBytesTotal: out,
  227. },
  228. }
  229. return res
  230. }
  231. // Returns statistics about each device
  232. func (m *Model) DeviceStatistics() map[string]stats.DeviceStatistics {
  233. var res = make(map[string]stats.DeviceStatistics)
  234. for id := range m.cfg.Devices() {
  235. res[id.String()] = m.deviceStatRef(id).GetStatistics()
  236. }
  237. return res
  238. }
  239. // Returns the completion status, in percent, for the given device and folder.
  240. func (m *Model) Completion(device protocol.DeviceID, folder string) float64 {
  241. defer m.leveldbPanicWorkaround()
  242. var tot int64
  243. m.fmut.RLock()
  244. rf, ok := m.folderFiles[folder]
  245. m.fmut.RUnlock()
  246. if !ok {
  247. return 0 // Folder doesn't exist, so we hardly have any of it
  248. }
  249. rf.WithGlobalTruncated(func(f protocol.FileIntf) bool {
  250. if !f.IsDeleted() {
  251. tot += f.Size()
  252. }
  253. return true
  254. })
  255. if tot == 0 {
  256. return 100 // Folder is empty, so we have all of it
  257. }
  258. var need int64
  259. rf.WithNeedTruncated(device, func(f protocol.FileIntf) bool {
  260. if !f.IsDeleted() {
  261. need += f.Size()
  262. }
  263. return true
  264. })
  265. res := 100 * (1 - float64(need)/float64(tot))
  266. if debug {
  267. l.Debugf("%v Completion(%s, %q): %f (%d / %d)", m, device, folder, res, need, tot)
  268. }
  269. return res
  270. }
  271. func sizeOf(fs []protocol.FileInfo) (files, deleted int, bytes int64) {
  272. for _, f := range fs {
  273. fs, de, by := sizeOfFile(f)
  274. files += fs
  275. deleted += de
  276. bytes += by
  277. }
  278. return
  279. }
  280. func sizeOfFile(f protocol.FileIntf) (files, deleted int, bytes int64) {
  281. if !f.IsDeleted() {
  282. files++
  283. } else {
  284. deleted++
  285. }
  286. bytes += f.Size()
  287. return
  288. }
  289. // GlobalSize returns the number of files, deleted files and total bytes for all
  290. // files in the global model.
  291. func (m *Model) GlobalSize(folder string) (files, deleted int, bytes int64) {
  292. defer m.leveldbPanicWorkaround()
  293. m.fmut.RLock()
  294. defer m.fmut.RUnlock()
  295. if rf, ok := m.folderFiles[folder]; ok {
  296. rf.WithGlobalTruncated(func(f protocol.FileIntf) bool {
  297. fs, de, by := sizeOfFile(f)
  298. files += fs
  299. deleted += de
  300. bytes += by
  301. return true
  302. })
  303. }
  304. return
  305. }
  306. // LocalSize returns the number of files, deleted files and total bytes for all
  307. // files in the local folder.
  308. func (m *Model) LocalSize(folder string) (files, deleted int, bytes int64) {
  309. defer m.leveldbPanicWorkaround()
  310. m.fmut.RLock()
  311. defer m.fmut.RUnlock()
  312. if rf, ok := m.folderFiles[folder]; ok {
  313. rf.WithHaveTruncated(protocol.LocalDeviceID, func(f protocol.FileIntf) bool {
  314. if f.IsInvalid() {
  315. return true
  316. }
  317. fs, de, by := sizeOfFile(f)
  318. files += fs
  319. deleted += de
  320. bytes += by
  321. return true
  322. })
  323. }
  324. return
  325. }
  326. // NeedSize returns the number and total size of currently needed files.
  327. func (m *Model) NeedSize(folder string) (files int, bytes int64) {
  328. defer m.leveldbPanicWorkaround()
  329. m.fmut.RLock()
  330. defer m.fmut.RUnlock()
  331. if rf, ok := m.folderFiles[folder]; ok {
  332. rf.WithNeedTruncated(protocol.LocalDeviceID, func(f protocol.FileIntf) bool {
  333. fs, de, by := sizeOfFile(f)
  334. files += fs + de
  335. bytes += by
  336. return true
  337. })
  338. }
  339. if debug {
  340. l.Debugf("%v NeedSize(%q): %d %d", m, folder, files, bytes)
  341. }
  342. return
  343. }
  344. // NeedFiles returns the list of currently needed files, stopping at maxFiles
  345. // files or maxBlocks blocks. Limits <= 0 are ignored.
  346. func (m *Model) NeedFolderFilesLimited(folder string, maxFiles, maxBlocks int) []protocol.FileInfo {
  347. defer m.leveldbPanicWorkaround()
  348. m.fmut.RLock()
  349. defer m.fmut.RUnlock()
  350. nblocks := 0
  351. if rf, ok := m.folderFiles[folder]; ok {
  352. fs := make([]protocol.FileInfo, 0, maxFiles)
  353. rf.WithNeed(protocol.LocalDeviceID, func(f protocol.FileIntf) bool {
  354. fi := f.(protocol.FileInfo)
  355. fs = append(fs, fi)
  356. nblocks += len(fi.Blocks)
  357. return (maxFiles <= 0 || len(fs) < maxFiles) && (maxBlocks <= 0 || nblocks < maxBlocks)
  358. })
  359. return fs
  360. }
  361. return nil
  362. }
  363. // Index is called when a new device is connected and we receive their full index.
  364. // Implements the protocol.Model interface.
  365. func (m *Model) Index(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  366. if debug {
  367. l.Debugf("IDX(in): %s %q: %d files", deviceID, folder, len(fs))
  368. }
  369. if !m.folderSharedWith(folder, deviceID) {
  370. events.Default.Log(events.FolderRejected, map[string]string{
  371. "folder": folder,
  372. "device": deviceID.String(),
  373. })
  374. l.Warnf("Unexpected folder ID %q sent from device %q; ensure that the folder exists and that this device is selected under \"Share With\" in the folder configuration.", folder, deviceID)
  375. return
  376. }
  377. m.fmut.RLock()
  378. files, ok := m.folderFiles[folder]
  379. ignores, _ := m.folderIgnores[folder]
  380. m.fmut.RUnlock()
  381. if !ok {
  382. l.Fatalf("Index for nonexistant folder %q", folder)
  383. }
  384. for i := 0; i < len(fs); {
  385. lamport.Default.Tick(fs[i].Version)
  386. if ignores != nil && ignores.Match(fs[i].Name) {
  387. if debug {
  388. l.Debugln("dropping update for ignored", fs[i])
  389. }
  390. fs[i] = fs[len(fs)-1]
  391. fs = fs[:len(fs)-1]
  392. } else {
  393. i++
  394. }
  395. }
  396. files.Replace(deviceID, fs)
  397. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  398. "device": deviceID.String(),
  399. "folder": folder,
  400. "items": len(fs),
  401. "version": files.LocalVersion(deviceID),
  402. })
  403. }
  404. // IndexUpdate is called for incremental updates to connected devices' indexes.
  405. // Implements the protocol.Model interface.
  406. func (m *Model) IndexUpdate(deviceID protocol.DeviceID, folder string, fs []protocol.FileInfo) {
  407. if debug {
  408. l.Debugf("%v IDXUP(in): %s / %q: %d files", m, deviceID, folder, len(fs))
  409. }
  410. if !m.folderSharedWith(folder, deviceID) {
  411. l.Infof("Update for unexpected folder ID %q sent from device %q; ensure that the folder exists and that this device is selected under \"Share With\" in the folder configuration.", folder, deviceID)
  412. return
  413. }
  414. m.fmut.RLock()
  415. files, ok := m.folderFiles[folder]
  416. ignores, _ := m.folderIgnores[folder]
  417. m.fmut.RUnlock()
  418. if !ok {
  419. l.Fatalf("IndexUpdate for nonexistant folder %q", folder)
  420. }
  421. for i := 0; i < len(fs); {
  422. lamport.Default.Tick(fs[i].Version)
  423. if ignores != nil && ignores.Match(fs[i].Name) {
  424. if debug {
  425. l.Debugln("dropping update for ignored", fs[i])
  426. }
  427. fs[i] = fs[len(fs)-1]
  428. fs = fs[:len(fs)-1]
  429. } else {
  430. i++
  431. }
  432. }
  433. files.Update(deviceID, fs)
  434. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  435. "device": deviceID.String(),
  436. "folder": folder,
  437. "items": len(fs),
  438. "version": files.LocalVersion(deviceID),
  439. })
  440. }
  441. func (m *Model) folderSharedWith(folder string, deviceID protocol.DeviceID) bool {
  442. m.fmut.RLock()
  443. defer m.fmut.RUnlock()
  444. for _, nfolder := range m.deviceFolders[deviceID] {
  445. if nfolder == folder {
  446. return true
  447. }
  448. }
  449. return false
  450. }
  451. func (m *Model) ClusterConfig(deviceID protocol.DeviceID, cm protocol.ClusterConfigMessage) {
  452. m.pmut.Lock()
  453. if cm.ClientName == "syncthing" {
  454. m.deviceVer[deviceID] = cm.ClientVersion
  455. } else {
  456. m.deviceVer[deviceID] = cm.ClientName + " " + cm.ClientVersion
  457. }
  458. m.pmut.Unlock()
  459. l.Infof(`Device %s client is "%s %s"`, deviceID, cm.ClientName, cm.ClientVersion)
  460. if name := cm.GetOption("name"); name != "" {
  461. l.Infof("Device %s name is %q", deviceID, name)
  462. device, ok := m.cfg.Devices()[deviceID]
  463. if ok && device.Name == "" {
  464. device.Name = name
  465. m.cfg.SetDevice(device)
  466. }
  467. }
  468. if m.cfg.Devices()[deviceID].Introducer {
  469. // This device is an introducer. Go through the announced lists of folders
  470. // and devices and add what we are missing.
  471. var changed bool
  472. for _, folder := range cm.Folders {
  473. // If we don't have this folder yet, skip it. Ideally, we'd
  474. // offer up something in the GUI to create the folder, but for the
  475. // moment we only handle folders that we already have.
  476. if _, ok := m.folderDevices[folder.ID]; !ok {
  477. continue
  478. }
  479. nextDevice:
  480. for _, device := range folder.Devices {
  481. var id protocol.DeviceID
  482. copy(id[:], device.ID)
  483. if _, ok := m.cfg.Devices()[id]; !ok {
  484. // The device is currently unknown. Add it to the config.
  485. l.Infof("Adding device %v to config (vouched for by introducer %v)", id, deviceID)
  486. newDeviceCfg := config.DeviceConfiguration{
  487. DeviceID: id,
  488. Compression: true,
  489. Addresses: []string{"dynamic"},
  490. }
  491. // The introducers' introducers are also our introducers.
  492. if device.Flags&protocol.FlagIntroducer != 0 {
  493. l.Infof("Device %v is now also an introducer", id)
  494. newDeviceCfg.Introducer = true
  495. }
  496. m.cfg.SetDevice(newDeviceCfg)
  497. changed = true
  498. }
  499. for _, er := range m.deviceFolders[id] {
  500. if er == folder.ID {
  501. // We already share the folder with this device, so
  502. // nothing to do.
  503. continue nextDevice
  504. }
  505. }
  506. // We don't yet share this folder with this device. Add the device
  507. // to sharing list of the folder.
  508. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  509. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  510. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  511. folderCfg := m.cfg.Folders()[folder.ID]
  512. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  513. DeviceID: id,
  514. })
  515. m.cfg.SetFolder(folderCfg)
  516. changed = true
  517. }
  518. }
  519. if changed {
  520. m.cfg.Save()
  521. }
  522. }
  523. }
  524. // Close removes the peer from the model and closes the underlying connection if possible.
  525. // Implements the protocol.Model interface.
  526. func (m *Model) Close(device protocol.DeviceID, err error) {
  527. l.Infof("Connection to %s closed: %v", device, err)
  528. events.Default.Log(events.DeviceDisconnected, map[string]string{
  529. "id": device.String(),
  530. "error": err.Error(),
  531. })
  532. m.pmut.Lock()
  533. m.fmut.RLock()
  534. for _, folder := range m.deviceFolders[device] {
  535. m.folderFiles[folder].Replace(device, nil)
  536. }
  537. m.fmut.RUnlock()
  538. conn, ok := m.rawConn[device]
  539. if ok {
  540. if conn, ok := conn.(*tls.Conn); ok {
  541. // If the underlying connection is a *tls.Conn, Close() does more
  542. // than it says on the tin. Specifically, it sends a TLS alert
  543. // message, which might block forever if the connection is dead
  544. // and we don't have a deadline site.
  545. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  546. }
  547. conn.Close()
  548. }
  549. delete(m.protoConn, device)
  550. delete(m.rawConn, device)
  551. delete(m.deviceVer, device)
  552. m.pmut.Unlock()
  553. }
  554. // Request returns the specified data segment by reading it from local disk.
  555. // Implements the protocol.Model interface.
  556. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, size int) ([]byte, error) {
  557. // Verify that the requested file exists in the local model.
  558. m.fmut.RLock()
  559. r, ok := m.folderFiles[folder]
  560. m.fmut.RUnlock()
  561. if !ok {
  562. l.Warnf("Request from %s for file %s in nonexistent folder %q", deviceID, name, folder)
  563. return nil, ErrNoSuchFile
  564. }
  565. lf := r.Get(protocol.LocalDeviceID, name)
  566. if protocol.IsInvalid(lf.Flags) || protocol.IsDeleted(lf.Flags) {
  567. if debug {
  568. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d; invalid: %v", m, deviceID, folder, name, offset, size, lf)
  569. }
  570. return nil, ErrInvalid
  571. }
  572. if offset > lf.Size() {
  573. if debug {
  574. l.Debugf("%v REQ(in; nonexistent): %s: %q o=%d s=%d", m, deviceID, name, offset, size)
  575. }
  576. return nil, ErrNoSuchFile
  577. }
  578. if debug && deviceID != protocol.LocalDeviceID {
  579. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size)
  580. }
  581. m.fmut.RLock()
  582. fn := filepath.Join(m.folderCfgs[folder].Path, name)
  583. m.fmut.RUnlock()
  584. fd, err := os.Open(fn) // XXX: Inefficient, should cache fd?
  585. if err != nil {
  586. return nil, err
  587. }
  588. defer fd.Close()
  589. buf := make([]byte, size)
  590. _, err = fd.ReadAt(buf, offset)
  591. if err != nil {
  592. return nil, err
  593. }
  594. return buf, nil
  595. }
  596. // ReplaceLocal replaces the local folder index with the given list of files.
  597. func (m *Model) ReplaceLocal(folder string, fs []protocol.FileInfo) {
  598. m.fmut.RLock()
  599. m.folderFiles[folder].ReplaceWithDelete(protocol.LocalDeviceID, fs)
  600. m.fmut.RUnlock()
  601. }
  602. func (m *Model) CurrentFolderFile(folder string, file string) protocol.FileInfo {
  603. m.fmut.RLock()
  604. f := m.folderFiles[folder].Get(protocol.LocalDeviceID, file)
  605. m.fmut.RUnlock()
  606. return f
  607. }
  608. func (m *Model) CurrentGlobalFile(folder string, file string) protocol.FileInfo {
  609. m.fmut.RLock()
  610. f := m.folderFiles[folder].GetGlobal(file)
  611. m.fmut.RUnlock()
  612. return f
  613. }
  614. type cFiler struct {
  615. m *Model
  616. r string
  617. }
  618. // Implements scanner.CurrentFiler
  619. func (cf cFiler) CurrentFile(file string) protocol.FileInfo {
  620. return cf.m.CurrentFolderFile(cf.r, file)
  621. }
  622. // ConnectedTo returns true if we are connected to the named device.
  623. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool {
  624. m.pmut.RLock()
  625. _, ok := m.protoConn[deviceID]
  626. m.pmut.RUnlock()
  627. if ok {
  628. m.deviceWasSeen(deviceID)
  629. }
  630. return ok
  631. }
  632. func (m *Model) GetIgnores(folder string) ([]string, error) {
  633. var lines []string
  634. cfg, ok := m.folderCfgs[folder]
  635. if !ok {
  636. return lines, fmt.Errorf("Folder %s does not exist", folder)
  637. }
  638. m.fmut.Lock()
  639. defer m.fmut.Unlock()
  640. fd, err := os.Open(filepath.Join(cfg.Path, ".stignore"))
  641. if err != nil {
  642. if os.IsNotExist(err) {
  643. return lines, nil
  644. }
  645. l.Warnln("Loading .stignore:", err)
  646. return lines, err
  647. }
  648. defer fd.Close()
  649. scanner := bufio.NewScanner(fd)
  650. for scanner.Scan() {
  651. lines = append(lines, strings.TrimSpace(scanner.Text()))
  652. }
  653. return lines, nil
  654. }
  655. func (m *Model) SetIgnores(folder string, content []string) error {
  656. cfg, ok := m.folderCfgs[folder]
  657. if !ok {
  658. return fmt.Errorf("Folder %s does not exist", folder)
  659. }
  660. fd, err := ioutil.TempFile(cfg.Path, ".syncthing.stignore-"+folder)
  661. if err != nil {
  662. l.Warnln("Saving .stignore:", err)
  663. return err
  664. }
  665. defer os.Remove(fd.Name())
  666. for _, line := range content {
  667. _, err = fmt.Fprintln(fd, line)
  668. if err != nil {
  669. l.Warnln("Saving .stignore:", err)
  670. return err
  671. }
  672. }
  673. err = fd.Close()
  674. if err != nil {
  675. l.Warnln("Saving .stignore:", err)
  676. return err
  677. }
  678. file := filepath.Join(cfg.Path, ".stignore")
  679. err = osutil.Rename(fd.Name(), file)
  680. if err != nil {
  681. l.Warnln("Saving .stignore:", err)
  682. return err
  683. }
  684. return m.ScanFolder(folder)
  685. }
  686. // AddConnection adds a new peer connection to the model. An initial index will
  687. // be sent to the connected peer, thereafter index updates whenever the local
  688. // folder changes.
  689. func (m *Model) AddConnection(rawConn io.Closer, protoConn protocol.Connection) {
  690. deviceID := protoConn.ID()
  691. m.pmut.Lock()
  692. if _, ok := m.protoConn[deviceID]; ok {
  693. panic("add existing device")
  694. }
  695. m.protoConn[deviceID] = protoConn
  696. if _, ok := m.rawConn[deviceID]; ok {
  697. panic("add existing device")
  698. }
  699. m.rawConn[deviceID] = rawConn
  700. cm := m.clusterConfig(deviceID)
  701. protoConn.ClusterConfig(cm)
  702. m.fmut.RLock()
  703. for _, folder := range m.deviceFolders[deviceID] {
  704. fs := m.folderFiles[folder]
  705. go sendIndexes(protoConn, folder, fs, m.folderIgnores[folder])
  706. }
  707. m.fmut.RUnlock()
  708. m.pmut.Unlock()
  709. m.deviceWasSeen(deviceID)
  710. }
  711. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  712. m.fmut.Lock()
  713. defer m.fmut.Unlock()
  714. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  715. return sr
  716. } else {
  717. sr = stats.NewDeviceStatisticsReference(m.db, deviceID)
  718. m.deviceStatRefs[deviceID] = sr
  719. return sr
  720. }
  721. }
  722. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  723. m.deviceStatRef(deviceID).WasSeen()
  724. }
  725. func sendIndexes(conn protocol.Connection, folder string, fs *files.Set, ignores *ignore.Matcher) {
  726. deviceID := conn.ID()
  727. name := conn.Name()
  728. var err error
  729. if debug {
  730. l.Debugf("sendIndexes for %s-%s/%q starting", deviceID, name, folder)
  731. }
  732. minLocalVer, err := sendIndexTo(true, 0, conn, folder, fs, ignores)
  733. for err == nil {
  734. time.Sleep(5 * time.Second)
  735. if fs.LocalVersion(protocol.LocalDeviceID) <= minLocalVer {
  736. continue
  737. }
  738. minLocalVer, err = sendIndexTo(false, minLocalVer, conn, folder, fs, ignores)
  739. }
  740. if debug {
  741. l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err)
  742. }
  743. }
  744. func sendIndexTo(initial bool, minLocalVer uint64, conn protocol.Connection, folder string, fs *files.Set, ignores *ignore.Matcher) (uint64, error) {
  745. deviceID := conn.ID()
  746. name := conn.Name()
  747. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  748. currentBatchSize := 0
  749. maxLocalVer := uint64(0)
  750. var err error
  751. fs.WithHave(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool {
  752. f := fi.(protocol.FileInfo)
  753. if f.LocalVersion <= minLocalVer {
  754. return true
  755. }
  756. if f.LocalVersion > maxLocalVer {
  757. maxLocalVer = f.LocalVersion
  758. }
  759. if ignores != nil && ignores.Match(f.Name) {
  760. if debug {
  761. l.Debugln("not sending update for ignored", f)
  762. }
  763. return true
  764. }
  765. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  766. if initial {
  767. if err = conn.Index(folder, batch); err != nil {
  768. return false
  769. }
  770. if debug {
  771. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  772. }
  773. initial = false
  774. } else {
  775. if err = conn.IndexUpdate(folder, batch); err != nil {
  776. return false
  777. }
  778. if debug {
  779. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  780. }
  781. }
  782. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  783. currentBatchSize = 0
  784. }
  785. batch = append(batch, f)
  786. currentBatchSize += indexPerFileSize + len(f.Blocks)*IndexPerBlockSize
  787. return true
  788. })
  789. if initial && err == nil {
  790. err = conn.Index(folder, batch)
  791. if debug && err == nil {
  792. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  793. }
  794. } else if len(batch) > 0 && err == nil {
  795. err = conn.IndexUpdate(folder, batch)
  796. if debug && err == nil {
  797. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  798. }
  799. }
  800. return maxLocalVer, err
  801. }
  802. func (m *Model) updateLocal(folder string, f protocol.FileInfo) {
  803. f.LocalVersion = 0
  804. m.fmut.RLock()
  805. m.folderFiles[folder].Update(protocol.LocalDeviceID, []protocol.FileInfo{f})
  806. m.fmut.RUnlock()
  807. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  808. "folder": folder,
  809. "name": f.Name,
  810. "modified": time.Unix(f.Modified, 0),
  811. "flags": fmt.Sprintf("0%o", f.Flags),
  812. "size": f.Size(),
  813. })
  814. }
  815. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte) ([]byte, error) {
  816. m.pmut.RLock()
  817. nc, ok := m.protoConn[deviceID]
  818. m.pmut.RUnlock()
  819. if !ok {
  820. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  821. }
  822. if debug {
  823. l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x", m, deviceID, folder, name, offset, size, hash)
  824. }
  825. return nc.Request(folder, name, offset, size)
  826. }
  827. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  828. if m.started {
  829. panic("cannot add folder to started model")
  830. }
  831. if len(cfg.ID) == 0 {
  832. panic("cannot add empty folder id")
  833. }
  834. m.fmut.Lock()
  835. m.folderCfgs[cfg.ID] = cfg
  836. m.folderFiles[cfg.ID] = files.NewSet(cfg.ID, m.db)
  837. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  838. for i, device := range cfg.Devices {
  839. m.folderDevices[cfg.ID][i] = device.DeviceID
  840. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  841. }
  842. m.addedFolder = true
  843. m.fmut.Unlock()
  844. }
  845. func (m *Model) ScanFolders() {
  846. m.fmut.RLock()
  847. var folders = make([]string, 0, len(m.folderCfgs))
  848. for folder := range m.folderCfgs {
  849. folders = append(folders, folder)
  850. }
  851. m.fmut.RUnlock()
  852. var wg sync.WaitGroup
  853. wg.Add(len(folders))
  854. for _, folder := range folders {
  855. folder := folder
  856. go func() {
  857. err := m.ScanFolder(folder)
  858. if err != nil {
  859. m.cfg.InvalidateFolder(folder, err.Error())
  860. }
  861. wg.Done()
  862. }()
  863. }
  864. wg.Wait()
  865. }
  866. func (m *Model) ScanFolder(folder string) error {
  867. return m.ScanFolderSub(folder, "")
  868. }
  869. func (m *Model) ScanFolderSub(folder, sub string) error {
  870. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  871. return errors.New("invalid subpath")
  872. }
  873. m.fmut.RLock()
  874. fs, ok := m.folderFiles[folder]
  875. dir := m.folderCfgs[folder].Path
  876. ignores, _ := ignore.Load(filepath.Join(dir, ".stignore"), m.cfg.Options().CacheIgnoredFiles)
  877. m.folderIgnores[folder] = ignores
  878. w := &scanner.Walker{
  879. Dir: dir,
  880. Sub: sub,
  881. Matcher: ignores,
  882. BlockSize: protocol.BlockSize,
  883. TempNamer: defTempNamer,
  884. CurrentFiler: cFiler{m, folder},
  885. IgnorePerms: m.folderCfgs[folder].IgnorePerms,
  886. }
  887. m.fmut.RUnlock()
  888. if !ok {
  889. return errors.New("no such folder")
  890. }
  891. m.setState(folder, FolderScanning)
  892. fchan, err := w.Walk()
  893. if err != nil {
  894. return err
  895. }
  896. batchSize := 100
  897. batch := make([]protocol.FileInfo, 0, 00)
  898. for f := range fchan {
  899. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  900. "folder": folder,
  901. "name": f.Name,
  902. "modified": time.Unix(f.Modified, 0),
  903. "flags": fmt.Sprintf("0%o", f.Flags),
  904. "size": f.Size(),
  905. })
  906. if len(batch) == batchSize {
  907. fs.Update(protocol.LocalDeviceID, batch)
  908. batch = batch[:0]
  909. }
  910. batch = append(batch, f)
  911. }
  912. if len(batch) > 0 {
  913. fs.Update(protocol.LocalDeviceID, batch)
  914. }
  915. batch = batch[:0]
  916. // TODO: We should limit the Have scanning to start at sub
  917. seenPrefix := false
  918. fs.WithHaveTruncated(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool {
  919. f := fi.(protocol.FileInfoTruncated)
  920. if !strings.HasPrefix(f.Name, sub) {
  921. // Return true so that we keep iterating, until we get to the part
  922. // of the tree we are interested in. Then return false so we stop
  923. // iterating when we've passed the end of the subtree.
  924. return !seenPrefix
  925. }
  926. seenPrefix = true
  927. if !protocol.IsDeleted(f.Flags) {
  928. if f.IsInvalid() {
  929. return true
  930. }
  931. if len(batch) == batchSize {
  932. fs.Update(protocol.LocalDeviceID, batch)
  933. batch = batch[:0]
  934. }
  935. if ignores != nil && ignores.Match(f.Name) {
  936. // File has been ignored. Set invalid bit.
  937. l.Debugln("setting invalid bit on ignored", f)
  938. nf := protocol.FileInfo{
  939. Name: f.Name,
  940. Flags: f.Flags | protocol.FlagInvalid,
  941. Modified: f.Modified,
  942. Version: f.Version, // The file is still the same, so don't bump version
  943. }
  944. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  945. "folder": folder,
  946. "name": f.Name,
  947. "modified": time.Unix(f.Modified, 0),
  948. "flags": fmt.Sprintf("0%o", f.Flags),
  949. "size": f.Size(),
  950. })
  951. batch = append(batch, nf)
  952. } else if _, err := os.Stat(filepath.Join(dir, f.Name)); err != nil && os.IsNotExist(err) {
  953. // File has been deleted
  954. nf := protocol.FileInfo{
  955. Name: f.Name,
  956. Flags: f.Flags | protocol.FlagDeleted,
  957. Modified: f.Modified,
  958. Version: lamport.Default.Tick(f.Version),
  959. }
  960. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  961. "folder": folder,
  962. "name": f.Name,
  963. "modified": time.Unix(f.Modified, 0),
  964. "flags": fmt.Sprintf("0%o", f.Flags),
  965. "size": f.Size(),
  966. })
  967. batch = append(batch, nf)
  968. }
  969. }
  970. return true
  971. })
  972. if len(batch) > 0 {
  973. fs.Update(protocol.LocalDeviceID, batch)
  974. }
  975. m.setState(folder, FolderIdle)
  976. return nil
  977. }
  978. // clusterConfig returns a ClusterConfigMessage that is correct for the given peer device
  979. func (m *Model) clusterConfig(device protocol.DeviceID) protocol.ClusterConfigMessage {
  980. cm := protocol.ClusterConfigMessage{
  981. ClientName: m.clientName,
  982. ClientVersion: m.clientVersion,
  983. Options: []protocol.Option{
  984. {
  985. Key: "name",
  986. Value: m.deviceName,
  987. },
  988. },
  989. }
  990. m.fmut.RLock()
  991. for _, folder := range m.deviceFolders[device] {
  992. cr := protocol.Folder{
  993. ID: folder,
  994. }
  995. for _, device := range m.folderDevices[folder] {
  996. // DeviceID is a value type, but with an underlying array. Copy it
  997. // so we don't grab aliases to the same array later on in device[:]
  998. device := device
  999. // TODO: Set read only bit when relevant
  1000. cn := protocol.Device{
  1001. ID: device[:],
  1002. Flags: protocol.FlagShareTrusted,
  1003. }
  1004. if deviceCfg := m.cfg.Devices()[device]; deviceCfg.Introducer {
  1005. cn.Flags |= protocol.FlagIntroducer
  1006. }
  1007. cr.Devices = append(cr.Devices, cn)
  1008. }
  1009. cm.Folders = append(cm.Folders, cr)
  1010. }
  1011. m.fmut.RUnlock()
  1012. return cm
  1013. }
  1014. func (m *Model) setState(folder string, state folderState) {
  1015. m.smut.Lock()
  1016. oldState := m.folderState[folder]
  1017. changed, ok := m.folderStateChanged[folder]
  1018. if state != oldState {
  1019. m.folderState[folder] = state
  1020. m.folderStateChanged[folder] = time.Now()
  1021. eventData := map[string]interface{}{
  1022. "folder": folder,
  1023. "to": state.String(),
  1024. }
  1025. if ok {
  1026. eventData["duration"] = time.Since(changed).Seconds()
  1027. eventData["from"] = oldState.String()
  1028. }
  1029. events.Default.Log(events.StateChanged, eventData)
  1030. }
  1031. m.smut.Unlock()
  1032. }
  1033. func (m *Model) State(folder string) (string, time.Time) {
  1034. m.smut.RLock()
  1035. state := m.folderState[folder]
  1036. changed := m.folderStateChanged[folder]
  1037. m.smut.RUnlock()
  1038. return state.String(), changed
  1039. }
  1040. func (m *Model) Override(folder string) {
  1041. m.fmut.RLock()
  1042. fs := m.folderFiles[folder]
  1043. m.fmut.RUnlock()
  1044. m.setState(folder, FolderScanning)
  1045. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1046. fs.WithNeed(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool {
  1047. need := fi.(protocol.FileInfo)
  1048. if len(batch) == indexBatchSize {
  1049. fs.Update(protocol.LocalDeviceID, batch)
  1050. batch = batch[:0]
  1051. }
  1052. have := fs.Get(protocol.LocalDeviceID, need.Name)
  1053. if have.Name != need.Name {
  1054. // We are missing the file
  1055. need.Flags |= protocol.FlagDeleted
  1056. need.Blocks = nil
  1057. } else {
  1058. // We have the file, replace with our version
  1059. need = have
  1060. }
  1061. need.Version = lamport.Default.Tick(need.Version)
  1062. need.LocalVersion = 0
  1063. batch = append(batch, need)
  1064. return true
  1065. })
  1066. if len(batch) > 0 {
  1067. fs.Update(protocol.LocalDeviceID, batch)
  1068. }
  1069. m.setState(folder, FolderIdle)
  1070. }
  1071. // CurrentLocalVersion returns the change version for the given folder.
  1072. // This is guaranteed to increment if the contents of the local folder has
  1073. // changed.
  1074. func (m *Model) CurrentLocalVersion(folder string) uint64 {
  1075. m.fmut.Lock()
  1076. defer m.fmut.Unlock()
  1077. fs, ok := m.folderFiles[folder]
  1078. if !ok {
  1079. // The folder might not exist, since this can be called with a user
  1080. // specified folder name from the REST interface.
  1081. return 0
  1082. }
  1083. return fs.LocalVersion(protocol.LocalDeviceID)
  1084. }
  1085. // RemoteLocalVersion returns the change version for the given folder, as
  1086. // sent by remote peers. This is guaranteed to increment if the contents of
  1087. // the remote or global folder has changed.
  1088. func (m *Model) RemoteLocalVersion(folder string) uint64 {
  1089. m.fmut.Lock()
  1090. defer m.fmut.Unlock()
  1091. fs, ok := m.folderFiles[folder]
  1092. if !ok {
  1093. // The folder might not exist, since this can be called with a user
  1094. // specified folder name from the REST interface.
  1095. return 0
  1096. }
  1097. var ver uint64
  1098. for _, n := range m.folderDevices[folder] {
  1099. ver += fs.LocalVersion(n)
  1100. }
  1101. return ver
  1102. }
  1103. func (m *Model) availability(folder string, file string) []protocol.DeviceID {
  1104. m.fmut.Lock()
  1105. defer m.fmut.Unlock()
  1106. fs, ok := m.folderFiles[folder]
  1107. if !ok {
  1108. return nil
  1109. }
  1110. return fs.Availability(file)
  1111. }
  1112. func (m *Model) String() string {
  1113. return fmt.Sprintf("model@%p", m)
  1114. }
  1115. func (m *Model) leveldbPanicWorkaround() {
  1116. // When an inconsistency is detected in leveldb we panic(). This is
  1117. // appropriate because it should never happen, but currently it does for
  1118. // some reason. However it only seems to trigger in the asynchronous full-
  1119. // database scans that happen due to REST and usage-reporting calls. In
  1120. // those places we defer to this workaround to catch the panic instead of
  1121. // taking down syncthing.
  1122. // This is just a band-aid and should be removed as soon as we have found
  1123. // a real root cause.
  1124. if pnc := recover(); pnc != nil {
  1125. if err, ok := pnc.(error); ok && strings.Contains(err.Error(), "leveldb") {
  1126. l.Infoln("recovered:", err)
  1127. } else {
  1128. // Any non-leveldb error is genuine and should continue panicing.
  1129. panic(err)
  1130. }
  1131. }
  1132. }