fabric/core/vendors.go

108 lines
2.3 KiB
Go
Raw Normal View History

2024-08-16 19:43:27 +00:00
package core
import (
"context"
2024-08-16 19:43:27 +00:00
"fmt"
"sync"
2024-09-03 16:19:33 +00:00
"github.com/danielmiessler/fabric/vendors"
2024-08-16 19:43:27 +00:00
)
func NewVendorsManager() *VendorsManager {
return &VendorsManager{
Vendors: map[string]vendors.Vendor{},
2024-08-16 19:43:27 +00:00
}
}
type VendorsManager struct {
Vendors map[string]vendors.Vendor
Models *VendorsModels
2024-08-16 19:43:27 +00:00
}
func (o *VendorsManager) AddVendors(vendors ...vendors.Vendor) {
2024-08-16 19:43:27 +00:00
for _, vendor := range vendors {
o.Vendors[vendor.GetName()] = vendor
2024-08-16 19:43:27 +00:00
}
}
func (o *VendorsManager) GetModels() *VendorsModels {
2024-08-16 19:43:27 +00:00
if o.Models == nil {
o.readModels()
}
return o.Models
2024-08-16 19:43:27 +00:00
}
func (o *VendorsManager) HasVendors() bool {
return len(o.Vendors) > 0
2024-08-16 19:43:27 +00:00
}
func (o *VendorsManager) FindByName(name string) vendors.Vendor {
return o.Vendors[name]
}
func (o *VendorsManager) readModels() {
2024-08-16 19:43:27 +00:00
o.Models = NewVendorsModels()
var wg sync.WaitGroup
resultsChan := make(chan modelResult, len(o.Vendors))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
2024-08-16 19:43:27 +00:00
for _, vendor := range o.Vendors {
wg.Add(1)
go o.fetchVendorModels(ctx, &wg, vendor, resultsChan)
2024-08-16 19:43:27 +00:00
}
// Wait for all goroutines to finish
go func() {
wg.Wait()
close(resultsChan)
}()
2024-08-16 19:43:27 +00:00
// Collect results
for result := range resultsChan {
if result.err != nil {
fmt.Println(result.vendorName, result.err)
o.Models.AddError(result.err)
cancel() // Cancel remaining goroutines if needed
} else {
o.Models.AddVendorModels(result.vendorName, result.models)
2024-08-16 19:43:27 +00:00
}
}
}
func (o *VendorsManager) fetchVendorModels(
ctx context.Context, wg *sync.WaitGroup, vendor vendors.Vendor, resultsChan chan<- modelResult) {
2024-08-16 19:43:27 +00:00
defer wg.Done()
2024-08-16 19:43:27 +00:00
models, err := vendor.ListModels()
select {
case <-ctx.Done():
// Context canceled, don't send the result
return
case resultsChan <- modelResult{vendorName: vendor.GetName(), models: models, err: err}:
// Result sent
}
}
2024-08-22 19:45:36 +00:00
func (o *VendorsManager) Setup() (ret map[string]vendors.Vendor, err error) {
ret = map[string]vendors.Vendor{}
for _, vendor := range o.Vendors {
fmt.Println()
if vendorErr := vendor.Setup(); vendorErr == nil {
fmt.Printf("[%v] configured\n", vendor.GetName())
ret[vendor.GetName()] = vendor
} else {
fmt.Printf("[%v] skipped\n", vendor.GetName())
}
}
return
}
type modelResult struct {
vendorName string
models []string
err error
2024-08-16 19:43:27 +00:00
}