node.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package mhayaProfile
  2. import (
  3. "fmt"
  4. cerr "github.com/mhaya/error"
  5. cfacade "github.com/mhaya/facade"
  6. )
  7. // Node node info
  8. type Node struct {
  9. nodeId string
  10. nodeType string
  11. address string
  12. rpcAddress string
  13. settings cfacade.ProfileJSON
  14. enabled bool
  15. }
  16. func (n *Node) NodeId() string {
  17. return n.nodeId
  18. }
  19. func (n *Node) NodeType() string {
  20. return n.nodeType
  21. }
  22. func (n *Node) Address() string {
  23. return n.address
  24. }
  25. func (n *Node) RpcAddress() string {
  26. return n.rpcAddress
  27. }
  28. func (n *Node) Settings() cfacade.ProfileJSON {
  29. return n.settings
  30. }
  31. func (n *Node) Enabled() bool {
  32. return n.enabled
  33. }
  34. const stringFormat = "nodeId = %s, nodeType = %s, address = %s, rpcAddress = %s, enabled = %v"
  35. func (n *Node) String() string {
  36. return fmt.Sprintf(stringFormat,
  37. n.nodeId,
  38. n.nodeType,
  39. n.address,
  40. n.rpcAddress,
  41. n.enabled,
  42. )
  43. }
  44. func GetNodeWithConfig(config *Config, nodeId string) (cfacade.INode, error) {
  45. nodeConfig := config.GetConfig("node")
  46. if nodeConfig.LastError() != nil {
  47. return nil, cerr.Error("`nodes` property not found in profile file.")
  48. }
  49. for _, nodeType := range nodeConfig.Keys() {
  50. typeJson := nodeConfig.GetConfig(nodeType)
  51. for i := 0; i < typeJson.Size(); i++ {
  52. item := typeJson.GetConfig(i)
  53. if !findNodeId(nodeId, item.GetConfig("node_id")) {
  54. continue
  55. }
  56. node := &Node{
  57. nodeId: nodeId,
  58. nodeType: nodeType,
  59. address: item.GetString("address"),
  60. rpcAddress: item.GetString("rpc_address"),
  61. settings: item.GetConfig("__settings__"),
  62. enabled: item.GetBool("enabled"),
  63. }
  64. return node, nil
  65. }
  66. }
  67. return nil, cerr.Errorf("nodeId = %s not found.", nodeId)
  68. }
  69. func LoadNode(nodeId string) (cfacade.INode, error) {
  70. return GetNodeWithConfig(cfg.jsonConfig, nodeId)
  71. }
  72. func findNodeId(nodeId string, nodeIdJson cfacade.ProfileJSON) bool {
  73. if nodeIdJson.ToString() == nodeId {
  74. return true
  75. }
  76. for i := 0; i < nodeIdJson.Size(); i++ {
  77. if nodeIdJson.GetString(i) == nodeId {
  78. return true
  79. }
  80. }
  81. return false
  82. }