model.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. package main
  2. /*
  3. Locking
  4. =======
  5. The model has read and write locks. These must be acquired as appropriate by
  6. public methods. To prevent deadlock situations, private methods should never
  7. acquire locks, but document what locks they require.
  8. */
  9. import (
  10. "errors"
  11. "fmt"
  12. "os"
  13. "path"
  14. "sync"
  15. "time"
  16. "github.com/calmh/syncthing/buffers"
  17. "github.com/calmh/syncthing/protocol"
  18. )
  19. type Model struct {
  20. sync.RWMutex
  21. dir string
  22. global map[string]File // the latest version of each file as it exists in the cluster
  23. local map[string]File // the files we currently have locally on disk
  24. remote map[string]map[string]File
  25. need map[string]bool // the files we need to update
  26. nodes map[string]*protocol.Connection
  27. updatedLocal int64 // timestamp of last update to local
  28. updateGlobal int64 // timestamp of last update to remote
  29. lastIdxBcast time.Time
  30. lastIdxBcastRequest time.Time
  31. }
  32. var (
  33. errNoSuchNode = errors.New("no such node")
  34. )
  35. const (
  36. FlagDeleted = 1 << 12
  37. idxBcastHoldtime = 15 * time.Second // Wait at least this long after the last index modification
  38. idxBcastMaxDelay = 120 * time.Second // Unless we've already waited this long
  39. )
  40. func NewModel(dir string) *Model {
  41. m := &Model{
  42. dir: dir,
  43. global: make(map[string]File),
  44. local: make(map[string]File),
  45. remote: make(map[string]map[string]File),
  46. need: make(map[string]bool),
  47. nodes: make(map[string]*protocol.Connection),
  48. lastIdxBcast: time.Now(),
  49. }
  50. go m.printStatsLoop()
  51. go m.broadcastIndexLoop()
  52. return m
  53. }
  54. func (m *Model) Start() {
  55. go m.puller()
  56. }
  57. func (m *Model) printStatsLoop() {
  58. var lastUpdated int64
  59. for {
  60. time.Sleep(60 * time.Second)
  61. m.RLock()
  62. m.printConnectionStats()
  63. if m.updatedLocal+m.updateGlobal > lastUpdated {
  64. m.printModelStats()
  65. lastUpdated = m.updatedLocal + m.updateGlobal
  66. }
  67. m.RUnlock()
  68. }
  69. }
  70. func (m *Model) printConnectionStats() {
  71. for node, conn := range m.nodes {
  72. stats := conn.Statistics()
  73. if (stats.InBytesPerSec > 0 || stats.OutBytesPerSec > 0) && stats.Latency > 0 {
  74. infof("%s: %sB/s in, %sB/s out, %0.02f ms", node, toSI(stats.InBytesPerSec), toSI(stats.OutBytesPerSec), stats.Latency.Seconds()*1000)
  75. } else if stats.InBytesPerSec > 0 || stats.OutBytesPerSec > 0 {
  76. infof("%s: %sB/s in, %sB/s out", node, toSI(stats.InBytesPerSec), toSI(stats.OutBytesPerSec))
  77. }
  78. }
  79. }
  80. func (m *Model) printModelStats() {
  81. var tot int
  82. for _, f := range m.global {
  83. tot += f.Size()
  84. }
  85. infof("%6d files, %8sB in cluster", len(m.global), toSI(tot))
  86. if len(m.need) > 0 {
  87. tot = 0
  88. for _, f := range m.local {
  89. tot += f.Size()
  90. }
  91. infof("%6d files, %8sB in local repo", len(m.local), toSI(tot))
  92. tot = 0
  93. for n := range m.need {
  94. tot += m.global[n].Size()
  95. }
  96. infof("%6d files, %8sB to synchronize", len(m.need), toSI(tot))
  97. }
  98. }
  99. func toSI(n int) string {
  100. if n > 1<<30 {
  101. return fmt.Sprintf("%.02f G", float64(n)/(1<<30))
  102. }
  103. if n > 1<<20 {
  104. return fmt.Sprintf("%.02f M", float64(n)/(1<<20))
  105. }
  106. if n > 1<<10 {
  107. return fmt.Sprintf("%.01f K", float64(n)/(1<<10))
  108. }
  109. return fmt.Sprintf("%d ", n)
  110. }
  111. // Index is called when a new node is connected and we receive their full index.
  112. func (m *Model) Index(nodeID string, fs []protocol.FileInfo) {
  113. m.Lock()
  114. defer m.Unlock()
  115. if opts.Debug.TraceNet {
  116. debugf("NET IDX(in): %s: %d files", nodeID, len(fs))
  117. }
  118. m.remote[nodeID] = make(map[string]File)
  119. for _, f := range fs {
  120. if f.Flags&FlagDeleted != 0 && !opts.Delete {
  121. // Files marked as deleted do not even enter the model
  122. continue
  123. }
  124. m.remote[nodeID][f.Name] = fileFromFileInfo(f)
  125. }
  126. m.recomputeGlobal()
  127. m.recomputeNeed()
  128. m.printModelStats()
  129. }
  130. // IndexUpdate is called for incremental updates to connected nodes' indexes.
  131. func (m *Model) IndexUpdate(nodeID string, fs []protocol.FileInfo) {
  132. m.Lock()
  133. defer m.Unlock()
  134. if opts.Debug.TraceNet {
  135. debugf("NET IDXUP(in): %s: %d files", nodeID, len(fs))
  136. }
  137. repo, ok := m.remote[nodeID]
  138. if !ok {
  139. return
  140. }
  141. for _, f := range fs {
  142. if f.Flags&FlagDeleted != 0 && !opts.Delete {
  143. // Files marked as deleted do not even enter the model
  144. continue
  145. }
  146. repo[f.Name] = fileFromFileInfo(f)
  147. }
  148. m.recomputeGlobal()
  149. m.recomputeNeed()
  150. }
  151. // SeedIndex is called when our previously cached index is loaded from disk at startup.
  152. func (m *Model) SeedIndex(fs []protocol.FileInfo) {
  153. m.Lock()
  154. defer m.Unlock()
  155. m.local = make(map[string]File)
  156. for _, f := range fs {
  157. m.local[f.Name] = fileFromFileInfo(f)
  158. }
  159. m.recomputeGlobal()
  160. m.recomputeNeed()
  161. m.printModelStats()
  162. }
  163. func (m *Model) Close(node string) {
  164. m.Lock()
  165. defer m.Unlock()
  166. infoln("Disconnected from node", node)
  167. delete(m.remote, node)
  168. delete(m.nodes, node)
  169. m.recomputeGlobal()
  170. m.recomputeNeed()
  171. }
  172. func (m *Model) Request(nodeID, name string, offset uint64, size uint32, hash []byte) ([]byte, error) {
  173. if opts.Debug.TraceNet && nodeID != "<local>" {
  174. debugf("NET REQ(in): %s: %q o=%d s=%d h=%x", nodeID, name, offset, size, hash)
  175. }
  176. fn := path.Join(m.dir, name)
  177. fd, err := os.Open(fn) // XXX: Inefficient, should cache fd?
  178. if err != nil {
  179. return nil, err
  180. }
  181. defer fd.Close()
  182. buf := buffers.Get(int(size))
  183. _, err = fd.ReadAt(buf, int64(offset))
  184. if err != nil {
  185. return nil, err
  186. }
  187. return buf, nil
  188. }
  189. func (m *Model) RequestGlobal(nodeID, name string, offset uint64, size uint32, hash []byte) ([]byte, error) {
  190. m.RLock()
  191. nc, ok := m.nodes[nodeID]
  192. m.RUnlock()
  193. if !ok {
  194. return nil, errNoSuchNode
  195. }
  196. if opts.Debug.TraceNet {
  197. debugf("NET REQ(out): %s: %q o=%d s=%d h=%x", nodeID, name, offset, size, hash)
  198. }
  199. return nc.Request(name, offset, size, hash)
  200. }
  201. func (m *Model) ReplaceLocal(fs []File) {
  202. m.Lock()
  203. defer m.Unlock()
  204. var updated bool
  205. var newLocal = make(map[string]File)
  206. for _, f := range fs {
  207. newLocal[f.Name] = f
  208. if ef := m.local[f.Name]; ef.Modified != f.Modified {
  209. updated = true
  210. }
  211. }
  212. if m.markDeletedLocals(newLocal) {
  213. updated = true
  214. }
  215. if len(newLocal) != len(m.local) {
  216. updated = true
  217. }
  218. if updated {
  219. m.local = newLocal
  220. m.recomputeGlobal()
  221. m.recomputeNeed()
  222. m.updatedLocal = time.Now().Unix()
  223. m.lastIdxBcastRequest = time.Now()
  224. }
  225. }
  226. func (m *Model) broadcastIndexLoop() {
  227. for {
  228. m.RLock()
  229. bcastRequested := m.lastIdxBcastRequest.After(m.lastIdxBcast)
  230. holdtimeExceeded := time.Since(m.lastIdxBcastRequest) > idxBcastHoldtime
  231. m.RUnlock()
  232. maxDelayExceeded := time.Since(m.lastIdxBcast) > idxBcastMaxDelay
  233. if bcastRequested && (holdtimeExceeded || maxDelayExceeded) {
  234. m.Lock()
  235. var indexWg sync.WaitGroup
  236. indexWg.Add(len(m.nodes))
  237. idx := m.protocolIndex()
  238. m.lastIdxBcast = time.Now()
  239. for _, node := range m.nodes {
  240. node := node
  241. if opts.Debug.TraceNet {
  242. debugf("NET IDX(out/loop): %s: %d files", node.ID, len(idx))
  243. }
  244. go func() {
  245. node.Index(idx)
  246. indexWg.Done()
  247. }()
  248. }
  249. m.Unlock()
  250. indexWg.Wait()
  251. }
  252. time.Sleep(idxBcastHoldtime)
  253. }
  254. }
  255. // markDeletedLocals sets the deleted flag on files that have gone missing locally.
  256. // Must be called with the write lock held.
  257. func (m *Model) markDeletedLocals(newLocal map[string]File) bool {
  258. // For every file in the existing local table, check if they are also
  259. // present in the new local table. If they are not, check that we already
  260. // had the newest version available according to the global table and if so
  261. // note the file as having been deleted.
  262. var updated bool
  263. for n, f := range m.local {
  264. if _, ok := newLocal[n]; !ok {
  265. if gf := m.global[n]; gf.Modified <= f.Modified {
  266. if f.Flags&FlagDeleted == 0 {
  267. f.Flags = FlagDeleted
  268. f.Modified = f.Modified + 1
  269. f.Blocks = nil
  270. updated = true
  271. }
  272. newLocal[n] = f
  273. }
  274. }
  275. }
  276. return updated
  277. }
  278. func (m *Model) UpdateLocal(f File) {
  279. m.Lock()
  280. defer m.Unlock()
  281. if ef, ok := m.local[f.Name]; !ok || ef.Modified != f.Modified {
  282. m.local[f.Name] = f
  283. m.recomputeGlobal()
  284. m.recomputeNeed()
  285. m.updatedLocal = time.Now().Unix()
  286. m.lastIdxBcastRequest = time.Now()
  287. }
  288. }
  289. func (m *Model) Dir() string {
  290. m.RLock()
  291. defer m.RUnlock()
  292. return m.dir
  293. }
  294. func (m *Model) HaveFiles() []File {
  295. m.RLock()
  296. defer m.RUnlock()
  297. var files []File
  298. for _, file := range m.local {
  299. files = append(files, file)
  300. }
  301. return files
  302. }
  303. func (m *Model) LocalFile(name string) (File, bool) {
  304. m.RLock()
  305. defer m.RUnlock()
  306. f, ok := m.local[name]
  307. return f, ok
  308. }
  309. func (m *Model) GlobalFile(name string) (File, bool) {
  310. m.RLock()
  311. defer m.RUnlock()
  312. f, ok := m.global[name]
  313. return f, ok
  314. }
  315. // Must be called with the write lock held.
  316. func (m *Model) recomputeGlobal() {
  317. var newGlobal = make(map[string]File)
  318. for n, f := range m.local {
  319. newGlobal[n] = f
  320. }
  321. for _, fs := range m.remote {
  322. for n, f := range fs {
  323. if cf, ok := newGlobal[n]; !ok || cf.Modified < f.Modified {
  324. newGlobal[n] = f
  325. }
  326. }
  327. }
  328. // Figure out if anything actually changed
  329. var updated bool
  330. if len(newGlobal) != len(m.global) {
  331. updated = true
  332. } else {
  333. for n, f0 := range newGlobal {
  334. if f1, ok := m.global[n]; !ok || f0.Modified != f1.Modified {
  335. updated = true
  336. break
  337. }
  338. }
  339. }
  340. if updated {
  341. m.updateGlobal = time.Now().Unix()
  342. m.global = newGlobal
  343. }
  344. }
  345. // Must be called with the write lock held.
  346. func (m *Model) recomputeNeed() {
  347. m.need = make(map[string]bool)
  348. for n, f := range m.global {
  349. hf, ok := m.local[n]
  350. if !ok || f.Modified > hf.Modified {
  351. m.need[n] = true
  352. }
  353. }
  354. }
  355. // Must be called with the read lock held.
  356. func (m *Model) whoHas(name string) []string {
  357. var remote []string
  358. gf := m.global[name]
  359. for node, files := range m.remote {
  360. if file, ok := files[name]; ok && file.Modified == gf.Modified {
  361. remote = append(remote, node)
  362. }
  363. }
  364. return remote
  365. }
  366. func (m *Model) ConnectedTo(nodeID string) bool {
  367. m.RLock()
  368. defer m.RUnlock()
  369. _, ok := m.nodes[nodeID]
  370. return ok
  371. }
  372. func (m *Model) ProtocolIndex() []protocol.FileInfo {
  373. m.RLock()
  374. defer m.RUnlock()
  375. return m.protocolIndex()
  376. }
  377. // Must be called with the read lock held.
  378. func (m *Model) protocolIndex() []protocol.FileInfo {
  379. var index []protocol.FileInfo
  380. for _, f := range m.local {
  381. mf := fileInfoFromFile(f)
  382. if opts.Debug.TraceIdx {
  383. var flagComment string
  384. if mf.Flags&FlagDeleted != 0 {
  385. flagComment = " (deleted)"
  386. }
  387. debugf("IDX: %q m=%d f=%o%s (%d blocks)", mf.Name, mf.Modified, mf.Flags, flagComment, len(mf.Blocks))
  388. }
  389. index = append(index, mf)
  390. }
  391. return index
  392. }
  393. func (m *Model) AddNode(node *protocol.Connection) {
  394. m.Lock()
  395. m.nodes[node.ID] = node
  396. m.Unlock()
  397. m.RLock()
  398. idx := m.protocolIndex()
  399. m.RUnlock()
  400. if opts.Debug.TraceNet {
  401. debugf("NET IDX(out/add): %s: %d files", node.ID, len(idx))
  402. }
  403. // Sending the index might take a while if we have many files and a slow
  404. // uplink. Return from AddNode in the meantime.
  405. go node.Index(idx)
  406. }
  407. func fileFromFileInfo(f protocol.FileInfo) File {
  408. var blocks []Block
  409. var offset uint64
  410. for _, b := range f.Blocks {
  411. blocks = append(blocks, Block{
  412. Offset: offset,
  413. Length: b.Length,
  414. Hash: b.Hash,
  415. })
  416. offset += uint64(b.Length)
  417. }
  418. return File{
  419. Name: f.Name,
  420. Flags: f.Flags,
  421. Modified: int64(f.Modified),
  422. Blocks: blocks,
  423. }
  424. }
  425. func fileInfoFromFile(f File) protocol.FileInfo {
  426. var blocks []protocol.BlockInfo
  427. for _, b := range f.Blocks {
  428. blocks = append(blocks, protocol.BlockInfo{
  429. Length: b.Length,
  430. Hash: b.Hash,
  431. })
  432. }
  433. return protocol.FileInfo{
  434. Name: f.Name,
  435. Flags: f.Flags,
  436. Modified: int64(f.Modified),
  437. Blocks: blocks,
  438. }
  439. }