github.com/replicatedhq/ship@v0.55.0/pkg/lifecycle/daemon/daemontypes/progress.go (about)

     1  package daemontypes
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"sync"
     7  )
     8  
     9  type Progress struct {
    10  	Source string `json:"source"`
    11  	Type   string `json:"type"`  // string, json, etc
    12  	Level  string `json:"level"` // string, json, etc
    13  	Detail string `json:"detail,omitempty"`
    14  }
    15  
    16  func (p Progress) String() string {
    17  	asJSON, err := json.Marshal(p)
    18  	if err == nil {
    19  		return string(asJSON)
    20  	}
    21  	return fmt.Sprintf("Progress{%s %s %s %s}", p.Source, p.Type, p.Level, p.Detail)
    22  }
    23  
    24  // Status parses the status code within progress detail that is used by the FE to determine
    25  // progress phases within a step
    26  func (p Progress) Status() string {
    27  	if p.Detail != "" {
    28  		var statusDetail map[string]string
    29  		_ = json.Unmarshal([]byte(p.Detail), &statusDetail)
    30  		return statusDetail["status"]
    31  	}
    32  	return ""
    33  }
    34  
    35  func StringProgress(source, detail string) Progress {
    36  	return JSONProgress(source, map[string]interface{}{
    37  		"status": detail,
    38  	})
    39  }
    40  
    41  func JSONProgress(source string, detail interface{}) Progress {
    42  	d, _ := json.Marshal(detail)
    43  	return Progress{
    44  		Source: source,
    45  		Type:   "json",
    46  		Level:  "info",
    47  		Detail: string(d),
    48  	}
    49  }
    50  
    51  func MessageProgress(source string, msg Message) Progress {
    52  	d, _ := json.Marshal(msg)
    53  	return Progress{
    54  		Source: source,
    55  		Type:   "string",
    56  		Level:  "info",
    57  		Detail: string(d),
    58  	}
    59  }
    60  
    61  // the empty value is initialized and ready to use
    62  type ProgressMap struct {
    63  	Map sync.Map
    64  }
    65  
    66  func (p *ProgressMap) Load(stepID string) (Progress, bool) {
    67  	empty := Progress{}
    68  	value, ok := p.Map.Load(stepID)
    69  	if !ok {
    70  		return empty, false
    71  	}
    72  
    73  	progress, ok := value.(Progress)
    74  	if !ok {
    75  		return empty, false
    76  	}
    77  
    78  	return progress, true
    79  }
    80  
    81  func (p *ProgressMap) Store(stepID string, progress Progress) {
    82  	p.Map.Store(stepID, progress)
    83  }
    84  
    85  func (p *ProgressMap) Delete(stepID string) {
    86  	p.Map.Delete(stepID)
    87  }