api.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. // Copyright © 2021-2022 Ettore Di Giacinto <[email protected]>
  2. //
  3. // This program is free software; you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation; either version 2 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program; if not, see <http://www.gnu.org/licenses/>.
  15. package api
  16. import (
  17. "context"
  18. "embed"
  19. "fmt"
  20. "io/fs"
  21. "net"
  22. "net/http"
  23. _ "net/http/pprof"
  24. "strings"
  25. "time"
  26. "github.com/libp2p/go-libp2p-core/network"
  27. "github.com/libp2p/go-libp2p-core/peer"
  28. "github.com/miekg/dns"
  29. apiTypes "github.com/mudler/edgevpn/api/types"
  30. "github.com/labstack/echo/v4"
  31. "github.com/mudler/edgevpn/pkg/node"
  32. "github.com/mudler/edgevpn/pkg/protocol"
  33. "github.com/mudler/edgevpn/pkg/services"
  34. "github.com/mudler/edgevpn/pkg/types"
  35. )
  36. //go:embed public
  37. var embededFiles embed.FS
  38. func getFileSystem() http.FileSystem {
  39. fsys, err := fs.Sub(embededFiles, "public")
  40. if err != nil {
  41. panic(err)
  42. }
  43. return http.FS(fsys)
  44. }
  45. const (
  46. MachineURL = "/api/machines"
  47. UsersURL = "/api/users"
  48. ServiceURL = "/api/services"
  49. BlockchainURL = "/api/blockchain"
  50. LedgerURL = "/api/ledger"
  51. SummaryURL = "/api/summary"
  52. FileURL = "/api/files"
  53. NodesURL = "/api/nodes"
  54. DNSURL = "/api/dns"
  55. PeerstoreURL = "/api/peerstore"
  56. )
  57. func API(ctx context.Context, l string, defaultInterval, timeout time.Duration, e *node.Node, debugMode bool) error {
  58. ledger, _ := e.Ledger()
  59. ec := echo.New()
  60. if strings.HasPrefix(l, "unix://") {
  61. unixListener, err := net.Listen("unix", strings.ReplaceAll(l, "unix://", ""))
  62. if err != nil {
  63. return err
  64. }
  65. ec.Listener = unixListener
  66. }
  67. assetHandler := http.FileServer(getFileSystem())
  68. if debugMode {
  69. ec.GET("/debug/pprof/*", echo.WrapHandler(http.DefaultServeMux))
  70. }
  71. // Get data from ledger
  72. ec.GET(FileURL, func(c echo.Context) error {
  73. list := []*types.File{}
  74. for _, v := range ledger.CurrentData()[protocol.FilesLedgerKey] {
  75. machine := &types.File{}
  76. v.Unmarshal(machine)
  77. list = append(list, machine)
  78. }
  79. return c.JSON(http.StatusOK, list)
  80. })
  81. ec.GET(SummaryURL, func(c echo.Context) error {
  82. files := len(ledger.CurrentData()[protocol.FilesLedgerKey])
  83. machines := len(ledger.CurrentData()[protocol.MachinesLedgerKey])
  84. users := len(ledger.CurrentData()[protocol.UsersLedgerKey])
  85. services := len(ledger.CurrentData()[protocol.ServicesLedgerKey])
  86. peers, err := e.MessageHub.ListPeers()
  87. if err != nil {
  88. return err
  89. }
  90. onChainNodes := len(peers)
  91. p2pPeers := len(e.Host().Network().Peerstore().Peers())
  92. nodeID := e.Host().ID().String()
  93. blockchain := ledger.Index()
  94. return c.JSON(http.StatusOK, types.Summary{
  95. Files: files,
  96. Machines: machines,
  97. Users: users,
  98. Services: services,
  99. BlockChain: blockchain,
  100. OnChainNodes: onChainNodes,
  101. Peers: p2pPeers,
  102. NodeID: nodeID,
  103. })
  104. })
  105. ec.GET(MachineURL, func(c echo.Context) error {
  106. list := []*apiTypes.Machine{}
  107. online := services.AvailableNodes(ledger, 20*time.Minute)
  108. for _, v := range ledger.CurrentData()[protocol.MachinesLedgerKey] {
  109. machine := &types.Machine{}
  110. v.Unmarshal(machine)
  111. m := &apiTypes.Machine{Machine: *machine}
  112. if e.Host().Network().Connectedness(peer.ID(machine.PeerID)) == network.Connected {
  113. m.Connected = true
  114. }
  115. peers, err := e.MessageHub.ListPeers()
  116. if err != nil {
  117. return err
  118. }
  119. for _, p := range peers {
  120. if p.String() == machine.PeerID {
  121. m.OnChain = true
  122. }
  123. }
  124. for _, a := range online {
  125. if a == machine.PeerID {
  126. m.Online = true
  127. }
  128. }
  129. list = append(list, m)
  130. }
  131. return c.JSON(http.StatusOK, list)
  132. })
  133. ec.GET(NodesURL, func(c echo.Context) error {
  134. list := []apiTypes.Peer{}
  135. peers, err := e.MessageHub.ListPeers()
  136. if err != nil {
  137. return err
  138. }
  139. // Sum up state also from services
  140. online := services.AvailableNodes(ledger, 10*time.Minute)
  141. p := map[string]interface{}{}
  142. for _, v := range online {
  143. p[v] = nil
  144. }
  145. for _, v := range peers {
  146. _, exists := p[v.String()]
  147. if !exists {
  148. p[v.String()] = nil
  149. }
  150. }
  151. for id, _ := range p {
  152. list = append(list, apiTypes.Peer{ID: id, Online: true})
  153. }
  154. return c.JSON(http.StatusOK, list)
  155. })
  156. ec.GET(PeerstoreURL, func(c echo.Context) error {
  157. list := []apiTypes.Peer{}
  158. for _, v := range e.Host().Network().Peerstore().Peers() {
  159. list = append(list, apiTypes.Peer{ID: v.String()})
  160. }
  161. return c.JSON(http.StatusOK, list)
  162. })
  163. ec.GET(UsersURL, func(c echo.Context) error {
  164. user := []*types.User{}
  165. for _, v := range ledger.CurrentData()[protocol.UsersLedgerKey] {
  166. u := &types.User{}
  167. v.Unmarshal(u)
  168. user = append(user, u)
  169. }
  170. return c.JSON(http.StatusOK, user)
  171. })
  172. ec.GET(ServiceURL, func(c echo.Context) error {
  173. list := []*types.Service{}
  174. for _, v := range ledger.CurrentData()[protocol.ServicesLedgerKey] {
  175. srvc := &types.Service{}
  176. v.Unmarshal(srvc)
  177. list = append(list, srvc)
  178. }
  179. return c.JSON(http.StatusOK, list)
  180. })
  181. ec.GET("/*", echo.WrapHandler(http.StripPrefix("/", assetHandler)))
  182. ec.GET(BlockchainURL, func(c echo.Context) error {
  183. return c.JSON(http.StatusOK, ledger.LastBlock())
  184. })
  185. ec.GET(LedgerURL, func(c echo.Context) error {
  186. return c.JSON(http.StatusOK, ledger.CurrentData())
  187. })
  188. ec.GET(fmt.Sprintf("%s/:bucket/:key", LedgerURL), func(c echo.Context) error {
  189. bucket := c.Param("bucket")
  190. key := c.Param("key")
  191. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket][key])
  192. })
  193. ec.GET(fmt.Sprintf("%s/:bucket", LedgerURL), func(c echo.Context) error {
  194. bucket := c.Param("bucket")
  195. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket])
  196. })
  197. announcing := struct{ State string }{"Announcing"}
  198. // Store arbitrary data
  199. ec.PUT(fmt.Sprintf("%s/:bucket/:key/:value", LedgerURL), func(c echo.Context) error {
  200. bucket := c.Param("bucket")
  201. key := c.Param("key")
  202. value := c.Param("value")
  203. ledger.Persist(context.Background(), defaultInterval, timeout, bucket, key, value)
  204. return c.JSON(http.StatusOK, announcing)
  205. })
  206. ec.GET(DNSURL, func(c echo.Context) error {
  207. res := []apiTypes.DNS{}
  208. for r, e := range ledger.CurrentData()[protocol.DNSKey] {
  209. var t types.DNS
  210. e.Unmarshal(&t)
  211. d := map[string]string{}
  212. for k, v := range t {
  213. d[dns.TypeToString[uint16(k)]] = v
  214. }
  215. res = append(res,
  216. apiTypes.DNS{
  217. Regex: r,
  218. Records: d,
  219. })
  220. }
  221. return c.JSON(http.StatusOK, res)
  222. })
  223. // Announce dns
  224. ec.POST(DNSURL, func(c echo.Context) error {
  225. d := new(apiTypes.DNS)
  226. if err := c.Bind(d); err != nil {
  227. return echo.NewHTTPError(http.StatusBadRequest, err.Error())
  228. }
  229. entry := make(types.DNS)
  230. for r, e := range d.Records {
  231. entry[dns.Type(dns.StringToType[r])] = e
  232. }
  233. services.PersistDNSRecord(context.Background(), ledger, defaultInterval, timeout, d.Regex, entry)
  234. return c.JSON(http.StatusOK, announcing)
  235. })
  236. // Delete data from ledger
  237. ec.DELETE(fmt.Sprintf("%s/:bucket", LedgerURL), func(c echo.Context) error {
  238. bucket := c.Param("bucket")
  239. ledger.AnnounceDeleteBucket(context.Background(), defaultInterval, timeout, bucket)
  240. return c.JSON(http.StatusOK, announcing)
  241. })
  242. ec.DELETE(fmt.Sprintf("%s/:bucket/:key", LedgerURL), func(c echo.Context) error {
  243. bucket := c.Param("bucket")
  244. key := c.Param("key")
  245. ledger.AnnounceDeleteBucketKey(context.Background(), defaultInterval, timeout, bucket, key)
  246. return c.JSON(http.StatusOK, announcing)
  247. })
  248. ec.HideBanner = true
  249. if err := ec.Start(l); err != nil && err != http.ErrServerClosed {
  250. return err
  251. }
  252. go func() {
  253. <-ctx.Done()
  254. ct, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  255. ec.Shutdown(ct)
  256. cancel()
  257. }()
  258. return nil
  259. }