model.go 11 KB

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