doc
stringlengths 10
26.3k
| code
stringlengths 52
3.87M
|
---|---|
// DatasetExists checks for the existence of a dataset
|
func DatasetExists(name string) bool {
err := exec.Command("zfs", "list", "-t", "filesystem", name).Run()
return err == nil
}
|
// GetProperty returns a property for a dataset
|
func (ds *Dataset) GetProperty(property string) (string, error) {
out, err := exec.Command("zfs", "get", "-H",
"-o", "value",
property, ds.Name).Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
|
// CreateDatasetRecursive recursively creates a dataset
|
func CreateDatasetRecursive(name string, properties map[string]string) (*Dataset, error) {
return createDataset(name, true, properties)
}
|
// CreateDataset creates a dataset
|
func CreateDataset(name string, properties map[string]string) (*Dataset, error) {
return createDataset(name, false, properties)
}
|
// Destroy destroys a dataset
|
func (ds *Dataset) Destroy() error {
if err := exec.Command("zfs", "destroy", "-R", ds.Name).Run(); err != nil {
return err
}
return nil
}
|
// GetSnapshot returns a snapshot from a string
|
func GetSnapshot(name string) (*Snapshot, error) {
if !SnapshotExists(name) {
return nil, fmt.Errorf("Snapshot not found")
}
return &Snapshot{
Name: name,
}, nil
}
|
// SnapshotExists checks for the existence of a dataset
|
func SnapshotExists(Name string) bool {
err := exec.Command("zfs", "list", "-t", "snapshot", Name).Run()
return err == nil
}
|
// Snapshot creates a snapshot
|
func (ds *Dataset) Snapshot(name string) (*Snapshot, error) {
sn := fmt.Sprintf("%v@%v", ds.Name, name)
err := exec.Command("zfs", "snapshot", sn).Run()
if err != nil {
return nil, err
}
return GetSnapshot(sn)
}
|
// Clone clones a snapshot
|
func (sn *Snapshot) Clone(target string) (*Dataset, error) {
err := exec.Command("zfs", "clone", sn.Name, target).Run()
if err != nil {
return nil, err
}
return GetDataset(target)
}
|
// NewPostgreSQLCluster creates Cluster. Drivername can be specified,
// but must point to a PostgreSQL driver.
|
func NewPostgreSQLCluster(drivername string, connStrings []string) (*Cluster, error) {
cleanUpDBs := func(dbs []*sql.DB) {
for _, db := range dbs {
db.Close()
}
}
dedup := make(map[string]struct{})
dbs := make([]*sql.DB, 0, len(connStrings))
if len(connStrings) == 0 {
return nil, ErrZeroDataSource
}
for _, connStr := range connStrings {
if _, ok := dedup[connStr]; ok {
cleanUpDBs(dbs)
return nil, ErrDublicatedDataSource
}
dedup[connStr] = struct{}{}
db, err := sql.Open(drivername, connStr)
if err != nil {
cleanUpDBs(dbs)
return nil, err
}
dbs = append(dbs, db)
}
cluster := &Cluster{
dbs: dbs,
stopCh: make(chan struct{}),
}
// electMaster relies on the fact that the value is Stored,
// so pick the random one
cluster.setMaster(0, dbs[0])
cluster.electMaster()
go cluster.overwatch()
return cluster, nil
}
|
// NOTE: SetConnMaxLifetime implement fot go1.6 only
// SetMaxIdleConns sets the maximum number of connections
// in the idle connection pool for each memeber of a cluster
|
func (c *Cluster) SetMaxIdleConns(n int) {
for _, db := range c.dbs {
db.SetMaxIdleConns(n)
}
}
|
// SetMaxOpenConns sets the maximum number of open connections
// to the database for each memeber of a cluster
|
func (c *Cluster) SetMaxOpenConns(n int) {
for _, db := range c.dbs {
db.SetMaxOpenConns(n)
}
}
|
// Close closes connections per each db contained in Cluster.
// An error fron each Close is collected.
|
func (c *Cluster) Close() error {
close(c.stopCh)
var errors []error
for _, db := range c.dbs {
if err := db.Close(); err != nil {
errors = append(errors, err)
}
}
if len(errors) != 0 {
return fmt.Errorf("%v", errors)
}
return nil
}
|
// DB returns *sql.DB suggested to be a master in the cluster.
// Current implementation checks master every 5 seconds.
// However the proper approach is to reelect a master after disconnection error.
|
func (c *Cluster) DB(role Role) *sql.DB {
switch role {
case MASTER:
// It is always set. Even if there's no master at all.
return c.currentMaster.Load().(*sql.DB)
case SLAVE:
// TODO: NOT IMPLEMENTED
// It is always set. Even if there's no master at all.
return c.currentMaster.Load().(*sql.DB)
default:
panic("invalid Role requested")
}
}
|
// Create an Annotation
//
// Librato API docs: https://www.librato.com/docs/api/?shell#create-an-Annotation
|
func (a *AnnotationsService) Create(annotation *Annotation) (*Annotation, *http.Response, error) {
u := fmt.Sprintf("annotations/%s", *annotation.Name)
req, err := a.client.NewRequest("POST", u, annotation)
if err != nil {
return nil, nil, err
}
an := new(Annotation)
resp, err := a.client.Do(req, an)
if err != nil {
return nil, resp, err
}
return an, resp, err
}
|
// SetConnMaxLifetime sets the maximum amount of time
// a connection may be reused for each memeber of a cluster
|
func (c *Cluster) SetConnMaxLifetime(d time.Duration) {
for _, db := range c.dbs {
db.SetConnMaxLifetime(d)
}
}
|
// Note this is exactly what autoload.go does
|
func main() {
pwd, _ := os.Getwd()
env.ReadEnv(path.Join(pwd, ".env"))
for _, v := range os.Environ() {
fmt.Println(v)
}
}
|
// GetDomains retrieves all the domains for a given account.
|
func (c *Client) GetDomains() ([]Domain, error) {
req, err := c.NewRequest(nil, "GET", "/domains")
if err != nil {
return nil, err
}
resp, err := c.Http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
domainResponses := []DomainResponse{}
err = decode(resp.Body, &domainResponses)
if err != nil {
return nil, err
}
domains := make([]Domain, len(domainResponses))
for i, dr := range domainResponses {
domains[i] = dr.Domain
}
return domains, nil
}
|
// MarkdownToText parses the markdown using the Blackfriday Markdown Processor
// and an internal renderer to return any metadata and the formatted text. If
// opt is nil the defaults will be used.
//
// See MarkdownMetadata for a description of the [][]string metadata returned.
|
func MarkdownToText(markdown []byte, opt *Options) ([][]string, []byte) {
metadata, position := MarkdownMetadata(markdown)
return metadata, MarkdownToTextNoMetadata(markdown[position:], opt)
}
|
// MarkdownMetadata parses just the metadata from the markdown and returns the
// metadata and the position of the rest of the markdown.
//
// The metadata is a [][]string where each []string will have two elements, the
// metadata item name and the value. Metadata is an extension of standard
// Markdown and is documented at
// https://github.com/fletcher/MultiMarkdown/wiki/MultiMarkdown-Syntax-Guide#metadata
// -- this implementation currently differs in that it does not support
// multiline values.
//
// In addition, the rest of markdown is scanned for lines containing only
// "///".
//
// If there is one "///" line, the text above that mark is considered the
// "Summary" metadata item; the summary will also be treated as part of the
// content (with the "///" line omitted). This is known as a "soft break".
//
// If there are two "///" lines, one right after the other, the summary will
// only be contained in the "Summary" metadata item and not part of the main
// content. This is known as a "hard break".
|
func MarkdownMetadata(markdown []byte) ([][]string, int) {
var metadata [][]string
pos := 0
for _, line := range bytes.Split(markdown, []byte("\n")) {
sline := strings.Trim(string(line), " ")
if sline == "" {
break
}
colon := strings.Index(sline, ": ")
if colon == -1 {
// Since there's no blank line separating the metadata and content,
// we assume there wasn't actually any metadata.
metadata = make([][]string, 0)
pos = 0
break
}
name := strings.Trim(sline[:colon], " ")
value := strings.Trim(sline[colon+1:], " ")
metadata = append(metadata, []string{name, value})
pos += len(line) + 1
}
if pos > len(markdown) {
pos = len(markdown) - 1
}
pos2 := bytes.Index(markdown[pos:], []byte("\n///\n"))
if pos2 != -1 {
value := string(markdown[pos : pos+pos2])
metadata = append(metadata, []string{"Summary", value})
if string(markdown[pos+pos2+5:pos+pos2+9]) == "///\n" {
pos += pos2 + 9
}
}
return metadata, pos
}
|
// MarkdownToTextNoMetadata is the same as MarkdownToText only skipping the
// detection and parsing of any leading metadata. If opts is nil the defaults
// will be used.
|
func MarkdownToTextNoMetadata(markdown []byte, opts *Options) []byte {
opts = resolveOpts(opts)
rend := &renderer{
width: opts.Width,
color: opts.Color,
tableAlignOptions: opts.TableAlignOptions,
headerPrefix: opts.HeaderPrefix,
headerSuffix: opts.HeaderSuffix,
}
markdown = bytes.Replace(markdown, []byte("\n///\n"), []byte(""), -1)
txt := blackfriday.Markdown(markdown, rend,
blackfriday.EXTENSION_NO_INTRA_EMPHASIS|
blackfriday.EXTENSION_TABLES|
blackfriday.EXTENSION_FENCED_CODE|
blackfriday.EXTENSION_AUTOLINK|
blackfriday.EXTENSION_STRIKETHROUGH|
blackfriday.EXTENSION_DEFINITION_LISTS)
for rend.level > 0 {
txt = append(txt, markIndentStop)
rend.level--
}
if len(txt) > 0 {
txt = bytes.Replace(txt, []byte(" \n"), []byte(" "), -1)
txt = bytes.Replace(txt, []byte("\n"), []byte(" "), -1)
txt = reflow(txt, opts.Indent1, opts.Indent2, rend.width)
txt = bytes.Replace(txt, []byte{markNBSP}, []byte(" "), -1)
txt = bytes.Replace(txt, []byte{markLineBreak}, []byte("\n"), -1)
}
return txt
}
|
// ConvertToConditionalUpdates converts a bundle containing POST requests to a bundle with PUT requests using
// conditional updates. For patient resources, the update is based on the Medical Record Number. For all other
// resources it is based on reasonable indicators of sameness (such as equal dates and codes).
|
func ConvertToConditionalUpdates(bundle *models.Bundle) error {
for _, entry := range bundle.Entry {
values := url.Values{}
switch t := entry.Resource.(type) {
case *models.AllergyIntolerance:
if check(t.Patient, t.Substance, t.Onset) {
addRefParam(values, "patient", t.Patient)
addCCParam(values, "substance", t.Substance)
addDateParam(values, "onset", t.Onset)
}
case *models.Condition:
if check(t.Patient, t.Code, t.OnsetDateTime) {
addRefParam(values, "patient", t.Patient)
addCCParam(values, "code", t.Code)
addDateParam(values, "onset", t.OnsetDateTime)
}
case *models.DiagnosticReport:
// TODO: Consider if this query is precise enough, consider searching on results too
if check(t.Subject, t.Code, t.EffectivePeriod) {
addRefParam(values, "patient", t.Subject)
addCCParam(values, "code", t.Code)
addPeriodParam(values, "date", t.EffectivePeriod)
}
case *models.Encounter:
if check(t.Patient, t.Type, t.Period) {
addRefParam(values, "patient", t.Patient)
for _, cc := range t.Type {
addCCParam(values, "type", &cc)
}
// TODO: the date param references "a date within the period the encounter lasted." Is this OK?
addPeriodParam(values, "date", t.Period)
}
case *models.Immunization:
if check(t.Patient, t.VaccineCode, t.Date) {
addRefParam(values, "patient", t.Patient)
addCCParam(values, "vaccine-code", t.VaccineCode)
addDateParam(values, "date", t.Date)
}
case *models.MedicationStatement:
if check(t.Patient, t.MedicationCodeableConcept, t.EffectivePeriod) {
addRefParam(values, "patient", t.Patient)
addCCParam(values, "code", t.MedicationCodeableConcept)
addPeriodParam(values, "effectivedate", t.EffectivePeriod)
}
case *models.Observation:
if check(t.Subject, t.Code, t.EffectivePeriod) {
addRefParam(values, "patient", t.Subject)
addCCParam(values, "code", t.Code)
addPeriodParam(values, "date", t.EffectivePeriod)
if check(t.ValueCodeableConcept) {
addCCParam(values, "value-concept", t.ValueCodeableConcept)
} else if check(t.ValueQuantity) {
q := t.ValueQuantity
if q.Code != "" {
values.Add("value-quantity", fmt.Sprintf("%g|%s|%s", *q.Value, q.System, q.Code))
} else {
values.Add("value-quantity", fmt.Sprintf("%g|%s|%s", *q.Value, q.System, q.Unit))
}
} else if check(t.ValueString) {
values.Add("value-string", t.ValueString)
}
}
case *models.Procedure:
if check(t.Subject, t.Code, t.PerformedPeriod) {
addRefParam(values, "patient", t.Subject)
addCCParam(values, "code", t.Code)
addPeriodParam(values, "date", t.PerformedPeriod)
}
case *models.ProcedureRequest:
// We can't do anything meaningful because ProcedureRequest does not have search params
// for code or orderedOn. We simply can't get precise enough for a conditional update.
case *models.Patient:
if len(t.Identifier) > 0 && t.Identifier[0].Value != "" {
values.Set("identifier", t.Identifier[0].Value)
}
}
if entry.Request.Method == "POST" && len(values) > 0 {
entry.Request.Method = "PUT"
entry.Request.Url += "?" + values.Encode()
}
}
return nil
}
|
// Parses and compiles the contents of a supplied directory path, with options.
// Returns a map of a template identifier (key) to a Go Template instance.
// Ex: if the dirname="templates/" had a file "index.jade" the key would be "index"
// If option for recursive is True, this parses every file of relevant extension
// in all subdirectories. The key then is the path e.g: "layouts/layout"
|
func CompileDir(dirname string, dopt DirOptions, opt Options) (map[string]*template.Template, error) {
dir, err := os.Open(dirname)
if err != nil {
return nil, err
}
defer dir.Close()
files, err := dir.Readdir(0)
if err != nil {
return nil, err
}
compiled := make(map[string]*template.Template)
for _, file := range files {
// filename is for example "index.jade"
filename := file.Name()
fileext := filepath.Ext(filename)
// If recursive is true and there's a subdirectory, recurse
if dopt.Recursive && file.IsDir() {
dirpath := filepath.Join(dirname, filename)
subcompiled, err := CompileDir(dirpath, dopt, opt)
if err != nil {
return nil, err
}
// Copy templates from subdirectory into parent template mapping
for k, v := range subcompiled {
// Concat with parent directory name for unique paths
key := filepath.Join(filename, k)
compiled[key] = v
}
} else if fileext == dopt.Ext {
// Otherwise compile the file and add to mapping
fullpath := filepath.Join(dirname, filename)
tmpl, err := CompileFile(fullpath, opt)
if err != nil {
return nil, err
}
// Strip extension
key := filename[0 : len(filename)-len(fileext)]
compiled[key] = tmpl
}
}
return compiled, nil
}
|
// Parse given raw jade template string.
|
func (c *Compiler) Parse(input string) (err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New(r.(string))
}
}()
parser, err := parser.StringParser(input)
parser.FileName(c.filename)
if err != nil {
return
}
c.node = parser.Parse()
return
}
|
// Parse the jade template file in given path
|
func (c *Compiler) ParseFile(filename string) (err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New(r.(string))
}
}()
parser, err := parser.FileParser(filename)
if err != nil {
return
}
c.node = parser.Parse()
c.filename = filename
return
}
|
// NewClient returns a new Librato API client bound to the public Librato API.
|
func NewClient(email, token string) *Client {
bu, err := url.Parse(defaultBaseURL)
if err != nil {
panic("Default Librato API base URL couldn't be parsed")
}
return NewClientWithBaseURL(bu, email, token)
}
|
// NewClientWithBaseURL returned a new Librato API client with a custom base URL.
|
func NewClientWithBaseURL(baseURL *url.URL, email, token string) *Client {
headers := map[string]string{
"Content-Type": defaultMediaType,
"Accept": defaultMediaType,
}
c := &Client{
client: http.DefaultClient,
Headers: headers,
Email: email,
Token: token,
BaseURL: baseURL,
UserAgent: userAgent,
}
c.Spaces = &SpacesService{client: c}
c.Metrics = &MetricsService{client: c}
c.Alerts = &AlertsService{client: c}
c.Services = &ServicesService{client: c}
c.Annotations = &AnnotationsService{client: c}
return c
}
|
// NewRequest creates an API request. A relative URL can be provided in urlStr,
// in which case it is resolved relative to the BaseURL of the Client.
// Relative URLs should always be specified without a preceding slash. If
// specified, the value pointed to by body is JSON encoded and included as the
// request body. If specified, the map provided by headers will be used to
// update request headers.
|
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
rel, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
u := c.BaseURL.ResolveReference(rel)
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
encodeErr := json.NewEncoder(buf).Encode(body)
if encodeErr != nil {
return nil, encodeErr
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
req.SetBasicAuth(c.Email, c.Token)
if c.UserAgent != "" {
req.Header.Set("User-Agent", c.UserAgent)
}
for k, v := range c.Headers {
req.Header.Set(k, v)
}
return req, nil
}
|
// RenderErrorFromArray returns a string with the parameter errors
|
func RenderErrorFromArray(errors []interface{}) string {
buf := new(bytes.Buffer)
for _, err := range errors {
fmt.Fprintf(buf, " %s,", err.(string))
}
return buf.String()
}
|
// RenderErrorFromMap returns a string with the parameter errors
// (e.g. from Conditions)
|
func RenderErrorFromMap(errors map[string]interface{}) string {
buf := new(bytes.Buffer)
for cond, condErrs := range errors {
fmt.Fprintf(buf, " %s:", cond)
for _, err := range condErrs.([]interface{}) {
fmt.Fprintf(buf, " %s,", err.(string))
}
}
return buf.String()
}
|
// Float is a helper routine that allocates a new float64 value
// to store v and returns a pointer to it.
|
func Float(v float64) *float64 {
p := new(float64)
*p = v
return p
}
|
// Get an alert by ID
//
// Librato API docs: https://www.librato.com/docs/api/#retrieve-alert-by-id
|
func (a *AlertsService) Get(id uint) (*Alert, *http.Response, error) {
urlStr := fmt.Sprintf("alerts/%d", id)
req, err := a.client.NewRequest("GET", urlStr, nil)
if err != nil {
return nil, nil, err
}
alert := new(Alert)
resp, err := a.client.Do(req, alert)
if err != nil {
return nil, resp, err
}
return alert, resp, err
}
|
// Create an alert
//
// Librato API docs: https://www.librato.com/docs/api/?shell#create-an-alert
|
func (a *AlertsService) Create(alert *Alert) (*Alert, *http.Response, error) {
req, err := a.client.NewRequest("POST", "alerts", alert)
if err != nil {
return nil, nil, err
}
al := new(Alert)
resp, err := a.client.Do(req, al)
if err != nil {
return nil, resp, err
}
return al, resp, err
}
|
// Update an alert.
//
// Librato API docs: https://www.librato.com/docs/api/?shell#update-alert
|
func (a *AlertsService) Update(alertID uint, alert *Alert) (*http.Response, error) {
u := fmt.Sprintf("alerts/%d", alertID)
req, err := a.client.NewRequest("PUT", u, alert)
if err != nil {
return nil, err
}
return a.client.Do(req, nil)
}
|
// Delete an alert
//
// Librato API docs: https://www.librato.com/docs/api/?shell#delete-alert
|
func (a *AlertsService) Delete(id uint) (*http.Response, error) {
u := fmt.Sprintf("alerts/%d", id)
req, err := a.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return a.client.Do(req, nil)
}
|
// CreateFilesystem runs zfs create
|
func CreateFilesystem(name string, opts *CreateFilesystemOpts) error {
cmd := newCmd("create")
if opts != nil {
cmd = addOpt(cmd, opts.DontMount, "-u")
cmd = addOpt(cmd, opts.CreateParents, "-p")
cmd = addProperties(cmd, opts.SetProperties)
}
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
}
|
// CreateVolue runs zfs create -V
|
func CreateVolue(name, size string, opts *CreateVolumeOpts) error {
cmd := newCmd("create")
cmd = addOpt(cmd, true, "-V", size)
if opts != nil {
cmd = addProperties(cmd, opts.SetProperties)
cmd = addOpt(cmd, opts.BlockSize != "", "-b", opts.BlockSize)
cmd = addOpt(cmd, opts.Sparse, "-s")
}
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
}
|
// Destroy runs zfs destroy
|
func Destroy(name string, opts *DestroyOpts) error {
cmd := newCmd("destroy")
if opts != nil {
cmd = addOpt(cmd, opts.DestroyChildren, "-r")
cmd = addOpt(cmd, opts.DestroyClones, "-R")
cmd = addOpt(cmd, opts.ForceUnmount, "-f")
cmd = addOpt(cmd, opts.Defer, "-d")
}
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
}
|
// Snapshot runs zfs snapshot
|
func Snapshot(name string, opts *SnapshotOpts) error {
cmd := newCmd("snapshot")
if opts != nil {
cmd = addOpt(cmd, opts.Recurse, "-r")
cmd = addProperties(cmd, opts.SetProperties)
}
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
}
|
// Rollback runs zfs rollback
|
func Rollback(name string, opts *RollbackOpts) error {
cmd := newCmd("rollback")
if opts != nil {
cmd = addOpt(cmd, opts.DestroyLaterSnapshots, "-r")
cmd = addOpt(cmd, opts.DestroyClones, "-R")
cmd = addOpt(cmd, opts.ForceUnmount, "-f")
}
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
}
|
// Clone runs zfs clone
|
func Clone(snapshot, name string, opts *CloneOpts) error {
cmd := newCmd("clone")
if opts != nil {
cmd = addOpt(cmd, opts.CreateParents, "-p")
cmd = addProperties(cmd, opts.SetProperties)
}
cmd = addNonEmpty(cmd, snapshot, name)
return zExecNoOut(cmd)
}
|
// Rename runs zfs rename
|
func Rename(name, newName string, opts *RenameOpts) error {
cmd := newCmd("rename")
if opts != nil {
cmd = addOpt(cmd, opts.CreateParents, "-p")
cmd = addOpt(cmd, opts.DontReMount, "-u")
cmd = addOpt(cmd, opts.ForceUnmount, "-f")
cmd = addOpt(cmd, opts.Recurse, "-r")
}
cmd = addNonEmpty(cmd, name, newName)
return zExecNoOut(cmd)
}
|
// List runs zfs list
// Returns a map indexed by dataset name, which holds maps of the requested properties
|
func List(name string, opts *ListOpts) ([]string, error) {
cmd := newCmd("list", "-Hp")
if opts == nil {
opts = &ListOpts{}
}
cmd = addOpt(cmd, opts.Recurse, "-r")
cmd = addOpt(cmd, opts.Depth != -1, "-d", fmt.Sprintf("%d", opts.Depth))
cmd = addCommaSeparatedOption(cmd, "-o", []string{"name"})
cmd = addCommaSeparatedOption(cmd, "-t", opts.Types)
out, err := zExec(cmd)
if err != nil {
return nil, err
}
return strings.Split(string(out), "\n"), nil
}
|
// Set runs zfs set
|
func Set(name string, properties map[string]string) error {
cmd := newCmd("set")
cmd = addSetProperties(cmd, properties)
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
}
|
// Get runs zfs get
// Returns a map indexed by dataset, each of which holds a map indexed by the requested property
|
func Get(name string, properties []string, opts *GetOpts) (map[string]map[string]*Property, error) {
cmd := newCmd("get", "-Hp")
if opts == nil {
opts = &GetOpts{}
}
if len(properties) == 0 {
properties = []string{"name"}
}
cmd = addOpt(cmd, opts.Recurse, "-r")
cmd = addOpt(cmd, opts.Depth != -1, "-d", fmt.Sprintf("%d", opts.Depth))
cmd = addCommaSeparatedOption(cmd, "-t", opts.Types)
cmd = addCommaSeparatedOption(cmd, "-s", opts.Sources)
cmd = addCommaSeparated(cmd, properties)
cmd = addNonEmpty(cmd, name)
out, err := zExec(cmd)
if err != nil {
return nil, err
}
ret := make(map[string]map[string]*Property)
for _, l := range bytes.Split(out, []byte("\n")) {
d := strings.Split(string(l), "\t")
if len(d) < 4 {
continue
}
if _, ok := ret[d[0]]; !ok {
ret[d[0]] = make(map[string]*Property)
}
ret[d[0]][d[1]] = &Property{Value: d[2], Source: d[3]}
}
return ret, nil
}
|
// Inherit runs zfs inherit
|
func Inherit(name string, property string, opts *InheritOpts) error {
cmd := newCmd("inherit")
if opts != nil {
cmd = addOpt(cmd, opts.Recurse, "-r")
cmd = addOpt(cmd, opts.Received, "-S")
}
cmd = addNonEmpty(cmd, property, name)
return zExecNoOut(cmd)
}
|
// GetMounts runs zfs mount with no arguments
|
func GetMounts() ([]*MountEntry, error) {
cmd := newCmd("mount")
out, err := zExec(cmd)
if err != nil {
return nil, err
}
ret := []*MountEntry{}
for _, l := range strings.Split(string(out), "\n") {
d := strings.SplitN(l, " ", 2)
ret = append(ret, &MountEntry{
Name: strings.Trim(d[0], " "),
Mountpoint: strings.Trim(d[1], " "),
})
}
return ret, nil
}
|
// Mount runs zfs mount
|
func Mount(name string, opts *MountOpts) error {
cmd := newCmd("mount")
if opts != nil {
cmd = addCommaSeparatedOption(cmd, "-o", opts.Properties)
cmd = addOpt(cmd, opts.MountAll, "-a")
}
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
}
|
// UnMount runs zfs unmount
|
func UnMount(name string, opts *UnMountOpts) error {
cmd := newCmd("unmount")
if opts != nil {
cmd = addOpt(cmd, opts.ForceUnmount, "-f")
cmd = addOpt(cmd, opts.UnMountAll, "-a")
}
cmd = addNonEmpty(cmd, name)
return zExecNoOut(cmd)
}
|
// Bookmark runs zfs bookmark
|
func Bookmark(snapshot, bookmark string) error {
cmd := newCmd("bookmark", snapshot, bookmark)
return zExecNoOut(cmd)
}
|
// GetWith will call .New(...); .Show() and returns .Get()
|
func GetWith(name string, options []string) string {
l := New(name, options)
l.Show()
return l.Get()
}
|
// New returns a list initialized with Default theme.
|
func New(name string, options []string) *List {
list := &List{}
list.name = name
list.options = options
list.Index = 0
list.Cursor = &curse.Cursor{}
list.SetColors(DefaultColors)
list.SetPrint(fmt.Print)
list.SetChooser(" ❯ ")
list.SetIndent(3)
return list
}
|
// SetIndent sets indent before options
|
func (list *List) SetIndent(indent int) {
list.indent = "" + strings.Repeat(" ", indent)
}
|
// PrintHighlight prints highlighted list element
|
func (list *List) PrintHighlight(element string) int {
newIndent := len(list.indent) - 3
indent := ""
if newIndent > 1 {
indent = strings.Repeat(" ", newIndent)
}
list.colors.Highlight.Set()
bytes, _ := list.Print(indent + list.chooser + element)
color.Unset()
return bytes
}
|
// PrintOption prints list option
|
func (list *List) PrintOption(option string) int {
list.colors.Option.Set()
bytes, _ := list.Print(list.indent + option)
color.Unset()
return bytes
}
|
// PrintHead prints list header
|
func (list *List) PrintHead() int {
list.colors.Head.Set()
bytes, _ := list.Print(list.name)
color.Unset()
return bytes
}
|
// PrintResult prints list header and choosen option
|
func (list *List) PrintResult(result string) int {
var bytes int
bytes = list.PrintHead()
list.colors.Highlight.Set()
printBytes, _ := list.Print(" ", result)
color.Unset()
return bytes + printBytes + list.Println()
}
|
// ShowOptions shows options
|
func (list *List) ShowOptions() int {
result := 0
for Index, element := range list.options {
if Index == 0 {
result += list.PrintHighlight(element) + list.Println()
continue
}
result += list.PrintOption(element) + list.Println()
}
list.Index = 1
list.Cursor.MoveUp(len(list.options))
return result
}
|
// ClearOptions clears options from console
|
func (list *List) ClearOptions() {
length := len(list.options)
diff := length - list.Index
// Move to the last line.
if diff != 0 {
list.Cursor.MoveDown(diff)
}
list.Index = length
// Erase options
for list.Index != 0 {
list.Index--
list.Cursor.EraseCurrentLine()
list.Cursor.MoveUp(1)
}
}
|
// Enter key handler
|
func (list *List) Enter() string {
result := list.options[list.Index-1]
list.ClearOptions()
list.PrintResult(result)
list.Print(ShowCursor)
return result
}
|
// Exit Ctrl + (C | D | Z) and alike handler
|
func (list *List) Exit() {
// Should go down to the last option
for list.Index != len(list.options) {
list.Index++
list.Cursor.MoveDown(1)
}
list.Println()
list.Println()
list.Print(ShowCursor)
os.Exit(1)
}
|
// HighlightUp highlights option above
|
func (list *List) HighlightUp() *List {
// If there is no where to go
if 0 >= list.Index-1 {
return list
}
list.Cursor.EraseCurrentLine()
list.PrintOption(list.options[list.Index-1])
list.Cursor.MoveUp(1)
list.Cursor.EraseCurrentLine()
list.Index--
list.PrintHighlight(list.options[list.Index-1])
return list
}
|
// HighlightDown highlights option below
|
func (list *List) HighlightDown() *List {
// If there is no where to go
if len(list.options) < list.Index+1 {
return list
}
list.Cursor.EraseCurrentLine()
list.PrintOption(list.options[list.Index-1])
list.Cursor.MoveDown(1)
list.Cursor.EraseCurrentLine()
list.PrintHighlight(list.options[list.Index])
list.Index++
return list
}
|
// convertClinicalStatus maps the clinical status to a code in the "preferred" FHIR value set:
// http://hl7.org/fhir/DSTU2/valueset-condition-clinical.html
// If the status cannot be reliably mapped, an empty code will be returned.
|
func (c *Condition) convertClinicalStatus() string {
var status string
statusConcept := c.StatusCode.FHIRCodeableConcept("")
switch {
case statusConcept.MatchesCode("http://snomed.info/sct", "55561003"):
status = "active"
case statusConcept.MatchesCode("http://snomed.info/sct", "73425007"):
status = "remission"
case statusConcept.MatchesCode("http://snomed.info/sct", "413322009"):
status = "resolved"
case statusConcept.MatchesCode("http://hl7.org/fhir/ValueSet/v3-ActStatus", "active"):
status = "active"
}
// In order to remain consistent, fix the status if there is an end date (abatement)
// and it doesn't match the start date (in which case we can't be sure it's really an end)
if status == "" && c.EndTime != nil && c.StartTime != nil && *c.EndTime != *c.StartTime {
status = "resolved"
}
return status
}
|
// convertSeverity maps the severity to a CodeableConcept. If possible, it will add a display name.
// FHIR has a "preferred" value set for severity:
// http://hl7.org/fhir/DSTU2/valueset-condition-severity.html
// Note that this is a subset of the value set that is often used:
// https://phinvads.cdc.gov/vads/ViewValueSet.action?id=72FDBFB5-A277-DE11-9B52-0015173D1785
// Rather than make a subjective mapping decision, we keep the codes as-is, which is likely
// more in line with the larger value set (containing "mild to moderate" and "moderate to severe")
|
func (c *Condition) convertSeverity() *fhir.CodeableConcept {
if len(c.Severity) == 0 {
return nil
}
severity := c.Severity.FHIRCodeableConcept("")
switch {
case severity.MatchesCode("http://snomed.info/sct", "399166001"):
severity.Text = "Fatal"
case severity.MatchesCode("http://snomed.info/sct", "255604002"):
severity.Text = "Mild"
case severity.MatchesCode("http://snomed.info/sct", "371923003"):
severity.Text = "Mild to moderate"
case severity.MatchesCode("http://snomed.info/sct", "6736007"):
severity.Text = "Moderate"
case severity.MatchesCode("http://snomed.info/sct", "371924009"):
severity.Text = "Moderate to severe"
case severity.MatchesCode("http://snomed.info/sct", "24484000"):
severity.Text = "Severe"
}
return severity
}
|
// NewDataClient creates a new DataClient for talking to the Read API
|
func NewDataClient(url string, logger *logrus.Logger, options ...Option) DataClient {
return &defaultDataClient{
URL: url,
log: logger,
options: options,
}
}
|
// CreateChart creates a chart in a given Librato Space.
//
// Librato API docs: http://dev.librato.com/v1/post/spaces/:id/charts
|
func (s *SpacesService) CreateChart(spaceID uint, chart *SpaceChart) (*SpaceChart, *http.Response, error) {
u := fmt.Sprintf("spaces/%d/charts", spaceID)
req, err := s.client.NewRequest("POST", u, chart)
if err != nil {
return nil, nil, err
}
c := new(SpaceChart)
resp, err := s.client.Do(req, c)
if err != nil {
return nil, resp, err
}
return c, resp, err
}
|
// ListCharts lists all charts in a given Librato Space.
//
// Librato API docs: http://dev.librato.com/v1/get/spaces/:id/charts
|
func (s *SpacesService) ListCharts(spaceID uint) ([]SpaceChart, *http.Response, error) {
u := fmt.Sprintf("spaces/%d/charts", spaceID)
req, err := s.client.NewRequest("GET", u, nil)
if err != nil {
return nil, nil, err
}
charts := new([]SpaceChart)
resp, err := s.client.Do(req, charts)
if err != nil {
return nil, resp, err
}
return *charts, resp, err
}
|
// DeleteChart deletes a chart.
//
// Librato API docs: http://dev.librato.com/v1/delete/spaces/:id/charts/:id
|
func (s *SpacesService) DeleteChart(spaceID, chartID uint) (*http.Response, error) {
u := fmt.Sprintf("spaces/%d/charts/%d", spaceID, chartID)
req, err := s.client.NewRequest("DELETE", u, nil)
if err != nil {
return nil, err
}
return s.client.Do(req, nil)
}
|
// NewSinkHandler creates SinkHandler with sink channel buffer size bufSize that wraps inner handler for writing logs.
// When SinkHandler is created a go routine is started. When not used always call Close to terminate go routine.
|
func NewSinkHandler(inner Handler, bufSize int) *SinkHandler {
b := &SinkHandler{
inner: inner,
sinkCh: make(chan *Record, bufSize),
bufSize: bufSize,
}
b.wg.Add(1)
go b.process()
return b
}
|
// process reads log records from sinkCh and calls inner log handler to write it.
|
func (b *SinkHandler) process() {
for {
rec, ok := <-b.sinkCh
if !ok {
b.inner.Close()
break
}
b.inner.Handle(rec)
}
b.wg.Done()
}
|
// Status reports sink capacity and length.
|
func (b *SinkHandler) Status() (int, int) {
return b.bufSize, len(b.sinkCh)
}
|
// Handle puts rec to the sink.
|
func (b *SinkHandler) Handle(rec *Record) {
select {
case b.sinkCh <- rec:
default:
fmt.Fprintf(os.Stderr, "SinkHandler buffer too small dropping record\n")
}
}
|
//OnEvent calls lf with ctx and event.
|
func (lf ListenerFunc) OnEvent(ctx context.Context, event Event) {
lf(ctx, event)
}
|
// NewRequest tries to make a request to the URL, returning the http.Response if it was successful, or an error if there was a problem.
// Optional Option arguments can be passed to specify contextual behaviour for this request. See MaxElapsedTime.
|
func NewRequest(url string, options ...Option) (*http.Response, error) {
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
request.Header.Add("Accept", "application/json")
request.Header.Add("User-Agent", "Performance-Platform-Client/1.0")
requestOptions := RequestOptions{MaxElapsedTime: 5 * time.Second}
requestOptions.option(request, options...)
response, err := tryGet(request, requestOptions)
if err != nil {
return nil, err
}
if response.StatusCode == http.StatusNotFound {
return nil, ErrNotFound
}
if response.StatusCode == http.StatusBadRequest {
return response, ErrBadRequest
}
return response, err
}
|
// MaxElapsedTime specifies the maximum duration that we should use to retry requests to the origin server. The default value is 5 seconds.
|
func MaxElapsedTime(duration time.Duration) Option {
return func(req *http.Request, ro *RequestOptions) Option {
previous := ro.MaxElapsedTime
ro.MaxElapsedTime = duration
return MaxElapsedTime(previous)
}
}
|
// BearerToken sets the Authorization header for a request
|
func BearerToken(bearerToken string) Option {
return func(req *http.Request, ro *RequestOptions) Option {
previous := req.Header.Get("Authorization")
if bearerToken != "" {
req.Header.Add("Authorization", "Bearer "+bearerToken)
} else {
req.Header.Del("Authorization")
}
return BearerToken(previous)
}
}
|
// ReadResponseBody reads the response body stream and returns a byte array, or an error if there was a problem.
|
func ReadResponseBody(response *http.Response) ([]byte, error) {
defer response.Body.Close()
return ioutil.ReadAll(response.Body)
}
|
// Mark marks the begin/end of a function, and also indents the log output
// accordingly
|
func Mark(format string, args ...interface{}) func() {
if !debug {
return func() {}
}
Trace("START "+format, args...)
old := logger.Prefix()
logger.SetPrefix(old + "| ")
return func() {
logger.SetPrefix(old)
Trace("END "+format, args...)
}
}
|
// RoundTrip parses incoming GET "HTTP" request and transforms it into
// commands to ftp client
|
func (rt *FTPRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
if request.URL.Scheme != "ftp" {
return nil, fmt.Errorf("only ftp protocol is supported, got %s", request.Proto)
}
if request.Method != "GET" {
return nil, fmt.Errorf("only GET method is supported, got %s", request.Method)
}
hostport := request.URL.Host
if strings.Index(hostport, ":") == -1 {
hostport = hostport + ":21"
}
connection, err := rt.getConnection(hostport)
if err != nil {
return nil, err
}
var body io.ReadCloser
body, err = connection.Retr(request.URL.Path)
if err != nil {
if te, ok := err.(*textproto.Error); ok {
rt.putConnection(hostport, connection)
if te.Code == ftp.StatusFileUnavailable {
return &http.Response{
Status: "404 Not Found",
StatusCode: 404,
Proto: "FTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
Request: request,
}, nil
}
}
return nil, err
}
return &http.Response{
Status: "200 OK",
StatusCode: 200,
Proto: "FTP/1.0",
ProtoMajor: 1,
ProtoMinor: 0,
Body: &readCloserWrapper{
body: body,
rt: rt,
hostport: hostport,
conn: connection,
},
ContentLength: -1,
Request: request,
}, nil
}
|
// LexRun starts lexing using Lexer l, and a context Lexer ctx. "Context" in
// this case can be thought as the concret lexer, and l is the parent class.
// This is a utility function to be called from concrete Lexer types
|
func LexRun(l Lexer) {
for fn := l.GetEntryPoint(); fn != nil; {
fn = fn(l)
}
close(l.Items())
}
|
// This method moves the cursor 1 rune if the rune is contained in the given
// string. This is a utility function to be called from concrete Lexer types
|
func AcceptAny(l Lexer, valid string) bool {
if strings.IndexRune(valid, l.Next()) >= 0 {
return true
}
l.Backup()
return false
}
|
// AcceptRun takes a string, and moves the cursor forward as long as
// the input matches one of the given runes in the string
// This is a utility function to be called from concrete Lexer types
|
func AcceptRun(l Lexer, valid string) bool {
guard := Mark("lex.AcceptRun %q", valid)
defer guard()
return AcceptRunFunc(l, func(r rune) bool {
return strings.IndexRune(valid, r) >= 0
})
}
|
// AcceptString returns true if the given string can be matched exactly.
// This is a utility function to be called from concrete Lexer types
|
func AcceptString(l Lexer, word string, rewind bool) (ok bool) {
i := 0
defer func() {
if rewind {
Trace("Rewinding AccepString(%q) (%d runes)\n", word, i)
for j := i; j > 0; j-- {
l.Backup()
}
}
Trace("AcceptString returning %s\n", ok)
}()
for pos := 0; pos < len(word); {
r, width := utf8.DecodeRuneInString(word[pos:])
pos += width
var n rune
if pos == 0 {
n = l.Current()
} else {
n = l.Next()
}
i++
Trace("r (%q) == n (%q) %s ? \n", r, n, r == n)
if r != n {
rewind = true
ok = false
return
}
}
ok = true
return
}
|
// NewMetaClient returns a new MetaClient implementation with sensible defaults.
|
func NewMetaClient(baseURL string, log *logrus.Logger) MetaClient {
return &defaultMetaClient{baseURL, log}
}
|
//Handle calls hf with ctx and command.
|
func (hf HandlerFunc) Handle(ctx context.Context, command Command) (result interface{}, err error) {
return hf(ctx, command)
}
|
//Handle associates a Handler in b that will be called when a Command whose type
//equals command's type.
//Only one Handler is allowed per Command type. Any previously added Handlers
//with the same commandType will be overwritten.
//prev is the Handler previously associated with commandType if it exists.
|
func (b *Bus) Handle(command Command, handler Handler) (prev Handler) {
b.lock.Lock()
defer b.lock.Unlock()
return b.putHandler(reflect.TypeOf(command), handler)
}
|
//Listen registers lis to be called for all Commands at the time in the
//Command lifecycle denoted by et.
//A value for et that is not documented in this package will never be called.
|
func (b *Bus) Listen(et EventType, lis Listener) {
b.lock.Lock()
defer b.lock.Unlock()
b.appendListener(et, nil, lis)
}
|
//ListenCommand registers lis to be called for Commands of the same type as command
//at the time in the Command lifecycle denoted by et.
//A value for et that is not documented in this package will never be called.
|
func (b *Bus) ListenCommand(et EventType, command Command, lis Listener) {
b.lock.Lock()
defer b.lock.Unlock()
b.appendListener(et, command, lis)
}
|
//RemoveHandler removes the Handler associated with Command's type and returns it.
//This is a no-op and returns nil if a Handler does not exist for command.
|
func (b *Bus) RemoveHandler(command Command) Handler {
b.lock.Lock()
defer b.lock.Unlock()
commandType := reflect.TypeOf(command)
handler := b.handlers[commandType]
delete(b.handlers, commandType)
return handler
}
|
//RemoveListener removes all Listeners that match lis (via ==) and et.
//The return value indicates if any Listeners were removed.
|
func (b *Bus) RemoveListener(et EventType, lis Listener) bool {
b.lock.Lock()
defer b.lock.Unlock()
removed := b.removeListeners(
et,
func(_ Command, _lis Listener) bool {
return _lis == lis
},
)
return len(removed) > 0
}
|
//RemoveListenerCommand remove all Listeners that were registered with Command type
//equal to command's and et.
//It returns all removed Listeners.
|
func (b *Bus) RemoveListenerCommand(et EventType, command Command) []Listener {
b.lock.Lock()
defer b.lock.Unlock()
return b.removeListeners(
et,
func(_command Command, _ Listener) bool {
return reflect.TypeOf(_command) == reflect.TypeOf(command)
},
)
}
|
//Execute is sugar for b.ExecuteContext(context.Background(), command).
|
func (b *Bus) Execute(command Command) (result interface{}, err error) {
return b.ExecuteContext(context.Background(), command)
}
|
//ExecuteContext attempts to find a Handler for command's Type().
//If a Handler is not found, then ErrHandlerNotFound is returned immediately.
//If a Handler is found, then a new goroutine is spawned and all registered Before
//Listeners are called, followed by command's Handler, finally followed by all
//registered After* and Complete Listeners.
//
//If ctx.Done() is closed before the event Listeners and command Handler complete,
//then ctx.Err() is returned with a nil result.
|
func (b *Bus) ExecuteContext(ctx context.Context, command Command) (result interface{}, err error) {
b.lock.RLock()
defer b.lock.RUnlock()
handler, ok := b.handlers[reflect.TypeOf(command)]
if !ok {
return nil, &HandlerNotFoundError{command}
}
return b.execute(ctx, command, handler)
}
|
// Calculate the pagination metadata for the next page of the result set.
// Takes the metadata used to request the current page so that it can use the
// same sort/orderby options
|
func (p *PaginationResponseMeta) nextPage(originalQuery *PaginationMeta) (next *PaginationMeta) {
nextOffset := p.Offset + p.Length
if nextOffset >= p.Found {
return nil
}
next = &PaginationMeta{}
next.Offset = nextOffset
next.Length = p.Length
if originalQuery != nil {
next.OrderBy = originalQuery.OrderBy
next.Sort = originalQuery.Sort
}
return next
}
|
// EncodeValues is implemented to allow other strucs to embed PaginationMeta and
// still use github.com/google/go-querystring/query to encode the struct. It
// makes PaginationMeta implement query.Encoder.
|
func (m *PaginationMeta) EncodeValues(name string, values *url.Values) error {
if m == nil {
return nil
}
if m.Offset != 0 {
values.Set("offset", fmt.Sprintf("%d", m.Offset))
}
if m.Length != 0 {
values.Set("length", fmt.Sprintf("%d", m.Length))
}
if m.OrderBy != "" {
values.Set("orderby", m.OrderBy)
}
if m.Sort != "" {
values.Set("sort", m.Sort)
}
return nil
}
|
//
// Client
// NewCachedClient creates a new fantasy client that checks and updates the
// given Cache when retrieving fantasy content.
//
// See NewLRUCache
|
func NewCachedClient(cache Cache, client HTTPClient) *Client {
return &Client{
Provider: &cachedContentProvider{
delegate: NewClient(client).Provider,
cache: cache,
},
}
}
|
// NewClient creates a Client that to communicate with the Yahoo fantasy
// sports API. See the package level documentation for one way to create a
// http.Client that can authenticate with Yahoo's APIs which can be passed
// in here.
|
func NewClient(c HTTPClient) *Client {
return &Client{
Provider: &xmlContentProvider{
client: &countingHTTPApiClient{
client: c,
requestCount: 0,
},
},
}
}
|
// GetConsumer generates an OAuth Consumer for the Yahoo fantasy sports API
|
func GetConsumer(clientID string, clientSecret string) *oauth.Consumer {
return oauth.NewConsumer(
clientID,
clientSecret,
oauth.ServiceProvider{
RequestTokenUrl: YahooRequestTokenURL,
AuthorizeTokenUrl: YahooAuthTokenURL,
AccessTokenUrl: YahooGetTokenURL,
})
}
|
// GetOAuth2Config generates an OAuth 2 configuration for the Yahoo fantasy
// sports API
|
func GetOAuth2Config(clientID string, clientSecret string, redirectURL string) *oauth2.Config {
return &oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Scopes: []string{"fspt-r"},
Endpoint: oauth2.Endpoint{
AuthURL: YahooOauth2AuthURL,
TokenURL: YahooOauth2TokenURL,
},
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.