Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Port 5363 UI create default resources #20

Merged
merged 38 commits into from
Dec 27, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
9c2efe3
default resources
yairsimantov20 Dec 13, 2023
b5d6718
imports
yairsimantov20 Dec 13, 2023
d2ca0fd
Merge branch 'PORT-5363-ui-for-the-kubernetes-exporter-moving-the-con…
yairsimantov20 Dec 13, 2023
9d40a7d
Merge remote-tracking branch 'origin/PORT-5363-ui-for-the-kubernetes-…
yairsimantov20 Dec 13, 2023
de5e006
Merge remote-tracking branch 'origin/PORT-5363-ui-for-the-kubernetes-…
yairsimantov20 Dec 13, 2023
0ad1ecf
Merge remote-tracking branch 'origin/PORT-5363-ui-for-the-kubernetes-…
yairsimantov20 Dec 13, 2023
205cfb3
fixed imports
yairsimantov20 Dec 13, 2023
6ff6dad
fixed defaults behavior
yairsimantov20 Dec 14, 2023
1383405
Merge remote-tracking branch 'origin/PORT-5363-ui-for-the-kubernetes-…
yairsimantov20 Dec 20, 2023
34b8a32
fixed init integration.go
yairsimantov20 Dec 20, 2023
6194ac8
removed whitespace
yairsimantov20 Dec 20, 2023
b29c7b8
Merge remote-tracking branch 'origin/PORT-5363-ui-for-the-kubernetes-…
yairsimantov20 Dec 20, 2023
926be7e
cr fixes
yairsimantov20 Dec 20, 2023
48d5295
update naming
yairsimantov20 Dec 20, 2023
f34bf6b
fixed pr conflicts
yairsimantov20 Dec 22, 2023
281c440
comment
yairsimantov20 Dec 22, 2023
8be7fc7
renaming
yairsimantov20 Dec 22, 2023
f763647
defaults tests
yairsimantov20 Dec 24, 2023
bc5ceb6
removed error printing for the .env file
yairsimantov20 Dec 24, 2023
ef56c38
removed a comment
yairsimantov20 Dec 24, 2023
c7d2801
fix tests
yairsimantov20 Dec 24, 2023
b4a5270
allow configuring if resources should be created
yairsimantov20 Dec 24, 2023
2378a36
moved configuration
yairsimantov20 Dec 25, 2023
e48d782
fixed tests
yairsimantov20 Dec 25, 2023
9f685ed
fixed tests
yairsimantov20 Dec 25, 2023
b8c8cde
pr comments
yairsimantov20 Dec 25, 2023
8a7a69e
more comments
yairsimantov20 Dec 25, 2023
a298f08
omit calculation
yairsimantov20 Dec 25, 2023
9d63dcc
aggregation properties
yairsimantov20 Dec 25, 2023
22ec10f
deleting blueprints at the start
yairsimantov20 Dec 25, 2023
0599ab3
fixed tests
yairsimantov20 Dec 25, 2023
dc887c3
switch to klog
yairsimantov20 Dec 25, 2023
0de6337
wrapped signal with mutex
yairsimantov20 Dec 25, 2023
1566804
removed service from defaults
yairsimantov20 Dec 25, 2023
5d78b84
removed service from defaults
yairsimantov20 Dec 25, 2023
161e6ec
overriding configs
yairsimantov20 Dec 26, 2023
50f60c2
statekey to lower
yairsimantov20 Dec 26, 2023
7e18cab
supporting delete dependents deprecated
yairsimantov20 Dec 27, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 2 additions & 35 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import (
"github.com/port-labs/port-k8s-exporter/pkg/config"
"github.com/port-labs/port-k8s-exporter/pkg/defaults"
"github.com/port-labs/port-k8s-exporter/pkg/event_handler"
"github.com/port-labs/port-k8s-exporter/pkg/event_handler/consumer"
"github.com/port-labs/port-k8s-exporter/pkg/event_handler/polling"
"github.com/port-labs/port-k8s-exporter/pkg/handlers"
"github.com/port-labs/port-k8s-exporter/pkg/k8s"
"github.com/port-labs/port-k8s-exporter/pkg/port"
Expand Down Expand Up @@ -35,42 +33,11 @@ func initiateHandler(exporterConfig *port.Config, k8sClient *k8s.Client, portCli
return newHandler, nil
}

func createEventListener(stateKey string, eventListenerType string, portClient *cli.PortClient) (event_handler.IListener, error) {
klog.Infof("Received event listener type: %s", eventListenerType)
switch eventListenerType {
case "KAFKA":
return consumer.NewEventListener(stateKey, portClient)
case "POLLING":
return polling.NewEventListener(stateKey, portClient), nil
default:
return nil, fmt.Errorf("unknown event listener type: %s", eventListenerType)
}
}

func getApplicationConfig() *port.Config {
appConfig, err := config.GetConfigFile(config.ApplicationConfig.ConfigFilePath)
var fileNotFoundError *config.FileNotFoundError
if errors.As(err, &fileNotFoundError) {
appConfig = &port.Config{
StateKey: config.ApplicationConfig.StateKey,
EventListenerType: config.ApplicationConfig.EventListenerType,
CreateDefaultResources: config.ApplicationConfig.CreateDefaultResources,
}
}

if config.ApplicationConfig.ResyncInterval != 0 {
appConfig.ResyncInterval = config.ApplicationConfig.ResyncInterval
}

return appConfig
}

func main() {
klog.InitFlags(nil)

k8sConfig := k8s.NewKubeConfig()

applicationConfig := getApplicationConfig()
applicationConfig := config.NewConfiguration()

clientConfig, err := k8sConfig.ClientConfig()
if err != nil {
Expand All @@ -95,7 +62,7 @@ func main() {
klog.Fatalf("Error initializing Port integration: %s", err.Error())
}

eventListener, err := createEventListener(applicationConfig.StateKey, applicationConfig.EventListenerType, portClient)
eventListener, err := event_handler.CreateEventListener(applicationConfig.StateKey, applicationConfig.EventListenerType, portClient)
if err != nil {
klog.Fatalf("Error creating event listener: %s", err.Error())
}
Expand Down
24 changes: 23 additions & 1 deletion pkg/config/config.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package config

import (
"errors"
"flag"
"github.com/joho/godotenv"
"github.com/port-labs/port-k8s-exporter/pkg/port"
)

var KafkaConfig = &KafkaConfiguration{}
Expand All @@ -12,6 +14,9 @@ var ApplicationConfig = &ApplicationConfiguration{}

func Init() {
_ = godotenv.Load()

NewString(&ApplicationConfig.EventListenerType, "event-listener-type", "POLLING", "Event listener type, can be either POLLING or KAFKA. Optional.")

// Kafka listener Configuration
NewString(&KafkaConfig.Brokers, "event-listener-brokers", "localhost:9092", "Kafka event listener brokers")
NewString(&KafkaConfig.SecurityProtocol, "event-listener-security-protocol", "plaintext", "Kafka event listener security protocol")
Expand All @@ -27,8 +32,25 @@ func Init() {
NewString(&ApplicationConfig.PortBaseURL, "port-base-url", "https://api.getport.io", "Port base URL. Optional.")
NewString(&ApplicationConfig.PortClientId, "port-client-id", "", "Port client id. Required.")
NewString(&ApplicationConfig.PortClientSecret, "port-client-secret", "", "Port client secret. Required.")
NewString(&ApplicationConfig.EventListenerType, "event-listener-type", "POLLING", "Event listener type, can be either POLLING or KAFKA. Optional.")
NewBool(&ApplicationConfig.CreateDefaultResources, "create-default-resources", true, "Create default resources on installation. Optional.")

flag.Parse()
}

func NewConfiguration() *port.Config {
c, err := GetConfigFile(ApplicationConfig.ConfigFilePath)
var fileNotFoundError *FileNotFoundError
if errors.As(err, &fileNotFoundError) {
c = &port.Config{
StateKey: ApplicationConfig.StateKey,
EventListenerType: ApplicationConfig.EventListenerType,
CreateDefaultResources: ApplicationConfig.CreateDefaultResources,
}
}

if ApplicationConfig.ResyncInterval != 0 {
c.ResyncInterval = ApplicationConfig.ResyncInterval
}

return c
}
53 changes: 32 additions & 21 deletions pkg/defaults/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,13 @@ type Defaults struct {
AppConfig *port.IntegrationAppConfig
}

var BlueprintsAsset = "assets/defaults/blueprints.json"
var ScorecardsAsset = "assets/defaults/scorecards.json"
var AppConfigAsset = "assets/defaults/appConfig.yaml"

func getDefaults() (*Defaults, error) {
var bp []port.Blueprint
file, err := os.ReadFile("assets/defaults/blueprints.json")
file, err := os.ReadFile(BlueprintsAsset)
if err != nil {
klog.Infof("No default blueprints found. Skipping...")
} else {
Expand All @@ -39,7 +43,7 @@ func getDefaults() (*Defaults, error) {
}

var sc []ScorecardDefault
file, err = os.ReadFile("./assets/defaults/scorecards.json")
file, err = os.ReadFile(ScorecardsAsset)
if err != nil {
klog.Infof("No default scorecards found. Skipping...")
} else {
Expand All @@ -50,7 +54,7 @@ func getDefaults() (*Defaults, error) {
}

var appConfig *port.IntegrationAppConfig
file, err = os.ReadFile("./assets/defaults/appConfig.yaml")
file, err = os.ReadFile(AppConfigAsset)
if err != nil {
klog.Infof("No default appConfig found. Skipping...")
} else {
Expand All @@ -67,14 +71,19 @@ func getDefaults() (*Defaults, error) {
}, nil
}

// deconstructBlueprintsToCreationSteps takes a list of blueprints and returns a list of blueprints with only the
// required fields for creation, a list of blueprints with the required fields for creation and relations, and a list
// of blueprints with all fields for creation, relations, and calculation properties.
// This is done because there might be a case where a blueprint has a relation to another blueprint that
// hasn't been created yet.
func deconstructBlueprintsToCreationSteps(rawBlueprints []port.Blueprint) ([]port.Blueprint, [][]port.Blueprint) {
yairsimantov20 marked this conversation as resolved.
Show resolved Hide resolved
var (
bareBlueprints []port.Blueprint
withRelations []port.Blueprint
fullBlueprints []port.Blueprint
)

for _, bp := range append([]port.Blueprint{}, rawBlueprints...) {
for _, bp := range rawBlueprints {
bareBlueprint := port.Blueprint{
Identifier: bp.Identifier,
Title: bp.Title,
Expand All @@ -89,7 +98,7 @@ func deconstructBlueprintsToCreationSteps(rawBlueprints []port.Blueprint) ([]por
withRelations = append(withRelations, withRelation)

fullBlueprint := withRelation
fullBlueprint.FormulaProperties = bp.FormulaProperties
fullBlueprint.CalculationProperties = bp.CalculationProperties
fullBlueprint.MirrorProperties = bp.MirrorProperties
fullBlueprints = append(fullBlueprints, fullBlueprint)
}
Expand All @@ -109,7 +118,7 @@ func (e *AbortDefaultCreationError) Error() string {
func validateBlueprintErrors(createdBlueprints []string, blueprintErrors []error) *AbortDefaultCreationError {
if len(blueprintErrors) > 0 {
for _, err := range blueprintErrors {
log.Printf("Failed to create resources: %v.", err.Error())
klog.Infof("Failed to create resources: %v.", err.Error())
}
return &AbortDefaultCreationError{BlueprintsToRollback: createdBlueprints, Errors: blueprintErrors}
}
Expand All @@ -129,18 +138,21 @@ func createResources(portClient *cli.PortClient, defaults *Defaults, config *por

var blueprintErrors []error
var createdBlueprints []string
mutex := sync.Mutex{}

for _, bp := range bareBlueprints {
waitGroup.Add(1)
go func(bp port.Blueprint) {
defer waitGroup.Done()
result, err := blueprint.NewBlueprint(portClient, bp)

mutex.Lock()
if err != nil {
blueprintErrors = append(blueprintErrors, err)
yairsimantov20 marked this conversation as resolved.
Show resolved Hide resolved
} else {
createdBlueprints = append(createdBlueprints, result.Identifier)
}
mutex.Unlock()
}(bp)
}
waitGroup.Wait()
Expand Down Expand Up @@ -171,7 +183,7 @@ func createResources(portClient *cli.PortClient, defaults *Defaults, config *por
waitGroup.Add(1)
go func(blueprintIdentifier string, scorecard port.Scorecard) {
defer waitGroup.Done()
if _, err := scorecards.NewScorecard(portClient, blueprintIdentifier, scorecard); err != nil {
if err := scorecards.CreateScorecard(portClient, blueprintIdentifier, scorecard); err != nil {
blueprintErrors = append(blueprintErrors, err)
}
}(blueprintScorecards.Blueprint, scorecard)
Expand All @@ -183,7 +195,7 @@ func createResources(portClient *cli.PortClient, defaults *Defaults, config *por
return err
}

if err := integration.NewIntegration(portClient, config.StateKey, config.EventListenerType, defaults.AppConfig); err != nil {
if err := integration.CreateIntegration(portClient, config.StateKey, config.EventListenerType, defaults.AppConfig); err != nil {
log.Printf("Failed to create resources: %v.", err.Error())
yairsimantov20 marked this conversation as resolved.
Show resolved Hide resolved
return &AbortDefaultCreationError{BlueprintsToRollback: createdBlueprints, Errors: []error{err}}
}
Expand All @@ -198,20 +210,19 @@ func initializeDefaults(portClient *cli.PortClient, config *port.Config) error {
}

if err := createResources(portClient, defaults, config); err != nil {
if err != nil {
log.Printf("Failed to create resources. Rolling back blueprints: %v", err.BlueprintsToRollback)
var rollbackWg sync.WaitGroup
for _, identifier := range err.BlueprintsToRollback {
rollbackWg.Add(1)
go func(identifier string) {
defer rollbackWg.Done()
_ = blueprint.DeleteBlueprint(portClient, identifier)
}(identifier)
}
rollbackWg.Wait()
return &ExceptionGroup{Message: err.Error(), Errors: err.Errors}
log.Printf("Failed to create resources. Rolling back blueprints: %v", err.BlueprintsToRollback)
yairsimantov20 marked this conversation as resolved.
Show resolved Hide resolved
var rollbackWg sync.WaitGroup
for _, identifier := range err.BlueprintsToRollback {
rollbackWg.Add(1)
go func(identifier string) {
defer rollbackWg.Done()
if err := blueprint.DeleteBlueprint(portClient, identifier); err != nil {
klog.Warningf("Failed to rollback blueprint %s creation: %v", identifier, err)
}
}(identifier)
}
return fmt.Errorf("unknown error during resource creation")
rollbackWg.Wait()
return &ExceptionGroup{Message: err.Error(), Errors: err.Errors}
}

return nil
Expand Down
Loading
Loading