Skip to content

Commit

Permalink
#35: added code to handle the --expires-on flag for dce leases create
Browse files Browse the repository at this point in the history
  • Loading branch information
nathanagood committed Dec 12, 2019
1 parent abfa706 commit ecfb961
Show file tree
Hide file tree
Showing 13 changed files with 275 additions and 25 deletions.
2 changes: 1 addition & 1 deletion client/operations/post_leases_responses.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion cmd/leases.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ var principalID string
var budgetAmount float64
var budgetCurrency string
var email []string
var expiresOn string

var pagLimit int64
var nextAcctID string
Expand All @@ -37,6 +38,7 @@ func init() {
leasesCreateCmd.Flags().StringVarP(&principalID, "principal-id", "p", "", "Principle ID for the user of the leased account")
leasesCreateCmd.Flags().Float64VarP(&budgetAmount, "budget-amount", "b", 0, "The leased accounts budget amount")
leasesCreateCmd.Flags().StringVarP(&budgetCurrency, "budget-currency", "c", "USD", "The leased accounts budget currency")
leasesCreateCmd.Flags().StringVarP(&expiresOn, "expires-on", "E", "7d", "The leased accounts expiry date as a long (UNIX epoch) or string (eg., '7d', '8h'")
leasesCreateCmd.Flags().StringArrayVarP(&email, "email", "e", nil, "The email address that budget notifications will be sent to")
leasesCreateCmd.MarkFlagRequired("principal-id")
leasesCreateCmd.MarkFlagRequired("budget-amount")
Expand Down Expand Up @@ -86,7 +88,7 @@ var leasesCreateCmd = &cobra.Command{
Short: "Create a lease.",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
Service.CreateLease(principalID, budgetAmount, budgetCurrency, email)
Service.CreateLease(principalID, budgetAmount, budgetCurrency, email, expiresOn)
},
}

Expand Down
78 changes: 78 additions & 0 deletions internal/util/duration.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package util

import (
"fmt"
"regexp"
"strconv"
"time"
)

// DurationUtil has the
type DurationUtil struct {
DayFormatExp *regexp.Regexp
TimeUnitFormatExp *regexp.Regexp
}

const (
EmptyDuration time.Duration = time.Duration(0)
)

// ExpandEpochTime "expands" the given time from a string. If it is an int64, it assumes the time
// is a UNIX epoch time and is "absolute" and so refers the time. If it is a string, it assumes
// the time is "relative" to now and returns the UNIX epoch time with the duration added.
func (d *DurationUtil) ExpandEpochTime(str string) (int64, error) {
// if the incoming time can be used as a number, assume it's an "absolute" time
epoch, err := strconv.ParseInt(str, 10, 64)
if err == nil {
return epoch, nil
}

// if it's a string, assume that it's "relative" to now, so return that...
duration, err := d.ParseDuration(str)

if err != nil {
return 0, err
}

return time.Now().Add(duration).Unix(), nil

}

// ParseDuration accepts a string to parse and return a `time.Duration`.
// This is used because the default time.Duration in go only supports up
// to the hour, and for lease expirations we want to support days,
func (d *DurationUtil) ParseDuration(str string) (time.Duration, error) {

if d.TimeUnitFormatExp.Match([]byte(str)) {
// use the default time.Duration behavior
dur, err := time.ParseDuration(str)
return dur, err
}

// calc for days..
if d.DayFormatExp.Match([]byte(str)) {
matches := d.DayFormatExp.FindStringSubmatch(str)
day, err := strconv.Atoi(matches[1])
if err != nil {
return EmptyDuration, err
}
if day <= 0 {
// Well, that's just silly...
return EmptyDuration, fmt.Errorf("invalid zero or negative date: %d", day)
}
dur := time.Duration(day*24) * time.Hour
return dur, nil
}

return EmptyDuration, fmt.Errorf("invalid duration format: %s", str)
}

// NewDurationUtil creates a new `DuractionUtil`
func NewDurationUtil() *DurationUtil {
durationUtil := &DurationUtil{
DayFormatExp: regexp.MustCompile(`([\d]+)(\s*)(?:d)`),
TimeUnitFormatExp: regexp.MustCompile(`[\d]+(ns|us|ms|s|m|h)`),
}

return durationUtil
}
14 changes: 11 additions & 3 deletions internal/util/util.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package util

import (
"github.com/aws/aws-sdk-go/aws/session"
"os"
"time"

"github.com/aws/aws-sdk-go/aws/session"

"github.com/Optum/dce-cli/configs"
observ "github.com/Optum/dce-cli/internal/observation"
Expand All @@ -14,14 +16,15 @@ type UtilContainer struct {
// Useful if we want to reload or modify the file later
ConfigFile string
Observation *observ.ObservationContainer
AWSSession *session.Session
AWSSession *session.Session
AWSer
APIer
Terraformer
Githuber
Prompter
FileSystemer
Weber
Durationer
}

var log observ.Logger
Expand All @@ -48,7 +51,6 @@ func New(config *configs.Root, configFile string, observation *observ.Observatio
})
}


utilContainer := UtilContainer{
Config: config,
Observation: observation,
Expand All @@ -60,6 +62,7 @@ func New(config *configs.Root, configFile string, observation *observ.Observatio
Prompter: &PromptUtil{Config: config, Observation: observation},
FileSystemer: &FileSystemUtil{Config: config, ConfigFile: configFile},
Weber: &WebUtil{Observation: observation},
Durationer: NewDurationUtil(),
}

return &utilContainer
Expand Down Expand Up @@ -104,3 +107,8 @@ type FileSystemer interface {
type Weber interface {
OpenURL(url string)
}

type Durationer interface {
ExpandEpochTime(str string) (int64, error)
ParseDuration(str string) (time.Duration, error)
}
9 changes: 6 additions & 3 deletions mocks/APIer.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 11 additions & 2 deletions mocks/Authenticater.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions mocks/Deployer.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

56 changes: 56 additions & 0 deletions mocks/Durationer.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions mocks/FileSystemer.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions mocks/Leaser.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 16 additions & 7 deletions pkg/service/leases.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,23 @@ type LeasesService struct {
Util *utl.UtilContainer
}

func (s *LeasesService) CreateLease(principalID string, budgetAmount float64, budgetCurrency string, email []string) {
func (s *LeasesService) CreateLease(principalID string, budgetAmount float64, budgetCurrency string, email []string, expiresOn string) {
postBody := operations.PostLeasesBody{
PrincipalID: &principalID,
BudgetAmount: &budgetAmount,
BudgetCurrency: &budgetCurrency,
BudgetNotificationEmails: email,
}

expiry, err := s.Util.ExpandEpochTime(expiresOn)

if err != nil && expiry > 0 {
expiryf := float64(expiry)
postBody.ExpiresOn = &expiryf
}

params := &operations.PostLeasesParams{
Lease: operations.PostLeasesBody{
PrincipalID: &principalID,
BudgetAmount: &budgetAmount,
BudgetCurrency: &budgetCurrency,
BudgetNotificationEmails: email,
},
Lease: postBody,
}
params.SetTimeout(5 * time.Second)
res, err := apiClient.PostLeases(params, nil)
Expand Down
2 changes: 1 addition & 1 deletion pkg/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ type Accounter interface {
}

type Leaser interface {
CreateLease(principalID string, budgetAmount float64, budgetCurrency string, email []string)
CreateLease(principalID string, budgetAmount float64, budgetCurrency string, email []string, expiresOn string)
EndLease(accountID, principalID string)
LoginToLease(leaseID, profile string, loginOpenBrowser, loginPrintCreds bool)
ListLeases(acctID, principalID, nextAcctID, nextPrincipalID, leaseStatus string, pagLimit int64)
Expand Down
Loading

0 comments on commit ecfb961

Please sign in to comment.