github.com/kubewharf/katalyst-core@v0.5.3/pkg/controller/resource-recommend/datasource/datasource_proxy.go (about)

     1  /*
     2  Copyright 2022 The Katalyst Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package datasource
    18  
    19  import (
    20  	"errors"
    21  	"time"
    22  
    23  	datasourcetypes "github.com/kubewharf/katalyst-core/pkg/util/resource-recommend/types/datasource"
    24  )
    25  
    26  type DatasourceType string
    27  
    28  const (
    29  	PrometheusDatasource DatasourceType = "Prometheus"
    30  )
    31  
    32  type Datasource interface {
    33  	QueryTimeSeries(query *datasourcetypes.Query, start time.Time, end time.Time, step time.Duration) (*datasourcetypes.TimeSeries, error)
    34  	ConvertMetricToQuery(metric datasourcetypes.Metric) (*datasourcetypes.Query, error)
    35  }
    36  
    37  type Proxy struct {
    38  	datasourceMap map[DatasourceType]Datasource
    39  }
    40  
    41  func NewProxy() *Proxy {
    42  	return &Proxy{
    43  		datasourceMap: make(map[DatasourceType]Datasource),
    44  	}
    45  }
    46  
    47  func (p *Proxy) RegisterDatasource(name DatasourceType, datasource Datasource) {
    48  	p.datasourceMap[name] = datasource
    49  }
    50  
    51  func (p *Proxy) getDatasource(name DatasourceType) (Datasource, error) {
    52  	if datasource, ok := p.datasourceMap[name]; ok {
    53  		return datasource, nil
    54  	}
    55  	return nil, errors.New("datasource not found")
    56  }
    57  
    58  func (p *Proxy) QueryTimeSeries(DatasourceName DatasourceType, metric datasourcetypes.Metric, start time.Time, end time.Time, step time.Duration) (*datasourcetypes.TimeSeries, error) {
    59  	datasource, err := p.getDatasource(DatasourceName)
    60  	if err != nil {
    61  		return nil, err
    62  	}
    63  	query, err := datasource.ConvertMetricToQuery(metric)
    64  	if err != nil {
    65  		return nil, err
    66  	}
    67  	return datasource.QueryTimeSeries(query, start, end, step)
    68  }