Skip to content

Commit

Permalink
Feat: Added excludeRules for exclude resources only specified and als…
Browse files Browse the repository at this point in the history
…o apply rules to specific resources only
  • Loading branch information
MeNsaaH committed Jan 24, 2021
1 parent 28b5edb commit b290e5d
Show file tree
Hide file tree
Showing 11 changed files with 153 additions and 95 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ This tool is **HIGHLY DESTRUCTIVE** and can deletes all resources! This should b
- [x] [Persist state to remote sources](https://github.com/MeNsaaH/reka/issues/4)
- [ ] [Add More AWS Resources](https://github.com/MeNsaaH/reka/issues/1)
- [ ] [Add More GCP Resources](https://github.com/MeNsaaH/reka/issues/2)
- [ ] [Add More Azure Resources](https://github.com/MeNsaaH/reka/issues/6)
- [ ] [Add MoreAzure Resources](https://github.com/MeNsaaH/reka/issues/6)
- [ ] [Create Web Dashboard](https://github.com/MeNsaaH/reka/issues/3)

#### Supported Resources
Expand Down
64 changes: 39 additions & 25 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package cmd
import (
"fmt"
"os"
"unsafe"

"github.com/spf13/cobra"

Expand All @@ -36,12 +35,15 @@ import (
)

var (
cfgFile string
cfg *config.Config
providers []*types.Provider
backend state.Backender
activeState *state.State
verbose bool
cfgFile string
cfg *config.Config
providers []*types.Provider
backend state.Backender
activeState *state.State
verbose bool
disableStop bool
disableResume bool
disableDestroy bool
)

// rootCmd represents the base command when called without any subcommands
Expand All @@ -56,12 +58,9 @@ var rootCmd = &cobra.Command{
config.LoadConfig()

cfg = config.GetConfig()

for _, rule := range cfg.Rules {
// Convert Rule in config to rules.Rule type
r := *((*rules.Rule)(unsafe.Pointer(&rule)))
r.Tags = resource.Tags(rule.Tags)
rules.ParseRule(r)
err := rules.LoadRules()
if err != nil {
log.Fatal(err)
}

// Initialize Provider objects
Expand All @@ -72,20 +71,26 @@ var rootCmd = &cobra.Command{
for _, p := range providers {
res := activeState.Current[p.Name]

stoppableResources := p.GetStoppableResources(res)
fmt.Println("Stoppable Resources: ", stoppableResources)
errs := p.StopResources(stoppableResources)
fmt.Println("Errors Stopping Resources: ", errs)
if !disableStop {
stoppableResources := p.GetStoppableResources(res)
fmt.Println("Stoppable Resources: ", stoppableResources)
errs := p.StopResources(stoppableResources)
logErrors(errs)
}

resumableResources := p.GetResumableResources(res)
fmt.Println("Resumable Resources: ", resumableResources)
errs = p.ResumeResources(resumableResources)
fmt.Println("Errors Resuming Resources: ", errs)
if !disableResume {
resumableResources := p.GetResumableResources(res)
fmt.Println("Resumable Resources: ", resumableResources)
errs := p.ResumeResources(resumableResources)
logErrors(errs)
}

destroyableResources := p.GetDestroyableResources(res)
fmt.Println("Destroyable Resources: ", destroyableResources)
errs = p.DestroyResources(destroyableResources)
fmt.Println("Errors Destroying Resources: ", errs)
if !disableDestroy {
destroyableResources := p.GetDestroyableResources(res)
fmt.Println("Destroyable Resources: ", destroyableResources)
errs := p.DestroyResources(destroyableResources)
logErrors(errs)
}
}
},
}
Expand All @@ -104,6 +109,9 @@ func init() {
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.reka.yaml)")
rootCmd.Flags().BoolP("unused-only", "t", false, "Reap only unused resources")
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Output verbose logs (DEBUG)")
rootCmd.Flags().BoolVar(&disableStop, "disable-stop", false, "Disable stopping of resources")
rootCmd.Flags().BoolVar(&disableResume, "disable-resume", false, "Disable resuming of resources")
rootCmd.Flags().BoolVar(&disableDestroy, "disable-destroy", false, "Disable destruction of resources")
}

// initConfig reads in config file and ENV variables if set.
Expand Down Expand Up @@ -201,3 +209,9 @@ func containsResource(res []*resource.Resource, r *resource.Resource) bool {
}
return false
}

func logErrors(errs map[string]error) {
for k, v := range errs {
log.Errorf("%s: %s", k, v.Error())
}
}
10 changes: 0 additions & 10 deletions cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,4 @@ var versionCmd = &cobra.Command{

func init() {
rootCmd.AddCommand(versionCmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// versionCmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// versionCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
67 changes: 38 additions & 29 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,41 @@ const (
appName = "REKA"
)

type ExcludeRule struct {
Name string
Region string
Tags map[string]string
Resources []string
}

type Rule struct {
Name string
Condition struct {
ActiveDuration struct {
StartTime string
StopTime string
StartDay string
StopDay string
}
TerminationPolicy string
TerminationDate string
}
Resources []string
Region string
Tags map[string]string
}

func (r Rule) String() string {
return r.Name
}

type Backend struct {
Type string
Path string
Bucket string
Region string
}

// Config : The Config values passed to application
type Config struct {
Name string
Expand All @@ -43,41 +78,15 @@ type Config struct {
staticPath string // Path to Static File

// Exclude block prevents certain resources from been tracked or affected by reka.
Exclude []struct {
Name string
Region string
Tags map[string]string
Resources []string
}
Exclude []*ExcludeRule

// StateBackend is how state is stored (read & write)
// State files contain details used for infrastructure resumption and history of
// infrastructural management
StateBackend struct {
Type string
Path string
Bucket string
Region string
}

StateBackend *Backend
// Rules block define how reka should behave given certain resources. These rules
// usually target resources based on tags/labels which are attached to the resources
Rules []struct {
Name string
Condition struct {
ActiveDuration struct {
StartTime string
StopTime string
StartDay string
StopDay string
}
TerminationPolicy string
TerminationDate string
}
Region string
Tags map[string]string
}

Rules []*Rule
// AWS Config
Aws *aws.Config
// Gcp configuration
Expand Down
1 change: 1 addition & 0 deletions config/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,6 @@ func GetLogger(mgrName, logPath string) *log.Entry {
}
return logger.WithFields(log.Fields{
"resource": mgrName,
"provider": mgrName,
})
}
1 change: 1 addition & 0 deletions provider/aws/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ func NewResource(id, manager string) *resource.Resource {
resource := resource.Resource{}
resource.UUID = id
resource.Manager = resourceManagers[manager]
resource.ProviderName = providerName

return &resource
}
Expand Down
1 change: 1 addition & 0 deletions provider/gcp/gcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ func NewResource(id, manager string) *resource.Resource {
resource := resource.Resource{}
resource.UUID = id
resource.Manager = resourceManagers[manager]
resource.ProviderName = providerName

return &resource
}
Expand Down
2 changes: 1 addition & 1 deletion provider/types/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ func (p *Provider) GetUnusedResources(resources Resources) Resources {
// DestroyResources : Return the resources which can be destroyed
func (p *Provider) DestroyResources(resources Resources) map[string]error {
errs := make(map[string]error)
p.Logger.Debugf("Destroying Resources...")
p.Logger.Info("Destroying Resources...")
var wg sync.WaitGroup

for mgrName, res := range resources {
Expand Down
14 changes: 11 additions & 3 deletions resource/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package resource

import (
"fmt"
"strings"
"time"

log "github.com/sirupsen/logrus"
Expand Down Expand Up @@ -45,9 +46,9 @@ type Resource struct {
gorm.Model `json:"-"`
// UUID defines any unique field use to identify a resource. For some resources its their IDs, some their names.
// Not using ID because gorm.Model defines an ID field already
UUID string `gorm:"unique;not null"`
ManagerName string `json:"-"`
Manager *Manager `gorm:"foreignKey:ManagerName;references:Name" json:"-"`
UUID string `gorm:"unique;not null"`
Manager *Manager `gorm:"foreignKey:ManagerName;references:Name" json:"-"`
ProviderName string

Region string // Region of Resource

Expand Down Expand Up @@ -85,3 +86,10 @@ func (r Resource) IsStopped() bool {
func (r Resource) IsUnused() bool {
return r.Status == Unused
}

// Uri a simple uri of the resource in the form provider.resource_type for example ec2 instances will have the
// url aws.ec2
func (r Resource) Uri() string {
return fmt.Sprintf("%s.%s", strings.ToLower(r.ProviderName), strings.ToLower(r.Manager.Name))

}
Loading

0 comments on commit b290e5d

Please sign in to comment.