MtnMCG

cluster storage node

Sep 6th, 2024 (edited)
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.93 KB | None | 0 0
  1. -- store_node.lua
  2.  
  3. local modem = peripheral.find("modem") or error("No modem found")
  4. local drive = peripheral.find("drive") or error("No disk drive found")
  5.  
  6. modem.open(1) -- Open channel 1 for communication
  7.  
  8. local function sendResponse(id, response)
  9. modem.transmit(1, 1, {id = id, response = response})
  10. end
  11.  
  12. local function handleRequest(sender, message)
  13. if message.type == "discovery" then
  14. modem.transmit(1, 1, {type = "discovery_response", id = os.getComputerID()})
  15. elseif message.targetNode == os.getComputerID() then
  16. if message.action == "write" then
  17. if not drive.isDiskPresent() then
  18. sendResponse(message.id, {success = false, error = "No disk present"})
  19. return
  20. end
  21. local path = fs.combine(drive.getMountPath(), message.path .. "_chunk_" .. message.chunk)
  22. local file = fs.open(path, "w")
  23. file.write(message.content)
  24. file.close()
  25. sendResponse(message.id, {success = true})
  26. elseif message.action == "read" then
  27. if not drive.isDiskPresent() then
  28. sendResponse(message.id, {success = false, error = "No disk present"})
  29. return
  30. end
  31. local path = fs.combine(drive.getMountPath(), message.path .. "_chunk_" .. message.chunk)
  32. if fs.exists(path) then
  33. local file = fs.open(path, "r")
  34. local content = file.readAll()
  35. file.close()
  36. sendResponse(message.id, {success = true, content = content})
  37. else
  38. sendResponse(message.id, {success = false, error = "File not found"})
  39. end
  40. elseif message.action == "delete" then
  41. if not drive.isDiskPresent() then
  42. sendResponse(message.id, {success = false, error = "No disk present"})
  43. return
  44. end
  45. local path = fs.combine(drive.getMountPath(), message.path .. "_chunk_" .. message.chunk)
  46. if fs.exists(path) then
  47. fs.delete(path)
  48. sendResponse(message.id, {success = true})
  49. else
  50. sendResponse(message.id, {success = false, error = "File not found"})
  51. end
  52. elseif message.action == "getSpace" then
  53. if not drive.isDiskPresent() then
  54. sendResponse(message.id, {success = false, error = "No disk present"})
  55. return
  56. end
  57. local freeSpace = fs.getFreeSpace(drive.getMountPath())
  58. sendResponse(message.id, {success = true, space = freeSpace})
  59. end
  60. end
  61. end
  62.  
  63. print("Storage node ready. Waiting for requests...")
  64. print("Node ID: " .. os.getComputerID())
  65.  
  66. while true do
  67. local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
  68. if channel == 1 then
  69. handleRequest(side, message)
  70. end
  71. end
Advertisement
Add Comment
Please, Sign In to add comment