cluster.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. package main
  2. import (
  3. "io"
  4. "net/http"
  5. "net/url"
  6. "path/filepath"
  7. "sync"
  8. "time"
  9. "encoding/json"
  10. "errors"
  11. "strings"
  12. "imuslab.com/arozos/mod/cluster/capability"
  13. "imuslab.com/arozos/mod/cluster/events"
  14. "imuslab.com/arozos/mod/cluster/identity"
  15. "imuslab.com/arozos/mod/cluster/jobs"
  16. "imuslab.com/arozos/mod/cluster/membership"
  17. "imuslab.com/arozos/mod/cluster/metadata"
  18. "imuslab.com/arozos/mod/cluster/replication"
  19. "imuslab.com/arozos/mod/cluster/scheduling"
  20. "imuslab.com/arozos/mod/cluster/storage"
  21. fs "imuslab.com/arozos/mod/filesystem"
  22. "imuslab.com/arozos/mod/filesystem/abstractions/clusterfs"
  23. "imuslab.com/arozos/mod/filesystem/arozfs"
  24. "imuslab.com/arozos/mod/info/usageinfo"
  25. "imuslab.com/arozos/mod/network/neighbour"
  26. prout "imuslab.com/arozos/mod/prouter"
  27. "imuslab.com/arozos/mod/time/nightly"
  28. )
  29. /*
  30. Functions related to ArozOS clusters
  31. Author: tobychui
  32. This is a section of the arozos core that handle cluster
  33. related function endpoints:
  34. - Neighbourhood: mDNS discovery of nearby ArozOS hosts (LAN only)
  35. - Cluster membership: the cluster agent of this node (mod/cluster/membership)
  36. reachable by other nodes under /cluster/acn/* (see main.router.go)
  37. */
  38. var (
  39. NeighbourDiscoverer *neighbour.Discoverer
  40. clusterManager *membership.Manager
  41. clusterIdentity *identity.Manager
  42. clusterMetadata *metadata.Manager
  43. clusterStorage *storage.Service
  44. clusterReplication *replication.Manager
  45. clusterEvents *events.Bus
  46. clusterJobs *jobs.Manager
  47. clusterScheduling *scheduling.Manager
  48. clusterMountMu sync.Mutex
  49. )
  50. // clusterRunHook executes an event hook script as its owner with the event
  51. // readable through postPara("event") (JSON).
  52. func clusterRunHook(h events.Hook, ev events.Event) error {
  53. if AGIGateway == nil {
  54. return errors.New("AGI gateway not ready")
  55. }
  56. u, err := userHandler.GetUserInfoFromUsername(h.Owner)
  57. if err != nil {
  58. return err
  59. }
  60. fsh, err := u.GetFileSystemHandlerFromVirtualPath(h.Script)
  61. if err != nil {
  62. return err
  63. }
  64. rpath, err := fsh.FileSystemAbstraction.VirtualPathToRealPath(h.Script, u.Username)
  65. if err != nil {
  66. return err
  67. }
  68. if !fsh.FileSystemAbstraction.FileExists(rpath) {
  69. return errors.New("hook script not found: " + h.Script)
  70. }
  71. js, _ := json.Marshal(ev)
  72. form := "event=" + url.QueryEscape(string(js))
  73. req, _ := http.NewRequest(http.MethodPost, "/system/cluster/events/hook", strings.NewReader(form))
  74. req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  75. _, _, err = AGIGateway.ExecuteAGIScriptAsUser(fsh, rpath, u, nil, req)
  76. return err
  77. }
  78. // clusterProvider adapts the cluster services to the AGI cluster library.
  79. type clusterProvider struct{}
  80. func (c *clusterProvider) InCluster() bool {
  81. return clusterManager != nil && clusterManager.InCluster()
  82. }
  83. func (c *clusterProvider) Self() interface{} {
  84. for _, n := range clusterManager.NodeViews() {
  85. if n.Local {
  86. return n
  87. }
  88. }
  89. return nil
  90. }
  91. func (c *clusterProvider) Nodes() interface{} { return clusterManager.NodeViews() }
  92. func (c *clusterProvider) Status() interface{} {
  93. out := map[string]interface{}{"cluster": clusterManager.Cluster(), "identityOrigin": clusterManager.IdentityOrigin()}
  94. if clusterMetadata != nil {
  95. out["metadata"] = clusterMetadata.Status()
  96. out["volumes"] = clusterMetadata.Volumes()
  97. }
  98. if clusterStorage != nil {
  99. out["storage"] = clusterStorage.Status()
  100. }
  101. if clusterReplication != nil {
  102. out["replication"] = clusterReplication.Status()
  103. }
  104. return out
  105. }
  106. func (c *clusterProvider) Stat(path string) (interface{}, error) {
  107. if clusterMetadata == nil {
  108. return nil, errors.New("metadata store not available")
  109. }
  110. return clusterMetadata.Stat(path)
  111. }
  112. func (c *clusterProvider) List(path string) (interface{}, error) {
  113. if clusterMetadata == nil {
  114. return nil, errors.New("metadata store not available")
  115. }
  116. return clusterMetadata.ListDir(path)
  117. }
  118. func (c *clusterProvider) SetReplicas(path string, n int) error {
  119. if clusterMetadata == nil {
  120. return errors.New("metadata store not available")
  121. }
  122. if n < 0 || n > 16 {
  123. return errors.New("replicas must be between 0 and 16")
  124. }
  125. rec, err := clusterMetadata.Stat(path)
  126. if err != nil {
  127. return err
  128. }
  129. rec.Replicas = n
  130. return clusterMetadata.Submit(metadata.KindFile, rec)
  131. }
  132. func (c *clusterProvider) SetPolicy(folder string, n int) error {
  133. if clusterMetadata == nil {
  134. return errors.New("metadata store not available")
  135. }
  136. if n < 1 || n > 16 {
  137. return errors.New("replicas must be between 1 and 16")
  138. }
  139. return clusterMetadata.Submit(metadata.KindPolicy, &metadata.Policy{Folder: folder, Replicas: n})
  140. }
  141. func (c *clusterProvider) AddHook(owner string, types []string, script string) (interface{}, error) {
  142. if clusterEvents == nil {
  143. return nil, errors.New("event bus not available")
  144. }
  145. return clusterEvents.AddHook(owner, types, script)
  146. }
  147. func (c *clusterProvider) RemoveHook(id string, owner string) error {
  148. if clusterEvents == nil {
  149. return errors.New("event bus not available")
  150. }
  151. return clusterEvents.RemoveHook(id, owner)
  152. }
  153. func (c *clusterProvider) Hooks(owner string) interface{} {
  154. if clusterEvents == nil {
  155. return []events.Hook{}
  156. }
  157. return clusterEvents.Hooks(owner)
  158. }
  159. func (c *clusterProvider) SubmitJob(owner string, name string, scriptVpath string, args []byte, inputs []string, features []string, nodes []string, timeoutSec int, dataset string, partitionMax int) (interface{}, error) {
  160. if clusterJobs == nil {
  161. return nil, errors.New("cluster jobs not available")
  162. }
  163. if err := clusterDatasetAllowed(owner, strings.TrimSpace(dataset)); err != nil {
  164. return nil, err
  165. }
  166. source, err := clusterReadScript(owner, scriptVpath)
  167. if err != nil {
  168. return nil, err
  169. }
  170. req := jobs.SubmitRequest{
  171. Name: name, ScriptVpath: scriptVpath, Script: source,
  172. Inputs: inputs, Features: features, Nodes: nodes, TimeoutSec: timeoutSec,
  173. Dataset: dataset, PartitionMax: partitionMax,
  174. }
  175. if len(args) > 0 && json.Valid(args) {
  176. req.Args = json.RawMessage(args)
  177. }
  178. return clusterJobs.Submit(jobs.SpecFrom(req, owner))
  179. }
  180. func (c *clusterProvider) JobStatus(id string, requester string, isAdmin bool) (interface{}, error) {
  181. if clusterJobs == nil {
  182. return nil, errors.New("cluster jobs not available")
  183. }
  184. rec, ok := clusterJobs.Get(id)
  185. if !ok || (!isAdmin && rec.Spec.Owner != requester) {
  186. return nil, errors.New("job not found")
  187. }
  188. return rec, nil
  189. }
  190. func (c *clusterProvider) JobList(owner string) interface{} {
  191. if clusterJobs == nil {
  192. return []jobs.Record{}
  193. }
  194. return clusterJobs.List(owner)
  195. }
  196. func (c *clusterProvider) CancelJob(id string, requester string, isAdmin bool) error {
  197. if clusterJobs == nil {
  198. return errors.New("cluster jobs not available")
  199. }
  200. return clusterJobs.Cancel(id, requester, isAdmin)
  201. }
  202. func (c *clusterProvider) WaitJob(id string, timeoutSec int, requester string, isAdmin bool) (interface{}, error) {
  203. if clusterJobs == nil {
  204. return nil, errors.New("cluster jobs not available")
  205. }
  206. rec, ok := clusterJobs.Get(id)
  207. if !ok || (!isAdmin && rec.Spec.Owner != requester) {
  208. return nil, errors.New("job not found")
  209. }
  210. return clusterJobs.WaitFor(id, timeoutSec)
  211. }
  212. func (c *clusterProvider) Emit(user string, evType string, data []byte) error {
  213. if clusterEvents == nil {
  214. return errors.New("event bus not available")
  215. }
  216. evType = strings.ToLower(strings.TrimSpace(evType))
  217. if evType == "" {
  218. return errors.New("event type required")
  219. }
  220. if !strings.HasPrefix(evType, "app.") {
  221. evType = "app." + evType
  222. }
  223. if len(data) > 64<<10 {
  224. return errors.New("event data too large (64 KB max)")
  225. }
  226. clusterEvents.Publish(events.Event{Type: evType, User: user, Data: json.RawMessage(data)})
  227. return nil
  228. }
  229. // clusterLocalRoots lists the local, non-buffered drives a volume may live on.
  230. func clusterLocalRoots() map[string]string {
  231. roots := map[string]string{}
  232. for _, fsh := range GetAllLoadedFsh() {
  233. if fsh == nil || fsh.Closed || fsh.RequireBuffer || fsh.UUID == "tmp" || fsh.UUID == "cluster" {
  234. continue
  235. }
  236. if arozfs.IsNetworkDrive(fsh.Filesystem) {
  237. continue
  238. }
  239. roots[fsh.UUID] = filepath.Clean(fsh.Path)
  240. }
  241. return roots
  242. }
  243. // clusterBackend adapts the storage service to the clusterfs backend interface.
  244. type clusterBackend struct{ s *storage.Service }
  245. func toInfo(i storage.Info) clusterfs.Info {
  246. return clusterfs.Info{Path: i.Path, IsDir: i.IsDir, Size: i.Size, ModTime: i.ModTime}
  247. }
  248. func (b *clusterBackend) Stat(p string) (clusterfs.Info, error) {
  249. i, err := b.s.Stat(p)
  250. return toInfo(i), err
  251. }
  252. func (b *clusterBackend) List(p string) ([]clusterfs.Info, error) {
  253. items, err := b.s.List(p)
  254. if err != nil {
  255. return nil, err
  256. }
  257. out := make([]clusterfs.Info, 0, len(items))
  258. for _, i := range items {
  259. out = append(out, toInfo(i))
  260. }
  261. return out, nil
  262. }
  263. func (b *clusterBackend) Mkdir(p string, owner string) error { return b.s.Mkdir(p, owner) }
  264. func (b *clusterBackend) Remove(p string, recursive bool) error { return b.s.Remove(p, recursive) }
  265. func (b *clusterBackend) Rename(o string, n string) error { return b.s.Rename(o, n) }
  266. func (b *clusterBackend) OpenRead(p string) (io.ReadCloser, error) { return b.s.OpenRead(p) }
  267. func (b *clusterBackend) Write(p string, r io.Reader, owner string) error {
  268. return b.s.Write(p, r, owner)
  269. }
  270. func (b *clusterBackend) Ready() bool { return b.s.Ready() }
  271. // clusterMountDrive attaches the cluster:/ drive to the base storage pool, and
  272. // clusterUnmountDrive removes it again. Who sees it is up to its access list,
  273. // see storage.access.go.
  274. // clusterDriveWanted reports whether cluster:/ should be visible: this node
  275. // is in a cluster and the cluster has at least one volume to keep files in.
  276. // Without either, the drive is left out of File Manager and every other part
  277. // of the system, nightly tasks included.
  278. func clusterDriveWanted() bool {
  279. if clusterManager == nil || clusterStorage == nil || clusterMetadata == nil || !clusterManager.InCluster() {
  280. return false
  281. }
  282. return clusterHasVolume(clusterMetadata.Volumes())
  283. }
  284. // clusterHasVolume reports whether any volume is still part of the cluster.
  285. func clusterHasVolume(vols []metadata.Volume) bool {
  286. for _, v := range vols {
  287. if !v.Removed {
  288. return true
  289. }
  290. }
  291. return false
  292. }
  293. /*
  294. Master node
  295. Nightly maintenance of cluster:/ (expired trash, old version history)
  296. acts on files every member can see, so letting every node run it means
  297. doing the same scan, and the same deletions, once per node. The master
  298. node is the node holding the metadata leader lease, which is also the
  299. node that hands out placement and replication decisions.
  300. */
  301. // clusterIsMasterNode reports whether this node maintains the storage shared
  302. // by the cluster. A node with no cluster is the only node there is, so it is
  303. // its own master.
  304. func clusterIsMasterNode() bool {
  305. if *disable_cluster || clusterManager == nil || clusterMetadata == nil || !clusterManager.InCluster() {
  306. return true
  307. }
  308. return clusterMetadata.IsLeader()
  309. }
  310. // nightlyFshOption returns how nightly maintenance of one file system handler
  311. // should be run: a drive shared by the whole cluster is maintained by the
  312. // master node only, every other drive by the host it belongs to.
  313. func nightlyFshOption(fsh *fs.FileSystemHandler) nightly.TaskOption {
  314. if fsh != nil && fsh.Filesystem == "cluster" {
  315. return nightly.TaskOption{Name: "cluster:/ maintenance", MasterNodeOnly: true}
  316. }
  317. return nightly.TaskOption{}
  318. }
  319. // nightlyShouldMaintainFsh reports whether tonight's maintenance of this file
  320. // system handler belongs to this host.
  321. func nightlyShouldMaintainFsh(fsh *fs.FileSystemHandler) bool {
  322. return nightlyManager.ShouldRun(nightlyFshOption(fsh))
  323. }
  324. // clusterSyncDrive mounts or unmounts cluster:/ to match clusterDriveWanted.
  325. func clusterSyncDrive() {
  326. if clusterDriveWanted() {
  327. clusterMountDrive()
  328. } else {
  329. clusterUnmountDrive()
  330. }
  331. }
  332. func clusterMountDrive() {
  333. clusterMountMu.Lock()
  334. defer clusterMountMu.Unlock()
  335. if clusterStorage == nil || baseStoragePool == nil || !clusterManager.InCluster() {
  336. return
  337. }
  338. if baseStoragePool.ContainDiskID("cluster") {
  339. return
  340. }
  341. handler := &fs.FileSystemHandler{
  342. Name: "Cluster",
  343. UUID: "cluster",
  344. Path: "cluster:/",
  345. Hierarchy: "public",
  346. HierarchyConfig: fs.DefaultEmptyHierarchySpecificConfig,
  347. ReadOnly: false,
  348. RequireBuffer: true,
  349. InitiationTime: time.Now().Unix(),
  350. FileSystemAbstraction: clusterfs.New("cluster", &clusterBackend{s: clusterStorage}),
  351. Filesystem: "cluster",
  352. StartOptions: fs.FileSystemOption{Name: "Cluster", Uuid: "cluster", Path: "cluster:/", Hierarchy: "public", Filesystem: "cluster"},
  353. RuntimePersistenceConfig: fs.RuntimePersistenceConfig{
  354. LocalBufferPath: *tmp_directory,
  355. },
  356. }
  357. if err := baseStoragePool.AttachFsHandler(handler); err != nil {
  358. systemWideLogger.PrintAndLog("Cluster", "Unable to mount cluster drive: "+err.Error(), err)
  359. return
  360. }
  361. systemWideLogger.PrintAndLog("Cluster", "cluster:/ mounted", nil)
  362. go clusterRemoveThumbnailFolders()
  363. }
  364. func clusterUnmountDrive() {
  365. clusterMountMu.Lock()
  366. defer clusterMountMu.Unlock()
  367. if baseStoragePool == nil || !baseStoragePool.ContainDiskID("cluster") {
  368. return
  369. }
  370. baseStoragePool.DetachFsHandler("cluster")
  371. systemWideLogger.PrintAndLog("Cluster", "cluster:/ unmounted", nil)
  372. }
  373. // clusterAccountStore adapts the auth agent and permission handler to the
  374. // identity service's AccountStore interface.
  375. type clusterAccountStore struct{}
  376. func (s *clusterAccountStore) UserExists(username string) bool { return authAgent.UserExists(username) }
  377. func (s *clusterAccountStore) PasswordHash(username string) (string, error) {
  378. return authAgent.GetPasswordHash(username)
  379. }
  380. func (s *clusterAccountStore) SetPasswordHash(username string, hash string) error {
  381. return authAgent.SetPasswordHash(username, hash)
  382. }
  383. func (s *clusterAccountStore) Groups(username string) ([]string, error) {
  384. return authAgent.GetUserGroups(username)
  385. }
  386. func (s *clusterAccountStore) SetGroups(username string, groups []string) error {
  387. return authAgent.SetUserGroups(username, groups)
  388. }
  389. func (s *clusterAccountStore) ListUsers() []string { return authAgent.ListUsers() }
  390. func (s *clusterAccountStore) DeleteUser(username string) error {
  391. return authAgent.UnregisterUser(username)
  392. }
  393. func (s *clusterAccountStore) GroupExists(group string) bool {
  394. return permissionHandler.GroupExists(group)
  395. }
  396. // clusterNotifyPasswordChanged forwards a password change of a replicated
  397. // account to the identity origin. Safe to call when clustering is off.
  398. func clusterNotifyPasswordChanged(username string, passwordHash string) {
  399. if clusterIdentity != nil {
  400. clusterIdentity.NotifyPasswordChanged(username, passwordHash)
  401. }
  402. }
  403. // clusterHealthProvider builds the load snapshot shipped with each heartbeat.
  404. // RAM figures are cached because reading them shells out on some platforms.
  405. type clusterHealthProvider struct {
  406. mu sync.Mutex
  407. ramUsed int64
  408. ramTotal int64
  409. ramSample time.Time
  410. }
  411. func (p *clusterHealthProvider) snapshot() membership.Health {
  412. h := membership.Health{}
  413. if cpu, _, _, _, ready := usageinfo.GetCachedStats(); ready {
  414. h.CPUUsage = cpu
  415. }
  416. p.mu.Lock()
  417. if time.Since(p.ramSample) > time.Minute {
  418. used, total := usageinfo.GetNumericRAMUsage()
  419. if total > 0 {
  420. p.ramUsed, p.ramTotal = used, total
  421. }
  422. p.ramSample = time.Now()
  423. }
  424. h.RAMUsed, h.RAMTotal = p.ramUsed, p.ramTotal
  425. p.mu.Unlock()
  426. if free, total, err := capability.DiskUsage(filepath.Clean(*root_directory)); err == nil {
  427. h.DiskFree, h.DiskTotal = free, total
  428. }
  429. return h
  430. }
  431. func ClusterInit() {
  432. if *disable_cluster {
  433. systemWideLogger.PrintAndLog("Cluster", "Cluster features are disabled by the -disable_cluster flag", nil)
  434. } else {
  435. clusterStartAgent()
  436. }
  437. clusterStartNeighbourhood()
  438. //Let the nightly tasks know which node maintains the shared storage
  439. nightlyManager.SetMasterNodeResolver(clusterIsMasterNode)
  440. }
  441. // clusterStartAgent starts the cluster agent and every cluster service on
  442. // top of it. It is always available unless -disable_cluster is set, so a node
  443. // can create or join a cluster from System Settings regardless of the LAN
  444. // discovery features.
  445. func clusterStartAgent() {
  446. health := &clusterHealthProvider{}
  447. manager, err := membership.NewManager(membership.Option{
  448. NodeID: deviceUUID,
  449. DBFile: filepath.Join("system", "cluster.db"),
  450. KeyFile: filepath.Join("system", "cluster", "node.key"),
  451. Version: build_version + " " + internal_version,
  452. DefaultName: *host_name,
  453. Health: health.snapshot,
  454. })
  455. if err != nil {
  456. systemWideLogger.PrintAndLog("Cluster", "Unable to start cluster agent: "+err.Error(), err)
  457. } else {
  458. clusterManager = manager
  459. //Settings first, then Info; Cluster Jobs is added once the job runtime starts
  460. registerSetting(settingModule{
  461. Name: "Cluster Settings",
  462. Desc: "Create or join a cluster and set up its storage and scheduling",
  463. IconPath: "SystemAO/cluster/img/small_icon.png",
  464. Group: "Cluster",
  465. StartDir: "SystemAO/cluster/cluster.html",
  466. RequireAdmin: true,
  467. })
  468. registerSetting(settingModule{
  469. Name: "Cluster Info",
  470. Desc: "Health of this node, its peers, replication and scheduling",
  471. IconPath: "SystemAO/cluster/img/small_icon.png",
  472. Group: "Cluster",
  473. StartDir: "SystemAO/cluster/clusterinfo.html",
  474. RequireAdmin: true,
  475. })
  476. adminRouter := prout.NewModuleRouter(prout.RouterOption{
  477. ModuleName: "System Setting",
  478. AdminOnly: true,
  479. UserHandler: userHandler,
  480. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  481. errorHandlePermissionDenied(w, r)
  482. },
  483. })
  484. registerAdmin := func(pattern string, handler func(http.ResponseWriter, *http.Request)) {
  485. adminRouter.HandleFunc(pattern, handler)
  486. }
  487. clusterManager.RegisterAdminRoutes(registerAdmin)
  488. //Identity service: forward auth to the cluster's identity origin with
  489. //replicated accounts as fallback, plus signed user assertions
  490. idm, err := identity.New(identity.Option{
  491. Membership: clusterManager,
  492. Accounts: &clusterAccountStore{},
  493. })
  494. if err != nil {
  495. systemWideLogger.PrintAndLog("Cluster", "Unable to start cluster identity service: "+err.Error(), err)
  496. } else {
  497. clusterIdentity = idm
  498. authAgent.ForwardAuth = clusterIdentity.ForwardAuth
  499. clusterIdentity.RegisterAdminRoutes(registerAdmin)
  500. }
  501. //Metadata store: replicated namespace index + leader lease
  502. mdm, err := metadata.New(metadata.Option{Membership: clusterManager})
  503. if err != nil {
  504. systemWideLogger.PrintAndLog("Cluster", "Unable to start cluster metadata store: "+err.Error(), err)
  505. } else {
  506. clusterMetadata = mdm
  507. clusterMetadata.RegisterAdminRoutes(registerAdmin)
  508. //Placement scoring shared by jobs, writes and replication
  509. if sch, err := scheduling.New(clusterManager, clusterMetadata); err != nil {
  510. systemWideLogger.PrintAndLog("Cluster", "Unable to start cluster scheduling: "+err.Error(), err)
  511. } else {
  512. clusterScheduling = sch
  513. clusterScheduling.RegisterAdminRoutes(registerAdmin, clusterSchedExplain)
  514. }
  515. //Storage: volumes, chunked transfer and the cluster:/ drive
  516. sto, err := storage.New(storage.Option{
  517. Membership: clusterManager,
  518. Metadata: clusterMetadata,
  519. Scheduler: clusterScheduling,
  520. TmpDir: *tmp_directory,
  521. LocalRoots: clusterLocalRoots,
  522. Thumbnailer: clusterRenderThumbnail,
  523. })
  524. if err != nil {
  525. systemWideLogger.PrintAndLog("Cluster", "Unable to start cluster storage: "+err.Error(), err)
  526. } else {
  527. clusterStorage = sto
  528. clusterStorage.RegisterAdminRoutes(registerAdmin)
  529. //Empty thumbnail folders earlier builds left in cluster:/
  530. nightlyManager.RegisterNightlyTask(func() { clusterRemoveThumbnailFolders() })
  531. prevChange := clusterManager.OnMembershipChange
  532. clusterManager.OnMembershipChange = func(in bool) {
  533. if prevChange != nil {
  534. prevChange(in)
  535. }
  536. clusterSyncDrive()
  537. }
  538. //Show or hide cluster:/ as volumes come and go
  539. clusterMetadata.OnChange = func(kind string, payload []byte) {
  540. if kind == metadata.KindVolume {
  541. go clusterSyncDrive()
  542. } else if kind == metadata.KindSetting {
  543. go clusterSettingChanged(payload)
  544. }
  545. }
  546. clusterSyncDrive()
  547. //Event bus: file / replica / node events, script hooks, web feed
  548. bus, err := events.New(clusterManager, clusterRunHook)
  549. if err != nil {
  550. systemWideLogger.PrintAndLog("Cluster", "Unable to start cluster event bus: "+err.Error(), err)
  551. } else {
  552. clusterEvents = bus
  553. clusterStorage.OnFileWritten = func(rec metadata.FileRecord) {
  554. bus.Publish(events.Event{Type: "file.created", Path: rec.Path, FileID: rec.ID, User: rec.Owner})
  555. }
  556. clusterStorage.OnFileRemoved = func(rec metadata.FileRecord) {
  557. bus.Publish(events.Event{Type: "file.removed", Path: rec.Path, FileID: rec.ID, User: rec.Owner})
  558. }
  559. clusterStorage.OnFileRenamed = func(oldPath string, rec metadata.FileRecord) {
  560. data, _ := json.Marshal(map[string]string{"from": oldPath})
  561. bus.Publish(events.Event{Type: "file.renamed", Path: rec.Path, FileID: rec.ID, User: rec.Owner, Data: data})
  562. }
  563. clusterStorage.OnReplicaVerified = func(rec metadata.FileRecord, volumeID string) {
  564. data, _ := json.Marshal(map[string]string{"volume": volumeID})
  565. bus.Publish(events.Event{Type: "replica.verified", Path: rec.Path, FileID: rec.ID, Data: data})
  566. }
  567. clusterStorage.OnReplicaStale = func(rec metadata.FileRecord, volumeID string) {
  568. data, _ := json.Marshal(map[string]string{"volume": volumeID})
  569. bus.Publish(events.Event{Type: "replica.stale", Path: rec.Path, FileID: rec.ID, Data: data})
  570. }
  571. clusterStorage.OnDiskFull = func(vol metadata.Volume) {
  572. data, _ := json.Marshal(map[string]interface{}{"volume": vol.ID, "name": vol.Name, "free": vol.Free, "capacity": vol.Capacity})
  573. bus.Publish(events.Event{Type: "node.diskfull", Node: vol.NodeID, Data: data})
  574. }
  575. userRouter := prout.NewModuleRouter(prout.RouterOption{
  576. ModuleName: "System Setting",
  577. AdminOnly: false,
  578. UserHandler: userHandler,
  579. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  580. errorHandlePermissionDenied(w, r)
  581. },
  582. })
  583. userRouter.HandleFunc("/system/cluster/events/ws", bus.HandleWebSocket)
  584. userRouter.HandleFunc("/system/cluster/events/hooks", func(w http.ResponseWriter, r *http.Request) {
  585. u, err := userHandler.GetUserInfoFromRequest(w, r)
  586. if err != nil {
  587. errorHandlePermissionDenied(w, r)
  588. return
  589. }
  590. owner := u.Username
  591. if u.IsAdmin() {
  592. owner = ""
  593. }
  594. js, _ := json.Marshal(bus.Hooks(owner))
  595. w.Header().Set("Content-Type", "application/json")
  596. w.Write(js)
  597. })
  598. }
  599. //Job runtime and scheduler
  600. jm, err := jobs.New(jobs.Option{
  601. Membership: clusterManager,
  602. Metadata: clusterMetadata,
  603. Executor: &clusterJobExecutor{},
  604. Scheduler: clusterScheduling,
  605. LocalityBytes: clusterJobLocality,
  606. })
  607. if err != nil {
  608. systemWideLogger.PrintAndLog("Cluster", "Unable to start cluster jobs: "+err.Error(), err)
  609. } else {
  610. clusterJobs = jm
  611. if clusterEvents != nil {
  612. clusterJobs.OnFinished = func(rec jobs.Record) {
  613. evType := "job.completed"
  614. if rec.State.Status != jobs.StatusSucceeded {
  615. evType = "job.failed"
  616. }
  617. data, _ := json.Marshal(map[string]string{"name": rec.Spec.Name, "status": rec.State.Status, "error": rec.State.Error})
  618. clusterEvents.Publish(events.Event{Type: evType, FileID: rec.Spec.ID, User: rec.Spec.Owner, Node: rec.State.Node, Data: data})
  619. }
  620. }
  621. jobRouter := prout.NewModuleRouter(prout.RouterOption{
  622. ModuleName: "Tasks Scheduler",
  623. AdminOnly: false,
  624. UserHandler: userHandler,
  625. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  626. errorHandlePermissionDenied(w, r)
  627. },
  628. })
  629. clusterJobs.RegisterUserRoutes(func(pattern string, handler func(http.ResponseWriter, *http.Request)) {
  630. jobRouter.HandleFunc(pattern, handler)
  631. }, clusterJobCaller, clusterJobSubmit)
  632. registerSetting(settingModule{
  633. Name: "Cluster Jobs",
  634. Desc: "Run scripts on any node of the cluster",
  635. IconPath: "SystemAO/cluster/img/small_icon.png",
  636. Group: "Cluster",
  637. StartDir: "SystemAO/cluster/jobs.html",
  638. RequireAdmin: false,
  639. })
  640. }
  641. //AGI "cluster" library
  642. if AGIGateway != nil {
  643. AGIGateway.Option.ClusterProvider = &clusterProvider{}
  644. AGIGateway.ClusterLibRegister()
  645. }
  646. //Replication: keep every file at its policy's copy count
  647. rep, err := replication.New(replication.Option{
  648. Membership: clusterManager,
  649. Metadata: clusterMetadata,
  650. Storage: clusterStorage,
  651. Scheduler: clusterScheduling,
  652. })
  653. if err != nil {
  654. systemWideLogger.PrintAndLog("Cluster", "Unable to start cluster replication: "+err.Error(), err)
  655. } else {
  656. clusterReplication = rep
  657. clusterReplication.RegisterAdminRoutes(registerAdmin)
  658. //Nightly integrity pass over this node's copies (1 GB budget)
  659. nightlyManager.RegisterNightlyTask(func() {
  660. if clusterStorage != nil && clusterManager.InCluster() {
  661. clusterStorage.VerifyLocalCopies(1 << 30)
  662. }
  663. })
  664. }
  665. }
  666. }
  667. }
  668. }
  669. // clusterStartNeighbourhood runs the older mDNS neighbour discovery, which is
  670. // separate from the cluster and governed by -allow_mdns.
  671. func clusterStartNeighbourhood() {
  672. //Only enable neighbourhood scanning on mdns enabled mode
  673. if *allow_mdns && MDNS != nil {
  674. //Start the network discovery
  675. thisDiscoverer := neighbour.NewDiscoverer(MDNS, sysdb)
  676. //Start a scan immediately (in go routine for non blocking)
  677. go func() {
  678. thisDiscoverer.UpdateScan(10)
  679. }()
  680. //Setup the scanning timer
  681. thisDiscoverer.StartScanning(300, 15)
  682. NeighbourDiscoverer = &thisDiscoverer
  683. //Register the settings
  684. registerSetting(settingModule{
  685. Name: "Neighbourhood",
  686. Desc: "Nearby ArOZ Host for Clustering",
  687. IconPath: "SystemAO/cluster/img/small_icon.png",
  688. Group: "Cluster",
  689. StartDir: "SystemAO/cluster/neighbour.html",
  690. RequireAdmin: false,
  691. })
  692. //Register cluster scanning endpoints
  693. router := prout.NewModuleRouter(prout.RouterOption{
  694. ModuleName: "System Setting",
  695. UserHandler: userHandler,
  696. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  697. errorHandlePermissionDenied(w, r)
  698. },
  699. })
  700. router.HandleFunc("/system/cluster/scan", NeighbourDiscoverer.HandleScanningRequest)
  701. router.HandleFunc("/system/cluster/record", NeighbourDiscoverer.HandleScanRecord)
  702. router.HandleFunc("/system/cluster/wol", NeighbourDiscoverer.HandleWakeOnLan)
  703. } else {
  704. systemWideLogger.PrintAndLog("Cluster", "MDNS not enabled or startup failed. Skipping Cluster Scanner initiation.", nil)
  705. }
  706. }
  707. // ClusterShutdown stops heartbeats and tunnels before the process exits.
  708. func ClusterShutdown() {
  709. if clusterJobs != nil {
  710. clusterJobs.Close()
  711. }
  712. if clusterEvents != nil {
  713. clusterEvents.Close()
  714. }
  715. if clusterReplication != nil {
  716. clusterReplication.Close()
  717. }
  718. if clusterStorage != nil {
  719. clusterStorage.Close()
  720. }
  721. if clusterMetadata != nil {
  722. clusterMetadata.Close()
  723. }
  724. if clusterIdentity != nil {
  725. clusterIdentity.Close()
  726. }
  727. if clusterManager != nil {
  728. clusterManager.Close()
  729. }
  730. }