api.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. "path/filepath"
  25. "strings"
  26. "time"
  27. "github.com/libp2p/go-libp2p/core/metrics"
  28. "github.com/libp2p/go-libp2p/core/network"
  29. "github.com/libp2p/go-libp2p/core/peer"
  30. p2pprotocol "github.com/libp2p/go-libp2p/core/protocol"
  31. "github.com/miekg/dns"
  32. apiTypes "github.com/mudler/edgevpn/api/types"
  33. "github.com/labstack/echo/v4"
  34. "github.com/mudler/edgevpn/pkg/node"
  35. "github.com/mudler/edgevpn/pkg/protocol"
  36. "github.com/mudler/edgevpn/pkg/services"
  37. "github.com/mudler/edgevpn/pkg/types"
  38. )
  39. //go:embed public
  40. var embededFiles embed.FS
  41. func getFileSystem() http.FileSystem {
  42. fsys, err := fs.Sub(embededFiles, "public")
  43. if err != nil {
  44. panic(err)
  45. }
  46. return http.FS(fsys)
  47. }
  48. const (
  49. MachineURL = "/api/machines"
  50. UsersURL = "/api/users"
  51. ServiceURL = "/api/services"
  52. BlockchainURL = "/api/blockchain"
  53. LedgerURL = "/api/ledger"
  54. SummaryURL = "/api/summary"
  55. FileURL = "/api/files"
  56. NodesURL = "/api/nodes"
  57. DNSURL = "/api/dns"
  58. MetricsURL = "/api/metrics"
  59. PeerstoreURL = "/api/peerstore"
  60. PeerGateURL = "/api/peergate"
  61. )
  62. func API(ctx context.Context, l string, defaultInterval, timeout time.Duration, e *node.Node, bwc metrics.Reporter, debugMode bool) error {
  63. ledger, _ := e.Ledger()
  64. ec := echo.New()
  65. if strings.HasPrefix(l, "unix://") {
  66. unixListener, err := net.Listen("unix", strings.ReplaceAll(l, "unix://", ""))
  67. if err != nil {
  68. return err
  69. }
  70. ec.Listener = unixListener
  71. }
  72. assetHandler := http.FileServer(getFileSystem())
  73. if debugMode {
  74. ec.GET("/debug/pprof/*", echo.WrapHandler(http.DefaultServeMux))
  75. }
  76. if bwc != nil {
  77. ec.GET(MetricsURL, func(c echo.Context) error {
  78. return c.JSON(http.StatusOK, bwc.GetBandwidthTotals())
  79. })
  80. ec.GET(filepath.Join(MetricsURL, "protocol"), func(c echo.Context) error {
  81. return c.JSON(http.StatusOK, bwc.GetBandwidthByProtocol())
  82. })
  83. ec.GET(filepath.Join(MetricsURL, "peer"), func(c echo.Context) error {
  84. return c.JSON(http.StatusOK, bwc.GetBandwidthByPeer())
  85. })
  86. ec.GET(filepath.Join(MetricsURL, "peer", ":peer"), func(c echo.Context) error {
  87. return c.JSON(http.StatusOK, bwc.GetBandwidthForPeer(peer.ID(c.Param("peer"))))
  88. })
  89. ec.GET(filepath.Join(MetricsURL, "protocol", ":protocol"), func(c echo.Context) error {
  90. return c.JSON(http.StatusOK, bwc.GetBandwidthForProtocol(p2pprotocol.ID(c.Param("protocol"))))
  91. })
  92. }
  93. // Get data from ledger
  94. ec.GET(FileURL, func(c echo.Context) error {
  95. list := []*types.File{}
  96. for _, v := range ledger.CurrentData()[protocol.FilesLedgerKey] {
  97. machine := &types.File{}
  98. v.Unmarshal(machine)
  99. list = append(list, machine)
  100. }
  101. return c.JSON(http.StatusOK, list)
  102. })
  103. if e.PeerGater() != nil {
  104. ec.PUT(fmt.Sprintf("%s/:state", PeerGateURL), func(c echo.Context) error {
  105. state := c.Param("state")
  106. switch state {
  107. case "enable":
  108. e.PeerGater().Enable()
  109. case "disable":
  110. e.PeerGater().Disable()
  111. }
  112. return c.JSON(http.StatusOK, e.PeerGater().Enabled())
  113. })
  114. ec.GET(PeerGateURL, func(c echo.Context) error {
  115. return c.JSON(http.StatusOK, e.PeerGater().Enabled())
  116. })
  117. }
  118. ec.GET(SummaryURL, func(c echo.Context) error {
  119. files := len(ledger.CurrentData()[protocol.FilesLedgerKey])
  120. machines := len(ledger.CurrentData()[protocol.MachinesLedgerKey])
  121. users := len(ledger.CurrentData()[protocol.UsersLedgerKey])
  122. services := len(ledger.CurrentData()[protocol.ServicesLedgerKey])
  123. peers, err := e.MessageHub.ListPeers()
  124. if err != nil {
  125. return err
  126. }
  127. onChainNodes := len(peers)
  128. p2pPeers := len(e.Host().Network().Peerstore().Peers())
  129. nodeID := e.Host().ID().String()
  130. blockchain := ledger.Index()
  131. return c.JSON(http.StatusOK, types.Summary{
  132. Files: files,
  133. Machines: machines,
  134. Users: users,
  135. Services: services,
  136. BlockChain: blockchain,
  137. OnChainNodes: onChainNodes,
  138. Peers: p2pPeers,
  139. NodeID: nodeID,
  140. })
  141. })
  142. ec.GET(MachineURL, func(c echo.Context) error {
  143. list := []*apiTypes.Machine{}
  144. online := services.AvailableNodes(ledger, 20*time.Minute)
  145. for _, v := range ledger.CurrentData()[protocol.MachinesLedgerKey] {
  146. machine := &types.Machine{}
  147. v.Unmarshal(machine)
  148. m := &apiTypes.Machine{Machine: *machine}
  149. if e.Host().Network().Connectedness(peer.ID(machine.PeerID)) == network.Connected {
  150. m.Connected = true
  151. }
  152. peers, err := e.MessageHub.ListPeers()
  153. if err != nil {
  154. return err
  155. }
  156. for _, p := range peers {
  157. if p.String() == machine.PeerID {
  158. m.OnChain = true
  159. }
  160. }
  161. for _, a := range online {
  162. if a == machine.PeerID {
  163. m.Online = true
  164. }
  165. }
  166. list = append(list, m)
  167. }
  168. return c.JSON(http.StatusOK, list)
  169. })
  170. ec.GET(NodesURL, func(c echo.Context) error {
  171. list := []apiTypes.Peer{}
  172. peers, err := e.MessageHub.ListPeers()
  173. if err != nil {
  174. return err
  175. }
  176. // Sum up state also from services
  177. online := services.AvailableNodes(ledger, 10*time.Minute)
  178. p := map[string]interface{}{}
  179. for _, v := range online {
  180. p[v] = nil
  181. }
  182. for _, v := range peers {
  183. _, exists := p[v.String()]
  184. if !exists {
  185. p[v.String()] = nil
  186. }
  187. }
  188. for id, _ := range p {
  189. list = append(list, apiTypes.Peer{ID: id, Online: true})
  190. }
  191. return c.JSON(http.StatusOK, list)
  192. })
  193. ec.GET(PeerstoreURL, func(c echo.Context) error {
  194. list := []apiTypes.Peer{}
  195. for _, v := range e.Host().Network().Peerstore().Peers() {
  196. list = append(list, apiTypes.Peer{ID: v.String()})
  197. }
  198. return c.JSON(http.StatusOK, list)
  199. })
  200. ec.GET(UsersURL, func(c echo.Context) error {
  201. user := []*types.User{}
  202. for _, v := range ledger.CurrentData()[protocol.UsersLedgerKey] {
  203. u := &types.User{}
  204. v.Unmarshal(u)
  205. user = append(user, u)
  206. }
  207. return c.JSON(http.StatusOK, user)
  208. })
  209. ec.GET(ServiceURL, func(c echo.Context) error {
  210. list := []*types.Service{}
  211. for _, v := range ledger.CurrentData()[protocol.ServicesLedgerKey] {
  212. srvc := &types.Service{}
  213. v.Unmarshal(srvc)
  214. list = append(list, srvc)
  215. }
  216. return c.JSON(http.StatusOK, list)
  217. })
  218. ec.GET("/*", echo.WrapHandler(http.StripPrefix("/", assetHandler)))
  219. ec.GET(BlockchainURL, func(c echo.Context) error {
  220. return c.JSON(http.StatusOK, ledger.LastBlock())
  221. })
  222. ec.GET(LedgerURL, func(c echo.Context) error {
  223. return c.JSON(http.StatusOK, ledger.CurrentData())
  224. })
  225. ec.GET(fmt.Sprintf("%s/:bucket/:key", LedgerURL), func(c echo.Context) error {
  226. bucket := c.Param("bucket")
  227. key := c.Param("key")
  228. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket][key])
  229. })
  230. ec.GET(fmt.Sprintf("%s/:bucket", LedgerURL), func(c echo.Context) error {
  231. bucket := c.Param("bucket")
  232. return c.JSON(http.StatusOK, ledger.CurrentData()[bucket])
  233. })
  234. announcing := struct{ State string }{"Announcing"}
  235. // Store arbitrary data
  236. ec.PUT(fmt.Sprintf("%s/:bucket/:key/:value", LedgerURL), func(c echo.Context) error {
  237. bucket := c.Param("bucket")
  238. key := c.Param("key")
  239. value := c.Param("value")
  240. ledger.Persist(context.Background(), defaultInterval, timeout, bucket, key, value)
  241. return c.JSON(http.StatusOK, announcing)
  242. })
  243. ec.GET(DNSURL, func(c echo.Context) error {
  244. res := []apiTypes.DNS{}
  245. for r, e := range ledger.CurrentData()[protocol.DNSKey] {
  246. var t types.DNS
  247. e.Unmarshal(&t)
  248. d := map[string]string{}
  249. for k, v := range t {
  250. d[dns.TypeToString[uint16(k)]] = v
  251. }
  252. res = append(res,
  253. apiTypes.DNS{
  254. Regex: r,
  255. Records: d,
  256. })
  257. }
  258. return c.JSON(http.StatusOK, res)
  259. })
  260. // Announce dns
  261. ec.POST(DNSURL, func(c echo.Context) error {
  262. d := new(apiTypes.DNS)
  263. if err := c.Bind(d); err != nil {
  264. return echo.NewHTTPError(http.StatusBadRequest, err.Error())
  265. }
  266. entry := make(types.DNS)
  267. for r, e := range d.Records {
  268. entry[dns.Type(dns.StringToType[r])] = e
  269. }
  270. services.PersistDNSRecord(context.Background(), ledger, defaultInterval, timeout, d.Regex, entry)
  271. return c.JSON(http.StatusOK, announcing)
  272. })
  273. // Delete data from ledger
  274. ec.DELETE(fmt.Sprintf("%s/:bucket", LedgerURL), func(c echo.Context) error {
  275. bucket := c.Param("bucket")
  276. ledger.AnnounceDeleteBucket(context.Background(), defaultInterval, timeout, bucket)
  277. return c.JSON(http.StatusOK, announcing)
  278. })
  279. ec.DELETE(fmt.Sprintf("%s/:bucket/:key", LedgerURL), func(c echo.Context) error {
  280. bucket := c.Param("bucket")
  281. key := c.Param("key")
  282. ledger.AnnounceDeleteBucketKey(context.Background(), defaultInterval, timeout, bucket, key)
  283. return c.JSON(http.StatusOK, announcing)
  284. })
  285. ec.HideBanner = true
  286. if err := ec.Start(l); err != nil && err != http.ErrServerClosed {
  287. return err
  288. }
  289. go func() {
  290. <-ctx.Done()
  291. ct, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  292. ec.Shutdown(ct)
  293. cancel()
  294. }()
  295. return nil
  296. }