model.go 35 KB

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