api.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. for _, v := range ledger.CurrentData()[protocol.MachinesLedgerKey] {
  108. machine := &types.Machine{}
  109. v.Unmarshal(machine)
  110. m := &apiTypes.Machine{Machine: *machine}
  111. if e.Host().Network().Connectedness(peer.ID(machine.PeerID)) == network.Connected {
  112. m.Connected = true
  113. }
  114. peers, err := e.MessageHub.ListPeers()
  115. if err != nil {
  116. return err
  117. }
  118. for _, p := range peers {
  119. if p.String() == machine.PeerID {
  120. m.OnChain = true
  121. }
  122. }
  123. list = append(list, m)
  124. }
  125. return c.JSON(http.StatusOK, list)
  126. })
  127. ec.GET(NodesURL, func(c echo.Context) error {
  128. list := []apiTypes.Peer{}
  129. peers, err := e.MessageHub.ListPeers()
  130. if err != nil {
  131. return err
  132. }
  133. for _, v := range peers {
  134. list = append(list, apiTypes.Peer{ID: v.String()})
  135. }
  136. return c.JSON(http.StatusOK, list)
  137. })
  138. ec.GET(PeerstoreURL, func(c echo.Context) error {
  139. list := []apiTypes.Peer{}
  140. for _, v := range e.Host().Network().Peerstore().Peers() {
  141. list = append(list, apiTypes.Peer{ID: v.String()})
  142. }
  143. peers, err := e.MessageHub.ListPeers()
  144. if err != nil {
  145. return err
  146. }
  147. return c.JSON(http.StatusOK, peers)
  148. })
  149. ec.GET(UsersURL, func(c echo.Context) error {
  150. user := []*types.User{}
  151. for _, v := range ledger.CurrentData()[protocol.UsersLedgerKey] {
  152. u := &types.User{}
  153. v.Unmarshal(u)
  154. user = append(user, u)
  155. }
  156. return c.JSON(http.StatusOK, user)
  157. })
  158. ec.GET(ServiceURL, func(c echo.Context) error {
  159. list := []*types.Service{}
  160. for _, v := range ledger.CurrentData()[protocol.ServicesLedgerKey] {
  161. srvc := &types.Service{}
  162. v.Unmarshal(srvc)
  163. list = append(list, srvc)
  164. }
  165. return c.JSON(http.StatusOK, list)
  166. })
  167. ec.GET("/*", echo.WrapHandler(http.StripPrefix("/", assetHandler)))
  168. ec.GET(BlockchainURL, func(c echo.Context) error {
  169. return c.JSON(http.StatusOK, ledger.LastBlock())
  170. })
  171. ec.GET(LedgerURL, func(c echo.Context) error {
  172. return c.JSON(http.StatusOK, ledger.CurrentData())
  173. })
  174. ec.GET(fmt.Sprintf("%s/:bucket/:key", LedgerURL), func(c echo.Context) error {
  175. bucket := c.Param("bucket")
  176. key := c.Param("key")
  177. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket][key])
  178. })
  179. ec.GET(fmt.Sprintf("%s/:bucket", LedgerURL), func(c echo.Context) error {
  180. bucket := c.Param("bucket")
  181. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket])
  182. })
  183. announcing := struct{ State string }{"Announcing"}
  184. // Store arbitrary data
  185. ec.PUT(fmt.Sprintf("%s/:bucket/:key/:value", LedgerURL), func(c echo.Context) error {
  186. bucket := c.Param("bucket")
  187. key := c.Param("key")
  188. value := c.Param("value")
  189. ledger.Persist(context.Background(), defaultInterval, timeout, bucket, key, value)
  190. return c.JSON(http.StatusOK, announcing)
  191. })
  192. ec.GET(DNSURL, func(c echo.Context) error {
  193. res := []apiTypes.DNS{}
  194. for r, e := range ledger.CurrentData()[protocol.DNSKey] {
  195. var t types.DNS
  196. e.Unmarshal(&t)
  197. d := map[string]string{}
  198. for k, v := range t {
  199. d[dns.TypeToString[uint16(k)]] = v
  200. }
  201. res = append(res,
  202. apiTypes.DNS{
  203. Regex: r,
  204. Records: d,
  205. })
  206. }
  207. return c.JSON(http.StatusOK, res)
  208. })
  209. // Announce dns
  210. ec.POST(DNSURL, func(c echo.Context) error {
  211. d := new(apiTypes.DNS)
  212. if err := c.Bind(d); err != nil {
  213. return echo.NewHTTPError(http.StatusBadRequest, err.Error())
  214. }
  215. entry := make(types.DNS)
  216. for r, e := range d.Records {
  217. entry[dns.Type(dns.StringToType[r])] = e
  218. }
  219. services.PersistDNSRecord(context.Background(), ledger, defaultInterval, timeout, d.Regex, entry)
  220. return c.JSON(http.StatusOK, announcing)
  221. })
  222. // Delete data from ledger
  223. ec.DELETE(fmt.Sprintf("%s/:bucket", LedgerURL), func(c echo.Context) error {
  224. bucket := c.Param("bucket")
  225. ledger.AnnounceDeleteBucket(context.Background(), defaultInterval, timeout, bucket)
  226. return c.JSON(http.StatusOK, announcing)
  227. })
  228. ec.DELETE(fmt.Sprintf("%s/:bucket/:key", LedgerURL), func(c echo.Context) error {
  229. bucket := c.Param("bucket")
  230. key := c.Param("key")
  231. ledger.AnnounceDeleteBucketKey(context.Background(), defaultInterval, timeout, bucket, key)
  232. return c.JSON(http.StatusOK, announcing)
  233. })
  234. ec.HideBanner = true
  235. if err := ec.Start(l); err != nil && err != http.ErrServerClosed {
  236. return err
  237. }
  238. go func() {
  239. <-ctx.Done()
  240. ct, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  241. ec.Shutdown(ct)
  242. cancel()
  243. }()
  244. return nil
  245. }