model.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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. if statRef, ok := m.nodeStatRefs[nodeID]; ok {
  508. statRef.WasSeen()
  509. } else {
  510. l.Warnf("AddConnection for unconfigured node %v?", nodeID)
  511. }
  512. m.rmut.RUnlock()
  513. m.pmut.Unlock()
  514. }
  515. func sendIndexes(conn protocol.Connection, repo string, fs *files.Set) {
  516. nodeID := conn.ID()
  517. name := conn.Name()
  518. var err error
  519. if debug {
  520. l.Debugf("sendIndexes for %s-%s@/%q starting", nodeID, name, repo)
  521. }
  522. defer func() {
  523. if debug {
  524. l.Debugf("sendIndexes for %s-%s@/%q exiting: %v", nodeID, name, repo, err)
  525. }
  526. }()
  527. minLocalVer, err := sendIndexTo(true, 0, conn, repo, fs)
  528. for err == nil {
  529. time.Sleep(5 * time.Second)
  530. if fs.LocalVersion(protocol.LocalNodeID) <= minLocalVer {
  531. continue
  532. }
  533. minLocalVer, err = sendIndexTo(false, minLocalVer, conn, repo, fs)
  534. }
  535. }
  536. func sendIndexTo(initial bool, minLocalVer uint64, conn protocol.Connection, repo string, fs *files.Set) (uint64, error) {
  537. nodeID := conn.ID()
  538. name := conn.Name()
  539. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  540. currentBatchSize := 0
  541. maxLocalVer := uint64(0)
  542. var err error
  543. fs.WithHave(protocol.LocalNodeID, func(fi protocol.FileIntf) bool {
  544. f := fi.(protocol.FileInfo)
  545. if f.LocalVersion <= minLocalVer {
  546. return true
  547. }
  548. if f.LocalVersion > maxLocalVer {
  549. maxLocalVer = f.LocalVersion
  550. }
  551. if len(batch) == indexBatchSize || currentBatchSize > indexTargetSize {
  552. if initial {
  553. if err = conn.Index(repo, batch); err != nil {
  554. return false
  555. }
  556. if debug {
  557. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (initial index)", nodeID, name, repo, len(batch), currentBatchSize)
  558. }
  559. initial = false
  560. } else {
  561. if err = conn.IndexUpdate(repo, batch); err != nil {
  562. return false
  563. }
  564. if debug {
  565. l.Debugf("sendIndexes for %s-%s/%q: %d files (<%d bytes) (batched update)", nodeID, name, repo, len(batch), currentBatchSize)
  566. }
  567. }
  568. batch = make([]protocol.FileInfo, 0, indexBatchSize)
  569. currentBatchSize = 0
  570. }
  571. batch = append(batch, f)
  572. currentBatchSize += indexPerFileSize + len(f.Blocks)*IndexPerBlockSize
  573. return true
  574. })
  575. if initial && err == nil {
  576. err = conn.Index(repo, batch)
  577. if debug && err == nil {
  578. l.Debugf("sendIndexes for %s-%s/%q: %d files (small initial index)", nodeID, name, repo, len(batch))
  579. }
  580. } else if len(batch) > 0 && err == nil {
  581. err = conn.IndexUpdate(repo, batch)
  582. if debug && err == nil {
  583. l.Debugf("sendIndexes for %s-%s/%q: %d files (last batch)", nodeID, name, repo, len(batch))
  584. }
  585. }
  586. return maxLocalVer, err
  587. }
  588. func (m *Model) updateLocal(repo string, f protocol.FileInfo) {
  589. f.LocalVersion = 0
  590. m.rmut.RLock()
  591. m.repoFiles[repo].Update(protocol.LocalNodeID, []protocol.FileInfo{f})
  592. m.rmut.RUnlock()
  593. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  594. "repo": repo,
  595. "name": f.Name,
  596. "modified": time.Unix(f.Modified, 0),
  597. "flags": fmt.Sprintf("0%o", f.Flags),
  598. "size": f.Size(),
  599. })
  600. }
  601. func (m *Model) requestGlobal(nodeID protocol.NodeID, repo, name string, offset int64, size int, hash []byte) ([]byte, error) {
  602. m.pmut.RLock()
  603. nc, ok := m.protoConn[nodeID]
  604. m.pmut.RUnlock()
  605. if !ok {
  606. return nil, fmt.Errorf("requestGlobal: no such node: %s", nodeID)
  607. }
  608. if debug {
  609. l.Debugf("REQ(out): %s: %q / %q o=%d s=%d h=%x", nodeID, repo, name, offset, size, hash)
  610. }
  611. return nc.Request(repo, name, offset, size)
  612. }
  613. func (m *Model) AddRepo(cfg config.RepositoryConfiguration) {
  614. if m.started {
  615. panic("cannot add repo to started model")
  616. }
  617. if len(cfg.ID) == 0 {
  618. panic("cannot add empty repo id")
  619. }
  620. m.rmut.Lock()
  621. m.repoCfgs[cfg.ID] = cfg
  622. m.repoFiles[cfg.ID] = files.NewSet(cfg.ID, m.db)
  623. m.repoNodes[cfg.ID] = make([]protocol.NodeID, len(cfg.Nodes))
  624. for i, node := range cfg.Nodes {
  625. m.repoNodes[cfg.ID][i] = node.NodeID
  626. m.nodeRepos[node.NodeID] = append(m.nodeRepos[node.NodeID], cfg.ID)
  627. }
  628. m.addedRepo = true
  629. m.rmut.Unlock()
  630. }
  631. func (m *Model) ScanRepos() {
  632. m.rmut.RLock()
  633. var repos = make([]string, 0, len(m.repoCfgs))
  634. for repo := range m.repoCfgs {
  635. repos = append(repos, repo)
  636. }
  637. m.rmut.RUnlock()
  638. var wg sync.WaitGroup
  639. wg.Add(len(repos))
  640. for _, repo := range repos {
  641. repo := repo
  642. go func() {
  643. err := m.ScanRepo(repo)
  644. if err != nil {
  645. invalidateRepo(m.cfg, repo, err)
  646. }
  647. wg.Done()
  648. }()
  649. }
  650. wg.Wait()
  651. }
  652. func (m *Model) CleanRepos() {
  653. m.rmut.RLock()
  654. var dirs = make([]string, 0, len(m.repoCfgs))
  655. for _, cfg := range m.repoCfgs {
  656. dirs = append(dirs, cfg.Directory)
  657. }
  658. m.rmut.RUnlock()
  659. var wg sync.WaitGroup
  660. wg.Add(len(dirs))
  661. for _, dir := range dirs {
  662. w := &scanner.Walker{
  663. Dir: dir,
  664. TempNamer: defTempNamer,
  665. }
  666. go func() {
  667. w.CleanTempFiles()
  668. wg.Done()
  669. }()
  670. }
  671. wg.Wait()
  672. }
  673. func (m *Model) ScanRepo(repo string) error {
  674. return m.ScanRepoSub(repo, "")
  675. }
  676. func (m *Model) ScanRepoSub(repo, sub string) error {
  677. if p := filepath.Clean(filepath.Join(repo, sub)); !strings.HasPrefix(p, repo) {
  678. return errors.New("invalid subpath")
  679. }
  680. m.rmut.RLock()
  681. fs, ok := m.repoFiles[repo]
  682. dir := m.repoCfgs[repo].Directory
  683. w := &scanner.Walker{
  684. Dir: dir,
  685. Sub: sub,
  686. IgnoreFile: ".stignore",
  687. BlockSize: scanner.StandardBlockSize,
  688. TempNamer: defTempNamer,
  689. CurrentFiler: cFiler{m, repo},
  690. IgnorePerms: m.repoCfgs[repo].IgnorePerms,
  691. }
  692. m.rmut.RUnlock()
  693. if !ok {
  694. return errors.New("no such repo")
  695. }
  696. m.setState(repo, RepoScanning)
  697. fchan, err := w.Walk()
  698. if err != nil {
  699. return err
  700. }
  701. batchSize := 100
  702. batch := make([]protocol.FileInfo, 0, 00)
  703. for f := range fchan {
  704. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  705. "repo": repo,
  706. "name": f.Name,
  707. "modified": time.Unix(f.Modified, 0),
  708. "flags": fmt.Sprintf("0%o", f.Flags),
  709. "size": f.Size(),
  710. })
  711. if len(batch) == batchSize {
  712. fs.Update(protocol.LocalNodeID, batch)
  713. batch = batch[:0]
  714. }
  715. batch = append(batch, f)
  716. }
  717. if len(batch) > 0 {
  718. fs.Update(protocol.LocalNodeID, batch)
  719. }
  720. batch = batch[:0]
  721. // TODO: We should limit the Have scanning to start at sub
  722. seenPrefix := false
  723. fs.WithHaveTruncated(protocol.LocalNodeID, func(fi protocol.FileIntf) bool {
  724. f := fi.(protocol.FileInfoTruncated)
  725. if !strings.HasPrefix(f.Name, sub) {
  726. return !seenPrefix
  727. }
  728. seenPrefix = true
  729. if !protocol.IsDeleted(f.Flags) {
  730. if len(batch) == batchSize {
  731. fs.Update(protocol.LocalNodeID, batch)
  732. batch = batch[:0]
  733. }
  734. if _, err := os.Stat(filepath.Join(dir, f.Name)); err != nil && os.IsNotExist(err) {
  735. // File has been deleted
  736. nf := protocol.FileInfo{
  737. Name: f.Name,
  738. Flags: f.Flags | protocol.FlagDeleted,
  739. Modified: f.Modified,
  740. Version: lamport.Default.Tick(f.Version),
  741. }
  742. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  743. "repo": repo,
  744. "name": f.Name,
  745. "modified": time.Unix(f.Modified, 0),
  746. "flags": fmt.Sprintf("0%o", f.Flags),
  747. "size": f.Size(),
  748. })
  749. batch = append(batch, nf)
  750. }
  751. }
  752. return true
  753. })
  754. if len(batch) > 0 {
  755. fs.Update(protocol.LocalNodeID, batch)
  756. }
  757. m.setState(repo, RepoIdle)
  758. return nil
  759. }
  760. // clusterConfig returns a ClusterConfigMessage that is correct for the given peer node
  761. func (m *Model) clusterConfig(node protocol.NodeID) protocol.ClusterConfigMessage {
  762. cm := protocol.ClusterConfigMessage{
  763. ClientName: m.clientName,
  764. ClientVersion: m.clientVersion,
  765. Options: []protocol.Option{
  766. {
  767. Key: "name",
  768. Value: m.nodeName,
  769. },
  770. },
  771. }
  772. m.rmut.RLock()
  773. for _, repo := range m.nodeRepos[node] {
  774. cr := protocol.Repository{
  775. ID: repo,
  776. }
  777. for _, node := range m.repoNodes[repo] {
  778. // TODO: Set read only bit when relevant
  779. cr.Nodes = append(cr.Nodes, protocol.Node{
  780. ID: node[:],
  781. Flags: protocol.FlagShareTrusted,
  782. })
  783. }
  784. cm.Repositories = append(cm.Repositories, cr)
  785. }
  786. m.rmut.RUnlock()
  787. return cm
  788. }
  789. func (m *Model) setState(repo string, state repoState) {
  790. m.smut.Lock()
  791. oldState := m.repoState[repo]
  792. changed, ok := m.repoStateChanged[repo]
  793. if state != oldState {
  794. m.repoState[repo] = state
  795. m.repoStateChanged[repo] = time.Now()
  796. eventData := map[string]interface{}{
  797. "repo": repo,
  798. "to": state.String(),
  799. }
  800. if ok {
  801. eventData["duration"] = time.Since(changed).Seconds()
  802. eventData["from"] = oldState.String()
  803. }
  804. events.Default.Log(events.StateChanged, eventData)
  805. }
  806. m.smut.Unlock()
  807. }
  808. func (m *Model) State(repo string) (string, time.Time) {
  809. m.smut.RLock()
  810. state := m.repoState[repo]
  811. changed := m.repoStateChanged[repo]
  812. m.smut.RUnlock()
  813. return state.String(), changed
  814. }
  815. func (m *Model) Override(repo string) {
  816. m.rmut.RLock()
  817. fs := m.repoFiles[repo]
  818. m.rmut.RUnlock()
  819. batch := make([]protocol.FileInfo, 0, indexBatchSize)
  820. fs.WithNeed(protocol.LocalNodeID, func(fi protocol.FileIntf) bool {
  821. need := fi.(protocol.FileInfo)
  822. if len(batch) == indexBatchSize {
  823. fs.Update(protocol.LocalNodeID, batch)
  824. batch = batch[:0]
  825. }
  826. have := fs.Get(protocol.LocalNodeID, need.Name)
  827. if have.Name != need.Name {
  828. // We are missing the file
  829. need.Flags |= protocol.FlagDeleted
  830. need.Blocks = nil
  831. } else {
  832. // We have the file, replace with our version
  833. need = have
  834. }
  835. need.Version = lamport.Default.Tick(need.Version)
  836. need.LocalVersion = 0
  837. batch = append(batch, need)
  838. return true
  839. })
  840. if len(batch) > 0 {
  841. fs.Update(protocol.LocalNodeID, batch)
  842. }
  843. }
  844. // Version returns the change version for the given repository. This is
  845. // guaranteed to increment if the contents of the local or global repository
  846. // has changed.
  847. func (m *Model) LocalVersion(repo string) uint64 {
  848. m.rmut.Lock()
  849. defer m.rmut.Unlock()
  850. fs, ok := m.repoFiles[repo]
  851. if !ok {
  852. return 0
  853. }
  854. ver := fs.LocalVersion(protocol.LocalNodeID)
  855. for _, n := range m.repoNodes[repo] {
  856. ver += fs.LocalVersion(n)
  857. }
  858. return ver
  859. }