model.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. package model
  5. import (
  6. "errors"
  7. "fmt"
  8. "io"
  9. "net"
  10. "os"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/syncthing/syncthing/config"
  17. "github.com/syncthing/syncthing/events"
  18. "github.com/syncthing/syncthing/files"
  19. "github.com/syncthing/syncthing/lamport"
  20. "github.com/syncthing/syncthing/protocol"
  21. "github.com/syncthing/syncthing/scanner"
  22. "github.com/syndtr/goleveldb/leveldb"
  23. )
  24. type repoState int
  25. const (
  26. RepoIdle repoState = iota
  27. RepoScanning
  28. RepoSyncing
  29. RepoCleaning
  30. )
  31. func (s repoState) String() string {
  32. switch s {
  33. case RepoIdle:
  34. return "idle"
  35. case RepoScanning:
  36. return "scanning"
  37. case RepoCleaning:
  38. return "cleaning"
  39. case RepoSyncing:
  40. return "syncing"
  41. default:
  42. return "unknown"
  43. }
  44. }
  45. // Somewhat arbitrary amount of bytes that we choose to let represent the size
  46. // of an unsynchronized directory entry or a deleted file. We need it to be
  47. // larger than zero so that it's visible that there is some amount of bytes to
  48. // transfer to bring the systems into synchronization.
  49. const zeroEntrySize = 128
  50. // How many files to send in each Index/IndexUpdate message.
  51. const (
  52. indexTargetSize = 250 * 1024 // Aim for making index messages no larger than 250 KiB (uncompressed)
  53. indexPerFileSize = 250 // Each FileInfo is approximately this big, in bytes, excluding BlockInfos
  54. IndexPerBlockSize = 40 // Each BlockInfo is approximately this big
  55. indexBatchSize = 1000 // Either way, don't include more files than this
  56. )
  57. type Model struct {
  58. indexDir string
  59. cfg *config.Configuration
  60. db *leveldb.DB
  61. clientName string
  62. clientVersion string
  63. repoCfgs map[string]config.RepositoryConfiguration // repo -> cfg
  64. repoFiles map[string]*files.Set // repo -> files
  65. repoNodes map[string][]protocol.NodeID // repo -> nodeIDs
  66. nodeRepos map[protocol.NodeID][]string // nodeID -> repos
  67. rmut sync.RWMutex // protects the above
  68. repoState map[string]repoState // repo -> state
  69. repoStateChanged map[string]time.Time // repo -> time when state changed
  70. smut sync.RWMutex
  71. protoConn map[protocol.NodeID]protocol.Connection
  72. rawConn map[protocol.NodeID]io.Closer
  73. nodeVer map[protocol.NodeID]string
  74. pmut sync.RWMutex // protects protoConn and rawConn
  75. sentLocalVer map[protocol.NodeID]map[string]uint64
  76. slMut sync.Mutex
  77. addedRepo bool
  78. started bool
  79. }
  80. var (
  81. ErrNoSuchFile = errors.New("no such file")
  82. ErrInvalid = errors.New("file is invalid")
  83. )
  84. // NewModel creates and starts a new model. The model starts in read-only mode,
  85. // where it sends index information to connected peers and responds to requests
  86. // for file data without altering the local repository in any way.
  87. func NewModel(indexDir string, cfg *config.Configuration, clientName, clientVersion string, db *leveldb.DB) *Model {
  88. m := &Model{
  89. indexDir: indexDir,
  90. cfg: cfg,
  91. db: db,
  92. clientName: clientName,
  93. clientVersion: clientVersion,
  94. repoCfgs: make(map[string]config.RepositoryConfiguration),
  95. repoFiles: make(map[string]*files.Set),
  96. repoNodes: make(map[string][]protocol.NodeID),
  97. nodeRepos: make(map[protocol.NodeID][]string),
  98. repoState: make(map[string]repoState),
  99. repoStateChanged: make(map[string]time.Time),
  100. protoConn: make(map[protocol.NodeID]protocol.Connection),
  101. rawConn: make(map[protocol.NodeID]io.Closer),
  102. nodeVer: make(map[protocol.NodeID]string),
  103. sentLocalVer: make(map[protocol.NodeID]map[string]uint64),
  104. }
  105. var timeout = 20 * 60 // seconds
  106. if t := os.Getenv("STDEADLOCKTIMEOUT"); len(t) > 0 {
  107. it, err := strconv.Atoi(t)
  108. if err == nil {
  109. timeout = it
  110. }
  111. }
  112. deadlockDetect(&m.rmut, time.Duration(timeout)*time.Second)
  113. deadlockDetect(&m.smut, time.Duration(timeout)*time.Second)
  114. deadlockDetect(&m.pmut, time.Duration(timeout)*time.Second)
  115. return m
  116. }
  117. // StartRW starts read/write processing on the current model. When in
  118. // read/write mode the model will attempt to keep in sync with the cluster by
  119. // pulling needed files from peer nodes.
  120. func (m *Model) StartRepoRW(repo string, threads int) {
  121. m.rmut.RLock()
  122. defer m.rmut.RUnlock()
  123. if cfg, ok := m.repoCfgs[repo]; !ok {
  124. panic("cannot start without repo")
  125. } else {
  126. newPuller(cfg, m, threads, m.cfg)
  127. }
  128. }
  129. // StartRO starts read only processing on the current model. When in
  130. // read only mode the model will announce files to the cluster but not
  131. // pull in any external changes.
  132. func (m *Model) StartRepoRO(repo string) {
  133. m.StartRepoRW(repo, 0) // zero threads => read only
  134. }
  135. type ConnectionInfo struct {
  136. protocol.Statistics
  137. Address string
  138. ClientVersion string
  139. }
  140. // ConnectionStats returns a map with connection statistics for each connected node.
  141. func (m *Model) ConnectionStats() map[string]ConnectionInfo {
  142. type remoteAddrer interface {
  143. RemoteAddr() net.Addr
  144. }
  145. m.pmut.RLock()
  146. m.rmut.RLock()
  147. var res = make(map[string]ConnectionInfo)
  148. for node, conn := range m.protoConn {
  149. ci := ConnectionInfo{
  150. Statistics: conn.Statistics(),
  151. ClientVersion: m.nodeVer[node],
  152. }
  153. if nc, ok := m.rawConn[node].(remoteAddrer); ok {
  154. ci.Address = nc.RemoteAddr().String()
  155. }
  156. res[node.String()] = ci
  157. }
  158. m.rmut.RUnlock()
  159. m.pmut.RUnlock()
  160. in, out := protocol.TotalInOut()
  161. res["total"] = ConnectionInfo{
  162. Statistics: protocol.Statistics{
  163. At: time.Now(),
  164. InBytesTotal: in,
  165. OutBytesTotal: out,
  166. },
  167. }
  168. return res
  169. }
  170. // Returns the completion status, in percent, for the given node and repo.
  171. func (m *Model) Completion(node protocol.NodeID, repo string) float64 {
  172. var tot int64
  173. m.rmut.RLock()
  174. rf, ok := m.repoFiles[repo]
  175. m.rmut.RUnlock()
  176. if !ok {
  177. return 0 // Repo doesn't exist, so we hardly have any of it
  178. }
  179. rf.WithGlobalTruncated(func(f protocol.FileIntf) bool {
  180. if !f.IsDeleted() {
  181. tot += f.Size()
  182. }
  183. return true
  184. })
  185. if tot == 0 {
  186. return 100 // Repo is empty, so we have all of it
  187. }
  188. var need int64
  189. rf.WithNeedTruncated(node, func(f protocol.FileIntf) bool {
  190. if !f.IsDeleted() {
  191. need += f.Size()
  192. }
  193. return true
  194. })
  195. res := 100 * (1 - float64(need)/float64(tot))
  196. if debug {
  197. l.Debugf("Completion(%s, %q): %f (%d / %d)", node, repo, res, need, tot)
  198. }
  199. return res
  200. }
  201. func sizeOf(fs []protocol.FileInfo) (files, deleted int, bytes int64) {
  202. for _, f := range fs {
  203. fs, de, by := sizeOfFile(f)
  204. files += fs
  205. deleted += de
  206. bytes += by
  207. }
  208. return
  209. }
  210. func sizeOfFile(f protocol.FileIntf) (files, deleted int, bytes int64) {
  211. if !f.IsDeleted() {
  212. files++
  213. } else {
  214. deleted++
  215. }
  216. bytes += f.Size()
  217. return
  218. }
  219. // GlobalSize returns the number of files, deleted files and total bytes for all
  220. // files in the global model.
  221. func (m *Model) GlobalSize(repo string) (files, deleted int, bytes int64) {
  222. m.rmut.RLock()
  223. defer m.rmut.RUnlock()
  224. if rf, ok := m.repoFiles[repo]; ok {
  225. rf.WithGlobalTruncated(func(f protocol.FileIntf) bool {
  226. fs, de, by := sizeOfFile(f)
  227. files += fs
  228. deleted += de
  229. bytes += by
  230. return true
  231. })
  232. }
  233. return
  234. }
  235. // LocalSize returns the number of files, deleted files and total bytes for all
  236. // files in the local repository.
  237. func (m *Model) LocalSize(repo string) (files, deleted int, bytes int64) {
  238. m.rmut.RLock()
  239. defer m.rmut.RUnlock()
  240. if rf, ok := m.repoFiles[repo]; ok {
  241. rf.WithHaveTruncated(protocol.LocalNodeID, func(f protocol.FileIntf) bool {
  242. fs, de, by := sizeOfFile(f)
  243. files += fs
  244. deleted += de
  245. bytes += by
  246. return true
  247. })
  248. }
  249. return
  250. }
  251. // NeedSize returns the number and total size of currently needed files.
  252. func (m *Model) NeedSize(repo string) (files int, bytes int64) {
  253. m.rmut.RLock()
  254. defer m.rmut.RUnlock()
  255. if rf, ok := m.repoFiles[repo]; ok {
  256. rf.WithNeedTruncated(protocol.LocalNodeID, func(f protocol.FileIntf) bool {
  257. fs, de, by := sizeOfFile(f)
  258. files += fs + de
  259. bytes += by
  260. return true
  261. })
  262. }
  263. if debug {
  264. l.Debugf("NeedSize(%q): %d %d", repo, files, bytes)
  265. }
  266. return
  267. }
  268. // NeedFiles returns the list of currently needed files
  269. func (m *Model) NeedFilesRepo(repo string) []protocol.FileInfo {
  270. m.rmut.RLock()
  271. defer m.rmut.RUnlock()
  272. if rf, ok := m.repoFiles[repo]; ok {
  273. fs := make([]protocol.FileInfo, 0, indexBatchSize)
  274. rf.WithNeed(protocol.LocalNodeID, func(f protocol.FileIntf) bool {
  275. fs = append(fs, f.(protocol.FileInfo))
  276. return len(fs) < indexBatchSize
  277. })
  278. return fs
  279. }
  280. return nil
  281. }
  282. // Index is called when a new node is connected and we receive their full index.
  283. // Implements the protocol.Model interface.
  284. func (m *Model) Index(nodeID protocol.NodeID, repo string, fs []protocol.FileInfo) {
  285. if debug {
  286. l.Debugf("IDX(in): %s %q: %d files", nodeID, repo, len(fs))
  287. }
  288. if !m.repoSharedWith(repo, nodeID) {
  289. l.Warnf("Unexpected repository ID %q sent from node %q; ensure that the repository exists and that this node is selected under \"Share With\" in the repository configuration.", repo, nodeID)
  290. return
  291. }
  292. for i := range fs {
  293. lamport.Default.Tick(fs[i].Version)
  294. }
  295. m.rmut.RLock()
  296. r, ok := m.repoFiles[repo]
  297. m.rmut.RUnlock()
  298. if ok {
  299. r.Replace(nodeID, fs)
  300. } else {
  301. l.Fatalf("Index for nonexistant repo %q", repo)
  302. }
  303. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  304. "node": nodeID.String(),
  305. "repo": repo,
  306. "items": len(fs),
  307. "version": r.LocalVersion(nodeID),
  308. })
  309. }
  310. // IndexUpdate is called for incremental updates to connected nodes' indexes.
  311. // Implements the protocol.Model interface.
  312. func (m *Model) IndexUpdate(nodeID protocol.NodeID, repo string, fs []protocol.FileInfo) {
  313. if debug {
  314. l.Debugf("IDXUP(in): %s / %q: %d files", nodeID, repo, len(fs))
  315. }
  316. if !m.repoSharedWith(repo, nodeID) {
  317. l.Infof("Update for unexpected repository ID %q sent from node %q; ensure that the repository exists and that this node is selected under \"Share With\" in the repository configuration.", repo, nodeID)
  318. return
  319. }
  320. for i := range fs {
  321. lamport.Default.Tick(fs[i].Version)
  322. }
  323. m.rmut.RLock()
  324. r, ok := m.repoFiles[repo]
  325. m.rmut.RUnlock()
  326. if ok {
  327. r.Update(nodeID, fs)
  328. } else {
  329. l.Fatalf("IndexUpdate for nonexistant repo %q", repo)
  330. }
  331. events.Default.Log(events.RemoteIndexUpdated, map[string]interface{}{
  332. "node": nodeID.String(),
  333. "repo": repo,
  334. "items": len(fs),
  335. "version": r.LocalVersion(nodeID),
  336. })
  337. }
  338. func (m *Model) repoSharedWith(repo string, nodeID protocol.NodeID) bool {
  339. m.rmut.RLock()
  340. defer m.rmut.RUnlock()
  341. for _, nrepo := range m.nodeRepos[nodeID] {
  342. if nrepo == repo {
  343. return true
  344. }
  345. }
  346. return false
  347. }
  348. func (m *Model) ClusterConfig(nodeID protocol.NodeID, config protocol.ClusterConfigMessage) {
  349. m.pmut.Lock()
  350. if config.ClientName == "syncthing" {
  351. m.nodeVer[nodeID] = config.ClientVersion
  352. } else {
  353. m.nodeVer[nodeID] = config.ClientName + " " + config.ClientVersion
  354. }
  355. m.pmut.Unlock()
  356. l.Infof(`Node %s client is "%s %s"`, nodeID, config.ClientName, config.ClientVersion)
  357. }
  358. // Close removes the peer from the model and closes the underlying connection if possible.
  359. // Implements the protocol.Model interface.
  360. func (m *Model) Close(node protocol.NodeID, err error) {
  361. l.Infof("Connection to %s closed: %v", node, err)
  362. events.Default.Log(events.NodeDisconnected, map[string]string{
  363. "id": node.String(),
  364. "error": err.Error(),
  365. })
  366. m.pmut.Lock()
  367. m.rmut.RLock()
  368. for _, repo := range m.nodeRepos[node] {
  369. m.repoFiles[repo].Replace(node, nil)
  370. }
  371. m.rmut.RUnlock()
  372. conn, ok := m.rawConn[node]
  373. if ok {
  374. conn.Close()
  375. }
  376. delete(m.protoConn, node)
  377. delete(m.rawConn, node)
  378. delete(m.nodeVer, node)
  379. m.pmut.Unlock()
  380. }
  381. // Request returns the specified data segment by reading it from local disk.
  382. // Implements the protocol.Model interface.
  383. func (m *Model) Request(nodeID protocol.NodeID, repo, name string, offset int64, size int) ([]byte, error) {
  384. // Verify that the requested file exists in the local model.
  385. m.rmut.RLock()
  386. r, ok := m.repoFiles[repo]
  387. m.rmut.RUnlock()
  388. if !ok {
  389. l.Warnf("Request from %s for file %s in nonexistent repo %q", nodeID, name, repo)
  390. return nil, ErrNoSuchFile
  391. }
  392. lf := r.Get(protocol.LocalNodeID, name)
  393. if protocol.IsInvalid(lf.Flags) || protocol.IsDeleted(lf.Flags) {
  394. if debug {
  395. l.Debugf("REQ(in): %s: %q / %q o=%d s=%d; invalid: %v", nodeID, repo, name, offset, size, lf)
  396. }
  397. return nil, ErrInvalid
  398. }
  399. if offset > lf.Size() {
  400. if debug {
  401. l.Debugf("REQ(in; nonexistent): %s: %q o=%d s=%d", nodeID, name, offset, size)
  402. }
  403. return nil, ErrNoSuchFile
  404. }
  405. if debug && nodeID != protocol.LocalNodeID {
  406. l.Debugf("REQ(in): %s: %q / %q o=%d s=%d", nodeID, repo, name, offset, size)
  407. }
  408. m.rmut.RLock()
  409. fn := filepath.Join(m.repoCfgs[repo].Directory, name)
  410. m.rmut.RUnlock()
  411. fd, err := os.Open(fn) // XXX: Inefficient, should cache fd?
  412. if err != nil {
  413. return nil, err
  414. }
  415. defer fd.Close()
  416. buf := make([]byte, size)
  417. _, err = fd.ReadAt(buf, offset)
  418. if err != nil {
  419. return nil, err
  420. }
  421. return buf, nil
  422. }
  423. // ReplaceLocal replaces the local repository index with the given list of files.
  424. func (m *Model) ReplaceLocal(repo string, fs []protocol.FileInfo) {
  425. m.rmut.RLock()
  426. m.repoFiles[repo].ReplaceWithDelete(protocol.LocalNodeID, fs)
  427. m.rmut.RUnlock()
  428. }
  429. func (m *Model) CurrentRepoFile(repo string, file string) protocol.FileInfo {
  430. m.rmut.RLock()
  431. f := m.repoFiles[repo].Get(protocol.LocalNodeID, file)
  432. m.rmut.RUnlock()
  433. return f
  434. }
  435. func (m *Model) CurrentGlobalFile(repo string, file string) protocol.FileInfo {
  436. m.rmut.RLock()
  437. f := m.repoFiles[repo].GetGlobal(file)
  438. m.rmut.RUnlock()
  439. return f
  440. }
  441. type cFiler struct {
  442. m *Model
  443. r string
  444. }
  445. // Implements scanner.CurrentFiler
  446. func (cf cFiler) CurrentFile(file string) protocol.FileInfo {
  447. return cf.m.CurrentRepoFile(cf.r, file)
  448. }
  449. // ConnectedTo returns true if we are connected to the named node.
  450. func (m *Model) ConnectedTo(nodeID protocol.NodeID) bool {
  451. m.pmut.RLock()
  452. _, ok := m.protoConn[nodeID]
  453. m.pmut.RUnlock()
  454. return ok
  455. }
  456. // AddConnection adds a new peer connection to the model. An initial index will
  457. // be sent to the connected peer, thereafter index updates whenever the local
  458. // repository changes.
  459. func (m *Model) AddConnection(rawConn io.Closer, protoConn protocol.Connection) {
  460. nodeID := protoConn.ID()
  461. m.pmut.Lock()
  462. if _, ok := m.protoConn[nodeID]; ok {
  463. panic("add existing node")
  464. }
  465. m.protoConn[nodeID] = protoConn
  466. if _, ok := m.rawConn[nodeID]; ok {
  467. panic("add existing node")
  468. }
  469. m.rawConn[nodeID] = rawConn
  470. cm := m.clusterConfig(nodeID)
  471. protoConn.ClusterConfig(cm)
  472. m.rmut.RLock()
  473. for _, repo := range m.nodeRepos[nodeID] {
  474. fs := m.repoFiles[repo]
  475. go sendIndexes(protoConn, repo, fs)
  476. }
  477. m.rmut.RUnlock()
  478. m.pmut.Unlock()
  479. }
  480. func sendIndexes(conn protocol.Connection, repo string, fs *files.Set) {
  481. nodeID := conn.ID()
  482. name := conn.Name()
  483. var err error
  484. if debug {
  485. l.Debugf("sendIndexes for %s-%s@/%q starting", nodeID, name, repo)
  486. }
  487. defer func() {
  488. if debug {
  489. l.Debugf("sendIndexes for %s-%s@/%q exiting: %v", nodeID, name, repo, err)
  490. }
  491. }()
  492. minLocalVer, err := sendIndexTo(true, 0, conn, repo, fs)
  493. for err == nil {
  494. time.Sleep(5 * time.Second)
  495. if fs.LocalVersion(protocol.LocalNodeID) <= minLocalVer {
  496. continue
  497. }
  498. minLocalVer, err = sendIndexTo(false, minLocalVer, conn, repo, fs)
  499. }
  500. }
  501. func sendIndexTo(initial bool, minLocalVer uint64, conn protocol.Connection, repo string, fs *files.Set) (uint64, error) {
  502. nodeID := conn.ID()
  503. name := conn.Name()
  504. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  505. currentBatchSize := 0
  506. maxLocalVer := uint64(0)
  507. var err error
  508. fs.WithHave(protocol.LocalNodeID, func(fi protocol.FileIntf) bool {
  509. f := fi.(protocol.FileInfo)
  510. if f.LocalVersion <= minLocalVer {
  511. return true
  512. }
  513. if f.LocalVersion > maxLocalVer {
  514. maxLocalVer = f.LocalVersion
  515. }
  516. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  517. if initial {
  518. if err = conn.Index(repo, batch); err != nil {
  519. return false
  520. }
  521. if debug {
  522. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", nodeID, name, repo, len(batch), currentBatchSize)
  523. }
  524. initial = false
  525. } else {
  526. if err = conn.IndexUpdate(repo, batch); err != nil {
  527. return false
  528. }
  529. if debug {
  530. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", nodeID, name, repo, len(batch), currentBatchSize)
  531. }
  532. }
  533. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  534. currentBatchSize = 0
  535. }
  536. batch = append(batch, f)
  537. currentBatchSize += indexPerFileSize + len(f.Blocks)*IndexPerBlockSize
  538. return true
  539. })
  540. if initial && err == nil {
  541. err = conn.Index(repo, batch)
  542. if debug && err == nil {
  543. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", nodeID, name, repo, len(batch))
  544. }
  545. } else if len(batch) > 0 && err == nil {
  546. err = conn.IndexUpdate(repo, batch)
  547. if debug && err == nil {
  548. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", nodeID, name, repo, len(batch))
  549. }
  550. }
  551. return maxLocalVer, err
  552. }
  553. func (m *Model) updateLocal(repo string, f protocol.FileInfo) {
  554. f.LocalVersion = 0
  555. m.rmut.RLock()
  556. m.repoFiles[repo].Update(protocol.LocalNodeID, []protocol.FileInfo{f})
  557. m.rmut.RUnlock()
  558. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  559. "repo": repo,
  560. "name": f.Name,
  561. "modified": time.Unix(f.Modified, 0),
  562. "flags": fmt.Sprintf("0%o", f.Flags),
  563. "size": f.Size(),
  564. })
  565. }
  566. func (m *Model) requestGlobal(nodeID protocol.NodeID, repo, name string, offset int64, size int, hash []byte) ([]byte, error) {
  567. m.pmut.RLock()
  568. nc, ok := m.protoConn[nodeID]
  569. m.pmut.RUnlock()
  570. if !ok {
  571. return nil, fmt.Errorf("requestGlobal: no such node: %s", nodeID)
  572. }
  573. if debug {
  574. l.Debugf("REQ(out): %s: %q / %q o=%d s=%d h=%x", nodeID, repo, name, offset, size, hash)
  575. }
  576. return nc.Request(repo, name, offset, size)
  577. }
  578. func (m *Model) AddRepo(cfg config.RepositoryConfiguration) {
  579. if m.started {
  580. panic("cannot add repo to started model")
  581. }
  582. if len(cfg.ID) == 0 {
  583. panic("cannot add empty repo id")
  584. }
  585. m.rmut.Lock()
  586. m.repoCfgs[cfg.ID] = cfg
  587. m.repoFiles[cfg.ID] = files.NewSet(cfg.ID, m.db)
  588. m.repoNodes[cfg.ID] = make([]protocol.NodeID, len(cfg.Nodes))
  589. for i, node := range cfg.Nodes {
  590. m.repoNodes[cfg.ID][i] = node.NodeID
  591. m.nodeRepos[node.NodeID] = append(m.nodeRepos[node.NodeID], cfg.ID)
  592. }
  593. m.addedRepo = true
  594. m.rmut.Unlock()
  595. }
  596. func (m *Model) ScanRepos() {
  597. m.rmut.RLock()
  598. var repos = make([]string, 0, len(m.repoCfgs))
  599. for repo := range m.repoCfgs {
  600. repos = append(repos, repo)
  601. }
  602. m.rmut.RUnlock()
  603. var wg sync.WaitGroup
  604. wg.Add(len(repos))
  605. for _, repo := range repos {
  606. repo := repo
  607. go func() {
  608. err := m.ScanRepo(repo)
  609. if err != nil {
  610. invalidateRepo(m.cfg, repo, err)
  611. }
  612. wg.Done()
  613. }()
  614. }
  615. wg.Wait()
  616. }
  617. func (m *Model) CleanRepos() {
  618. m.rmut.RLock()
  619. var dirs = make([]string, 0, len(m.repoCfgs))
  620. for _, cfg := range m.repoCfgs {
  621. dirs = append(dirs, cfg.Directory)
  622. }
  623. m.rmut.RUnlock()
  624. var wg sync.WaitGroup
  625. wg.Add(len(dirs))
  626. for _, dir := range dirs {
  627. w := &scanner.Walker{
  628. Dir: dir,
  629. TempNamer: defTempNamer,
  630. }
  631. go func() {
  632. w.CleanTempFiles()
  633. wg.Done()
  634. }()
  635. }
  636. wg.Wait()
  637. }
  638. func (m *Model) ScanRepo(repo string) error {
  639. return m.ScanRepoSub(repo, "")
  640. }
  641. func (m *Model) ScanRepoSub(repo, sub string) error {
  642. if p := filepath.Clean(filepath.Join(repo, sub)); !strings.HasPrefix(p, repo) {
  643. return errors.New("invalid subpath")
  644. }
  645. m.rmut.RLock()
  646. fs, ok := m.repoFiles[repo]
  647. dir := m.repoCfgs[repo].Directory
  648. w := &scanner.Walker{
  649. Dir: dir,
  650. Sub: sub,
  651. IgnoreFile: ".stignore",
  652. BlockSize: scanner.StandardBlockSize,
  653. TempNamer: defTempNamer,
  654. CurrentFiler: cFiler{m, repo},
  655. IgnorePerms: m.repoCfgs[repo].IgnorePerms,
  656. }
  657. m.rmut.RUnlock()
  658. if !ok {
  659. return errors.New("no such repo")
  660. }
  661. m.setState(repo, RepoScanning)
  662. fchan, _, err := w.Walk()
  663. if err != nil {
  664. return err
  665. }
  666. batchSize := 100
  667. batch := make([]protocol.FileInfo, 0, 00)
  668. for f := range fchan {
  669. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  670. "repo": repo,
  671. "name": f.Name,
  672. "modified": time.Unix(f.Modified, 0),
  673. "flags": fmt.Sprintf("0%o", f.Flags),
  674. "size": f.Size(),
  675. })
  676. if len(batch) == batchSize {
  677. fs.Update(protocol.LocalNodeID, batch)
  678. batch = batch[:0]
  679. }
  680. batch = append(batch, f)
  681. }
  682. if len(batch) > 0 {
  683. fs.Update(protocol.LocalNodeID, batch)
  684. }
  685. batch = batch[:0]
  686. // TODO: We should limit the Have scanning to start at sub
  687. seenPrefix := false
  688. fs.WithHaveTruncated(protocol.LocalNodeID, func(fi protocol.FileIntf) bool {
  689. f := fi.(protocol.FileInfoTruncated)
  690. if !strings.HasPrefix(f.Name, sub) {
  691. return !seenPrefix
  692. }
  693. seenPrefix = true
  694. if !protocol.IsDeleted(f.Flags) {
  695. if len(batch) == batchSize {
  696. fs.Update(protocol.LocalNodeID, batch)
  697. batch = batch[:0]
  698. }
  699. if _, err := os.Stat(filepath.Join(dir, f.Name)); err != nil && os.IsNotExist(err) {
  700. // File has been deleted
  701. nf := protocol.FileInfo{
  702. Name: f.Name,
  703. Flags: f.Flags | protocol.FlagDeleted,
  704. Modified: f.Modified,
  705. Version: lamport.Default.Tick(f.Version),
  706. }
  707. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  708. "repo": repo,
  709. "name": f.Name,
  710. "modified": time.Unix(f.Modified, 0),
  711. "flags": fmt.Sprintf("0%o", f.Flags),
  712. "size": f.Size(),
  713. })
  714. batch = append(batch, nf)
  715. }
  716. }
  717. return true
  718. })
  719. if len(batch) > 0 {
  720. fs.Update(protocol.LocalNodeID, batch)
  721. }
  722. m.setState(repo, RepoIdle)
  723. return nil
  724. }
  725. // clusterConfig returns a ClusterConfigMessage that is correct for the given peer node
  726. func (m *Model) clusterConfig(node protocol.NodeID) protocol.ClusterConfigMessage {
  727. cm := protocol.ClusterConfigMessage{
  728. ClientName: m.clientName,
  729. ClientVersion: m.clientVersion,
  730. }
  731. m.rmut.RLock()
  732. for _, repo := range m.nodeRepos[node] {
  733. cr := protocol.Repository{
  734. ID: repo,
  735. }
  736. for _, node := range m.repoNodes[repo] {
  737. // TODO: Set read only bit when relevant
  738. cr.Nodes = append(cr.Nodes, protocol.Node{
  739. ID: node[:],
  740. Flags: protocol.FlagShareTrusted,
  741. })
  742. }
  743. cm.Repositories = append(cm.Repositories, cr)
  744. }
  745. m.rmut.RUnlock()
  746. return cm
  747. }
  748. func (m *Model) setState(repo string, state repoState) {
  749. m.smut.Lock()
  750. oldState := m.repoState[repo]
  751. changed, ok := m.repoStateChanged[repo]
  752. if state != oldState {
  753. m.repoState[repo] = state
  754. m.repoStateChanged[repo] = time.Now()
  755. eventData := map[string]interface{}{
  756. "repo": repo,
  757. "to": state.String(),
  758. }
  759. if ok {
  760. eventData["duration"] = time.Since(changed).Seconds()
  761. eventData["from"] = oldState.String()
  762. }
  763. events.Default.Log(events.StateChanged, eventData)
  764. }
  765. m.smut.Unlock()
  766. }
  767. func (m *Model) State(repo string) (string, time.Time) {
  768. m.smut.RLock()
  769. state := m.repoState[repo]
  770. changed := m.repoStateChanged[repo]
  771. m.smut.RUnlock()
  772. return state.String(), changed
  773. }
  774. func (m *Model) Override(repo string) {
  775. m.rmut.RLock()
  776. fs := m.repoFiles[repo]
  777. m.rmut.RUnlock()
  778. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  779. fs.WithNeed(protocol.LocalNodeID, func(fi protocol.FileIntf) bool {
  780. need := fi.(protocol.FileInfo)
  781. if len(batch) == indexBatchSize {
  782. fs.Update(protocol.LocalNodeID, batch)
  783. batch = batch[:0]
  784. }
  785. have := fs.Get(protocol.LocalNodeID, need.Name)
  786. if have.Name != need.Name {
  787. // We are missing the file
  788. need.Flags |= protocol.FlagDeleted
  789. need.Blocks = nil
  790. } else {
  791. // We have the file, replace with our version
  792. need = have
  793. }
  794. need.Version = lamport.Default.Tick(need.Version)
  795. need.LocalVersion = 0
  796. batch = append(batch, need)
  797. return true
  798. })
  799. if len(batch) > 0 {
  800. fs.Update(protocol.LocalNodeID, batch)
  801. }
  802. }
  803. // Version returns the change version for the given repository. This is
  804. // guaranteed to increment if the contents of the local or global repository
  805. // has changed.
  806. func (m *Model) LocalVersion(repo string) uint64 {
  807. m.rmut.Lock()
  808. defer m.rmut.Unlock()
  809. fs, ok := m.repoFiles[repo]
  810. if !ok {
  811. return 0
  812. }
  813. ver := fs.LocalVersion(protocol.LocalNodeID)
  814. for _, n := range m.repoNodes[repo] {
  815. ver += fs.LocalVersion(n)
  816. }
  817. return ver
  818. }