model_test.go 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "bytes"
  9. "context"
  10. "encoding/json"
  11. "fmt"
  12. "io/ioutil"
  13. "math/rand"
  14. "net"
  15. "os"
  16. "path/filepath"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "sync/atomic"
  22. "testing"
  23. "time"
  24. "github.com/syncthing/syncthing/lib/config"
  25. "github.com/syncthing/syncthing/lib/db"
  26. "github.com/syncthing/syncthing/lib/fs"
  27. "github.com/syncthing/syncthing/lib/ignore"
  28. "github.com/syncthing/syncthing/lib/osutil"
  29. "github.com/syncthing/syncthing/lib/protocol"
  30. srand "github.com/syncthing/syncthing/lib/rand"
  31. "github.com/syncthing/syncthing/lib/scanner"
  32. "github.com/syncthing/syncthing/lib/versioner"
  33. )
  34. var device1, device2 protocol.DeviceID
  35. var defaultCfgWrapper *config.Wrapper
  36. var defaultFolderConfig config.FolderConfiguration
  37. var defaultFs fs.Filesystem
  38. var defaultCfg config.Configuration
  39. var defaultAutoAcceptCfg config.Configuration
  40. var tmpLocation string
  41. func init() {
  42. device1, _ = protocol.DeviceIDFromString("AIR6LPZ-7K4PTTV-UXQSMUU-CPQ5YWH-OEDFIIQ-JUG777G-2YQXXR5-YD6AWQR")
  43. device2, _ = protocol.DeviceIDFromString("GYRZZQB-IRNPV4Z-T7TC52W-EQYJ3TT-FDQW6MW-DFLMU42-SSSU6EM-FBK2VAY")
  44. defaultFs = fs.NewFilesystem(fs.FilesystemTypeBasic, "testdata")
  45. defaultFolderConfig = config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, "testdata")
  46. defaultFolderConfig.Devices = []config.FolderDeviceConfiguration{{DeviceID: device1}}
  47. defaultCfg = config.Configuration{
  48. Version: config.CurrentVersion,
  49. Folders: []config.FolderConfiguration{defaultFolderConfig},
  50. Devices: []config.DeviceConfiguration{config.NewDeviceConfiguration(device1, "device1")},
  51. Options: config.OptionsConfiguration{
  52. // Don't remove temporaries directly on startup
  53. KeepTemporariesH: 1,
  54. },
  55. }
  56. defaultAutoAcceptCfg = config.Configuration{
  57. Devices: []config.DeviceConfiguration{
  58. {
  59. DeviceID: protocol.LocalDeviceID, // self
  60. },
  61. {
  62. DeviceID: device1,
  63. AutoAcceptFolders: true,
  64. },
  65. {
  66. DeviceID: device2,
  67. AutoAcceptFolders: true,
  68. },
  69. },
  70. Options: config.OptionsConfiguration{
  71. DefaultFolderPath: "testdata",
  72. },
  73. }
  74. }
  75. var testDataExpected = map[string]protocol.FileInfo{
  76. "foo": {
  77. Name: "foo",
  78. Type: protocol.FileInfoTypeFile,
  79. ModifiedS: 0,
  80. Blocks: []protocol.BlockInfo{{Offset: 0x0, Size: 0x7, Hash: []uint8{0xae, 0xc0, 0x70, 0x64, 0x5f, 0xe5, 0x3e, 0xe3, 0xb3, 0x76, 0x30, 0x59, 0x37, 0x61, 0x34, 0xf0, 0x58, 0xcc, 0x33, 0x72, 0x47, 0xc9, 0x78, 0xad, 0xd1, 0x78, 0xb6, 0xcc, 0xdf, 0xb0, 0x1, 0x9f}}},
  81. },
  82. "empty": {
  83. Name: "empty",
  84. Type: protocol.FileInfoTypeFile,
  85. ModifiedS: 0,
  86. Blocks: []protocol.BlockInfo{{Offset: 0x0, Size: 0x0, Hash: []uint8{0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}}},
  87. },
  88. "bar": {
  89. Name: "bar",
  90. Type: protocol.FileInfoTypeFile,
  91. ModifiedS: 0,
  92. Blocks: []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}},
  93. },
  94. }
  95. func init() {
  96. // Fix expected test data to match reality
  97. for n, f := range testDataExpected {
  98. fi, _ := os.Stat("testdata/" + n)
  99. f.Permissions = uint32(fi.Mode())
  100. f.ModifiedS = fi.ModTime().Unix()
  101. f.Size = fi.Size()
  102. testDataExpected[n] = f
  103. }
  104. }
  105. func TestMain(m *testing.M) {
  106. tmpLocation = "/tmp"
  107. if runtime.GOOS == "windows" {
  108. tmpLocation = filepath.Join("testdata", "tmp")
  109. if err := os.MkdirAll(tmpLocation, 0777); err != nil {
  110. panic(err)
  111. }
  112. }
  113. tmpName := fs.TempName("file")
  114. if err := osutil.Copy(defaultFs, "tmpfile", tmpName); err != nil {
  115. panic(err)
  116. }
  117. future := time.Now().Add(time.Hour)
  118. if err := os.Chtimes(filepath.Join("testdata", tmpName), future, future); err != nil {
  119. panic(err)
  120. }
  121. defaultCfgWrapper = createTmpWrapper(defaultCfg)
  122. exitCode := m.Run()
  123. os.Remove(defaultCfgWrapper.ConfigPath())
  124. defaultFs.Remove(tmpName)
  125. defaultFs.RemoveAll(config.DefaultMarkerName)
  126. defaultFs.RemoveAll(tmpLocation)
  127. os.Exit(exitCode)
  128. }
  129. func createTmpWrapper(cfg config.Configuration) *config.Wrapper {
  130. tmpFile, err := ioutil.TempFile(tmpLocation, "syncthing-testConfig-")
  131. if err != nil {
  132. panic(err)
  133. }
  134. wrapper := config.Wrap(tmpFile.Name(), cfg)
  135. tmpFile.Close()
  136. return wrapper
  137. }
  138. func newState(cfg config.Configuration) (*config.Wrapper, *Model) {
  139. db := db.OpenMemory()
  140. wcfg := createTmpWrapper(cfg)
  141. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  142. for _, folder := range cfg.Folders {
  143. if !folder.Paused {
  144. m.AddFolder(folder)
  145. m.StartFolder(folder.ID)
  146. }
  147. }
  148. m.ServeBackground()
  149. for _, dev := range cfg.Devices {
  150. m.AddConnection(&fakeConnection{id: dev.DeviceID}, protocol.HelloResult{})
  151. }
  152. return wcfg, m
  153. }
  154. func TestRequest(t *testing.T) {
  155. db := db.OpenMemory()
  156. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  157. // device1 shares default, but device2 doesn't
  158. m.AddFolder(defaultFolderConfig)
  159. m.StartFolder("default")
  160. m.ServeBackground()
  161. defer m.Stop()
  162. m.ScanFolder("default")
  163. bs := make([]byte, protocol.MinBlockSize)
  164. // Existing, shared file
  165. bs = bs[:6]
  166. err := m.Request(device1, "default", "foo", 0, nil, 0, false, bs)
  167. if err != nil {
  168. t.Error(err)
  169. }
  170. if !bytes.Equal(bs, []byte("foobar")) {
  171. t.Errorf("Incorrect data from request: %q", string(bs))
  172. }
  173. // Existing, nonshared file
  174. err = m.Request(device2, "default", "foo", 0, nil, 0, false, bs)
  175. if err == nil {
  176. t.Error("Unexpected nil error on insecure file read")
  177. }
  178. // Nonexistent file
  179. err = m.Request(device1, "default", "nonexistent", 0, nil, 0, false, bs)
  180. if err == nil {
  181. t.Error("Unexpected nil error on insecure file read")
  182. }
  183. // Shared folder, but disallowed file name
  184. err = m.Request(device1, "default", "../walk.go", 0, nil, 0, false, bs)
  185. if err == nil {
  186. t.Error("Unexpected nil error on insecure file read")
  187. }
  188. // Negative offset
  189. err = m.Request(device1, "default", "foo", -4, nil, 0, false, bs[:0])
  190. if err == nil {
  191. t.Error("Unexpected nil error on insecure file read")
  192. }
  193. // Larger block than available
  194. bs = bs[:42]
  195. err = m.Request(device1, "default", "foo", 0, nil, 0, false, bs)
  196. if err == nil {
  197. t.Error("Unexpected nil error on insecure file read")
  198. }
  199. }
  200. func genFiles(n int) []protocol.FileInfo {
  201. files := make([]protocol.FileInfo, n)
  202. t := time.Now().Unix()
  203. for i := 0; i < n; i++ {
  204. files[i] = protocol.FileInfo{
  205. Name: fmt.Sprintf("file%d", i),
  206. ModifiedS: t,
  207. Sequence: int64(i + 1),
  208. Blocks: []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}},
  209. Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}},
  210. }
  211. }
  212. return files
  213. }
  214. func BenchmarkIndex_10000(b *testing.B) {
  215. benchmarkIndex(b, 10000)
  216. }
  217. func BenchmarkIndex_100(b *testing.B) {
  218. benchmarkIndex(b, 100)
  219. }
  220. func benchmarkIndex(b *testing.B, nfiles int) {
  221. db := db.OpenMemory()
  222. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  223. m.AddFolder(defaultFolderConfig)
  224. m.StartFolder("default")
  225. m.ServeBackground()
  226. defer m.Stop()
  227. files := genFiles(nfiles)
  228. m.Index(device1, "default", files)
  229. b.ResetTimer()
  230. for i := 0; i < b.N; i++ {
  231. m.Index(device1, "default", files)
  232. }
  233. b.ReportAllocs()
  234. }
  235. func BenchmarkIndexUpdate_10000_10000(b *testing.B) {
  236. benchmarkIndexUpdate(b, 10000, 10000)
  237. }
  238. func BenchmarkIndexUpdate_10000_100(b *testing.B) {
  239. benchmarkIndexUpdate(b, 10000, 100)
  240. }
  241. func BenchmarkIndexUpdate_10000_1(b *testing.B) {
  242. benchmarkIndexUpdate(b, 10000, 1)
  243. }
  244. func benchmarkIndexUpdate(b *testing.B, nfiles, nufiles int) {
  245. db := db.OpenMemory()
  246. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  247. m.AddFolder(defaultFolderConfig)
  248. m.StartFolder("default")
  249. m.ServeBackground()
  250. defer m.Stop()
  251. files := genFiles(nfiles)
  252. ufiles := genFiles(nufiles)
  253. m.Index(device1, "default", files)
  254. b.ResetTimer()
  255. for i := 0; i < b.N; i++ {
  256. m.IndexUpdate(device1, "default", ufiles)
  257. }
  258. b.ReportAllocs()
  259. }
  260. type downloadProgressMessage struct {
  261. folder string
  262. updates []protocol.FileDownloadProgressUpdate
  263. }
  264. type fakeConnection struct {
  265. id protocol.DeviceID
  266. downloadProgressMessages []downloadProgressMessage
  267. closed bool
  268. files []protocol.FileInfo
  269. fileData map[string][]byte
  270. folder string
  271. model *Model
  272. indexFn func(string, []protocol.FileInfo)
  273. requestFn func(folder, name string, offset int64, size int, hash []byte, fromTemporary bool) ([]byte, error)
  274. mut sync.Mutex
  275. }
  276. func (f *fakeConnection) Close() error {
  277. f.mut.Lock()
  278. defer f.mut.Unlock()
  279. f.closed = true
  280. return nil
  281. }
  282. func (f *fakeConnection) Start() {
  283. }
  284. func (f *fakeConnection) ID() protocol.DeviceID {
  285. return f.id
  286. }
  287. func (f *fakeConnection) Name() string {
  288. return ""
  289. }
  290. func (f *fakeConnection) String() string {
  291. return ""
  292. }
  293. func (f *fakeConnection) Option(string) string {
  294. return ""
  295. }
  296. func (f *fakeConnection) Index(folder string, fs []protocol.FileInfo) error {
  297. f.mut.Lock()
  298. defer f.mut.Unlock()
  299. if f.indexFn != nil {
  300. f.indexFn(folder, fs)
  301. }
  302. return nil
  303. }
  304. func (f *fakeConnection) IndexUpdate(folder string, fs []protocol.FileInfo) error {
  305. f.mut.Lock()
  306. defer f.mut.Unlock()
  307. if f.indexFn != nil {
  308. f.indexFn(folder, fs)
  309. }
  310. return nil
  311. }
  312. func (f *fakeConnection) Request(folder, name string, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  313. f.mut.Lock()
  314. defer f.mut.Unlock()
  315. if f.requestFn != nil {
  316. return f.requestFn(folder, name, offset, size, hash, fromTemporary)
  317. }
  318. return f.fileData[name], nil
  319. }
  320. func (f *fakeConnection) ClusterConfig(protocol.ClusterConfig) {}
  321. func (f *fakeConnection) Ping() bool {
  322. f.mut.Lock()
  323. defer f.mut.Unlock()
  324. return f.closed
  325. }
  326. func (f *fakeConnection) Closed() bool {
  327. f.mut.Lock()
  328. defer f.mut.Unlock()
  329. return f.closed
  330. }
  331. func (f *fakeConnection) Statistics() protocol.Statistics {
  332. return protocol.Statistics{}
  333. }
  334. func (f *fakeConnection) RemoteAddr() net.Addr {
  335. return &fakeAddr{}
  336. }
  337. func (f *fakeConnection) Type() string {
  338. return "fake"
  339. }
  340. func (f *fakeConnection) Transport() string {
  341. return "fake"
  342. }
  343. func (f *fakeConnection) Priority() int {
  344. return 9000
  345. }
  346. func (f *fakeConnection) DownloadProgress(folder string, updates []protocol.FileDownloadProgressUpdate) {
  347. f.downloadProgressMessages = append(f.downloadProgressMessages, downloadProgressMessage{
  348. folder: folder,
  349. updates: updates,
  350. })
  351. }
  352. func (f *fakeConnection) addFileLocked(name string, flags uint32, ftype protocol.FileInfoType, data []byte, version protocol.Vector) {
  353. blockSize := protocol.BlockSize(int64(len(data)))
  354. blocks, _ := scanner.Blocks(context.TODO(), bytes.NewReader(data), blockSize, int64(len(data)), nil, true)
  355. if ftype == protocol.FileInfoTypeFile || ftype == protocol.FileInfoTypeDirectory {
  356. f.files = append(f.files, protocol.FileInfo{
  357. Name: name,
  358. Type: ftype,
  359. Size: int64(len(data)),
  360. ModifiedS: time.Now().Unix(),
  361. Permissions: flags,
  362. Version: version,
  363. Sequence: time.Now().UnixNano(),
  364. RawBlockSize: int32(blockSize),
  365. Blocks: blocks,
  366. })
  367. } else {
  368. // Symlink
  369. f.files = append(f.files, protocol.FileInfo{
  370. Name: name,
  371. Type: ftype,
  372. Version: version,
  373. Sequence: time.Now().UnixNano(),
  374. SymlinkTarget: string(data),
  375. NoPermissions: true,
  376. })
  377. }
  378. if f.fileData == nil {
  379. f.fileData = make(map[string][]byte)
  380. }
  381. f.fileData[name] = data
  382. }
  383. func (f *fakeConnection) addFile(name string, flags uint32, ftype protocol.FileInfoType, data []byte) {
  384. f.mut.Lock()
  385. defer f.mut.Unlock()
  386. var version protocol.Vector
  387. version = version.Update(f.id.Short())
  388. f.addFileLocked(name, flags, ftype, data, version)
  389. }
  390. func (f *fakeConnection) updateFile(name string, flags uint32, ftype protocol.FileInfoType, data []byte) {
  391. f.mut.Lock()
  392. defer f.mut.Unlock()
  393. for i, fi := range f.files {
  394. if fi.Name == name {
  395. f.files = append(f.files[:i], f.files[i+1:]...)
  396. f.addFileLocked(name, flags, ftype, data, fi.Version.Update(f.id.Short()))
  397. return
  398. }
  399. }
  400. }
  401. func (f *fakeConnection) deleteFile(name string) {
  402. f.mut.Lock()
  403. defer f.mut.Unlock()
  404. for i, fi := range f.files {
  405. if fi.Name == name {
  406. fi.Deleted = true
  407. fi.ModifiedS = time.Now().Unix()
  408. fi.Version = fi.Version.Update(f.id.Short())
  409. fi.Sequence = time.Now().UnixNano()
  410. fi.Blocks = nil
  411. f.files = append(append(f.files[:i], f.files[i+1:]...), fi)
  412. return
  413. }
  414. }
  415. }
  416. func (f *fakeConnection) sendIndexUpdate() {
  417. f.model.IndexUpdate(f.id, f.folder, f.files)
  418. }
  419. func BenchmarkRequestOut(b *testing.B) {
  420. db := db.OpenMemory()
  421. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  422. m.AddFolder(defaultFolderConfig)
  423. m.ServeBackground()
  424. defer m.Stop()
  425. m.ScanFolder("default")
  426. const n = 1000
  427. files := genFiles(n)
  428. fc := &fakeConnection{id: device1}
  429. for _, f := range files {
  430. fc.addFile(f.Name, 0644, protocol.FileInfoTypeFile, []byte("some data to return"))
  431. }
  432. m.AddConnection(fc, protocol.HelloResult{})
  433. m.Index(device1, "default", files)
  434. b.ResetTimer()
  435. for i := 0; i < b.N; i++ {
  436. data, err := m.requestGlobal(device1, "default", files[i%n].Name, 0, 32, nil, 0, false)
  437. if err != nil {
  438. b.Error(err)
  439. }
  440. if data == nil {
  441. b.Error("nil data")
  442. }
  443. }
  444. }
  445. func BenchmarkRequestInSingleFile(b *testing.B) {
  446. db := db.OpenMemory()
  447. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  448. m.AddFolder(defaultFolderConfig)
  449. m.ServeBackground()
  450. defer m.Stop()
  451. m.ScanFolder("default")
  452. buf := make([]byte, 128<<10)
  453. rand.Read(buf)
  454. os.RemoveAll("testdata/request")
  455. defer os.RemoveAll("testdata/request")
  456. os.MkdirAll("testdata/request/for/a/file/in/a/couple/of/dirs", 0755)
  457. ioutil.WriteFile("testdata/request/for/a/file/in/a/couple/of/dirs/128k", buf, 0644)
  458. b.ResetTimer()
  459. for i := 0; i < b.N; i++ {
  460. if err := m.Request(device1, "default", "request/for/a/file/in/a/couple/of/dirs/128k", 0, nil, 0, false, buf); err != nil {
  461. b.Error(err)
  462. }
  463. }
  464. b.SetBytes(128 << 10)
  465. }
  466. func TestDeviceRename(t *testing.T) {
  467. hello := protocol.HelloResult{
  468. ClientName: "syncthing",
  469. ClientVersion: "v0.9.4",
  470. }
  471. defer os.Remove("testdata/tmpconfig.xml")
  472. rawCfg := config.New(device1)
  473. rawCfg.Devices = []config.DeviceConfiguration{
  474. {
  475. DeviceID: device1,
  476. },
  477. }
  478. cfg := config.Wrap("testdata/tmpconfig.xml", rawCfg)
  479. db := db.OpenMemory()
  480. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  481. if cfg.Devices()[device1].Name != "" {
  482. t.Errorf("Device already has a name")
  483. }
  484. conn := &fakeConnection{id: device1}
  485. m.AddConnection(conn, hello)
  486. m.ServeBackground()
  487. defer m.Stop()
  488. if cfg.Devices()[device1].Name != "" {
  489. t.Errorf("Device already has a name")
  490. }
  491. m.Closed(conn, protocol.ErrTimeout)
  492. hello.DeviceName = "tester"
  493. m.AddConnection(conn, hello)
  494. if cfg.Devices()[device1].Name != "tester" {
  495. t.Errorf("Device did not get a name")
  496. }
  497. m.Closed(conn, protocol.ErrTimeout)
  498. hello.DeviceName = "tester2"
  499. m.AddConnection(conn, hello)
  500. if cfg.Devices()[device1].Name != "tester" {
  501. t.Errorf("Device name got overwritten")
  502. }
  503. cfgw, err := config.Load("testdata/tmpconfig.xml", protocol.LocalDeviceID)
  504. if err != nil {
  505. t.Error(err)
  506. return
  507. }
  508. if cfgw.Devices()[device1].Name != "tester" {
  509. t.Errorf("Device name not saved in config")
  510. }
  511. m.Closed(conn, protocol.ErrTimeout)
  512. opts := cfg.Options()
  513. opts.OverwriteRemoteDevNames = true
  514. cfg.SetOptions(opts)
  515. hello.DeviceName = "tester2"
  516. m.AddConnection(conn, hello)
  517. if cfg.Devices()[device1].Name != "tester2" {
  518. t.Errorf("Device name not overwritten")
  519. }
  520. }
  521. func TestClusterConfig(t *testing.T) {
  522. cfg := config.New(device1)
  523. cfg.Devices = []config.DeviceConfiguration{
  524. {
  525. DeviceID: device1,
  526. Introducer: true,
  527. },
  528. {
  529. DeviceID: device2,
  530. },
  531. }
  532. cfg.Folders = []config.FolderConfiguration{
  533. {
  534. ID: "folder1",
  535. Path: "testdata1",
  536. Devices: []config.FolderDeviceConfiguration{
  537. {DeviceID: device1},
  538. {DeviceID: device2},
  539. },
  540. },
  541. {
  542. ID: "folder2",
  543. Path: "testdata2",
  544. Paused: true, // should still be included
  545. Devices: []config.FolderDeviceConfiguration{
  546. {DeviceID: device1},
  547. {DeviceID: device2},
  548. },
  549. },
  550. {
  551. ID: "folder3",
  552. Path: "testdata3",
  553. Devices: []config.FolderDeviceConfiguration{
  554. {DeviceID: device1},
  555. // should not be included, does not include device2
  556. },
  557. },
  558. }
  559. db := db.OpenMemory()
  560. wrapper := createTmpWrapper(cfg)
  561. defer os.Remove(wrapper.ConfigPath())
  562. m := NewModel(wrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  563. m.AddFolder(cfg.Folders[0])
  564. m.AddFolder(cfg.Folders[1])
  565. m.ServeBackground()
  566. defer m.Stop()
  567. cm := m.generateClusterConfig(device2)
  568. if l := len(cm.Folders); l != 2 {
  569. t.Fatalf("Incorrect number of folders %d != 2", l)
  570. }
  571. r := cm.Folders[0]
  572. if r.ID != "folder1" {
  573. t.Errorf("Incorrect folder %q != folder1", r.ID)
  574. }
  575. if l := len(r.Devices); l != 2 {
  576. t.Errorf("Incorrect number of devices %d != 2", l)
  577. }
  578. if id := r.Devices[0].ID; id != device1 {
  579. t.Errorf("Incorrect device ID %s != %s", id, device1)
  580. }
  581. if !r.Devices[0].Introducer {
  582. t.Error("Device1 should be flagged as Introducer")
  583. }
  584. if id := r.Devices[1].ID; id != device2 {
  585. t.Errorf("Incorrect device ID %s != %s", id, device2)
  586. }
  587. if r.Devices[1].Introducer {
  588. t.Error("Device2 should not be flagged as Introducer")
  589. }
  590. r = cm.Folders[1]
  591. if r.ID != "folder2" {
  592. t.Errorf("Incorrect folder %q != folder2", r.ID)
  593. }
  594. if l := len(r.Devices); l != 2 {
  595. t.Errorf("Incorrect number of devices %d != 2", l)
  596. }
  597. if id := r.Devices[0].ID; id != device1 {
  598. t.Errorf("Incorrect device ID %s != %s", id, device1)
  599. }
  600. if !r.Devices[0].Introducer {
  601. t.Error("Device1 should be flagged as Introducer")
  602. }
  603. if id := r.Devices[1].ID; id != device2 {
  604. t.Errorf("Incorrect device ID %s != %s", id, device2)
  605. }
  606. if r.Devices[1].Introducer {
  607. t.Error("Device2 should not be flagged as Introducer")
  608. }
  609. }
  610. func TestIntroducer(t *testing.T) {
  611. var introducedByAnyone protocol.DeviceID
  612. // LocalDeviceID is a magic value meaning don't check introducer
  613. contains := func(cfg config.FolderConfiguration, id, introducedBy protocol.DeviceID) bool {
  614. for _, dev := range cfg.Devices {
  615. if dev.DeviceID.Equals(id) {
  616. if introducedBy.Equals(introducedByAnyone) {
  617. return true
  618. }
  619. return dev.IntroducedBy.Equals(introducedBy)
  620. }
  621. }
  622. return false
  623. }
  624. wcfg, m := newState(config.Configuration{
  625. Devices: []config.DeviceConfiguration{
  626. {
  627. DeviceID: device1,
  628. Introducer: true,
  629. },
  630. },
  631. Folders: []config.FolderConfiguration{
  632. {
  633. ID: "folder1",
  634. Path: "testdata",
  635. Devices: []config.FolderDeviceConfiguration{
  636. {DeviceID: device1},
  637. },
  638. },
  639. {
  640. ID: "folder2",
  641. Path: "testdata",
  642. Devices: []config.FolderDeviceConfiguration{
  643. {DeviceID: device1},
  644. },
  645. },
  646. },
  647. })
  648. defer os.Remove(wcfg.ConfigPath())
  649. m.ClusterConfig(device1, protocol.ClusterConfig{
  650. Folders: []protocol.Folder{
  651. {
  652. ID: "folder1",
  653. Devices: []protocol.Device{
  654. {
  655. ID: device2,
  656. Introducer: true,
  657. SkipIntroductionRemovals: true,
  658. },
  659. },
  660. },
  661. },
  662. })
  663. if newDev, ok := wcfg.Device(device2); !ok || !newDev.Introducer || !newDev.SkipIntroductionRemovals {
  664. t.Error("devie 2 missing or wrong flags")
  665. }
  666. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  667. t.Error("expected folder 1 to have device2 introduced by device 1")
  668. }
  669. wcfg, m = newState(config.Configuration{
  670. Devices: []config.DeviceConfiguration{
  671. {
  672. DeviceID: device1,
  673. Introducer: true,
  674. },
  675. {
  676. DeviceID: device2,
  677. IntroducedBy: device1,
  678. },
  679. },
  680. Folders: []config.FolderConfiguration{
  681. {
  682. ID: "folder1",
  683. Path: "testdata",
  684. Devices: []config.FolderDeviceConfiguration{
  685. {DeviceID: device1},
  686. {DeviceID: device2, IntroducedBy: device1},
  687. },
  688. },
  689. {
  690. ID: "folder2",
  691. Path: "testdata",
  692. Devices: []config.FolderDeviceConfiguration{
  693. {DeviceID: device1},
  694. },
  695. },
  696. },
  697. })
  698. defer os.Remove(wcfg.ConfigPath())
  699. m.ClusterConfig(device1, protocol.ClusterConfig{
  700. Folders: []protocol.Folder{
  701. {
  702. ID: "folder2",
  703. Devices: []protocol.Device{
  704. {
  705. ID: device2,
  706. Introducer: true,
  707. SkipIntroductionRemovals: true,
  708. },
  709. },
  710. },
  711. },
  712. })
  713. // Should not get introducer, as it's already unset, and it's an existing device.
  714. if newDev, ok := wcfg.Device(device2); !ok || newDev.Introducer || newDev.SkipIntroductionRemovals {
  715. t.Error("device 2 missing or changed flags")
  716. }
  717. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  718. t.Error("expected device 2 to be removed from folder 1")
  719. }
  720. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  721. t.Error("expected device 2 to be added to folder 2")
  722. }
  723. wcfg, m = newState(config.Configuration{
  724. Devices: []config.DeviceConfiguration{
  725. {
  726. DeviceID: device1,
  727. Introducer: true,
  728. },
  729. {
  730. DeviceID: device2,
  731. IntroducedBy: device1,
  732. },
  733. },
  734. Folders: []config.FolderConfiguration{
  735. {
  736. ID: "folder1",
  737. Path: "testdata",
  738. Devices: []config.FolderDeviceConfiguration{
  739. {DeviceID: device1},
  740. {DeviceID: device2, IntroducedBy: device1},
  741. },
  742. },
  743. {
  744. ID: "folder2",
  745. Path: "testdata",
  746. Devices: []config.FolderDeviceConfiguration{
  747. {DeviceID: device1},
  748. {DeviceID: device2, IntroducedBy: device1},
  749. },
  750. },
  751. },
  752. })
  753. defer os.Remove(wcfg.ConfigPath())
  754. m.ClusterConfig(device1, protocol.ClusterConfig{})
  755. if _, ok := wcfg.Device(device2); ok {
  756. t.Error("device 2 should have been removed")
  757. }
  758. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  759. t.Error("expected device 2 to be removed from folder 1")
  760. }
  761. if contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  762. t.Error("expected device 2 to be removed from folder 2")
  763. }
  764. // Two cases when removals should not happen
  765. // 1. Introducer flag no longer set on device
  766. wcfg, m = newState(config.Configuration{
  767. Devices: []config.DeviceConfiguration{
  768. {
  769. DeviceID: device1,
  770. Introducer: false,
  771. },
  772. {
  773. DeviceID: device2,
  774. IntroducedBy: device1,
  775. },
  776. },
  777. Folders: []config.FolderConfiguration{
  778. {
  779. ID: "folder1",
  780. Path: "testdata",
  781. Devices: []config.FolderDeviceConfiguration{
  782. {DeviceID: device1},
  783. {DeviceID: device2, IntroducedBy: device1},
  784. },
  785. },
  786. {
  787. ID: "folder2",
  788. Path: "testdata",
  789. Devices: []config.FolderDeviceConfiguration{
  790. {DeviceID: device1},
  791. {DeviceID: device2, IntroducedBy: device1},
  792. },
  793. },
  794. },
  795. })
  796. defer os.Remove(wcfg.ConfigPath())
  797. m.ClusterConfig(device1, protocol.ClusterConfig{})
  798. if _, ok := wcfg.Device(device2); !ok {
  799. t.Error("device 2 should not have been removed")
  800. }
  801. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  802. t.Error("expected device 2 not to be removed from folder 1")
  803. }
  804. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  805. t.Error("expected device 2 not to be removed from folder 2")
  806. }
  807. // 2. SkipIntroductionRemovals is set
  808. wcfg, m = newState(config.Configuration{
  809. Devices: []config.DeviceConfiguration{
  810. {
  811. DeviceID: device1,
  812. Introducer: true,
  813. SkipIntroductionRemovals: true,
  814. },
  815. {
  816. DeviceID: device2,
  817. IntroducedBy: device1,
  818. },
  819. },
  820. Folders: []config.FolderConfiguration{
  821. {
  822. ID: "folder1",
  823. Path: "testdata",
  824. Devices: []config.FolderDeviceConfiguration{
  825. {DeviceID: device1},
  826. {DeviceID: device2, IntroducedBy: device1},
  827. },
  828. },
  829. {
  830. ID: "folder2",
  831. Path: "testdata",
  832. Devices: []config.FolderDeviceConfiguration{
  833. {DeviceID: device1},
  834. },
  835. },
  836. },
  837. })
  838. defer os.Remove(wcfg.ConfigPath())
  839. m.ClusterConfig(device1, protocol.ClusterConfig{
  840. Folders: []protocol.Folder{
  841. {
  842. ID: "folder2",
  843. Devices: []protocol.Device{
  844. {
  845. ID: device2,
  846. Introducer: true,
  847. SkipIntroductionRemovals: true,
  848. },
  849. },
  850. },
  851. },
  852. })
  853. if _, ok := wcfg.Device(device2); !ok {
  854. t.Error("device 2 should not have been removed")
  855. }
  856. if !contains(wcfg.Folders()["folder1"], device2, device1) {
  857. t.Error("expected device 2 not to be removed from folder 1")
  858. }
  859. if !contains(wcfg.Folders()["folder2"], device2, device1) {
  860. t.Error("expected device 2 not to be added to folder 2")
  861. }
  862. // Test device not being removed as it's shared without an introducer.
  863. wcfg, m = newState(config.Configuration{
  864. Devices: []config.DeviceConfiguration{
  865. {
  866. DeviceID: device1,
  867. Introducer: true,
  868. },
  869. {
  870. DeviceID: device2,
  871. IntroducedBy: device1,
  872. },
  873. },
  874. Folders: []config.FolderConfiguration{
  875. {
  876. ID: "folder1",
  877. Path: "testdata",
  878. Devices: []config.FolderDeviceConfiguration{
  879. {DeviceID: device1},
  880. {DeviceID: device2, IntroducedBy: device1},
  881. },
  882. },
  883. {
  884. ID: "folder2",
  885. Path: "testdata",
  886. Devices: []config.FolderDeviceConfiguration{
  887. {DeviceID: device1},
  888. {DeviceID: device2},
  889. },
  890. },
  891. },
  892. })
  893. defer os.Remove(wcfg.ConfigPath())
  894. m.ClusterConfig(device1, protocol.ClusterConfig{})
  895. if _, ok := wcfg.Device(device2); !ok {
  896. t.Error("device 2 should not have been removed")
  897. }
  898. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  899. t.Error("expected device 2 to be removed from folder 1")
  900. }
  901. if !contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  902. t.Error("expected device 2 not to be removed from folder 2")
  903. }
  904. // Test device not being removed as it's shared by a different introducer.
  905. wcfg, m = newState(config.Configuration{
  906. Devices: []config.DeviceConfiguration{
  907. {
  908. DeviceID: device1,
  909. Introducer: true,
  910. },
  911. {
  912. DeviceID: device2,
  913. IntroducedBy: device1,
  914. },
  915. },
  916. Folders: []config.FolderConfiguration{
  917. {
  918. ID: "folder1",
  919. Path: "testdata",
  920. Devices: []config.FolderDeviceConfiguration{
  921. {DeviceID: device1},
  922. {DeviceID: device2, IntroducedBy: device1},
  923. },
  924. },
  925. {
  926. ID: "folder2",
  927. Path: "testdata",
  928. Devices: []config.FolderDeviceConfiguration{
  929. {DeviceID: device1},
  930. {DeviceID: device2, IntroducedBy: protocol.LocalDeviceID},
  931. },
  932. },
  933. },
  934. })
  935. defer os.Remove(wcfg.ConfigPath())
  936. m.ClusterConfig(device1, protocol.ClusterConfig{})
  937. if _, ok := wcfg.Device(device2); !ok {
  938. t.Error("device 2 should not have been removed")
  939. }
  940. if contains(wcfg.Folders()["folder1"], device2, introducedByAnyone) {
  941. t.Error("expected device 2 to be removed from folder 1")
  942. }
  943. if !contains(wcfg.Folders()["folder2"], device2, introducedByAnyone) {
  944. t.Error("expected device 2 not to be removed from folder 2")
  945. }
  946. }
  947. func TestIssue4897(t *testing.T) {
  948. wcfg, m := newState(config.Configuration{
  949. Devices: []config.DeviceConfiguration{
  950. {
  951. DeviceID: device1,
  952. Introducer: true,
  953. },
  954. },
  955. Folders: []config.FolderConfiguration{
  956. {
  957. ID: "folder1",
  958. Path: "testdata",
  959. Devices: []config.FolderDeviceConfiguration{
  960. {DeviceID: device1},
  961. },
  962. Paused: true,
  963. },
  964. },
  965. })
  966. defer os.Remove(wcfg.ConfigPath())
  967. cm := m.generateClusterConfig(device1)
  968. if l := len(cm.Folders); l != 1 {
  969. t.Errorf("Cluster config contains %v folders, expected 1", l)
  970. }
  971. }
  972. func TestIssue5063(t *testing.T) {
  973. wcfg, m := newState(defaultAutoAcceptCfg)
  974. defer os.Remove(wcfg.ConfigPath())
  975. addAndVerify := func(wg *sync.WaitGroup) {
  976. id := srand.String(8)
  977. m.ClusterConfig(device1, protocol.ClusterConfig{
  978. Folders: []protocol.Folder{
  979. {
  980. ID: id,
  981. Label: id,
  982. },
  983. },
  984. })
  985. os.RemoveAll(filepath.Join("testdata", id))
  986. wg.Done()
  987. if fcfg, ok := wcfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  988. t.Error("expected shared", id)
  989. }
  990. }
  991. wg := &sync.WaitGroup{}
  992. for i := 0; i <= 10; i++ {
  993. wg.Add(1)
  994. go addAndVerify(wg)
  995. }
  996. wg.Wait()
  997. }
  998. func TestAutoAcceptRejected(t *testing.T) {
  999. // Nothing happens if AutoAcceptFolders not set
  1000. tcfg := defaultAutoAcceptCfg.Copy()
  1001. for i := range tcfg.Devices {
  1002. tcfg.Devices[i].AutoAcceptFolders = false
  1003. }
  1004. wcfg, m := newState(tcfg)
  1005. defer os.Remove(wcfg.ConfigPath())
  1006. id := srand.String(8)
  1007. defer os.RemoveAll(filepath.Join("testdata", id))
  1008. m.ClusterConfig(device1, protocol.ClusterConfig{
  1009. Folders: []protocol.Folder{
  1010. {
  1011. ID: id,
  1012. Label: id,
  1013. },
  1014. },
  1015. })
  1016. if cfg, ok := m.cfg.Folder(id); ok && cfg.SharedWith(device1) {
  1017. t.Error("unexpected shared", id)
  1018. }
  1019. }
  1020. func TestAutoAcceptNewFolder(t *testing.T) {
  1021. // New folder
  1022. wcfg, m := newState(defaultAutoAcceptCfg)
  1023. defer os.Remove(wcfg.ConfigPath())
  1024. id := srand.String(8)
  1025. defer os.RemoveAll(filepath.Join("testdata", id))
  1026. m.ClusterConfig(device1, protocol.ClusterConfig{
  1027. Folders: []protocol.Folder{
  1028. {
  1029. ID: id,
  1030. Label: id,
  1031. },
  1032. },
  1033. })
  1034. if fcfg, ok := wcfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1035. t.Error("expected shared", id)
  1036. }
  1037. }
  1038. func TestAutoAcceptNewFolderFromTwoDevices(t *testing.T) {
  1039. wcfg, m := newState(defaultAutoAcceptCfg)
  1040. defer os.Remove(wcfg.ConfigPath())
  1041. id := srand.String(8)
  1042. defer os.RemoveAll(filepath.Join("testdata", id))
  1043. m.ClusterConfig(device1, protocol.ClusterConfig{
  1044. Folders: []protocol.Folder{
  1045. {
  1046. ID: id,
  1047. Label: id,
  1048. },
  1049. },
  1050. })
  1051. if fcfg, ok := wcfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1052. t.Error("expected shared", id)
  1053. }
  1054. if fcfg, ok := wcfg.Folder(id); !ok || fcfg.SharedWith(device2) {
  1055. t.Error("unexpected expected shared", id)
  1056. }
  1057. m.ClusterConfig(device2, protocol.ClusterConfig{
  1058. Folders: []protocol.Folder{
  1059. {
  1060. ID: id,
  1061. Label: id,
  1062. },
  1063. },
  1064. })
  1065. if fcfg, ok := wcfg.Folder(id); !ok || !fcfg.SharedWith(device2) {
  1066. t.Error("expected shared", id)
  1067. }
  1068. m.Stop()
  1069. }
  1070. func TestAutoAcceptNewFolderFromOnlyOneDevice(t *testing.T) {
  1071. modifiedCfg := defaultAutoAcceptCfg.Copy()
  1072. modifiedCfg.Devices[2].AutoAcceptFolders = false
  1073. wcfg, m := newState(modifiedCfg)
  1074. defer os.Remove(wcfg.ConfigPath())
  1075. id := srand.String(8)
  1076. defer os.RemoveAll(filepath.Join("testdata", id))
  1077. m.ClusterConfig(device1, protocol.ClusterConfig{
  1078. Folders: []protocol.Folder{
  1079. {
  1080. ID: id,
  1081. Label: id,
  1082. },
  1083. },
  1084. })
  1085. if fcfg, ok := wcfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1086. t.Error("expected shared", id)
  1087. }
  1088. if fcfg, ok := wcfg.Folder(id); !ok || fcfg.SharedWith(device2) {
  1089. t.Error("unexpected expected shared", id)
  1090. }
  1091. m.ClusterConfig(device2, protocol.ClusterConfig{
  1092. Folders: []protocol.Folder{
  1093. {
  1094. ID: id,
  1095. Label: id,
  1096. },
  1097. },
  1098. })
  1099. if fcfg, ok := wcfg.Folder(id); !ok || fcfg.SharedWith(device2) {
  1100. t.Error("unexpected shared", id)
  1101. }
  1102. m.Stop()
  1103. }
  1104. func TestAutoAcceptNewFolderPremutationsNoPanic(t *testing.T) {
  1105. if testing.Short() {
  1106. t.Skip("short tests only")
  1107. }
  1108. id := srand.String(8)
  1109. label := srand.String(8)
  1110. premutations := []protocol.Folder{
  1111. {ID: id, Label: id},
  1112. {ID: id, Label: label},
  1113. {ID: label, Label: id},
  1114. {ID: label, Label: label},
  1115. }
  1116. localFolders := append(premutations, protocol.Folder{})
  1117. for _, localFolder := range localFolders {
  1118. for _, localFolderPaused := range []bool{false, true} {
  1119. for _, dev1folder := range premutations {
  1120. for _, dev2folder := range premutations {
  1121. cfg := defaultAutoAcceptCfg.Copy()
  1122. if localFolder.Label != "" {
  1123. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, localFolder.ID, localFolder.Label, fs.FilesystemTypeBasic, filepath.Join("testdata", localFolder.ID))
  1124. fcfg.Paused = localFolderPaused
  1125. cfg.Folders = append(cfg.Folders, fcfg)
  1126. }
  1127. wcfg, m := newState(cfg)
  1128. defer os.Remove(wcfg.ConfigPath())
  1129. m.ClusterConfig(device1, protocol.ClusterConfig{
  1130. Folders: []protocol.Folder{dev1folder},
  1131. })
  1132. m.ClusterConfig(device2, protocol.ClusterConfig{
  1133. Folders: []protocol.Folder{dev2folder},
  1134. })
  1135. m.Stop()
  1136. os.RemoveAll(filepath.Join("testdata", id))
  1137. os.RemoveAll(filepath.Join("testdata", label))
  1138. }
  1139. }
  1140. }
  1141. }
  1142. }
  1143. func TestAutoAcceptMultipleFolders(t *testing.T) {
  1144. // Multiple new folders
  1145. wcfg, m := newState(defaultAutoAcceptCfg)
  1146. defer os.Remove(wcfg.ConfigPath())
  1147. id1 := srand.String(8)
  1148. defer os.RemoveAll(filepath.Join("testdata", id1))
  1149. id2 := srand.String(8)
  1150. defer os.RemoveAll(filepath.Join("testdata", id2))
  1151. m.ClusterConfig(device1, protocol.ClusterConfig{
  1152. Folders: []protocol.Folder{
  1153. {
  1154. ID: id1,
  1155. Label: id1,
  1156. },
  1157. {
  1158. ID: id2,
  1159. Label: id2,
  1160. },
  1161. },
  1162. })
  1163. if fcfg, ok := wcfg.Folder(id1); !ok || !fcfg.SharedWith(device1) {
  1164. t.Error("expected shared", id1)
  1165. }
  1166. if fcfg, ok := wcfg.Folder(id2); !ok || !fcfg.SharedWith(device1) {
  1167. t.Error("expected shared", id2)
  1168. }
  1169. }
  1170. func TestAutoAcceptExistingFolder(t *testing.T) {
  1171. // Existing folder
  1172. id := srand.String(8)
  1173. idOther := srand.String(8) // To check that path does not get changed.
  1174. defer os.RemoveAll(filepath.Join("testdata", id))
  1175. defer os.RemoveAll(filepath.Join("testdata", idOther))
  1176. tcfg := defaultAutoAcceptCfg.Copy()
  1177. tcfg.Folders = []config.FolderConfiguration{
  1178. {
  1179. ID: id,
  1180. Path: filepath.Join("testdata", idOther), // To check that path does not get changed.
  1181. },
  1182. }
  1183. wcfg, m := newState(tcfg)
  1184. defer os.Remove(wcfg.ConfigPath())
  1185. if fcfg, ok := wcfg.Folder(id); !ok || fcfg.SharedWith(device1) {
  1186. t.Error("missing folder, or shared", id)
  1187. }
  1188. m.ClusterConfig(device1, protocol.ClusterConfig{
  1189. Folders: []protocol.Folder{
  1190. {
  1191. ID: id,
  1192. Label: id,
  1193. },
  1194. },
  1195. })
  1196. if fcfg, ok := wcfg.Folder(id); !ok || !fcfg.SharedWith(device1) || fcfg.Path != filepath.Join("testdata", idOther) {
  1197. t.Error("missing folder, or unshared, or path changed", id)
  1198. }
  1199. }
  1200. func TestAutoAcceptNewAndExistingFolder(t *testing.T) {
  1201. // New and existing folder
  1202. id1 := srand.String(8)
  1203. defer os.RemoveAll(filepath.Join("testdata", id1))
  1204. id2 := srand.String(8)
  1205. defer os.RemoveAll(filepath.Join("testdata", id2))
  1206. tcfg := defaultAutoAcceptCfg.Copy()
  1207. tcfg.Folders = []config.FolderConfiguration{
  1208. {
  1209. ID: id1,
  1210. Path: filepath.Join("testdata", id1), // from previous test case, to verify that path doesn't get changed.
  1211. },
  1212. }
  1213. wcfg, m := newState(tcfg)
  1214. defer os.Remove(wcfg.ConfigPath())
  1215. if fcfg, ok := wcfg.Folder(id1); !ok || fcfg.SharedWith(device1) {
  1216. t.Error("missing folder, or shared", id1)
  1217. }
  1218. m.ClusterConfig(device1, protocol.ClusterConfig{
  1219. Folders: []protocol.Folder{
  1220. {
  1221. ID: id1,
  1222. Label: id1,
  1223. },
  1224. {
  1225. ID: id2,
  1226. Label: id2,
  1227. },
  1228. },
  1229. })
  1230. for i, id := range []string{id1, id2} {
  1231. if fcfg, ok := wcfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1232. t.Error("missing folder, or unshared", i, id)
  1233. }
  1234. }
  1235. }
  1236. func TestAutoAcceptAlreadyShared(t *testing.T) {
  1237. // Already shared
  1238. id := srand.String(8)
  1239. defer os.RemoveAll(filepath.Join("testdata", id))
  1240. tcfg := defaultAutoAcceptCfg.Copy()
  1241. tcfg.Folders = []config.FolderConfiguration{
  1242. {
  1243. ID: id,
  1244. Path: filepath.Join("testdata", id),
  1245. Devices: []config.FolderDeviceConfiguration{
  1246. {
  1247. DeviceID: device1,
  1248. },
  1249. },
  1250. },
  1251. }
  1252. wcfg, m := newState(tcfg)
  1253. defer os.Remove(wcfg.ConfigPath())
  1254. if fcfg, ok := wcfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1255. t.Error("missing folder, or not shared", id)
  1256. }
  1257. m.ClusterConfig(device1, protocol.ClusterConfig{
  1258. Folders: []protocol.Folder{
  1259. {
  1260. ID: id,
  1261. Label: id,
  1262. },
  1263. },
  1264. })
  1265. if fcfg, ok := wcfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1266. t.Error("missing folder, or not shared", id)
  1267. }
  1268. }
  1269. func TestAutoAcceptNameConflict(t *testing.T) {
  1270. id := srand.String(8)
  1271. label := srand.String(8)
  1272. os.MkdirAll(filepath.Join("testdata", id), 0777)
  1273. os.MkdirAll(filepath.Join("testdata", label), 0777)
  1274. defer os.RemoveAll(filepath.Join("testdata", id))
  1275. defer os.RemoveAll(filepath.Join("testdata", label))
  1276. wcfg, m := newState(defaultAutoAcceptCfg)
  1277. defer os.Remove(wcfg.ConfigPath())
  1278. m.ClusterConfig(device1, protocol.ClusterConfig{
  1279. Folders: []protocol.Folder{
  1280. {
  1281. ID: id,
  1282. Label: label,
  1283. },
  1284. },
  1285. })
  1286. if fcfg, ok := wcfg.Folder(id); ok && fcfg.SharedWith(device1) {
  1287. t.Error("unexpected folder", id)
  1288. }
  1289. }
  1290. func TestAutoAcceptPrefersLabel(t *testing.T) {
  1291. // Prefers label, falls back to ID.
  1292. wcfg, m := newState(defaultAutoAcceptCfg)
  1293. defer os.Remove(wcfg.ConfigPath())
  1294. id := srand.String(8)
  1295. label := srand.String(8)
  1296. defer os.RemoveAll(filepath.Join("testdata", id))
  1297. defer os.RemoveAll(filepath.Join("testdata", label))
  1298. m.ClusterConfig(device1, protocol.ClusterConfig{
  1299. Folders: []protocol.Folder{
  1300. {
  1301. ID: id,
  1302. Label: label,
  1303. },
  1304. },
  1305. })
  1306. if fcfg, ok := wcfg.Folder(id); !ok || !fcfg.SharedWith(device1) || !strings.HasSuffix(fcfg.Path, label) {
  1307. t.Error("expected shared, or wrong path", id, label, fcfg.Path)
  1308. }
  1309. }
  1310. func TestAutoAcceptFallsBackToID(t *testing.T) {
  1311. // Prefers label, falls back to ID.
  1312. wcfg, m := newState(defaultAutoAcceptCfg)
  1313. defer os.Remove(wcfg.ConfigPath())
  1314. id := srand.String(8)
  1315. label := srand.String(8)
  1316. os.MkdirAll(filepath.Join("testdata", label), 0777)
  1317. defer os.RemoveAll(filepath.Join("testdata", label))
  1318. defer os.RemoveAll(filepath.Join("testdata", id))
  1319. m.ClusterConfig(device1, protocol.ClusterConfig{
  1320. Folders: []protocol.Folder{
  1321. {
  1322. ID: id,
  1323. Label: label,
  1324. },
  1325. },
  1326. })
  1327. if fcfg, ok := wcfg.Folder(id); !ok || !fcfg.SharedWith(device1) || !strings.HasSuffix(fcfg.Path, id) {
  1328. t.Error("expected shared, or wrong path", id, label, fcfg.Path)
  1329. }
  1330. }
  1331. func TestAutoAcceptPausedWhenFolderConfigChanged(t *testing.T) {
  1332. // Existing folder
  1333. id := srand.String(8)
  1334. idOther := srand.String(8) // To check that path does not get changed.
  1335. defer os.RemoveAll(filepath.Join("testdata", id))
  1336. defer os.RemoveAll(filepath.Join("testdata", idOther))
  1337. tcfg := defaultAutoAcceptCfg.Copy()
  1338. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, id, "", fs.FilesystemTypeBasic, filepath.Join("testdata", idOther))
  1339. fcfg.Paused = true
  1340. // The order of devices here is wrong (cfg.clean() sorts them), which will cause the folder to restart.
  1341. // Because of the restart, folder gets removed from m.deviceFolder, which means that generateClusterConfig will not panic.
  1342. // This wasn't an issue before, yet keeping the test case to prove that it still isn't.
  1343. fcfg.Devices = append(fcfg.Devices, config.FolderDeviceConfiguration{
  1344. DeviceID: device1,
  1345. })
  1346. tcfg.Folders = []config.FolderConfiguration{fcfg}
  1347. wcfg, m := newState(tcfg)
  1348. defer os.Remove(wcfg.ConfigPath())
  1349. if fcfg, ok := wcfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1350. t.Error("missing folder, or not shared", id)
  1351. }
  1352. if _, ok := m.folderRunners[id]; ok {
  1353. t.Fatal("folder running?")
  1354. }
  1355. m.ClusterConfig(device1, protocol.ClusterConfig{
  1356. Folders: []protocol.Folder{
  1357. {
  1358. ID: id,
  1359. Label: id,
  1360. },
  1361. },
  1362. })
  1363. m.generateClusterConfig(device1)
  1364. if fcfg, ok := wcfg.Folder(id); !ok {
  1365. t.Error("missing folder")
  1366. } else if fcfg.Path != filepath.Join("testdata", idOther) {
  1367. t.Error("folder path changed")
  1368. } else {
  1369. for _, dev := range fcfg.DeviceIDs() {
  1370. if dev == device1 {
  1371. return
  1372. }
  1373. }
  1374. t.Error("device missing")
  1375. }
  1376. if _, ok := m.folderRunners[id]; ok {
  1377. t.Error("folder started")
  1378. }
  1379. }
  1380. func TestAutoAcceptPausedWhenFolderConfigNotChanged(t *testing.T) {
  1381. // Existing folder
  1382. id := srand.String(8)
  1383. idOther := srand.String(8) // To check that path does not get changed.
  1384. defer os.RemoveAll(filepath.Join("testdata", id))
  1385. defer os.RemoveAll(filepath.Join("testdata", idOther))
  1386. tcfg := defaultAutoAcceptCfg.Copy()
  1387. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, id, "", fs.FilesystemTypeBasic, filepath.Join("testdata", idOther))
  1388. fcfg.Paused = true
  1389. // The new folder is exactly the same as the one constructed by handleAutoAccept, which means
  1390. // the folder will not be restarted (even if it's paused), yet handleAutoAccept used to add the folder
  1391. // to m.deviceFolders which had caused panics when calling generateClusterConfig, as the folder
  1392. // did not have a file set.
  1393. fcfg.Devices = append([]config.FolderDeviceConfiguration{
  1394. {
  1395. DeviceID: device1,
  1396. },
  1397. }, fcfg.Devices...) // Need to ensure this device order to avoid folder restart.
  1398. tcfg.Folders = []config.FolderConfiguration{fcfg}
  1399. wcfg, m := newState(tcfg)
  1400. defer os.Remove(wcfg.ConfigPath())
  1401. if fcfg, ok := wcfg.Folder(id); !ok || !fcfg.SharedWith(device1) {
  1402. t.Error("missing folder, or not shared", id)
  1403. }
  1404. if _, ok := m.folderRunners[id]; ok {
  1405. t.Fatal("folder running?")
  1406. }
  1407. m.ClusterConfig(device1, protocol.ClusterConfig{
  1408. Folders: []protocol.Folder{
  1409. {
  1410. ID: id,
  1411. Label: id,
  1412. },
  1413. },
  1414. })
  1415. m.generateClusterConfig(device1)
  1416. if fcfg, ok := wcfg.Folder(id); !ok {
  1417. t.Error("missing folder")
  1418. } else if fcfg.Path != filepath.Join("testdata", idOther) {
  1419. t.Error("folder path changed")
  1420. } else {
  1421. for _, dev := range fcfg.DeviceIDs() {
  1422. if dev == device1 {
  1423. return
  1424. }
  1425. }
  1426. t.Error("device missing")
  1427. }
  1428. if _, ok := m.folderRunners[id]; ok {
  1429. t.Error("folder started")
  1430. }
  1431. }
  1432. func changeIgnores(t *testing.T, m *Model, expected []string) {
  1433. arrEqual := func(a, b []string) bool {
  1434. if len(a) != len(b) {
  1435. return false
  1436. }
  1437. for i := range a {
  1438. if a[i] != b[i] {
  1439. return false
  1440. }
  1441. }
  1442. return true
  1443. }
  1444. ignores, _, err := m.GetIgnores("default")
  1445. if err != nil {
  1446. t.Error(err)
  1447. }
  1448. if !arrEqual(ignores, expected) {
  1449. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  1450. }
  1451. ignores = append(ignores, "pox")
  1452. err = m.SetIgnores("default", ignores)
  1453. if err != nil {
  1454. t.Error(err)
  1455. }
  1456. ignores2, _, err := m.GetIgnores("default")
  1457. if err != nil {
  1458. t.Error(err)
  1459. }
  1460. if !arrEqual(ignores, ignores2) {
  1461. t.Errorf("Incorrect ignores: %v != %v", ignores2, ignores)
  1462. }
  1463. if runtime.GOOS == "darwin" {
  1464. // see above
  1465. time.Sleep(time.Second)
  1466. } else {
  1467. time.Sleep(time.Millisecond)
  1468. }
  1469. err = m.SetIgnores("default", expected)
  1470. if err != nil {
  1471. t.Error(err)
  1472. }
  1473. ignores, _, err = m.GetIgnores("default")
  1474. if err != nil {
  1475. t.Error(err)
  1476. }
  1477. if !arrEqual(ignores, expected) {
  1478. t.Errorf("Incorrect ignores: %v != %v", ignores, expected)
  1479. }
  1480. }
  1481. func TestIgnores(t *testing.T) {
  1482. // Assure a clean start state
  1483. os.RemoveAll(filepath.Join("testdata", config.DefaultMarkerName))
  1484. os.MkdirAll(filepath.Join("testdata", config.DefaultMarkerName), 0644)
  1485. ioutil.WriteFile("testdata/.stignore", []byte(".*\nquux\n"), 0644)
  1486. db := db.OpenMemory()
  1487. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1488. m.ServeBackground()
  1489. defer m.Stop()
  1490. // m.cfg.SetFolder is not usable as it is non-blocking, and there is no
  1491. // way to know when the folder is actually added.
  1492. m.AddFolder(defaultFolderConfig)
  1493. m.StartFolder("default")
  1494. // Reach in and update the ignore matcher to one that always does
  1495. // reloads when asked to, instead of checking file mtimes. This is
  1496. // because we will be changing the files on disk often enough that the
  1497. // mtimes will be unreliable to determine change status.
  1498. m.fmut.Lock()
  1499. m.folderIgnores["default"] = ignore.New(defaultFs, ignore.WithCache(true), ignore.WithChangeDetector(newAlwaysChanged()))
  1500. m.fmut.Unlock()
  1501. // Make sure the initial scan has finished (ScanFolders is blocking)
  1502. m.ScanFolders()
  1503. expected := []string{
  1504. ".*",
  1505. "quux",
  1506. }
  1507. changeIgnores(t, m, expected)
  1508. _, _, err := m.GetIgnores("doesnotexist")
  1509. if err == nil {
  1510. t.Error("No error")
  1511. }
  1512. err = m.SetIgnores("doesnotexist", expected)
  1513. if err == nil {
  1514. t.Error("No error")
  1515. }
  1516. // Invalid path, marker should be missing, hence returns an error.
  1517. m.AddFolder(config.FolderConfiguration{ID: "fresh", Path: "XXX"})
  1518. _, _, err = m.GetIgnores("fresh")
  1519. if err == nil {
  1520. t.Error("No error")
  1521. }
  1522. // Repeat tests with paused folder
  1523. pausedDefaultFolderConfig := defaultFolderConfig
  1524. pausedDefaultFolderConfig.Paused = true
  1525. m.RestartFolder(defaultFolderConfig, pausedDefaultFolderConfig)
  1526. // Here folder initialization is not an issue as a paused folder isn't
  1527. // added to the model and thus there is no initial scan happening.
  1528. changeIgnores(t, m, expected)
  1529. // Make sure no .stignore file is considered valid
  1530. os.Rename("testdata/.stignore", "testdata/.stignore.bak")
  1531. changeIgnores(t, m, []string{})
  1532. os.Rename("testdata/.stignore.bak", "testdata/.stignore")
  1533. }
  1534. func TestROScanRecovery(t *testing.T) {
  1535. ldb := db.OpenMemory()
  1536. set := db.NewFileSet("default", defaultFs, ldb)
  1537. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  1538. {Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
  1539. })
  1540. fcfg := config.FolderConfiguration{
  1541. ID: "default",
  1542. Path: "testdata/rotestfolder",
  1543. Type: config.FolderTypeSendOnly,
  1544. RescanIntervalS: 1,
  1545. MarkerName: config.DefaultMarkerName,
  1546. }
  1547. cfg := createTmpWrapper(config.Configuration{
  1548. Folders: []config.FolderConfiguration{fcfg},
  1549. Devices: []config.DeviceConfiguration{
  1550. {
  1551. DeviceID: device1,
  1552. },
  1553. },
  1554. })
  1555. defer os.Remove(cfg.ConfigPath())
  1556. os.RemoveAll(fcfg.Path)
  1557. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  1558. m.AddFolder(fcfg)
  1559. m.StartFolder("default")
  1560. m.ServeBackground()
  1561. defer m.Stop()
  1562. waitFor := func(status string) error {
  1563. timeout := time.Now().Add(2 * time.Second)
  1564. for {
  1565. _, _, err := m.State("default")
  1566. if err == nil && status == "" {
  1567. return nil
  1568. }
  1569. if err != nil && err.Error() == status {
  1570. return nil
  1571. }
  1572. if time.Now().After(timeout) {
  1573. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  1574. }
  1575. time.Sleep(10 * time.Millisecond)
  1576. }
  1577. }
  1578. if err := waitFor("folder path missing"); err != nil {
  1579. t.Error(err)
  1580. return
  1581. }
  1582. os.Mkdir(fcfg.Path, 0700)
  1583. if err := waitFor("folder marker missing"); err != nil {
  1584. t.Error(err)
  1585. return
  1586. }
  1587. fd, err := os.Create(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1588. if err != nil {
  1589. t.Error(err)
  1590. return
  1591. }
  1592. fd.Close()
  1593. if err := waitFor(""); err != nil {
  1594. t.Error(err)
  1595. return
  1596. }
  1597. os.Remove(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1598. if err := waitFor("folder marker missing"); err != nil {
  1599. t.Error(err)
  1600. return
  1601. }
  1602. os.Remove(fcfg.Path)
  1603. if err := waitFor("folder path missing"); err != nil {
  1604. t.Error(err)
  1605. return
  1606. }
  1607. }
  1608. func TestRWScanRecovery(t *testing.T) {
  1609. ldb := db.OpenMemory()
  1610. set := db.NewFileSet("default", defaultFs, ldb)
  1611. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  1612. {Name: "dummyfile", Version: protocol.Vector{Counters: []protocol.Counter{{ID: 42, Value: 1}}}},
  1613. })
  1614. fcfg := config.FolderConfiguration{
  1615. ID: "default",
  1616. Path: "testdata/rwtestfolder",
  1617. Type: config.FolderTypeSendReceive,
  1618. RescanIntervalS: 1,
  1619. MarkerName: config.DefaultMarkerName,
  1620. }
  1621. cfg := createTmpWrapper(config.Configuration{
  1622. Folders: []config.FolderConfiguration{fcfg},
  1623. Devices: []config.DeviceConfiguration{
  1624. {
  1625. DeviceID: device1,
  1626. },
  1627. },
  1628. })
  1629. defer os.Remove(cfg.ConfigPath())
  1630. os.RemoveAll(fcfg.Path)
  1631. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  1632. m.AddFolder(fcfg)
  1633. m.StartFolder("default")
  1634. m.ServeBackground()
  1635. defer m.Stop()
  1636. waitFor := func(status string) error {
  1637. timeout := time.Now().Add(2 * time.Second)
  1638. for {
  1639. _, _, err := m.State("default")
  1640. if err == nil && status == "" {
  1641. return nil
  1642. }
  1643. if err != nil && err.Error() == status {
  1644. return nil
  1645. }
  1646. if time.Now().After(timeout) {
  1647. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  1648. }
  1649. time.Sleep(10 * time.Millisecond)
  1650. }
  1651. }
  1652. if err := waitFor("folder path missing"); err != nil {
  1653. t.Error(err)
  1654. return
  1655. }
  1656. os.Mkdir(fcfg.Path, 0700)
  1657. if err := waitFor("folder marker missing"); err != nil {
  1658. t.Error(err)
  1659. return
  1660. }
  1661. fd, err := os.Create(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1662. if err != nil {
  1663. t.Error(err)
  1664. return
  1665. }
  1666. fd.Close()
  1667. if err := waitFor(""); err != nil {
  1668. t.Error(err)
  1669. return
  1670. }
  1671. os.Remove(filepath.Join(fcfg.Path, config.DefaultMarkerName))
  1672. if err := waitFor("folder marker missing"); err != nil {
  1673. t.Error(err)
  1674. return
  1675. }
  1676. os.Remove(fcfg.Path)
  1677. if err := waitFor("folder path missing"); err != nil {
  1678. t.Error(err)
  1679. return
  1680. }
  1681. }
  1682. func TestGlobalDirectoryTree(t *testing.T) {
  1683. db := db.OpenMemory()
  1684. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1685. m.AddFolder(defaultFolderConfig)
  1686. m.ServeBackground()
  1687. defer m.Stop()
  1688. b := func(isfile bool, path ...string) protocol.FileInfo {
  1689. typ := protocol.FileInfoTypeDirectory
  1690. blocks := []protocol.BlockInfo{}
  1691. if isfile {
  1692. typ = protocol.FileInfoTypeFile
  1693. blocks = []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}}
  1694. }
  1695. return protocol.FileInfo{
  1696. Name: filepath.Join(path...),
  1697. Type: typ,
  1698. ModifiedS: 0x666,
  1699. Blocks: blocks,
  1700. Size: 0xa,
  1701. }
  1702. }
  1703. filedata := []interface{}{time.Unix(0x666, 0), 0xa}
  1704. testdata := []protocol.FileInfo{
  1705. b(false, "another"),
  1706. b(false, "another", "directory"),
  1707. b(true, "another", "directory", "afile"),
  1708. b(false, "another", "directory", "with"),
  1709. b(false, "another", "directory", "with", "a"),
  1710. b(true, "another", "directory", "with", "a", "file"),
  1711. b(true, "another", "directory", "with", "file"),
  1712. b(true, "another", "file"),
  1713. b(false, "other"),
  1714. b(false, "other", "rand"),
  1715. b(false, "other", "random"),
  1716. b(false, "other", "random", "dir"),
  1717. b(false, "other", "random", "dirx"),
  1718. b(false, "other", "randomx"),
  1719. b(false, "some"),
  1720. b(false, "some", "directory"),
  1721. b(false, "some", "directory", "with"),
  1722. b(false, "some", "directory", "with", "a"),
  1723. b(true, "some", "directory", "with", "a", "file"),
  1724. b(true, "rootfile"),
  1725. }
  1726. expectedResult := map[string]interface{}{
  1727. "another": map[string]interface{}{
  1728. "directory": map[string]interface{}{
  1729. "afile": filedata,
  1730. "with": map[string]interface{}{
  1731. "a": map[string]interface{}{
  1732. "file": filedata,
  1733. },
  1734. "file": filedata,
  1735. },
  1736. },
  1737. "file": filedata,
  1738. },
  1739. "other": map[string]interface{}{
  1740. "rand": map[string]interface{}{},
  1741. "random": map[string]interface{}{
  1742. "dir": map[string]interface{}{},
  1743. "dirx": map[string]interface{}{},
  1744. },
  1745. "randomx": map[string]interface{}{},
  1746. },
  1747. "some": map[string]interface{}{
  1748. "directory": map[string]interface{}{
  1749. "with": map[string]interface{}{
  1750. "a": map[string]interface{}{
  1751. "file": filedata,
  1752. },
  1753. },
  1754. },
  1755. },
  1756. "rootfile": filedata,
  1757. }
  1758. mm := func(data interface{}) string {
  1759. bytes, err := json.Marshal(data)
  1760. if err != nil {
  1761. panic(err)
  1762. }
  1763. return string(bytes)
  1764. }
  1765. m.Index(device1, "default", testdata)
  1766. result := m.GlobalDirectoryTree("default", "", -1, false)
  1767. if mm(result) != mm(expectedResult) {
  1768. t.Errorf("Does not match:\n%#v\n%#v", result, expectedResult)
  1769. }
  1770. result = m.GlobalDirectoryTree("default", "another", -1, false)
  1771. if mm(result) != mm(expectedResult["another"]) {
  1772. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult["another"]))
  1773. }
  1774. result = m.GlobalDirectoryTree("default", "", 0, false)
  1775. currentResult := map[string]interface{}{
  1776. "another": map[string]interface{}{},
  1777. "other": map[string]interface{}{},
  1778. "some": map[string]interface{}{},
  1779. "rootfile": filedata,
  1780. }
  1781. if mm(result) != mm(currentResult) {
  1782. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1783. }
  1784. result = m.GlobalDirectoryTree("default", "", 1, false)
  1785. currentResult = map[string]interface{}{
  1786. "another": map[string]interface{}{
  1787. "directory": map[string]interface{}{},
  1788. "file": filedata,
  1789. },
  1790. "other": map[string]interface{}{
  1791. "rand": map[string]interface{}{},
  1792. "random": map[string]interface{}{},
  1793. "randomx": map[string]interface{}{},
  1794. },
  1795. "some": map[string]interface{}{
  1796. "directory": map[string]interface{}{},
  1797. },
  1798. "rootfile": filedata,
  1799. }
  1800. if mm(result) != mm(currentResult) {
  1801. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1802. }
  1803. result = m.GlobalDirectoryTree("default", "", -1, true)
  1804. currentResult = map[string]interface{}{
  1805. "another": map[string]interface{}{
  1806. "directory": map[string]interface{}{
  1807. "with": map[string]interface{}{
  1808. "a": map[string]interface{}{},
  1809. },
  1810. },
  1811. },
  1812. "other": map[string]interface{}{
  1813. "rand": map[string]interface{}{},
  1814. "random": map[string]interface{}{
  1815. "dir": map[string]interface{}{},
  1816. "dirx": map[string]interface{}{},
  1817. },
  1818. "randomx": map[string]interface{}{},
  1819. },
  1820. "some": map[string]interface{}{
  1821. "directory": map[string]interface{}{
  1822. "with": map[string]interface{}{
  1823. "a": map[string]interface{}{},
  1824. },
  1825. },
  1826. },
  1827. }
  1828. if mm(result) != mm(currentResult) {
  1829. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1830. }
  1831. result = m.GlobalDirectoryTree("default", "", 1, true)
  1832. currentResult = map[string]interface{}{
  1833. "another": map[string]interface{}{
  1834. "directory": map[string]interface{}{},
  1835. },
  1836. "other": map[string]interface{}{
  1837. "rand": map[string]interface{}{},
  1838. "random": map[string]interface{}{},
  1839. "randomx": map[string]interface{}{},
  1840. },
  1841. "some": map[string]interface{}{
  1842. "directory": map[string]interface{}{},
  1843. },
  1844. }
  1845. if mm(result) != mm(currentResult) {
  1846. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1847. }
  1848. result = m.GlobalDirectoryTree("default", "another", 0, false)
  1849. currentResult = map[string]interface{}{
  1850. "directory": map[string]interface{}{},
  1851. "file": filedata,
  1852. }
  1853. if mm(result) != mm(currentResult) {
  1854. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1855. }
  1856. result = m.GlobalDirectoryTree("default", "some/directory", 0, false)
  1857. currentResult = map[string]interface{}{
  1858. "with": map[string]interface{}{},
  1859. }
  1860. if mm(result) != mm(currentResult) {
  1861. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1862. }
  1863. result = m.GlobalDirectoryTree("default", "some/directory", 1, false)
  1864. currentResult = map[string]interface{}{
  1865. "with": map[string]interface{}{
  1866. "a": map[string]interface{}{},
  1867. },
  1868. }
  1869. if mm(result) != mm(currentResult) {
  1870. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1871. }
  1872. result = m.GlobalDirectoryTree("default", "some/directory", 2, false)
  1873. currentResult = map[string]interface{}{
  1874. "with": map[string]interface{}{
  1875. "a": map[string]interface{}{
  1876. "file": filedata,
  1877. },
  1878. },
  1879. }
  1880. if mm(result) != mm(currentResult) {
  1881. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1882. }
  1883. result = m.GlobalDirectoryTree("default", "another", -1, true)
  1884. currentResult = map[string]interface{}{
  1885. "directory": map[string]interface{}{
  1886. "with": map[string]interface{}{
  1887. "a": map[string]interface{}{},
  1888. },
  1889. },
  1890. }
  1891. if mm(result) != mm(currentResult) {
  1892. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1893. }
  1894. // No prefix matching!
  1895. result = m.GlobalDirectoryTree("default", "som", -1, false)
  1896. currentResult = map[string]interface{}{}
  1897. if mm(result) != mm(currentResult) {
  1898. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  1899. }
  1900. }
  1901. func TestGlobalDirectorySelfFixing(t *testing.T) {
  1902. db := db.OpenMemory()
  1903. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  1904. m.AddFolder(defaultFolderConfig)
  1905. m.ServeBackground()
  1906. b := func(isfile bool, path ...string) protocol.FileInfo {
  1907. typ := protocol.FileInfoTypeDirectory
  1908. blocks := []protocol.BlockInfo{}
  1909. if isfile {
  1910. typ = protocol.FileInfoTypeFile
  1911. blocks = []protocol.BlockInfo{{Offset: 0x0, Size: 0xa, Hash: []uint8{0x2f, 0x72, 0xcc, 0x11, 0xa6, 0xfc, 0xd0, 0x27, 0x1e, 0xce, 0xf8, 0xc6, 0x10, 0x56, 0xee, 0x1e, 0xb1, 0x24, 0x3b, 0xe3, 0x80, 0x5b, 0xf9, 0xa9, 0xdf, 0x98, 0xf9, 0x2f, 0x76, 0x36, 0xb0, 0x5c}}}
  1912. }
  1913. return protocol.FileInfo{
  1914. Name: filepath.Join(path...),
  1915. Type: typ,
  1916. ModifiedS: 0x666,
  1917. Blocks: blocks,
  1918. Size: 0xa,
  1919. }
  1920. }
  1921. filedata := []interface{}{time.Unix(0x666, 0).Format(time.RFC3339), 0xa}
  1922. testdata := []protocol.FileInfo{
  1923. b(true, "another", "directory", "afile"),
  1924. b(true, "another", "directory", "with", "a", "file"),
  1925. b(true, "another", "directory", "with", "file"),
  1926. b(false, "other", "random", "dirx"),
  1927. b(false, "other", "randomx"),
  1928. b(false, "some", "directory", "with", "x"),
  1929. b(true, "some", "directory", "with", "a", "file"),
  1930. b(false, "this", "is", "a", "deep", "invalid", "directory"),
  1931. b(true, "xthis", "is", "a", "deep", "invalid", "file"),
  1932. }
  1933. expectedResult := map[string]interface{}{
  1934. "another": map[string]interface{}{
  1935. "directory": map[string]interface{}{
  1936. "afile": filedata,
  1937. "with": map[string]interface{}{
  1938. "a": map[string]interface{}{
  1939. "file": filedata,
  1940. },
  1941. "file": filedata,
  1942. },
  1943. },
  1944. },
  1945. "other": map[string]interface{}{
  1946. "random": map[string]interface{}{
  1947. "dirx": map[string]interface{}{},
  1948. },
  1949. "randomx": map[string]interface{}{},
  1950. },
  1951. "some": map[string]interface{}{
  1952. "directory": map[string]interface{}{
  1953. "with": map[string]interface{}{
  1954. "a": map[string]interface{}{
  1955. "file": filedata,
  1956. },
  1957. "x": map[string]interface{}{},
  1958. },
  1959. },
  1960. },
  1961. "this": map[string]interface{}{
  1962. "is": map[string]interface{}{
  1963. "a": map[string]interface{}{
  1964. "deep": map[string]interface{}{
  1965. "invalid": map[string]interface{}{
  1966. "directory": map[string]interface{}{},
  1967. },
  1968. },
  1969. },
  1970. },
  1971. },
  1972. "xthis": map[string]interface{}{
  1973. "is": map[string]interface{}{
  1974. "a": map[string]interface{}{
  1975. "deep": map[string]interface{}{
  1976. "invalid": map[string]interface{}{
  1977. "file": filedata,
  1978. },
  1979. },
  1980. },
  1981. },
  1982. },
  1983. }
  1984. mm := func(data interface{}) string {
  1985. bytes, err := json.Marshal(data)
  1986. if err != nil {
  1987. panic(err)
  1988. }
  1989. return string(bytes)
  1990. }
  1991. m.Index(device1, "default", testdata)
  1992. result := m.GlobalDirectoryTree("default", "", -1, false)
  1993. if mm(result) != mm(expectedResult) {
  1994. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(expectedResult))
  1995. }
  1996. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, false)
  1997. currentResult := map[string]interface{}{
  1998. "invalid": map[string]interface{}{
  1999. "file": filedata,
  2000. },
  2001. }
  2002. if mm(result) != mm(currentResult) {
  2003. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  2004. }
  2005. result = m.GlobalDirectoryTree("default", "xthis/is/a/deep", -1, true)
  2006. currentResult = map[string]interface{}{
  2007. "invalid": map[string]interface{}{},
  2008. }
  2009. if mm(result) != mm(currentResult) {
  2010. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  2011. }
  2012. // !!! This is actually BAD, because we don't have enough level allowance
  2013. // to accept this file, hence the tree is left unbuilt !!!
  2014. result = m.GlobalDirectoryTree("default", "xthis", 1, false)
  2015. currentResult = map[string]interface{}{}
  2016. if mm(result) != mm(currentResult) {
  2017. t.Errorf("Does not match:\n%s\n%s", mm(result), mm(currentResult))
  2018. }
  2019. }
  2020. func genDeepFiles(n, d int) []protocol.FileInfo {
  2021. rand.Seed(int64(n))
  2022. files := make([]protocol.FileInfo, n)
  2023. t := time.Now().Unix()
  2024. for i := 0; i < n; i++ {
  2025. path := ""
  2026. for i := 0; i <= d; i++ {
  2027. path = filepath.Join(path, strconv.Itoa(rand.Int()))
  2028. }
  2029. sofar := ""
  2030. for _, path := range filepath.SplitList(path) {
  2031. sofar = filepath.Join(sofar, path)
  2032. files[i] = protocol.FileInfo{
  2033. Name: sofar,
  2034. }
  2035. i++
  2036. }
  2037. files[i].ModifiedS = t
  2038. files[i].Blocks = []protocol.BlockInfo{{Offset: 0, Size: 100, Hash: []byte("some hash bytes")}}
  2039. }
  2040. return files
  2041. }
  2042. func BenchmarkTree_10000_50(b *testing.B) {
  2043. benchmarkTree(b, 10000, 50)
  2044. }
  2045. func BenchmarkTree_100_50(b *testing.B) {
  2046. benchmarkTree(b, 100, 50)
  2047. }
  2048. func BenchmarkTree_100_10(b *testing.B) {
  2049. benchmarkTree(b, 100, 10)
  2050. }
  2051. func benchmarkTree(b *testing.B, n1, n2 int) {
  2052. db := db.OpenMemory()
  2053. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  2054. m.AddFolder(defaultFolderConfig)
  2055. m.ServeBackground()
  2056. m.ScanFolder("default")
  2057. files := genDeepFiles(n1, n2)
  2058. m.Index(device1, "default", files)
  2059. b.ResetTimer()
  2060. for i := 0; i < b.N; i++ {
  2061. m.GlobalDirectoryTree("default", "", -1, false)
  2062. }
  2063. b.ReportAllocs()
  2064. }
  2065. func TestIssue3028(t *testing.T) {
  2066. // Create two files that we'll delete, one with a name that is a prefix of the other.
  2067. if err := ioutil.WriteFile("testdata/testrm", []byte("Hello"), 0644); err != nil {
  2068. t.Fatal(err)
  2069. }
  2070. defer os.Remove("testdata/testrm")
  2071. if err := ioutil.WriteFile("testdata/testrm2", []byte("Hello"), 0644); err != nil {
  2072. t.Fatal(err)
  2073. }
  2074. defer os.Remove("testdata/testrm2")
  2075. // Create a model and default folder
  2076. db := db.OpenMemory()
  2077. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  2078. defCfg := defaultFolderConfig.Copy()
  2079. defCfg.RescanIntervalS = 86400
  2080. m.AddFolder(defCfg)
  2081. m.StartFolder("default")
  2082. m.ServeBackground()
  2083. // Make sure the initial scan has finished (ScanFolders is blocking)
  2084. m.ScanFolders()
  2085. // Get a count of how many files are there now
  2086. locorigfiles := m.LocalSize("default").Files
  2087. globorigfiles := m.GlobalSize("default").Files
  2088. // Delete and rescan specifically these two
  2089. os.Remove("testdata/testrm")
  2090. os.Remove("testdata/testrm2")
  2091. m.ScanFolderSubdirs("default", []string{"testrm", "testrm2"})
  2092. // Verify that the number of files decreased by two and the number of
  2093. // deleted files increases by two
  2094. loc := m.LocalSize("default")
  2095. glob := m.GlobalSize("default")
  2096. if loc.Files != locorigfiles-2 {
  2097. t.Errorf("Incorrect local accounting; got %d current files, expected %d", loc.Files, locorigfiles-2)
  2098. }
  2099. if glob.Files != globorigfiles-2 {
  2100. t.Errorf("Incorrect global accounting; got %d current files, expected %d", glob.Files, globorigfiles-2)
  2101. }
  2102. if loc.Deleted != 2 {
  2103. t.Errorf("Incorrect local accounting; got %d deleted files, expected 2", loc.Deleted)
  2104. }
  2105. if glob.Deleted != 2 {
  2106. t.Errorf("Incorrect global accounting; got %d deleted files, expected 2", glob.Deleted)
  2107. }
  2108. }
  2109. func TestIssue4357(t *testing.T) {
  2110. db := db.OpenMemory()
  2111. cfg := defaultCfgWrapper.RawCopy()
  2112. // Create a separate wrapper not to pollute other tests.
  2113. wrapper := createTmpWrapper(config.Configuration{})
  2114. defer os.Remove(wrapper.ConfigPath())
  2115. m := NewModel(wrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  2116. m.ServeBackground()
  2117. defer m.Stop()
  2118. // Force the model to wire itself and add the folders
  2119. p, err := wrapper.Replace(cfg)
  2120. p.Wait()
  2121. if err != nil {
  2122. t.Error(err)
  2123. }
  2124. if _, ok := m.folderCfgs["default"]; !ok {
  2125. t.Error("Folder should be running")
  2126. }
  2127. newCfg := wrapper.RawCopy()
  2128. newCfg.Folders[0].Paused = true
  2129. p, err = wrapper.Replace(newCfg)
  2130. p.Wait()
  2131. if err != nil {
  2132. t.Error(err)
  2133. }
  2134. if _, ok := m.folderCfgs["default"]; ok {
  2135. t.Error("Folder should not be running")
  2136. }
  2137. if _, ok := m.cfg.Folder("default"); !ok {
  2138. t.Error("should still have folder in config")
  2139. }
  2140. p, err = wrapper.Replace(config.Configuration{})
  2141. p.Wait()
  2142. if err != nil {
  2143. t.Error(err)
  2144. }
  2145. if _, ok := m.cfg.Folder("default"); ok {
  2146. t.Error("should not have folder in config")
  2147. }
  2148. // Add the folder back, should be running
  2149. p, err = wrapper.Replace(cfg)
  2150. p.Wait()
  2151. if err != nil {
  2152. t.Error(err)
  2153. }
  2154. if _, ok := m.folderCfgs["default"]; !ok {
  2155. t.Error("Folder should be running")
  2156. }
  2157. if _, ok := m.cfg.Folder("default"); !ok {
  2158. t.Error("should still have folder in config")
  2159. }
  2160. // Should not panic when removing a running folder.
  2161. p, err = wrapper.Replace(config.Configuration{})
  2162. p.Wait()
  2163. if err != nil {
  2164. t.Error(err)
  2165. }
  2166. if _, ok := m.folderCfgs["default"]; ok {
  2167. t.Error("Folder should not be running")
  2168. }
  2169. if _, ok := m.cfg.Folder("default"); ok {
  2170. t.Error("should not have folder in config")
  2171. }
  2172. }
  2173. func TestIssue2782(t *testing.T) {
  2174. // CheckHealth should accept a symlinked folder, when using tilde-expanded path.
  2175. if runtime.GOOS == "windows" {
  2176. t.Skip("not reliable on Windows")
  2177. return
  2178. }
  2179. home := os.Getenv("HOME")
  2180. if home == "" {
  2181. t.Skip("no home")
  2182. }
  2183. // Create the test env. Needs to be based on $HOME as tilde expansion is
  2184. // part of the issue. Skip the test if any of this fails, as we are a
  2185. // bit outside of our stated domain here...
  2186. testName := ".syncthing-test." + srand.String(16)
  2187. testDir := filepath.Join(home, testName)
  2188. if err := os.RemoveAll(testDir); err != nil {
  2189. t.Skip(err)
  2190. }
  2191. if err := os.MkdirAll(testDir+"/syncdir", 0755); err != nil {
  2192. t.Skip(err)
  2193. }
  2194. if err := ioutil.WriteFile(testDir+"/syncdir/file", []byte("hello, world\n"), 0644); err != nil {
  2195. t.Skip(err)
  2196. }
  2197. if err := os.Symlink("syncdir", testDir+"/synclink"); err != nil {
  2198. t.Skip(err)
  2199. }
  2200. defer os.RemoveAll(testDir)
  2201. db := db.OpenMemory()
  2202. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  2203. m.AddFolder(config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, "~/"+testName+"/synclink/"))
  2204. m.StartFolder("default")
  2205. m.ServeBackground()
  2206. defer m.Stop()
  2207. if err := m.ScanFolder("default"); err != nil {
  2208. t.Error("scan error:", err)
  2209. }
  2210. m.fmut.Lock()
  2211. runner, _ := m.folderRunners["default"]
  2212. m.fmut.Unlock()
  2213. if err := runner.CheckHealth(); err != nil {
  2214. t.Error("health check error:", err)
  2215. }
  2216. }
  2217. func TestIndexesForUnknownDevicesDropped(t *testing.T) {
  2218. dbi := db.OpenMemory()
  2219. files := db.NewFileSet("default", defaultFs, dbi)
  2220. files.Drop(device1)
  2221. files.Update(device1, genFiles(1))
  2222. files.Drop(device2)
  2223. files.Update(device2, genFiles(1))
  2224. if len(files.ListDevices()) != 2 {
  2225. t.Error("expected two devices")
  2226. }
  2227. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2228. m.AddFolder(defaultFolderConfig)
  2229. m.StartFolder("default")
  2230. // Remote sequence is cached, hence need to recreated.
  2231. files = db.NewFileSet("default", defaultFs, dbi)
  2232. if len(files.ListDevices()) != 1 {
  2233. t.Error("Expected one device")
  2234. }
  2235. }
  2236. func TestSharedWithClearedOnDisconnect(t *testing.T) {
  2237. dbi := db.OpenMemory()
  2238. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, "testdata")
  2239. fcfg.Devices = []config.FolderDeviceConfiguration{
  2240. {DeviceID: device1},
  2241. {DeviceID: device2},
  2242. }
  2243. cfg := config.Configuration{
  2244. Folders: []config.FolderConfiguration{fcfg},
  2245. Devices: []config.DeviceConfiguration{
  2246. config.NewDeviceConfiguration(device1, "device1"),
  2247. config.NewDeviceConfiguration(device2, "device2"),
  2248. },
  2249. Options: config.OptionsConfiguration{
  2250. // Don't remove temporaries directly on startup
  2251. KeepTemporariesH: 1,
  2252. },
  2253. }
  2254. wcfg := createTmpWrapper(cfg)
  2255. defer os.Remove(wcfg.ConfigPath())
  2256. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2257. m.AddFolder(fcfg)
  2258. m.StartFolder(fcfg.ID)
  2259. m.ServeBackground()
  2260. conn1 := &fakeConnection{id: device1}
  2261. m.AddConnection(conn1, protocol.HelloResult{})
  2262. conn2 := &fakeConnection{id: device2}
  2263. m.AddConnection(conn2, protocol.HelloResult{})
  2264. m.ClusterConfig(device1, protocol.ClusterConfig{
  2265. Folders: []protocol.Folder{
  2266. {
  2267. ID: "default",
  2268. Devices: []protocol.Device{
  2269. {ID: device1},
  2270. {ID: device2},
  2271. },
  2272. },
  2273. },
  2274. })
  2275. m.ClusterConfig(device2, protocol.ClusterConfig{
  2276. Folders: []protocol.Folder{
  2277. {
  2278. ID: "default",
  2279. Devices: []protocol.Device{
  2280. {ID: device1},
  2281. {ID: device2},
  2282. },
  2283. },
  2284. },
  2285. })
  2286. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device1) {
  2287. t.Error("not shared with device1")
  2288. }
  2289. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device2) {
  2290. t.Error("not shared with device2")
  2291. }
  2292. if conn2.Closed() {
  2293. t.Error("conn already closed")
  2294. }
  2295. cfg = cfg.Copy()
  2296. cfg.Devices = cfg.Devices[:1]
  2297. if _, err := wcfg.Replace(cfg); err != nil {
  2298. t.Error(err)
  2299. }
  2300. time.Sleep(100 * time.Millisecond) // Committer notification happens in a separate routine
  2301. fcfg, ok := m.cfg.Folder("default")
  2302. if !ok {
  2303. t.Fatal("default folder missing")
  2304. }
  2305. if !fcfg.SharedWith(device1) {
  2306. t.Error("not shared with device1")
  2307. }
  2308. if fcfg.SharedWith(device2) {
  2309. t.Error("shared with device2")
  2310. }
  2311. for _, dev := range fcfg.Devices {
  2312. if dev.DeviceID == device2 {
  2313. t.Error("still there")
  2314. }
  2315. }
  2316. if !conn2.Closed() {
  2317. t.Error("connection not closed")
  2318. }
  2319. if _, ok := wcfg.Devices()[device2]; ok {
  2320. t.Error("device still in config")
  2321. }
  2322. if _, ok := m.conn[device2]; !ok {
  2323. t.Error("conn missing early")
  2324. }
  2325. if _, ok := m.helloMessages[device2]; !ok {
  2326. t.Error("hello missing early")
  2327. }
  2328. if _, ok := m.deviceDownloads[device2]; !ok {
  2329. t.Error("downloads missing early")
  2330. }
  2331. m.Closed(conn2, fmt.Errorf("foo"))
  2332. if _, ok := m.conn[device2]; ok {
  2333. t.Error("conn not missing")
  2334. }
  2335. if _, ok := m.helloMessages[device2]; ok {
  2336. t.Error("hello not missing")
  2337. }
  2338. if _, ok := m.deviceDownloads[device2]; ok {
  2339. t.Error("downloads not missing")
  2340. }
  2341. }
  2342. func TestIssue3496(t *testing.T) {
  2343. t.Skip("This test deletes files that the other test depend on. Needs fixing.")
  2344. // It seems like lots of deleted files can cause negative completion
  2345. // percentages. Lets make sure that doesn't happen. Also do some general
  2346. // checks on the completion calculation stuff.
  2347. dbi := db.OpenMemory()
  2348. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2349. m.AddFolder(defaultFolderConfig)
  2350. m.StartFolder("default")
  2351. m.ServeBackground()
  2352. defer m.Stop()
  2353. m.ScanFolder("default")
  2354. addFakeConn(m, device1)
  2355. addFakeConn(m, device2)
  2356. // Reach into the model and grab the current file list...
  2357. m.fmut.RLock()
  2358. fs := m.folderFiles["default"]
  2359. m.fmut.RUnlock()
  2360. var localFiles []protocol.FileInfo
  2361. fs.WithHave(protocol.LocalDeviceID, func(i db.FileIntf) bool {
  2362. localFiles = append(localFiles, i.(protocol.FileInfo))
  2363. return true
  2364. })
  2365. // Mark all files as deleted and fake it as update from device1
  2366. for i := range localFiles {
  2367. localFiles[i].Deleted = true
  2368. localFiles[i].Version = localFiles[i].Version.Update(device1.Short())
  2369. localFiles[i].Blocks = nil
  2370. }
  2371. // Also add a small file that we're supposed to need, or the global size
  2372. // stuff will bail out early due to the entire folder being zero size.
  2373. localFiles = append(localFiles, protocol.FileInfo{
  2374. Name: "fake",
  2375. Size: 1234,
  2376. Type: protocol.FileInfoTypeFile,
  2377. Version: protocol.Vector{Counters: []protocol.Counter{{ID: device1.Short(), Value: 42}}},
  2378. })
  2379. m.IndexUpdate(device1, "default", localFiles)
  2380. // Check that the completion percentage for us makes sense
  2381. comp := m.Completion(protocol.LocalDeviceID, "default")
  2382. if comp.NeedBytes > comp.GlobalBytes {
  2383. t.Errorf("Need more bytes than exist, not possible: %d > %d", comp.NeedBytes, comp.GlobalBytes)
  2384. }
  2385. if comp.CompletionPct < 0 {
  2386. t.Errorf("Less than zero percent complete, not possible: %.02f%%", comp.CompletionPct)
  2387. }
  2388. if comp.NeedBytes == 0 {
  2389. t.Error("Need no bytes even though some files are deleted")
  2390. }
  2391. if comp.CompletionPct == 100 {
  2392. t.Errorf("Fully complete, not possible: %.02f%%", comp.CompletionPct)
  2393. }
  2394. t.Log(comp)
  2395. // Check that NeedSize does the correct thing
  2396. need := m.NeedSize("default")
  2397. if need.Files != 1 || need.Bytes != 1234 {
  2398. // The one we added synthetically above
  2399. t.Errorf("Incorrect need size; %d, %d != 1, 1234", need.Files, need.Bytes)
  2400. }
  2401. if int(need.Deleted) != len(localFiles)-1 {
  2402. // The rest
  2403. t.Errorf("Incorrect need deletes; %d != %d", need.Deleted, len(localFiles)-1)
  2404. }
  2405. }
  2406. func TestIssue3804(t *testing.T) {
  2407. dbi := db.OpenMemory()
  2408. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2409. m.AddFolder(defaultFolderConfig)
  2410. m.StartFolder("default")
  2411. m.ServeBackground()
  2412. defer m.Stop()
  2413. // Subdirs ending in slash should be accepted
  2414. if err := m.ScanFolderSubdirs("default", []string{"baz/", "foo"}); err != nil {
  2415. t.Error("Unexpected error:", err)
  2416. }
  2417. }
  2418. func TestIssue3829(t *testing.T) {
  2419. dbi := db.OpenMemory()
  2420. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2421. m.AddFolder(defaultFolderConfig)
  2422. m.StartFolder("default")
  2423. m.ServeBackground()
  2424. defer m.Stop()
  2425. // Empty subdirs should be accepted
  2426. if err := m.ScanFolderSubdirs("default", []string{""}); err != nil {
  2427. t.Error("Unexpected error:", err)
  2428. }
  2429. }
  2430. func TestNoRequestsFromPausedDevices(t *testing.T) {
  2431. t.Skip("broken, fails randomly, #3843")
  2432. dbi := db.OpenMemory()
  2433. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, "testdata")
  2434. fcfg.Devices = []config.FolderDeviceConfiguration{
  2435. {DeviceID: device1},
  2436. {DeviceID: device2},
  2437. }
  2438. cfg := config.Configuration{
  2439. Folders: []config.FolderConfiguration{fcfg},
  2440. Devices: []config.DeviceConfiguration{
  2441. config.NewDeviceConfiguration(device1, "device1"),
  2442. config.NewDeviceConfiguration(device2, "device2"),
  2443. },
  2444. Options: config.OptionsConfiguration{
  2445. // Don't remove temporaries directly on startup
  2446. KeepTemporariesH: 1,
  2447. },
  2448. }
  2449. wcfg := createTmpWrapper(cfg)
  2450. defer os.Remove(wcfg.ConfigPath())
  2451. m := NewModel(wcfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2452. m.AddFolder(fcfg)
  2453. m.StartFolder(fcfg.ID)
  2454. m.ServeBackground()
  2455. file := testDataExpected["foo"]
  2456. files := m.folderFiles["default"]
  2457. files.Update(device1, []protocol.FileInfo{file})
  2458. files.Update(device2, []protocol.FileInfo{file})
  2459. avail := m.Availability("default", file, file.Blocks[0])
  2460. if len(avail) != 0 {
  2461. t.Errorf("should not be available, no connections")
  2462. }
  2463. addFakeConn(m, device1)
  2464. addFakeConn(m, device2)
  2465. // !!! This is not what I'd expect to happen, as we don't even know if the peer has the original index !!!
  2466. avail = m.Availability("default", file, file.Blocks[0])
  2467. if len(avail) != 2 {
  2468. t.Errorf("should have two available")
  2469. }
  2470. cc := protocol.ClusterConfig{
  2471. Folders: []protocol.Folder{
  2472. {
  2473. ID: "default",
  2474. Devices: []protocol.Device{
  2475. {ID: device1},
  2476. {ID: device2},
  2477. },
  2478. },
  2479. },
  2480. }
  2481. m.ClusterConfig(device1, cc)
  2482. m.ClusterConfig(device2, cc)
  2483. avail = m.Availability("default", file, file.Blocks[0])
  2484. if len(avail) != 2 {
  2485. t.Errorf("should have two available")
  2486. }
  2487. m.Closed(&fakeConnection{id: device1}, errDeviceUnknown)
  2488. m.Closed(&fakeConnection{id: device2}, errDeviceUnknown)
  2489. avail = m.Availability("default", file, file.Blocks[0])
  2490. if len(avail) != 0 {
  2491. t.Errorf("should have no available")
  2492. }
  2493. // Test that remote paused folders are not used.
  2494. addFakeConn(m, device1)
  2495. addFakeConn(m, device2)
  2496. m.ClusterConfig(device1, cc)
  2497. ccp := cc
  2498. ccp.Folders[0].Paused = true
  2499. m.ClusterConfig(device1, ccp)
  2500. avail = m.Availability("default", file, file.Blocks[0])
  2501. if len(avail) != 1 {
  2502. t.Errorf("should have one available")
  2503. }
  2504. }
  2505. // TestIssue2571 tests replacing a directory with content with a symlink
  2506. func TestIssue2571(t *testing.T) {
  2507. if runtime.GOOS == "windows" {
  2508. t.Skip("Scanning symlinks isn't supported on windows")
  2509. }
  2510. err := defaultFs.MkdirAll("replaceDir", 0755)
  2511. if err != nil {
  2512. t.Fatal(err)
  2513. }
  2514. defer func() {
  2515. defaultFs.RemoveAll("replaceDir")
  2516. }()
  2517. testFs := fs.NewFilesystem(fs.FilesystemTypeBasic, filepath.Join(defaultFs.URI(), "replaceDir"))
  2518. for _, dir := range []string{"toLink", "linkTarget"} {
  2519. err := testFs.MkdirAll(dir, 0775)
  2520. if err != nil {
  2521. t.Fatal(err)
  2522. }
  2523. fd, err := testFs.Create(filepath.Join(dir, "a"))
  2524. if err != nil {
  2525. t.Fatal(err)
  2526. }
  2527. fd.Close()
  2528. }
  2529. dbi := db.OpenMemory()
  2530. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2531. m.AddFolder(defaultFolderConfig)
  2532. m.StartFolder("default")
  2533. m.ServeBackground()
  2534. defer m.Stop()
  2535. m.ScanFolder("default")
  2536. if err = testFs.RemoveAll("toLink"); err != nil {
  2537. t.Fatal(err)
  2538. }
  2539. if err := osutil.DebugSymlinkForTestsOnly(filepath.Join(testFs.URI(), "linkTarget"), filepath.Join(testFs.URI(), "toLink")); err != nil {
  2540. t.Fatal(err)
  2541. }
  2542. m.ScanFolder("default")
  2543. if dir, ok := m.CurrentFolderFile("default", filepath.Join("replaceDir", "toLink")); !ok {
  2544. t.Fatalf("Dir missing in db")
  2545. } else if !dir.IsSymlink() {
  2546. t.Errorf("Dir wasn't changed to symlink")
  2547. }
  2548. if file, ok := m.CurrentFolderFile("default", filepath.Join("replaceDir", "toLink", "a")); !ok {
  2549. t.Fatalf("File missing in db")
  2550. } else if !file.Deleted {
  2551. t.Errorf("File below symlink has not been marked as deleted")
  2552. }
  2553. }
  2554. // TestIssue4573 tests that contents of an unavailable dir aren't marked deleted
  2555. func TestIssue4573(t *testing.T) {
  2556. if runtime.GOOS == "windows" {
  2557. t.Skip("Can't make the dir inaccessible on windows")
  2558. }
  2559. err := defaultFs.MkdirAll("inaccessible", 0755)
  2560. if err != nil {
  2561. t.Fatal(err)
  2562. }
  2563. defer func() {
  2564. defaultFs.Chmod("inaccessible", 0777)
  2565. defaultFs.RemoveAll("inaccessible")
  2566. }()
  2567. file := filepath.Join("inaccessible", "a")
  2568. fd, err := defaultFs.Create(file)
  2569. if err != nil {
  2570. t.Fatal(err)
  2571. }
  2572. fd.Close()
  2573. dbi := db.OpenMemory()
  2574. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2575. m.AddFolder(defaultFolderConfig)
  2576. m.StartFolder("default")
  2577. m.ServeBackground()
  2578. defer m.Stop()
  2579. m.ScanFolder("default")
  2580. err = defaultFs.Chmod("inaccessible", 0000)
  2581. if err != nil {
  2582. t.Fatal(err)
  2583. }
  2584. m.ScanFolder("default")
  2585. if file, ok := m.CurrentFolderFile("default", file); !ok {
  2586. t.Fatalf("File missing in db")
  2587. } else if file.Deleted {
  2588. t.Errorf("Inaccessible file has been marked as deleted.")
  2589. }
  2590. }
  2591. // TestInternalScan checks whether various fs operations are correctly represented
  2592. // in the db after scanning.
  2593. func TestInternalScan(t *testing.T) {
  2594. err := defaultFs.MkdirAll("internalScan", 0755)
  2595. if err != nil {
  2596. t.Fatal(err)
  2597. }
  2598. defer func() {
  2599. defaultFs.RemoveAll("internalScan")
  2600. }()
  2601. testFs := fs.NewFilesystem(fs.FilesystemTypeBasic, filepath.Join(defaultFs.URI(), "internalScan"))
  2602. testCases := map[string]func(protocol.FileInfo) bool{
  2603. "removeDir": func(f protocol.FileInfo) bool {
  2604. return !f.Deleted
  2605. },
  2606. "dirToFile": func(f protocol.FileInfo) bool {
  2607. return f.Deleted || f.IsDirectory()
  2608. },
  2609. }
  2610. baseDirs := []string{"dirToFile", "removeDir"}
  2611. for _, dir := range baseDirs {
  2612. sub := filepath.Join(dir, "subDir")
  2613. for _, dir := range []string{dir, sub} {
  2614. err := testFs.MkdirAll(dir, 0775)
  2615. if err != nil {
  2616. t.Fatalf("%v: %v", dir, err)
  2617. }
  2618. }
  2619. testCases[sub] = func(f protocol.FileInfo) bool {
  2620. return !f.Deleted
  2621. }
  2622. for _, dir := range []string{dir, sub} {
  2623. file := filepath.Join(dir, "a")
  2624. fd, err := testFs.Create(file)
  2625. if err != nil {
  2626. t.Fatal(err)
  2627. }
  2628. fd.Close()
  2629. testCases[file] = func(f protocol.FileInfo) bool {
  2630. return !f.Deleted
  2631. }
  2632. }
  2633. }
  2634. dbi := db.OpenMemory()
  2635. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2636. m.AddFolder(defaultFolderConfig)
  2637. m.StartFolder("default")
  2638. m.ServeBackground()
  2639. defer m.Stop()
  2640. m.ScanFolder("default")
  2641. for _, dir := range baseDirs {
  2642. if err = testFs.RemoveAll(dir); err != nil {
  2643. t.Fatal(err)
  2644. }
  2645. }
  2646. fd, err := testFs.Create("dirToFile")
  2647. if err != nil {
  2648. t.Fatal(err)
  2649. }
  2650. fd.Close()
  2651. m.ScanFolder("default")
  2652. for path, cond := range testCases {
  2653. if f, ok := m.CurrentFolderFile("default", filepath.Join("internalScan", path)); !ok {
  2654. t.Fatalf("%v missing in db", path)
  2655. } else if cond(f) {
  2656. t.Errorf("Incorrect db entry for %v", path)
  2657. }
  2658. }
  2659. }
  2660. func TestCustomMarkerName(t *testing.T) {
  2661. ldb := db.OpenMemory()
  2662. set := db.NewFileSet("default", defaultFs, ldb)
  2663. set.Update(protocol.LocalDeviceID, []protocol.FileInfo{
  2664. {Name: "dummyfile"},
  2665. })
  2666. fcfg := config.FolderConfiguration{
  2667. ID: "default",
  2668. Path: "testdata/rwtestfolder",
  2669. Type: config.FolderTypeSendReceive,
  2670. RescanIntervalS: 1,
  2671. MarkerName: "myfile",
  2672. }
  2673. cfg := createTmpWrapper(config.Configuration{
  2674. Folders: []config.FolderConfiguration{fcfg},
  2675. Devices: []config.DeviceConfiguration{
  2676. {
  2677. DeviceID: device1,
  2678. },
  2679. },
  2680. })
  2681. defer os.Remove(cfg.ConfigPath())
  2682. os.RemoveAll(fcfg.Path)
  2683. defer os.RemoveAll(fcfg.Path)
  2684. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", ldb, nil)
  2685. m.AddFolder(fcfg)
  2686. m.StartFolder("default")
  2687. m.ServeBackground()
  2688. defer m.Stop()
  2689. waitFor := func(status string) error {
  2690. timeout := time.Now().Add(2 * time.Second)
  2691. for {
  2692. _, _, err := m.State("default")
  2693. if err == nil && status == "" {
  2694. return nil
  2695. }
  2696. if err != nil && err.Error() == status {
  2697. return nil
  2698. }
  2699. if time.Now().After(timeout) {
  2700. return fmt.Errorf("Timed out waiting for status: %s, current status: %v", status, err)
  2701. }
  2702. time.Sleep(10 * time.Millisecond)
  2703. }
  2704. }
  2705. if err := waitFor("folder path missing"); err != nil {
  2706. t.Error(err)
  2707. return
  2708. }
  2709. os.Mkdir(fcfg.Path, 0700)
  2710. fd, err := os.Create(filepath.Join(fcfg.Path, "myfile"))
  2711. if err != nil {
  2712. t.Error(err)
  2713. return
  2714. }
  2715. fd.Close()
  2716. if err := waitFor(""); err != nil {
  2717. t.Error(err)
  2718. return
  2719. }
  2720. }
  2721. func TestRemoveDirWithContent(t *testing.T) {
  2722. defer func() {
  2723. defaultFs.RemoveAll("dirwith")
  2724. }()
  2725. defaultFs.MkdirAll("dirwith", 0755)
  2726. content := filepath.Join("dirwith", "content")
  2727. fd, err := defaultFs.Create(content)
  2728. if err != nil {
  2729. t.Fatal(err)
  2730. return
  2731. }
  2732. fd.Close()
  2733. dbi := db.OpenMemory()
  2734. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2735. m.AddFolder(defaultFolderConfig)
  2736. m.StartFolder("default")
  2737. m.ServeBackground()
  2738. defer m.Stop()
  2739. m.ScanFolder("default")
  2740. dir, ok := m.CurrentFolderFile("default", "dirwith")
  2741. if !ok {
  2742. t.Fatalf("Can't get dir \"dirwith\" after initial scan")
  2743. }
  2744. dir.Deleted = true
  2745. dir.Version = dir.Version.Update(device1.Short()).Update(device1.Short())
  2746. file, ok := m.CurrentFolderFile("default", content)
  2747. if !ok {
  2748. t.Fatalf("Can't get file \"%v\" after initial scan", content)
  2749. }
  2750. file.Deleted = true
  2751. file.Version = file.Version.Update(device1.Short()).Update(device1.Short())
  2752. m.IndexUpdate(device1, "default", []protocol.FileInfo{dir, file})
  2753. // Is there something we could trigger on instead of just waiting?
  2754. timeout := time.NewTimer(5 * time.Second)
  2755. for {
  2756. dir, ok := m.CurrentFolderFile("default", "dirwith")
  2757. if !ok {
  2758. t.Fatalf("Can't get dir \"dirwith\" after index update")
  2759. }
  2760. file, ok := m.CurrentFolderFile("default", content)
  2761. if !ok {
  2762. t.Fatalf("Can't get file \"%v\" after index update", content)
  2763. }
  2764. if dir.Deleted && file.Deleted {
  2765. return
  2766. }
  2767. select {
  2768. case <-timeout.C:
  2769. if !dir.Deleted && !file.Deleted {
  2770. t.Errorf("Neither the dir nor its content was deleted before timing out.")
  2771. } else if !dir.Deleted {
  2772. t.Errorf("The dir was not deleted before timing out.")
  2773. } else {
  2774. t.Errorf("The content of the dir was not deleted before timing out.")
  2775. }
  2776. return
  2777. default:
  2778. time.Sleep(100 * time.Millisecond)
  2779. }
  2780. }
  2781. }
  2782. func TestIssue4475(t *testing.T) {
  2783. defer func() {
  2784. defaultFs.RemoveAll("delDir")
  2785. }()
  2786. err := defaultFs.MkdirAll("delDir", 0755)
  2787. if err != nil {
  2788. t.Fatal(err)
  2789. }
  2790. dbi := db.OpenMemory()
  2791. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2792. m.AddFolder(defaultFolderConfig)
  2793. m.StartFolder("default")
  2794. m.ServeBackground()
  2795. defer m.Stop()
  2796. m.ScanFolder("default")
  2797. // Scenario: Dir is deleted locally and before syncing/index exchange
  2798. // happens, a file is create in that dir on the remote.
  2799. // This should result in the directory being recreated and added to the
  2800. // db locally.
  2801. if err = defaultFs.RemoveAll("delDir"); err != nil {
  2802. t.Fatal(err)
  2803. }
  2804. m.ScanFolder("default")
  2805. conn := addFakeConn(m, device1)
  2806. conn.folder = "default"
  2807. if fcfg, ok := m.cfg.Folder("default"); !ok || !fcfg.SharedWith(device1) {
  2808. t.Fatal("not shared with device1")
  2809. }
  2810. fileName := filepath.Join("delDir", "file")
  2811. conn.addFile(fileName, 0644, protocol.FileInfoTypeFile, nil)
  2812. conn.sendIndexUpdate()
  2813. // Is there something we could trigger on instead of just waiting?
  2814. timeout := time.NewTimer(5 * time.Second)
  2815. created := false
  2816. for {
  2817. if !created {
  2818. if _, ok := m.CurrentFolderFile("default", fileName); ok {
  2819. created = true
  2820. }
  2821. } else {
  2822. dir, ok := m.CurrentFolderFile("default", "delDir")
  2823. if !ok {
  2824. t.Fatalf("can't get dir from db")
  2825. }
  2826. if !dir.Deleted {
  2827. return
  2828. }
  2829. }
  2830. select {
  2831. case <-timeout.C:
  2832. if created {
  2833. t.Errorf("Timed out before file from remote was created")
  2834. } else {
  2835. t.Errorf("Timed out before directory was resurrected in db")
  2836. }
  2837. return
  2838. default:
  2839. time.Sleep(100 * time.Millisecond)
  2840. }
  2841. }
  2842. }
  2843. func TestVersionRestore(t *testing.T) {
  2844. // We create a bunch of files which we restore
  2845. // In each file, we write the filename as the content
  2846. // We verify that the content matches at the expected filenames
  2847. // after the restore operation.
  2848. dir, err := ioutil.TempDir("", "")
  2849. if err != nil {
  2850. t.Fatal(err)
  2851. }
  2852. defer os.RemoveAll(dir)
  2853. dbi := db.OpenMemory()
  2854. fcfg := config.NewFolderConfiguration(protocol.LocalDeviceID, "default", "default", fs.FilesystemTypeBasic, dir)
  2855. fcfg.Versioning.Type = "simple"
  2856. fcfg.FSWatcherEnabled = false
  2857. filesystem := fcfg.Filesystem()
  2858. rawConfig := config.Configuration{
  2859. Folders: []config.FolderConfiguration{fcfg},
  2860. }
  2861. cfg := createTmpWrapper(rawConfig)
  2862. defer os.Remove(cfg.ConfigPath())
  2863. m := NewModel(cfg, protocol.LocalDeviceID, "syncthing", "dev", dbi, nil)
  2864. m.AddFolder(fcfg)
  2865. m.StartFolder("default")
  2866. m.ServeBackground()
  2867. defer m.Stop()
  2868. m.ScanFolder("default")
  2869. sentinel, err := time.ParseInLocation(versioner.TimeFormat, "20200101-010101", locationLocal)
  2870. if err != nil {
  2871. t.Fatal(err)
  2872. }
  2873. sentinelTag := sentinel.Format(versioner.TimeFormat)
  2874. for _, file := range []string{
  2875. // Versions directory
  2876. ".stversions/file~20171210-040404.txt", // will be restored
  2877. ".stversions/existing~20171210-040404", // exists, should expect to be archived.
  2878. ".stversions/something~20171210-040404", // will become directory, hence error
  2879. ".stversions/dir/file~20171210-040404.txt",
  2880. ".stversions/dir/file~20171210-040405.txt",
  2881. ".stversions/dir/file~20171210-040406.txt",
  2882. ".stversions/very/very/deep/one~20171210-040406.txt", // lives deep down, no directory exists.
  2883. ".stversions/dir/existing~20171210-040406.txt", // exists, should expect to be archived.
  2884. ".stversions/dir/file.txt~20171210-040405", // incorrect tag format, ignored.
  2885. ".stversions/dir/cat", // incorrect tag format, ignored.
  2886. // "file.txt" will be restored
  2887. "existing",
  2888. "something/file", // Becomes directory
  2889. "dir/file.txt",
  2890. "dir/existing.txt",
  2891. } {
  2892. if runtime.GOOS == "windows" {
  2893. file = filepath.FromSlash(file)
  2894. }
  2895. dir := filepath.Dir(file)
  2896. if err := filesystem.MkdirAll(dir, 0755); err != nil {
  2897. t.Fatal(err)
  2898. }
  2899. if fd, err := filesystem.Create(file); err != nil {
  2900. t.Fatal(err)
  2901. } else if _, err := fd.Write([]byte(file)); err != nil {
  2902. t.Fatal(err)
  2903. } else if err := fd.Close(); err != nil {
  2904. t.Fatal(err)
  2905. } else if err := filesystem.Chtimes(file, sentinel, sentinel); err != nil {
  2906. t.Fatal(err)
  2907. }
  2908. }
  2909. versions, err := m.GetFolderVersions("default")
  2910. if err != nil {
  2911. t.Fatal(err)
  2912. }
  2913. expectedVersions := map[string]int{
  2914. "file.txt": 1,
  2915. "existing": 1,
  2916. "something": 1,
  2917. "dir/file.txt": 3,
  2918. "dir/existing.txt": 1,
  2919. "very/very/deep/one.txt": 1,
  2920. }
  2921. for name, vers := range versions {
  2922. cnt, ok := expectedVersions[name]
  2923. if !ok {
  2924. t.Errorf("unexpected %s", name)
  2925. }
  2926. if len(vers) != cnt {
  2927. t.Errorf("%s: %d != %d", name, cnt, len(vers))
  2928. }
  2929. // Delete, so we can check if we didn't hit something we expect afterwards.
  2930. delete(expectedVersions, name)
  2931. }
  2932. for name := range expectedVersions {
  2933. t.Errorf("not found expected %s", name)
  2934. }
  2935. // Restoring non existing folder fails.
  2936. _, err = m.RestoreFolderVersions("does not exist", nil)
  2937. if err == nil {
  2938. t.Errorf("expected an error")
  2939. }
  2940. makeTime := func(s string) time.Time {
  2941. tm, err := time.ParseInLocation(versioner.TimeFormat, s, locationLocal)
  2942. if err != nil {
  2943. t.Error(err)
  2944. }
  2945. return tm.Truncate(time.Second)
  2946. }
  2947. restore := map[string]time.Time{
  2948. "file.txt": makeTime("20171210-040404"),
  2949. "existing": makeTime("20171210-040404"),
  2950. "something": makeTime("20171210-040404"),
  2951. "dir/file.txt": makeTime("20171210-040406"),
  2952. "dir/existing.txt": makeTime("20171210-040406"),
  2953. "very/very/deep/one.txt": makeTime("20171210-040406"),
  2954. }
  2955. ferr, err := m.RestoreFolderVersions("default", restore)
  2956. if err != nil {
  2957. t.Fatal(err)
  2958. }
  2959. if err, ok := ferr["something"]; len(ferr) > 1 || !ok || err != "cannot replace a non-file" {
  2960. t.Fatalf("incorrect error or count: %d %s", len(ferr), ferr)
  2961. }
  2962. // Failed items are not expected to be restored.
  2963. // Remove them from expectations
  2964. for name := range ferr {
  2965. delete(restore, name)
  2966. }
  2967. // Check that content of files matches to the version they've been restored.
  2968. for file, version := range restore {
  2969. if runtime.GOOS == "windows" {
  2970. file = filepath.FromSlash(file)
  2971. }
  2972. tag := version.In(locationLocal).Truncate(time.Second).Format(versioner.TimeFormat)
  2973. taggedName := filepath.Join(".stversions", versioner.TagFilename(file, tag))
  2974. fd, err := filesystem.Open(file)
  2975. if err != nil {
  2976. t.Error(err)
  2977. }
  2978. defer fd.Close()
  2979. content, err := ioutil.ReadAll(fd)
  2980. if err != nil {
  2981. t.Error(err)
  2982. }
  2983. if !bytes.Equal(content, []byte(taggedName)) {
  2984. t.Errorf("%s: %s != %s", file, string(content), taggedName)
  2985. }
  2986. }
  2987. // Simple versioner uses modtime for timestamp generation, so we can check
  2988. // if existing stuff was correctly archived as we restored.
  2989. expectArchived := map[string]struct{}{
  2990. "existing": {},
  2991. "dir/file.txt": {},
  2992. "dir/existing.txt": {},
  2993. }
  2994. // Even if they are at the archived path, content should have the non
  2995. // archived name.
  2996. for file := range expectArchived {
  2997. if runtime.GOOS == "windows" {
  2998. file = filepath.FromSlash(file)
  2999. }
  3000. taggedName := versioner.TagFilename(file, sentinelTag)
  3001. taggedArchivedName := filepath.Join(".stversions", taggedName)
  3002. fd, err := filesystem.Open(taggedArchivedName)
  3003. if err != nil {
  3004. t.Fatal(err)
  3005. }
  3006. defer fd.Close()
  3007. content, err := ioutil.ReadAll(fd)
  3008. if err != nil {
  3009. t.Error(err)
  3010. }
  3011. if !bytes.Equal(content, []byte(file)) {
  3012. t.Errorf("%s: %s != %s", file, string(content), file)
  3013. }
  3014. }
  3015. // Check for other unexpected things that are tagged.
  3016. filesystem.Walk(".", func(path string, f fs.FileInfo, err error) error {
  3017. if !f.IsRegular() {
  3018. return nil
  3019. }
  3020. if strings.Contains(path, sentinelTag) {
  3021. path = osutil.NormalizedFilename(path)
  3022. name, _ := versioner.UntagFilename(path)
  3023. name = strings.TrimPrefix(name, ".stversions/")
  3024. if _, ok := expectArchived[name]; !ok {
  3025. t.Errorf("unexpected file with sentinel tag: %s", name)
  3026. }
  3027. }
  3028. return nil
  3029. })
  3030. }
  3031. func TestPausedFolders(t *testing.T) {
  3032. // Create a separate wrapper not to pollute other tests.
  3033. cfg := defaultCfgWrapper.RawCopy()
  3034. wrapper := createTmpWrapper(cfg)
  3035. defer os.Remove(wrapper.ConfigPath())
  3036. db := db.OpenMemory()
  3037. m := NewModel(wrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  3038. m.AddFolder(defaultFolderConfig)
  3039. m.StartFolder("default")
  3040. m.ServeBackground()
  3041. defer m.Stop()
  3042. if err := m.ScanFolder("default"); err != nil {
  3043. t.Error(err)
  3044. }
  3045. pausedConfig := wrapper.RawCopy()
  3046. pausedConfig.Folders[0].Paused = true
  3047. w, err := m.cfg.Replace(pausedConfig)
  3048. if err != nil {
  3049. t.Fatal(err)
  3050. }
  3051. w.Wait()
  3052. if err := m.ScanFolder("default"); err != ErrFolderPaused {
  3053. t.Errorf("Expected folder paused error, received: %v", err)
  3054. }
  3055. if err := m.ScanFolder("nonexistent"); err != errFolderMissing {
  3056. t.Errorf("Expected missing folder error, received: %v", err)
  3057. }
  3058. }
  3059. func TestIssue4094(t *testing.T) {
  3060. db := db.OpenMemory()
  3061. // Create a separate wrapper not to pollute other tests.
  3062. wrapper := createTmpWrapper(config.Configuration{})
  3063. defer os.Remove(wrapper.ConfigPath())
  3064. m := NewModel(wrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  3065. m.ServeBackground()
  3066. defer m.Stop()
  3067. // Force the model to wire itself and add the folders
  3068. folderPath := "testdata/nonexistent"
  3069. defer os.RemoveAll(folderPath)
  3070. cfg := defaultCfgWrapper.RawCopy()
  3071. fcfg := config.FolderConfiguration{
  3072. ID: "folder1",
  3073. Path: folderPath,
  3074. Paused: true,
  3075. Devices: []config.FolderDeviceConfiguration{
  3076. {DeviceID: device1},
  3077. },
  3078. }
  3079. cfg.Folders = []config.FolderConfiguration{fcfg}
  3080. p, err := wrapper.Replace(cfg)
  3081. if err != nil {
  3082. t.Fatal(err)
  3083. }
  3084. p.Wait()
  3085. if err := m.SetIgnores(fcfg.ID, []string{"foo"}); err != nil {
  3086. t.Fatalf("failed setting ignores: %v", err)
  3087. }
  3088. if _, err := fcfg.Filesystem().Lstat(".stignore"); err != nil {
  3089. t.Fatalf("failed stating .stignore: %v", err)
  3090. }
  3091. }
  3092. func TestIssue4903(t *testing.T) {
  3093. db := db.OpenMemory()
  3094. // Create a separate wrapper not to pollute other tests.
  3095. wrapper := createTmpWrapper(config.Configuration{})
  3096. defer os.Remove(wrapper.ConfigPath())
  3097. m := NewModel(wrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  3098. m.ServeBackground()
  3099. defer m.Stop()
  3100. // Force the model to wire itself and add the folders
  3101. folderPath := "testdata/nonexistent"
  3102. defer os.RemoveAll(folderPath)
  3103. cfg := defaultCfgWrapper.RawCopy()
  3104. fcfg := config.FolderConfiguration{
  3105. ID: "folder1",
  3106. Path: folderPath,
  3107. Paused: true,
  3108. Devices: []config.FolderDeviceConfiguration{
  3109. {DeviceID: device1},
  3110. },
  3111. }
  3112. cfg.Folders = []config.FolderConfiguration{fcfg}
  3113. p, err := wrapper.Replace(cfg)
  3114. if err != nil {
  3115. t.Fatal(err)
  3116. }
  3117. p.Wait()
  3118. if err := fcfg.CheckPath(); err != config.ErrPathMissing {
  3119. t.Fatalf("expected path missing error, got: %v", err)
  3120. }
  3121. if _, err := fcfg.Filesystem().Lstat("."); !fs.IsNotExist(err) {
  3122. t.Fatalf("Expected missing path error, got: %v", err)
  3123. }
  3124. }
  3125. func TestIssue5002(t *testing.T) {
  3126. // recheckFile should not panic when given an index equal to the number of blocks
  3127. db := db.OpenMemory()
  3128. m := NewModel(defaultCfgWrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  3129. m.AddFolder(defaultFolderConfig)
  3130. m.StartFolder("default")
  3131. m.ServeBackground()
  3132. defer m.Stop()
  3133. if err := m.ScanFolder("default"); err != nil {
  3134. t.Error(err)
  3135. }
  3136. file, ok := m.CurrentFolderFile("default", "foo")
  3137. if !ok {
  3138. t.Fatal("test file should exist")
  3139. }
  3140. nBlocks := len(file.Blocks)
  3141. m.recheckFile(protocol.LocalDeviceID, defaultFolderConfig.Filesystem(), "default", "foo", nBlocks-1, []byte{1, 2, 3, 4})
  3142. m.recheckFile(protocol.LocalDeviceID, defaultFolderConfig.Filesystem(), "default", "foo", nBlocks, []byte{1, 2, 3, 4}) // panic
  3143. m.recheckFile(protocol.LocalDeviceID, defaultFolderConfig.Filesystem(), "default", "foo", nBlocks+1, []byte{1, 2, 3, 4})
  3144. }
  3145. func TestParentOfUnignored(t *testing.T) {
  3146. wcfg, m := newState(defaultCfg)
  3147. defer func() {
  3148. m.Stop()
  3149. defaultFolderConfig.Filesystem().Remove(".stignore")
  3150. os.Remove(wcfg.ConfigPath())
  3151. }()
  3152. m.SetIgnores("default", []string{"!quux", "*"})
  3153. if parent, ok := m.CurrentFolderFile("default", "baz"); !ok {
  3154. t.Errorf(`Directory "baz" missing in db`)
  3155. } else if parent.IsIgnored() {
  3156. t.Errorf(`Directory "baz" is ignored`)
  3157. }
  3158. }
  3159. func addFakeConn(m *Model, dev protocol.DeviceID) *fakeConnection {
  3160. fc := &fakeConnection{id: dev, model: m}
  3161. m.AddConnection(fc, protocol.HelloResult{})
  3162. m.ClusterConfig(dev, protocol.ClusterConfig{
  3163. Folders: []protocol.Folder{
  3164. {
  3165. ID: "default",
  3166. Devices: []protocol.Device{
  3167. {ID: device1},
  3168. {ID: device2},
  3169. },
  3170. },
  3171. },
  3172. })
  3173. return fc
  3174. }
  3175. func TestFolderRestartZombies(t *testing.T) {
  3176. // This is for issue 5233, where multiple concurrent folder restarts
  3177. // would leave more than one folder runner alive.
  3178. wrapper := createTmpWrapper(defaultCfg.Copy())
  3179. folderCfg, _ := wrapper.Folder("default")
  3180. folderCfg.FilesystemType = fs.FilesystemTypeFake
  3181. wrapper.SetFolder(folderCfg)
  3182. db := db.OpenMemory()
  3183. m := NewModel(wrapper, protocol.LocalDeviceID, "syncthing", "dev", db, nil)
  3184. m.AddFolder(folderCfg)
  3185. m.StartFolder("default")
  3186. m.ServeBackground()
  3187. defer m.Stop()
  3188. // Make sure the folder is up and running, because we want to count it.
  3189. m.ScanFolder("default")
  3190. // Check how many running folders we have running before the test.
  3191. if r := atomic.LoadInt32(&m.foldersRunning); r != 1 {
  3192. t.Error("Expected one running folder, not", r)
  3193. }
  3194. // Run a few parallel configuration changers for one second. Each waits
  3195. // for the commit to complete, but there are many of them.
  3196. var wg sync.WaitGroup
  3197. for i := 0; i < 25; i++ {
  3198. wg.Add(1)
  3199. go func() {
  3200. defer wg.Done()
  3201. t0 := time.Now()
  3202. for time.Since(t0) < time.Second {
  3203. cfg := folderCfg.Copy()
  3204. cfg.MaxConflicts = rand.Int() // safe change that should cause a folder restart
  3205. w, err := wrapper.SetFolder(cfg)
  3206. if err != nil {
  3207. panic(err)
  3208. }
  3209. w.Wait()
  3210. }
  3211. }()
  3212. }
  3213. // Wait for the above to complete and check how many folders we have
  3214. // running now. It should not have increased.
  3215. wg.Wait()
  3216. // Make sure the folder is up and running, because we want to count it.
  3217. m.ScanFolder("default")
  3218. if r := atomic.LoadInt32(&m.foldersRunning); r != 1 {
  3219. t.Error("Expected one running folder, not", r)
  3220. }
  3221. }
  3222. type fakeAddr struct{}
  3223. func (fakeAddr) Network() string {
  3224. return "network"
  3225. }
  3226. func (fakeAddr) String() string {
  3227. return "address"
  3228. }
  3229. type alwaysChangedKey struct {
  3230. fs fs.Filesystem
  3231. name string
  3232. }
  3233. // alwaysChanges is an ignore.ChangeDetector that always returns true on Changed()
  3234. type alwaysChanged struct {
  3235. seen map[alwaysChangedKey]struct{}
  3236. }
  3237. func newAlwaysChanged() *alwaysChanged {
  3238. return &alwaysChanged{
  3239. seen: make(map[alwaysChangedKey]struct{}),
  3240. }
  3241. }
  3242. func (c *alwaysChanged) Remember(fs fs.Filesystem, name string, _ time.Time) {
  3243. c.seen[alwaysChangedKey{fs, name}] = struct{}{}
  3244. }
  3245. func (c *alwaysChanged) Reset() {
  3246. c.seen = make(map[alwaysChangedKey]struct{})
  3247. }
  3248. func (c *alwaysChanged) Seen(fs fs.Filesystem, name string) bool {
  3249. _, ok := c.seen[alwaysChangedKey{fs, name}]
  3250. return ok
  3251. }
  3252. func (c *alwaysChanged) Changed() bool {
  3253. return true
  3254. }