hostactions.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package hostactions
  2. import (
  3. "encoding/json"
  4. "github.com/gravitl/netmaker/database"
  5. "github.com/gravitl/netmaker/models"
  6. )
  7. // AddAction - adds a host action to a host's list to be retrieved from broker update
  8. func AddAction(hu models.HostUpdate) {
  9. hostID := hu.Host.ID.String()
  10. currentRecords, err := database.FetchRecord(database.HOST_ACTIONS_TABLE_NAME, hostID)
  11. if err != nil {
  12. if database.IsEmptyRecord(err) { // no list exists yet
  13. newEntry, err := json.Marshal([]models.HostUpdate{hu})
  14. if err != nil {
  15. return
  16. }
  17. _ = database.Insert(hostID, string(newEntry), database.HOST_ACTIONS_TABLE_NAME)
  18. }
  19. return
  20. }
  21. var currentList []models.HostUpdate
  22. if err := json.Unmarshal([]byte(currentRecords), &currentList); err != nil {
  23. return
  24. }
  25. currentList = append(currentList, hu)
  26. newData, err := json.Marshal(currentList)
  27. if err != nil {
  28. return
  29. }
  30. _ = database.Insert(hostID, string(newData), database.HOST_ACTIONS_TABLE_NAME)
  31. }
  32. // GetAction - gets an action if exists
  33. func GetAction(id string) *models.HostUpdate {
  34. currentRecords, err := database.FetchRecord(database.HOST_ACTIONS_TABLE_NAME, id)
  35. if err != nil {
  36. return nil
  37. }
  38. var currentList []models.HostUpdate
  39. if err = json.Unmarshal([]byte(currentRecords), &currentList); err != nil {
  40. return nil
  41. }
  42. if len(currentList) > 0 {
  43. hu := currentList[0]
  44. newData, err := json.Marshal(currentList[1:])
  45. if err != nil {
  46. newData, _ = json.Marshal([]models.HostUpdate{})
  47. }
  48. _ = database.Insert(id, string(newData), database.HOST_ACTIONS_TABLE_NAME)
  49. return &hu
  50. }
  51. return nil
  52. }