model.go 25 KB

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