github.com/jdolitsky/cnab-go@v0.7.1-beta1/claim/claim.go (about) 1 package claim 2 3 import ( 4 "fmt" 5 "math/rand" 6 "regexp" 7 "time" 8 9 "github.com/oklog/ulid" 10 11 "github.com/deislabs/cnab-go/bundle" 12 ) 13 14 // Status constants define the CNAB status fields on a Result. 15 const ( 16 StatusSuccess = "success" 17 StatusFailure = "failure" 18 StatusUnderway = "underway" 19 StatusUnknown = "unknown" 20 ) 21 22 // Action constants define the CNAB action to be taken 23 const ( 24 ActionInstall = "install" 25 ActionUpgrade = "upgrade" 26 ActionDowngrade = "downgrade" 27 ActionUninstall = "uninstall" 28 ActionStatus = "status" 29 ActionUnknown = "unknown" 30 ) 31 32 // Claim is an installation claim receipt. 33 // 34 // Claims reprsent information about a particular installation, and 35 // provide the necessary data to upgrade, uninstall, and downgrade 36 // a CNAB package. 37 type Claim struct { 38 Name string `json:"name"` 39 Revision string `json:"revision"` 40 Created time.Time `json:"created"` 41 Modified time.Time `json:"modified"` 42 Bundle *bundle.Bundle `json:"bundle"` 43 Result Result `json:"result,omitempty"` 44 Parameters map[string]interface{} `json:"parameters,omitempty"` 45 // Outputs is a map from the names of outputs (defined in the bundle) to the contents of the files. 46 Outputs map[string]interface{} `json:"outputs,omitempty"` 47 Custom interface{} `json:"custom,omitempty"` 48 } 49 50 // ValidName is a regular expression that indicates whether a name is a valid claim name. 51 var ValidName = regexp.MustCompile("^[a-zA-Z0-9._-]+$") 52 53 // New creates a new Claim initialized for an installation operation. 54 func New(name string) (*Claim, error) { 55 56 if !ValidName.MatchString(name) { 57 return nil, fmt.Errorf("invalid name %q. Names must be [a-zA-Z0-9-_]+", name) 58 } 59 60 now := time.Now() 61 return &Claim{ 62 Name: name, 63 Revision: ULID(), 64 Created: now, 65 Modified: now, 66 Result: Result{ 67 Action: ActionUnknown, 68 Status: StatusUnknown, 69 }, 70 Parameters: map[string]interface{}{}, 71 Outputs: map[string]interface{}{}, 72 }, nil 73 } 74 75 // Update is a convenience for modifying the necessary fields on a Claim. 76 // 77 // Per spec, when a claim is updated, the action, status, revision, and modified fields all change. 78 // All but status and action can be computed. 79 func (c *Claim) Update(action, status string) { 80 c.Result.Action = action 81 c.Result.Status = status 82 c.Modified = time.Now() 83 c.Revision = ULID() 84 } 85 86 // Result tracks the result of a Duffle operation on a CNAB installation 87 type Result struct { 88 Message string `json:"message"` 89 Action string `json:"action"` 90 Status string `json:"status"` 91 } 92 93 // ULID generates a string representation of a ULID. 94 func ULID() string { 95 now := time.Now() 96 entropy := rand.New(rand.NewSource(now.UnixNano())) 97 return ulid.MustNew(ulid.Timestamp(now), entropy).String() 98 }