server.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. package raft
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/http"
  9. "sort"
  10. "strings"
  11. "sync"
  12. "time"
  13. "igit.com/xbase/raft/db"
  14. )
  15. // KVServer wraps Raft to provide a distributed key-value store
  16. type KVServer struct {
  17. Raft *Raft
  18. DB *db.Engine
  19. CLI *CLI
  20. AuthManager *AuthManager
  21. Watcher *WebHookWatcher
  22. httpServer *http.Server
  23. stopCh chan struct{}
  24. wg sync.WaitGroup
  25. stopOnce sync.Once
  26. // leavingNodes tracks nodes that are currently being removed
  27. // to prevent auto-rejoin/discovery logic from interfering
  28. leavingNodes sync.Map
  29. // Pending requests for synchronous operations (Read-Your-Writes)
  30. pendingRequests map[uint64]chan error
  31. pendingMu sync.Mutex
  32. }
  33. // NewKVServer creates a new KV server
  34. func NewKVServer(config *Config) (*KVServer, error) {
  35. // Initialize DB Engine
  36. // Use a subdirectory for DB to avoid conflict with Raft logs if they share DataDir
  37. dbPath := config.DataDir + "/kv_engine"
  38. engine, err := db.NewEngine(dbPath)
  39. if err != nil {
  40. return nil, fmt.Errorf("failed to create db engine: %w", err)
  41. }
  42. // Initialize LastAppliedIndex from DB to prevent re-applying entries
  43. config.LastAppliedIndex = engine.GetLastAppliedIndex()
  44. // Create stop channel early for use in callbacks
  45. stopCh := make(chan struct{})
  46. // Configure snapshot provider
  47. config.SnapshotProvider = func(minIncludeIndex uint64) ([]byte, error) {
  48. // Wait for DB to catch up to the requested index
  49. // This is critical for data integrity during compaction
  50. for engine.GetLastAppliedIndex() < minIncludeIndex {
  51. select {
  52. case <-stopCh:
  53. return nil, fmt.Errorf("server stopping")
  54. default:
  55. time.Sleep(10 * time.Millisecond)
  56. }
  57. }
  58. // Force sync to disk to ensure data durability before compaction
  59. // This prevents data loss if Raft logs are compacted but DB data is only in OS cache
  60. if err := engine.Sync(); err != nil {
  61. return nil, fmt.Errorf("failed to sync engine before snapshot: %w", err)
  62. }
  63. return engine.Snapshot()
  64. }
  65. // Configure get handler for remote reads
  66. config.GetHandler = func(key string) (string, bool) {
  67. return engine.Get(key)
  68. }
  69. applyCh := make(chan ApplyMsg, 1000) // Increase buffer for async processing
  70. transport := NewTCPTransport(config.ListenAddr, 10, config.Logger)
  71. // Initialize WebHookWatcher
  72. // 5 workers, 3 retries
  73. watcher := NewWebHookWatcher(5, 3, config.Logger)
  74. r, err := NewRaft(config, transport, applyCh)
  75. if err != nil {
  76. engine.Close()
  77. return nil, err
  78. }
  79. s := &KVServer{
  80. Raft: r,
  81. DB: engine,
  82. CLI: nil,
  83. AuthManager: nil, // initialized below
  84. Watcher: watcher,
  85. stopCh: stopCh,
  86. pendingRequests: make(map[uint64]chan error),
  87. }
  88. // Initialize AuthManager
  89. s.AuthManager = NewAuthManager(s)
  90. // Load Auth Data from DB (if any)
  91. if err := s.AuthManager.LoadFromDB(); err != nil {
  92. s.Raft.config.Logger.Warn("Failed to load auth data from DB: %v", err)
  93. }
  94. // Initialize CLI
  95. s.CLI = NewCLI(s)
  96. // Start applying entries
  97. go s.runApplyLoop(applyCh)
  98. // Start background maintenance loop
  99. s.wg.Add(1)
  100. go s.maintenanceLoop()
  101. return s, nil
  102. }
  103. func (s *KVServer) Start() error {
  104. // Start CLI if enabled
  105. if s.Raft.config.EnableCLI {
  106. go s.CLI.Start()
  107. }
  108. // Start HTTP Server if configured
  109. if s.Raft.config.HTTPAddr != "" {
  110. if err := s.startHTTPServer(s.Raft.config.HTTPAddr); err != nil {
  111. s.Raft.config.Logger.Warn("Failed to start HTTP server: %v", err)
  112. }
  113. }
  114. // Start TCP Server (Hardcoded offset +10 for demo or config?)
  115. // User didn't add TCPPort to config, so let's derive it or just fix it.
  116. // For demo, if ListenAddr is 127.0.0.1:9001, we try 9011.
  117. host, port, _ := net.SplitHostPort(s.Raft.config.ListenAddr)
  118. if port == "9001" {
  119. tcpAddr := fmt.Sprintf("%s:%s", host, "9011")
  120. if err := s.StartTCPServer(tcpAddr); err != nil {
  121. s.Raft.config.Logger.Warn("Failed to start TCP server: %v", err)
  122. }
  123. } else if port == "9002" {
  124. tcpAddr := fmt.Sprintf("%s:%s", host, "9012")
  125. s.StartTCPServer(tcpAddr)
  126. } else {
  127. // Fallback or ignore for other nodes in demo
  128. }
  129. return s.Raft.Start()
  130. }
  131. func (s *KVServer) Stop() error {
  132. var err error
  133. s.stopOnce.Do(func() {
  134. // Stop maintenance loop
  135. if s.stopCh != nil {
  136. close(s.stopCh)
  137. s.wg.Wait()
  138. }
  139. // Stop Watcher
  140. if s.Watcher != nil {
  141. s.Watcher.Stop()
  142. }
  143. // Stop HTTP Server
  144. if s.httpServer != nil {
  145. s.httpServer.Close()
  146. }
  147. // Stop Raft first
  148. if errRaft := s.Raft.Stop(); errRaft != nil {
  149. err = errRaft
  150. }
  151. // Close DB
  152. if s.DB != nil {
  153. if errDB := s.DB.Close(); errDB != nil {
  154. // Combine errors if both fail
  155. if err != nil {
  156. err = fmt.Errorf("raft stop error: %v, db close error: %v", err, errDB)
  157. } else {
  158. err = errDB
  159. }
  160. }
  161. }
  162. })
  163. return err
  164. }
  165. func (s *KVServer) runApplyLoop(applyCh chan ApplyMsg) {
  166. for msg := range applyCh {
  167. if msg.CommandValid {
  168. // Optimization: Skip if already applied
  169. // We check this here to avoid unmarshalling and locking DB for known duplicates
  170. if msg.CommandIndex <= s.DB.GetLastAppliedIndex() {
  171. // Even if duplicate, we might have someone waiting for it if they just proposed it
  172. // but this is unlikely for duplicates.
  173. // However, notify waiters just in case.
  174. s.notifyPending(msg.CommandIndex, nil)
  175. continue
  176. }
  177. var cmd KVCommand
  178. if err := json.Unmarshal(msg.Command, &cmd); err != nil {
  179. s.Raft.config.Logger.Error("Failed to unmarshal command: %v", err)
  180. s.notifyPending(msg.CommandIndex, err)
  181. continue
  182. }
  183. var err error
  184. switch cmd.Type {
  185. case KVSet:
  186. // Update Auth Cache for system keys
  187. // This includes AuthLockPrefix now
  188. if strings.HasPrefix(cmd.Key, SystemKeyPrefix) {
  189. s.AuthManager.UpdateCache(cmd.Key, cmd.Value, false)
  190. }
  191. err = s.DB.Set(cmd.Key, cmd.Value, msg.CommandIndex)
  192. if err == nil {
  193. s.Watcher.Notify(cmd.Key, cmd.Value, KVSet)
  194. }
  195. case KVDel:
  196. // Update Auth Cache for system keys
  197. if strings.HasPrefix(cmd.Key, SystemKeyPrefix) {
  198. s.AuthManager.UpdateCache(cmd.Key, "", true)
  199. }
  200. err = s.DB.Delete(cmd.Key, msg.CommandIndex)
  201. if err == nil {
  202. s.Watcher.Notify(cmd.Key, "", KVDel)
  203. }
  204. default:
  205. s.Raft.config.Logger.Error("Unknown command type: %d", cmd.Type)
  206. }
  207. if err != nil {
  208. s.Raft.config.Logger.Error("DB Apply failed: %v", err)
  209. }
  210. // Notify anyone waiting for this index
  211. s.notifyPending(msg.CommandIndex, err)
  212. } else if msg.SnapshotValid {
  213. if err := s.DB.Restore(msg.Snapshot); err != nil {
  214. s.Raft.config.Logger.Error("DB Restore failed: %v", err)
  215. }
  216. }
  217. }
  218. }
  219. // notifyPending notifies any waiting requests for the given index
  220. func (s *KVServer) notifyPending(index uint64, err error) {
  221. s.pendingMu.Lock()
  222. defer s.pendingMu.Unlock()
  223. if ch, ok := s.pendingRequests[index]; ok {
  224. // Non-blocking send in case listener is gone (buffered channel recommended)
  225. select {
  226. case ch <- err:
  227. default:
  228. }
  229. close(ch)
  230. delete(s.pendingRequests, index)
  231. }
  232. }
  233. // SetAuthenticatedAsync sets a key-value pair asynchronously with permission check
  234. func (s *KVServer) SetAuthenticatedAsync(key, value, token string) error {
  235. if err := s.AuthManager.CheckPermission(token, key, ActionWrite, value); err != nil {
  236. return err
  237. }
  238. return s.Set(key, value)
  239. }
  240. // SetAuthenticated sets a key-value pair with permission check
  241. func (s *KVServer) SetAuthenticated(key, value, token string) error {
  242. if err := s.AuthManager.CheckPermission(token, key, ActionWrite, value); err != nil {
  243. return err
  244. }
  245. // Use SetSync for consistency in CLI/API
  246. return s.SetSync(key, value)
  247. }
  248. // DelAuthenticated deletes a key with permission check
  249. func (s *KVServer) DelAuthenticated(key, token string) error {
  250. if err := s.AuthManager.CheckPermission(token, key, ActionWrite, ""); err != nil {
  251. return err
  252. }
  253. // Use SetSync (via Del which should be updated or create DelSync)
  254. // For simplicity, we implement DelSync logic here or update Del to be sync?
  255. // Let's implement DelSync
  256. return s.DelSync(key)
  257. }
  258. // Set sets a key-value pair (Async - eventually consistent)
  259. func (s *KVServer) Set(key, value string) error {
  260. cmd := KVCommand{
  261. Type: KVSet,
  262. Key: key,
  263. Value: value,
  264. }
  265. data, err := json.Marshal(cmd)
  266. if err != nil {
  267. return err
  268. }
  269. _, _, err = s.Raft.ProposeWithForward(data)
  270. return err
  271. }
  272. // SetSync sets a key-value pair and waits for it to be applied (Read-Your-Writes)
  273. func (s *KVServer) SetSync(key, value string) error {
  274. cmd := KVCommand{
  275. Type: KVSet,
  276. Key: key,
  277. Value: value,
  278. }
  279. data, err := json.Marshal(cmd)
  280. if err != nil {
  281. return err
  282. }
  283. index, _, err := s.Raft.ProposeWithForward(data)
  284. if err != nil {
  285. return err
  286. }
  287. // Wait for application
  288. ch := make(chan error, 1)
  289. s.pendingMu.Lock()
  290. s.pendingRequests[index] = ch
  291. s.pendingMu.Unlock()
  292. select {
  293. case applyErr := <-ch:
  294. return applyErr
  295. case <-time.After(5 * time.Second):
  296. s.pendingMu.Lock()
  297. delete(s.pendingRequests, index)
  298. s.pendingMu.Unlock()
  299. return fmt.Errorf("timeout waiting for apply")
  300. }
  301. }
  302. // Del deletes a key (Async)
  303. func (s *KVServer) Del(key string) error {
  304. cmd := KVCommand{
  305. Type: KVDel,
  306. Key: key,
  307. }
  308. data, err := json.Marshal(cmd)
  309. if err != nil {
  310. return err
  311. }
  312. _, _, err = s.Raft.ProposeWithForward(data)
  313. return err
  314. }
  315. // DelSync deletes a key and waits for it to be applied
  316. func (s *KVServer) DelSync(key string) error {
  317. cmd := KVCommand{
  318. Type: KVDel,
  319. Key: key,
  320. }
  321. data, err := json.Marshal(cmd)
  322. if err != nil {
  323. return err
  324. }
  325. index, _, err := s.Raft.ProposeWithForward(data)
  326. if err != nil {
  327. return err
  328. }
  329. // Wait for application
  330. ch := make(chan error, 1)
  331. s.pendingMu.Lock()
  332. s.pendingRequests[index] = ch
  333. s.pendingMu.Unlock()
  334. select {
  335. case applyErr := <-ch:
  336. return applyErr
  337. case <-time.After(5 * time.Second):
  338. s.pendingMu.Lock()
  339. delete(s.pendingRequests, index)
  340. s.pendingMu.Unlock()
  341. return fmt.Errorf("timeout waiting for apply")
  342. }
  343. }
  344. // GetAuthenticated gets a value with permission check (local read)
  345. func (s *KVServer) GetAuthenticated(key, token string) (string, bool, error) {
  346. if err := s.AuthManager.CheckPermission(token, key, ActionRead, ""); err != nil {
  347. return "", false, err
  348. }
  349. val, ok := s.Get(key)
  350. return val, ok, nil
  351. }
  352. // Get gets a value (local read, can be stale)
  353. // For linearizable reads, use GetLinear instead
  354. func (s *KVServer) Get(key string) (string, bool) {
  355. return s.DB.Get(key)
  356. }
  357. // GetLinearAuthenticated gets a value with linearizable consistency and permission check
  358. func (s *KVServer) GetLinearAuthenticated(key, token string) (string, bool, error) {
  359. if err := s.AuthManager.CheckPermission(token, key, ActionRead, ""); err != nil {
  360. return "", false, err
  361. }
  362. return s.GetLinear(key)
  363. }
  364. // Logout invalidates the current session
  365. func (s *KVServer) Logout(token string) error {
  366. return s.AuthManager.Logout(token)
  367. }
  368. // GetSessionInfo returns the session details
  369. func (s *KVServer) GetSessionInfo(token string) (*Session, error) {
  370. return s.AuthManager.GetSession(token)
  371. }
  372. // IsAdmin checks if the token belongs to a user with admin privileges
  373. // defined as having "admin" action on "*" key pattern
  374. func (s *KVServer) IsAdmin(token string) bool {
  375. if !s.AuthManager.IsEnabled() {
  376. return true // If auth disabled, everyone is admin (or handled by caller)
  377. }
  378. // Check internal system token
  379. if token == "SYSTEM_INTERNAL" {
  380. return true
  381. }
  382. return s.AuthManager.CheckPermission(token, "*", ActionAdmin, "") == nil
  383. }
  384. // IsRoot checks if the token belongs to the root user
  385. // Deprecated: Use IsAdmin instead
  386. func (s *KVServer) IsRoot(token string) bool {
  387. sess, err := s.AuthManager.GetSession(token)
  388. if err != nil {
  389. return false
  390. }
  391. return sess.Username == "root"
  392. }
  393. // CreateUser creates a new user (Admin only)
  394. func (s *KVServer) CreateUser(username, password string, roles []string, token string) error {
  395. if s.AuthManager.IsEnabled() && !s.IsAdmin(token) {
  396. return fmt.Errorf("permission denied: admin access required")
  397. }
  398. // Use RegisterUserSync
  399. return s.AuthManager.RegisterUser(username, password, roles)
  400. }
  401. // DeleteUser deletes a user (Admin only)
  402. func (s *KVServer) DeleteUser(username string, token string) error {
  403. if s.AuthManager.IsEnabled() && !s.IsAdmin(token) {
  404. return fmt.Errorf("permission denied: admin access required")
  405. }
  406. // Check if user exists
  407. if _, err := s.AuthManager.GetUser(username); err != nil {
  408. return err
  409. }
  410. if username == "root" {
  411. return fmt.Errorf("cannot delete root user")
  412. }
  413. // Use DelSync
  414. return s.DelSync(AuthUserPrefix + username)
  415. }
  416. // UpdateUser updates generic user fields (Admin only)
  417. func (s *KVServer) UpdateUser(user User, token string) error {
  418. if s.AuthManager.IsEnabled() && !s.IsAdmin(token) {
  419. return fmt.Errorf("permission denied: admin access required")
  420. }
  421. // Check if user exists
  422. if _, err := s.AuthManager.GetUser(user.Username); err != nil {
  423. return err
  424. }
  425. return s.AuthManager.UpdateUser(user)
  426. }
  427. // ChangeUserPassword changes a user's password (Admin or Self)
  428. func (s *KVServer) ChangeUserPassword(username, newPassword string, token string) error {
  429. if s.AuthManager.IsEnabled() {
  430. session, err := s.AuthManager.GetSession(token)
  431. if err != nil {
  432. return err
  433. }
  434. // Allow if Admin OR Self
  435. if !s.IsAdmin(token) && session.Username != username {
  436. return fmt.Errorf("permission denied")
  437. }
  438. }
  439. // Use ChangePassword (which should use SetSync)
  440. return s.AuthManager.ChangePassword(username, newPassword)
  441. }
  442. // Role Management Helpers
  443. // CreateRole creates a new role (Admin only)
  444. func (s *KVServer) CreateRole(name string, token string) error {
  445. if s.AuthManager.IsEnabled() && !s.IsAdmin(token) {
  446. return fmt.Errorf("permission denied: admin access required")
  447. }
  448. return s.AuthManager.CreateRole(name)
  449. }
  450. // DeleteRole deletes a role (Admin only)
  451. func (s *KVServer) DeleteRole(name string, token string) error {
  452. if s.AuthManager.IsEnabled() && !s.IsAdmin(token) {
  453. return fmt.Errorf("permission denied: admin access required")
  454. }
  455. return s.AuthManager.DeleteRole(name)
  456. }
  457. // UpdateRole updates a role (Admin only)
  458. func (s *KVServer) UpdateRole(role Role, token string) error {
  459. if s.AuthManager.IsEnabled() && !s.IsAdmin(token) {
  460. return fmt.Errorf("permission denied: admin access required")
  461. }
  462. return s.AuthManager.UpdateRole(role)
  463. }
  464. // ListUsers lists all users (Admin only)
  465. func (s *KVServer) ListUsers(token string) ([]*User, error) {
  466. if s.AuthManager.IsEnabled() && !s.IsAdmin(token) {
  467. return nil, fmt.Errorf("permission denied: admin access required")
  468. }
  469. return s.AuthManager.ListUsers(), nil
  470. }
  471. // ListRoles lists all roles (Admin only)
  472. func (s *KVServer) ListRoles(token string) ([]*Role, error) {
  473. if s.AuthManager.IsEnabled() && !s.IsAdmin(token) {
  474. return nil, fmt.Errorf("permission denied: admin access required")
  475. }
  476. return s.AuthManager.ListRoles(), nil
  477. }
  478. // SearchAuthenticated searches keys with permission checks
  479. func (s *KVServer) SearchAuthenticated(pattern string, limit, offset int, token string) ([]db.QueryResult, error) {
  480. // Optimization: If user has full access (*), delegate to DB with limit/offset
  481. if s.AuthManager.HasFullAccess(token) {
  482. sql := fmt.Sprintf("key like \"%s\" LIMIT %d OFFSET %d", pattern, limit, offset)
  483. return s.DB.Query(sql)
  484. }
  485. // Slow path: Fetch all potential matches and filter
  486. // We construct a SQL query that retrieves CANDIDATES.
  487. // We cannot safely apply LIMIT/OFFSET in SQL because we might filter out some results.
  488. // So we must fetch ALL matches.
  489. // WARNING: This can be slow and memory intensive.
  490. // If pattern is wildcard, we might fetch everything.
  491. sql := fmt.Sprintf("key like \"%s\"", pattern)
  492. results, err := s.DB.Query(sql)
  493. if err != nil {
  494. return nil, err
  495. }
  496. filtered := make([]db.QueryResult, 0, len(results))
  497. // Apply Filtering
  498. for _, r := range results {
  499. if err := s.AuthManager.CheckPermission(token, r.Key, ActionRead, ""); err == nil {
  500. filtered = append(filtered, r)
  501. }
  502. }
  503. // Apply Pagination on Filtered Results
  504. if offset > len(filtered) {
  505. return []db.QueryResult{}, nil
  506. }
  507. start := offset
  508. end := offset + limit
  509. if end > len(filtered) {
  510. end = len(filtered)
  511. }
  512. return filtered[start:end], nil
  513. }
  514. // CountAuthenticated counts keys with permission checks
  515. func (s *KVServer) CountAuthenticated(pattern string, token string) (int, error) {
  516. // Optimization: If user has full access
  517. if s.AuthManager.HasFullAccess(token) {
  518. sql := ""
  519. if pattern == "*" {
  520. sql = "*"
  521. } else {
  522. sql = fmt.Sprintf("key like \"%s\"", pattern)
  523. }
  524. return s.DB.Count(sql)
  525. }
  526. // Slow path: Iterate and check
  527. // We use DB.Query to get keys (Query returns values too, which is wasteful but DB engine doesn't expose keys-only Query yet)
  528. // Actually, we can access s.DB.Index.WalkPrefix if we want to be faster and avoid value read,
  529. // but s.DB.Index is inside 'db' package. We can access it if it's exported.
  530. // 'db' package exports 'Engine' and 'FlatIndex'.
  531. // So s.DB.Index IS accessible.
  532. count := 0
  533. // Determine prefix from pattern
  534. prefix := ""
  535. if strings.HasSuffix(pattern, "*") {
  536. prefix = strings.TrimSuffix(pattern, "*")
  537. } else if pattern == "*" {
  538. prefix = ""
  539. } else {
  540. // Exact match check
  541. if err := s.AuthManager.CheckPermission(token, pattern, ActionRead, ""); err == nil {
  542. // Check if exists
  543. if _, ok := s.DB.Get(pattern); ok {
  544. return 1, nil
  545. }
  546. return 0, nil
  547. }
  548. return 0, nil // No perm or not found
  549. }
  550. // Walk
  551. // Note: WalkPrefix locks the DB Index (Read Lock).
  552. // Calling CheckPermission inside might involve some logic but it is memory-only and usually fast.
  553. // However, if CheckPermission takes time, we hold DB lock.
  554. s.DB.Index.WalkPrefix(prefix, func(key string, entry db.IndexEntry) bool {
  555. // Check pattern match first (WalkPrefix is just prefix, pattern might be more complex like "user.*.name")
  556. if !db.WildcardMatch(key, pattern) {
  557. return true
  558. }
  559. if err := s.AuthManager.CheckPermission(token, key, ActionRead, ""); err == nil {
  560. count++
  561. }
  562. return true
  563. })
  564. return count, nil
  565. }
  566. // GetLinear gets a value with linearizable consistency
  567. // This ensures the read sees all writes committed before the read started
  568. func (s *KVServer) GetLinear(key string) (string, bool, error) {
  569. // First, ensure we have up-to-date data via ReadIndex
  570. _, err := s.Raft.ReadIndex()
  571. if err != nil {
  572. // If we're not leader, try forwarding
  573. if errors.Is(err, ErrNotLeader) {
  574. return s.forwardGet(key)
  575. }
  576. return "", false, err
  577. }
  578. val, ok := s.DB.Get(key)
  579. return val, ok, nil
  580. }
  581. // forwardGet forwards a get request to the leader
  582. func (s *KVServer) forwardGet(key string) (string, bool, error) {
  583. return s.Raft.ForwardGet(key)
  584. }
  585. // Join joins an existing cluster
  586. func (s *KVServer) Join(nodeID, addr string) error {
  587. return s.Raft.AddNodeWithForward(nodeID, addr)
  588. }
  589. // Leave leaves the cluster
  590. func (s *KVServer) Leave(nodeID string) error {
  591. // Mark node as leaving to prevent auto-rejoin
  592. s.leavingNodes.Store(nodeID, time.Now())
  593. // Auto-expire the leaving flag after a while
  594. go func() {
  595. time.Sleep(30 * time.Second)
  596. s.leavingNodes.Delete(nodeID)
  597. }()
  598. // Remove from RaftNode discovery key first to prevent auto-rejoin
  599. if err := s.removeNodeFromDiscovery(nodeID); err != nil {
  600. s.Raft.config.Logger.Warn("Failed to remove node from discovery key: %v", err)
  601. // Continue anyway, as the main goal is to leave the cluster
  602. }
  603. return s.Raft.RemoveNodeWithForward(nodeID)
  604. }
  605. // removeNodeFromDiscovery removes a node from the RaftNode key to prevent auto-rejoin
  606. func (s *KVServer) removeNodeFromDiscovery(targetID string) error {
  607. val, ok := s.Get("RaftNode")
  608. if !ok || val == "" {
  609. return nil
  610. }
  611. parts := strings.Split(val, ";")
  612. var newParts []string
  613. changed := false
  614. for _, part := range parts {
  615. if part == "" {
  616. continue
  617. }
  618. kv := strings.SplitN(part, "=", 2)
  619. if len(kv) == 2 {
  620. if kv[0] == targetID {
  621. changed = true
  622. continue // Skip this node
  623. }
  624. newParts = append(newParts, part)
  625. }
  626. }
  627. if changed {
  628. newVal := strings.Join(newParts, ";")
  629. return s.Set("RaftNode", newVal)
  630. }
  631. return nil
  632. }
  633. // WaitForLeader waits until a leader is elected
  634. func (s *KVServer) WaitForLeader(timeout time.Duration) error {
  635. deadline := time.Now().Add(timeout)
  636. for time.Now().Before(deadline) {
  637. leader := s.Raft.GetLeaderID()
  638. if leader != "" {
  639. return nil
  640. }
  641. time.Sleep(100 * time.Millisecond)
  642. }
  643. return fmt.Errorf("timeout waiting for leader")
  644. }
  645. // HealthCheck returns the health status of this server
  646. func (s *KVServer) HealthCheck() HealthStatus {
  647. return s.Raft.HealthCheck()
  648. }
  649. // GetStats returns runtime statistics
  650. func (s *KVServer) GetStats() Stats {
  651. return s.Raft.GetStats()
  652. }
  653. // GetMetrics returns runtime metrics
  654. func (s *KVServer) GetMetrics() Metrics {
  655. return s.Raft.GetMetrics()
  656. }
  657. // TransferLeadership transfers leadership to the specified node
  658. func (s *KVServer) TransferLeadership(targetID string) error {
  659. return s.Raft.TransferLeadership(targetID)
  660. }
  661. // GetClusterNodes returns current cluster membership
  662. func (s *KVServer) GetClusterNodes() map[string]string {
  663. return s.Raft.GetClusterNodes()
  664. }
  665. // IsLeader returns true if this node is the leader
  666. func (s *KVServer) IsLeader() bool {
  667. _, isLeader := s.Raft.GetState()
  668. return isLeader
  669. }
  670. // GetLeaderID returns the current leader ID
  671. func (s *KVServer) GetLeaderID() string {
  672. return s.Raft.GetLeaderID()
  673. }
  674. // GetLogSize returns the raft log size
  675. func (s *KVServer) GetLogSize() int64 {
  676. return s.Raft.log.GetLogSize()
  677. }
  678. // GetDBSize returns the db size
  679. func (s *KVServer) GetDBSize() int64 {
  680. return s.DB.GetDBSize()
  681. }
  682. // WatchURL registers a webhook url for a key
  683. func (s *KVServer) WatchURL(key, url string) {
  684. s.Watcher.Subscribe(key, url)
  685. }
  686. // UnwatchURL removes a webhook url for a key
  687. func (s *KVServer) UnwatchURL(key, url string) {
  688. s.Watcher.Unsubscribe(key, url)
  689. }
  690. // WatchAll registers a watcher for all keys
  691. func (s *KVServer) WatchAll(handler WatchHandler) {
  692. // s.FSM.WatchAll(handler)
  693. // TODO: Implement Watcher for DB
  694. }
  695. // Watch registers a watcher for a key
  696. func (s *KVServer) Watch(key string, handler WatchHandler) {
  697. // s.FSM.Watch(key, handler)
  698. // TODO: Implement Watcher for DB
  699. }
  700. // Unwatch removes watchers for a key
  701. func (s *KVServer) Unwatch(key string) {
  702. // s.FSM.Unwatch(key)
  703. // TODO: Implement Watcher for DB
  704. }
  705. func (s *KVServer) maintenanceLoop() {
  706. defer s.wg.Done()
  707. // Check every 1 second for faster reaction
  708. ticker := time.NewTicker(1 * time.Second)
  709. defer ticker.Stop()
  710. for {
  711. select {
  712. case <-s.stopCh:
  713. return
  714. case <-ticker.C:
  715. s.updateNodeInfo()
  716. s.checkConnections()
  717. }
  718. }
  719. }
  720. func (s *KVServer) updateNodeInfo() {
  721. // 1. Ensure "CreateNode/<NodeID>" is set to self address
  722. // We do this via Propose (Set) so it's replicated
  723. myID := s.Raft.config.NodeID
  724. myAddr := s.Raft.config.ListenAddr
  725. key := fmt.Sprintf("CreateNode/%s", myID)
  726. // Check if we need to update (avoid spamming logs/proposals)
  727. val, exists := s.Get(key)
  728. if !exists || val != myAddr {
  729. // Run in goroutine to avoid blocking
  730. go func() {
  731. if err := s.Set(key, myAddr); err != nil {
  732. s.Raft.config.Logger.Debug("Failed to update node info: %v", err)
  733. }
  734. }()
  735. }
  736. // 2. Only leader updates RaftNode aggregation
  737. if s.IsLeader() {
  738. // Read current RaftNode to preserve history
  739. currentVal, _ := s.Get("RaftNode")
  740. knownNodes := make(map[string]string)
  741. if currentVal != "" {
  742. parts := strings.Split(currentVal, ";")
  743. for _, part := range parts {
  744. if part == "" { continue }
  745. kv := strings.SplitN(part, "=", 2)
  746. if len(kv) == 2 {
  747. knownNodes[kv[0]] = kv[1]
  748. }
  749. }
  750. }
  751. // Merge current cluster nodes
  752. changed := false
  753. currentCluster := s.GetClusterNodes()
  754. for id, addr := range currentCluster {
  755. // Skip nodes that are marked as leaving
  756. if _, leaving := s.leavingNodes.Load(id); leaving {
  757. continue
  758. }
  759. if knownNodes[id] != addr {
  760. knownNodes[id] = addr
  761. changed = true
  762. }
  763. }
  764. // If changed, update RaftNode
  765. if changed {
  766. var peers []string
  767. for id, addr := range knownNodes {
  768. peers = append(peers, fmt.Sprintf("%s=%s", id, addr))
  769. }
  770. sort.Strings(peers)
  771. newVal := strings.Join(peers, ";")
  772. // Check again if we need to write to avoid loops if Get returned stale
  773. if newVal != currentVal {
  774. go func(k, v string) {
  775. if err := s.Set(k, v); err != nil {
  776. s.Raft.config.Logger.Warn("Failed to update RaftNode key: %v", err)
  777. }
  778. }("RaftNode", newVal)
  779. }
  780. }
  781. }
  782. }
  783. func (s *KVServer) checkConnections() {
  784. if !s.IsLeader() {
  785. return
  786. }
  787. // Read RaftNode key to find potential members that are missing
  788. val, ok := s.Get("RaftNode")
  789. if !ok || val == "" {
  790. return
  791. }
  792. // Parse saved nodes
  793. savedParts := strings.Split(val, ";")
  794. currentNodes := s.GetClusterNodes()
  795. // Invert currentNodes for address check
  796. currentAddrs := make(map[string]bool)
  797. for _, addr := range currentNodes {
  798. currentAddrs[addr] = true
  799. }
  800. for _, part := range savedParts {
  801. if part == "" {
  802. continue
  803. }
  804. // Expect id=addr
  805. kv := strings.SplitN(part, "=", 2)
  806. if len(kv) != 2 {
  807. continue
  808. }
  809. id, addr := kv[0], kv[1]
  810. // Skip invalid addresses
  811. if strings.HasPrefix(addr, ".") || !strings.Contains(addr, ":") {
  812. continue
  813. }
  814. if !currentAddrs[addr] {
  815. // Skip nodes that are marked as leaving
  816. if _, leaving := s.leavingNodes.Load(id); leaving {
  817. continue
  818. }
  819. // Found a node that was previously in the cluster but is now missing
  820. // Try to add it back
  821. // We use AddNodeWithForward which handles non-blocking internally somewhat,
  822. // but we should run this in goroutine to not block the loop
  823. go func(nodeID, nodeAddr string) {
  824. // Try to add node
  825. s.Raft.config.Logger.Info("Auto-rejoining node found in RaftNode: %s (%s)", nodeID, nodeAddr)
  826. if err := s.Join(nodeID, nodeAddr); err != nil {
  827. s.Raft.config.Logger.Debug("Failed to auto-rejoin node %s: %v", nodeID, err)
  828. }
  829. }(id, addr)
  830. }
  831. }
  832. }
  833. // startHTTPServer starts the HTTP API server
  834. func (s *KVServer) startHTTPServer(addr string) error {
  835. mux := http.NewServeMux()
  836. // KV API
  837. mux.HandleFunc("/kv", func(w http.ResponseWriter, r *http.Request) {
  838. token := r.Header.Get("X-Raft-Token")
  839. switch r.Method {
  840. case http.MethodGet:
  841. key := r.URL.Query().Get("key")
  842. if key == "" {
  843. http.Error(w, "missing key", http.StatusBadRequest)
  844. return
  845. }
  846. // Use Authenticated method
  847. val, found, err := s.GetLinearAuthenticated(key, token)
  848. if err != nil {
  849. // Distinguish auth error vs raft error?
  850. if strings.Contains(err.Error(), "permission") || strings.Contains(err.Error(), "unauthorized") {
  851. http.Error(w, err.Error(), http.StatusForbidden)
  852. } else {
  853. http.Error(w, err.Error(), http.StatusInternalServerError)
  854. }
  855. return
  856. }
  857. if !found {
  858. http.Error(w, "not found", http.StatusNotFound)
  859. return
  860. }
  861. w.Write([]byte(val))
  862. case http.MethodPost:
  863. body, _ := io.ReadAll(r.Body)
  864. var req struct {
  865. Key string `json:"key"`
  866. Value string `json:"value"`
  867. }
  868. if err := json.Unmarshal(body, &req); err != nil {
  869. http.Error(w, "invalid json", http.StatusBadRequest)
  870. return
  871. }
  872. if err := s.SetAuthenticated(req.Key, req.Value, token); err != nil {
  873. if strings.Contains(err.Error(), "permission") || strings.Contains(err.Error(), "unauthorized") {
  874. http.Error(w, err.Error(), http.StatusForbidden)
  875. } else {
  876. http.Error(w, err.Error(), http.StatusInternalServerError)
  877. }
  878. return
  879. }
  880. w.WriteHeader(http.StatusOK)
  881. case http.MethodDelete:
  882. key := r.URL.Query().Get("key")
  883. if key == "" {
  884. http.Error(w, "missing key", http.StatusBadRequest)
  885. return
  886. }
  887. if err := s.DelAuthenticated(key, token); err != nil {
  888. if strings.Contains(err.Error(), "permission") || strings.Contains(err.Error(), "unauthorized") {
  889. http.Error(w, err.Error(), http.StatusForbidden)
  890. } else {
  891. http.Error(w, err.Error(), http.StatusInternalServerError)
  892. }
  893. return
  894. }
  895. w.WriteHeader(http.StatusOK)
  896. default:
  897. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  898. }
  899. })
  900. // Auth API
  901. mux.HandleFunc("/auth/login", func(w http.ResponseWriter, r *http.Request) {
  902. if r.Method != http.MethodPost {
  903. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  904. return
  905. }
  906. var req struct {
  907. Username string `json:"username"`
  908. Password string `json:"password"`
  909. Code string `json:"code"`
  910. }
  911. body, _ := io.ReadAll(r.Body)
  912. if err := json.Unmarshal(body, &req); err != nil {
  913. http.Error(w, "invalid json", http.StatusBadRequest)
  914. return
  915. }
  916. ip := r.RemoteAddr
  917. if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
  918. ip = host
  919. }
  920. token, err := s.AuthManager.Login(req.Username, req.Password, req.Code, ip)
  921. if err != nil {
  922. http.Error(w, err.Error(), http.StatusUnauthorized)
  923. return
  924. }
  925. resp := struct {
  926. Token string `json:"token"`
  927. }{Token: token}
  928. json.NewEncoder(w).Encode(resp)
  929. })
  930. // Watcher API
  931. mux.HandleFunc("/watch", func(w http.ResponseWriter, r *http.Request) {
  932. if r.Method != http.MethodPost {
  933. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  934. return
  935. }
  936. body, _ := io.ReadAll(r.Body)
  937. var req struct {
  938. Key string `json:"key"`
  939. URL string `json:"url"`
  940. }
  941. if err := json.Unmarshal(body, &req); err != nil {
  942. http.Error(w, "invalid json", http.StatusBadRequest)
  943. return
  944. }
  945. if req.Key == "" || req.URL == "" {
  946. http.Error(w, "missing key or url", http.StatusBadRequest)
  947. return
  948. }
  949. s.WatchURL(req.Key, req.URL)
  950. w.WriteHeader(http.StatusOK)
  951. })
  952. mux.HandleFunc("/unwatch", func(w http.ResponseWriter, r *http.Request) {
  953. if r.Method != http.MethodPost {
  954. http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
  955. return
  956. }
  957. body, _ := io.ReadAll(r.Body)
  958. var req struct {
  959. Key string `json:"key"`
  960. URL string `json:"url"`
  961. }
  962. if err := json.Unmarshal(body, &req); err != nil {
  963. http.Error(w, "invalid json", http.StatusBadRequest)
  964. return
  965. }
  966. s.UnwatchURL(req.Key, req.URL)
  967. w.WriteHeader(http.StatusOK)
  968. })
  969. s.httpServer = &http.Server{
  970. Addr: addr,
  971. Handler: mux,
  972. }
  973. go func() {
  974. s.Raft.config.Logger.Info("HTTP API server listening on %s", addr)
  975. if err := s.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  976. s.Raft.config.Logger.Error("HTTP server failed: %v", err)
  977. }
  978. }()
  979. return nil
  980. }