github.com/kuoss/venti@v0.2.20/pkg/service/dashboard/dashboard.go (about)

     1  package dashboard
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/kuoss/common/logger"
     9  	"github.com/kuoss/venti/pkg/model"
    10  	"gopkg.in/yaml.v2"
    11  )
    12  
    13  type DashboardService struct {
    14  	dashboards []model.Dashboard
    15  }
    16  
    17  func getDashboardFilesFromPath(dirpath string) ([]string, error) {
    18  	if dirpath == "" {
    19  		dirpath = "etc/dashboards"
    20  	}
    21  	files, err := filepath.Glob(dirpath + "/*.y*ml")
    22  	if err != nil {
    23  		return nil, fmt.Errorf("glob err: %w", err)
    24  	}
    25  	files2, err := filepath.Glob(dirpath + "/*/*.y*ml")
    26  	if err != nil {
    27  		return nil, fmt.Errorf("glob err: %w", err)
    28  	}
    29  	files = append(files, files2...)
    30  	if len(files) < 1 {
    31  		return nil, fmt.Errorf("no dashboard file: dirpath: %s", dirpath)
    32  	}
    33  	return files, nil
    34  }
    35  
    36  func New(dirpath string) (*DashboardService, error) {
    37  	logger.Debugf("NewDashboardService...")
    38  	files, err := getDashboardFilesFromPath(dirpath)
    39  	if err != nil {
    40  		return nil, fmt.Errorf("getDashboardFilesFromPath err: %w", err)
    41  	}
    42  
    43  	var dashboards []model.Dashboard
    44  	for _, filename := range files {
    45  		dashboard, err := loadDashboardFromFile(filename)
    46  		if err != nil {
    47  			logger.Warnf("Warning: error on loadDashboardFromFile(skipped): %s", err)
    48  			continue
    49  		}
    50  		dashboards = append(dashboards, *dashboard)
    51  	}
    52  	return &DashboardService{dashboards: dashboards}, nil
    53  }
    54  
    55  func loadDashboardFromFile(filename string) (*model.Dashboard, error) {
    56  	logger.Infof("load dashboard file: %s", filename)
    57  	yamlBytes, err := os.ReadFile(filename)
    58  	if err != nil {
    59  		return nil, fmt.Errorf("error on ReadFile: %w", err)
    60  	}
    61  	var dashboard *model.Dashboard
    62  	if err := yaml.UnmarshalStrict(yamlBytes, &dashboard); err != nil {
    63  		return nil, fmt.Errorf("error on UnmarshalStrict: %w", err)
    64  	}
    65  	return dashboard, nil
    66  }
    67  
    68  func (s *DashboardService) Dashboards() []model.Dashboard {
    69  	return s.dashboards
    70  }