model.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  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. }
  490. // The introducers' introducers are also our introducers.
  491. if device.Flags&protocol.FlagIntroducer != 0 {
  492. l.Infof("Device %v is now also an introducer", id)
  493. newDeviceCfg.Introducer = true
  494. }
  495. m.cfg.SetDevice(newDeviceCfg)
  496. changed = true
  497. }
  498. for _, er := range m.deviceFolders[id] {
  499. if er == folder.ID {
  500. // We already share the folder with this device, so
  501. // nothing to do.
  502. continue nextDevice
  503. }
  504. }
  505. // We don't yet share this folder with this device. Add the device
  506. // to sharing list of the folder.
  507. l.Infof("Adding device %v to share %q (vouched for by introducer %v)", id, folder.ID, deviceID)
  508. m.deviceFolders[id] = append(m.deviceFolders[id], folder.ID)
  509. m.folderDevices[folder.ID] = append(m.folderDevices[folder.ID], id)
  510. folderCfg := m.cfg.Folders()[folder.ID]
  511. folderCfg.Devices = append(folderCfg.Devices, config.FolderDeviceConfiguration{
  512. DeviceID: id,
  513. })
  514. m.cfg.SetFolder(folderCfg)
  515. changed = true
  516. }
  517. }
  518. if changed {
  519. m.cfg.Save()
  520. }
  521. }
  522. }
  523. // Close removes the peer from the model and closes the underlying connection if possible.
  524. // Implements the protocol.Model interface.
  525. func (m *Model) Close(device protocol.DeviceID, err error) {
  526. l.Infof("Connection to %s closed: %v", device, err)
  527. events.Default.Log(events.DeviceDisconnected, map[string]string{
  528. "id": device.String(),
  529. "error": err.Error(),
  530. })
  531. m.pmut.Lock()
  532. m.fmut.RLock()
  533. for _, folder := range m.deviceFolders[device] {
  534. m.folderFiles[folder].Replace(device, nil)
  535. }
  536. m.fmut.RUnlock()
  537. conn, ok := m.rawConn[device]
  538. if ok {
  539. if conn, ok := conn.(*tls.Conn); ok {
  540. // If the underlying connection is a *tls.Conn, Close() does more
  541. // than it says on the tin. Specifically, it sends a TLS alert
  542. // message, which might block forever if the connection is dead
  543. // and we don't have a deadline site.
  544. conn.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))
  545. }
  546. conn.Close()
  547. }
  548. delete(m.protoConn, device)
  549. delete(m.rawConn, device)
  550. delete(m.deviceVer, device)
  551. m.pmut.Unlock()
  552. }
  553. // Request returns the specified data segment by reading it from local disk.
  554. // Implements the protocol.Model interface.
  555. func (m *Model) Request(deviceID protocol.DeviceID, folder, name string, offset int64, size int) ([]byte, error) {
  556. // Verify that the requested file exists in the local model.
  557. m.fmut.RLock()
  558. r, ok := m.folderFiles[folder]
  559. m.fmut.RUnlock()
  560. if !ok {
  561. l.Warnf("Request from %s for file %s in nonexistent folder %q", deviceID, name, folder)
  562. return nil, ErrNoSuchFile
  563. }
  564. lf := r.Get(protocol.LocalDeviceID, name)
  565. if protocol.IsInvalid(lf.Flags) || protocol.IsDeleted(lf.Flags) {
  566. if debug {
  567. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d; invalid: %v", m, deviceID, folder, name, offset, size, lf)
  568. }
  569. return nil, ErrInvalid
  570. }
  571. if offset > lf.Size() {
  572. if debug {
  573. l.Debugf("%v REQ(in; nonexistent): %s: %q o=%d s=%d", m, deviceID, name, offset, size)
  574. }
  575. return nil, ErrNoSuchFile
  576. }
  577. if debug && deviceID != protocol.LocalDeviceID {
  578. l.Debugf("%v REQ(in): %s: %q / %q o=%d s=%d", m, deviceID, folder, name, offset, size)
  579. }
  580. m.fmut.RLock()
  581. fn := filepath.Join(m.folderCfgs[folder].Path, name)
  582. m.fmut.RUnlock()
  583. fd, err := os.Open(fn) // XXX: Inefficient, should cache fd?
  584. if err != nil {
  585. return nil, err
  586. }
  587. defer fd.Close()
  588. buf := make([]byte, size)
  589. _, err = fd.ReadAt(buf, offset)
  590. if err != nil {
  591. return nil, err
  592. }
  593. return buf, nil
  594. }
  595. // ReplaceLocal replaces the local folder index with the given list of files.
  596. func (m *Model) ReplaceLocal(folder string, fs []protocol.FileInfo) {
  597. m.fmut.RLock()
  598. m.folderFiles[folder].ReplaceWithDelete(protocol.LocalDeviceID, fs)
  599. m.fmut.RUnlock()
  600. }
  601. func (m *Model) CurrentFolderFile(folder string, file string) protocol.FileInfo {
  602. m.fmut.RLock()
  603. f := m.folderFiles[folder].Get(protocol.LocalDeviceID, file)
  604. m.fmut.RUnlock()
  605. return f
  606. }
  607. func (m *Model) CurrentGlobalFile(folder string, file string) protocol.FileInfo {
  608. m.fmut.RLock()
  609. f := m.folderFiles[folder].GetGlobal(file)
  610. m.fmut.RUnlock()
  611. return f
  612. }
  613. type cFiler struct {
  614. m *Model
  615. r string
  616. }
  617. // Implements scanner.CurrentFiler
  618. func (cf cFiler) CurrentFile(file string) protocol.FileInfo {
  619. return cf.m.CurrentFolderFile(cf.r, file)
  620. }
  621. // ConnectedTo returns true if we are connected to the named device.
  622. func (m *Model) ConnectedTo(deviceID protocol.DeviceID) bool {
  623. m.pmut.RLock()
  624. _, ok := m.protoConn[deviceID]
  625. m.pmut.RUnlock()
  626. if ok {
  627. m.deviceWasSeen(deviceID)
  628. }
  629. return ok
  630. }
  631. func (m *Model) GetIgnores(folder string) ([]string, error) {
  632. var lines []string
  633. cfg, ok := m.folderCfgs[folder]
  634. if !ok {
  635. return lines, fmt.Errorf("Folder %s does not exist", folder)
  636. }
  637. m.fmut.Lock()
  638. defer m.fmut.Unlock()
  639. fd, err := os.Open(filepath.Join(cfg.Path, ".stignore"))
  640. if err != nil {
  641. if os.IsNotExist(err) {
  642. return lines, nil
  643. }
  644. l.Warnln("Loading .stignore:", err)
  645. return lines, err
  646. }
  647. defer fd.Close()
  648. scanner := bufio.NewScanner(fd)
  649. for scanner.Scan() {
  650. lines = append(lines, strings.TrimSpace(scanner.Text()))
  651. }
  652. return lines, nil
  653. }
  654. func (m *Model) SetIgnores(folder string, content []string) error {
  655. cfg, ok := m.folderCfgs[folder]
  656. if !ok {
  657. return fmt.Errorf("Folder %s does not exist", folder)
  658. }
  659. fd, err := ioutil.TempFile(cfg.Path, ".syncthing.stignore-"+folder)
  660. if err != nil {
  661. l.Warnln("Saving .stignore:", err)
  662. return err
  663. }
  664. defer os.Remove(fd.Name())
  665. for _, line := range content {
  666. _, err = fmt.Fprintln(fd, line)
  667. if err != nil {
  668. l.Warnln("Saving .stignore:", err)
  669. return err
  670. }
  671. }
  672. err = fd.Close()
  673. if err != nil {
  674. l.Warnln("Saving .stignore:", err)
  675. return err
  676. }
  677. file := filepath.Join(cfg.Path, ".stignore")
  678. err = osutil.Rename(fd.Name(), file)
  679. if err != nil {
  680. l.Warnln("Saving .stignore:", err)
  681. return err
  682. }
  683. return m.ScanFolder(folder)
  684. }
  685. // AddConnection adds a new peer connection to the model. An initial index will
  686. // be sent to the connected peer, thereafter index updates whenever the local
  687. // folder changes.
  688. func (m *Model) AddConnection(rawConn io.Closer, protoConn protocol.Connection) {
  689. deviceID := protoConn.ID()
  690. m.pmut.Lock()
  691. if _, ok := m.protoConn[deviceID]; ok {
  692. panic("add existing device")
  693. }
  694. m.protoConn[deviceID] = protoConn
  695. if _, ok := m.rawConn[deviceID]; ok {
  696. panic("add existing device")
  697. }
  698. m.rawConn[deviceID] = rawConn
  699. cm := m.clusterConfig(deviceID)
  700. protoConn.ClusterConfig(cm)
  701. m.fmut.RLock()
  702. for _, folder := range m.deviceFolders[deviceID] {
  703. fs := m.folderFiles[folder]
  704. go sendIndexes(protoConn, folder, fs, m.folderIgnores[folder])
  705. }
  706. m.fmut.RUnlock()
  707. m.pmut.Unlock()
  708. m.deviceWasSeen(deviceID)
  709. }
  710. func (m *Model) deviceStatRef(deviceID protocol.DeviceID) *stats.DeviceStatisticsReference {
  711. m.fmut.Lock()
  712. defer m.fmut.Unlock()
  713. if sr, ok := m.deviceStatRefs[deviceID]; ok {
  714. return sr
  715. } else {
  716. sr = stats.NewDeviceStatisticsReference(m.db, deviceID)
  717. m.deviceStatRefs[deviceID] = sr
  718. return sr
  719. }
  720. }
  721. func (m *Model) deviceWasSeen(deviceID protocol.DeviceID) {
  722. m.deviceStatRef(deviceID).WasSeen()
  723. }
  724. func sendIndexes(conn protocol.Connection, folder string, fs *files.Set, ignores *ignore.Matcher) {
  725. deviceID := conn.ID()
  726. name := conn.Name()
  727. var err error
  728. if debug {
  729. l.Debugf("sendIndexes for %s-%s/%q starting", deviceID, name, folder)
  730. }
  731. minLocalVer, err := sendIndexTo(true, 0, conn, folder, fs, ignores)
  732. for err == nil {
  733. time.Sleep(5 * time.Second)
  734. if fs.LocalVersion(protocol.LocalDeviceID) <= minLocalVer {
  735. continue
  736. }
  737. minLocalVer, err = sendIndexTo(false, minLocalVer, conn, folder, fs, ignores)
  738. }
  739. if debug {
  740. l.Debugf("sendIndexes for %s-%s/%q exiting: %v", deviceID, name, folder, err)
  741. }
  742. }
  743. func sendIndexTo(initial bool, minLocalVer uint64, conn protocol.Connection, folder string, fs *files.Set, ignores *ignore.Matcher) (uint64, error) {
  744. deviceID := conn.ID()
  745. name := conn.Name()
  746. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  747. currentBatchSize := 0
  748. maxLocalVer := uint64(0)
  749. var err error
  750. fs.WithHave(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool {
  751. f := fi.(protocol.FileInfo)
  752. if f.LocalVersion <= minLocalVer {
  753. return true
  754. }
  755. if f.LocalVersion > maxLocalVer {
  756. maxLocalVer = f.LocalVersion
  757. }
  758. if ignores != nil && ignores.Match(f.Name) {
  759. if debug {
  760. l.Debugln("not sending update for ignored", f)
  761. }
  762. return true
  763. }
  764. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  765. if initial {
  766. if err = conn.Index(folder, batch); err != nil {
  767. return false
  768. }
  769. if debug {
  770. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", deviceID, name, folder, len(batch), currentBatchSize)
  771. }
  772. initial = false
  773. } else {
  774. if err = conn.IndexUpdate(folder, batch); err != nil {
  775. return false
  776. }
  777. if debug {
  778. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", deviceID, name, folder, len(batch), currentBatchSize)
  779. }
  780. }
  781. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  782. currentBatchSize = 0
  783. }
  784. batch = append(batch, f)
  785. currentBatchSize += indexPerFileSize + len(f.Blocks)*IndexPerBlockSize
  786. return true
  787. })
  788. if initial && err == nil {
  789. err = conn.Index(folder, batch)
  790. if debug && err == nil {
  791. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", deviceID, name, folder, len(batch))
  792. }
  793. } else if len(batch) > 0 && err == nil {
  794. err = conn.IndexUpdate(folder, batch)
  795. if debug && err == nil {
  796. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", deviceID, name, folder, len(batch))
  797. }
  798. }
  799. return maxLocalVer, err
  800. }
  801. func (m *Model) updateLocal(folder string, f protocol.FileInfo) {
  802. f.LocalVersion = 0
  803. m.fmut.RLock()
  804. m.folderFiles[folder].Update(protocol.LocalDeviceID, []protocol.FileInfo{f})
  805. m.fmut.RUnlock()
  806. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  807. "folder": folder,
  808. "name": f.Name,
  809. "modified": time.Unix(f.Modified, 0),
  810. "flags": fmt.Sprintf("0%o", f.Flags),
  811. "size": f.Size(),
  812. })
  813. }
  814. func (m *Model) requestGlobal(deviceID protocol.DeviceID, folder, name string, offset int64, size int, hash []byte) ([]byte, error) {
  815. m.pmut.RLock()
  816. nc, ok := m.protoConn[deviceID]
  817. m.pmut.RUnlock()
  818. if !ok {
  819. return nil, fmt.Errorf("requestGlobal: no such device: %s", deviceID)
  820. }
  821. if debug {
  822. l.Debugf("%v REQ(out): %s: %q / %q o=%d s=%d h=%x", m, deviceID, folder, name, offset, size, hash)
  823. }
  824. return nc.Request(folder, name, offset, size)
  825. }
  826. func (m *Model) AddFolder(cfg config.FolderConfiguration) {
  827. if m.started {
  828. panic("cannot add folder to started model")
  829. }
  830. if len(cfg.ID) == 0 {
  831. panic("cannot add empty folder id")
  832. }
  833. m.fmut.Lock()
  834. m.folderCfgs[cfg.ID] = cfg
  835. m.folderFiles[cfg.ID] = files.NewSet(cfg.ID, m.db)
  836. m.folderDevices[cfg.ID] = make([]protocol.DeviceID, len(cfg.Devices))
  837. for i, device := range cfg.Devices {
  838. m.folderDevices[cfg.ID][i] = device.DeviceID
  839. m.deviceFolders[device.DeviceID] = append(m.deviceFolders[device.DeviceID], cfg.ID)
  840. }
  841. m.addedFolder = true
  842. m.fmut.Unlock()
  843. }
  844. func (m *Model) ScanFolders() {
  845. m.fmut.RLock()
  846. var folders = make([]string, 0, len(m.folderCfgs))
  847. for folder := range m.folderCfgs {
  848. folders = append(folders, folder)
  849. }
  850. m.fmut.RUnlock()
  851. var wg sync.WaitGroup
  852. wg.Add(len(folders))
  853. for _, folder := range folders {
  854. folder := folder
  855. go func() {
  856. err := m.ScanFolder(folder)
  857. if err != nil {
  858. m.cfg.InvalidateFolder(folder, err.Error())
  859. }
  860. wg.Done()
  861. }()
  862. }
  863. wg.Wait()
  864. }
  865. func (m *Model) ScanFolder(folder string) error {
  866. return m.ScanFolderSub(folder, "")
  867. }
  868. func (m *Model) ScanFolderSub(folder, sub string) error {
  869. if p := filepath.Clean(filepath.Join(folder, sub)); !strings.HasPrefix(p, folder) {
  870. return errors.New("invalid subpath")
  871. }
  872. m.fmut.RLock()
  873. fs, ok := m.folderFiles[folder]
  874. dir := m.folderCfgs[folder].Path
  875. ignores, _ := ignore.Load(filepath.Join(dir, ".stignore"), m.cfg.Options().CacheIgnoredFiles)
  876. m.folderIgnores[folder] = ignores
  877. w := &scanner.Walker{
  878. Dir: dir,
  879. Sub: sub,
  880. Matcher: ignores,
  881. BlockSize: protocol.BlockSize,
  882. TempNamer: defTempNamer,
  883. CurrentFiler: cFiler{m, folder},
  884. IgnorePerms: m.folderCfgs[folder].IgnorePerms,
  885. }
  886. m.fmut.RUnlock()
  887. if !ok {
  888. return errors.New("no such folder")
  889. }
  890. m.setState(folder, FolderScanning)
  891. fchan, err := w.Walk()
  892. if err != nil {
  893. return err
  894. }
  895. batchSize := 100
  896. batch := make([]protocol.FileInfo, 0, 00)
  897. for f := range fchan {
  898. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  899. "folder": folder,
  900. "name": f.Name,
  901. "modified": time.Unix(f.Modified, 0),
  902. "flags": fmt.Sprintf("0%o", f.Flags),
  903. "size": f.Size(),
  904. })
  905. if len(batch) == batchSize {
  906. fs.Update(protocol.LocalDeviceID, batch)
  907. batch = batch[:0]
  908. }
  909. batch = append(batch, f)
  910. }
  911. if len(batch) > 0 {
  912. fs.Update(protocol.LocalDeviceID, batch)
  913. }
  914. batch = batch[:0]
  915. // TODO: We should limit the Have scanning to start at sub
  916. seenPrefix := false
  917. fs.WithHaveTruncated(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool {
  918. f := fi.(protocol.FileInfoTruncated)
  919. if !strings.HasPrefix(f.Name, sub) {
  920. // Return true so that we keep iterating, until we get to the part
  921. // of the tree we are interested in. Then return false so we stop
  922. // iterating when we've passed the end of the subtree.
  923. return !seenPrefix
  924. }
  925. seenPrefix = true
  926. if !protocol.IsDeleted(f.Flags) {
  927. if f.IsInvalid() {
  928. return true
  929. }
  930. if len(batch) == batchSize {
  931. fs.Update(protocol.LocalDeviceID, batch)
  932. batch = batch[:0]
  933. }
  934. if ignores != nil && ignores.Match(f.Name) {
  935. // File has been ignored. Set invalid bit.
  936. l.Debugln("setting invalid bit on ignored", f)
  937. nf := protocol.FileInfo{
  938. Name: f.Name,
  939. Flags: f.Flags | protocol.FlagInvalid,
  940. Modified: f.Modified,
  941. Version: f.Version, // The file is still the same, so don't bump version
  942. }
  943. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  944. "folder": folder,
  945. "name": f.Name,
  946. "modified": time.Unix(f.Modified, 0),
  947. "flags": fmt.Sprintf("0%o", f.Flags),
  948. "size": f.Size(),
  949. })
  950. batch = append(batch, nf)
  951. } else if _, err := os.Stat(filepath.Join(dir, f.Name)); err != nil && os.IsNotExist(err) {
  952. // File has been deleted
  953. nf := protocol.FileInfo{
  954. Name: f.Name,
  955. Flags: f.Flags | protocol.FlagDeleted,
  956. Modified: f.Modified,
  957. Version: lamport.Default.Tick(f.Version),
  958. }
  959. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  960. "folder": folder,
  961. "name": f.Name,
  962. "modified": time.Unix(f.Modified, 0),
  963. "flags": fmt.Sprintf("0%o", f.Flags),
  964. "size": f.Size(),
  965. })
  966. batch = append(batch, nf)
  967. }
  968. }
  969. return true
  970. })
  971. if len(batch) > 0 {
  972. fs.Update(protocol.LocalDeviceID, batch)
  973. }
  974. m.setState(folder, FolderIdle)
  975. return nil
  976. }
  977. // clusterConfig returns a ClusterConfigMessage that is correct for the given peer device
  978. func (m *Model) clusterConfig(device protocol.DeviceID) protocol.ClusterConfigMessage {
  979. cm := protocol.ClusterConfigMessage{
  980. ClientName: m.clientName,
  981. ClientVersion: m.clientVersion,
  982. Options: []protocol.Option{
  983. {
  984. Key: "name",
  985. Value: m.deviceName,
  986. },
  987. },
  988. }
  989. m.fmut.RLock()
  990. for _, folder := range m.deviceFolders[device] {
  991. cr := protocol.Folder{
  992. ID: folder,
  993. }
  994. for _, device := range m.folderDevices[folder] {
  995. // DeviceID is a value type, but with an underlying array. Copy it
  996. // so we don't grab aliases to the same array later on in device[:]
  997. device := device
  998. // TODO: Set read only bit when relevant
  999. cn := protocol.Device{
  1000. ID: device[:],
  1001. Flags: protocol.FlagShareTrusted,
  1002. }
  1003. if deviceCfg := m.cfg.Devices()[device]; deviceCfg.Introducer {
  1004. cn.Flags |= protocol.FlagIntroducer
  1005. }
  1006. cr.Devices = append(cr.Devices, cn)
  1007. }
  1008. cm.Folders = append(cm.Folders, cr)
  1009. }
  1010. m.fmut.RUnlock()
  1011. return cm
  1012. }
  1013. func (m *Model) setState(folder string, state folderState) {
  1014. m.smut.Lock()
  1015. oldState := m.folderState[folder]
  1016. changed, ok := m.folderStateChanged[folder]
  1017. if state != oldState {
  1018. m.folderState[folder] = state
  1019. m.folderStateChanged[folder] = time.Now()
  1020. eventData := map[string]interface{}{
  1021. "folder": folder,
  1022. "to": state.String(),
  1023. }
  1024. if ok {
  1025. eventData["duration"] = time.Since(changed).Seconds()
  1026. eventData["from"] = oldState.String()
  1027. }
  1028. events.Default.Log(events.StateChanged, eventData)
  1029. }
  1030. m.smut.Unlock()
  1031. }
  1032. func (m *Model) State(folder string) (string, time.Time) {
  1033. m.smut.RLock()
  1034. state := m.folderState[folder]
  1035. changed := m.folderStateChanged[folder]
  1036. m.smut.RUnlock()
  1037. return state.String(), changed
  1038. }
  1039. func (m *Model) Override(folder string) {
  1040. m.fmut.RLock()
  1041. fs := m.folderFiles[folder]
  1042. m.fmut.RUnlock()
  1043. m.setState(folder, FolderScanning)
  1044. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  1045. fs.WithNeed(protocol.LocalDeviceID, func(fi protocol.FileIntf) bool {
  1046. need := fi.(protocol.FileInfo)
  1047. if len(batch) == indexBatchSize {
  1048. fs.Update(protocol.LocalDeviceID, batch)
  1049. batch = batch[:0]
  1050. }
  1051. have := fs.Get(protocol.LocalDeviceID, need.Name)
  1052. if have.Name != need.Name {
  1053. // We are missing the file
  1054. need.Flags |= protocol.FlagDeleted
  1055. need.Blocks = nil
  1056. } else {
  1057. // We have the file, replace with our version
  1058. need = have
  1059. }
  1060. need.Version = lamport.Default.Tick(need.Version)
  1061. need.LocalVersion = 0
  1062. batch = append(batch, need)
  1063. return true
  1064. })
  1065. if len(batch) > 0 {
  1066. fs.Update(protocol.LocalDeviceID, batch)
  1067. }
  1068. m.setState(folder, FolderIdle)
  1069. }
  1070. // CurrentLocalVersion returns the change version for the given folder.
  1071. // This is guaranteed to increment if the contents of the local folder has
  1072. // changed.
  1073. func (m *Model) CurrentLocalVersion(folder string) uint64 {
  1074. m.fmut.Lock()
  1075. defer m.fmut.Unlock()
  1076. fs, ok := m.folderFiles[folder]
  1077. if !ok {
  1078. // The folder might not exist, since this can be called with a user
  1079. // specified folder name from the REST interface.
  1080. return 0
  1081. }
  1082. return fs.LocalVersion(protocol.LocalDeviceID)
  1083. }
  1084. // RemoteLocalVersion returns the change version for the given folder, as
  1085. // sent by remote peers. This is guaranteed to increment if the contents of
  1086. // the remote or global folder has changed.
  1087. func (m *Model) RemoteLocalVersion(folder string) uint64 {
  1088. m.fmut.Lock()
  1089. defer m.fmut.Unlock()
  1090. fs, ok := m.folderFiles[folder]
  1091. if !ok {
  1092. panic("bug: LocalVersion called for nonexistent folder " + folder)
  1093. }
  1094. var ver uint64
  1095. for _, n := range m.folderDevices[folder] {
  1096. ver += fs.LocalVersion(n)
  1097. }
  1098. return ver
  1099. }
  1100. func (m *Model) availability(folder string, file string) []protocol.DeviceID {
  1101. m.fmut.Lock()
  1102. defer m.fmut.Unlock()
  1103. fs, ok := m.folderFiles[folder]
  1104. if !ok {
  1105. return nil
  1106. }
  1107. return fs.Availability(file)
  1108. }
  1109. func (m *Model) String() string {
  1110. return fmt.Sprintf("model@%p", m)
  1111. }
  1112. func (m *Model) leveldbPanicWorkaround() {
  1113. // When an inconsistency is detected in leveldb we panic(). This is
  1114. // appropriate because it should never happen, but currently it does for
  1115. // some reason. However it only seems to trigger in the asynchronous full-
  1116. // database scans that happen due to REST and usage-reporting calls. In
  1117. // those places we defer to this workaround to catch the panic instead of
  1118. // taking down syncthing.
  1119. // This is just a band-aid and should be removed as soon as we have found
  1120. // a real root cause.
  1121. if pnc := recover(); pnc != nil {
  1122. if err, ok := pnc.(error); ok && strings.Contains(err.Error(), "leveldb") {
  1123. l.Infoln("recovered:", err)
  1124. } else {
  1125. // Any non-leveldb error is genuine and should continue panicing.
  1126. panic(err)
  1127. }
  1128. }
  1129. }