...

Source file src/github.com/datawire/ambassador/v2/pkg/metriton/install_id.go

Documentation: github.com/datawire/ambassador/v2/pkg/metriton

     1  package metriton
     2  
     3  import (
     4  	"errors"
     5  	"io/ioutil"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/google/uuid"
    10  )
    11  
    12  // StaticInstallID is returns an install-ID-getter that always returns
    13  // a fixed install ID.
    14  func StaticInstallID(id string) func(*Reporter) (string, error) {
    15  	return func(*Reporter) (string, error) {
    16  		return id, nil
    17  	}
    18  }
    19  
    20  // This is the same as os.UserConfigDir() on GOOS=linux.  We Use this
    21  // instead of os.UserConfigDir() because on we want the GOOS=linux
    22  // behavior on macOS, because:
    23  //
    24  //   - For consistency with Telepresence; as that's what scout.py does,
    25  //     and Telepresence uses scout.py
    26  //   - This is what existing versions of edgectl do (for consistency
    27  //     with Telepresence)
    28  //   - It's what many macOS users expect any way; they expect XDG file
    29  //     paths to work, because other cross-platform unix-y applications
    30  //     (like gcloud & pgcli) use them.
    31  //
    32  // That said, neither Telepresence nor existing versions of edgectl
    33  // obey XDG_CONFIG_HOME.
    34  func userConfigDir() (string, error) {
    35  	var dir string
    36  	dir = os.Getenv("XDG_CONFIG_HOME")
    37  	if dir == "" {
    38  		dir = os.Getenv("HOME")
    39  		if dir == "" {
    40  			return "", errors.New("neither $XDG_CONFIG_HOME nor $HOME are defined")
    41  		}
    42  		dir += "/.config"
    43  	}
    44  	return dir, nil
    45  }
    46  
    47  // InstallIDFromFilesystem is an install-ID-getter that tracks the
    48  // install ID in the filesystem (à la `telepresence` or `edgectl`).
    49  func InstallIDFromFilesystem(reporter *Reporter) (string, error) {
    50  	dir, err := userConfigDir()
    51  	if err != nil {
    52  		return "", err
    53  	}
    54  
    55  	idFilename := filepath.Join(dir, reporter.Application, "id")
    56  	if idBytes, err := ioutil.ReadFile(idFilename); err == nil {
    57  		reporter.BaseMetadata["new_install"] = false
    58  		return string(idBytes), nil
    59  	} else if !os.IsNotExist(err) {
    60  		return "", err
    61  	}
    62  
    63  	id := uuid.New().String()
    64  	reporter.BaseMetadata["new_install"] = true
    65  
    66  	if err := os.MkdirAll(filepath.Dir(idFilename), 0755); err != nil {
    67  		return "", err
    68  	}
    69  	if err := ioutil.WriteFile(idFilename, []byte(id), 0644); err != nil {
    70  		return "", err
    71  	}
    72  	return id, nil
    73  }
    74  

View as plain text