Dataset Viewer
doc
stringlengths 10
26.3k
| code
stringlengths 52
3.87M
|
---|---|
// RunFunc is a generic solution for running appropriate commands
// on local or remote host
|
func RunFunc(config *sshconf.Config) func(string) (string, error) {
if config == nil {
return func(command string) (string, error) {
var stderr bytes.Buffer
var stdout bytes.Buffer
c := exec.Command("/bin/bash", "-c", command)
c.Stderr = &stderr
c.Stdout = &stdout
if err := c.Start(); err != nil {
return "", err
}
if err := c.Wait(); err != nil {
return "", fmt.Errorf("executing %s : %s [%s]", command, stderr.String(), err)
}
return strings.TrimSpace(stdout.String()), nil
}
}
return func(command string) (string, error) {
c, err := ssh.NewSshConn(config)
if err != nil {
return "", err
}
defer c.ConnClose()
outstr, errstr, err := c.Run("sudo " + command)
if err != nil {
return "", fmt.Errorf("executing %s : %s [%s]", command, errstr, err)
}
return strings.TrimSpace(outstr), nil
}
}
|
// InterruptHandler is trying to release appropriate image
// in case SIGHUP, SIGINT or SIGTERM signal received
|
func InterruptHandler(fn func() error) {
//create a channel for interrupt handler
interrupt := make(chan os.Signal, 1)
// create an interrupt handler
signal.Notify(interrupt, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
// run a seperate goroutine.It's job is handling events in case a signal has been sent
go func() {
for {
select {
case <-interrupt:
fn()
}
}
}()
}
|
///// Functions providing verification services /////
// HexToDec converts hexadecimal number (two bytes) to decimal
|
func HexToDec(hexMask string, base int) (int, bool) {
var number int = 0
var i int
for i = base; i < len(hexMask); i++ {
if '0' <= hexMask[i] && hexMask[i] <= '9' {
number *= 16
number += int(hexMask[i] - '0')
} else if 'a' <= hexMask[i] && hexMask[i] <= 'f' {
number *= 16
number += int(hexMask[i]-'a') + 10
} else if 'A' <= hexMask[i] && hexMask[i] <= 'F' {
number *= 16
number += int(hexMask[i]-'A') + 10
} else {
break
}
if number >= 0xFFFFFF {
return 0, false
}
}
if i == base {
return 0, false
}
return number, true
}
|
// ConvertMaskHexToDotString converts a subnet mask from hexadecimal to a decimal form
|
func ConvertMaskHexToDotString(hexMask net.IPMask) string {
var strMask string // dec mask (255.255.255.0 for example)
var octet int // octet (255 for example)
var ok bool
maxOctet := 4 // IPv4 consists of 4 octets
for i := 0; i < maxOctet; i++ {
if octet, ok = HexToDec(fmt.Sprintf("%s", (hexMask[i:i+1])), 0); !ok {
return ""
//log.Fatalf("wrong mask is provided %s ", hexMask[:])
}
// in case it's the last octet add do not add '.'
if i == (maxOctet - 1) {
strMask += fmt.Sprintf("%d", octet)
} else {
strMask += fmt.Sprintf("%d.", octet)
}
}
// return mask represented as dec
return strMask
}
|
// CalculateBcast
// Gets strings (ip and netmask)
// Returns a string representing broadcast address
|
func CalculateBcast(ip, netmask string) string {
if ip == "" && netmask == "" {
return ""
}
var ipAddr [4]int
fmt.Sscanf(ip, "%d.%d.%d.%d", &ipAddr[0], &ipAddr[1], &ipAddr[2], &ipAddr[3])
var netMask [4]int
fmt.Sscanf(netmask, "%d.%d.%d.%d", &netMask[0], &netMask[1], &netMask[2], &netMask[3])
var brdCast [4]int
for oct := 0; oct < 4; oct++ {
brdCast[oct] = ((ipAddr[oct] * 1) & (netMask[oct] * 1)) + (255 ^ (netMask[oct] * 1))
}
return fmt.Sprintf("%d.%d.%d.%d", brdCast[0], brdCast[1], brdCast[2], brdCast[3])
}
|
// ConvertMaskDotStringToBits converts decimal mask (255.255.0.0 for example) to
// net.IPMask and returns once and bits of the mask
|
func ConvertMaskDotStringToBits(netmask string) (int, int) {
return net.ParseIP(netmask).DefaultMask().Size()
}
|
// GetLocalBridges finds bridges installed on the local system
// Returns a slice containing bridges names and error/nil
|
func GetLocalBridges() (installedBridges []string, err error) {
var netInterfaces []net.Interface
netInterfaces, err = net.Interfaces()
if err != nil {
return
}
for _, inet := range netInterfaces {
if _, err = os.Stat("/sys/class/net/" + inet.Name + "/bridge"); err == nil {
installedBridges = append(installedBridges, inet.Name)
}
}
if len(installedBridges) == 0 {
err = errors.New("cannot find any bridge")
}
return
}
|
// ParseInterfacesRH parses network configuration based on RHEL topology
// and represents the contents as a map
|
func ParseInterfacesRH() (map[string]map[string]string, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
dir := "/etc/sysconfig/network-scripts"
if _, err := os.Stat(dir); err != nil {
return nil, err
}
pattern := "ifcfg-"
ignoreFile := "ifcfg-lo"
var files []string
err = filepath.Walk(dir, func(ifcfgFile string, info os.FileInfo, err error) error {
if strings.Contains(ifcfgFile, pattern) && !strings.Contains(ifcfgFile, ignoreFile) {
files = append(files, ifcfgFile)
}
return nil
})
ifacesMap := make(map[string]map[string]string)
for _, iface := range ifaces {
if !strings.HasPrefix(iface.Name, "veth") || !strings.HasPrefix(iface.Name, "lo") {
netAddr, err := GetIfaceAddr(iface.Name)
if err != nil && err != ErrorNoIpv4 {
return nil, err
}
pat := `DEVICE\s*=\s*` + iface.Name
for _, file := range files {
if ioutils.PatternFound(file, pat) {
var addr string
switch {
case netAddr == nil:
addr = "N/A"
default:
addr = netAddr.String()
}
label := strings.Split(filepath.Base(file), "-")[1]
ifacesMap[label] = make(map[string]string)
ifacesMap[label][iface.Name] = addr
}
}
}
}
return ifacesMap, nil
}
|
// Return the IPv4 address of a network interface
|
func GetIfaceAddr(name string) (net.Addr, error) {
iface, err := net.InterfaceByName(name)
if err != nil {
return nil, err
}
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
var addrs4 []net.Addr
for _, addr := range addrs {
ip := (addr.(*net.IPNet)).IP
if ip4 := ip.To4(); len(ip4) == net.IPv4len {
addrs4 = append(addrs4, addr)
}
}
if len(addrs4) == 0 {
return nil, ErrorNoIpv4
}
return addrs4[0], nil
}
|
// FindAndReplace is looking for appropriate pattern
// in the file and replace it with a new one
// Could be also applied for generating a new file
|
func FindAndReplace(srcFile, dstFile, oldPattern, newPattern string,
filePermissions os.FileMode) error {
srcFileBuf, err := ioutil.ReadFile(srcFile)
if err != nil {
return err
}
// convert the string pattern to the slice of bytes
newPat := []byte(newPattern)
// compile reg exp
rgxp, _ := regexp.Compile(oldPattern)
// Not so fast : returns a new copy of the slice (copying here)
newBuf := rgxp.ReplaceAll(srcFileBuf, newPat)
return ioutil.WriteFile(dstFile, newBuf, filePermissions)
}
|
// FindAndReplaceMulti is looking for appropriate patterns
// in the file and replace them with new patterns
// The patterns must be represented as a map where key is the old pattern and value
// is a new one
// Could be also applied for generating a new file
|
func FindAndReplaceMulti(srcFile, dstFile string, patternMap map[string]string,
filePermissions os.FileMode) error {
fileBuf, err := ioutil.ReadFile(srcFile)
if err != nil {
return err
}
for oldp, newp := range patternMap {
// convert the string pattern to the slice of bytes
newPattern := []byte(newp)
// compile reg exp
rgxp, _ := regexp.Compile(oldp)
// Not so fast : returns a new copy of the slice (copying here)
fileBuf = rgxp.ReplaceAll(fileBuf, newPattern)
}
return ioutil.WriteFile(dstFile, fileBuf, filePermissions)
}
|
// CreateDirRecursively gets path to directories tree , permissions , UID
// and GID and a boolean value telling whether we should backup existing tree
// in case of necessity
// Creates the whole tree
// Returns error or nil
|
func CreateDirRecursively(dirToCreate string, permissions os.FileMode,
owner, group int, backupOriginal bool) error {
info, err := os.Stat(dirToCreate)
if err == nil {
if !info.IsDir() {
return errors.New(dirToCreate + " exsists but it's not directory")
}
if backupOriginal {
if err := os.Rename(dirToCreate, dirToCreate+".bkp"); err != nil {
return err
}
}
} else {
if err := os.MkdirAll(dirToCreate, permissions); err != nil {
return err
}
}
if err = os.Chown(dirToCreate, owner, group); err != nil {
return err
}
return nil
}
|
// RemoveIfExists cleans up appropriate stuff
// It gets a single path or multiple paths and
// boolean value telling if an error shall be thrown
// Returns error or nil
|
func RemoveIfExists(handleError bool, paths ...string) error {
for _, path := range paths {
if _, err := os.Stat(path); err == nil {
if err = os.RemoveAll(path); err != nil {
if handleError {
return err
}
}
}
}
return nil
}
|
///// Functions for copying/moving files and directories /////
|
func MyCopy(src, dst string, dstFilePermissions os.FileMode,
dstFileOwner, dstFileGroup int, removeOriginal bool) error {
srcInfo, err := os.Stat(src)
if err != nil {
return err
}
if srcInfo.IsDir() {
return CopyDir(src, dst)
}
return CopyFile(src, dst, dstFilePermissions, dstFileOwner, dstFileGroup, removeOriginal)
}
|
// Copy a directory(not portable function due to the "cp" usage)
|
func CopyDir(srcDir, dstDir string) error {
if err := exec.Command("cp", "-a", srcDir, dstDir).Run(); err != nil {
return errors.New(fmt.Sprintf("copying %s to %s : %s", srcDir, dstDir, err.Error()))
}
return nil
}
|
// copyFile copies a file.
// Returns amount of written bytes and error
|
func CopyFile(srcFile, dstFile string, dstFilePermissions os.FileMode,
dstFileOwner, dstFileGroup int, removeOriginal bool) error {
var srcfd, dstfd *os.File
var err error
// open source file
if srcfd, err = os.Open(srcFile); err != nil {
return err
}
// make sure descryptor is closed upon an error or exitting the function
defer srcfd.Close()
// get the file statistic
srcFdStat, _ := srcfd.Stat()
if dstFilePermissions == 0 {
dstFilePermissions = srcFdStat.Mode().Perm()
}
finfo, err := os.Stat(dstFile)
var newDstFile string
if err == nil && finfo.IsDir() {
newDstFile = filepath.Join(dstFile, filepath.Base(srcFile))
} else {
newDstFile = dstFile
}
// open destination file
if dstfd, err = os.OpenFile(newDstFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC,
dstFilePermissions); err != nil {
return err
}
// close destination fd upon an error or exitting the function
defer dstfd.Close()
// use io.Copy from standard library
if _, err = io.Copy(dstfd, srcfd); err != nil {
return err
}
if removeOriginal {
if err := os.Remove(srcFile); err != nil {
return err
}
}
return err
}
|
// ValidateDistro validates distribution
|
func ValidateDistro(regExp, file string) error {
buf, err := ioutil.ReadFile(file)
if err == nil {
ok, err := regexp.Match(regExp, buf)
if ok && err == nil {
return nil
}
}
return errors.New("unsupported Linux distribution")
}
|
// ValidateNics gets a reference to a string slice containing
// NICs names and verifies if appropriate NIC is available
|
func ValidateNics(nicList []string) error {
for _, iface := range nicList {
if _, err := net.InterfaceByName(iface); err != nil {
return err
}
}
return nil
}
|
// ValidateAmountOfCpus gets amount of CPUs required
// It verifies that amount of installed CPUs is equal
// to amount of required
|
func ValidateAmountOfCpus(required int) error {
amountOfInstalledCpus := runtime.NumCPU()
if amountOfInstalledCpus != required {
return errors.New(fmt.Sprintf("CPU amount.Required %d.Installed %d",
required, amountOfInstalledCpus))
}
return nil
}
|
// ValidateAmountOfRam gets amount of RAM needed for proceeding
// The function verifies if eligable amount RAM is installed
|
func ValidateAmountOfRam(minRequiredInMb int) error {
installedRamInMb, err := sysutils.SysinfoRam()
if err != nil {
return err
}
if minRequiredInMb > installedRamInMb {
return errors.New(fmt.Sprintf("RAM amount.Required %d.Installed %d",
minRequiredInMb, installedRamInMb))
}
return nil
}
|
// Very simple and ugly implementation.
|
func Extract(fileToExtract, targetLocation string) error {
var execCmd string
var cmdArgs string
var cmdArgDst string
switch {
case strings.HasSuffix(fileToExtract, ".tgz") ||
strings.HasSuffix(fileToExtract, ".tar.gz"):
execCmd = "tar"
cmdArgs = "xfzp"
cmdArgDst = "-C"
case strings.HasSuffix(fileToExtract, ".tgx") ||
strings.HasSuffix(fileToExtract, ".tar.gx"):
execCmd = "tar"
cmdArgs = "xfJp"
cmdArgDst = "-C"
case strings.HasSuffix(fileToExtract, ".bz2"):
execCmd = "tar"
cmdArgs = "xfjp"
cmdArgDst = "-C"
case strings.HasSuffix(fileToExtract, ".zip"):
execCmd = "unzip"
cmdArgDst = "-d"
default:
return errors.New("unknown compression format")
}
out, err := exec.Command(execCmd, cmdArgs, fileToExtract, cmdArgDst, targetLocation).CombinedOutput()
if err != nil {
return fmt.Errorf("%s [%s]", out, err)
}
return nil
}
|
// SysinfoRam returns total amount of installed RAM in Megabytes
|
func SysinfoRam() (int, error) {
sysInfoBufPtr := new(syscall.Sysinfo_t)
if err := syscall.Sysinfo(sysInfoBufPtr); err != nil {
return 0, err
}
return int(sysInfoBufPtr.Totalram / 1024 / 1024), nil
}
|
// Looks at /proc/mounts to determine of the specified
// mountpoint has been mounted
|
func Mounted(device, mountpoint string) (bool, error) {
entries, err := parseMountTable()
if err != nil {
return false, err
}
// Search the table for the mountpoint
for _, entry := range entries {
if entry.mountpoint == mountpoint || strings.Contains(entry.source, device) {
return true, nil
}
}
return false, nil
}
|
// Peek returns the next item, but does not consume it
|
func (c *ItemConsume) Peek() LexItem {
if c.peekCount > 0 {
return c.items[c.peekCount-1]
}
c.peekCount = 1
c.items[0] = c.lexer.NextItem()
return c.items[0]
}
|
// Consume returns the next item, and consumes it.
|
func (c *ItemConsume) Consume() LexItem {
if c.peekCount > 0 {
c.peekCount--
} else {
c.items[0] = c.lexer.NextItem()
}
return c.items[c.peekCount]
}
|
// Backup2 pushes `t1` into the buffer, and moves 2 items back
|
func (c *ItemConsume) Backup2(t1 LexItem) {
c.items[1] = t1
c.peekCount = 2
}
|
// Load loads `pwd`/.env or GOENV and a `.local` for overrides
|
func Load() {
pwd, _ := os.Getwd()
goenv := os.Getenv("GOENV")
envFile := ".env"
if len(goenv) > 0 && goenv != "development" {
envFile = fmt.Sprintf("%s.%s", envFile, goenv)
}
localFile := envFile + ".local"
env.ReadEnv(path.Join(pwd, envFile))
env.ReadEnv(path.Join(pwd, localFile))
}
|
// AdvancePage advances to the specified page in result set, while retaining
// the filtering options.
|
func (l *ListMetricsOptions) AdvancePage(next *PaginationMeta) ListMetricsOptions {
return ListMetricsOptions{
PaginationMeta: next,
Name: l.Name,
}
}
|
// List metrics using the provided options.
//
// Librato API docs: https://www.librato.com/docs/api/#list-a-subset-of-metrics
|
func (m *MetricsService) List(opts *ListMetricsOptions) ([]Metric, *ListMetricsResponse, error) {
u, err := urlWithOptions("metrics", opts)
if err != nil {
return nil, nil, err
}
req, err := m.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
var metricsResponse struct {
Query PaginationResponseMeta
Metrics []Metric
}
_, err = m.client.Do(req, &metricsResponse)
if err != nil {
return nil, nil, err
}
return metricsResponse.Metrics,
&ListMetricsResponse{
ThisPage: &metricsResponse.Query,
NextPage: metricsResponse.Query.nextPage(opts.PaginationMeta),
},
nil
}
|
// Get a metric by name
//
// Librato API docs: https://www.librato.com/docs/api/#retrieve-a-metric-by-name
|
func (m *MetricsService) Get(name string) (*Metric, *http.Response, error) {
u := fmt.Sprintf("metrics/%s", name)
req, err := m.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
metric := new(Metric)
resp, err := m.client.Do(req, metric)
if err != nil {
return nil, resp, err
}
return metric, resp, err
}
|
// Create metrics
//
// Librato API docs: https://www.librato.com/docs/api/#create-a-measurement
|
func (m *MetricsService) Create(measurements *MeasurementSubmission) (*http.Response, error) {
req, err := m.client.NewRequest("POST", "/metrics", measurements)
if err != nil {
return nil, err
}
return m.client.Do(req, nil)
}
|
// Update a metric.
//
// Librato API docs: https://www.librato.com/docs/api/#update-a-metric-by-name
|
func (m *MetricsService) Update(metric *Metric) (*http.Response, error) {
u := fmt.Sprintf("metrics/%s", *metric.Name)
req, err := m.client.NewRequest("PUT", u, metric)
if err != nil {
return nil, err
}
return m.client.Do(req, nil)
}
|
// Delete a metric.
//
// Librato API docs: https://www.librato.com/docs/api/#delete-a-metric-by-name
|
func (m *MetricsService) Delete(name string) (*http.Response, error) {
u := fmt.Sprintf("metrics/%s", name)
req, err := m.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return m.client.Do(req, nil)
}
|
// Format outputs a message like "2014-02-28 18:15:57 [example] INFO something happened"
|
func (f *defaultFormatter) Format(rec *Record) string {
return fmt.Sprintf("%s [%s] %-8s %s", fmt.Sprint(rec.Time)[:19], rec.LoggerName, LevelNames[rec.Level], fmt.Sprintf(rec.Format, rec.Args...))
}
|
// NewLogger returns a new Logger implementation. Do not forget to close it at exit.
|
func NewLogger(name string) Logger {
return &logger{
Name: name,
Level: DefaultLevel,
Handler: DefaultHandler,
}
}
|
// Fatal is equivalent to Critical() followed by a call to os.Exit(1).
|
func (l *logger) Fatal(format string, args ...interface{}) {
l.Critical(format, args...)
l.Handler.Close()
os.Exit(1)
}
|
// Panic is equivalent to Critical() followed by a call to panic().
|
func (l *logger) Panic(format string, args ...interface{}) {
l.Critical(format, args...)
panic(fmt.Sprintf(format, args...))
}
|
// Critical sends a critical level log message to the handler. Arguments are handled in the manner of fmt.Printf.
|
func (l *logger) Critical(format string, args ...interface{}) {
if l.Level >= CRITICAL {
l.log(CRITICAL, format, args...)
}
}
|
// Error sends a error level log message to the handler. Arguments are handled in the manner of fmt.Printf.
|
func (l *logger) Error(format string, args ...interface{}) {
if l.Level >= ERROR {
l.log(ERROR, format, args...)
}
}
|
// Warning sends a warning level log message to the handler. Arguments are handled in the manner of fmt.Printf.
|
func (l *logger) Warning(format string, args ...interface{}) {
if l.Level >= WARNING {
l.log(WARNING, format, args...)
}
}
|
// Notice sends a notice level log message to the handler. Arguments are handled in the manner of fmt.Printf.
|
func (l *logger) Notice(format string, args ...interface{}) {
if l.Level >= NOTICE {
l.log(NOTICE, format, args...)
}
}
|
// Info sends a info level log message to the handler. Arguments are handled in the manner of fmt.Printf.
|
func (l *logger) Info(format string, args ...interface{}) {
if l.Level >= INFO {
l.log(INFO, format, args...)
}
}
|
// Debug sends a debug level log message to the handler. Arguments are handled in the manner of fmt.Printf.
|
func (l *logger) Debug(format string, args ...interface{}) {
if l.Level >= DEBUG {
l.log(DEBUG, format, args...)
}
}
|
// FilterAndFormat filters any record according to loggging level
|
func (h *BaseHandler) FilterAndFormat(rec *Record) string {
if h.Level >= rec.Level {
return h.Formatter.Format(rec)
}
return ""
}
|
// NewWriterHandler creates a new writer handler with given io.Writer
|
func NewWriterHandler(w io.Writer) *WriterHandler {
return &WriterHandler{
BaseHandler: NewBaseHandler(),
w: w,
}
}
|
// Handle writes any given Record to the Writer.
|
func (b *WriterHandler) Handle(rec *Record) {
message := b.BaseHandler.FilterAndFormat(rec)
if message == "" {
return
}
if b.Colorize {
b.w.Write([]byte(fmt.Sprintf("\033[%dm", LevelColors[rec.Level])))
}
fmt.Fprint(b.w, message)
if b.Colorize {
b.w.Write([]byte("\033[0m")) // reset color
}
}
|
// SetFormatter sets formatter for all handlers
|
func (b *MultiHandler) SetFormatter(f Formatter) {
for _, h := range b.handlers {
h.SetFormatter(f)
}
}
|
// SetLevel sets level for all handlers
|
func (b *MultiHandler) SetLevel(l Level) {
for _, h := range b.handlers {
h.SetLevel(l)
}
}
|
// Handle handles given record with all handlers concurrently
|
func (b *MultiHandler) Handle(rec *Record) {
wg := sync.WaitGroup{}
wg.Add(len(b.handlers))
for _, handler := range b.handlers {
go func(handler Handler) {
handler.Handle(rec)
wg.Done()
}(handler)
}
wg.Wait()
}
|
// Close closes all handlers concurrently
|
func (b *MultiHandler) Close() {
wg := sync.WaitGroup{}
wg.Add(len(b.handlers))
for _, handler := range b.handlers {
go func(handler Handler) {
handler.Close()
wg.Done()
}(handler)
}
wg.Wait()
}
|
// NewClient returns a new dnsimple client,
// requires an authorization token. You can generate
// an OAuth token by visiting the Apps & API section
// of the DNSimple control panel for your account.
|
func NewClient(email string, token string) (*Client, error) {
client := Client{
Token: token,
Email: email,
URL: "https://api.dnsimple.com/v1",
Http: cleanhttp.DefaultClient(),
}
return &client, nil
}
|
// Creates a new request with the params
|
func (c *Client) NewRequest(body map[string]interface{}, method string, endpoint string) (*http.Request, error) {
u, err := url.Parse(c.URL + endpoint)
if err != nil {
return nil, fmt.Errorf("Error parsing base URL: %s", err)
}
rBody, err := encodeBody(body)
if err != nil {
return nil, fmt.Errorf("Error encoding request body: %s", err)
}
// Build the request
req, err := http.NewRequest(method, u.String(), rBody)
if err != nil {
return nil, fmt.Errorf("Error creating request: %s", err)
}
// Add the authorization header
if c.DomainToken != "" {
req.Header.Add("X-DNSimple-Domain-Token", c.DomainToken)
} else {
req.Header.Add("X-DNSimple-Token", fmt.Sprintf("%s:%s", c.Email, c.Token))
}
req.Header.Add("Accept", "application/json")
// If it's a not a get, add a content-type
if method != "GET" {
req.Header.Add("Content-Type", "application/json")
}
return req, nil
}
|
// parseErr is used to take an error json resp
// and return a single string for use in error messages
|
func parseErr(resp *http.Response) error {
dnsError := DNSimpleError{}
err := decodeBody(resp, &dnsError)
// if there was an error decoding the body, just return that
if err != nil {
return fmt.Errorf("Error parsing error body for non-200 request: %s", err)
}
return fmt.Errorf("API Error: %s", dnsError.Join())
}
|
// Fatal is equivalent to Critical() followed by a call to os.Exit(1).
|
func (c *context) Fatal(format string, args ...interface{}) {
c.logger.Fatal(c.prefixFormat()+format, args...)
}
|
// Panic is equivalent to Critical() followed by a call to panic().
|
func (c *context) Panic(format string, args ...interface{}) {
c.logger.Panic(c.prefixFormat()+format, args...)
}
|
// Critical sends a critical level log message to the handler. Arguments are
// handled in the manner of fmt.Printf.
|
func (c *context) Critical(format string, args ...interface{}) {
c.logger.Critical(c.prefixFormat()+format, args...)
}
|
// Error sends a error level log message to the handler. Arguments are handled
// in the manner of fmt.Printf.
|
func (c *context) Error(format string, args ...interface{}) {
c.logger.Error(c.prefixFormat()+format, args...)
}
|
// Warning sends a warning level log message to the handler. Arguments are
// handled in the manner of fmt.Printf.
|
func (c *context) Warning(format string, args ...interface{}) {
c.logger.Warning(c.prefixFormat()+format, args...)
}
|
// Notice sends a notice level log message to the handler. Arguments are
// handled in the manner of fmt.Printf.
|
func (c *context) Notice(format string, args ...interface{}) {
c.logger.Notice(c.prefixFormat()+format, args...)
}
|
// Info sends a info level log message to the handler. Arguments are handled in
// the manner of fmt.Printf.
|
func (c *context) Info(format string, args ...interface{}) {
c.logger.Info(c.prefixFormat()+format, args...)
}
|
// Debug sends a debug level log message to the handler. Arguments are handled
// in the manner of fmt.Printf.
|
func (c *context) Debug(format string, args ...interface{}) {
c.logger.Debug(c.prefixFormat()+format, args...)
}
|
// New creates a new Logger from current context
|
func (c *context) New(prefixes ...interface{}) Logger {
return newContext(c.logger, c.prefix, prefixes...)
}
|
// CreateRecord creates a record from the parameters specified and
// returns an error if it fails. If no error and an ID is returned,
// the Record was succesfully created.
|
func (c *Client) CreateRecord(domain string, opts *ChangeRecord) (string, error) {
// Make the request parameters
params := make(map[string]interface{})
params["name"] = opts.Name
params["record_type"] = opts.Type
params["content"] = opts.Value
if opts.Ttl != "" {
ttl, err := strconv.ParseInt(opts.Ttl, 0, 0)
if err != nil {
return "", fmt.Errorf("Error parsing ttl: %s", err.Error())
}
params["ttl"] = ttl
}
endpoint := fmt.Sprintf("/domains/%s/records", domain)
req, err := c.NewRequest(params, "POST", endpoint)
if err != nil {
return "", err
}
resp, err := checkResp(c.Http.Do(req))
if err != nil {
return "", fmt.Errorf("Error creating record: %s", err)
}
record := new(RecordResponse)
err = decodeBody(resp, &record)
if err != nil {
return "", fmt.Errorf("Error parsing record response: %s", err)
}
// The request was successful
return record.Record.StringId(), nil
}
|
// DestroyRecord destroys a record by the ID specified and
// returns an error if it fails. If no error is returned,
// the Record was succesfully destroyed.
|
func (c *Client) DestroyRecord(domain string, id string) error {
var body map[string]interface{}
req, err := c.NewRequest(body, "DELETE", fmt.Sprintf("/domains/%s/records/%s", domain, id))
if err != nil {
return err
}
_, err = checkResp(c.Http.Do(req))
if err != nil {
return fmt.Errorf("Error destroying record: %s", err)
}
// The request was successful
return nil
}
|
// RetrieveRecord gets a record by the ID specified and
// returns a Record and an error. An error will be returned for failed
// requests with a nil Record.
|
func (c *Client) RetrieveRecord(domain string, id string) (*Record, error) {
var body map[string]interface{}
req, err := c.NewRequest(body, "GET", fmt.Sprintf("/domains/%s/records/%s", domain, id))
if err != nil {
return nil, err
}
resp, err := checkResp(c.Http.Do(req))
if err != nil {
return nil, fmt.Errorf("Error retrieving record: %s", err)
}
recordResp := RecordResponse{}
err = decodeBody(resp, &recordResp)
if err != nil {
return nil, fmt.Errorf("Error decoding record response: %s", err)
}
// The request was successful
return &recordResp.Record, nil
}
|
// GetRecords retrieves all the records for the given domain.
|
func (c *Client) GetRecords(domain string) ([]Record, error) {
req, err := c.NewRequest(nil, "GET", "/domains/"+domain+"/records")
if err != nil {
return nil, err
}
resp, err := c.Http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
recordResponses := make([]RecordResponse, 10)
err = decode(resp.Body, &recordResponses)
if err != nil {
return nil, err
}
records := make([]Record, len(recordResponses))
for i, rr := range recordResponses {
records[i] = rr.Record
}
return records, nil
}
|
// convertStatus maps the status to a code in the "required" FHIR value set:
// http://hl7.org/fhir/DSTU2/valueset-allergy-intolerance-status.html
// If the status cannot be reliably mapped, active is assumed.
|
func (a *Allergy) convertStatus() string {
var status string
if a.NegationInd {
return "refuted"
}
statusConcept := a.StatusCode.FHIRCodeableConcept("")
switch {
case statusConcept.MatchesCode("http://snomed.info/sct", "55561003"):
status = "active"
case statusConcept.MatchesCode("http://snomed.info/sct", "73425007"):
status = "inactive"
case statusConcept.MatchesCode("http://snomed.info/sct", "413322009"):
status = "resolved"
default:
status = "active"
}
// In order to remain consistent, fix the status if there is an end date
// and it doesn't match the start date (in which case we can't be sure it's really an end)
if status == "" && a.EndTime != nil && a.StartTime != nil && *a.EndTime != *a.StartTime {
status = "resolved"
}
return status
}
|
// convertCriticality maps the severity to a CodeableConcept. FHIR has a "required" value set for
// criticality:
// http://hl7.org/fhir/DSTU2/valueset-allergy-intolerance-criticality.html
// If the severity can't be mapped, criticality will be left blank
|
func (a *Allergy) convertCriticality() string {
if a.Severity == nil {
return ""
}
criticality := a.Severity.FHIRCodeableConcept("")
switch {
case criticality.MatchesCode("http://snomed.info/sct", "399166001"):
return "CRITH"
case criticality.MatchesCode("http://snomed.info/sct", "255604002"):
return "CRITL"
case criticality.MatchesCode("http://snomed.info/sct", "371923003"):
// Mild to moderate: translate to L
return "CRITL"
case criticality.MatchesCode("http://snomed.info/sct", "6736007"):
// Moderate: tough to call L or H, translate to CRITU (unable to determine)
return "CRITU"
case criticality.MatchesCode("http://snomed.info/sct", "371924009"):
// Moderate to severe: err on the side of safety, translate to CRITH
return "CRITH"
case criticality.MatchesCode("http://snomed.info/sct", "24484000"):
return "CRITH"
}
return ""
}
|
// convertSeverity maps the severity to a CodeableConcept. FHIR has a "required" value set for
// severity:
// http://hl7.org/fhir/DSTU2/valueset-reaction-event-severity.html
// If the severity can't be mapped, severity will be left blank
|
func (a *Allergy) convertSeverity() string {
if a.Severity == nil {
return ""
}
severity := a.Severity.FHIRCodeableConcept("")
switch {
case severity.MatchesCode("http://snomed.info/sct", "399166001"):
return "severe"
case severity.MatchesCode("http://snomed.info/sct", "255604002"):
return "mild"
case severity.MatchesCode("http://snomed.info/sct", "371923003"):
// Mild to moderate: translate to moderate
return "moderate"
case severity.MatchesCode("http://snomed.info/sct", "6736007"):
return "moderate"
case severity.MatchesCode("http://snomed.info/sct", "371924009"):
// Moderate to severe: err on the side of safety, translate to severe
return "severe"
case severity.MatchesCode("http://snomed.info/sct", "24484000"):
return "severe"
}
return ""
}
|
// TODO: :care_goals, :medical_equipment, :results, :social_history, :support, :advance_directives, :insurance_providers, :functional_statuses
|
func (p *Patient) MatchingEncounterReference(entry Entry) *fhir.Reference {
for _, encounter := range p.Encounters {
// TODO: Tough to do right. Most conservative approach is to only match things that start during the encounter
if entry.StartTime != nil && encounter.StartTime != nil && encounter.EndTime != nil &&
*encounter.StartTime <= *entry.StartTime && *entry.StartTime <= *encounter.EndTime {
return encounter.FHIRReference()
}
}
return nil
}
|
// FHIRTransactionBundle returns a FHIR bundle representing a transaction to post all patient data to a server
|
func (p *Patient) FHIRTransactionBundle(conditionalUpdate bool) *fhir.Bundle {
bundle := new(fhir.Bundle)
bundle.Type = "transaction"
fhirModels := p.FHIRModels()
bundle.Entry = make([]fhir.BundleEntryComponent, len(fhirModels))
for i := range fhirModels {
bundle.Entry[i].FullUrl = "urn:uuid:" + reflect.ValueOf(fhirModels[i]).Elem().FieldByName("Id").String()
bundle.Entry[i].Resource = fhirModels[i]
bundle.Entry[i].Request = &fhir.BundleEntryRequestComponent{
Method: "POST",
Url: reflect.TypeOf(fhirModels[i]).Elem().Name(),
}
}
if conditionalUpdate {
if err := ConvertToConditionalUpdates(bundle); err != nil {
log.Println("Error:", err.Error())
}
}
return bundle
}
|
// Expect sorted string-length.
|
func AutoLink(html string, names []string) string {
doc, err := gq.NewDocumentFromReader(strings.NewReader(html))
if err != nil {
return html
}
for _, name := range names {
if len([]rune(name)) <= 1 {
continue
}
doc.Find("*").EachWithBreak(func(i int, s *gq.Selection) bool {
if strings.Contains(s.Text(), name) {
t := s.Text()
h, _ := s.Html()
if t != "" && h == "" {
html := strings.Replace(t, name, fmt.Sprintf(`<a class="link-underline external" href="/d/%[1]s">%[1]s</a>`, name), 1)
s.ReplaceWithHtml(html)
return false
}
}
return true
})
}
res, err := doc.Find("body").Html()
if err != nil {
return html
}
return res
}
|
// convertMedicationStatus maps the status to a code in the required FHIR value set:
// http://hl7.org/fhir/DSTU2/valueset-medication-statement-status.html
|
func (m *Medication) convertMedicationStatus() string {
var status string
statusConcept := m.StatusCode.FHIRCodeableConcept("")
switch {
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "active"):
status = "active"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "cancelled"):
status = "entered-in-error"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "held"):
status = "intended"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "new"):
status = "intended"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "suspended"):
status = "completed"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "nullified"):
status = "entered-in-error"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "obsolete"):
status = "cancelled"
// NOTE: this is not a real ActStatus, but HDS seems to use it
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "ordered"):
status = "intended"
// NOTE: this is not a real ActStatus, but HDS seems to use it
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "discharge"):
status = "intended"
// NOTE: this is not a real ActStatus, but HDS seems to use it
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "dispensed"):
status = "intended"
case m.MoodCode == "RQO":
status = "intended"
case len(m.StatusCode) == 0 && m.EndTime == nil:
status = "active"
default:
status = "completed"
}
return status
}
|
// NewReaderLexer creats a ReaderLexer
|
func NewReaderLexer(in io.Reader, fn LexFn) *ReaderLexer {
return &ReaderLexer{
bufio.NewReader(in),
0,
-1,
-1,
1,
[]rune{},
make(chan LexItem, 1),
fn,
}
}
|
// Current returns current rune being considered
|
func (l *ReaderLexer) Current() (r rune) {
if len(l.buf) == 0 {
return l.Next()
}
return l.buf[l.peekLoc]
}
|
// Next returns the next rune
|
func (l *ReaderLexer) Next() (r rune) {
/* Illustrated guide to how the cursors move:
pos
|
v
buf | a | b | c |
^
|
peekLoc
-> l.Nex() -> returns d
pos
|
v
buf | a | b | c | d |
^
|
peekLoc
-> l.Peek() -> returns e
pos
|
v
buf | a | b | c | d | e |
^
|
peekLoc
-> l.Backup()
-> l.Backup()
pos
|
v
buf | a | b | c | d | e |
^
|
peekLoc
-> l.Next() -> returns c
pos
|
v
buf | a | b | c | d | e |
^
|
peekLoc
-> l.Next() -> returns d
pos
|
v
buf | a | b | c | d | e |
^
|
peekLoc
*/
guard := Mark("Next")
defer func() {
Trace("return = %q", r)
guard()
}()
if l.pos == -1 || len(l.buf) == l.peekLoc+1 {
r, _, err := l.source.ReadRune()
switch err {
case nil:
l.peekLoc++
l.pos++
l.buf = append(l.buf, r)
case io.EOF:
l.peekLoc++
l.pos++
r = -1
if l.buf[len(l.buf)-1] != r {
l.buf = append(l.buf, r)
}
}
} else {
l.peekLoc++
l.pos++
}
loc := l.peekLoc
if loc < 0 || len(l.buf) <= loc {
return EOF
// panic(fmt.Sprintf("FATAL: loc = %d, l.buf = %q (len = %d)", loc, l.buf, len(l.buf)))
}
Trace("l.buf = %q, loc = %d", l.buf, loc)
return l.buf[loc]
}
|
// Peek returns the next rune, but does not move the position
|
func (l *ReaderLexer) Peek() (r rune) {
guard := Mark("Peek")
defer func() {
Trace("return = %q", r)
guard()
}()
r = l.Next()
l.Backup()
return r
}
|
// Backup moves the cursor 1 position
|
func (l *ReaderLexer) Backup() {
guard := Mark("Backup")
defer guard()
l.pos--
l.peekLoc = l.pos // align
Trace("Backed up l.pos = %d", l.pos)
}
|
// AcceptString returns true if the given string can be matched exactly.
// This is a utility function to be called from concrete Lexer types
|
func (l *ReaderLexer) AcceptString(word string) bool {
guard := Mark("AcceptString")
defer guard()
return AcceptString(l, word, false)
}
|
// PeekString returns true if the given string can be matched exactly,
// but does not move the position
|
func (l *ReaderLexer) PeekString(word string) bool {
guard := Mark(fmt.Sprintf("PeekString '%s'", word))
defer guard()
return AcceptString(l, word, true)
}
|
// AcceptRun takes a string, and moves the cursor forward as long as
// the input matches one of the given runes in the string
|
func (l *ReaderLexer) AcceptRun(valid string) bool {
guard := Mark("AcceptRun")
defer guard()
return AcceptRun(l, valid)
}
|
// AcceptRunExcept takes a string, and moves the cursor forward as
// long as the input DOES NOT match one of the given runes in the string
|
func (l *ReaderLexer) AcceptRunExcept(valid string) bool {
guard := Mark("AcceptRunExcept")
defer guard()
return AcceptRunExcept(l, valid)
}
|
// Emit creates and sends a new Item of type `t` through the output
// channel. The Item is generated using `Grab`
|
func (l *ReaderLexer) Emit(t ItemType) {
Trace("Emit %s", t)
l.items <- l.Grab(t)
}
|
// EmitErrorf emits an Error Item
|
func (l *ReaderLexer) EmitErrorf(format string, args ...interface{}) LexFn {
l.items <- NewItem(ItemError, l.pos, l.line, fmt.Sprintf(format, args...))
return nil
}
|
// BufferString returns the current buffer
|
func (l *ReaderLexer) BufferString() (str string) {
guard := Mark("BufferString")
defer func() {
Trace("BufferString() -> l.pos = %d, l.buf = %q, return = %q\n", l.pos, l.buf, str)
guard()
}()
Trace("l.buf = %q, l.pos = %d", l.buf, l.pos)
total := 0
for i := 0; len(l.buf) > i && i < l.pos+1; i++ {
Trace("l.buf[%d] = %q\n", i, l.buf[i])
if l.buf[i] == -1 {
break
}
total += utf8.RuneLen(l.buf[i])
}
Trace("Expecting buffer to contain %d bytes", total)
if total == 0 {
str = ""
return
}
strbuf := make([]byte, total)
pos := 0
for i := 0; len(l.buf) > i && i < l.pos+1; i++ {
if l.buf[i] == -1 {
break
}
Trace("Encoding rune %q into position %d", l.buf[i], pos)
pos += utf8.EncodeRune(strbuf[pos:], l.buf[i])
}
Trace("%q (%d)\n", strbuf, len(strbuf))
str = string(strbuf)
return str
}
|
// Grab creates a new Item of type `t`. The value in the item is created
// from the position of the last read item to current cursor position
|
func (l *ReaderLexer) Grab(t ItemType) Item {
guard := Mark("Grab")
defer guard()
// special case
line := l.line
strbuf := l.BufferString()
if strings.ContainsRune(strbuf, '\n') {
l.line++
}
strlen := len(strbuf)
item := NewItem(t, l.start, line, strbuf)
l.buf = l.buf[utf8.RuneCountInString(strbuf):]
l.peekLoc = l.peekLoc - l.pos - 1
l.pos = -1
l.start += strlen
Trace("Emit item %#v", item)
return item
}
|
// ReadEnv reads an .env formatted file and sets the vars to the current
// environment so exec calls respect the settings.
|
func ReadEnv(file string) error {
content, err := ioutil.ReadFile(file)
if err != nil {
return err
}
for _, line := range strings.Split(string(content), "\n") {
tokens := strings.SplitN(line, "=", 2)
if len(tokens) == 2 && tokens[0][0] != '#' {
k, v := strings.TrimSpace(tokens[0]), strings.TrimSpace(tokens[1])
os.Setenv(k, v)
}
}
return nil
}
|
//Setup will ensure the w1-gpio and w1-therm modules are loaded
//and ensure that there is at least one w1_bus_masterX present
|
func Setup() error {
//ensure the modules are loaded
cmd := exec.Command(modprobeCmd, w1gpioMod)
if err := cmd.Run(); err != nil {
return err
}
cmd = exec.Command(modprobeCmd, w1thermMod)
if err := cmd.Run(); err != nil {
return err
}
//check that the 1 wire master device is present
fis, err := ioutil.ReadDir(basePath)
if err != nil {
return err
}
masterPresent := false
for i := range fis {
if strings.HasPrefix(fis[i].Name(), masterPrefix) {
masterPresent = true
break
}
}
if !masterPresent {
return errNoBus
}
//good to go
return nil
}
|
//Slaves will return a listing of available slaves
|
func Slaves() ([]string, error) {
var slaves []string
fis, err := ioutil.ReadDir(basePath)
if err != nil {
return nil, err
}
for i := range fis {
if strings.HasPrefix(fis[i].Name(), slavePrefix) {
if (fis[i].Mode() & os.ModeSymlink) == os.ModeSymlink {
slaves = append(slaves, fis[i].Name())
}
}
}
return slaves, nil
}
|
// FromJSON initializes a new Config instance from a JSON string
|
func FromJSON(from string) (types.Config, error) {
c := newConfig()
m := map[string]interface{}{}
if err := json.Unmarshal([]byte(from), &m); err != nil {
return nil, err
}
for k, v := range m {
c.v.Set(k, v)
}
return c, nil
}
|
// Register registers a new configuration with the config package.
|
func Register(r types.ConfigRegistration) {
registrationsRWL.Lock()
defer registrationsRWL.Unlock()
for x, rr := range registrations {
if rr.Name() == r.Name() {
registrations[x] = r
return
}
}
registrations = append(registrations, r)
}
|
// NewConfig initialies a new instance of a Config object with the specified
// options.
|
func NewConfig(
loadGlobalConfig, loadUserConfig bool,
configName, configType string) types.Config {
return newConfigWithOptions(
loadGlobalConfig, loadUserConfig, configName, configType)
}
|
// flattenEnvVars returns a map of configuration keys coming from a config
// which may have been nested.
|
func (c *config) flattenEnvVars(
prefix string, keys map[string]interface{}, envVars map[string]string) {
for k, v := range keys {
var kk string
if prefix == "" {
kk = k
} else {
kk = fmt.Sprintf("%s.%s", prefix, k)
}
ek := strings.ToUpper(strings.Replace(kk, ".", "_", -1))
if LogFlattenEnvVars {
log.WithFields(log.Fields{
"key": kk,
"value": v,
}).Debug("flattening env vars")
}
switch vt := v.(type) {
case string:
envVars[ek] = vt
case []interface{}:
var vArr []string
for _, iv := range vt {
vArr = append(vArr, iv.(string))
}
envVars[ek] = strings.Join(vArr, " ")
case map[string]interface{}:
c.flattenEnvVars(kk, vt, envVars)
case bool:
envVars[ek] = fmt.Sprintf("%v", vt)
case int, int32, int64:
envVars[ek] = fmt.Sprintf("%v", vt)
}
}
return
}
|
// ValidateYAML verifies the YAML in the stream is valid.
|
func ValidateYAML(r io.Reader) (map[interface{}]interface{}, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
m := map[interface{}]interface{}{}
if err := yaml.Unmarshal(b, &m); err != nil {
return nil, err
}
return m, nil
}
|
// ValidateYAMLString verifies the YAML string valid.
|
func ValidateYAMLString(s string) (map[interface{}]interface{}, error) {
b := &bytes.Buffer{}
b.WriteString(s)
return ValidateYAML(b)
}
|
// Get a service by ID
//
// Librato API docs: https://www.librato.com/docs/api/#retrieve-specific-service
|
func (s *ServicesService) Get(id uint) (*Service, *http.Response, error) {
urlStr := fmt.Sprintf("services/%d", id)
req, err := s.client.NewRequest("GET", urlStr, nil)
if err != nil {
return nil, nil, err
}
service := new(Service)
resp, err := s.client.Do(req, service)
if err != nil {
return nil, resp, err
}
return service, resp, err
}
|
// Create a service
//
// Librato API docs: https://www.librato.com/docs/api/#create-a-service
|
func (s *ServicesService) Create(service *Service) (*Service, *http.Response, error) {
req, err := s.client.NewRequest("POST", "services", service)
if err != nil {
return nil, nil, err
}
sv := new(Service)
resp, err := s.client.Do(req, sv)
if err != nil {
return nil, resp, err
}
return sv, resp, err
}
|
// Update a service.
//
// Librato API docs: https://www.librato.com/docs/api/#update-a-service
|
func (s *ServicesService) Update(serviceID uint, service *Service) (*http.Response, error) {
u := fmt.Sprintf("services/%d", serviceID)
req, err := s.client.NewRequest("PUT", u, service)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
|
// Delete a service
//
// Librato API docs: https://www.librato.com/docs/api/#delete-a-service
|
func (s *ServicesService) Delete(id uint) (*http.Response, error) {
u := fmt.Sprintf("services/%d", id)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
|
// GetDataset returns a zfs dataset object from a string
|
func GetDataset(name string) (*Dataset, error) {
if !DatasetExists(name) {
return nil, fmt.Errorf("Dataset not found")
}
return &Dataset{
Name: name,
}, nil
}
|
End of preview. Expand
in Data Studio
- Downloads last month
- 93