github.com/inspektor-gadget/inspektor-gadget@v0.28.1/pkg/gadget-service/api/helpers.go (about)

     1  // Copyright 2023-2024 The Inspektor Gadget authors
     2  //
     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  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package api
    16  
    17  import (
    18  	"fmt"
    19  	"net/url"
    20  	"strings"
    21  )
    22  
    23  type (
    24  	Params      []*Param
    25  	ParamValues map[string]string
    26  )
    27  
    28  func ParseSocketAddress(addr string) (string, string, error) {
    29  	socketURL, err := url.Parse(addr)
    30  	if err != nil {
    31  		return "", "", fmt.Errorf("invalid socket address %q: %w", addr, err)
    32  	}
    33  	var socketPath string
    34  	socketType := socketURL.Scheme
    35  	switch socketType {
    36  	default:
    37  		return "", "", fmt.Errorf("invalid type %q for socket; please use 'unix' or 'tcp'", socketType)
    38  	case "unix":
    39  		socketPath = socketURL.Path
    40  	case "tcp":
    41  		if socketURL.Host == "" {
    42  			return "", "", fmt.Errorf("invalid tcp socket address '%s'. Use something like 'tcp://127.0.0.1:1234'", addr)
    43  		}
    44  		socketPath = socketURL.Host
    45  	}
    46  	return socketType, socketPath, nil
    47  }
    48  
    49  func (p *Param) AddPrefix(prefix string) *Param {
    50  	p.Prefix = prefix + "." + p.Prefix
    51  	return p
    52  }
    53  
    54  func (pv Params) AddPrefix(prefix string) Params {
    55  	for _, p := range pv {
    56  		p.AddPrefix(prefix)
    57  	}
    58  	return pv
    59  }
    60  
    61  func (pv ParamValues) ExtractPrefixedValues(prefix string) ParamValues {
    62  	prefix = prefix + "."
    63  	res := make(ParamValues)
    64  	for k, v := range pv {
    65  		if strings.HasPrefix(k, prefix) {
    66  			res[strings.TrimPrefix(k, prefix)] = v
    67  		}
    68  	}
    69  	return res
    70  }