github.com/splunk/qbec@v0.15.2/vm/internal/ds/factory/datasource.go (about)

     1  /*
     2     Copyright 2021 Splunk Inc.
     3     Licensed under the Apache License, Version 2.0 (the "License");
     4     you may not use this file except in compliance with the License.
     5     You may obtain a copy of the License at
     6         http://www.apache.org/licenses/LICENSE-2.0
     7     Unless required by applicable law or agreed to in writing, software
     8     distributed under the License is distributed on an "AS IS" BASIS,
     9     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    10     See the License for the specific language governing permissions and
    11     limitations under the License.
    12  */
    13  
    14  // Package factory provides a mechanism to create data sources from URLs with custom schemes.
    15  package factory
    16  
    17  import (
    18  	"fmt"
    19  	"net/url"
    20  
    21  	"github.com/pkg/errors"
    22  	"github.com/splunk/qbec/vm/internal/ds"
    23  	"github.com/splunk/qbec/vm/internal/ds/exec"
    24  )
    25  
    26  // Create creates a new data source from the supplied URL.
    27  // Such a URL has a scheme that is the type of supported data source,
    28  // a hostname that is the name that it should be referred to in user code,
    29  // and a query param called configVar which supplies the data source config.
    30  func Create(u string) (ds.DataSourceWithLifecycle, error) {
    31  	parsed, err := url.Parse(u)
    32  	if err != nil {
    33  		return nil, errors.Wrapf(err, "parse URL '%s'", u)
    34  	}
    35  	scheme := parsed.Scheme
    36  	switch scheme {
    37  	case exec.Scheme:
    38  	default:
    39  		return nil, fmt.Errorf("data source URL '%s', unsupported scheme '%s'", u, scheme)
    40  	}
    41  	name := parsed.Host
    42  	if name == "" {
    43  		if parsed.Opaque != "" {
    44  			return nil, fmt.Errorf("data source '%s' does not have a name (did you forget the '//' after the ':'?)", u)
    45  		}
    46  		return nil, fmt.Errorf("data source '%s' does not have a name", u)
    47  	}
    48  	varName := parsed.Query().Get("configVar")
    49  	if varName == "" {
    50  		return nil, fmt.Errorf("data source '%s' must have a configVar param", u)
    51  	}
    52  	switch scheme {
    53  	case exec.Scheme:
    54  		return makeLazy(exec.New(name, varName)), nil
    55  	default:
    56  		return nil, fmt.Errorf("internal error: unable to create a data source for %s", u)
    57  	}
    58  }