id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
9,500
luci/luci-go
machine-db/client/cli/physical_hosts.go
printPhysicalHosts
func printPhysicalHosts(tsv bool, hosts ...*crimson.PhysicalHost) { if len(hosts) > 0 { p := newStdoutPrinter(tsv) defer p.Flush() if !tsv { p.Row("Name", "VLAN", "IP Address", "Machine", "NIC", "MAC Address", "OS", "Max VM Slots", "Virtual Datacenter", "Description", "Deployment Ticket", "State") } for _, h := range hosts { p.Row(h.Name, h.Vlan, h.Ipv4, h.Machine, h.Nic, h.MacAddress, h.Os, h.VmSlots, h.VirtualDatacenter, h.Description, h.DeploymentTicket, h.State) } } }
go
func printPhysicalHosts(tsv bool, hosts ...*crimson.PhysicalHost) { if len(hosts) > 0 { p := newStdoutPrinter(tsv) defer p.Flush() if !tsv { p.Row("Name", "VLAN", "IP Address", "Machine", "NIC", "MAC Address", "OS", "Max VM Slots", "Virtual Datacenter", "Description", "Deployment Ticket", "State") } for _, h := range hosts { p.Row(h.Name, h.Vlan, h.Ipv4, h.Machine, h.Nic, h.MacAddress, h.Os, h.VmSlots, h.VirtualDatacenter, h.Description, h.DeploymentTicket, h.State) } } }
[ "func", "printPhysicalHosts", "(", "tsv", "bool", ",", "hosts", "...", "*", "crimson", ".", "PhysicalHost", ")", "{", "if", "len", "(", "hosts", ")", ">", "0", "{", "p", ":=", "newStdoutPrinter", "(", "tsv", ")", "\n", "defer", "p", ".", "Flush", "(", ")", "\n", "if", "!", "tsv", "{", "p", ".", "Row", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "h", ":=", "range", "hosts", "{", "p", ".", "Row", "(", "h", ".", "Name", ",", "h", ".", "Vlan", ",", "h", ".", "Ipv4", ",", "h", ".", "Machine", ",", "h", ".", "Nic", ",", "h", ".", "MacAddress", ",", "h", ".", "Os", ",", "h", ".", "VmSlots", ",", "h", ".", "VirtualDatacenter", ",", "h", ".", "Description", ",", "h", ".", "DeploymentTicket", ",", "h", ".", "State", ")", "\n", "}", "\n", "}", "\n", "}" ]
// printPhysicalHosts prints physical host data to stdout in tab-separated columns.
[ "printPhysicalHosts", "prints", "physical", "host", "data", "to", "stdout", "in", "tab", "-", "separated", "columns", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/physical_hosts.go#L28-L39
9,501
luci/luci-go
machine-db/client/cli/physical_hosts.go
Run
func (c *AddPhysicalHostCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) // TODO(smut): Validate required fields client-side. req := &crimson.CreatePhysicalHostRequest{ Host: &c.host, } client := getClient(ctx) resp, err := client.CreatePhysicalHost(ctx, req) if err != nil { errors.Log(ctx, err) return 1 } printPhysicalHosts(c.f.tsv, resp) return 0 }
go
func (c *AddPhysicalHostCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) // TODO(smut): Validate required fields client-side. req := &crimson.CreatePhysicalHostRequest{ Host: &c.host, } client := getClient(ctx) resp, err := client.CreatePhysicalHost(ctx, req) if err != nil { errors.Log(ctx, err) return 1 } printPhysicalHosts(c.f.tsv, resp) return 0 }
[ "func", "(", "c", "*", "AddPhysicalHostCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "ctx", ":=", "cli", ".", "GetContext", "(", "app", ",", "c", ",", "env", ")", "\n", "// TODO(smut): Validate required fields client-side.", "req", ":=", "&", "crimson", ".", "CreatePhysicalHostRequest", "{", "Host", ":", "&", "c", ".", "host", ",", "}", "\n", "client", ":=", "getClient", "(", "ctx", ")", "\n", "resp", ",", "err", ":=", "client", ".", "CreatePhysicalHost", "(", "ctx", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "errors", ".", "Log", "(", "ctx", ",", "err", ")", "\n", "return", "1", "\n", "}", "\n", "printPhysicalHosts", "(", "c", ".", "f", ".", "tsv", ",", "resp", ")", "\n", "return", "0", "\n", "}" ]
// Run runs the command to add a physical host.
[ "Run", "runs", "the", "command", "to", "add", "a", "physical", "host", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/physical_hosts.go#L48-L62
9,502
luci/luci-go
machine-db/client/cli/physical_hosts.go
editPhysicalHostCmd
func editPhysicalHostCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "edit-host -name <name> [-machine <machine>] [-os <os>] [-state <state>] [-slots <vm slots>] [-vdc <virtual datacenter>] [-desc <description>] [-tick <deployment ticket>]", ShortDesc: "edits a physical host", LongDesc: "Edits a physical host in the database.\n\nExample edit the state of a host:\ncrimson edit-host -name server01-y0 -state test -desc 'testing for labs'", CommandRun: func() subcommands.CommandRun { cmd := &EditPhysicalHostCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.host.Name, "name", "", "The name of this host on the network. Required and must be the name of a host returned by get-hosts.") cmd.Flags.StringVar(&cmd.host.Machine, "machine", "", "The machine backing this host. Must be the name of a machine returned by get-machines.") cmd.Flags.StringVar(&cmd.host.Os, "os", "", "The operating system this host is running. Must be the name of an operating system returned by get-oses.") cmd.Flags.Var(StateFlag(&cmd.host.State), "state", "The state of this host. Must be a state returned by get-states.") cmd.Flags.Var(flag.Int32(&cmd.host.VmSlots), "slots", "The number of VMs which can be deployed on this host.") cmd.Flags.StringVar(&cmd.host.VirtualDatacenter, "vdc", "", "The virtual datacenter VMs deployed on this host will belong to.") cmd.Flags.StringVar(&cmd.host.Description, "desc", "", "A description of this host.") cmd.Flags.StringVar(&cmd.host.DeploymentTicket, "tick", "", "The deployment ticket associated with this host.") return cmd }, } }
go
func editPhysicalHostCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "edit-host -name <name> [-machine <machine>] [-os <os>] [-state <state>] [-slots <vm slots>] [-vdc <virtual datacenter>] [-desc <description>] [-tick <deployment ticket>]", ShortDesc: "edits a physical host", LongDesc: "Edits a physical host in the database.\n\nExample edit the state of a host:\ncrimson edit-host -name server01-y0 -state test -desc 'testing for labs'", CommandRun: func() subcommands.CommandRun { cmd := &EditPhysicalHostCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.host.Name, "name", "", "The name of this host on the network. Required and must be the name of a host returned by get-hosts.") cmd.Flags.StringVar(&cmd.host.Machine, "machine", "", "The machine backing this host. Must be the name of a machine returned by get-machines.") cmd.Flags.StringVar(&cmd.host.Os, "os", "", "The operating system this host is running. Must be the name of an operating system returned by get-oses.") cmd.Flags.Var(StateFlag(&cmd.host.State), "state", "The state of this host. Must be a state returned by get-states.") cmd.Flags.Var(flag.Int32(&cmd.host.VmSlots), "slots", "The number of VMs which can be deployed on this host.") cmd.Flags.StringVar(&cmd.host.VirtualDatacenter, "vdc", "", "The virtual datacenter VMs deployed on this host will belong to.") cmd.Flags.StringVar(&cmd.host.Description, "desc", "", "A description of this host.") cmd.Flags.StringVar(&cmd.host.DeploymentTicket, "tick", "", "The deployment ticket associated with this host.") return cmd }, } }
[ "func", "editPhysicalHostCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n", "\\n", "\\n", "\"", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "cmd", ":=", "&", "EditPhysicalHostCmd", "{", "}", "\n", "cmd", ".", "Initialize", "(", "params", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "host", ".", "Name", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "host", ".", "Machine", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "host", ".", "Os", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "StateFlag", "(", "&", "cmd", ".", "host", ".", "State", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "Int32", "(", "&", "cmd", ".", "host", ".", "VmSlots", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "host", ".", "VirtualDatacenter", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "host", ".", "Description", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "host", ".", "DeploymentTicket", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "cmd", "\n", "}", ",", "}", "\n", "}" ]
// editPhysicalHostCmd returns a command to edit a physical host.
[ "editPhysicalHostCmd", "returns", "a", "command", "to", "edit", "a", "physical", "host", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/physical_hosts.go#L121-L140
9,503
luci/luci-go
machine-db/client/cli/physical_hosts.go
Run
func (c *GetPhysicalHostsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) client := getClient(ctx) resp, err := client.ListPhysicalHosts(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } printPhysicalHosts(c.f.tsv, resp.Hosts...) return 0 }
go
func (c *GetPhysicalHostsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) client := getClient(ctx) resp, err := client.ListPhysicalHosts(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } printPhysicalHosts(c.f.tsv, resp.Hosts...) return 0 }
[ "func", "(", "c", "*", "GetPhysicalHostsCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "ctx", ":=", "cli", ".", "GetContext", "(", "app", ",", "c", ",", "env", ")", "\n", "client", ":=", "getClient", "(", "ctx", ")", "\n", "resp", ",", "err", ":=", "client", ".", "ListPhysicalHosts", "(", "ctx", ",", "&", "c", ".", "req", ")", "\n", "if", "err", "!=", "nil", "{", "errors", ".", "Log", "(", "ctx", ",", "err", ")", "\n", "return", "1", "\n", "}", "\n", "printPhysicalHosts", "(", "c", ".", "f", ".", "tsv", ",", "resp", ".", "Hosts", "...", ")", "\n", "return", "0", "\n", "}" ]
// Run runs the command to get physical hosts.
[ "Run", "runs", "the", "command", "to", "get", "physical", "hosts", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/physical_hosts.go#L149-L159
9,504
luci/luci-go
machine-db/client/cli/physical_hosts.go
getPhysicalHostsCmd
func getPhysicalHostsCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-hosts [-name <name>]... [-vlan <id>]... [-machine <machine>]... [-nic <nic>]... [-mac <mac address>]... [-os <os>]... [-ip <ip address>]... [-state <state>]... [-vdc <virtual datacenter>]...", ShortDesc: "retrieves physical hosts", LongDesc: "Retrieves physical hosts matching the given names and VLANs, or all physical hosts if names and VLANs are omitted.\n\nExample to get all hosts:\ncrimson get-hosts\nExample to get hosts in repair state in rack xx1:\ncrimson get-hosts -rack xx1 -state repair", CommandRun: func() subcommands.CommandRun { cmd := &GetPhysicalHostsCmd{} cmd.Initialize(params) cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a physical host to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.Int64Slice(&cmd.req.Vlans), "vlan", "ID of a VLAN to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Machines), "machine", "Name of a machine to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Nics), "nic", "Name of a NIC to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.MacAddresses), "mac", "MAC address to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Oses), "os", "Name of an operating system to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Ipv4S), "ip", "IPv4 address to filter by. Can be specified multiple times.") cmd.Flags.Var(StateSliceFlag(&cmd.req.States), "state", "State to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Platforms), "plat", "Name of a platform to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Racks), "rack", "Name of a rack to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Datacenters), "dc", "Name of a datacenter to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.VirtualDatacenters), "vdc", "Name of a virtual datacenter to filter by. Can be specified multiple times.") return cmd }, } }
go
func getPhysicalHostsCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-hosts [-name <name>]... [-vlan <id>]... [-machine <machine>]... [-nic <nic>]... [-mac <mac address>]... [-os <os>]... [-ip <ip address>]... [-state <state>]... [-vdc <virtual datacenter>]...", ShortDesc: "retrieves physical hosts", LongDesc: "Retrieves physical hosts matching the given names and VLANs, or all physical hosts if names and VLANs are omitted.\n\nExample to get all hosts:\ncrimson get-hosts\nExample to get hosts in repair state in rack xx1:\ncrimson get-hosts -rack xx1 -state repair", CommandRun: func() subcommands.CommandRun { cmd := &GetPhysicalHostsCmd{} cmd.Initialize(params) cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a physical host to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.Int64Slice(&cmd.req.Vlans), "vlan", "ID of a VLAN to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Machines), "machine", "Name of a machine to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Nics), "nic", "Name of a NIC to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.MacAddresses), "mac", "MAC address to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Oses), "os", "Name of an operating system to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Ipv4S), "ip", "IPv4 address to filter by. Can be specified multiple times.") cmd.Flags.Var(StateSliceFlag(&cmd.req.States), "state", "State to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Platforms), "plat", "Name of a platform to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Racks), "rack", "Name of a rack to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Datacenters), "dc", "Name of a datacenter to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.VirtualDatacenters), "vdc", "Name of a virtual datacenter to filter by. Can be specified multiple times.") return cmd }, } }
[ "func", "getPhysicalHostsCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n", "\\n", "\\n", "\\n", "\\n", "\"", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "cmd", ":=", "&", "GetPhysicalHostsCmd", "{", "}", "\n", "cmd", ".", "Initialize", "(", "params", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Names", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "Int64Slice", "(", "&", "cmd", ".", "req", ".", "Vlans", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Machines", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Nics", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "MacAddresses", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Oses", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Ipv4S", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "StateSliceFlag", "(", "&", "cmd", ".", "req", ".", "States", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Platforms", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Racks", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Datacenters", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "VirtualDatacenters", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "cmd", "\n", "}", ",", "}", "\n", "}" ]
// getPhysicalHostsCmd returns a command to get physical hosts.
[ "getPhysicalHostsCmd", "returns", "a", "command", "to", "get", "physical", "hosts", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/physical_hosts.go#L162-L185
9,505
luci/luci-go
grpc/prpc/decoding.go
readMessage
func readMessage(r *http.Request, msg proto.Message) *protocolError { format, err := FormatFromContentType(r.Header.Get(headerContentType)) if err != nil { // Spec: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.16 return errorf(http.StatusUnsupportedMediaType, "Content-Type header: %s", err) } buf, err := ioutil.ReadAll(r.Body) if err != nil { return errorf(http.StatusBadRequest, "could not read body: %s", err) } switch format { // Do not redefine "err" below. case FormatJSONPB: err = jsonpb.Unmarshal(bytes.NewBuffer(buf), msg) case FormatText: err = proto.UnmarshalText(string(buf), msg) case FormatBinary: err = proto.Unmarshal(buf, msg) default: panic(fmt.Errorf("impossible: invalid format %v", format)) } if err != nil { return errorf(http.StatusBadRequest, "could not decode body: %s", err) } return nil }
go
func readMessage(r *http.Request, msg proto.Message) *protocolError { format, err := FormatFromContentType(r.Header.Get(headerContentType)) if err != nil { // Spec: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.16 return errorf(http.StatusUnsupportedMediaType, "Content-Type header: %s", err) } buf, err := ioutil.ReadAll(r.Body) if err != nil { return errorf(http.StatusBadRequest, "could not read body: %s", err) } switch format { // Do not redefine "err" below. case FormatJSONPB: err = jsonpb.Unmarshal(bytes.NewBuffer(buf), msg) case FormatText: err = proto.UnmarshalText(string(buf), msg) case FormatBinary: err = proto.Unmarshal(buf, msg) default: panic(fmt.Errorf("impossible: invalid format %v", format)) } if err != nil { return errorf(http.StatusBadRequest, "could not decode body: %s", err) } return nil }
[ "func", "readMessage", "(", "r", "*", "http", ".", "Request", ",", "msg", "proto", ".", "Message", ")", "*", "protocolError", "{", "format", ",", "err", ":=", "FormatFromContentType", "(", "r", ".", "Header", ".", "Get", "(", "headerContentType", ")", ")", "\n", "if", "err", "!=", "nil", "{", "// Spec: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.16", "return", "errorf", "(", "http", ".", "StatusUnsupportedMediaType", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "buf", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errorf", "(", "http", ".", "StatusBadRequest", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "switch", "format", "{", "// Do not redefine \"err\" below.", "case", "FormatJSONPB", ":", "err", "=", "jsonpb", ".", "Unmarshal", "(", "bytes", ".", "NewBuffer", "(", "buf", ")", ",", "msg", ")", "\n\n", "case", "FormatText", ":", "err", "=", "proto", ".", "UnmarshalText", "(", "string", "(", "buf", ")", ",", "msg", ")", "\n\n", "case", "FormatBinary", ":", "err", "=", "proto", ".", "Unmarshal", "(", "buf", ",", "msg", ")", "\n\n", "default", ":", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "format", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errorf", "(", "http", ".", "StatusBadRequest", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// readMessage decodes a protobuf message from an HTTP request. // Does not close the request body.
[ "readMessage", "decodes", "a", "protobuf", "message", "from", "an", "HTTP", "request", ".", "Does", "not", "close", "the", "request", "body", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/decoding.go#L46-L76
9,506
luci/luci-go
grpc/prpc/decoding.go
parseHeader
func parseHeader(c context.Context, header http.Header) (context.Context, error) { origC := c md, ok := metadata.FromIncomingContext(c) if ok { md = md.Copy() } else { md = metadata.MD{} } addedMeta := false for name, values := range header { if len(values) == 0 { continue } name = http.CanonicalHeaderKey(name) switch name { case HeaderTimeout: // Decode only first value, ignore the rest // to be consistent with http.Header.Get. timeout, err := DecodeTimeout(values[0]) if err != nil { return origC, fmt.Errorf("%s header: %s", HeaderTimeout, err) } c, _ = clock.WithTimeout(c, timeout) case headerAccept, headerContentType: // readMessage and writeMessage handle these headers. default: addedMeta = true if !strings.HasSuffix(name, headerSuffixBinary) { md[name] = append(md[name], values...) break // switch name } trimmedName := strings.TrimSuffix(name, headerSuffixBinary) for _, v := range values { decoded, err := base64.StdEncoding.DecodeString(v) if err != nil { return origC, fmt.Errorf("%s header: %s", name, err) } md[trimmedName] = append(md[trimmedName], string(decoded)) } } } if addedMeta { c = metadata.NewIncomingContext(c, md) } return c, nil }
go
func parseHeader(c context.Context, header http.Header) (context.Context, error) { origC := c md, ok := metadata.FromIncomingContext(c) if ok { md = md.Copy() } else { md = metadata.MD{} } addedMeta := false for name, values := range header { if len(values) == 0 { continue } name = http.CanonicalHeaderKey(name) switch name { case HeaderTimeout: // Decode only first value, ignore the rest // to be consistent with http.Header.Get. timeout, err := DecodeTimeout(values[0]) if err != nil { return origC, fmt.Errorf("%s header: %s", HeaderTimeout, err) } c, _ = clock.WithTimeout(c, timeout) case headerAccept, headerContentType: // readMessage and writeMessage handle these headers. default: addedMeta = true if !strings.HasSuffix(name, headerSuffixBinary) { md[name] = append(md[name], values...) break // switch name } trimmedName := strings.TrimSuffix(name, headerSuffixBinary) for _, v := range values { decoded, err := base64.StdEncoding.DecodeString(v) if err != nil { return origC, fmt.Errorf("%s header: %s", name, err) } md[trimmedName] = append(md[trimmedName], string(decoded)) } } } if addedMeta { c = metadata.NewIncomingContext(c, md) } return c, nil }
[ "func", "parseHeader", "(", "c", "context", ".", "Context", ",", "header", "http", ".", "Header", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "origC", ":=", "c", "\n\n", "md", ",", "ok", ":=", "metadata", ".", "FromIncomingContext", "(", "c", ")", "\n", "if", "ok", "{", "md", "=", "md", ".", "Copy", "(", ")", "\n", "}", "else", "{", "md", "=", "metadata", ".", "MD", "{", "}", "\n", "}", "\n\n", "addedMeta", ":=", "false", "\n", "for", "name", ",", "values", ":=", "range", "header", "{", "if", "len", "(", "values", ")", "==", "0", "{", "continue", "\n", "}", "\n", "name", "=", "http", ".", "CanonicalHeaderKey", "(", "name", ")", "\n", "switch", "name", "{", "case", "HeaderTimeout", ":", "// Decode only first value, ignore the rest", "// to be consistent with http.Header.Get.", "timeout", ",", "err", ":=", "DecodeTimeout", "(", "values", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "origC", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "HeaderTimeout", ",", "err", ")", "\n", "}", "\n", "c", ",", "_", "=", "clock", ".", "WithTimeout", "(", "c", ",", "timeout", ")", "\n\n", "case", "headerAccept", ",", "headerContentType", ":", "// readMessage and writeMessage handle these headers.", "default", ":", "addedMeta", "=", "true", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "name", ",", "headerSuffixBinary", ")", "{", "md", "[", "name", "]", "=", "append", "(", "md", "[", "name", "]", ",", "values", "...", ")", "\n", "break", "// switch name", "\n", "}", "\n", "trimmedName", ":=", "strings", ".", "TrimSuffix", "(", "name", ",", "headerSuffixBinary", ")", "\n", "for", "_", ",", "v", ":=", "range", "values", "{", "decoded", ",", "err", ":=", "base64", ".", "StdEncoding", ".", "DecodeString", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "origC", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "md", "[", "trimmedName", "]", "=", "append", "(", "md", "[", "trimmedName", "]", ",", "string", "(", "decoded", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "addedMeta", "{", "c", "=", "metadata", ".", "NewIncomingContext", "(", "c", ",", "md", ")", "\n", "}", "\n", "return", "c", ",", "nil", "\n", "}" ]
// parseHeader parses HTTP headers and derives a new context. // Supports HeaderTimeout. // Ignores "Accept" and "Content-Type" headers. // // If there are unrecognized HTTP headers, with or without headerSuffixBinary, // they are added to a metadata.MD and a new context is derived. // If c already has metadata, the latter is copied. // // In case of an error, returns c unmodified.
[ "parseHeader", "parses", "HTTP", "headers", "and", "derives", "a", "new", "context", ".", "Supports", "HeaderTimeout", ".", "Ignores", "Accept", "and", "Content", "-", "Type", "headers", ".", "If", "there", "are", "unrecognized", "HTTP", "headers", "with", "or", "without", "headerSuffixBinary", "they", "are", "added", "to", "a", "metadata", ".", "MD", "and", "a", "new", "context", "is", "derived", ".", "If", "c", "already", "has", "metadata", "the", "latter", "is", "copied", ".", "In", "case", "of", "an", "error", "returns", "c", "unmodified", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/decoding.go#L87-L137
9,507
luci/luci-go
gce/api/config/v1/timeperiod.go
Normalize
func (t *TimePeriod) Normalize() error { if t.GetDuration() == "" { return nil } n, err := t.Time.(*TimePeriod_Duration).ToSeconds() if err != nil { return errors.Annotate(err, "invalid duration").Err() } t.Time = &TimePeriod_Seconds{ Seconds: n, } return nil }
go
func (t *TimePeriod) Normalize() error { if t.GetDuration() == "" { return nil } n, err := t.Time.(*TimePeriod_Duration).ToSeconds() if err != nil { return errors.Annotate(err, "invalid duration").Err() } t.Time = &TimePeriod_Seconds{ Seconds: n, } return nil }
[ "func", "(", "t", "*", "TimePeriod", ")", "Normalize", "(", ")", "error", "{", "if", "t", ".", "GetDuration", "(", ")", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "n", ",", "err", ":=", "t", ".", "Time", ".", "(", "*", "TimePeriod_Duration", ")", ".", "ToSeconds", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "t", ".", "Time", "=", "&", "TimePeriod_Seconds", "{", "Seconds", ":", "n", ",", "}", "\n", "return", "nil", "\n", "}" ]
// Normalize ensures this time period is in seconds. // Parses and converts duration to seconds if necessary.
[ "Normalize", "ensures", "this", "time", "period", "is", "in", "seconds", ".", "Parses", "and", "converts", "duration", "to", "seconds", "if", "necessary", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/timeperiod.go#L24-L36
9,508
luci/luci-go
gce/api/config/v1/timeperiod.go
ToSeconds
func (t *TimePeriod) ToSeconds() (int64, error) { if t == nil { return 0, nil } switch t := t.Time.(type) { case *TimePeriod_Duration: return t.ToSeconds() case *TimePeriod_Seconds: return t.Seconds, nil default: return 0, errors.Reason("unexpected type %T", t).Err() } }
go
func (t *TimePeriod) ToSeconds() (int64, error) { if t == nil { return 0, nil } switch t := t.Time.(type) { case *TimePeriod_Duration: return t.ToSeconds() case *TimePeriod_Seconds: return t.Seconds, nil default: return 0, errors.Reason("unexpected type %T", t).Err() } }
[ "func", "(", "t", "*", "TimePeriod", ")", "ToSeconds", "(", ")", "(", "int64", ",", "error", ")", "{", "if", "t", "==", "nil", "{", "return", "0", ",", "nil", "\n", "}", "\n", "switch", "t", ":=", "t", ".", "Time", ".", "(", "type", ")", "{", "case", "*", "TimePeriod_Duration", ":", "return", "t", ".", "ToSeconds", "(", ")", "\n", "case", "*", "TimePeriod_Seconds", ":", "return", "t", ".", "Seconds", ",", "nil", "\n", "default", ":", "return", "0", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "t", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}" ]
// ToSeconds returns this time period in seconds. Clamps to math.MaxInt64.
[ "ToSeconds", "returns", "this", "time", "period", "in", "seconds", ".", "Clamps", "to", "math", ".", "MaxInt64", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/timeperiod.go#L39-L51
9,509
luci/luci-go
gce/api/config/v1/timeperiod.go
Validate
func (t *TimePeriod) Validate(c *validation.Context) { switch { case t.GetDuration() != "": c.Enter("duration") t.Time.(*TimePeriod_Duration).Validate(c) c.Exit() case t.GetSeconds() < 0: c.Errorf("seconds must be non-negative") } }
go
func (t *TimePeriod) Validate(c *validation.Context) { switch { case t.GetDuration() != "": c.Enter("duration") t.Time.(*TimePeriod_Duration).Validate(c) c.Exit() case t.GetSeconds() < 0: c.Errorf("seconds must be non-negative") } }
[ "func", "(", "t", "*", "TimePeriod", ")", "Validate", "(", "c", "*", "validation", ".", "Context", ")", "{", "switch", "{", "case", "t", ".", "GetDuration", "(", ")", "!=", "\"", "\"", ":", "c", ".", "Enter", "(", "\"", "\"", ")", "\n", "t", ".", "Time", ".", "(", "*", "TimePeriod_Duration", ")", ".", "Validate", "(", "c", ")", "\n", "c", ".", "Exit", "(", ")", "\n", "case", "t", ".", "GetSeconds", "(", ")", "<", "0", ":", "c", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Validate validates this time period.
[ "Validate", "validates", "this", "time", "period", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/timeperiod.go#L54-L63
9,510
luci/luci-go
gce/api/projects/v1/configs.go
Validate
func (cfgs *Configs) Validate(c *validation.Context) { prjs := stringset.New(len(cfgs.GetProject())) for i, cfg := range cfgs.GetProject() { c.Enter("project %d", i) cfg.Validate(c) if !prjs.Add(cfg.Project) { c.Errorf("project %q is not unique", cfg.Project) } c.Exit() } }
go
func (cfgs *Configs) Validate(c *validation.Context) { prjs := stringset.New(len(cfgs.GetProject())) for i, cfg := range cfgs.GetProject() { c.Enter("project %d", i) cfg.Validate(c) if !prjs.Add(cfg.Project) { c.Errorf("project %q is not unique", cfg.Project) } c.Exit() } }
[ "func", "(", "cfgs", "*", "Configs", ")", "Validate", "(", "c", "*", "validation", ".", "Context", ")", "{", "prjs", ":=", "stringset", ".", "New", "(", "len", "(", "cfgs", ".", "GetProject", "(", ")", ")", ")", "\n", "for", "i", ",", "cfg", ":=", "range", "cfgs", ".", "GetProject", "(", ")", "{", "c", ".", "Enter", "(", "\"", "\"", ",", "i", ")", "\n", "cfg", ".", "Validate", "(", "c", ")", "\n", "if", "!", "prjs", ".", "Add", "(", "cfg", ".", "Project", ")", "{", "c", ".", "Errorf", "(", "\"", "\"", ",", "cfg", ".", "Project", ")", "\n", "}", "\n", "c", ".", "Exit", "(", ")", "\n", "}", "\n", "}" ]
// Validate validates these configs.
[ "Validate", "validates", "these", "configs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/projects/v1/configs.go#L23-L33
9,511
luci/luci-go
milo/frontend/ui/console.go
HasCategory
func (c *Console) HasCategory() bool { if len(c.Table.children) != 1 { return true } root := c.Table.children[0] rootCat, ok := root.(*Category) if !ok { return false // This shouldn't happen. } for _, child := range rootCat.children { if _, ok := child.(*Category); ok { return true } } return false }
go
func (c *Console) HasCategory() bool { if len(c.Table.children) != 1 { return true } root := c.Table.children[0] rootCat, ok := root.(*Category) if !ok { return false // This shouldn't happen. } for _, child := range rootCat.children { if _, ok := child.(*Category); ok { return true } } return false }
[ "func", "(", "c", "*", "Console", ")", "HasCategory", "(", ")", "bool", "{", "if", "len", "(", "c", ".", "Table", ".", "children", ")", "!=", "1", "{", "return", "true", "\n", "}", "\n", "root", ":=", "c", ".", "Table", ".", "children", "[", "0", "]", "\n", "rootCat", ",", "ok", ":=", "root", ".", "(", "*", "Category", ")", "\n", "if", "!", "ok", "{", "return", "false", "// This shouldn't happen.", "\n", "}", "\n", "for", "_", ",", "child", ":=", "range", "rootCat", ".", "children", "{", "if", "_", ",", "ok", ":=", "child", ".", "(", "*", "Category", ")", ";", "ok", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasCategory returns true if there is at least a single category defined in the console.
[ "HasCategory", "returns", "true", "if", "there", "is", "at", "least", "a", "single", "category", "defined", "in", "the", "console", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/console.go#L75-L90
9,512
luci/luci-go
milo/frontend/ui/console.go
NewCategory
func NewCategory(name string) *Category { return &Category{ Name: name, childrenMap: make(map[string]ConsoleElement), children: make([]ConsoleElement, 0), cachedNumLeafNodes: -1, } }
go
func NewCategory(name string) *Category { return &Category{ Name: name, childrenMap: make(map[string]ConsoleElement), children: make([]ConsoleElement, 0), cachedNumLeafNodes: -1, } }
[ "func", "NewCategory", "(", "name", "string", ")", "*", "Category", "{", "return", "&", "Category", "{", "Name", ":", "name", ",", "childrenMap", ":", "make", "(", "map", "[", "string", "]", "ConsoleElement", ")", ",", "children", ":", "make", "(", "[", "]", "ConsoleElement", ",", "0", ")", ",", "cachedNumLeafNodes", ":", "-", "1", ",", "}", "\n", "}" ]
// NewCategory allocates a new Category struct with no children.
[ "NewCategory", "allocates", "a", "new", "Category", "struct", "with", "no", "children", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/console.go#L229-L236
9,513
luci/luci-go
milo/frontend/ui/console.go
AddBuilder
func (c *Category) AddBuilder(categories []string, builder *BuilderRef) { current := c current.cachedNumLeafNodes = -1 for _, category := range categories { if child, ok := current.childrenMap[category]; ok { original := child.(*Category) original.cachedNumLeafNodes = -1 current = original } else { newChild := NewCategory(category) current.childrenMap[category] = ConsoleElement(newChild) current.children = append(current.children, ConsoleElement(newChild)) current = newChild } } current.childrenMap[builder.ID] = ConsoleElement(builder) current.children = append(current.children, ConsoleElement(builder)) }
go
func (c *Category) AddBuilder(categories []string, builder *BuilderRef) { current := c current.cachedNumLeafNodes = -1 for _, category := range categories { if child, ok := current.childrenMap[category]; ok { original := child.(*Category) original.cachedNumLeafNodes = -1 current = original } else { newChild := NewCategory(category) current.childrenMap[category] = ConsoleElement(newChild) current.children = append(current.children, ConsoleElement(newChild)) current = newChild } } current.childrenMap[builder.ID] = ConsoleElement(builder) current.children = append(current.children, ConsoleElement(builder)) }
[ "func", "(", "c", "*", "Category", ")", "AddBuilder", "(", "categories", "[", "]", "string", ",", "builder", "*", "BuilderRef", ")", "{", "current", ":=", "c", "\n", "current", ".", "cachedNumLeafNodes", "=", "-", "1", "\n", "for", "_", ",", "category", ":=", "range", "categories", "{", "if", "child", ",", "ok", ":=", "current", ".", "childrenMap", "[", "category", "]", ";", "ok", "{", "original", ":=", "child", ".", "(", "*", "Category", ")", "\n", "original", ".", "cachedNumLeafNodes", "=", "-", "1", "\n", "current", "=", "original", "\n", "}", "else", "{", "newChild", ":=", "NewCategory", "(", "category", ")", "\n", "current", ".", "childrenMap", "[", "category", "]", "=", "ConsoleElement", "(", "newChild", ")", "\n", "current", ".", "children", "=", "append", "(", "current", ".", "children", ",", "ConsoleElement", "(", "newChild", ")", ")", "\n", "current", "=", "newChild", "\n", "}", "\n", "}", "\n", "current", ".", "childrenMap", "[", "builder", ".", "ID", "]", "=", "ConsoleElement", "(", "builder", ")", "\n", "current", ".", "children", "=", "append", "(", "current", ".", "children", ",", "ConsoleElement", "(", "builder", ")", ")", "\n", "}" ]
// AddBuilder inserts the builder into this Category tree. // // AddBuilder will create new subcategories as a chain of Category structs // as needed until there are no categories remaining. The builder is then // made a child of the deepest such Category.
[ "AddBuilder", "inserts", "the", "builder", "into", "this", "Category", "tree", ".", "AddBuilder", "will", "create", "new", "subcategories", "as", "a", "chain", "of", "Category", "structs", "as", "needed", "until", "there", "are", "no", "categories", "remaining", ".", "The", "builder", "is", "then", "made", "a", "child", "of", "the", "deepest", "such", "Category", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/console.go#L243-L260
9,514
luci/luci-go
milo/frontend/ui/console.go
NumLeafNodes
func (c *Category) NumLeafNodes() int { if c.cachedNumLeafNodes != -1 { return c.cachedNumLeafNodes } leafNodes := 0 for _, child := range c.children { leafNodes += child.NumLeafNodes() } c.cachedNumLeafNodes = leafNodes return c.cachedNumLeafNodes }
go
func (c *Category) NumLeafNodes() int { if c.cachedNumLeafNodes != -1 { return c.cachedNumLeafNodes } leafNodes := 0 for _, child := range c.children { leafNodes += child.NumLeafNodes() } c.cachedNumLeafNodes = leafNodes return c.cachedNumLeafNodes }
[ "func", "(", "c", "*", "Category", ")", "NumLeafNodes", "(", ")", "int", "{", "if", "c", ".", "cachedNumLeafNodes", "!=", "-", "1", "{", "return", "c", ".", "cachedNumLeafNodes", "\n", "}", "\n\n", "leafNodes", ":=", "0", "\n", "for", "_", ",", "child", ":=", "range", "c", ".", "children", "{", "leafNodes", "+=", "child", ".", "NumLeafNodes", "(", ")", "\n", "}", "\n", "c", ".", "cachedNumLeafNodes", "=", "leafNodes", "\n", "return", "c", ".", "cachedNumLeafNodes", "\n", "}" ]
// NumLeafNodes calculates the number of leaf nodes in Category.
[ "NumLeafNodes", "calculates", "the", "number", "of", "leaf", "nodes", "in", "Category", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/console.go#L269-L280
9,515
luci/luci-go
milo/frontend/ui/console.go
RenderHTML
func (c Category) RenderHTML(buffer *bytes.Buffer, depth int, maxDepth int) { // Check to see if this category is a leaf. // A leaf category has no other categories as it's children. isLeafCategory := true for _, child := range c.children { if _, ok := child.(*Category); ok { isLeafCategory = false break } } if maxDepth > 0 { must(fmt.Fprintf(buffer, `<div class="console-column" style="flex: %d">`, c.NumLeafNodes())) must(fmt.Fprintf(buffer, `<div class="console-top-item">%s</div>`, template.HTMLEscapeString(c.Name))) if isLeafCategory { must(fmt.Fprintf(buffer, `<div class="console-top-row console-leaf-category">`)) } else { must(fmt.Fprintf(buffer, `<div class="console-top-row">`)) } } for _, child := range c.children { child.RenderHTML(buffer, depth+1, maxDepth) } if maxDepth > 0 { must(buffer.WriteString(`</div></div>`)) } }
go
func (c Category) RenderHTML(buffer *bytes.Buffer, depth int, maxDepth int) { // Check to see if this category is a leaf. // A leaf category has no other categories as it's children. isLeafCategory := true for _, child := range c.children { if _, ok := child.(*Category); ok { isLeafCategory = false break } } if maxDepth > 0 { must(fmt.Fprintf(buffer, `<div class="console-column" style="flex: %d">`, c.NumLeafNodes())) must(fmt.Fprintf(buffer, `<div class="console-top-item">%s</div>`, template.HTMLEscapeString(c.Name))) if isLeafCategory { must(fmt.Fprintf(buffer, `<div class="console-top-row console-leaf-category">`)) } else { must(fmt.Fprintf(buffer, `<div class="console-top-row">`)) } } for _, child := range c.children { child.RenderHTML(buffer, depth+1, maxDepth) } if maxDepth > 0 { must(buffer.WriteString(`</div></div>`)) } }
[ "func", "(", "c", "Category", ")", "RenderHTML", "(", "buffer", "*", "bytes", ".", "Buffer", ",", "depth", "int", ",", "maxDepth", "int", ")", "{", "// Check to see if this category is a leaf.", "// A leaf category has no other categories as it's children.", "isLeafCategory", ":=", "true", "\n", "for", "_", ",", "child", ":=", "range", "c", ".", "children", "{", "if", "_", ",", "ok", ":=", "child", ".", "(", "*", "Category", ")", ";", "ok", "{", "isLeafCategory", "=", "false", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "maxDepth", ">", "0", "{", "must", "(", "fmt", ".", "Fprintf", "(", "buffer", ",", "`<div class=\"console-column\" style=\"flex: %d\">`", ",", "c", ".", "NumLeafNodes", "(", ")", ")", ")", "\n", "must", "(", "fmt", ".", "Fprintf", "(", "buffer", ",", "`<div class=\"console-top-item\">%s</div>`", ",", "template", ".", "HTMLEscapeString", "(", "c", ".", "Name", ")", ")", ")", "\n", "if", "isLeafCategory", "{", "must", "(", "fmt", ".", "Fprintf", "(", "buffer", ",", "`<div class=\"console-top-row console-leaf-category\">`", ")", ")", "\n", "}", "else", "{", "must", "(", "fmt", ".", "Fprintf", "(", "buffer", ",", "`<div class=\"console-top-row\">`", ")", ")", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "child", ":=", "range", "c", ".", "children", "{", "child", ".", "RenderHTML", "(", "buffer", ",", "depth", "+", "1", ",", "maxDepth", ")", "\n", "}", "\n\n", "if", "maxDepth", ">", "0", "{", "must", "(", "buffer", ".", "WriteString", "(", "`</div></div>`", ")", ")", "\n", "}", "\n", "}" ]
// RenderHTML renders the Category struct and its children as HTML into a buffer. // If maxDepth is negative, skip the labels to render the HTML as flat rather than nested.
[ "RenderHTML", "renders", "the", "Category", "struct", "and", "its", "children", "as", "HTML", "into", "a", "buffer", ".", "If", "maxDepth", "is", "negative", "skip", "the", "labels", "to", "render", "the", "HTML", "as", "flat", "rather", "than", "nested", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/console.go#L492-L520
9,516
luci/luci-go
milo/api/buildbot/buildid.go
Validate
func (id BuildID) Validate() error { switch { case id.Master == "": return errors.New("master is unspecified", grpcutil.InvalidArgumentTag) case id.Builder == "": return errors.New("builder is unspecified", grpcutil.InvalidArgumentTag) case id.Number < 0: return errors.New("nunber must be >= 0", grpcutil.InvalidArgumentTag) default: return nil } }
go
func (id BuildID) Validate() error { switch { case id.Master == "": return errors.New("master is unspecified", grpcutil.InvalidArgumentTag) case id.Builder == "": return errors.New("builder is unspecified", grpcutil.InvalidArgumentTag) case id.Number < 0: return errors.New("nunber must be >= 0", grpcutil.InvalidArgumentTag) default: return nil } }
[ "func", "(", "id", "BuildID", ")", "Validate", "(", ")", "error", "{", "switch", "{", "case", "id", ".", "Master", "==", "\"", "\"", ":", "return", "errors", ".", "New", "(", "\"", "\"", ",", "grpcutil", ".", "InvalidArgumentTag", ")", "\n", "case", "id", ".", "Builder", "==", "\"", "\"", ":", "return", "errors", ".", "New", "(", "\"", "\"", ",", "grpcutil", ".", "InvalidArgumentTag", ")", "\n", "case", "id", ".", "Number", "<", "0", ":", "return", "errors", ".", "New", "(", "\"", "\"", ",", "grpcutil", ".", "InvalidArgumentTag", ")", "\n", "default", ":", "return", "nil", "\n", "}", "\n", "}" ]
// Validate returns an error if id is invalid.
[ "Validate", "returns", "an", "error", "if", "id", "is", "invalid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/api/buildbot/buildid.go#L32-L43
9,517
luci/luci-go
gce/api/config/v1/kinds.go
Map
func (kinds *Kinds) Map() map[string]*Kind { m := make(map[string]*Kind, len(kinds.GetKind())) for _, k := range kinds.GetKind() { m[k.Name] = k } return m }
go
func (kinds *Kinds) Map() map[string]*Kind { m := make(map[string]*Kind, len(kinds.GetKind())) for _, k := range kinds.GetKind() { m[k.Name] = k } return m }
[ "func", "(", "kinds", "*", "Kinds", ")", "Map", "(", ")", "map", "[", "string", "]", "*", "Kind", "{", "m", ":=", "make", "(", "map", "[", "string", "]", "*", "Kind", ",", "len", "(", "kinds", ".", "GetKind", "(", ")", ")", ")", "\n", "for", "_", ",", "k", ":=", "range", "kinds", ".", "GetKind", "(", ")", "{", "m", "[", "k", ".", "Name", "]", "=", "k", "\n", "}", "\n", "return", "m", "\n", "}" ]
// Map returns a map of name to VM kind. // For each name, only the last kind is included in the map. // Use Validate to ensure names are unique.
[ "Map", "returns", "a", "map", "of", "name", "to", "VM", "kind", ".", "For", "each", "name", "only", "the", "last", "kind", "is", "included", "in", "the", "map", ".", "Use", "Validate", "to", "ensure", "names", "are", "unique", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/kinds.go#L25-L31
9,518
luci/luci-go
gce/api/config/v1/kinds.go
Names
func (kinds *Kinds) Names() []string { names := make([]string, len(kinds.GetKind())) for i, k := range kinds.GetKind() { names[i] = k.Name } return names }
go
func (kinds *Kinds) Names() []string { names := make([]string, len(kinds.GetKind())) for i, k := range kinds.GetKind() { names[i] = k.Name } return names }
[ "func", "(", "kinds", "*", "Kinds", ")", "Names", "(", ")", "[", "]", "string", "{", "names", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "kinds", ".", "GetKind", "(", ")", ")", ")", "\n", "for", "i", ",", "k", ":=", "range", "kinds", ".", "GetKind", "(", ")", "{", "names", "[", "i", "]", "=", "k", ".", "Name", "\n", "}", "\n", "return", "names", "\n", "}" ]
// Names returns the names of VM kinds.
[ "Names", "returns", "the", "names", "of", "VM", "kinds", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/kinds.go#L34-L40
9,519
luci/luci-go
gce/api/config/v1/kinds.go
Validate
func (kinds *Kinds) Validate(c *validation.Context) { names := stringset.New(len(kinds.GetKind())) for i, k := range kinds.GetKind() { c.Enter("kind %d", i) switch { case k.Name == "": c.Errorf("name is required") case !names.Add(k.Name): c.Errorf("duplicate name %q", k.Name) } c.Exit() } }
go
func (kinds *Kinds) Validate(c *validation.Context) { names := stringset.New(len(kinds.GetKind())) for i, k := range kinds.GetKind() { c.Enter("kind %d", i) switch { case k.Name == "": c.Errorf("name is required") case !names.Add(k.Name): c.Errorf("duplicate name %q", k.Name) } c.Exit() } }
[ "func", "(", "kinds", "*", "Kinds", ")", "Validate", "(", "c", "*", "validation", ".", "Context", ")", "{", "names", ":=", "stringset", ".", "New", "(", "len", "(", "kinds", ".", "GetKind", "(", ")", ")", ")", "\n", "for", "i", ",", "k", ":=", "range", "kinds", ".", "GetKind", "(", ")", "{", "c", ".", "Enter", "(", "\"", "\"", ",", "i", ")", "\n", "switch", "{", "case", "k", ".", "Name", "==", "\"", "\"", ":", "c", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "!", "names", ".", "Add", "(", "k", ".", "Name", ")", ":", "c", ".", "Errorf", "(", "\"", "\"", ",", "k", ".", "Name", ")", "\n", "}", "\n", "c", ".", "Exit", "(", ")", "\n", "}", "\n", "}" ]
// Validate validates VM kinds.
[ "Validate", "validates", "VM", "kinds", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/kinds.go#L43-L55
9,520
luci/luci-go
cipd/client/cipd/deployer/deployer.go
New
func New(root string) Deployer { var err error if root == "" { err = fmt.Errorf("site root path is not provided") } else { root, err = filepath.Abs(filepath.Clean(root)) } if err != nil { return errDeployer{err} } trashDir := filepath.Join(root, fs.SiteServiceDir, "trash") return &deployerImpl{fs.NewFileSystem(root, trashDir)} }
go
func New(root string) Deployer { var err error if root == "" { err = fmt.Errorf("site root path is not provided") } else { root, err = filepath.Abs(filepath.Clean(root)) } if err != nil { return errDeployer{err} } trashDir := filepath.Join(root, fs.SiteServiceDir, "trash") return &deployerImpl{fs.NewFileSystem(root, trashDir)} }
[ "func", "New", "(", "root", "string", ")", "Deployer", "{", "var", "err", "error", "\n", "if", "root", "==", "\"", "\"", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "else", "{", "root", ",", "err", "=", "filepath", ".", "Abs", "(", "filepath", ".", "Clean", "(", "root", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errDeployer", "{", "err", "}", "\n", "}", "\n", "trashDir", ":=", "filepath", ".", "Join", "(", "root", ",", "fs", ".", "SiteServiceDir", ",", "\"", "\"", ")", "\n", "return", "&", "deployerImpl", "{", "fs", ".", "NewFileSystem", "(", "root", ",", "trashDir", ")", "}", "\n", "}" ]
// New return default Deployer implementation.
[ "New", "return", "default", "Deployer", "implementation", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/deployer/deployer.go#L191-L203
9,521
luci/luci-go
cipd/client/cipd/deployer/deployer.go
readDescription
func readDescription(r io.Reader) (desc *description, err error) { blob, err := ioutil.ReadAll(r) if err == nil { err = json.Unmarshal(blob, &desc) } return }
go
func readDescription(r io.Reader) (desc *description, err error) { blob, err := ioutil.ReadAll(r) if err == nil { err = json.Unmarshal(blob, &desc) } return }
[ "func", "readDescription", "(", "r", "io", ".", "Reader", ")", "(", "desc", "*", "description", ",", "err", "error", ")", "{", "blob", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "json", ".", "Unmarshal", "(", "blob", ",", "&", "desc", ")", "\n", "}", "\n", "return", "\n", "}" ]
// readDescription reads and decodes description JSON from io.Reader.
[ "readDescription", "reads", "and", "decodes", "description", "JSON", "from", "io", ".", "Reader", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/deployer/deployer.go#L248-L254
9,522
luci/luci-go
cipd/client/cipd/deployer/deployer.go
writeDescription
func writeDescription(d *description, w io.Writer) error { data, err := json.MarshalIndent(d, "", " ") if err != nil { return err } _, err = w.Write(data) return err }
go
func writeDescription(d *description, w io.Writer) error { data, err := json.MarshalIndent(d, "", " ") if err != nil { return err } _, err = w.Write(data) return err }
[ "func", "writeDescription", "(", "d", "*", "description", ",", "w", "io", ".", "Writer", ")", "error", "{", "data", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "d", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "w", ".", "Write", "(", "data", ")", "\n", "return", "err", "\n", "}" ]
// writeDescription encodes and writes description JSON to io.Writer.
[ "writeDescription", "encodes", "and", "writes", "description", "JSON", "to", "io", ".", "Writer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/deployer/deployer.go#L257-L264
9,523
luci/luci-go
cipd/client/cipd/deployer/deployer.go
removeFromSiteRoot
func (d *deployerImpl) removeFromSiteRoot(ctx context.Context, subdir string, files []pkg.FileInfo, keep *pathTree) { dirsToCleanup := stringset.New(0) for _, f := range files { rootRel := filepath.Join(subdir, filepath.FromSlash(f.Name)) if keep.has(rootRel) { continue } absPath, err := d.fs.RootRelToAbs(rootRel) if err != nil { logging.Warningf(ctx, "Refusing to remove %q: %s", f.Name, err) continue } if err := d.fs.EnsureFileGone(ctx, absPath); err != nil { logging.Warningf(ctx, "Failed to remove a file from the site root: %s", err) } else { dirsToCleanup.Add(filepath.Dir(absPath)) } } if dirsToCleanup.Len() != 0 { subdirAbs, err := d.fs.RootRelToAbs(subdir) if err != nil { logging.Warningf(ctx, "Can't resolve relative %q to absolute path: %s", subdir, err) } else { removeEmptyTrees(ctx, subdirAbs, dirsToCleanup) } } }
go
func (d *deployerImpl) removeFromSiteRoot(ctx context.Context, subdir string, files []pkg.FileInfo, keep *pathTree) { dirsToCleanup := stringset.New(0) for _, f := range files { rootRel := filepath.Join(subdir, filepath.FromSlash(f.Name)) if keep.has(rootRel) { continue } absPath, err := d.fs.RootRelToAbs(rootRel) if err != nil { logging.Warningf(ctx, "Refusing to remove %q: %s", f.Name, err) continue } if err := d.fs.EnsureFileGone(ctx, absPath); err != nil { logging.Warningf(ctx, "Failed to remove a file from the site root: %s", err) } else { dirsToCleanup.Add(filepath.Dir(absPath)) } } if dirsToCleanup.Len() != 0 { subdirAbs, err := d.fs.RootRelToAbs(subdir) if err != nil { logging.Warningf(ctx, "Can't resolve relative %q to absolute path: %s", subdir, err) } else { removeEmptyTrees(ctx, subdirAbs, dirsToCleanup) } } }
[ "func", "(", "d", "*", "deployerImpl", ")", "removeFromSiteRoot", "(", "ctx", "context", ".", "Context", ",", "subdir", "string", ",", "files", "[", "]", "pkg", ".", "FileInfo", ",", "keep", "*", "pathTree", ")", "{", "dirsToCleanup", ":=", "stringset", ".", "New", "(", "0", ")", "\n\n", "for", "_", ",", "f", ":=", "range", "files", "{", "rootRel", ":=", "filepath", ".", "Join", "(", "subdir", ",", "filepath", ".", "FromSlash", "(", "f", ".", "Name", ")", ")", "\n", "if", "keep", ".", "has", "(", "rootRel", ")", "{", "continue", "\n", "}", "\n", "absPath", ",", "err", ":=", "d", ".", "fs", ".", "RootRelToAbs", "(", "rootRel", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ",", "f", ".", "Name", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "err", ":=", "d", ".", "fs", ".", "EnsureFileGone", "(", "ctx", ",", "absPath", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "dirsToCleanup", ".", "Add", "(", "filepath", ".", "Dir", "(", "absPath", ")", ")", "\n", "}", "\n", "}", "\n\n", "if", "dirsToCleanup", ".", "Len", "(", ")", "!=", "0", "{", "subdirAbs", ",", "err", ":=", "d", ".", "fs", ".", "RootRelToAbs", "(", "subdir", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ",", "subdir", ",", "err", ")", "\n", "}", "else", "{", "removeEmptyTrees", "(", "ctx", ",", "subdirAbs", ",", "dirsToCleanup", ")", "\n", "}", "\n", "}", "\n", "}" ]
// removeFromSiteRoot deletes files from the site root directory unless they // are present in the 'keep' set. // // Best effort. Logs errors and carries on.
[ "removeFromSiteRoot", "deletes", "files", "from", "the", "site", "root", "directory", "unless", "they", "are", "present", "in", "the", "keep", "set", ".", "Best", "effort", ".", "Logs", "errors", "and", "carries", "on", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/deployer/deployer.go#L1151-L1179
9,524
luci/luci-go
cipd/client/cipd/deployer/deployer.go
isPresentInSite
func (d *deployerImpl) isPresentInSite(ctx context.Context, subdir string, f pkg.FileInfo, followSymlinks bool) bool { absPath, err := d.fs.RootRelToAbs(filepath.Join(subdir, filepath.FromSlash(f.Name))) if err != nil { panic(err) // should not happen for files present in installed packages } stat := d.fs.Lstat if followSymlinks { stat = d.fs.Stat } // TODO(vadimsh): Use result of this call to check the correctness of file // mode of the deployed file. Also use ModTime to detect modifications to the // file content in higher paranoia modes. switch _, err = stat(ctx, absPath); { case err == nil: return true case os.IsNotExist(err): return false default: logging.Warningf(ctx, "Failed to check presence of %q, assuming it needs repair: %s", f.Name, err) return false } }
go
func (d *deployerImpl) isPresentInSite(ctx context.Context, subdir string, f pkg.FileInfo, followSymlinks bool) bool { absPath, err := d.fs.RootRelToAbs(filepath.Join(subdir, filepath.FromSlash(f.Name))) if err != nil { panic(err) // should not happen for files present in installed packages } stat := d.fs.Lstat if followSymlinks { stat = d.fs.Stat } // TODO(vadimsh): Use result of this call to check the correctness of file // mode of the deployed file. Also use ModTime to detect modifications to the // file content in higher paranoia modes. switch _, err = stat(ctx, absPath); { case err == nil: return true case os.IsNotExist(err): return false default: logging.Warningf(ctx, "Failed to check presence of %q, assuming it needs repair: %s", f.Name, err) return false } }
[ "func", "(", "d", "*", "deployerImpl", ")", "isPresentInSite", "(", "ctx", "context", ".", "Context", ",", "subdir", "string", ",", "f", "pkg", ".", "FileInfo", ",", "followSymlinks", "bool", ")", "bool", "{", "absPath", ",", "err", ":=", "d", ".", "fs", ".", "RootRelToAbs", "(", "filepath", ".", "Join", "(", "subdir", ",", "filepath", ".", "FromSlash", "(", "f", ".", "Name", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "// should not happen for files present in installed packages", "\n", "}", "\n\n", "stat", ":=", "d", ".", "fs", ".", "Lstat", "\n", "if", "followSymlinks", "{", "stat", "=", "d", ".", "fs", ".", "Stat", "\n", "}", "\n\n", "// TODO(vadimsh): Use result of this call to check the correctness of file", "// mode of the deployed file. Also use ModTime to detect modifications to the", "// file content in higher paranoia modes.", "switch", "_", ",", "err", "=", "stat", "(", "ctx", ",", "absPath", ")", ";", "{", "case", "err", "==", "nil", ":", "return", "true", "\n", "case", "os", ".", "IsNotExist", "(", "err", ")", ":", "return", "false", "\n", "default", ":", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ",", "f", ".", "Name", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "}" ]
// isPresentInSite checks whether the given file is installed in the site root. // // Optionally follows symlinks. // // If the file can't be checked for some reason, logs the error and returns // false.
[ "isPresentInSite", "checks", "whether", "the", "given", "file", "is", "installed", "in", "the", "site", "root", ".", "Optionally", "follows", "symlinks", ".", "If", "the", "file", "can", "t", "be", "checked", "for", "some", "reason", "logs", "the", "error", "and", "returns", "false", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/deployer/deployer.go#L1187-L1210
9,525
luci/luci-go
cipd/client/cipd/deployer/deployer.go
checkIntegrity
func (d *deployerImpl) checkIntegrity(ctx context.Context, p *DeployedPackage, mode ParanoidMode) (redeploy, relink []string) { logging.Debugf(ctx, "Checking integrity of %q deployment in %q mode...", p.Pin.PackageName, mode) // TODO(vadimsh): Understand mode == CheckIntegrity. // Examine files that are supposed to be installed. for _, f := range p.Manifest.Files { switch { case d.isPresentInSite(ctx, p.Subdir, f, true): // no need to repair continue case f.Symlink == "": // a regular file (not a symlink) switch { case p.InstallMode == pkg.InstallModeCopy: // In 'copy' mode regular files are stored in the site root directly. // If they are gone, we need to refetch the package to restore them. redeploy = append(redeploy, f.Name) case d.isPresentInGuts(ctx, p.instancePath, f): // This is 'symlink' mode and the original file in .cipd guts exist. We // only need to relink the file then to repair it. relink = append(relink, f.Name) default: // This is 'symlink' mode, but the original file in .cipd guts is gone, // so we need to refetch it. redeploy = append(redeploy, f.Name) } case !filepath.IsAbs(filepath.FromSlash(f.Symlink)): // a relative symlink // We can restore it right away, all necessary information is in the // manifest. Note that CIPD packages cannot have invalid relative // symlinks, so if we see a broken one we know it is a corruption. relink = append(relink, f.Name) default: // This is a broken absolute symlink. Several possibilities here: // 1. The symlink file itself in the site root is missing. // 2. This is 'symlink' mode, and the symlink in .cipd/guts is missing. // 3. Both CIPD-managed symlinks exist and the external file is missing. // Such symlink is NOT broken. If we try to "repair" it, we end up in // the same state anyway: absolute symlinks point to files outside of // our control. switch { case !d.isPresentInSite(ctx, p.Subdir, f, false): // The symlink in the site root is gone, need to restore it. relink = append(relink, f.Name) case p.InstallMode == pkg.InstallModeSymlink && !d.isPresentInGuts(ctx, p.instancePath, f): // The symlink in the guts is gone, need to restore it. relink = append(relink, f.Name) default: // Both CIPD-managed symlinks are fine, nothing to restore. } } } return }
go
func (d *deployerImpl) checkIntegrity(ctx context.Context, p *DeployedPackage, mode ParanoidMode) (redeploy, relink []string) { logging.Debugf(ctx, "Checking integrity of %q deployment in %q mode...", p.Pin.PackageName, mode) // TODO(vadimsh): Understand mode == CheckIntegrity. // Examine files that are supposed to be installed. for _, f := range p.Manifest.Files { switch { case d.isPresentInSite(ctx, p.Subdir, f, true): // no need to repair continue case f.Symlink == "": // a regular file (not a symlink) switch { case p.InstallMode == pkg.InstallModeCopy: // In 'copy' mode regular files are stored in the site root directly. // If they are gone, we need to refetch the package to restore them. redeploy = append(redeploy, f.Name) case d.isPresentInGuts(ctx, p.instancePath, f): // This is 'symlink' mode and the original file in .cipd guts exist. We // only need to relink the file then to repair it. relink = append(relink, f.Name) default: // This is 'symlink' mode, but the original file in .cipd guts is gone, // so we need to refetch it. redeploy = append(redeploy, f.Name) } case !filepath.IsAbs(filepath.FromSlash(f.Symlink)): // a relative symlink // We can restore it right away, all necessary information is in the // manifest. Note that CIPD packages cannot have invalid relative // symlinks, so if we see a broken one we know it is a corruption. relink = append(relink, f.Name) default: // This is a broken absolute symlink. Several possibilities here: // 1. The symlink file itself in the site root is missing. // 2. This is 'symlink' mode, and the symlink in .cipd/guts is missing. // 3. Both CIPD-managed symlinks exist and the external file is missing. // Such symlink is NOT broken. If we try to "repair" it, we end up in // the same state anyway: absolute symlinks point to files outside of // our control. switch { case !d.isPresentInSite(ctx, p.Subdir, f, false): // The symlink in the site root is gone, need to restore it. relink = append(relink, f.Name) case p.InstallMode == pkg.InstallModeSymlink && !d.isPresentInGuts(ctx, p.instancePath, f): // The symlink in the guts is gone, need to restore it. relink = append(relink, f.Name) default: // Both CIPD-managed symlinks are fine, nothing to restore. } } } return }
[ "func", "(", "d", "*", "deployerImpl", ")", "checkIntegrity", "(", "ctx", "context", ".", "Context", ",", "p", "*", "DeployedPackage", ",", "mode", "ParanoidMode", ")", "(", "redeploy", ",", "relink", "[", "]", "string", ")", "{", "logging", ".", "Debugf", "(", "ctx", ",", "\"", "\"", ",", "p", ".", "Pin", ".", "PackageName", ",", "mode", ")", "\n\n", "// TODO(vadimsh): Understand mode == CheckIntegrity.", "// Examine files that are supposed to be installed.", "for", "_", ",", "f", ":=", "range", "p", ".", "Manifest", ".", "Files", "{", "switch", "{", "case", "d", ".", "isPresentInSite", "(", "ctx", ",", "p", ".", "Subdir", ",", "f", ",", "true", ")", ":", "// no need to repair", "continue", "\n", "case", "f", ".", "Symlink", "==", "\"", "\"", ":", "// a regular file (not a symlink)", "switch", "{", "case", "p", ".", "InstallMode", "==", "pkg", ".", "InstallModeCopy", ":", "// In 'copy' mode regular files are stored in the site root directly.", "// If they are gone, we need to refetch the package to restore them.", "redeploy", "=", "append", "(", "redeploy", ",", "f", ".", "Name", ")", "\n", "case", "d", ".", "isPresentInGuts", "(", "ctx", ",", "p", ".", "instancePath", ",", "f", ")", ":", "// This is 'symlink' mode and the original file in .cipd guts exist. We", "// only need to relink the file then to repair it.", "relink", "=", "append", "(", "relink", ",", "f", ".", "Name", ")", "\n", "default", ":", "// This is 'symlink' mode, but the original file in .cipd guts is gone,", "// so we need to refetch it.", "redeploy", "=", "append", "(", "redeploy", ",", "f", ".", "Name", ")", "\n", "}", "\n", "case", "!", "filepath", ".", "IsAbs", "(", "filepath", ".", "FromSlash", "(", "f", ".", "Symlink", ")", ")", ":", "// a relative symlink", "// We can restore it right away, all necessary information is in the", "// manifest. Note that CIPD packages cannot have invalid relative", "// symlinks, so if we see a broken one we know it is a corruption.", "relink", "=", "append", "(", "relink", ",", "f", ".", "Name", ")", "\n", "default", ":", "// This is a broken absolute symlink. Several possibilities here:", "// 1. The symlink file itself in the site root is missing.", "// 2. This is 'symlink' mode, and the symlink in .cipd/guts is missing.", "// 3. Both CIPD-managed symlinks exist and the external file is missing.", "// Such symlink is NOT broken. If we try to \"repair\" it, we end up in", "// the same state anyway: absolute symlinks point to files outside of", "// our control.", "switch", "{", "case", "!", "d", ".", "isPresentInSite", "(", "ctx", ",", "p", ".", "Subdir", ",", "f", ",", "false", ")", ":", "// The symlink in the site root is gone, need to restore it.", "relink", "=", "append", "(", "relink", ",", "f", ".", "Name", ")", "\n", "case", "p", ".", "InstallMode", "==", "pkg", ".", "InstallModeSymlink", "&&", "!", "d", ".", "isPresentInGuts", "(", "ctx", ",", "p", ".", "instancePath", ",", "f", ")", ":", "// The symlink in the guts is gone, need to restore it.", "relink", "=", "append", "(", "relink", ",", "f", ".", "Name", ")", "\n", "default", ":", "// Both CIPD-managed symlinks are fine, nothing to restore.", "}", "\n", "}", "\n", "}", "\n\n", "return", "\n", "}" ]
// checkIntegrity verifies the given deployed package is correctly installed and // returns a list of files to relink and to redeploy if something is broken. // // See DeployedPackage struct for definition of "relink" and "redeploy".
[ "checkIntegrity", "verifies", "the", "given", "deployed", "package", "is", "correctly", "installed", "and", "returns", "a", "list", "of", "files", "to", "relink", "and", "to", "redeploy", "if", "something", "is", "broken", ".", "See", "DeployedPackage", "struct", "for", "definition", "of", "relink", "and", "redeploy", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/deployer/deployer.go#L1239-L1291
9,526
luci/luci-go
cipd/client/cipd/deployer/deployer.go
newPathTree
func newPathTree(caseSensitive bool, capacity int) *pathTree { return &pathTree{ caseSensitive: caseSensitive, nodes: stringset.New(capacity / 5), // educated guess leafs: stringset.New(capacity), // exact } }
go
func newPathTree(caseSensitive bool, capacity int) *pathTree { return &pathTree{ caseSensitive: caseSensitive, nodes: stringset.New(capacity / 5), // educated guess leafs: stringset.New(capacity), // exact } }
[ "func", "newPathTree", "(", "caseSensitive", "bool", ",", "capacity", "int", ")", "*", "pathTree", "{", "return", "&", "pathTree", "{", "caseSensitive", ":", "caseSensitive", ",", "nodes", ":", "stringset", ".", "New", "(", "capacity", "/", "5", ")", ",", "// educated guess", "leafs", ":", "stringset", ".", "New", "(", "capacity", ")", ",", "// exact", "}", "\n", "}" ]
// newPathTree initializes the path tree, allocating the given capacity.
[ "newPathTree", "initializes", "the", "path", "tree", "allocating", "the", "given", "capacity", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/deployer/deployer.go#L1318-L1324
9,527
luci/luci-go
cipd/client/cipd/deployer/deployer.go
add
func (p *pathTree) add(rel string) { if !p.caseSensitive { rel = strings.ToLower(rel) } p.leafs.Add(rel) parentDirs(rel, func(par string) bool { p.nodes.Add(par) return true }) }
go
func (p *pathTree) add(rel string) { if !p.caseSensitive { rel = strings.ToLower(rel) } p.leafs.Add(rel) parentDirs(rel, func(par string) bool { p.nodes.Add(par) return true }) }
[ "func", "(", "p", "*", "pathTree", ")", "add", "(", "rel", "string", ")", "{", "if", "!", "p", ".", "caseSensitive", "{", "rel", "=", "strings", ".", "ToLower", "(", "rel", ")", "\n", "}", "\n", "p", ".", "leafs", ".", "Add", "(", "rel", ")", "\n", "parentDirs", "(", "rel", ",", "func", "(", "par", "string", ")", "bool", "{", "p", ".", "nodes", ".", "Add", "(", "par", ")", "\n", "return", "true", "\n", "}", ")", "\n", "}" ]
// add adds a native path 'rel', all its parents and all its children to the // path tree.
[ "add", "adds", "a", "native", "path", "rel", "all", "its", "parents", "and", "all", "its", "children", "to", "the", "path", "tree", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/deployer/deployer.go#L1328-L1337
9,528
luci/luci-go
cipd/client/cipd/deployer/deployer.go
has
func (p *pathTree) has(rel string) bool { if p == nil { return false } if !p.caseSensitive { rel = strings.ToLower(rel) } // It matches some added entry exactly? if p.leafs.Has(rel) { return true } // Was added as a parent of some entry? if p.nodes.Has(rel) { return true } // Maybe it has some added entry as its parent? found := false parentDirs(rel, func(par string) bool { found = p.leafs.Has(par) return !found }) return found }
go
func (p *pathTree) has(rel string) bool { if p == nil { return false } if !p.caseSensitive { rel = strings.ToLower(rel) } // It matches some added entry exactly? if p.leafs.Has(rel) { return true } // Was added as a parent of some entry? if p.nodes.Has(rel) { return true } // Maybe it has some added entry as its parent? found := false parentDirs(rel, func(par string) bool { found = p.leafs.Has(par) return !found }) return found }
[ "func", "(", "p", "*", "pathTree", ")", "has", "(", "rel", "string", ")", "bool", "{", "if", "p", "==", "nil", "{", "return", "false", "\n", "}", "\n\n", "if", "!", "p", ".", "caseSensitive", "{", "rel", "=", "strings", ".", "ToLower", "(", "rel", ")", "\n", "}", "\n\n", "// It matches some added entry exactly?", "if", "p", ".", "leafs", ".", "Has", "(", "rel", ")", "{", "return", "true", "\n", "}", "\n", "// Was added as a parent of some entry?", "if", "p", ".", "nodes", ".", "Has", "(", "rel", ")", "{", "return", "true", "\n", "}", "\n\n", "// Maybe it has some added entry as its parent?", "found", ":=", "false", "\n", "parentDirs", "(", "rel", ",", "func", "(", "par", "string", ")", "bool", "{", "found", "=", "p", ".", "leafs", ".", "Has", "(", "par", ")", "\n", "return", "!", "found", "\n", "}", ")", "\n", "return", "found", "\n", "}" ]
// has returns true if a native path 'rel' is in the tree. // // nil pathTree is considered empty.
[ "has", "returns", "true", "if", "a", "native", "path", "rel", "is", "in", "the", "tree", ".", "nil", "pathTree", "is", "considered", "empty", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/deployer/deployer.go#L1342-L1367
9,529
luci/luci-go
grpc/cmd/cproto/main.go
compile
func compile(c context.Context, gopath, importPaths, protoFiles []string, dir, descSetOut string) (outDir string, err error) { // make it absolute to find in $GOPATH and because protoc wants paths // to be under proto paths. if dir, err = filepath.Abs(dir); err != nil { return "", err } // By default place go files in CWD, // unless proto files are under a $GOPATH/src. goOut := "." // Combine user-defined proto paths with $GOPATH/src. allProtoPaths := make([]string, 0, len(importPaths)+len(gopath)+1) for _, p := range importPaths { if p, err = filepath.Abs(p); err != nil { return "", err } allProtoPaths = append(allProtoPaths, p) } for _, p := range gopath { path := filepath.Join(p, "src") if info, err := os.Stat(path); os.IsNotExist(err) || !info.IsDir() { continue } else if err != nil { return "", err } allProtoPaths = append(allProtoPaths, path) // If the dir is under $GOPATH/src, generate .go files near .proto files. if strings.HasPrefix(dir, path) { goOut = path } // Include well-known protobuf types. wellKnownProtoDir := filepath.Join(path, "go.chromium.org", "luci", "grpc", "proto") if info, err := os.Stat(wellKnownProtoDir); err == nil && info.IsDir() { allProtoPaths = append(allProtoPaths, wellKnownProtoDir) } } // Find where Go files will be generated. for _, p := range allProtoPaths { if strings.HasPrefix(dir, p) { outDir = filepath.Join(goOut, dir[len(p):]) break } } if outDir == "" { return "", fmt.Errorf("proto files are neither under $GOPATH/src nor -proto-path") } args := []string{ "--descriptor_set_out=" + descSetOut, "--include_imports", "--include_source_info", } for _, p := range allProtoPaths { args = append(args, "--proto_path="+p) } var params []string for k, v := range pathMap { params = append(params, fmt.Sprintf("M%s=%s", k, v)) } params = append(params, "plugins=grpc") args = append(args, fmt.Sprintf("--go_out=%s:%s", strings.Join(params, ","), goOut)) for _, f := range protoFiles { // We must prepend an go-style absolute path to the filename otherwise // protoc will complain that the files we specify here are not found // in any of proto-paths. // // We cannot specify --proto-path=. because of the following scenario: // we have file structure // - A // - x.proto, imports "y.proto" // - y.proto // - B // - z.proto, imports "github.com/user/repo/A/x.proto" // If cproto is executed in B, proto path does not include A, so y.proto // is not found. // The solution is to always use absolute paths. args = append(args, path.Join(dir, f)) } logging.Infof(c, "protoc %s", strings.Join(args, " ")) protoc := exec.Command("protoc", args...) protoc.Stdout = os.Stdout protoc.Stderr = os.Stderr return outDir, protoc.Run() }
go
func compile(c context.Context, gopath, importPaths, protoFiles []string, dir, descSetOut string) (outDir string, err error) { // make it absolute to find in $GOPATH and because protoc wants paths // to be under proto paths. if dir, err = filepath.Abs(dir); err != nil { return "", err } // By default place go files in CWD, // unless proto files are under a $GOPATH/src. goOut := "." // Combine user-defined proto paths with $GOPATH/src. allProtoPaths := make([]string, 0, len(importPaths)+len(gopath)+1) for _, p := range importPaths { if p, err = filepath.Abs(p); err != nil { return "", err } allProtoPaths = append(allProtoPaths, p) } for _, p := range gopath { path := filepath.Join(p, "src") if info, err := os.Stat(path); os.IsNotExist(err) || !info.IsDir() { continue } else if err != nil { return "", err } allProtoPaths = append(allProtoPaths, path) // If the dir is under $GOPATH/src, generate .go files near .proto files. if strings.HasPrefix(dir, path) { goOut = path } // Include well-known protobuf types. wellKnownProtoDir := filepath.Join(path, "go.chromium.org", "luci", "grpc", "proto") if info, err := os.Stat(wellKnownProtoDir); err == nil && info.IsDir() { allProtoPaths = append(allProtoPaths, wellKnownProtoDir) } } // Find where Go files will be generated. for _, p := range allProtoPaths { if strings.HasPrefix(dir, p) { outDir = filepath.Join(goOut, dir[len(p):]) break } } if outDir == "" { return "", fmt.Errorf("proto files are neither under $GOPATH/src nor -proto-path") } args := []string{ "--descriptor_set_out=" + descSetOut, "--include_imports", "--include_source_info", } for _, p := range allProtoPaths { args = append(args, "--proto_path="+p) } var params []string for k, v := range pathMap { params = append(params, fmt.Sprintf("M%s=%s", k, v)) } params = append(params, "plugins=grpc") args = append(args, fmt.Sprintf("--go_out=%s:%s", strings.Join(params, ","), goOut)) for _, f := range protoFiles { // We must prepend an go-style absolute path to the filename otherwise // protoc will complain that the files we specify here are not found // in any of proto-paths. // // We cannot specify --proto-path=. because of the following scenario: // we have file structure // - A // - x.proto, imports "y.proto" // - y.proto // - B // - z.proto, imports "github.com/user/repo/A/x.proto" // If cproto is executed in B, proto path does not include A, so y.proto // is not found. // The solution is to always use absolute paths. args = append(args, path.Join(dir, f)) } logging.Infof(c, "protoc %s", strings.Join(args, " ")) protoc := exec.Command("protoc", args...) protoc.Stdout = os.Stdout protoc.Stderr = os.Stderr return outDir, protoc.Run() }
[ "func", "compile", "(", "c", "context", ".", "Context", ",", "gopath", ",", "importPaths", ",", "protoFiles", "[", "]", "string", ",", "dir", ",", "descSetOut", "string", ")", "(", "outDir", "string", ",", "err", "error", ")", "{", "// make it absolute to find in $GOPATH and because protoc wants paths", "// to be under proto paths.", "if", "dir", ",", "err", "=", "filepath", ".", "Abs", "(", "dir", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "// By default place go files in CWD,", "// unless proto files are under a $GOPATH/src.", "goOut", ":=", "\"", "\"", "\n\n", "// Combine user-defined proto paths with $GOPATH/src.", "allProtoPaths", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "importPaths", ")", "+", "len", "(", "gopath", ")", "+", "1", ")", "\n", "for", "_", ",", "p", ":=", "range", "importPaths", "{", "if", "p", ",", "err", "=", "filepath", ".", "Abs", "(", "p", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "allProtoPaths", "=", "append", "(", "allProtoPaths", ",", "p", ")", "\n", "}", "\n", "for", "_", ",", "p", ":=", "range", "gopath", "{", "path", ":=", "filepath", ".", "Join", "(", "p", ",", "\"", "\"", ")", "\n", "if", "info", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "||", "!", "info", ".", "IsDir", "(", ")", "{", "continue", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "allProtoPaths", "=", "append", "(", "allProtoPaths", ",", "path", ")", "\n\n", "// If the dir is under $GOPATH/src, generate .go files near .proto files.", "if", "strings", ".", "HasPrefix", "(", "dir", ",", "path", ")", "{", "goOut", "=", "path", "\n", "}", "\n\n", "// Include well-known protobuf types.", "wellKnownProtoDir", ":=", "filepath", ".", "Join", "(", "path", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "info", ",", "err", ":=", "os", ".", "Stat", "(", "wellKnownProtoDir", ")", ";", "err", "==", "nil", "&&", "info", ".", "IsDir", "(", ")", "{", "allProtoPaths", "=", "append", "(", "allProtoPaths", ",", "wellKnownProtoDir", ")", "\n", "}", "\n", "}", "\n\n", "// Find where Go files will be generated.", "for", "_", ",", "p", ":=", "range", "allProtoPaths", "{", "if", "strings", ".", "HasPrefix", "(", "dir", ",", "p", ")", "{", "outDir", "=", "filepath", ".", "Join", "(", "goOut", ",", "dir", "[", "len", "(", "p", ")", ":", "]", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "outDir", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "args", ":=", "[", "]", "string", "{", "\"", "\"", "+", "descSetOut", ",", "\"", "\"", ",", "\"", "\"", ",", "}", "\n", "for", "_", ",", "p", ":=", "range", "allProtoPaths", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", "+", "p", ")", "\n", "}", "\n\n", "var", "params", "[", "]", "string", "\n", "for", "k", ",", "v", ":=", "range", "pathMap", "{", "params", "=", "append", "(", "params", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "k", ",", "v", ")", ")", "\n", "}", "\n", "params", "=", "append", "(", "params", ",", "\"", "\"", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "params", ",", "\"", "\"", ")", ",", "goOut", ")", ")", "\n\n", "for", "_", ",", "f", ":=", "range", "protoFiles", "{", "// We must prepend an go-style absolute path to the filename otherwise", "// protoc will complain that the files we specify here are not found", "// in any of proto-paths.", "//", "// We cannot specify --proto-path=. because of the following scenario:", "// we have file structure", "// - A", "// - x.proto, imports \"y.proto\"", "// - y.proto", "// - B", "// - z.proto, imports \"github.com/user/repo/A/x.proto\"", "// If cproto is executed in B, proto path does not include A, so y.proto", "// is not found.", "// The solution is to always use absolute paths.", "args", "=", "append", "(", "args", ",", "path", ".", "Join", "(", "dir", ",", "f", ")", ")", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "strings", ".", "Join", "(", "args", ",", "\"", "\"", ")", ")", "\n", "protoc", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "args", "...", ")", "\n", "protoc", ".", "Stdout", "=", "os", ".", "Stdout", "\n", "protoc", ".", "Stderr", "=", "os", ".", "Stderr", "\n", "return", "outDir", ",", "protoc", ".", "Run", "(", ")", "\n", "}" ]
// compile runs protoc on protoFiles. protoFiles must be relative to dir.
[ "compile", "runs", "protoc", "on", "protoFiles", ".", "protoFiles", "must", "be", "relative", "to", "dir", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/cproto/main.go#L73-L162
9,530
luci/luci-go
grpc/cmd/cproto/main.go
findProtoFiles
func findProtoFiles(dir string) ([]string, error) { files, err := filepath.Glob(filepath.Join(dir, "*.proto")) if err != nil { return nil, err } for i, f := range files { files[i] = filepath.Base(f) } return files, err }
go
func findProtoFiles(dir string) ([]string, error) { files, err := filepath.Glob(filepath.Join(dir, "*.proto")) if err != nil { return nil, err } for i, f := range files { files[i] = filepath.Base(f) } return files, err }
[ "func", "findProtoFiles", "(", "dir", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "files", ",", "err", ":=", "filepath", ".", "Glob", "(", "filepath", ".", "Join", "(", "dir", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "i", ",", "f", ":=", "range", "files", "{", "files", "[", "i", "]", "=", "filepath", ".", "Base", "(", "f", ")", "\n", "}", "\n", "return", "files", ",", "err", "\n", "}" ]
// findProtoFiles returns .proto files in dir. The returned file paths // are relative to dir.
[ "findProtoFiles", "returns", ".", "proto", "files", "in", "dir", ".", "The", "returned", "file", "paths", "are", "relative", "to", "dir", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/cproto/main.go#L296-L306
9,531
luci/luci-go
grpc/cmd/cproto/main.go
isInPackage
func isInPackage(fileName string, pkg string) (bool, error) { dir, err := filepath.Abs(filepath.Dir(fileName)) if err != nil { return false, err } dir = path.Clean(dir) pkg = path.Clean(pkg) if !strings.HasSuffix(dir, pkg) { return false, nil } src := strings.TrimSuffix(dir, pkg) src = path.Clean(src) goPaths := strings.Split(os.Getenv("GOPATH"), string(filepath.ListSeparator)) for _, goPath := range goPaths { if filepath.Join(goPath, "src") == src { return true, nil } } return false, nil }
go
func isInPackage(fileName string, pkg string) (bool, error) { dir, err := filepath.Abs(filepath.Dir(fileName)) if err != nil { return false, err } dir = path.Clean(dir) pkg = path.Clean(pkg) if !strings.HasSuffix(dir, pkg) { return false, nil } src := strings.TrimSuffix(dir, pkg) src = path.Clean(src) goPaths := strings.Split(os.Getenv("GOPATH"), string(filepath.ListSeparator)) for _, goPath := range goPaths { if filepath.Join(goPath, "src") == src { return true, nil } } return false, nil }
[ "func", "isInPackage", "(", "fileName", "string", ",", "pkg", "string", ")", "(", "bool", ",", "error", ")", "{", "dir", ",", "err", ":=", "filepath", ".", "Abs", "(", "filepath", ".", "Dir", "(", "fileName", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "dir", "=", "path", ".", "Clean", "(", "dir", ")", "\n", "pkg", "=", "path", ".", "Clean", "(", "pkg", ")", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "dir", ",", "pkg", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "src", ":=", "strings", ".", "TrimSuffix", "(", "dir", ",", "pkg", ")", "\n", "src", "=", "path", ".", "Clean", "(", "src", ")", "\n", "goPaths", ":=", "strings", ".", "Split", "(", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "string", "(", "filepath", ".", "ListSeparator", ")", ")", "\n", "for", "_", ",", "goPath", ":=", "range", "goPaths", "{", "if", "filepath", ".", "Join", "(", "goPath", ",", "\"", "\"", ")", "==", "src", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// isInPackage returns true if the filename is a part of the package.
[ "isInPackage", "returns", "true", "if", "the", "filename", "is", "a", "part", "of", "the", "package", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/cproto/main.go#L309-L329
9,532
luci/luci-go
buildbucket/protoutil/build.go
RunDuration
func RunDuration(b *pb.Build) (duration time.Duration, ok bool) { start, startErr := ptypes.Timestamp(b.StartTime) end, endErr := ptypes.Timestamp(b.EndTime) if startErr != nil || start.IsZero() || endErr != nil || end.IsZero() { return 0, false } return end.Sub(start), true }
go
func RunDuration(b *pb.Build) (duration time.Duration, ok bool) { start, startErr := ptypes.Timestamp(b.StartTime) end, endErr := ptypes.Timestamp(b.EndTime) if startErr != nil || start.IsZero() || endErr != nil || end.IsZero() { return 0, false } return end.Sub(start), true }
[ "func", "RunDuration", "(", "b", "*", "pb", ".", "Build", ")", "(", "duration", "time", ".", "Duration", ",", "ok", "bool", ")", "{", "start", ",", "startErr", ":=", "ptypes", ".", "Timestamp", "(", "b", ".", "StartTime", ")", "\n", "end", ",", "endErr", ":=", "ptypes", ".", "Timestamp", "(", "b", ".", "EndTime", ")", "\n", "if", "startErr", "!=", "nil", "||", "start", ".", "IsZero", "(", ")", "||", "endErr", "!=", "nil", "||", "end", ".", "IsZero", "(", ")", "{", "return", "0", ",", "false", "\n", "}", "\n\n", "return", "end", ".", "Sub", "(", "start", ")", ",", "true", "\n", "}" ]
// RunDuration returns duration between build start and end.
[ "RunDuration", "returns", "duration", "between", "build", "start", "and", "end", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/protoutil/build.go#L31-L39
9,533
luci/luci-go
buildbucket/protoutil/build.go
Tags
func Tags(b *pb.Build) strpair.Map { m := make(strpair.Map, len(b.Tags)) for _, t := range b.Tags { m.Add(t.Key, t.Value) } return m }
go
func Tags(b *pb.Build) strpair.Map { m := make(strpair.Map, len(b.Tags)) for _, t := range b.Tags { m.Add(t.Key, t.Value) } return m }
[ "func", "Tags", "(", "b", "*", "pb", ".", "Build", ")", "strpair", ".", "Map", "{", "m", ":=", "make", "(", "strpair", ".", "Map", ",", "len", "(", "b", ".", "Tags", ")", ")", "\n", "for", "_", ",", "t", ":=", "range", "b", ".", "Tags", "{", "m", ".", "Add", "(", "t", ".", "Key", ",", "t", ".", "Value", ")", "\n", "}", "\n", "return", "m", "\n", "}" ]
// Tags parses b.Tags as a strpair.Map.
[ "Tags", "parses", "b", ".", "Tags", "as", "a", "strpair", ".", "Map", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/protoutil/build.go#L53-L59
9,534
luci/luci-go
scheduler/appengine/task/gitiles/gitiles.go
isInteresting
func (p *pathFilter) isInteresting(diff []*git.Commit_TreeDiff) (skip bool) { isInterestingPath := func(path string) bool { switch { case path == "": return false case p.pathExclude != nil && p.pathExclude.MatchString(path): return false default: return p.pathInclude.MatchString(path) } } for _, d := range diff { if isInterestingPath(d.GetOldPath()) || isInterestingPath(d.GetNewPath()) { return true } } return false }
go
func (p *pathFilter) isInteresting(diff []*git.Commit_TreeDiff) (skip bool) { isInterestingPath := func(path string) bool { switch { case path == "": return false case p.pathExclude != nil && p.pathExclude.MatchString(path): return false default: return p.pathInclude.MatchString(path) } } for _, d := range diff { if isInterestingPath(d.GetOldPath()) || isInterestingPath(d.GetNewPath()) { return true } } return false }
[ "func", "(", "p", "*", "pathFilter", ")", "isInteresting", "(", "diff", "[", "]", "*", "git", ".", "Commit_TreeDiff", ")", "(", "skip", "bool", ")", "{", "isInterestingPath", ":=", "func", "(", "path", "string", ")", "bool", "{", "switch", "{", "case", "path", "==", "\"", "\"", ":", "return", "false", "\n", "case", "p", ".", "pathExclude", "!=", "nil", "&&", "p", ".", "pathExclude", ".", "MatchString", "(", "path", ")", ":", "return", "false", "\n", "default", ":", "return", "p", ".", "pathInclude", ".", "MatchString", "(", "path", ")", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "d", ":=", "range", "diff", "{", "if", "isInterestingPath", "(", "d", ".", "GetOldPath", "(", ")", ")", "||", "isInterestingPath", "(", "d", ".", "GetNewPath", "(", ")", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isInteresting decides whether commit is interesting according to pathFilter // based on which files were touched in commits.
[ "isInteresting", "decides", "whether", "commit", "is", "interesting", "according", "to", "pathFilter", "based", "on", "which", "files", "were", "touched", "in", "commits", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/task/gitiles/gitiles.go#L556-L574
9,535
luci/luci-go
lucicfg/sequence.go
next
func (s *sequences) next(seq string) int { if s.s == nil { s.s = make(map[string]int, 1) } v := s.s[seq] + 1 s.s[seq] = v return v }
go
func (s *sequences) next(seq string) int { if s.s == nil { s.s = make(map[string]int, 1) } v := s.s[seq] + 1 s.s[seq] = v return v }
[ "func", "(", "s", "*", "sequences", ")", "next", "(", "seq", "string", ")", "int", "{", "if", "s", ".", "s", "==", "nil", "{", "s", ".", "s", "=", "make", "(", "map", "[", "string", "]", "int", ",", "1", ")", "\n", "}", "\n", "v", ":=", "s", ".", "s", "[", "seq", "]", "+", "1", "\n", "s", ".", "s", "[", "seq", "]", "=", "v", "\n", "return", "v", "\n", "}" ]
// next returns the next number in the given sequence. // // Sequences start with 1.
[ "next", "returns", "the", "next", "number", "in", "the", "given", "sequence", ".", "Sequences", "start", "with", "1", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/sequence.go#L29-L36
9,536
luci/luci-go
cipd/client/cipd/pkg/installmode.go
PickInstallMode
func PickInstallMode(im InstallMode) (InstallMode, error) { switch { case runtime.GOOS == "windows": return InstallModeCopy, nil // Windows supports only 'copy' mode case im == "": return InstallModeSymlink, nil // default on other platforms } if err := ValidateInstallMode(im); err != nil { return "", err } return im, nil }
go
func PickInstallMode(im InstallMode) (InstallMode, error) { switch { case runtime.GOOS == "windows": return InstallModeCopy, nil // Windows supports only 'copy' mode case im == "": return InstallModeSymlink, nil // default on other platforms } if err := ValidateInstallMode(im); err != nil { return "", err } return im, nil }
[ "func", "PickInstallMode", "(", "im", "InstallMode", ")", "(", "InstallMode", ",", "error", ")", "{", "switch", "{", "case", "runtime", ".", "GOOS", "==", "\"", "\"", ":", "return", "InstallModeCopy", ",", "nil", "// Windows supports only 'copy' mode", "\n", "case", "im", "==", "\"", "\"", ":", "return", "InstallModeSymlink", ",", "nil", "// default on other platforms", "\n", "}", "\n", "if", "err", ":=", "ValidateInstallMode", "(", "im", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "im", ",", "nil", "\n", "}" ]
// PickInstallMode validates the install mode and picks the correct default // for the platform if no install mode is given.
[ "PickInstallMode", "validates", "the", "install", "mode", "and", "picks", "the", "correct", "default", "for", "the", "platform", "if", "no", "install", "mode", "is", "given", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/pkg/installmode.go#L68-L79
9,537
luci/luci-go
server/auth/oauth.go
Authenticate
func (m *GoogleOAuth2Method) Authenticate(c context.Context, r *http.Request) (user *User, err error) { cfg := getConfig(c) if cfg == nil || cfg.AnonymousTransport == nil { return nil, ErrNotConfigured } // Extract the access token from the Authorization header. header := r.Header.Get("Authorization") if header == "" || len(m.Scopes) == 0 { return nil, nil // this method is not applicable } accessToken, err := accessTokenFromHeader(header) if err != nil { return nil, err } // Store only the token hash in the cache, so that if a memory or cache dump // ever occurs, the tokens themselves aren't included in it. h := sha256.Sum256([]byte(accessToken)) cacheKey := hex.EncodeToString(h[:]) // Verify the token or grab a result of previous verification. We cache both // good and bad tokens. Note that bad token can't turn into good with passage // of time, so its OK to cache it. // // TODO(vadimsh): Strictly speaking we need to store bad tokens in a separate // cache, so a flood of bad tokens don't evict good tokens from the process // cache. cached, err := oauthChecksCache.GetOrCreate(c, cacheKey, func() (interface{}, time.Duration, error) { switch user, exp, err := m.authenticateAgainstGoogle(c, cfg, accessToken); { case transient.Tag.In(err): logging.WithError(err).Errorf(c, "oauth: Transient error when checking the token") return nil, 0, err case err != nil: // Cache the fact that the token is bad for 30 min. No need to recheck it // again just to find out it is (still) bad. logging.WithError(err).Errorf(c, "oauth: Caching bad access token SHA256=%q", cacheKey) return nil, 30 * time.Minute, nil default: return user, exp, nil } }) switch { case err != nil: return nil, err // can only be a transient error case cached == nil: logging.Errorf(c, "oauth: Bad access token SHA256=%q", cacheKey) return nil, ErrBadOAuthToken } user = cached.(*User) return }
go
func (m *GoogleOAuth2Method) Authenticate(c context.Context, r *http.Request) (user *User, err error) { cfg := getConfig(c) if cfg == nil || cfg.AnonymousTransport == nil { return nil, ErrNotConfigured } // Extract the access token from the Authorization header. header := r.Header.Get("Authorization") if header == "" || len(m.Scopes) == 0 { return nil, nil // this method is not applicable } accessToken, err := accessTokenFromHeader(header) if err != nil { return nil, err } // Store only the token hash in the cache, so that if a memory or cache dump // ever occurs, the tokens themselves aren't included in it. h := sha256.Sum256([]byte(accessToken)) cacheKey := hex.EncodeToString(h[:]) // Verify the token or grab a result of previous verification. We cache both // good and bad tokens. Note that bad token can't turn into good with passage // of time, so its OK to cache it. // // TODO(vadimsh): Strictly speaking we need to store bad tokens in a separate // cache, so a flood of bad tokens don't evict good tokens from the process // cache. cached, err := oauthChecksCache.GetOrCreate(c, cacheKey, func() (interface{}, time.Duration, error) { switch user, exp, err := m.authenticateAgainstGoogle(c, cfg, accessToken); { case transient.Tag.In(err): logging.WithError(err).Errorf(c, "oauth: Transient error when checking the token") return nil, 0, err case err != nil: // Cache the fact that the token is bad for 30 min. No need to recheck it // again just to find out it is (still) bad. logging.WithError(err).Errorf(c, "oauth: Caching bad access token SHA256=%q", cacheKey) return nil, 30 * time.Minute, nil default: return user, exp, nil } }) switch { case err != nil: return nil, err // can only be a transient error case cached == nil: logging.Errorf(c, "oauth: Bad access token SHA256=%q", cacheKey) return nil, ErrBadOAuthToken } user = cached.(*User) return }
[ "func", "(", "m", "*", "GoogleOAuth2Method", ")", "Authenticate", "(", "c", "context", ".", "Context", ",", "r", "*", "http", ".", "Request", ")", "(", "user", "*", "User", ",", "err", "error", ")", "{", "cfg", ":=", "getConfig", "(", "c", ")", "\n", "if", "cfg", "==", "nil", "||", "cfg", ".", "AnonymousTransport", "==", "nil", "{", "return", "nil", ",", "ErrNotConfigured", "\n", "}", "\n\n", "// Extract the access token from the Authorization header.", "header", ":=", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "header", "==", "\"", "\"", "||", "len", "(", "m", ".", "Scopes", ")", "==", "0", "{", "return", "nil", ",", "nil", "// this method is not applicable", "\n", "}", "\n", "accessToken", ",", "err", ":=", "accessTokenFromHeader", "(", "header", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Store only the token hash in the cache, so that if a memory or cache dump", "// ever occurs, the tokens themselves aren't included in it.", "h", ":=", "sha256", ".", "Sum256", "(", "[", "]", "byte", "(", "accessToken", ")", ")", "\n", "cacheKey", ":=", "hex", ".", "EncodeToString", "(", "h", "[", ":", "]", ")", "\n\n", "// Verify the token or grab a result of previous verification. We cache both", "// good and bad tokens. Note that bad token can't turn into good with passage", "// of time, so its OK to cache it.", "//", "// TODO(vadimsh): Strictly speaking we need to store bad tokens in a separate", "// cache, so a flood of bad tokens don't evict good tokens from the process", "// cache.", "cached", ",", "err", ":=", "oauthChecksCache", ".", "GetOrCreate", "(", "c", ",", "cacheKey", ",", "func", "(", ")", "(", "interface", "{", "}", ",", "time", ".", "Duration", ",", "error", ")", "{", "switch", "user", ",", "exp", ",", "err", ":=", "m", ".", "authenticateAgainstGoogle", "(", "c", ",", "cfg", ",", "accessToken", ")", ";", "{", "case", "transient", ".", "Tag", ".", "In", "(", "err", ")", ":", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "0", ",", "err", "\n", "case", "err", "!=", "nil", ":", "// Cache the fact that the token is bad for 30 min. No need to recheck it", "// again just to find out it is (still) bad.", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "cacheKey", ")", "\n", "return", "nil", ",", "30", "*", "time", ".", "Minute", ",", "nil", "\n", "default", ":", "return", "user", ",", "exp", ",", "nil", "\n", "}", "\n", "}", ")", "\n\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "// can only be a transient error", "\n", "case", "cached", "==", "nil", ":", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "cacheKey", ")", "\n", "return", "nil", ",", "ErrBadOAuthToken", "\n", "}", "\n\n", "user", "=", "cached", ".", "(", "*", "User", ")", "\n", "return", "\n", "}" ]
// Authenticate implements Method.
[ "Authenticate", "implements", "Method", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/oauth.go#L79-L132
9,538
luci/luci-go
server/auth/oauth.go
GetUserCredentials
func (m *GoogleOAuth2Method) GetUserCredentials(c context.Context, r *http.Request) (*oauth2.Token, error) { accessToken, err := accessTokenFromHeader(r.Header.Get("Authorization")) if err != nil { return nil, err } return &oauth2.Token{ AccessToken: accessToken, TokenType: "Bearer", }, nil }
go
func (m *GoogleOAuth2Method) GetUserCredentials(c context.Context, r *http.Request) (*oauth2.Token, error) { accessToken, err := accessTokenFromHeader(r.Header.Get("Authorization")) if err != nil { return nil, err } return &oauth2.Token{ AccessToken: accessToken, TokenType: "Bearer", }, nil }
[ "func", "(", "m", "*", "GoogleOAuth2Method", ")", "GetUserCredentials", "(", "c", "context", ".", "Context", ",", "r", "*", "http", ".", "Request", ")", "(", "*", "oauth2", ".", "Token", ",", "error", ")", "{", "accessToken", ",", "err", ":=", "accessTokenFromHeader", "(", "r", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "oauth2", ".", "Token", "{", "AccessToken", ":", "accessToken", ",", "TokenType", ":", "\"", "\"", ",", "}", ",", "nil", "\n", "}" ]
// GetUserCredentials implements UserCredentialsGetter.
[ "GetUserCredentials", "implements", "UserCredentialsGetter", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/oauth.go#L135-L144
9,539
luci/luci-go
milo/buildsource/swarming/build.go
addBuilderLink
func addBuilderLink(c context.Context, build *ui.MiloBuildLegacy, tags strpair.Map) { bucket := tags.Get("buildbucket_bucket") builder := tags.Get("builder") project := tags.Get("luci_project") if bucket != "" && builder != "" { builderParts := strings.Split(builder, "/") builder = builderParts[len(builderParts)-1] build.Summary.ParentLabel = ui.NewLink( builder, fmt.Sprintf("/p/%s/builders/%s/%s", project, bucket, builder), fmt.Sprintf("buildbucket builder %s on bucket %s", builder, bucket)) } }
go
func addBuilderLink(c context.Context, build *ui.MiloBuildLegacy, tags strpair.Map) { bucket := tags.Get("buildbucket_bucket") builder := tags.Get("builder") project := tags.Get("luci_project") if bucket != "" && builder != "" { builderParts := strings.Split(builder, "/") builder = builderParts[len(builderParts)-1] build.Summary.ParentLabel = ui.NewLink( builder, fmt.Sprintf("/p/%s/builders/%s/%s", project, bucket, builder), fmt.Sprintf("buildbucket builder %s on bucket %s", builder, bucket)) } }
[ "func", "addBuilderLink", "(", "c", "context", ".", "Context", ",", "build", "*", "ui", ".", "MiloBuildLegacy", ",", "tags", "strpair", ".", "Map", ")", "{", "bucket", ":=", "tags", ".", "Get", "(", "\"", "\"", ")", "\n", "builder", ":=", "tags", ".", "Get", "(", "\"", "\"", ")", "\n", "project", ":=", "tags", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "bucket", "!=", "\"", "\"", "&&", "builder", "!=", "\"", "\"", "{", "builderParts", ":=", "strings", ".", "Split", "(", "builder", ",", "\"", "\"", ")", "\n", "builder", "=", "builderParts", "[", "len", "(", "builderParts", ")", "-", "1", "]", "\n", "build", ".", "Summary", ".", "ParentLabel", "=", "ui", ".", "NewLink", "(", "builder", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "project", ",", "bucket", ",", "builder", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "builder", ",", "bucket", ")", ")", "\n", "}", "\n", "}" ]
// addBuilderLink adds a link to the buildbucket builder view.
[ "addBuilderLink", "adds", "a", "link", "to", "the", "buildbucket", "builder", "view", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L264-L275
9,540
luci/luci-go
milo/buildsource/swarming/build.go
AddBanner
func AddBanner(build *ui.MiloBuildLegacy, tags strpair.Map) { os := tags.Get("os") parts := strings.SplitN(os, "-", 2) var ver string if len(parts) == 2 { os = parts[0] ver = parts[1] } var base ui.LogoBase switch os { case "Ubuntu": base = ui.Ubuntu case "Windows": base = ui.Windows case "Mac": base = ui.OSX case "Android": base = ui.Android default: return } build.Summary.Banner = &ui.LogoBanner{ OS: []ui.Logo{{ LogoBase: base, Subtitle: ver, Count: 1, }}, } }
go
func AddBanner(build *ui.MiloBuildLegacy, tags strpair.Map) { os := tags.Get("os") parts := strings.SplitN(os, "-", 2) var ver string if len(parts) == 2 { os = parts[0] ver = parts[1] } var base ui.LogoBase switch os { case "Ubuntu": base = ui.Ubuntu case "Windows": base = ui.Windows case "Mac": base = ui.OSX case "Android": base = ui.Android default: return } build.Summary.Banner = &ui.LogoBanner{ OS: []ui.Logo{{ LogoBase: base, Subtitle: ver, Count: 1, }}, } }
[ "func", "AddBanner", "(", "build", "*", "ui", ".", "MiloBuildLegacy", ",", "tags", "strpair", ".", "Map", ")", "{", "os", ":=", "tags", ".", "Get", "(", "\"", "\"", ")", "\n", "parts", ":=", "strings", ".", "SplitN", "(", "os", ",", "\"", "\"", ",", "2", ")", "\n", "var", "ver", "string", "\n", "if", "len", "(", "parts", ")", "==", "2", "{", "os", "=", "parts", "[", "0", "]", "\n", "ver", "=", "parts", "[", "1", "]", "\n", "}", "\n\n", "var", "base", "ui", ".", "LogoBase", "\n", "switch", "os", "{", "case", "\"", "\"", ":", "base", "=", "ui", ".", "Ubuntu", "\n", "case", "\"", "\"", ":", "base", "=", "ui", ".", "Windows", "\n", "case", "\"", "\"", ":", "base", "=", "ui", ".", "OSX", "\n", "case", "\"", "\"", ":", "base", "=", "ui", ".", "Android", "\n", "default", ":", "return", "\n", "}", "\n", "build", ".", "Summary", ".", "Banner", "=", "&", "ui", ".", "LogoBanner", "{", "OS", ":", "[", "]", "ui", ".", "Logo", "{", "{", "LogoBase", ":", "base", ",", "Subtitle", ":", "ver", ",", "Count", ":", "1", ",", "}", "}", ",", "}", "\n", "}" ]
// AddBanner adds an OS banner derived from "os" swarming tag, if present.
[ "AddBanner", "adds", "an", "OS", "banner", "derived", "from", "os", "swarming", "tag", "if", "present", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L278-L307
9,541
luci/luci-go
milo/buildsource/swarming/build.go
addTaskToMiloStep
func addTaskToMiloStep(c context.Context, host string, sr *swarming.SwarmingRpcsTaskResult, step *miloProto.Step) error { step.Link = &miloProto.Link{ Label: "Task " + sr.TaskId, Value: &miloProto.Link_Url{ Url: TaskPageURL(host, sr.TaskId).String(), }, } switch sr.State { case TaskRunning: step.Status = miloProto.Status_RUNNING case TaskPending: step.Status = miloProto.Status_PENDING case TaskExpired, TaskTimedOut, TaskBotDied: step.Status = miloProto.Status_FAILURE switch sr.State { case TaskExpired: step.FailureDetails = &miloProto.FailureDetails{ Type: miloProto.FailureDetails_EXPIRED, Text: "Task expired", } case TaskTimedOut: step.FailureDetails = &miloProto.FailureDetails{ Type: miloProto.FailureDetails_INFRA, Text: "Task timed out", } case TaskBotDied: step.FailureDetails = &miloProto.FailureDetails{ Type: miloProto.FailureDetails_INFRA, Text: "Bot died", } } case TaskCanceled, TaskKilled: // Cancelled build is user action, so it is not an infra failure. step.Status = miloProto.Status_FAILURE step.FailureDetails = &miloProto.FailureDetails{ Type: miloProto.FailureDetails_CANCELLED, Text: "Task cancelled by user", } case TaskNoResource: step.Status = miloProto.Status_FAILURE step.FailureDetails = &miloProto.FailureDetails{ Type: miloProto.FailureDetails_EXPIRED, Text: "No resource available on Swarming", } case TaskCompleted: switch { case sr.InternalFailure: step.Status = miloProto.Status_FAILURE step.FailureDetails = &miloProto.FailureDetails{ Type: miloProto.FailureDetails_INFRA, } case sr.Failure: step.Status = miloProto.Status_FAILURE default: step.Status = miloProto.Status_SUCCESS } default: return fmt.Errorf("unknown swarming task state %q", sr.State) } // Compute start and finished times. if sr.StartedTs != "" { ts, err := time.Parse(SwarmingTimeLayout, sr.StartedTs) if err != nil { return fmt.Errorf("invalid task StartedTs: %s", err) } step.Started, _ = ptypes.TimestampProto(ts) } if sr.CompletedTs != "" { ts, err := time.Parse(SwarmingTimeLayout, sr.CompletedTs) if err != nil { return fmt.Errorf("invalid task CompletedTs: %s", err) } step.Ended, _ = ptypes.TimestampProto(ts) } return nil }
go
func addTaskToMiloStep(c context.Context, host string, sr *swarming.SwarmingRpcsTaskResult, step *miloProto.Step) error { step.Link = &miloProto.Link{ Label: "Task " + sr.TaskId, Value: &miloProto.Link_Url{ Url: TaskPageURL(host, sr.TaskId).String(), }, } switch sr.State { case TaskRunning: step.Status = miloProto.Status_RUNNING case TaskPending: step.Status = miloProto.Status_PENDING case TaskExpired, TaskTimedOut, TaskBotDied: step.Status = miloProto.Status_FAILURE switch sr.State { case TaskExpired: step.FailureDetails = &miloProto.FailureDetails{ Type: miloProto.FailureDetails_EXPIRED, Text: "Task expired", } case TaskTimedOut: step.FailureDetails = &miloProto.FailureDetails{ Type: miloProto.FailureDetails_INFRA, Text: "Task timed out", } case TaskBotDied: step.FailureDetails = &miloProto.FailureDetails{ Type: miloProto.FailureDetails_INFRA, Text: "Bot died", } } case TaskCanceled, TaskKilled: // Cancelled build is user action, so it is not an infra failure. step.Status = miloProto.Status_FAILURE step.FailureDetails = &miloProto.FailureDetails{ Type: miloProto.FailureDetails_CANCELLED, Text: "Task cancelled by user", } case TaskNoResource: step.Status = miloProto.Status_FAILURE step.FailureDetails = &miloProto.FailureDetails{ Type: miloProto.FailureDetails_EXPIRED, Text: "No resource available on Swarming", } case TaskCompleted: switch { case sr.InternalFailure: step.Status = miloProto.Status_FAILURE step.FailureDetails = &miloProto.FailureDetails{ Type: miloProto.FailureDetails_INFRA, } case sr.Failure: step.Status = miloProto.Status_FAILURE default: step.Status = miloProto.Status_SUCCESS } default: return fmt.Errorf("unknown swarming task state %q", sr.State) } // Compute start and finished times. if sr.StartedTs != "" { ts, err := time.Parse(SwarmingTimeLayout, sr.StartedTs) if err != nil { return fmt.Errorf("invalid task StartedTs: %s", err) } step.Started, _ = ptypes.TimestampProto(ts) } if sr.CompletedTs != "" { ts, err := time.Parse(SwarmingTimeLayout, sr.CompletedTs) if err != nil { return fmt.Errorf("invalid task CompletedTs: %s", err) } step.Ended, _ = ptypes.TimestampProto(ts) } return nil }
[ "func", "addTaskToMiloStep", "(", "c", "context", ".", "Context", ",", "host", "string", ",", "sr", "*", "swarming", ".", "SwarmingRpcsTaskResult", ",", "step", "*", "miloProto", ".", "Step", ")", "error", "{", "step", ".", "Link", "=", "&", "miloProto", ".", "Link", "{", "Label", ":", "\"", "\"", "+", "sr", ".", "TaskId", ",", "Value", ":", "&", "miloProto", ".", "Link_Url", "{", "Url", ":", "TaskPageURL", "(", "host", ",", "sr", ".", "TaskId", ")", ".", "String", "(", ")", ",", "}", ",", "}", "\n\n", "switch", "sr", ".", "State", "{", "case", "TaskRunning", ":", "step", ".", "Status", "=", "miloProto", ".", "Status_RUNNING", "\n\n", "case", "TaskPending", ":", "step", ".", "Status", "=", "miloProto", ".", "Status_PENDING", "\n\n", "case", "TaskExpired", ",", "TaskTimedOut", ",", "TaskBotDied", ":", "step", ".", "Status", "=", "miloProto", ".", "Status_FAILURE", "\n\n", "switch", "sr", ".", "State", "{", "case", "TaskExpired", ":", "step", ".", "FailureDetails", "=", "&", "miloProto", ".", "FailureDetails", "{", "Type", ":", "miloProto", ".", "FailureDetails_EXPIRED", ",", "Text", ":", "\"", "\"", ",", "}", "\n", "case", "TaskTimedOut", ":", "step", ".", "FailureDetails", "=", "&", "miloProto", ".", "FailureDetails", "{", "Type", ":", "miloProto", ".", "FailureDetails_INFRA", ",", "Text", ":", "\"", "\"", ",", "}", "\n", "case", "TaskBotDied", ":", "step", ".", "FailureDetails", "=", "&", "miloProto", ".", "FailureDetails", "{", "Type", ":", "miloProto", ".", "FailureDetails_INFRA", ",", "Text", ":", "\"", "\"", ",", "}", "\n", "}", "\n\n", "case", "TaskCanceled", ",", "TaskKilled", ":", "// Cancelled build is user action, so it is not an infra failure.", "step", ".", "Status", "=", "miloProto", ".", "Status_FAILURE", "\n", "step", ".", "FailureDetails", "=", "&", "miloProto", ".", "FailureDetails", "{", "Type", ":", "miloProto", ".", "FailureDetails_CANCELLED", ",", "Text", ":", "\"", "\"", ",", "}", "\n\n", "case", "TaskNoResource", ":", "step", ".", "Status", "=", "miloProto", ".", "Status_FAILURE", "\n", "step", ".", "FailureDetails", "=", "&", "miloProto", ".", "FailureDetails", "{", "Type", ":", "miloProto", ".", "FailureDetails_EXPIRED", ",", "Text", ":", "\"", "\"", ",", "}", "\n\n", "case", "TaskCompleted", ":", "switch", "{", "case", "sr", ".", "InternalFailure", ":", "step", ".", "Status", "=", "miloProto", ".", "Status_FAILURE", "\n", "step", ".", "FailureDetails", "=", "&", "miloProto", ".", "FailureDetails", "{", "Type", ":", "miloProto", ".", "FailureDetails_INFRA", ",", "}", "\n\n", "case", "sr", ".", "Failure", ":", "step", ".", "Status", "=", "miloProto", ".", "Status_FAILURE", "\n\n", "default", ":", "step", ".", "Status", "=", "miloProto", ".", "Status_SUCCESS", "\n", "}", "\n\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sr", ".", "State", ")", "\n", "}", "\n\n", "// Compute start and finished times.", "if", "sr", ".", "StartedTs", "!=", "\"", "\"", "{", "ts", ",", "err", ":=", "time", ".", "Parse", "(", "SwarmingTimeLayout", ",", "sr", ".", "StartedTs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "step", ".", "Started", ",", "_", "=", "ptypes", ".", "TimestampProto", "(", "ts", ")", "\n", "}", "\n", "if", "sr", ".", "CompletedTs", "!=", "\"", "\"", "{", "ts", ",", "err", ":=", "time", ".", "Parse", "(", "SwarmingTimeLayout", ",", "sr", ".", "CompletedTs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "step", ".", "Ended", ",", "_", "=", "ptypes", ".", "TimestampProto", "(", "ts", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// addTaskToMiloStep augments a Milo Annotation Protobuf with state from the // Swarming task.
[ "addTaskToMiloStep", "augments", "a", "Milo", "Annotation", "Protobuf", "with", "state", "from", "the", "Swarming", "task", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L311-L399
9,542
luci/luci-go
milo/buildsource/swarming/build.go
AddProjectInfo
func AddProjectInfo(build *ui.MiloBuildLegacy, tags strpair.Map) { if proj := tags.Get("luci_project"); proj != "" { if build.Trigger == nil { build.Trigger = &ui.Trigger{} } build.Trigger.Project = proj } }
go
func AddProjectInfo(build *ui.MiloBuildLegacy, tags strpair.Map) { if proj := tags.Get("luci_project"); proj != "" { if build.Trigger == nil { build.Trigger = &ui.Trigger{} } build.Trigger.Project = proj } }
[ "func", "AddProjectInfo", "(", "build", "*", "ui", ".", "MiloBuildLegacy", ",", "tags", "strpair", ".", "Map", ")", "{", "if", "proj", ":=", "tags", ".", "Get", "(", "\"", "\"", ")", ";", "proj", "!=", "\"", "\"", "{", "if", "build", ".", "Trigger", "==", "nil", "{", "build", ".", "Trigger", "=", "&", "ui", ".", "Trigger", "{", "}", "\n", "}", "\n", "build", ".", "Trigger", ".", "Project", "=", "proj", "\n", "}", "\n", "}" ]
// addProjectInfo adds the luci_project swarming tag to the build.
[ "addProjectInfo", "adds", "the", "luci_project", "swarming", "tag", "to", "the", "build", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L446-L453
9,543
luci/luci-go
milo/buildsource/swarming/build.go
addPendingTiming
func addPendingTiming(c context.Context, build *ui.MiloBuildLegacy, sr *swarming.SwarmingRpcsTaskResult) { created, err := time.Parse(SwarmingTimeLayout, sr.CreatedTs) if err != nil { return } build.Summary.PendingTime = ui.NewInterval(c, created, build.Summary.ExecutionTime.Started) }
go
func addPendingTiming(c context.Context, build *ui.MiloBuildLegacy, sr *swarming.SwarmingRpcsTaskResult) { created, err := time.Parse(SwarmingTimeLayout, sr.CreatedTs) if err != nil { return } build.Summary.PendingTime = ui.NewInterval(c, created, build.Summary.ExecutionTime.Started) }
[ "func", "addPendingTiming", "(", "c", "context", ".", "Context", ",", "build", "*", "ui", ".", "MiloBuildLegacy", ",", "sr", "*", "swarming", ".", "SwarmingRpcsTaskResult", ")", "{", "created", ",", "err", ":=", "time", ".", "Parse", "(", "SwarmingTimeLayout", ",", "sr", ".", "CreatedTs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "build", ".", "Summary", ".", "PendingTime", "=", "ui", ".", "NewInterval", "(", "c", ",", "created", ",", "build", ".", "Summary", ".", "ExecutionTime", ".", "Started", ")", "\n", "}" ]
// addPendingTiming adds pending timing information to the build.
[ "addPendingTiming", "adds", "pending", "timing", "information", "to", "the", "build", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L456-L462
9,544
luci/luci-go
milo/buildsource/swarming/build.go
streamsFromAnnotatedLog
func streamsFromAnnotatedLog(ctx context.Context, log string) (*rawpresentation.Streams, error) { c := &memoryClient{} p := annotee.New(ctx, annotee.Options{ Client: c, MetadataUpdateInterval: -1, // Neverrrrrr send incr updates. Offline: true, }) is := annotee.Stream{ Reader: bytes.NewBufferString(log), Name: types.StreamName("stdout"), Annotate: true, StripAnnotations: true, } // If this ever has more than one stream then memoryClient needs to become // goroutine safe if err := p.RunStreams([]*annotee.Stream{&is}); err != nil { return nil, err } p.Finish() return c.ToLogDogStreams() }
go
func streamsFromAnnotatedLog(ctx context.Context, log string) (*rawpresentation.Streams, error) { c := &memoryClient{} p := annotee.New(ctx, annotee.Options{ Client: c, MetadataUpdateInterval: -1, // Neverrrrrr send incr updates. Offline: true, }) is := annotee.Stream{ Reader: bytes.NewBufferString(log), Name: types.StreamName("stdout"), Annotate: true, StripAnnotations: true, } // If this ever has more than one stream then memoryClient needs to become // goroutine safe if err := p.RunStreams([]*annotee.Stream{&is}); err != nil { return nil, err } p.Finish() return c.ToLogDogStreams() }
[ "func", "streamsFromAnnotatedLog", "(", "ctx", "context", ".", "Context", ",", "log", "string", ")", "(", "*", "rawpresentation", ".", "Streams", ",", "error", ")", "{", "c", ":=", "&", "memoryClient", "{", "}", "\n", "p", ":=", "annotee", ".", "New", "(", "ctx", ",", "annotee", ".", "Options", "{", "Client", ":", "c", ",", "MetadataUpdateInterval", ":", "-", "1", ",", "// Neverrrrrr send incr updates.", "Offline", ":", "true", ",", "}", ")", "\n\n", "is", ":=", "annotee", ".", "Stream", "{", "Reader", ":", "bytes", ".", "NewBufferString", "(", "log", ")", ",", "Name", ":", "types", ".", "StreamName", "(", "\"", "\"", ")", ",", "Annotate", ":", "true", ",", "StripAnnotations", ":", "true", ",", "}", "\n", "// If this ever has more than one stream then memoryClient needs to become", "// goroutine safe", "if", "err", ":=", "p", ".", "RunStreams", "(", "[", "]", "*", "annotee", ".", "Stream", "{", "&", "is", "}", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "p", ".", "Finish", "(", ")", "\n", "return", "c", ".", "ToLogDogStreams", "(", ")", "\n", "}" ]
// streamsFromAnnotatedLog takes in an annotated log and returns a fully // populated set of logdog streams
[ "streamsFromAnnotatedLog", "takes", "in", "an", "annotated", "log", "and", "returns", "a", "fully", "populated", "set", "of", "logdog", "streams" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L495-L516
9,545
luci/luci-go
milo/buildsource/swarming/build.go
failedToStart
func failedToStart(c context.Context, build *ui.MiloBuildLegacy, res *swarming.SwarmingRpcsTaskResult, host string) error { build.Summary.Status = model.InfraFailure started, err := time.Parse(SwarmingTimeLayout, res.StartedTs) if err != nil { return err } ended, err := time.Parse(SwarmingTimeLayout, res.CompletedTs) if err != nil { return err } build.Summary.ExecutionTime = ui.NewInterval(c, started, ended) infoComp := infoComponent(model.InfraFailure, "LogDog stream not found", "Job likely failed to start.") infoComp.ExecutionTime = build.Summary.ExecutionTime build.Components = append(build.Components, infoComp) return addTaskToBuild(c, host, res, build) }
go
func failedToStart(c context.Context, build *ui.MiloBuildLegacy, res *swarming.SwarmingRpcsTaskResult, host string) error { build.Summary.Status = model.InfraFailure started, err := time.Parse(SwarmingTimeLayout, res.StartedTs) if err != nil { return err } ended, err := time.Parse(SwarmingTimeLayout, res.CompletedTs) if err != nil { return err } build.Summary.ExecutionTime = ui.NewInterval(c, started, ended) infoComp := infoComponent(model.InfraFailure, "LogDog stream not found", "Job likely failed to start.") infoComp.ExecutionTime = build.Summary.ExecutionTime build.Components = append(build.Components, infoComp) return addTaskToBuild(c, host, res, build) }
[ "func", "failedToStart", "(", "c", "context", ".", "Context", ",", "build", "*", "ui", ".", "MiloBuildLegacy", ",", "res", "*", "swarming", ".", "SwarmingRpcsTaskResult", ",", "host", "string", ")", "error", "{", "build", ".", "Summary", ".", "Status", "=", "model", ".", "InfraFailure", "\n", "started", ",", "err", ":=", "time", ".", "Parse", "(", "SwarmingTimeLayout", ",", "res", ".", "StartedTs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ended", ",", "err", ":=", "time", ".", "Parse", "(", "SwarmingTimeLayout", ",", "res", ".", "CompletedTs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "build", ".", "Summary", ".", "ExecutionTime", "=", "ui", ".", "NewInterval", "(", "c", ",", "started", ",", "ended", ")", "\n", "infoComp", ":=", "infoComponent", "(", "model", ".", "InfraFailure", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "infoComp", ".", "ExecutionTime", "=", "build", ".", "Summary", ".", "ExecutionTime", "\n", "build", ".", "Components", "=", "append", "(", "build", ".", "Components", ",", "infoComp", ")", "\n", "return", "addTaskToBuild", "(", "c", ",", "host", ",", "res", ",", "build", ")", "\n", "}" ]
// failedToStart is called in the case where logdog-only mode is on but the // stream doesn't exist and the swarming job is complete. It modifies the build // to add information that would've otherwise been in the annotation stream.
[ "failedToStart", "is", "called", "in", "the", "case", "where", "logdog", "-", "only", "mode", "is", "on", "but", "the", "stream", "doesn", "t", "exist", "and", "the", "swarming", "job", "is", "complete", ".", "It", "modifies", "the", "build", "to", "add", "information", "that", "would", "ve", "otherwise", "been", "in", "the", "annotation", "stream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L521-L537
9,546
luci/luci-go
milo/buildsource/swarming/build.go
swarmingFetchMaybeLogs
func swarmingFetchMaybeLogs(c context.Context, svc SwarmingService, taskID string) ( *swarmingFetchResult, *types.StreamAddr, error) { // Fetch the data from Swarming var logDogStreamAddr *types.StreamAddr fetchParams := swarmingFetchParams{ fetchLog: true, // Cancel if LogDog annotation stream parameters are present in the tag set. taskResCallback: func(res *swarming.SwarmingRpcsTaskResult) (cancelLogs bool) { // If the build hasn't started yet, then there is no LogDog log stream to // render. switch res.State { case TaskPending, TaskExpired: return false case TaskCanceled, TaskKilled: // If the task wasn't created, then it wasn't started. if res.CreatedTs == "" { return false } } // The task started ... is it using LogDog for logging? tags := swarmingTags(res.Tags) var err error if logDogStreamAddr, err = resolveLogDogStreamAddrFromTags(tags); err != nil { logging.WithError(err).Debugf(c, "Not using LogDog annotation stream.") return false } return true }, } fr, err := swarmingFetch(c, svc, taskID, fetchParams) return fr, logDogStreamAddr, err }
go
func swarmingFetchMaybeLogs(c context.Context, svc SwarmingService, taskID string) ( *swarmingFetchResult, *types.StreamAddr, error) { // Fetch the data from Swarming var logDogStreamAddr *types.StreamAddr fetchParams := swarmingFetchParams{ fetchLog: true, // Cancel if LogDog annotation stream parameters are present in the tag set. taskResCallback: func(res *swarming.SwarmingRpcsTaskResult) (cancelLogs bool) { // If the build hasn't started yet, then there is no LogDog log stream to // render. switch res.State { case TaskPending, TaskExpired: return false case TaskCanceled, TaskKilled: // If the task wasn't created, then it wasn't started. if res.CreatedTs == "" { return false } } // The task started ... is it using LogDog for logging? tags := swarmingTags(res.Tags) var err error if logDogStreamAddr, err = resolveLogDogStreamAddrFromTags(tags); err != nil { logging.WithError(err).Debugf(c, "Not using LogDog annotation stream.") return false } return true }, } fr, err := swarmingFetch(c, svc, taskID, fetchParams) return fr, logDogStreamAddr, err }
[ "func", "swarmingFetchMaybeLogs", "(", "c", "context", ".", "Context", ",", "svc", "SwarmingService", ",", "taskID", "string", ")", "(", "*", "swarmingFetchResult", ",", "*", "types", ".", "StreamAddr", ",", "error", ")", "{", "// Fetch the data from Swarming", "var", "logDogStreamAddr", "*", "types", ".", "StreamAddr", "\n\n", "fetchParams", ":=", "swarmingFetchParams", "{", "fetchLog", ":", "true", ",", "// Cancel if LogDog annotation stream parameters are present in the tag set.", "taskResCallback", ":", "func", "(", "res", "*", "swarming", ".", "SwarmingRpcsTaskResult", ")", "(", "cancelLogs", "bool", ")", "{", "// If the build hasn't started yet, then there is no LogDog log stream to", "// render.", "switch", "res", ".", "State", "{", "case", "TaskPending", ",", "TaskExpired", ":", "return", "false", "\n\n", "case", "TaskCanceled", ",", "TaskKilled", ":", "// If the task wasn't created, then it wasn't started.", "if", "res", ".", "CreatedTs", "==", "\"", "\"", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "// The task started ... is it using LogDog for logging?", "tags", ":=", "swarmingTags", "(", "res", ".", "Tags", ")", "\n\n", "var", "err", "error", "\n", "if", "logDogStreamAddr", ",", "err", "=", "resolveLogDogStreamAddrFromTags", "(", "tags", ")", ";", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}", ",", "}", "\n", "fr", ",", "err", ":=", "swarmingFetch", "(", "c", ",", "svc", ",", "taskID", ",", "fetchParams", ")", "\n", "return", "fr", ",", "logDogStreamAddr", ",", "err", "\n", "}" ]
// swarmingFetchMaybeLogs fetches the swarming task result. It also fetches // the log iff the task is not a logdog enabled task.
[ "swarmingFetchMaybeLogs", "fetches", "the", "swarming", "task", "result", ".", "It", "also", "fetches", "the", "log", "iff", "the", "task", "is", "not", "a", "logdog", "enabled", "task", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L541-L577
9,547
luci/luci-go
milo/buildsource/swarming/build.go
addFailureSummary
func addFailureSummary(b *ui.MiloBuildLegacy) { for _, comp := range b.Components { // Add interesting information into the main summary text. if comp.Status != model.Success { b.Summary.Text = append( b.Summary.Text, fmt.Sprintf("%s %s", comp.Status, comp.Label)) } } }
go
func addFailureSummary(b *ui.MiloBuildLegacy) { for _, comp := range b.Components { // Add interesting information into the main summary text. if comp.Status != model.Success { b.Summary.Text = append( b.Summary.Text, fmt.Sprintf("%s %s", comp.Status, comp.Label)) } } }
[ "func", "addFailureSummary", "(", "b", "*", "ui", ".", "MiloBuildLegacy", ")", "{", "for", "_", ",", "comp", ":=", "range", "b", ".", "Components", "{", "// Add interesting information into the main summary text.", "if", "comp", ".", "Status", "!=", "model", ".", "Success", "{", "b", ".", "Summary", ".", "Text", "=", "append", "(", "b", ".", "Summary", ".", "Text", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "comp", ".", "Status", ",", "comp", ".", "Label", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// addFailureSummary adds failure summary information to the main status, // derivied from individual steps.
[ "addFailureSummary", "adds", "failure", "summary", "information", "to", "the", "main", "status", "derivied", "from", "individual", "steps", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L618-L626
9,548
luci/luci-go
milo/buildsource/swarming/build.go
SwarmingBuildImpl
func SwarmingBuildImpl(c context.Context, svc SwarmingService, taskID string) (*ui.MiloBuildLegacy, error) { // First, get the task result from swarming, and maybe the logs. fr, logDogStreamAddr, err := swarmingFetchMaybeLogs(c, svc, taskID) if err != nil { return nil, err } swarmingResult := fr.res // Legacy codepath - Annotations are encoded in the swarming log instead of LogDog. // TODO(hinoka): Remove this once skia moves logging to logdog/kitchen. if logDogStreamAddr == nil { taskURL := TaskPageURL(svc.GetHost(), taskID) return buildFromLogs(c, taskURL, fr) } // Create an empty build here first because we might want to add some // system-level messages. var build ui.MiloBuildLegacy // Load the build from the LogDog service. For known classes of errors, add // steps in the build presentation to explain what may be going on. step, err := rawpresentation.ReadAnnotations(c, logDogStreamAddr) switch errors.Unwrap(err) { case coordinator.ErrNoSuchStream: // The stream was not found. This could be due to one of two things: // 1. The step just started and we're just waiting for the logs // to propogage to logdog. // 2. The bootsrap on the client failed, and never sent data to logdog. // This would be evident because the swarming result would be a failure. if swarmingResult.State == TaskCompleted { err = failedToStart(c, &build, swarmingResult, svc.GetHost()) return &build, err } logging.WithError(err).Errorf(c, "User cannot access stream.") build.Components = append(build.Components, infoComponent(model.Running, "Waiting...", "waiting for annotation stream")) case coordinator.ErrNoAccess: logging.WithError(err).Errorf(c, "User cannot access stream.") build.Components = append(build.Components, infoComponent(model.Failure, "No Access", "no access to annotation stream")) case nil: // continue default: logging.WithError(err).Errorf(c, "Failed to load LogDog annotation stream.") build.Components = append(build.Components, infoComponent(model.InfraFailure, "Error", "failed to load annotation stream: "+err.Error())) } // Skip these steps if the LogDog stream doesn't exist. // i.e. when the stream isn't ready yet, or errored out. if step != nil { // Milo Step Proto += Swarming Result Data if err := addTaskToMiloStep(c, svc.GetHost(), swarmingResult, step); err != nil { return nil, err } // Log links are linked directly to the logdog service. This is used when // converting proto step data to resp build structs ub := rawpresentation.NewURLBuilder(logDogStreamAddr) rawpresentation.AddLogDogToBuild(c, ub, step, &build) } addFailureSummary(&build) // Milo Resp Build += Swarming Result Data // This is done for things in resp but not in step like the banner, buildset, // recipe link, bot info, title, etc. err = addTaskToBuild(c, svc.GetHost(), swarmingResult, &build) return &build, err }
go
func SwarmingBuildImpl(c context.Context, svc SwarmingService, taskID string) (*ui.MiloBuildLegacy, error) { // First, get the task result from swarming, and maybe the logs. fr, logDogStreamAddr, err := swarmingFetchMaybeLogs(c, svc, taskID) if err != nil { return nil, err } swarmingResult := fr.res // Legacy codepath - Annotations are encoded in the swarming log instead of LogDog. // TODO(hinoka): Remove this once skia moves logging to logdog/kitchen. if logDogStreamAddr == nil { taskURL := TaskPageURL(svc.GetHost(), taskID) return buildFromLogs(c, taskURL, fr) } // Create an empty build here first because we might want to add some // system-level messages. var build ui.MiloBuildLegacy // Load the build from the LogDog service. For known classes of errors, add // steps in the build presentation to explain what may be going on. step, err := rawpresentation.ReadAnnotations(c, logDogStreamAddr) switch errors.Unwrap(err) { case coordinator.ErrNoSuchStream: // The stream was not found. This could be due to one of two things: // 1. The step just started and we're just waiting for the logs // to propogage to logdog. // 2. The bootsrap on the client failed, and never sent data to logdog. // This would be evident because the swarming result would be a failure. if swarmingResult.State == TaskCompleted { err = failedToStart(c, &build, swarmingResult, svc.GetHost()) return &build, err } logging.WithError(err).Errorf(c, "User cannot access stream.") build.Components = append(build.Components, infoComponent(model.Running, "Waiting...", "waiting for annotation stream")) case coordinator.ErrNoAccess: logging.WithError(err).Errorf(c, "User cannot access stream.") build.Components = append(build.Components, infoComponent(model.Failure, "No Access", "no access to annotation stream")) case nil: // continue default: logging.WithError(err).Errorf(c, "Failed to load LogDog annotation stream.") build.Components = append(build.Components, infoComponent(model.InfraFailure, "Error", "failed to load annotation stream: "+err.Error())) } // Skip these steps if the LogDog stream doesn't exist. // i.e. when the stream isn't ready yet, or errored out. if step != nil { // Milo Step Proto += Swarming Result Data if err := addTaskToMiloStep(c, svc.GetHost(), swarmingResult, step); err != nil { return nil, err } // Log links are linked directly to the logdog service. This is used when // converting proto step data to resp build structs ub := rawpresentation.NewURLBuilder(logDogStreamAddr) rawpresentation.AddLogDogToBuild(c, ub, step, &build) } addFailureSummary(&build) // Milo Resp Build += Swarming Result Data // This is done for things in resp but not in step like the banner, buildset, // recipe link, bot info, title, etc. err = addTaskToBuild(c, svc.GetHost(), swarmingResult, &build) return &build, err }
[ "func", "SwarmingBuildImpl", "(", "c", "context", ".", "Context", ",", "svc", "SwarmingService", ",", "taskID", "string", ")", "(", "*", "ui", ".", "MiloBuildLegacy", ",", "error", ")", "{", "// First, get the task result from swarming, and maybe the logs.", "fr", ",", "logDogStreamAddr", ",", "err", ":=", "swarmingFetchMaybeLogs", "(", "c", ",", "svc", ",", "taskID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "swarmingResult", ":=", "fr", ".", "res", "\n\n", "// Legacy codepath - Annotations are encoded in the swarming log instead of LogDog.", "// TODO(hinoka): Remove this once skia moves logging to logdog/kitchen.", "if", "logDogStreamAddr", "==", "nil", "{", "taskURL", ":=", "TaskPageURL", "(", "svc", ".", "GetHost", "(", ")", ",", "taskID", ")", "\n", "return", "buildFromLogs", "(", "c", ",", "taskURL", ",", "fr", ")", "\n", "}", "\n\n", "// Create an empty build here first because we might want to add some", "// system-level messages.", "var", "build", "ui", ".", "MiloBuildLegacy", "\n\n", "// Load the build from the LogDog service. For known classes of errors, add", "// steps in the build presentation to explain what may be going on.", "step", ",", "err", ":=", "rawpresentation", ".", "ReadAnnotations", "(", "c", ",", "logDogStreamAddr", ")", "\n", "switch", "errors", ".", "Unwrap", "(", "err", ")", "{", "case", "coordinator", ".", "ErrNoSuchStream", ":", "// The stream was not found. This could be due to one of two things:", "// 1. The step just started and we're just waiting for the logs", "// to propogage to logdog.", "// 2. The bootsrap on the client failed, and never sent data to logdog.", "// This would be evident because the swarming result would be a failure.", "if", "swarmingResult", ".", "State", "==", "TaskCompleted", "{", "err", "=", "failedToStart", "(", "c", ",", "&", "build", ",", "swarmingResult", ",", "svc", ".", "GetHost", "(", ")", ")", "\n", "return", "&", "build", ",", "err", "\n", "}", "\n", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "build", ".", "Components", "=", "append", "(", "build", ".", "Components", ",", "infoComponent", "(", "model", ".", "Running", ",", "\"", "\"", ",", "\"", "\"", ")", ")", "\n\n", "case", "coordinator", ".", "ErrNoAccess", ":", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "build", ".", "Components", "=", "append", "(", "build", ".", "Components", ",", "infoComponent", "(", "model", ".", "Failure", ",", "\"", "\"", ",", "\"", "\"", ")", ")", "\n", "case", "nil", ":", "// continue", "default", ":", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "build", ".", "Components", "=", "append", "(", "build", ".", "Components", ",", "infoComponent", "(", "model", ".", "InfraFailure", ",", "\"", "\"", ",", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "\n\n", "// Skip these steps if the LogDog stream doesn't exist.", "// i.e. when the stream isn't ready yet, or errored out.", "if", "step", "!=", "nil", "{", "// Milo Step Proto += Swarming Result Data", "if", "err", ":=", "addTaskToMiloStep", "(", "c", ",", "svc", ".", "GetHost", "(", ")", ",", "swarmingResult", ",", "step", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Log links are linked directly to the logdog service. This is used when", "// converting proto step data to resp build structs", "ub", ":=", "rawpresentation", ".", "NewURLBuilder", "(", "logDogStreamAddr", ")", "\n", "rawpresentation", ".", "AddLogDogToBuild", "(", "c", ",", "ub", ",", "step", ",", "&", "build", ")", "\n", "}", "\n", "addFailureSummary", "(", "&", "build", ")", "\n\n", "// Milo Resp Build += Swarming Result Data", "// This is done for things in resp but not in step like the banner, buildset,", "// recipe link, bot info, title, etc.", "err", "=", "addTaskToBuild", "(", "c", ",", "svc", ".", "GetHost", "(", ")", ",", "swarmingResult", ",", "&", "build", ")", "\n", "return", "&", "build", ",", "err", "\n", "}" ]
// SwarmingBuildImpl fetches data from Swarming and LogDog and produces a resp.MiloBuildLegacy // representation of a build state given a Swarming TaskID.
[ "SwarmingBuildImpl", "fetches", "data", "from", "Swarming", "and", "LogDog", "and", "produces", "a", "resp", ".", "MiloBuildLegacy", "representation", "of", "a", "build", "state", "given", "a", "Swarming", "TaskID", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L630-L699
9,549
luci/luci-go
milo/buildsource/swarming/build.go
infoComponent
func infoComponent(st model.Status, label, text string) *ui.BuildComponent { return &ui.BuildComponent{ Type: ui.Summary, Label: ui.NewEmptyLink(label), Text: []string{text}, Status: st, } }
go
func infoComponent(st model.Status, label, text string) *ui.BuildComponent { return &ui.BuildComponent{ Type: ui.Summary, Label: ui.NewEmptyLink(label), Text: []string{text}, Status: st, } }
[ "func", "infoComponent", "(", "st", "model", ".", "Status", ",", "label", ",", "text", "string", ")", "*", "ui", ".", "BuildComponent", "{", "return", "&", "ui", ".", "BuildComponent", "{", "Type", ":", "ui", ".", "Summary", ",", "Label", ":", "ui", ".", "NewEmptyLink", "(", "label", ")", ",", "Text", ":", "[", "]", "string", "{", "text", "}", ",", "Status", ":", "st", ",", "}", "\n", "}" ]
// infoComponent is a helper function to return a resp build step with the // given status, label, and step text.
[ "infoComponent", "is", "a", "helper", "function", "to", "return", "a", "resp", "build", "step", "with", "the", "given", "status", "label", "and", "step", "text", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L703-L710
9,550
luci/luci-go
milo/buildsource/swarming/build.go
TaskPageURL
func TaskPageURL(swarmingHostname, taskID string) *url.URL { val := url.Values{} val.Set("id", taskID) val.Set("show_raw", "1") val.Set("wide_logs", "true") return &url.URL{ Scheme: "https", Host: swarmingHostname, Path: "task", RawQuery: val.Encode(), } }
go
func TaskPageURL(swarmingHostname, taskID string) *url.URL { val := url.Values{} val.Set("id", taskID) val.Set("show_raw", "1") val.Set("wide_logs", "true") return &url.URL{ Scheme: "https", Host: swarmingHostname, Path: "task", RawQuery: val.Encode(), } }
[ "func", "TaskPageURL", "(", "swarmingHostname", ",", "taskID", "string", ")", "*", "url", ".", "URL", "{", "val", ":=", "url", ".", "Values", "{", "}", "\n", "val", ".", "Set", "(", "\"", "\"", ",", "taskID", ")", "\n", "val", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "val", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "&", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "swarmingHostname", ",", "Path", ":", "\"", "\"", ",", "RawQuery", ":", "val", ".", "Encode", "(", ")", ",", "}", "\n", "}" ]
// TaskPageURL returns a URL to a human-consumable page of a swarming task. // Supports host aliases.
[ "TaskPageURL", "returns", "a", "URL", "to", "a", "human", "-", "consumable", "page", "of", "a", "swarming", "task", ".", "Supports", "host", "aliases", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L742-L753
9,551
luci/luci-go
milo/buildsource/swarming/build.go
getSwarmingHost
func getSwarmingHost(c context.Context, host string) (string, error) { settings := common.GetSettings(c) if settings.Swarming == nil { err := errors.New("swarming not in settings") logging.WithError(err).Errorf(c, "Go configure swarming in the settings page.") return "", err } if host == "" || host == settings.Swarming.DefaultHost { return settings.Swarming.DefaultHost, nil } // If it is specified, validate the hostname. for _, allowed := range settings.Swarming.AllowedHosts { if host == allowed { return host, nil } } return "", errors.New("unknown swarming host", grpcutil.InvalidArgumentTag) }
go
func getSwarmingHost(c context.Context, host string) (string, error) { settings := common.GetSettings(c) if settings.Swarming == nil { err := errors.New("swarming not in settings") logging.WithError(err).Errorf(c, "Go configure swarming in the settings page.") return "", err } if host == "" || host == settings.Swarming.DefaultHost { return settings.Swarming.DefaultHost, nil } // If it is specified, validate the hostname. for _, allowed := range settings.Swarming.AllowedHosts { if host == allowed { return host, nil } } return "", errors.New("unknown swarming host", grpcutil.InvalidArgumentTag) }
[ "func", "getSwarmingHost", "(", "c", "context", ".", "Context", ",", "host", "string", ")", "(", "string", ",", "error", ")", "{", "settings", ":=", "common", ".", "GetSettings", "(", "c", ")", "\n", "if", "settings", ".", "Swarming", "==", "nil", "{", "err", ":=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "host", "==", "\"", "\"", "||", "host", "==", "settings", ".", "Swarming", ".", "DefaultHost", "{", "return", "settings", ".", "Swarming", ".", "DefaultHost", ",", "nil", "\n", "}", "\n", "// If it is specified, validate the hostname.", "for", "_", ",", "allowed", ":=", "range", "settings", ".", "Swarming", ".", "AllowedHosts", "{", "if", "host", "==", "allowed", "{", "return", "host", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ",", "grpcutil", ".", "InvalidArgumentTag", ")", "\n", "}" ]
// getSwarmingHost returns default hostname if host is empty. // If host is not empty and not allowed, returns an error.
[ "getSwarmingHost", "returns", "default", "hostname", "if", "host", "is", "empty", ".", "If", "host", "is", "not", "empty", "and", "not", "allowed", "returns", "an", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L816-L834
9,552
luci/luci-go
milo/buildsource/swarming/build.go
GetBuild
func GetBuild(c context.Context, host, taskId string) (*ui.MiloBuildLegacy, error) { if taskId == "" { return nil, errors.New("no swarming task id", grpcutil.InvalidArgumentTag) } sf, err := NewProdService(c, host) if err != nil { return nil, err } return SwarmingBuildImpl(c, sf, taskId) }
go
func GetBuild(c context.Context, host, taskId string) (*ui.MiloBuildLegacy, error) { if taskId == "" { return nil, errors.New("no swarming task id", grpcutil.InvalidArgumentTag) } sf, err := NewProdService(c, host) if err != nil { return nil, err } return SwarmingBuildImpl(c, sf, taskId) }
[ "func", "GetBuild", "(", "c", "context", ".", "Context", ",", "host", ",", "taskId", "string", ")", "(", "*", "ui", ".", "MiloBuildLegacy", ",", "error", ")", "{", "if", "taskId", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ",", "grpcutil", ".", "InvalidArgumentTag", ")", "\n", "}", "\n\n", "sf", ",", "err", ":=", "NewProdService", "(", "c", ",", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "SwarmingBuildImpl", "(", "c", ",", "sf", ",", "taskId", ")", "\n", "}" ]
// GetBuild returns a milo build from a swarming task id.
[ "GetBuild", "returns", "a", "milo", "build", "from", "a", "swarming", "task", "id", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L837-L848
9,553
luci/luci-go
milo/buildsource/swarming/build.go
GetLog
func GetLog(c context.Context, host, taskID, logname string) (text string, closed bool, err error) { switch { case taskID == "": err = errors.New("no swarming task id", grpcutil.InvalidArgumentTag) return case logname == "": err = errors.New("no log name", grpcutil.InvalidArgumentTag) return } sf, err := NewProdService(c, host) if err != nil { return } return swarmingBuildLogImpl(c, sf, taskID, logname) }
go
func GetLog(c context.Context, host, taskID, logname string) (text string, closed bool, err error) { switch { case taskID == "": err = errors.New("no swarming task id", grpcutil.InvalidArgumentTag) return case logname == "": err = errors.New("no log name", grpcutil.InvalidArgumentTag) return } sf, err := NewProdService(c, host) if err != nil { return } return swarmingBuildLogImpl(c, sf, taskID, logname) }
[ "func", "GetLog", "(", "c", "context", ".", "Context", ",", "host", ",", "taskID", ",", "logname", "string", ")", "(", "text", "string", ",", "closed", "bool", ",", "err", "error", ")", "{", "switch", "{", "case", "taskID", "==", "\"", "\"", ":", "err", "=", "errors", ".", "New", "(", "\"", "\"", ",", "grpcutil", ".", "InvalidArgumentTag", ")", "\n", "return", "\n", "case", "logname", "==", "\"", "\"", ":", "err", "=", "errors", ".", "New", "(", "\"", "\"", ",", "grpcutil", ".", "InvalidArgumentTag", ")", "\n", "return", "\n", "}", "\n\n", "sf", ",", "err", ":=", "NewProdService", "(", "c", ",", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "return", "swarmingBuildLogImpl", "(", "c", ",", "sf", ",", "taskID", ",", "logname", ")", "\n", "}" ]
// GetLog loads a step log.
[ "GetLog", "loads", "a", "step", "log", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/build.go#L851-L867
9,554
luci/luci-go
logdog/common/storage/cache.go
HashKey
func HashKey(parts ...string) string { hash := sha256.New() bio := bufio.NewWriter(hash) // Add a full NULL-delimited key sequence segment to our hash. for i, part := range parts { // Write the separator, except for the first key. if i > 0 { if _, err := bio.WriteRune('\x00'); err != nil { panic(err) } } if _, err := bio.WriteString(part); err != nil { panic(err) } } if err := bio.Flush(); err != nil { panic(err) } // Return the hex-encoded hash sum. return hex.EncodeToString(hash.Sum(nil)) }
go
func HashKey(parts ...string) string { hash := sha256.New() bio := bufio.NewWriter(hash) // Add a full NULL-delimited key sequence segment to our hash. for i, part := range parts { // Write the separator, except for the first key. if i > 0 { if _, err := bio.WriteRune('\x00'); err != nil { panic(err) } } if _, err := bio.WriteString(part); err != nil { panic(err) } } if err := bio.Flush(); err != nil { panic(err) } // Return the hex-encoded hash sum. return hex.EncodeToString(hash.Sum(nil)) }
[ "func", "HashKey", "(", "parts", "...", "string", ")", "string", "{", "hash", ":=", "sha256", ".", "New", "(", ")", "\n", "bio", ":=", "bufio", ".", "NewWriter", "(", "hash", ")", "\n\n", "// Add a full NULL-delimited key sequence segment to our hash.", "for", "i", ",", "part", ":=", "range", "parts", "{", "// Write the separator, except for the first key.", "if", "i", ">", "0", "{", "if", "_", ",", "err", ":=", "bio", ".", "WriteRune", "(", "'\\x00'", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "bio", ".", "WriteString", "(", "part", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "bio", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n\n", "// Return the hex-encoded hash sum.", "return", "hex", ".", "EncodeToString", "(", "hash", ".", "Sum", "(", "nil", ")", ")", "\n", "}" ]
// HashKey composes a hex-encoded SHA256 string from the supplied parts. The // local schema version and KeyType are included in the hash.
[ "HashKey", "composes", "a", "hex", "-", "encoded", "SHA256", "string", "from", "the", "supplied", "parts", ".", "The", "local", "schema", "version", "and", "KeyType", "are", "included", "in", "the", "hash", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/cache.go#L65-L88
9,555
luci/luci-go
buildbucket/protoutil/tag.go
StringPairs
func StringPairs(m strpair.Map) []*pb.StringPair { ret := make([]*pb.StringPair, 0, len(m)) for k, vs := range m { for _, v := range vs { ret = append(ret, &pb.StringPair{Key: k, Value: v}) } } SortStringPairs(ret) return ret }
go
func StringPairs(m strpair.Map) []*pb.StringPair { ret := make([]*pb.StringPair, 0, len(m)) for k, vs := range m { for _, v := range vs { ret = append(ret, &pb.StringPair{Key: k, Value: v}) } } SortStringPairs(ret) return ret }
[ "func", "StringPairs", "(", "m", "strpair", ".", "Map", ")", "[", "]", "*", "pb", ".", "StringPair", "{", "ret", ":=", "make", "(", "[", "]", "*", "pb", ".", "StringPair", ",", "0", ",", "len", "(", "m", ")", ")", "\n", "for", "k", ",", "vs", ":=", "range", "m", "{", "for", "_", ",", "v", ":=", "range", "vs", "{", "ret", "=", "append", "(", "ret", ",", "&", "pb", ".", "StringPair", "{", "Key", ":", "k", ",", "Value", ":", "v", "}", ")", "\n", "}", "\n", "}", "\n", "SortStringPairs", "(", "ret", ")", "\n", "return", "ret", "\n", "}" ]
// StringPairs converts a strpair.Map to a slice of StringPair messages.
[ "StringPairs", "converts", "a", "strpair", ".", "Map", "to", "a", "slice", "of", "StringPair", "messages", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/protoutil/tag.go#L31-L40
9,556
luci/luci-go
buildbucket/protoutil/tag.go
SortStringPairs
func SortStringPairs(pairs []*pb.StringPair) { sort.Slice(pairs, func(i, j int) bool { switch { case pairs[i].Key < pairs[j].Key: return true case pairs[i].Key > pairs[j].Key: return false default: return pairs[i].Value < pairs[j].Value } }) }
go
func SortStringPairs(pairs []*pb.StringPair) { sort.Slice(pairs, func(i, j int) bool { switch { case pairs[i].Key < pairs[j].Key: return true case pairs[i].Key > pairs[j].Key: return false default: return pairs[i].Value < pairs[j].Value } }) }
[ "func", "SortStringPairs", "(", "pairs", "[", "]", "*", "pb", ".", "StringPair", ")", "{", "sort", ".", "Slice", "(", "pairs", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "switch", "{", "case", "pairs", "[", "i", "]", ".", "Key", "<", "pairs", "[", "j", "]", ".", "Key", ":", "return", "true", "\n", "case", "pairs", "[", "i", "]", ".", "Key", ">", "pairs", "[", "j", "]", ".", "Key", ":", "return", "false", "\n", "default", ":", "return", "pairs", "[", "i", "]", ".", "Value", "<", "pairs", "[", "j", "]", ".", "Value", "\n", "}", "\n", "}", ")", "\n", "}" ]
// SortStringPairs sorts string pairs.
[ "SortStringPairs", "sorts", "string", "pairs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/protoutil/tag.go#L43-L54
9,557
luci/luci-go
buildbucket/protoutil/tag.go
BuildSets
func BuildSets(b *pb.Build) []string { var result []string for _, tag := range b.Tags { if tag.Key == "buildset" { result = append(result, tag.Value) } } return result }
go
func BuildSets(b *pb.Build) []string { var result []string for _, tag := range b.Tags { if tag.Key == "buildset" { result = append(result, tag.Value) } } return result }
[ "func", "BuildSets", "(", "b", "*", "pb", ".", "Build", ")", "[", "]", "string", "{", "var", "result", "[", "]", "string", "\n", "for", "_", ",", "tag", ":=", "range", "b", ".", "Tags", "{", "if", "tag", ".", "Key", "==", "\"", "\"", "{", "result", "=", "append", "(", "result", ",", "tag", ".", "Value", ")", "\n", "}", "\n", "}", "\n", "return", "result", "\n", "}" ]
// BuildSets returns all of the buildsets of the build.
[ "BuildSets", "returns", "all", "of", "the", "buildsets", "of", "the", "build", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/protoutil/tag.go#L57-L65
9,558
luci/luci-go
cipd/client/cipd/fs/files.go
ExistingDestination
func ExistingDestination(dest string, fs FileSystem) Destination { if fs == nil { fs = NewFileSystem(filepath.Dir(dest), "") } return &fsDest{ fs: fs, dest: dest, atomic: true, // note: txnFSDest unsets this, see Begin openFiles: map[string]*os.File{}, } }
go
func ExistingDestination(dest string, fs FileSystem) Destination { if fs == nil { fs = NewFileSystem(filepath.Dir(dest), "") } return &fsDest{ fs: fs, dest: dest, atomic: true, // note: txnFSDest unsets this, see Begin openFiles: map[string]*os.File{}, } }
[ "func", "ExistingDestination", "(", "dest", "string", ",", "fs", "FileSystem", ")", "Destination", "{", "if", "fs", "==", "nil", "{", "fs", "=", "NewFileSystem", "(", "filepath", ".", "Dir", "(", "dest", ")", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "fsDest", "{", "fs", ":", "fs", ",", "dest", ":", "dest", ",", "atomic", ":", "true", ",", "// note: txnFSDest unsets this, see Begin", "openFiles", ":", "map", "[", "string", "]", "*", "os", ".", "File", "{", "}", ",", "}", "\n", "}" ]
// ExistingDestination returns an object that knows how to create files in an // existing directory in the file system. // // Will use a provided FileSystem object to operate on files if given, otherwise // uses a default one. If FileSystem is provided, dest must be in a subdirectory // of the given FileSystem root. // // Note that the returned object doesn't support transactional semantics, since // transactionally writing a bunch of files into an existing directory is hard. // // See NewDestination for writing files into a completely new directory. This // method supports transactions.
[ "ExistingDestination", "returns", "an", "object", "that", "knows", "how", "to", "create", "files", "in", "an", "existing", "directory", "in", "the", "file", "system", ".", "Will", "use", "a", "provided", "FileSystem", "object", "to", "operate", "on", "files", "if", "given", "otherwise", "uses", "a", "default", "one", ".", "If", "FileSystem", "is", "provided", "dest", "must", "be", "in", "a", "subdirectory", "of", "the", "given", "FileSystem", "root", ".", "Note", "that", "the", "returned", "object", "doesn", "t", "support", "transactional", "semantics", "since", "transactionally", "writing", "a", "bunch", "of", "files", "into", "an", "existing", "directory", "is", "hard", ".", "See", "NewDestination", "for", "writing", "files", "into", "a", "completely", "new", "directory", ".", "This", "method", "supports", "transactions", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/fs/files.go#L388-L398
9,559
luci/luci-go
cipd/client/cipd/fs/files.go
numOpenFiles
func (d *fsDest) numOpenFiles() (n int) { d.lock.RLock() n = len(d.openFiles) d.lock.RUnlock() return }
go
func (d *fsDest) numOpenFiles() (n int) { d.lock.RLock() n = len(d.openFiles) d.lock.RUnlock() return }
[ "func", "(", "d", "*", "fsDest", ")", "numOpenFiles", "(", ")", "(", "n", "int", ")", "{", "d", ".", "lock", ".", "RLock", "(", ")", "\n", "n", "=", "len", "(", "d", ".", "openFiles", ")", "\n", "d", ".", "lock", ".", "RUnlock", "(", ")", "\n", "return", "\n", "}" ]
// numOpenFiles returns a number of currently open files. // // Used by txnFSDest to make sure all files are closed before finalizing the // transaction.
[ "numOpenFiles", "returns", "a", "number", "of", "currently", "open", "files", ".", "Used", "by", "txnFSDest", "to", "make", "sure", "all", "files", "are", "closed", "before", "finalizing", "the", "transaction", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/fs/files.go#L404-L409
9,560
luci/luci-go
cipd/client/cipd/fs/files.go
prepareFilePath
func (d *fsDest) prepareFilePath(ctx context.Context, name string) (string, error) { path := filepath.Clean(filepath.Join(d.dest, filepath.FromSlash(name))) if !IsSubpath(path, d.dest) { return "", fmt.Errorf("invalid relative file name: %s", name) } if _, err := d.fs.EnsureDirectory(ctx, filepath.Dir(path)); err != nil { return "", err } return path, nil }
go
func (d *fsDest) prepareFilePath(ctx context.Context, name string) (string, error) { path := filepath.Clean(filepath.Join(d.dest, filepath.FromSlash(name))) if !IsSubpath(path, d.dest) { return "", fmt.Errorf("invalid relative file name: %s", name) } if _, err := d.fs.EnsureDirectory(ctx, filepath.Dir(path)); err != nil { return "", err } return path, nil }
[ "func", "(", "d", "*", "fsDest", ")", "prepareFilePath", "(", "ctx", "context", ".", "Context", ",", "name", "string", ")", "(", "string", ",", "error", ")", "{", "path", ":=", "filepath", ".", "Clean", "(", "filepath", ".", "Join", "(", "d", ".", "dest", ",", "filepath", ".", "FromSlash", "(", "name", ")", ")", ")", "\n", "if", "!", "IsSubpath", "(", "path", ",", "d", ".", "dest", ")", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "d", ".", "fs", ".", "EnsureDirectory", "(", "ctx", ",", "filepath", ".", "Dir", "(", "path", ")", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "path", ",", "nil", "\n", "}" ]
// prepareFilePath performs steps common to CreateFile and CreateSymlink. // // It does some validation, expands "name" to an absolute path and creates // parent directories for a future file. Returns absolute path where the file // should be put.
[ "prepareFilePath", "performs", "steps", "common", "to", "CreateFile", "and", "CreateSymlink", ".", "It", "does", "some", "validation", "expands", "name", "to", "an", "absolute", "path", "and", "creates", "parent", "directories", "for", "a", "future", "file", ".", "Returns", "absolute", "path", "where", "the", "file", "should", "be", "put", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/fs/files.go#L416-L425
9,561
luci/luci-go
server/auth/client.go
GetPerRPCCredentials
func GetPerRPCCredentials(kind RPCAuthorityKind, opts ...RPCOption) (credentials.PerRPCCredentials, error) { options, err := makeRPCOptions(kind, opts) if err != nil { return nil, err } return perRPCCreds{options}, nil }
go
func GetPerRPCCredentials(kind RPCAuthorityKind, opts ...RPCOption) (credentials.PerRPCCredentials, error) { options, err := makeRPCOptions(kind, opts) if err != nil { return nil, err } return perRPCCreds{options}, nil }
[ "func", "GetPerRPCCredentials", "(", "kind", "RPCAuthorityKind", ",", "opts", "...", "RPCOption", ")", "(", "credentials", ".", "PerRPCCredentials", ",", "error", ")", "{", "options", ",", "err", ":=", "makeRPCOptions", "(", "kind", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "perRPCCreds", "{", "options", "}", ",", "nil", "\n", "}" ]
// GetPerRPCCredentials returns gRPC's PerRPCCredentials implementation. // // It can be used to authenticate outbound gPRC RPC's.
[ "GetPerRPCCredentials", "returns", "gRPC", "s", "PerRPCCredentials", "implementation", ".", "It", "can", "be", "used", "to", "authenticate", "outbound", "gPRC", "RPC", "s", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/client.go#L318-L324
9,562
luci/luci-go
server/auth/client.go
GetTokenSource
func GetTokenSource(c context.Context, kind RPCAuthorityKind, opts ...RPCOption) (oauth2.TokenSource, error) { if kind != AsSelf && kind != AsCredentialsForwarder && kind != AsActor { return nil, fmt.Errorf("auth: GetTokenSource can only be used with AsSelf, AsCredentialsForwarder or AsActor authorization kind") } options, err := makeRPCOptions(kind, opts) if err != nil { return nil, err } if options.checkCtx != nil { if err := options.checkCtx(c); err != nil { return nil, err } } return &tokenSource{c, options}, nil }
go
func GetTokenSource(c context.Context, kind RPCAuthorityKind, opts ...RPCOption) (oauth2.TokenSource, error) { if kind != AsSelf && kind != AsCredentialsForwarder && kind != AsActor { return nil, fmt.Errorf("auth: GetTokenSource can only be used with AsSelf, AsCredentialsForwarder or AsActor authorization kind") } options, err := makeRPCOptions(kind, opts) if err != nil { return nil, err } if options.checkCtx != nil { if err := options.checkCtx(c); err != nil { return nil, err } } return &tokenSource{c, options}, nil }
[ "func", "GetTokenSource", "(", "c", "context", ".", "Context", ",", "kind", "RPCAuthorityKind", ",", "opts", "...", "RPCOption", ")", "(", "oauth2", ".", "TokenSource", ",", "error", ")", "{", "if", "kind", "!=", "AsSelf", "&&", "kind", "!=", "AsCredentialsForwarder", "&&", "kind", "!=", "AsActor", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "options", ",", "err", ":=", "makeRPCOptions", "(", "kind", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "options", ".", "checkCtx", "!=", "nil", "{", "if", "err", ":=", "options", ".", "checkCtx", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "&", "tokenSource", "{", "c", ",", "options", "}", ",", "nil", "\n", "}" ]
// GetTokenSource returns an oauth2.TokenSource bound to the supplied Context. // // Supports only AsSelf, AsCredentialsForwarder and AsActor authorization kinds, // since they are only ones that exclusively use OAuth2 tokens and no other // extra headers. // // While GetPerRPCCredentials is preferred, this can be used by packages that // cannot or do not properly handle this gRPC option.
[ "GetTokenSource", "returns", "an", "oauth2", ".", "TokenSource", "bound", "to", "the", "supplied", "Context", ".", "Supports", "only", "AsSelf", "AsCredentialsForwarder", "and", "AsActor", "authorization", "kinds", "since", "they", "are", "only", "ones", "that", "exclusively", "use", "OAuth2", "tokens", "and", "no", "other", "extra", "headers", ".", "While", "GetPerRPCCredentials", "is", "preferred", "this", "can", "be", "used", "by", "packages", "that", "cannot", "or", "do", "not", "properly", "handle", "this", "gRPC", "option", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/client.go#L363-L377
9,563
luci/luci-go
server/auth/client.go
tokenFingerprint
func tokenFingerprint(tok string) string { digest := sha256.Sum256([]byte(tok)) return hex.EncodeToString(digest[:16]) }
go
func tokenFingerprint(tok string) string { digest := sha256.Sum256([]byte(tok)) return hex.EncodeToString(digest[:16]) }
[ "func", "tokenFingerprint", "(", "tok", "string", ")", "string", "{", "digest", ":=", "sha256", ".", "Sum256", "(", "[", "]", "byte", "(", "tok", ")", ")", "\n", "return", "hex", ".", "EncodeToString", "(", "digest", "[", ":", "16", "]", ")", "\n", "}" ]
// tokenFingerprint returns first 16 bytes of SHA256 of the token, as hex. // // Token fingerprints can be used to identify tokens without parsing them.
[ "tokenFingerprint", "returns", "first", "16", "bytes", "of", "SHA256", "of", "the", "token", "as", "hex", ".", "Token", "fingerprints", "can", "be", "used", "to", "identify", "tokens", "without", "parsing", "them", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/client.go#L426-L429
9,564
luci/luci-go
server/auth/client.go
makeRPCOptions
func makeRPCOptions(kind RPCAuthorityKind, opts []RPCOption) (*rpcOptions, error) { options := &rpcOptions{kind: kind} for _, o := range opts { o.apply(options) } // Set default scopes. asSelfOrActorOrProject := options.kind == AsSelf || options.kind == AsActor || options.kind == AsProject if asSelfOrActorOrProject && len(options.scopes) == 0 { options.scopes = defaultOAuthScopes } // Validate options. if !asSelfOrActorOrProject && len(options.scopes) != 0 { return nil, fmt.Errorf("auth: WithScopes can only be used with AsSelf or AsActor authorization kind") } if options.serviceAccount != "" && options.kind != AsActor { return nil, fmt.Errorf("auth: WithServiceAccount can only be used with AsActor authorization kind") } if options.serviceAccount == "" && options.kind == AsActor { return nil, fmt.Errorf("auth: AsActor authorization kind requires WithServiceAccount option") } if options.delegationToken != "" && options.kind != AsUser { return nil, fmt.Errorf("auth: WithDelegationToken can only be used with AsUser authorization kind") } if len(options.delegationTags) != 0 && options.kind != AsUser { return nil, fmt.Errorf("auth: WithDelegationTags can only be used with AsUser authorization kind") } if len(options.delegationTags) != 0 && options.delegationToken != "" { return nil, fmt.Errorf("auth: WithDelegationTags and WithDelegationToken cannot be used together") } if options.project == "" && options.kind == AsProject { return nil, fmt.Errorf("auth: AsProject authorization kind requires WithProject option") } // Validate 'kind' and pick correct implementation of getRPCHeaders. switch options.kind { case NoAuth: options.getRPCHeaders = noAuthHeaders case AsSelf: options.getRPCHeaders = asSelfHeaders case AsUser: options.getRPCHeaders = asUserHeaders case AsCredentialsForwarder: options.checkCtx = func(c context.Context) error { _, err := forwardedCreds(c) return err } options.getRPCHeaders = func(c context.Context, _ string, _ *rpcOptions) (*oauth2.Token, map[string]string, error) { tok, err := forwardedCreds(c) return tok, nil, err } case AsActor: options.getRPCHeaders = asActorHeaders case AsProject: options.getRPCHeaders = asProjectHeaders default: return nil, fmt.Errorf("auth: unknown RPCAuthorityKind %d", options.kind) } // Default value for "client" field in monitoring metrics. if options.monitoringClient == "" { options.monitoringClient = "luci-go-server" } return options, nil }
go
func makeRPCOptions(kind RPCAuthorityKind, opts []RPCOption) (*rpcOptions, error) { options := &rpcOptions{kind: kind} for _, o := range opts { o.apply(options) } // Set default scopes. asSelfOrActorOrProject := options.kind == AsSelf || options.kind == AsActor || options.kind == AsProject if asSelfOrActorOrProject && len(options.scopes) == 0 { options.scopes = defaultOAuthScopes } // Validate options. if !asSelfOrActorOrProject && len(options.scopes) != 0 { return nil, fmt.Errorf("auth: WithScopes can only be used with AsSelf or AsActor authorization kind") } if options.serviceAccount != "" && options.kind != AsActor { return nil, fmt.Errorf("auth: WithServiceAccount can only be used with AsActor authorization kind") } if options.serviceAccount == "" && options.kind == AsActor { return nil, fmt.Errorf("auth: AsActor authorization kind requires WithServiceAccount option") } if options.delegationToken != "" && options.kind != AsUser { return nil, fmt.Errorf("auth: WithDelegationToken can only be used with AsUser authorization kind") } if len(options.delegationTags) != 0 && options.kind != AsUser { return nil, fmt.Errorf("auth: WithDelegationTags can only be used with AsUser authorization kind") } if len(options.delegationTags) != 0 && options.delegationToken != "" { return nil, fmt.Errorf("auth: WithDelegationTags and WithDelegationToken cannot be used together") } if options.project == "" && options.kind == AsProject { return nil, fmt.Errorf("auth: AsProject authorization kind requires WithProject option") } // Validate 'kind' and pick correct implementation of getRPCHeaders. switch options.kind { case NoAuth: options.getRPCHeaders = noAuthHeaders case AsSelf: options.getRPCHeaders = asSelfHeaders case AsUser: options.getRPCHeaders = asUserHeaders case AsCredentialsForwarder: options.checkCtx = func(c context.Context) error { _, err := forwardedCreds(c) return err } options.getRPCHeaders = func(c context.Context, _ string, _ *rpcOptions) (*oauth2.Token, map[string]string, error) { tok, err := forwardedCreds(c) return tok, nil, err } case AsActor: options.getRPCHeaders = asActorHeaders case AsProject: options.getRPCHeaders = asProjectHeaders default: return nil, fmt.Errorf("auth: unknown RPCAuthorityKind %d", options.kind) } // Default value for "client" field in monitoring metrics. if options.monitoringClient == "" { options.monitoringClient = "luci-go-server" } return options, nil }
[ "func", "makeRPCOptions", "(", "kind", "RPCAuthorityKind", ",", "opts", "[", "]", "RPCOption", ")", "(", "*", "rpcOptions", ",", "error", ")", "{", "options", ":=", "&", "rpcOptions", "{", "kind", ":", "kind", "}", "\n", "for", "_", ",", "o", ":=", "range", "opts", "{", "o", ".", "apply", "(", "options", ")", "\n", "}", "\n\n", "// Set default scopes.", "asSelfOrActorOrProject", ":=", "options", ".", "kind", "==", "AsSelf", "||", "options", ".", "kind", "==", "AsActor", "||", "options", ".", "kind", "==", "AsProject", "\n", "if", "asSelfOrActorOrProject", "&&", "len", "(", "options", ".", "scopes", ")", "==", "0", "{", "options", ".", "scopes", "=", "defaultOAuthScopes", "\n", "}", "\n\n", "// Validate options.", "if", "!", "asSelfOrActorOrProject", "&&", "len", "(", "options", ".", "scopes", ")", "!=", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "options", ".", "serviceAccount", "!=", "\"", "\"", "&&", "options", ".", "kind", "!=", "AsActor", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "options", ".", "serviceAccount", "==", "\"", "\"", "&&", "options", ".", "kind", "==", "AsActor", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "options", ".", "delegationToken", "!=", "\"", "\"", "&&", "options", ".", "kind", "!=", "AsUser", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "options", ".", "delegationTags", ")", "!=", "0", "&&", "options", ".", "kind", "!=", "AsUser", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "options", ".", "delegationTags", ")", "!=", "0", "&&", "options", ".", "delegationToken", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "options", ".", "project", "==", "\"", "\"", "&&", "options", ".", "kind", "==", "AsProject", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Validate 'kind' and pick correct implementation of getRPCHeaders.", "switch", "options", ".", "kind", "{", "case", "NoAuth", ":", "options", ".", "getRPCHeaders", "=", "noAuthHeaders", "\n", "case", "AsSelf", ":", "options", ".", "getRPCHeaders", "=", "asSelfHeaders", "\n", "case", "AsUser", ":", "options", ".", "getRPCHeaders", "=", "asUserHeaders", "\n", "case", "AsCredentialsForwarder", ":", "options", ".", "checkCtx", "=", "func", "(", "c", "context", ".", "Context", ")", "error", "{", "_", ",", "err", ":=", "forwardedCreds", "(", "c", ")", "\n", "return", "err", "\n", "}", "\n", "options", ".", "getRPCHeaders", "=", "func", "(", "c", "context", ".", "Context", ",", "_", "string", ",", "_", "*", "rpcOptions", ")", "(", "*", "oauth2", ".", "Token", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "tok", ",", "err", ":=", "forwardedCreds", "(", "c", ")", "\n", "return", "tok", ",", "nil", ",", "err", "\n", "}", "\n", "case", "AsActor", ":", "options", ".", "getRPCHeaders", "=", "asActorHeaders", "\n", "case", "AsProject", ":", "options", ".", "getRPCHeaders", "=", "asProjectHeaders", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "options", ".", "kind", ")", "\n", "}", "\n\n", "// Default value for \"client\" field in monitoring metrics.", "if", "options", ".", "monitoringClient", "==", "\"", "\"", "{", "options", ".", "monitoringClient", "=", "\"", "\"", "\n", "}", "\n\n", "return", "options", ",", "nil", "\n", "}" ]
// makeRPCOptions applies all options and validates them.
[ "makeRPCOptions", "applies", "all", "options", "and", "validates", "them", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/client.go#L463-L529
9,565
luci/luci-go
server/auth/client.go
noAuthHeaders
func noAuthHeaders(c context.Context, uri string, opts *rpcOptions) (*oauth2.Token, map[string]string, error) { return nil, nil, nil }
go
func noAuthHeaders(c context.Context, uri string, opts *rpcOptions) (*oauth2.Token, map[string]string, error) { return nil, nil, nil }
[ "func", "noAuthHeaders", "(", "c", "context", ".", "Context", ",", "uri", "string", ",", "opts", "*", "rpcOptions", ")", "(", "*", "oauth2", ".", "Token", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "return", "nil", ",", "nil", ",", "nil", "\n", "}" ]
// noAuthHeaders is getRPCHeaders for NoAuth mode.
[ "noAuthHeaders", "is", "getRPCHeaders", "for", "NoAuth", "mode", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/client.go#L532-L534
9,566
luci/luci-go
server/auth/client.go
asSelfHeaders
func asSelfHeaders(c context.Context, uri string, opts *rpcOptions) (*oauth2.Token, map[string]string, error) { cfg := getConfig(c) if cfg == nil || cfg.AccessTokenProvider == nil { return nil, nil, ErrNotConfigured } tok, err := cfg.AccessTokenProvider(c, opts.scopes) return tok, nil, err }
go
func asSelfHeaders(c context.Context, uri string, opts *rpcOptions) (*oauth2.Token, map[string]string, error) { cfg := getConfig(c) if cfg == nil || cfg.AccessTokenProvider == nil { return nil, nil, ErrNotConfigured } tok, err := cfg.AccessTokenProvider(c, opts.scopes) return tok, nil, err }
[ "func", "asSelfHeaders", "(", "c", "context", ".", "Context", ",", "uri", "string", ",", "opts", "*", "rpcOptions", ")", "(", "*", "oauth2", ".", "Token", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "cfg", ":=", "getConfig", "(", "c", ")", "\n", "if", "cfg", "==", "nil", "||", "cfg", ".", "AccessTokenProvider", "==", "nil", "{", "return", "nil", ",", "nil", ",", "ErrNotConfigured", "\n", "}", "\n", "tok", ",", "err", ":=", "cfg", ".", "AccessTokenProvider", "(", "c", ",", "opts", ".", "scopes", ")", "\n", "return", "tok", ",", "nil", ",", "err", "\n", "}" ]
// asSelfHeaders returns a map of authentication headers to add to outbound // RPC requests done in AsSelf mode. // // This will be called by the transport layer on each request.
[ "asSelfHeaders", "returns", "a", "map", "of", "authentication", "headers", "to", "add", "to", "outbound", "RPC", "requests", "done", "in", "AsSelf", "mode", ".", "This", "will", "be", "called", "by", "the", "transport", "layer", "on", "each", "request", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/client.go#L540-L547
9,567
luci/luci-go
server/auth/client.go
asUserHeaders
func asUserHeaders(c context.Context, uri string, opts *rpcOptions) (*oauth2.Token, map[string]string, error) { cfg := getConfig(c) if cfg == nil || cfg.AccessTokenProvider == nil { return nil, nil, ErrNotConfigured } delegationToken := "" if opts.delegationToken != "" { delegationToken = opts.delegationToken // WithDelegationToken was used } else { // Outbound RPC calls in the context of a request from anonymous caller are // anonymous too. No need to use any authentication headers. userIdent := CurrentIdentity(c) if userIdent == identity.AnonymousIdentity { return nil, nil, nil } // Grab root URL of the destination service. Only https:// are allowed. uri = strings.ToLower(uri) if !strings.HasPrefix(uri, "https://") { return nil, nil, fmt.Errorf("auth: refusing to use delegation tokens with non-https URL") } host := uri[len("https://"):] if idx := strings.IndexRune(host, '/'); idx != -1 { host = host[:idx] } // Grab a token that's good enough for at least 10 min. Outbound RPCs // shouldn't last longer than that. mintTokenCall := MintDelegationToken if opts.rpcMocks != nil && opts.rpcMocks.MintDelegationToken != nil { mintTokenCall = opts.rpcMocks.MintDelegationToken } tok, err := mintTokenCall(c, DelegationTokenParams{ TargetHost: host, Tags: opts.delegationTags, MinTTL: 10 * time.Minute, }) if err != nil { return nil, nil, err } delegationToken = tok.Token } // Use our own OAuth token too, since the delegation token is bound to us. oauthTok, err := cfg.AccessTokenProvider(c, []string{auth.OAuthScopeEmail}) if err != nil { return nil, nil, err } logging.Fields{ "fingerprint": tokenFingerprint(delegationToken), }.Debugf(c, "auth: Sending delegation token") return oauthTok, map[string]string{delegation.HTTPHeaderName: delegationToken}, nil }
go
func asUserHeaders(c context.Context, uri string, opts *rpcOptions) (*oauth2.Token, map[string]string, error) { cfg := getConfig(c) if cfg == nil || cfg.AccessTokenProvider == nil { return nil, nil, ErrNotConfigured } delegationToken := "" if opts.delegationToken != "" { delegationToken = opts.delegationToken // WithDelegationToken was used } else { // Outbound RPC calls in the context of a request from anonymous caller are // anonymous too. No need to use any authentication headers. userIdent := CurrentIdentity(c) if userIdent == identity.AnonymousIdentity { return nil, nil, nil } // Grab root URL of the destination service. Only https:// are allowed. uri = strings.ToLower(uri) if !strings.HasPrefix(uri, "https://") { return nil, nil, fmt.Errorf("auth: refusing to use delegation tokens with non-https URL") } host := uri[len("https://"):] if idx := strings.IndexRune(host, '/'); idx != -1 { host = host[:idx] } // Grab a token that's good enough for at least 10 min. Outbound RPCs // shouldn't last longer than that. mintTokenCall := MintDelegationToken if opts.rpcMocks != nil && opts.rpcMocks.MintDelegationToken != nil { mintTokenCall = opts.rpcMocks.MintDelegationToken } tok, err := mintTokenCall(c, DelegationTokenParams{ TargetHost: host, Tags: opts.delegationTags, MinTTL: 10 * time.Minute, }) if err != nil { return nil, nil, err } delegationToken = tok.Token } // Use our own OAuth token too, since the delegation token is bound to us. oauthTok, err := cfg.AccessTokenProvider(c, []string{auth.OAuthScopeEmail}) if err != nil { return nil, nil, err } logging.Fields{ "fingerprint": tokenFingerprint(delegationToken), }.Debugf(c, "auth: Sending delegation token") return oauthTok, map[string]string{delegation.HTTPHeaderName: delegationToken}, nil }
[ "func", "asUserHeaders", "(", "c", "context", ".", "Context", ",", "uri", "string", ",", "opts", "*", "rpcOptions", ")", "(", "*", "oauth2", ".", "Token", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "cfg", ":=", "getConfig", "(", "c", ")", "\n", "if", "cfg", "==", "nil", "||", "cfg", ".", "AccessTokenProvider", "==", "nil", "{", "return", "nil", ",", "nil", ",", "ErrNotConfigured", "\n", "}", "\n\n", "delegationToken", ":=", "\"", "\"", "\n", "if", "opts", ".", "delegationToken", "!=", "\"", "\"", "{", "delegationToken", "=", "opts", ".", "delegationToken", "// WithDelegationToken was used", "\n", "}", "else", "{", "// Outbound RPC calls in the context of a request from anonymous caller are", "// anonymous too. No need to use any authentication headers.", "userIdent", ":=", "CurrentIdentity", "(", "c", ")", "\n", "if", "userIdent", "==", "identity", ".", "AnonymousIdentity", "{", "return", "nil", ",", "nil", ",", "nil", "\n", "}", "\n\n", "// Grab root URL of the destination service. Only https:// are allowed.", "uri", "=", "strings", ".", "ToLower", "(", "uri", ")", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "uri", ",", "\"", "\"", ")", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "host", ":=", "uri", "[", "len", "(", "\"", "\"", ")", ":", "]", "\n", "if", "idx", ":=", "strings", ".", "IndexRune", "(", "host", ",", "'/'", ")", ";", "idx", "!=", "-", "1", "{", "host", "=", "host", "[", ":", "idx", "]", "\n", "}", "\n\n", "// Grab a token that's good enough for at least 10 min. Outbound RPCs", "// shouldn't last longer than that.", "mintTokenCall", ":=", "MintDelegationToken", "\n", "if", "opts", ".", "rpcMocks", "!=", "nil", "&&", "opts", ".", "rpcMocks", ".", "MintDelegationToken", "!=", "nil", "{", "mintTokenCall", "=", "opts", ".", "rpcMocks", ".", "MintDelegationToken", "\n", "}", "\n", "tok", ",", "err", ":=", "mintTokenCall", "(", "c", ",", "DelegationTokenParams", "{", "TargetHost", ":", "host", ",", "Tags", ":", "opts", ".", "delegationTags", ",", "MinTTL", ":", "10", "*", "time", ".", "Minute", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "delegationToken", "=", "tok", ".", "Token", "\n", "}", "\n\n", "// Use our own OAuth token too, since the delegation token is bound to us.", "oauthTok", ",", "err", ":=", "cfg", ".", "AccessTokenProvider", "(", "c", ",", "[", "]", "string", "{", "auth", ".", "OAuthScopeEmail", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "logging", ".", "Fields", "{", "\"", "\"", ":", "tokenFingerprint", "(", "delegationToken", ")", ",", "}", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "oauthTok", ",", "map", "[", "string", "]", "string", "{", "delegation", ".", "HTTPHeaderName", ":", "delegationToken", "}", ",", "nil", "\n", "}" ]
// asUserHeaders returns a map of authentication headers to add to outbound // RPC requests done in AsUser mode. // // This will be called by the transport layer on each request.
[ "asUserHeaders", "returns", "a", "map", "of", "authentication", "headers", "to", "add", "to", "outbound", "RPC", "requests", "done", "in", "AsUser", "mode", ".", "This", "will", "be", "called", "by", "the", "transport", "layer", "on", "each", "request", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/client.go#L553-L607
9,568
luci/luci-go
server/auth/client.go
asActorHeaders
func asActorHeaders(c context.Context, uri string, opts *rpcOptions) (*oauth2.Token, map[string]string, error) { mintTokenCall := MintAccessTokenForServiceAccount if opts.rpcMocks != nil && opts.rpcMocks.MintAccessTokenForServiceAccount != nil { mintTokenCall = opts.rpcMocks.MintAccessTokenForServiceAccount } oauthTok, err := mintTokenCall(c, MintAccessTokenParams{ ServiceAccount: opts.serviceAccount, Scopes: opts.scopes, MinTTL: 2 * time.Minute, }) return oauthTok, nil, err }
go
func asActorHeaders(c context.Context, uri string, opts *rpcOptions) (*oauth2.Token, map[string]string, error) { mintTokenCall := MintAccessTokenForServiceAccount if opts.rpcMocks != nil && opts.rpcMocks.MintAccessTokenForServiceAccount != nil { mintTokenCall = opts.rpcMocks.MintAccessTokenForServiceAccount } oauthTok, err := mintTokenCall(c, MintAccessTokenParams{ ServiceAccount: opts.serviceAccount, Scopes: opts.scopes, MinTTL: 2 * time.Minute, }) return oauthTok, nil, err }
[ "func", "asActorHeaders", "(", "c", "context", ".", "Context", ",", "uri", "string", ",", "opts", "*", "rpcOptions", ")", "(", "*", "oauth2", ".", "Token", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "mintTokenCall", ":=", "MintAccessTokenForServiceAccount", "\n", "if", "opts", ".", "rpcMocks", "!=", "nil", "&&", "opts", ".", "rpcMocks", ".", "MintAccessTokenForServiceAccount", "!=", "nil", "{", "mintTokenCall", "=", "opts", ".", "rpcMocks", ".", "MintAccessTokenForServiceAccount", "\n", "}", "\n", "oauthTok", ",", "err", ":=", "mintTokenCall", "(", "c", ",", "MintAccessTokenParams", "{", "ServiceAccount", ":", "opts", ".", "serviceAccount", ",", "Scopes", ":", "opts", ".", "scopes", ",", "MinTTL", ":", "2", "*", "time", ".", "Minute", ",", "}", ")", "\n", "return", "oauthTok", ",", "nil", ",", "err", "\n", "}" ]
// asActorHeaders returns a map of authentication headers to add to outbound // RPC requests done in AsActor mode. // // This will be called by the transport layer on each request.
[ "asActorHeaders", "returns", "a", "map", "of", "authentication", "headers", "to", "add", "to", "outbound", "RPC", "requests", "done", "in", "AsActor", "mode", ".", "This", "will", "be", "called", "by", "the", "transport", "layer", "on", "each", "request", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/client.go#L630-L641
9,569
luci/luci-go
server/auth/client.go
asProjectHeaders
func asProjectHeaders(c context.Context, uri string, opts *rpcOptions) (*oauth2.Token, map[string]string, error) { internal, err := isInternalURI(c, uri) if err != nil { return nil, nil, err } // For calls within a single LUCI deployment use the service's own OAuth2 // token and 'X-Luci-Project' header to convey the project identity to the // peer. if internal { tok, _, err := asSelfHeaders(c, uri, opts) return tok, map[string]string{XLUCIProjectHeader: opts.project}, err } // For calls to external (non-LUCI) services get an OAuth2 token of a project // scoped service account. mintTokenCall := MintProjectToken if opts.rpcMocks != nil && opts.rpcMocks.MintProjectToken != nil { mintTokenCall = opts.rpcMocks.MintProjectToken } mintParams := ProjectTokenParams{ MinTTL: 2 * time.Minute, LuciProject: opts.project, OAuthScopes: opts.scopes, } tok, err := mintTokenCall(c, mintParams) // TODO(fmatenaar): This is only during migration and needs to be removed eventually. if tok == nil && err == nil { logging.Infof(c, "project %s not found, fallback to service identity", opts.project) return asSelfHeaders(c, uri, opts) } return tok, nil, err }
go
func asProjectHeaders(c context.Context, uri string, opts *rpcOptions) (*oauth2.Token, map[string]string, error) { internal, err := isInternalURI(c, uri) if err != nil { return nil, nil, err } // For calls within a single LUCI deployment use the service's own OAuth2 // token and 'X-Luci-Project' header to convey the project identity to the // peer. if internal { tok, _, err := asSelfHeaders(c, uri, opts) return tok, map[string]string{XLUCIProjectHeader: opts.project}, err } // For calls to external (non-LUCI) services get an OAuth2 token of a project // scoped service account. mintTokenCall := MintProjectToken if opts.rpcMocks != nil && opts.rpcMocks.MintProjectToken != nil { mintTokenCall = opts.rpcMocks.MintProjectToken } mintParams := ProjectTokenParams{ MinTTL: 2 * time.Minute, LuciProject: opts.project, OAuthScopes: opts.scopes, } tok, err := mintTokenCall(c, mintParams) // TODO(fmatenaar): This is only during migration and needs to be removed eventually. if tok == nil && err == nil { logging.Infof(c, "project %s not found, fallback to service identity", opts.project) return asSelfHeaders(c, uri, opts) } return tok, nil, err }
[ "func", "asProjectHeaders", "(", "c", "context", ".", "Context", ",", "uri", "string", ",", "opts", "*", "rpcOptions", ")", "(", "*", "oauth2", ".", "Token", ",", "map", "[", "string", "]", "string", ",", "error", ")", "{", "internal", ",", "err", ":=", "isInternalURI", "(", "c", ",", "uri", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "// For calls within a single LUCI deployment use the service's own OAuth2", "// token and 'X-Luci-Project' header to convey the project identity to the", "// peer.", "if", "internal", "{", "tok", ",", "_", ",", "err", ":=", "asSelfHeaders", "(", "c", ",", "uri", ",", "opts", ")", "\n", "return", "tok", ",", "map", "[", "string", "]", "string", "{", "XLUCIProjectHeader", ":", "opts", ".", "project", "}", ",", "err", "\n", "}", "\n\n", "// For calls to external (non-LUCI) services get an OAuth2 token of a project", "// scoped service account.", "mintTokenCall", ":=", "MintProjectToken", "\n", "if", "opts", ".", "rpcMocks", "!=", "nil", "&&", "opts", ".", "rpcMocks", ".", "MintProjectToken", "!=", "nil", "{", "mintTokenCall", "=", "opts", ".", "rpcMocks", ".", "MintProjectToken", "\n", "}", "\n", "mintParams", ":=", "ProjectTokenParams", "{", "MinTTL", ":", "2", "*", "time", ".", "Minute", ",", "LuciProject", ":", "opts", ".", "project", ",", "OAuthScopes", ":", "opts", ".", "scopes", ",", "}", "\n\n", "tok", ",", "err", ":=", "mintTokenCall", "(", "c", ",", "mintParams", ")", "\n", "// TODO(fmatenaar): This is only during migration and needs to be removed eventually.", "if", "tok", "==", "nil", "&&", "err", "==", "nil", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "opts", ".", "project", ")", "\n", "return", "asSelfHeaders", "(", "c", ",", "uri", ",", "opts", ")", "\n", "}", "\n", "return", "tok", ",", "nil", ",", "err", "\n", "}" ]
// asProjectHeaders returns a map of authentication headers to add to outbound // RPC requests done in AsProject mode. // // This will be called by the transport layer on each request.
[ "asProjectHeaders", "returns", "a", "map", "of", "authentication", "headers", "to", "add", "to", "outbound", "RPC", "requests", "done", "in", "AsProject", "mode", ".", "This", "will", "be", "called", "by", "the", "transport", "layer", "on", "each", "request", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/client.go#L647-L680
9,570
luci/luci-go
logdog/client/cmd/logdog_butler/subcommand_stream.go
Run
func (cmd *streamCommandRun) Run(app subcommands.Application, args []string, _ subcommands.Env) int { a := app.(*application) var ( streamFile *os.File defaultStreamName streamproto.StreamNameFlag ) if cmd.path == "-" { defaultStreamName = "stdin" streamFile = os.Stdin } else { streamName, err := types.MakeStreamName("file:", cmd.path) if err != nil { log.Fields{ log.ErrorKey: err, }.Errorf(a, "Failed to generate stream name.") return runtimeErrorReturnCode } defaultStreamName = streamproto.StreamNameFlag(streamName) file, err := os.Open(cmd.path) if err != nil { log.Fields{ log.ErrorKey: err, "path": cmd.path, }.Errorf(a, "Failed to open input stream file.") return runtimeErrorReturnCode } streamFile = file } if cmd.stream.Name == "" { cmd.stream.Name = defaultStreamName } // We think everything should work. Configure our Output instance. of, err := a.getOutputFactory() if err != nil { log.WithError(err).Errorf(a, "Failed to get output factory instance.") return runtimeErrorReturnCode } output, err := of.configOutput(a) if err != nil { log.WithError(err).Errorf(a, "Failed to create output instance.") return runtimeErrorReturnCode } defer output.Close() // Instantiate our Processor. err = a.runWithButler(output, func(b *butler.Butler) error { if err := b.AddStream(streamFile, cmd.stream.properties()); err != nil { return errors.Annotate(err, "failed to add stream").Err() } b.Activate() return b.Wait() }) if err != nil { logAnnotatedErr(a, err, "Failed to stream file.") return runtimeErrorReturnCode } return 0 }
go
func (cmd *streamCommandRun) Run(app subcommands.Application, args []string, _ subcommands.Env) int { a := app.(*application) var ( streamFile *os.File defaultStreamName streamproto.StreamNameFlag ) if cmd.path == "-" { defaultStreamName = "stdin" streamFile = os.Stdin } else { streamName, err := types.MakeStreamName("file:", cmd.path) if err != nil { log.Fields{ log.ErrorKey: err, }.Errorf(a, "Failed to generate stream name.") return runtimeErrorReturnCode } defaultStreamName = streamproto.StreamNameFlag(streamName) file, err := os.Open(cmd.path) if err != nil { log.Fields{ log.ErrorKey: err, "path": cmd.path, }.Errorf(a, "Failed to open input stream file.") return runtimeErrorReturnCode } streamFile = file } if cmd.stream.Name == "" { cmd.stream.Name = defaultStreamName } // We think everything should work. Configure our Output instance. of, err := a.getOutputFactory() if err != nil { log.WithError(err).Errorf(a, "Failed to get output factory instance.") return runtimeErrorReturnCode } output, err := of.configOutput(a) if err != nil { log.WithError(err).Errorf(a, "Failed to create output instance.") return runtimeErrorReturnCode } defer output.Close() // Instantiate our Processor. err = a.runWithButler(output, func(b *butler.Butler) error { if err := b.AddStream(streamFile, cmd.stream.properties()); err != nil { return errors.Annotate(err, "failed to add stream").Err() } b.Activate() return b.Wait() }) if err != nil { logAnnotatedErr(a, err, "Failed to stream file.") return runtimeErrorReturnCode } return 0 }
[ "func", "(", "cmd", "*", "streamCommandRun", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "_", "subcommands", ".", "Env", ")", "int", "{", "a", ":=", "app", ".", "(", "*", "application", ")", "\n\n", "var", "(", "streamFile", "*", "os", ".", "File", "\n", "defaultStreamName", "streamproto", ".", "StreamNameFlag", "\n", ")", "\n", "if", "cmd", ".", "path", "==", "\"", "\"", "{", "defaultStreamName", "=", "\"", "\"", "\n", "streamFile", "=", "os", ".", "Stdin", "\n", "}", "else", "{", "streamName", ",", "err", ":=", "types", ".", "MakeStreamName", "(", "\"", "\"", ",", "cmd", ".", "path", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fields", "{", "log", ".", "ErrorKey", ":", "err", ",", "}", ".", "Errorf", "(", "a", ",", "\"", "\"", ")", "\n", "return", "runtimeErrorReturnCode", "\n", "}", "\n", "defaultStreamName", "=", "streamproto", ".", "StreamNameFlag", "(", "streamName", ")", "\n\n", "file", ",", "err", ":=", "os", ".", "Open", "(", "cmd", ".", "path", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fields", "{", "log", ".", "ErrorKey", ":", "err", ",", "\"", "\"", ":", "cmd", ".", "path", ",", "}", ".", "Errorf", "(", "a", ",", "\"", "\"", ")", "\n", "return", "runtimeErrorReturnCode", "\n", "}", "\n", "streamFile", "=", "file", "\n", "}", "\n", "if", "cmd", ".", "stream", ".", "Name", "==", "\"", "\"", "{", "cmd", ".", "stream", ".", "Name", "=", "defaultStreamName", "\n", "}", "\n\n", "// We think everything should work. Configure our Output instance.", "of", ",", "err", ":=", "a", ".", "getOutputFactory", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "a", ",", "\"", "\"", ")", "\n", "return", "runtimeErrorReturnCode", "\n", "}", "\n", "output", ",", "err", ":=", "of", ".", "configOutput", "(", "a", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "a", ",", "\"", "\"", ")", "\n", "return", "runtimeErrorReturnCode", "\n", "}", "\n", "defer", "output", ".", "Close", "(", ")", "\n\n", "// Instantiate our Processor.", "err", "=", "a", ".", "runWithButler", "(", "output", ",", "func", "(", "b", "*", "butler", ".", "Butler", ")", "error", "{", "if", "err", ":=", "b", ".", "AddStream", "(", "streamFile", ",", "cmd", ".", "stream", ".", "properties", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "b", ".", "Activate", "(", ")", "\n", "return", "b", ".", "Wait", "(", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "logAnnotatedErr", "(", "a", ",", "err", ",", "\"", "\"", ")", "\n", "return", "runtimeErrorReturnCode", "\n", "}", "\n\n", "return", "0", "\n", "}" ]
// subcommands.Run
[ "subcommands", ".", "Run" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/cmd/logdog_butler/subcommand_stream.go#L55-L117
9,571
luci/luci-go
buildbucket/luciexe/runner.go
Run
func (r *runner) Run(ctx context.Context, args *pb.RunnerArgs) (*pb.Build, error) { ctx, cancel := context.WithCancel(ctx) defer cancel() // Validate and normalize parameters. args = proto.Clone(args).(*pb.RunnerArgs) if err := normalizeArgs(args); err != nil { return nil, errors.Annotate(err, "invalid args").Err() } // Print our input. argsJSON, err := indentedJSONPB(args) if err != nil { return nil, err } logging.Infof(ctx, "RunnerArgs: %s", argsJSON) // Prepare workdir. if err := r.setupWorkDir(args.WorkDir); err != nil { return nil, err } // Prepare auth contexts. systemAuth, userAuth, err := setupAuth(ctx, args) if err != nil { return nil, err } defer systemAuth.Close() defer userAuth.Close() // Prepare a build listener. var listenerErr error var listenerErrMU sync.Mutex listener := newBuildListener(streamNamePrefix, func(err error) { logging.Errorf(ctx, "%s", err) listenerErrMU.Lock() defer listenerErrMU.Unlock() if listenerErr == nil { listenerErr = err logging.Warningf(ctx, "canceling the user subprocess") cancel() } }) // Start a local LogDog server. logdogServ, err := r.startLogDog(ctx, args, systemAuth, listener) if err != nil { return nil, errors.Annotate(err, "failed to start local logdog server").Err() } defer func() { if logdogServ != nil { _ = logdogServ.Stop() } }() // Run the user executable. err = r.runUserExecutable(ctx, args, userAuth, logdogServ, streamNamePrefix) if err != nil { return nil, err } // Wait for logdog server to stop before returning the build. if err := logdogServ.Stop(); err != nil { return nil, errors.Annotate(err, "failed to stop logdog server").Err() } logdogServ = nil // do not stop for the second time. // Check listener error. listenerErrMU.Lock() err = listenerErr listenerErrMU.Unlock() if err != nil { return nil, err } // Read the final build state. build := listener.Build() if build == nil { return nil, errors.Reason("user executable did not send a build").Err() } // Print the final build state. buildJSON, err := indentedJSONPB(build) if err != nil { return build, err } logging.Infof(ctx, "final build state: %s", buildJSON) // TODO(nodir): make a final UpdateBuild call. return build, nil }
go
func (r *runner) Run(ctx context.Context, args *pb.RunnerArgs) (*pb.Build, error) { ctx, cancel := context.WithCancel(ctx) defer cancel() // Validate and normalize parameters. args = proto.Clone(args).(*pb.RunnerArgs) if err := normalizeArgs(args); err != nil { return nil, errors.Annotate(err, "invalid args").Err() } // Print our input. argsJSON, err := indentedJSONPB(args) if err != nil { return nil, err } logging.Infof(ctx, "RunnerArgs: %s", argsJSON) // Prepare workdir. if err := r.setupWorkDir(args.WorkDir); err != nil { return nil, err } // Prepare auth contexts. systemAuth, userAuth, err := setupAuth(ctx, args) if err != nil { return nil, err } defer systemAuth.Close() defer userAuth.Close() // Prepare a build listener. var listenerErr error var listenerErrMU sync.Mutex listener := newBuildListener(streamNamePrefix, func(err error) { logging.Errorf(ctx, "%s", err) listenerErrMU.Lock() defer listenerErrMU.Unlock() if listenerErr == nil { listenerErr = err logging.Warningf(ctx, "canceling the user subprocess") cancel() } }) // Start a local LogDog server. logdogServ, err := r.startLogDog(ctx, args, systemAuth, listener) if err != nil { return nil, errors.Annotate(err, "failed to start local logdog server").Err() } defer func() { if logdogServ != nil { _ = logdogServ.Stop() } }() // Run the user executable. err = r.runUserExecutable(ctx, args, userAuth, logdogServ, streamNamePrefix) if err != nil { return nil, err } // Wait for logdog server to stop before returning the build. if err := logdogServ.Stop(); err != nil { return nil, errors.Annotate(err, "failed to stop logdog server").Err() } logdogServ = nil // do not stop for the second time. // Check listener error. listenerErrMU.Lock() err = listenerErr listenerErrMU.Unlock() if err != nil { return nil, err } // Read the final build state. build := listener.Build() if build == nil { return nil, errors.Reason("user executable did not send a build").Err() } // Print the final build state. buildJSON, err := indentedJSONPB(build) if err != nil { return build, err } logging.Infof(ctx, "final build state: %s", buildJSON) // TODO(nodir): make a final UpdateBuild call. return build, nil }
[ "func", "(", "r", "*", "runner", ")", "Run", "(", "ctx", "context", ".", "Context", ",", "args", "*", "pb", ".", "RunnerArgs", ")", "(", "*", "pb", ".", "Build", ",", "error", ")", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "ctx", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "// Validate and normalize parameters.", "args", "=", "proto", ".", "Clone", "(", "args", ")", ".", "(", "*", "pb", ".", "RunnerArgs", ")", "\n", "if", "err", ":=", "normalizeArgs", "(", "args", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Print our input.", "argsJSON", ",", "err", ":=", "indentedJSONPB", "(", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "logging", ".", "Infof", "(", "ctx", ",", "\"", "\"", ",", "argsJSON", ")", "\n\n", "// Prepare workdir.", "if", "err", ":=", "r", ".", "setupWorkDir", "(", "args", ".", "WorkDir", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Prepare auth contexts.", "systemAuth", ",", "userAuth", ",", "err", ":=", "setupAuth", "(", "ctx", ",", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "systemAuth", ".", "Close", "(", ")", "\n", "defer", "userAuth", ".", "Close", "(", ")", "\n\n", "// Prepare a build listener.", "var", "listenerErr", "error", "\n", "var", "listenerErrMU", "sync", ".", "Mutex", "\n", "listener", ":=", "newBuildListener", "(", "streamNamePrefix", ",", "func", "(", "err", "error", ")", "{", "logging", ".", "Errorf", "(", "ctx", ",", "\"", "\"", ",", "err", ")", "\n\n", "listenerErrMU", ".", "Lock", "(", ")", "\n", "defer", "listenerErrMU", ".", "Unlock", "(", ")", "\n", "if", "listenerErr", "==", "nil", "{", "listenerErr", "=", "err", "\n", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ")", "\n", "cancel", "(", ")", "\n", "}", "\n", "}", ")", "\n\n", "// Start a local LogDog server.", "logdogServ", ",", "err", ":=", "r", ".", "startLogDog", "(", "ctx", ",", "args", ",", "systemAuth", ",", "listener", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "logdogServ", "!=", "nil", "{", "_", "=", "logdogServ", ".", "Stop", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// Run the user executable.", "err", "=", "r", ".", "runUserExecutable", "(", "ctx", ",", "args", ",", "userAuth", ",", "logdogServ", ",", "streamNamePrefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Wait for logdog server to stop before returning the build.", "if", "err", ":=", "logdogServ", ".", "Stop", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "logdogServ", "=", "nil", "// do not stop for the second time.", "\n\n", "// Check listener error.", "listenerErrMU", ".", "Lock", "(", ")", "\n", "err", "=", "listenerErr", "\n", "listenerErrMU", ".", "Unlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Read the final build state.", "build", ":=", "listener", ".", "Build", "(", ")", "\n", "if", "build", "==", "nil", "{", "return", "nil", ",", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Print the final build state.", "buildJSON", ",", "err", ":=", "indentedJSONPB", "(", "build", ")", "\n", "if", "err", "!=", "nil", "{", "return", "build", ",", "err", "\n", "}", "\n", "logging", ".", "Infof", "(", "ctx", ",", "\"", "\"", ",", "buildJSON", ")", "\n\n", "// TODO(nodir): make a final UpdateBuild call.", "return", "build", ",", "nil", "\n", "}" ]
// Run runs a user executable.
[ "Run", "runs", "a", "user", "executable", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/runner.go#L62-L154
9,572
luci/luci-go
buildbucket/luciexe/runner.go
setupWorkDir
func (r *runner) setupWorkDir(workDir string) error { switch _, err := os.Stat(workDir); { case err == nil: return errors.Reason("workdir %q already exists; it must not", workDir).Err() case os.IsNotExist(err): // good default: return err } return errors.Annotate(os.MkdirAll(workDir, 0700), "failed to create %q", workDir).Err() }
go
func (r *runner) setupWorkDir(workDir string) error { switch _, err := os.Stat(workDir); { case err == nil: return errors.Reason("workdir %q already exists; it must not", workDir).Err() case os.IsNotExist(err): // good default: return err } return errors.Annotate(os.MkdirAll(workDir, 0700), "failed to create %q", workDir).Err() }
[ "func", "(", "r", "*", "runner", ")", "setupWorkDir", "(", "workDir", "string", ")", "error", "{", "switch", "_", ",", "err", ":=", "os", ".", "Stat", "(", "workDir", ")", ";", "{", "case", "err", "==", "nil", ":", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "workDir", ")", ".", "Err", "(", ")", "\n\n", "case", "os", ".", "IsNotExist", "(", "err", ")", ":", "// good", "default", ":", "return", "err", "\n\n", "}", "\n\n", "return", "errors", ".", "Annotate", "(", "os", ".", "MkdirAll", "(", "workDir", ",", "0700", ")", ",", "\"", "\"", ",", "workDir", ")", ".", "Err", "(", ")", "\n", "}" ]
// setupWorkDir creates a work dir. // If workdir already exists, returns an error.
[ "setupWorkDir", "creates", "a", "work", "dir", ".", "If", "workdir", "already", "exists", "returns", "an", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/runner.go#L158-L172
9,573
luci/luci-go
buildbucket/luciexe/runner.go
setupUserEnv
func (r *runner) setupUserEnv(ctx context.Context, args *pb.RunnerArgs, userAuth *authctx.Context, logdogServ *logdogServer, logdogNamespace string) (environ.Env, error) { ret := environ.System() userAuth.ExportIntoEnv(ret) if err := logdogServ.ExportIntoEnv(ret); err != nil { return environ.Env{}, err } ret.Set("LOGDOG_NAMESPACE", logdogNamespace) // Prepare user LUCI context. ctx, err := lucictx.Set(ctx, "luci_executable", map[string]string{ "cache_dir": args.CacheDir, }) if err != nil { return environ.Env{}, err } lctx, err := lucictx.ExportInto(ctx, args.WorkDir) if err != nil { return environ.Env{}, err } lctx.SetInEnviron(ret) // Prepare a user temp dir. // Note that we can't use workdir directly because some overzealous scripts // like to remove everything they find under TEMPDIR, and it breaks LUCI // runner internals that keep some files in workdir (in particular git and // gsutil configs setup by AuthContext). userTempDir := filepath.Join(args.WorkDir, "ut") if err := os.MkdirAll(userTempDir, 0700); err != nil { return environ.Env{}, errors.Annotate(err, "failed to create temp dir").Err() } for _, v := range []string{"TEMPDIR", "TMPDIR", "TEMP", "TMP", "MAC_CHROMIUM_TMPDIR"} { ret.Set(v, userTempDir) } return ret, nil }
go
func (r *runner) setupUserEnv(ctx context.Context, args *pb.RunnerArgs, userAuth *authctx.Context, logdogServ *logdogServer, logdogNamespace string) (environ.Env, error) { ret := environ.System() userAuth.ExportIntoEnv(ret) if err := logdogServ.ExportIntoEnv(ret); err != nil { return environ.Env{}, err } ret.Set("LOGDOG_NAMESPACE", logdogNamespace) // Prepare user LUCI context. ctx, err := lucictx.Set(ctx, "luci_executable", map[string]string{ "cache_dir": args.CacheDir, }) if err != nil { return environ.Env{}, err } lctx, err := lucictx.ExportInto(ctx, args.WorkDir) if err != nil { return environ.Env{}, err } lctx.SetInEnviron(ret) // Prepare a user temp dir. // Note that we can't use workdir directly because some overzealous scripts // like to remove everything they find under TEMPDIR, and it breaks LUCI // runner internals that keep some files in workdir (in particular git and // gsutil configs setup by AuthContext). userTempDir := filepath.Join(args.WorkDir, "ut") if err := os.MkdirAll(userTempDir, 0700); err != nil { return environ.Env{}, errors.Annotate(err, "failed to create temp dir").Err() } for _, v := range []string{"TEMPDIR", "TMPDIR", "TEMP", "TMP", "MAC_CHROMIUM_TMPDIR"} { ret.Set(v, userTempDir) } return ret, nil }
[ "func", "(", "r", "*", "runner", ")", "setupUserEnv", "(", "ctx", "context", ".", "Context", ",", "args", "*", "pb", ".", "RunnerArgs", ",", "userAuth", "*", "authctx", ".", "Context", ",", "logdogServ", "*", "logdogServer", ",", "logdogNamespace", "string", ")", "(", "environ", ".", "Env", ",", "error", ")", "{", "ret", ":=", "environ", ".", "System", "(", ")", "\n", "userAuth", ".", "ExportIntoEnv", "(", "ret", ")", "\n", "if", "err", ":=", "logdogServ", ".", "ExportIntoEnv", "(", "ret", ")", ";", "err", "!=", "nil", "{", "return", "environ", ".", "Env", "{", "}", ",", "err", "\n", "}", "\n", "ret", ".", "Set", "(", "\"", "\"", ",", "logdogNamespace", ")", "\n\n", "// Prepare user LUCI context.", "ctx", ",", "err", ":=", "lucictx", ".", "Set", "(", "ctx", ",", "\"", "\"", ",", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "args", ".", "CacheDir", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "environ", ".", "Env", "{", "}", ",", "err", "\n", "}", "\n", "lctx", ",", "err", ":=", "lucictx", ".", "ExportInto", "(", "ctx", ",", "args", ".", "WorkDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "environ", ".", "Env", "{", "}", ",", "err", "\n", "}", "\n", "lctx", ".", "SetInEnviron", "(", "ret", ")", "\n\n", "// Prepare a user temp dir.", "// Note that we can't use workdir directly because some overzealous scripts", "// like to remove everything they find under TEMPDIR, and it breaks LUCI", "// runner internals that keep some files in workdir (in particular git and", "// gsutil configs setup by AuthContext).", "userTempDir", ":=", "filepath", ".", "Join", "(", "args", ".", "WorkDir", ",", "\"", "\"", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "userTempDir", ",", "0700", ")", ";", "err", "!=", "nil", "{", "return", "environ", ".", "Env", "{", "}", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", "{", "ret", ".", "Set", "(", "v", ",", "userTempDir", ")", "\n", "}", "\n\n", "return", "ret", ",", "nil", "\n", "}" ]
// setupUserEnv prepares user subprocess environment.
[ "setupUserEnv", "prepares", "user", "subprocess", "environment", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/runner.go#L243-L278
9,574
luci/luci-go
buildbucket/luciexe/runner.go
readBuildSecrets
func readBuildSecrets(ctx context.Context) (*pb.BuildSecrets, error) { swarming := lucictx.GetSwarming(ctx) if swarming == nil { return nil, nil } secrets := &pb.BuildSecrets{} if err := proto.Unmarshal(swarming.SecretBytes, secrets); err != nil { return nil, err } return secrets, nil }
go
func readBuildSecrets(ctx context.Context) (*pb.BuildSecrets, error) { swarming := lucictx.GetSwarming(ctx) if swarming == nil { return nil, nil } secrets := &pb.BuildSecrets{} if err := proto.Unmarshal(swarming.SecretBytes, secrets); err != nil { return nil, err } return secrets, nil }
[ "func", "readBuildSecrets", "(", "ctx", "context", ".", "Context", ")", "(", "*", "pb", ".", "BuildSecrets", ",", "error", ")", "{", "swarming", ":=", "lucictx", ".", "GetSwarming", "(", "ctx", ")", "\n", "if", "swarming", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "secrets", ":=", "&", "pb", ".", "BuildSecrets", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "swarming", ".", "SecretBytes", ",", "secrets", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "secrets", ",", "nil", "\n", "}" ]
// readBuildSecrets reads BuildSecrets message from swarming secret bytes, // if any.
[ "readBuildSecrets", "reads", "BuildSecrets", "message", "from", "swarming", "secret", "bytes", "if", "any", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/runner.go#L310-L321
9,575
luci/luci-go
buildbucket/luciexe/runner.go
indentedJSONPB
func indentedJSONPB(m proto.Message) ([]byte, error) { // Note: json.Indent indents more nicely than jsonpb.Marshaler. unindented := &bytes.Buffer{} if err := (&jsonpb.Marshaler{}).Marshal(unindented, m); err != nil { return nil, err } indented := &bytes.Buffer{} if err := json.Indent(indented, unindented.Bytes(), "", " "); err != nil { return nil, err } return indented.Bytes(), nil }
go
func indentedJSONPB(m proto.Message) ([]byte, error) { // Note: json.Indent indents more nicely than jsonpb.Marshaler. unindented := &bytes.Buffer{} if err := (&jsonpb.Marshaler{}).Marshal(unindented, m); err != nil { return nil, err } indented := &bytes.Buffer{} if err := json.Indent(indented, unindented.Bytes(), "", " "); err != nil { return nil, err } return indented.Bytes(), nil }
[ "func", "indentedJSONPB", "(", "m", "proto", ".", "Message", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Note: json.Indent indents more nicely than jsonpb.Marshaler.", "unindented", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "if", "err", ":=", "(", "&", "jsonpb", ".", "Marshaler", "{", "}", ")", ".", "Marshal", "(", "unindented", ",", "m", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "indented", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "if", "err", ":=", "json", ".", "Indent", "(", "indented", ",", "unindented", ".", "Bytes", "(", ")", ",", "\"", "\"", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "indented", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// indentedJSONPB returns m marshaled to indented JSON.
[ "indentedJSONPB", "returns", "m", "marshaled", "to", "indented", "JSON", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/runner.go#L407-L419
9,576
luci/luci-go
buildbucket/luciexe/runner.go
globalLogTags
func globalLogTags(args *pb.RunnerArgs) map[string]string { ret := make(map[string]string, 4) ret[logDogViewerURLTag] = fmt.Sprintf("https://%s/build/%d", args.BuildbucketHost, args.Build.Id) // SWARMING_SERVER is the full URL: https://example.com // We want just the hostname. env := environ.System() if v, ok := env.Get("SWARMING_SERVER"); ok { if u, err := url.Parse(v); err == nil && u.Host != "" { ret["swarming.host"] = u.Host } } if v, ok := env.Get("SWARMING_TASK_ID"); ok { ret["swarming.run_id"] = v } if v, ok := env.Get("SWARMING_BOT_ID"); ok { ret["swarming.bot_id"] = v } return ret }
go
func globalLogTags(args *pb.RunnerArgs) map[string]string { ret := make(map[string]string, 4) ret[logDogViewerURLTag] = fmt.Sprintf("https://%s/build/%d", args.BuildbucketHost, args.Build.Id) // SWARMING_SERVER is the full URL: https://example.com // We want just the hostname. env := environ.System() if v, ok := env.Get("SWARMING_SERVER"); ok { if u, err := url.Parse(v); err == nil && u.Host != "" { ret["swarming.host"] = u.Host } } if v, ok := env.Get("SWARMING_TASK_ID"); ok { ret["swarming.run_id"] = v } if v, ok := env.Get("SWARMING_BOT_ID"); ok { ret["swarming.bot_id"] = v } return ret }
[ "func", "globalLogTags", "(", "args", "*", "pb", ".", "RunnerArgs", ")", "map", "[", "string", "]", "string", "{", "ret", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "4", ")", "\n", "ret", "[", "logDogViewerURLTag", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "args", ".", "BuildbucketHost", ",", "args", ".", "Build", ".", "Id", ")", "\n\n", "// SWARMING_SERVER is the full URL: https://example.com", "// We want just the hostname.", "env", ":=", "environ", ".", "System", "(", ")", "\n", "if", "v", ",", "ok", ":=", "env", ".", "Get", "(", "\"", "\"", ")", ";", "ok", "{", "if", "u", ",", "err", ":=", "url", ".", "Parse", "(", "v", ")", ";", "err", "==", "nil", "&&", "u", ".", "Host", "!=", "\"", "\"", "{", "ret", "[", "\"", "\"", "]", "=", "u", ".", "Host", "\n", "}", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "env", ".", "Get", "(", "\"", "\"", ")", ";", "ok", "{", "ret", "[", "\"", "\"", "]", "=", "v", "\n", "}", "\n", "if", "v", ",", "ok", ":=", "env", ".", "Get", "(", "\"", "\"", ")", ";", "ok", "{", "ret", "[", "\"", "\"", "]", "=", "v", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// globalLogTags returns tags to be added to all logdog streams by default.
[ "globalLogTags", "returns", "tags", "to", "be", "added", "to", "all", "logdog", "streams", "by", "default", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/runner.go#L476-L495
9,577
luci/luci-go
common/api/buildbucket/buildbucket/v1/timestamp.go
ParseTimestamp
func ParseTimestamp(usec int64) time.Time { if usec == 0 { return time.Time{} } // TODO(nodir): will start to overflow in year ~2250+, fix it then. return time.Unix(0, usec*1000).UTC() }
go
func ParseTimestamp(usec int64) time.Time { if usec == 0 { return time.Time{} } // TODO(nodir): will start to overflow in year ~2250+, fix it then. return time.Unix(0, usec*1000).UTC() }
[ "func", "ParseTimestamp", "(", "usec", "int64", ")", "time", ".", "Time", "{", "if", "usec", "==", "0", "{", "return", "time", ".", "Time", "{", "}", "\n", "}", "\n", "// TODO(nodir): will start to overflow in year ~2250+, fix it then.", "return", "time", ".", "Unix", "(", "0", ",", "usec", "*", "1000", ")", ".", "UTC", "(", ")", "\n", "}" ]
// ParseTimestamp parses a buildbucket timestamp.
[ "ParseTimestamp", "parses", "a", "buildbucket", "timestamp", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/buildbucket/buildbucket/v1/timestamp.go#L20-L26
9,578
luci/luci-go
auth/internal/iam.go
NewIAMTokenProvider
func NewIAMTokenProvider(ctx context.Context, actAs string, scopes []string, transport http.RoundTripper) (TokenProvider, error) { return &iamTokenProvider{ actAs: actAs, scopes: scopes, transport: transport, cacheKey: CacheKey{ Key: fmt.Sprintf("iam/%s", actAs), Scopes: scopes, }, }, nil }
go
func NewIAMTokenProvider(ctx context.Context, actAs string, scopes []string, transport http.RoundTripper) (TokenProvider, error) { return &iamTokenProvider{ actAs: actAs, scopes: scopes, transport: transport, cacheKey: CacheKey{ Key: fmt.Sprintf("iam/%s", actAs), Scopes: scopes, }, }, nil }
[ "func", "NewIAMTokenProvider", "(", "ctx", "context", ".", "Context", ",", "actAs", "string", ",", "scopes", "[", "]", "string", ",", "transport", "http", ".", "RoundTripper", ")", "(", "TokenProvider", ",", "error", ")", "{", "return", "&", "iamTokenProvider", "{", "actAs", ":", "actAs", ",", "scopes", ":", "scopes", ",", "transport", ":", "transport", ",", "cacheKey", ":", "CacheKey", "{", "Key", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "actAs", ")", ",", "Scopes", ":", "scopes", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// NewIAMTokenProvider returns TokenProvider that uses SignBlob IAM API to // sign assertions on behalf of some service account.
[ "NewIAMTokenProvider", "returns", "TokenProvider", "that", "uses", "SignBlob", "IAM", "API", "to", "sign", "assertions", "on", "behalf", "of", "some", "service", "account", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/internal/iam.go#L38-L48
9,579
luci/luci-go
grpc/svcmux/svcmux.go
GetServiceVersion
func GetServiceVersion(c context.Context, defaultVer string) string { if md, ok := metadata.FromIncomingContext(c); ok { values := md[VersionMetadataKey] if len(values) != 0 { return values[0] } } return defaultVer }
go
func GetServiceVersion(c context.Context, defaultVer string) string { if md, ok := metadata.FromIncomingContext(c); ok { values := md[VersionMetadataKey] if len(values) != 0 { return values[0] } } return defaultVer }
[ "func", "GetServiceVersion", "(", "c", "context", ".", "Context", ",", "defaultVer", "string", ")", "string", "{", "if", "md", ",", "ok", ":=", "metadata", ".", "FromIncomingContext", "(", "c", ")", ";", "ok", "{", "values", ":=", "md", "[", "VersionMetadataKey", "]", "\n", "if", "len", "(", "values", ")", "!=", "0", "{", "return", "values", "[", "0", "]", "\n", "}", "\n", "}", "\n", "return", "defaultVer", "\n", "}" ]
// GetServiceVersion extracts requested service version from metadata in c.
[ "GetServiceVersion", "extracts", "requested", "service", "version", "from", "metadata", "in", "c", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/svcmux/svcmux.go#L33-L41
9,580
luci/luci-go
tokenserver/appengine/impl/certconfig/ca.go
ParseConfig
func (c *CA) ParseConfig() (*admin.CertificateAuthorityConfig, error) { msg := &admin.CertificateAuthorityConfig{} if err := proto.Unmarshal(c.Config, msg); err != nil { return nil, err } return msg, nil }
go
func (c *CA) ParseConfig() (*admin.CertificateAuthorityConfig, error) { msg := &admin.CertificateAuthorityConfig{} if err := proto.Unmarshal(c.Config, msg); err != nil { return nil, err } return msg, nil }
[ "func", "(", "c", "*", "CA", ")", "ParseConfig", "(", ")", "(", "*", "admin", ".", "CertificateAuthorityConfig", ",", "error", ")", "{", "msg", ":=", "&", "admin", ".", "CertificateAuthorityConfig", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "c", ".", "Config", ",", "msg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "msg", ",", "nil", "\n", "}" ]
// ParseConfig parses proto message stored in Config.
[ "ParseConfig", "parses", "proto", "message", "stored", "in", "Config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/ca.go#L74-L80
9,581
luci/luci-go
tokenserver/appengine/impl/certconfig/ca.go
ListCAs
func ListCAs(c context.Context) ([]string, error) { keys := []*ds.Key{} q := ds.NewQuery("CA").Eq("Removed", false).KeysOnly(true) if err := ds.GetAll(c, q, &keys); err != nil { return nil, transient.Tag.Apply(err) } names := make([]string, len(keys)) for i, key := range keys { names[i] = key.StringID() } return names, nil }
go
func ListCAs(c context.Context) ([]string, error) { keys := []*ds.Key{} q := ds.NewQuery("CA").Eq("Removed", false).KeysOnly(true) if err := ds.GetAll(c, q, &keys); err != nil { return nil, transient.Tag.Apply(err) } names := make([]string, len(keys)) for i, key := range keys { names[i] = key.StringID() } return names, nil }
[ "func", "ListCAs", "(", "c", "context", ".", "Context", ")", "(", "[", "]", "string", ",", "error", ")", "{", "keys", ":=", "[", "]", "*", "ds", ".", "Key", "{", "}", "\n", "q", ":=", "ds", ".", "NewQuery", "(", "\"", "\"", ")", ".", "Eq", "(", "\"", "\"", ",", "false", ")", ".", "KeysOnly", "(", "true", ")", "\n", "if", "err", ":=", "ds", ".", "GetAll", "(", "c", ",", "q", ",", "&", "keys", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "names", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "keys", ")", ")", "\n", "for", "i", ",", "key", ":=", "range", "keys", "{", "names", "[", "i", "]", "=", "key", ".", "StringID", "(", ")", "\n", "}", "\n", "return", "names", ",", "nil", "\n", "}" ]
// ListCAs returns names of all currently active CAs, in no particular order.
[ "ListCAs", "returns", "names", "of", "all", "currently", "active", "CAs", "in", "no", "particular", "order", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/ca.go#L83-L94
9,582
luci/luci-go
tokenserver/appengine/impl/certconfig/ca.go
StoreCAUniqueIDToCNMap
func StoreCAUniqueIDToCNMap(c context.Context, mapping map[int64]string) error { buf := bytes.Buffer{} enc := gob.NewEncoder(&buf) if err := enc.Encode(mapping); err != nil { return err } // Note that in practice 'mapping' is usually very small, so we are not // concerned about 1MB entity size limit. return transient.Tag.Apply(ds.Put(c, &CAUniqueIDToCNMap{ GobEncodedMap: buf.Bytes(), })) }
go
func StoreCAUniqueIDToCNMap(c context.Context, mapping map[int64]string) error { buf := bytes.Buffer{} enc := gob.NewEncoder(&buf) if err := enc.Encode(mapping); err != nil { return err } // Note that in practice 'mapping' is usually very small, so we are not // concerned about 1MB entity size limit. return transient.Tag.Apply(ds.Put(c, &CAUniqueIDToCNMap{ GobEncodedMap: buf.Bytes(), })) }
[ "func", "StoreCAUniqueIDToCNMap", "(", "c", "context", ".", "Context", ",", "mapping", "map", "[", "int64", "]", "string", ")", "error", "{", "buf", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "enc", ":=", "gob", ".", "NewEncoder", "(", "&", "buf", ")", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "mapping", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// Note that in practice 'mapping' is usually very small, so we are not", "// concerned about 1MB entity size limit.", "return", "transient", ".", "Tag", ".", "Apply", "(", "ds", ".", "Put", "(", "c", ",", "&", "CAUniqueIDToCNMap", "{", "GobEncodedMap", ":", "buf", ".", "Bytes", "(", ")", ",", "}", ")", ")", "\n", "}" ]
// StoreCAUniqueIDToCNMap overwrites CAUniqueIDToCNMap with new content.
[ "StoreCAUniqueIDToCNMap", "overwrites", "CAUniqueIDToCNMap", "with", "new", "content", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/ca.go#L108-L119
9,583
luci/luci-go
tokenserver/appengine/impl/certconfig/ca.go
LoadCAUniqueIDToCNMap
func LoadCAUniqueIDToCNMap(c context.Context) (map[int64]string, error) { ent := CAUniqueIDToCNMap{} switch err := ds.Get(c, &ent); { case err == ds.ErrNoSuchEntity: return nil, nil case err != nil: return nil, transient.Tag.Apply(err) } dec := gob.NewDecoder(bytes.NewReader(ent.GobEncodedMap)) out := map[int64]string{} if err := dec.Decode(&out); err != nil { return nil, err } return out, nil }
go
func LoadCAUniqueIDToCNMap(c context.Context) (map[int64]string, error) { ent := CAUniqueIDToCNMap{} switch err := ds.Get(c, &ent); { case err == ds.ErrNoSuchEntity: return nil, nil case err != nil: return nil, transient.Tag.Apply(err) } dec := gob.NewDecoder(bytes.NewReader(ent.GobEncodedMap)) out := map[int64]string{} if err := dec.Decode(&out); err != nil { return nil, err } return out, nil }
[ "func", "LoadCAUniqueIDToCNMap", "(", "c", "context", ".", "Context", ")", "(", "map", "[", "int64", "]", "string", ",", "error", ")", "{", "ent", ":=", "CAUniqueIDToCNMap", "{", "}", "\n", "switch", "err", ":=", "ds", ".", "Get", "(", "c", ",", "&", "ent", ")", ";", "{", "case", "err", "==", "ds", ".", "ErrNoSuchEntity", ":", "return", "nil", ",", "nil", "\n", "case", "err", "!=", "nil", ":", "return", "nil", ",", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "dec", ":=", "gob", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "ent", ".", "GobEncodedMap", ")", ")", "\n", "out", ":=", "map", "[", "int64", "]", "string", "{", "}", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "out", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// LoadCAUniqueIDToCNMap loads CAUniqueIDToCNMap from the datastore.
[ "LoadCAUniqueIDToCNMap", "loads", "CAUniqueIDToCNMap", "from", "the", "datastore", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/ca.go#L122-L136
9,584
luci/luci-go
tokenserver/appengine/impl/certconfig/ca.go
GetCAByUniqueID
func GetCAByUniqueID(c context.Context, id int64) (string, error) { cached, err := mappingCache.Fetch(c, func(interface{}) (interface{}, time.Duration, error) { val, err := LoadCAUniqueIDToCNMap(c) return val, time.Minute, err }) if err != nil { return "", err } mapping := cached.(map[int64]string) return mapping[id], nil }
go
func GetCAByUniqueID(c context.Context, id int64) (string, error) { cached, err := mappingCache.Fetch(c, func(interface{}) (interface{}, time.Duration, error) { val, err := LoadCAUniqueIDToCNMap(c) return val, time.Minute, err }) if err != nil { return "", err } mapping := cached.(map[int64]string) return mapping[id], nil }
[ "func", "GetCAByUniqueID", "(", "c", "context", ".", "Context", ",", "id", "int64", ")", "(", "string", ",", "error", ")", "{", "cached", ",", "err", ":=", "mappingCache", ".", "Fetch", "(", "c", ",", "func", "(", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "time", ".", "Duration", ",", "error", ")", "{", "val", ",", "err", ":=", "LoadCAUniqueIDToCNMap", "(", "c", ")", "\n", "return", "val", ",", "time", ".", "Minute", ",", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "mapping", ":=", "cached", ".", "(", "map", "[", "int64", "]", "string", ")", "\n", "return", "mapping", "[", "id", "]", ",", "nil", "\n", "}" ]
// GetCAByUniqueID returns CN name that corresponds to given unique ID. // // It uses cached CAUniqueIDToCNMap for lookups. Returns empty string if there's // no such CA.
[ "GetCAByUniqueID", "returns", "CN", "name", "that", "corresponds", "to", "given", "unique", "ID", ".", "It", "uses", "cached", "CAUniqueIDToCNMap", "for", "lookups", ".", "Returns", "empty", "string", "if", "there", "s", "no", "such", "CA", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certconfig/ca.go#L145-L155
9,585
libp2p/go-libp2p-nat
nat.go
DiscoverNAT
func DiscoverNAT(ctx context.Context) (*NAT, error) { var ( natInstance nat.NAT err error ) done := make(chan struct{}) go func() { defer close(done) // This will abort in 10 seconds anyways. natInstance, err = nat.DiscoverGateway() }() select { case <-done: case <-ctx.Done(): return nil, ctx.Err() } if err != nil { return nil, err } // Log the device addr. addr, err := natInstance.GetDeviceAddress() if err != nil { log.Debug("DiscoverGateway address error:", err) } else { log.Debug("DiscoverGateway address:", addr) } return newNAT(natInstance), nil }
go
func DiscoverNAT(ctx context.Context) (*NAT, error) { var ( natInstance nat.NAT err error ) done := make(chan struct{}) go func() { defer close(done) // This will abort in 10 seconds anyways. natInstance, err = nat.DiscoverGateway() }() select { case <-done: case <-ctx.Done(): return nil, ctx.Err() } if err != nil { return nil, err } // Log the device addr. addr, err := natInstance.GetDeviceAddress() if err != nil { log.Debug("DiscoverGateway address error:", err) } else { log.Debug("DiscoverGateway address:", addr) } return newNAT(natInstance), nil }
[ "func", "DiscoverNAT", "(", "ctx", "context", ".", "Context", ")", "(", "*", "NAT", ",", "error", ")", "{", "var", "(", "natInstance", "nat", ".", "NAT", "\n", "err", "error", "\n", ")", "\n\n", "done", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "done", ")", "\n", "// This will abort in 10 seconds anyways.", "natInstance", ",", "err", "=", "nat", ".", "DiscoverGateway", "(", ")", "\n", "}", "(", ")", "\n\n", "select", "{", "case", "<-", "done", ":", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "nil", ",", "ctx", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Log the device addr.", "addr", ",", "err", ":=", "natInstance", ".", "GetDeviceAddress", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Debug", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "{", "log", ".", "Debug", "(", "\"", "\"", ",", "addr", ")", "\n", "}", "\n\n", "return", "newNAT", "(", "natInstance", ")", ",", "nil", "\n", "}" ]
// DiscoverNAT looks for a NAT device in the network and // returns an object that can manage port mappings.
[ "DiscoverNAT", "looks", "for", "a", "NAT", "device", "in", "the", "network", "and", "returns", "an", "object", "that", "can", "manage", "port", "mappings", "." ]
2736f3ac758bcdffdf068f7b28df7075a6707188
https://github.com/libp2p/go-libp2p-nat/blob/2736f3ac758bcdffdf068f7b28df7075a6707188/nat.go#L32-L64
9,586
libp2p/go-libp2p-nat
nat.go
Mappings
func (nat *NAT) Mappings() []Mapping { nat.mappingmu.Lock() maps2 := make([]Mapping, 0, len(nat.mappings)) for m := range nat.mappings { maps2 = append(maps2, m) } nat.mappingmu.Unlock() return maps2 }
go
func (nat *NAT) Mappings() []Mapping { nat.mappingmu.Lock() maps2 := make([]Mapping, 0, len(nat.mappings)) for m := range nat.mappings { maps2 = append(maps2, m) } nat.mappingmu.Unlock() return maps2 }
[ "func", "(", "nat", "*", "NAT", ")", "Mappings", "(", ")", "[", "]", "Mapping", "{", "nat", ".", "mappingmu", ".", "Lock", "(", ")", "\n", "maps2", ":=", "make", "(", "[", "]", "Mapping", ",", "0", ",", "len", "(", "nat", ".", "mappings", ")", ")", "\n", "for", "m", ":=", "range", "nat", ".", "mappings", "{", "maps2", "=", "append", "(", "maps2", ",", "m", ")", "\n", "}", "\n", "nat", ".", "mappingmu", ".", "Unlock", "(", ")", "\n", "return", "maps2", "\n", "}" ]
// Mappings returns a slice of all NAT mappings
[ "Mappings", "returns", "a", "slice", "of", "all", "NAT", "mappings" ]
2736f3ac758bcdffdf068f7b28df7075a6707188
https://github.com/libp2p/go-libp2p-nat/blob/2736f3ac758bcdffdf068f7b28df7075a6707188/nat.go#L99-L107
9,587
gernest/front
front.go
Handle
func (m *Matter) Handle(delim string, fn HandlerFunc) { m.handlers[delim] = fn }
go
func (m *Matter) Handle(delim string, fn HandlerFunc) { m.handlers[delim] = fn }
[ "func", "(", "m", "*", "Matter", ")", "Handle", "(", "delim", "string", ",", "fn", "HandlerFunc", ")", "{", "m", ".", "handlers", "[", "delim", "]", "=", "fn", "\n", "}" ]
//Handle registers a handler for the given frontmatter delimiter
[ "Handle", "registers", "a", "handler", "for", "the", "given", "frontmatter", "delimiter" ]
ed80ca338b8848e3bfc3fa13824c91ebbcad53db
https://github.com/gernest/front/blob/ed80ca338b8848e3bfc3fa13824c91ebbcad53db/front.go#L40-L42
9,588
gernest/front
front.go
Parse
func (m *Matter) Parse(input io.Reader) (front map[string]interface{}, body string, err error) { return m.parse(input) }
go
func (m *Matter) Parse(input io.Reader) (front map[string]interface{}, body string, err error) { return m.parse(input) }
[ "func", "(", "m", "*", "Matter", ")", "Parse", "(", "input", "io", ".", "Reader", ")", "(", "front", "map", "[", "string", "]", "interface", "{", "}", ",", "body", "string", ",", "err", "error", ")", "{", "return", "m", ".", "parse", "(", "input", ")", "\n", "}" ]
// Parse parses the input and extract the frontmatter
[ "Parse", "parses", "the", "input", "and", "extract", "the", "frontmatter" ]
ed80ca338b8848e3bfc3fa13824c91ebbcad53db
https://github.com/gernest/front/blob/ed80ca338b8848e3bfc3fa13824c91ebbcad53db/front.go#L45-L47
9,589
gernest/front
front.go
split
func (m *Matter) split(data []byte, atEOF bool) (advance int, token []byte, err error) { if atEOF && len(data) == 0 { return 0, nil, nil } delim, err := sniffDelim(data) if err != nil { return 0, nil, err } if _, ok := m.handlers[delim]; !ok { return 0, nil, ErrUnknownDelim } if x := bytes.Index(data, []byte(delim)); x >= 0 { // check the next delim index if next := bytes.Index(data[x+len(delim):], []byte(delim)); next > 0 { return next + len(delim), dropSpace(data[:next+len(delim)]), nil } return len(data), dropSpace(data[x+len(delim):]), nil } if atEOF { return len(data), data, nil } return 0, nil, nil }
go
func (m *Matter) split(data []byte, atEOF bool) (advance int, token []byte, err error) { if atEOF && len(data) == 0 { return 0, nil, nil } delim, err := sniffDelim(data) if err != nil { return 0, nil, err } if _, ok := m.handlers[delim]; !ok { return 0, nil, ErrUnknownDelim } if x := bytes.Index(data, []byte(delim)); x >= 0 { // check the next delim index if next := bytes.Index(data[x+len(delim):], []byte(delim)); next > 0 { return next + len(delim), dropSpace(data[:next+len(delim)]), nil } return len(data), dropSpace(data[x+len(delim):]), nil } if atEOF { return len(data), data, nil } return 0, nil, nil }
[ "func", "(", "m", "*", "Matter", ")", "split", "(", "data", "[", "]", "byte", ",", "atEOF", "bool", ")", "(", "advance", "int", ",", "token", "[", "]", "byte", ",", "err", "error", ")", "{", "if", "atEOF", "&&", "len", "(", "data", ")", "==", "0", "{", "return", "0", ",", "nil", ",", "nil", "\n", "}", "\n", "delim", ",", "err", ":=", "sniffDelim", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "m", ".", "handlers", "[", "delim", "]", ";", "!", "ok", "{", "return", "0", ",", "nil", ",", "ErrUnknownDelim", "\n", "}", "\n", "if", "x", ":=", "bytes", ".", "Index", "(", "data", ",", "[", "]", "byte", "(", "delim", ")", ")", ";", "x", ">=", "0", "{", "// check the next delim index", "if", "next", ":=", "bytes", ".", "Index", "(", "data", "[", "x", "+", "len", "(", "delim", ")", ":", "]", ",", "[", "]", "byte", "(", "delim", ")", ")", ";", "next", ">", "0", "{", "return", "next", "+", "len", "(", "delim", ")", ",", "dropSpace", "(", "data", "[", ":", "next", "+", "len", "(", "delim", ")", "]", ")", ",", "nil", "\n", "}", "\n", "return", "len", "(", "data", ")", ",", "dropSpace", "(", "data", "[", "x", "+", "len", "(", "delim", ")", ":", "]", ")", ",", "nil", "\n", "}", "\n", "if", "atEOF", "{", "return", "len", "(", "data", ")", ",", "data", ",", "nil", "\n", "}", "\n", "return", "0", ",", "nil", ",", "nil", "\n", "}" ]
//split implements bufio.SplitFunc for spliting front matter from the body text.
[ "split", "implements", "bufio", ".", "SplitFunc", "for", "spliting", "front", "matter", "from", "the", "body", "text", "." ]
ed80ca338b8848e3bfc3fa13824c91ebbcad53db
https://github.com/gernest/front/blob/ed80ca338b8848e3bfc3fa13824c91ebbcad53db/front.go#L97-L119
9,590
gernest/front
front.go
JSONHandler
func JSONHandler(front string) (map[string]interface{}, error) { var rst interface{} err := json.Unmarshal([]byte(front), &rst) if err != nil { return nil, err } return rst.(map[string]interface{}), nil }
go
func JSONHandler(front string) (map[string]interface{}, error) { var rst interface{} err := json.Unmarshal([]byte(front), &rst) if err != nil { return nil, err } return rst.(map[string]interface{}), nil }
[ "func", "JSONHandler", "(", "front", "string", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "var", "rst", "interface", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "front", ")", ",", "&", "rst", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "rst", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ",", "nil", "\n", "}" ]
//JSONHandler implements HandlerFunc interface. It extracts front matter data from the given // string argument by interpreting it as a json string.
[ "JSONHandler", "implements", "HandlerFunc", "interface", ".", "It", "extracts", "front", "matter", "data", "from", "the", "given", "string", "argument", "by", "interpreting", "it", "as", "a", "json", "string", "." ]
ed80ca338b8848e3bfc3fa13824c91ebbcad53db
https://github.com/gernest/front/blob/ed80ca338b8848e3bfc3fa13824c91ebbcad53db/front.go#L127-L134
9,591
mindprince/gonvml
bindings.go
errorString
func errorString(ret C.nvmlReturn_t) error { if ret == C.NVML_SUCCESS { return nil } // We need to special case this because if nvml library is not found // nvmlErrorString() method will not work. if ret == C.NVML_ERROR_LIBRARY_NOT_FOUND || C.nvmlHandle == nil { return errLibraryNotLoaded } err := C.GoString(C.nvmlErrorString(ret)) return fmt.Errorf("nvml: %v", err) }
go
func errorString(ret C.nvmlReturn_t) error { if ret == C.NVML_SUCCESS { return nil } // We need to special case this because if nvml library is not found // nvmlErrorString() method will not work. if ret == C.NVML_ERROR_LIBRARY_NOT_FOUND || C.nvmlHandle == nil { return errLibraryNotLoaded } err := C.GoString(C.nvmlErrorString(ret)) return fmt.Errorf("nvml: %v", err) }
[ "func", "errorString", "(", "ret", "C", ".", "nvmlReturn_t", ")", "error", "{", "if", "ret", "==", "C", ".", "NVML_SUCCESS", "{", "return", "nil", "\n", "}", "\n", "// We need to special case this because if nvml library is not found", "// nvmlErrorString() method will not work.", "if", "ret", "==", "C", ".", "NVML_ERROR_LIBRARY_NOT_FOUND", "||", "C", ".", "nvmlHandle", "==", "nil", "{", "return", "errLibraryNotLoaded", "\n", "}", "\n", "err", ":=", "C", ".", "GoString", "(", "C", ".", "nvmlErrorString", "(", "ret", ")", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}" ]
// errorString takes a nvmlReturn_t and converts it into a golang error. // It uses a nvml method to convert to a user friendly error message.
[ "errorString", "takes", "a", "nvmlReturn_t", "and", "converts", "it", "into", "a", "golang", "error", ".", "It", "uses", "a", "nvml", "method", "to", "convert", "to", "a", "user", "friendly", "error", "message", "." ]
b364b296c7320f5d3dc084aa536a3dba33b68f90
https://github.com/mindprince/gonvml/blob/b364b296c7320f5d3dc084aa536a3dba33b68f90/bindings.go#L340-L351
9,592
mindprince/gonvml
bindings.go
SystemDriverVersion
func SystemDriverVersion() (string, error) { if C.nvmlHandle == nil { return "", errLibraryNotLoaded } var driver [szDriver]C.char r := C.nvmlSystemGetDriverVersion(&driver[0], szDriver) return C.GoString(&driver[0]), errorString(r) }
go
func SystemDriverVersion() (string, error) { if C.nvmlHandle == nil { return "", errLibraryNotLoaded } var driver [szDriver]C.char r := C.nvmlSystemGetDriverVersion(&driver[0], szDriver) return C.GoString(&driver[0]), errorString(r) }
[ "func", "SystemDriverVersion", "(", ")", "(", "string", ",", "error", ")", "{", "if", "C", ".", "nvmlHandle", "==", "nil", "{", "return", "\"", "\"", ",", "errLibraryNotLoaded", "\n", "}", "\n", "var", "driver", "[", "szDriver", "]", "C", ".", "char", "\n", "r", ":=", "C", ".", "nvmlSystemGetDriverVersion", "(", "&", "driver", "[", "0", "]", ",", "szDriver", ")", "\n", "return", "C", ".", "GoString", "(", "&", "driver", "[", "0", "]", ")", ",", "errorString", "(", "r", ")", "\n", "}" ]
// SystemDriverVersion returns the the driver version on the system.
[ "SystemDriverVersion", "returns", "the", "the", "driver", "version", "on", "the", "system", "." ]
b364b296c7320f5d3dc084aa536a3dba33b68f90
https://github.com/mindprince/gonvml/blob/b364b296c7320f5d3dc084aa536a3dba33b68f90/bindings.go#L354-L361
9,593
mindprince/gonvml
bindings.go
DeviceCount
func DeviceCount() (uint, error) { if C.nvmlHandle == nil { return 0, errLibraryNotLoaded } var n C.uint r := C.nvmlDeviceGetCount(&n) return uint(n), errorString(r) }
go
func DeviceCount() (uint, error) { if C.nvmlHandle == nil { return 0, errLibraryNotLoaded } var n C.uint r := C.nvmlDeviceGetCount(&n) return uint(n), errorString(r) }
[ "func", "DeviceCount", "(", ")", "(", "uint", ",", "error", ")", "{", "if", "C", ".", "nvmlHandle", "==", "nil", "{", "return", "0", ",", "errLibraryNotLoaded", "\n", "}", "\n", "var", "n", "C", ".", "uint", "\n", "r", ":=", "C", ".", "nvmlDeviceGetCount", "(", "&", "n", ")", "\n", "return", "uint", "(", "n", ")", ",", "errorString", "(", "r", ")", "\n", "}" ]
// DeviceCount returns the number of nvidia devices on the system.
[ "DeviceCount", "returns", "the", "number", "of", "nvidia", "devices", "on", "the", "system", "." ]
b364b296c7320f5d3dc084aa536a3dba33b68f90
https://github.com/mindprince/gonvml/blob/b364b296c7320f5d3dc084aa536a3dba33b68f90/bindings.go#L364-L371
9,594
mindprince/gonvml
bindings.go
UUID
func (d Device) UUID() (string, error) { if C.nvmlHandle == nil { return "", errLibraryNotLoaded } var uuid [szUUID]C.char r := C.nvmlDeviceGetUUID(d.dev, &uuid[0], szUUID) return C.GoString(&uuid[0]), errorString(r) }
go
func (d Device) UUID() (string, error) { if C.nvmlHandle == nil { return "", errLibraryNotLoaded } var uuid [szUUID]C.char r := C.nvmlDeviceGetUUID(d.dev, &uuid[0], szUUID) return C.GoString(&uuid[0]), errorString(r) }
[ "func", "(", "d", "Device", ")", "UUID", "(", ")", "(", "string", ",", "error", ")", "{", "if", "C", ".", "nvmlHandle", "==", "nil", "{", "return", "\"", "\"", ",", "errLibraryNotLoaded", "\n", "}", "\n", "var", "uuid", "[", "szUUID", "]", "C", ".", "char", "\n", "r", ":=", "C", ".", "nvmlDeviceGetUUID", "(", "d", ".", "dev", ",", "&", "uuid", "[", "0", "]", ",", "szUUID", ")", "\n", "return", "C", ".", "GoString", "(", "&", "uuid", "[", "0", "]", ")", ",", "errorString", "(", "r", ")", "\n", "}" ]
// UUID returns the globally unique immutable UUID associated with this device.
[ "UUID", "returns", "the", "globally", "unique", "immutable", "UUID", "associated", "with", "this", "device", "." ]
b364b296c7320f5d3dc084aa536a3dba33b68f90
https://github.com/mindprince/gonvml/blob/b364b296c7320f5d3dc084aa536a3dba33b68f90/bindings.go#L404-L411
9,595
mindprince/gonvml
bindings.go
Name
func (d Device) Name() (string, error) { if C.nvmlHandle == nil { return "", errLibraryNotLoaded } var name [szName]C.char r := C.nvmlDeviceGetName(d.dev, &name[0], szName) return C.GoString(&name[0]), errorString(r) }
go
func (d Device) Name() (string, error) { if C.nvmlHandle == nil { return "", errLibraryNotLoaded } var name [szName]C.char r := C.nvmlDeviceGetName(d.dev, &name[0], szName) return C.GoString(&name[0]), errorString(r) }
[ "func", "(", "d", "Device", ")", "Name", "(", ")", "(", "string", ",", "error", ")", "{", "if", "C", ".", "nvmlHandle", "==", "nil", "{", "return", "\"", "\"", ",", "errLibraryNotLoaded", "\n", "}", "\n", "var", "name", "[", "szName", "]", "C", ".", "char", "\n", "r", ":=", "C", ".", "nvmlDeviceGetName", "(", "d", ".", "dev", ",", "&", "name", "[", "0", "]", ",", "szName", ")", "\n", "return", "C", ".", "GoString", "(", "&", "name", "[", "0", "]", ")", ",", "errorString", "(", "r", ")", "\n", "}" ]
// Name returns the product name of the device.
[ "Name", "returns", "the", "product", "name", "of", "the", "device", "." ]
b364b296c7320f5d3dc084aa536a3dba33b68f90
https://github.com/mindprince/gonvml/blob/b364b296c7320f5d3dc084aa536a3dba33b68f90/bindings.go#L414-L421
9,596
mindprince/gonvml
bindings.go
AveragePowerUsage
func (d Device) AveragePowerUsage(since time.Duration) (uint, error) { if C.nvmlHandle == nil { return 0, errLibraryNotLoaded } lastTs := C.ulonglong(time.Now().Add(-1*since).UnixNano() / 1000) var n C.uint r := C.nvmlDeviceGetAverageUsage(d.dev, C.NVML_TOTAL_POWER_SAMPLES, lastTs, &n) return uint(n), errorString(r) }
go
func (d Device) AveragePowerUsage(since time.Duration) (uint, error) { if C.nvmlHandle == nil { return 0, errLibraryNotLoaded } lastTs := C.ulonglong(time.Now().Add(-1*since).UnixNano() / 1000) var n C.uint r := C.nvmlDeviceGetAverageUsage(d.dev, C.NVML_TOTAL_POWER_SAMPLES, lastTs, &n) return uint(n), errorString(r) }
[ "func", "(", "d", "Device", ")", "AveragePowerUsage", "(", "since", "time", ".", "Duration", ")", "(", "uint", ",", "error", ")", "{", "if", "C", ".", "nvmlHandle", "==", "nil", "{", "return", "0", ",", "errLibraryNotLoaded", "\n", "}", "\n", "lastTs", ":=", "C", ".", "ulonglong", "(", "time", ".", "Now", "(", ")", ".", "Add", "(", "-", "1", "*", "since", ")", ".", "UnixNano", "(", ")", "/", "1000", ")", "\n", "var", "n", "C", ".", "uint", "\n", "r", ":=", "C", ".", "nvmlDeviceGetAverageUsage", "(", "d", ".", "dev", ",", "C", ".", "NVML_TOTAL_POWER_SAMPLES", ",", "lastTs", ",", "&", "n", ")", "\n", "return", "uint", "(", "n", ")", ",", "errorString", "(", "r", ")", "\n", "}" ]
// AveragePowerUsage returns the power usage for this GPU and its associated circuitry // in milliwatts averaged over the samples collected in the last `since` duration.
[ "AveragePowerUsage", "returns", "the", "power", "usage", "for", "this", "GPU", "and", "its", "associated", "circuitry", "in", "milliwatts", "averaged", "over", "the", "samples", "collected", "in", "the", "last", "since", "duration", "." ]
b364b296c7320f5d3dc084aa536a3dba33b68f90
https://github.com/mindprince/gonvml/blob/b364b296c7320f5d3dc084aa536a3dba33b68f90/bindings.go#L458-L466
9,597
mindprince/gonvml
bindings.go
Temperature
func (d Device) Temperature() (uint, error) { if C.nvmlHandle == nil { return 0, errLibraryNotLoaded } var n C.uint r := C.nvmlDeviceGetTemperature(d.dev, C.NVML_TEMPERATURE_GPU, &n) return uint(n), errorString(r) }
go
func (d Device) Temperature() (uint, error) { if C.nvmlHandle == nil { return 0, errLibraryNotLoaded } var n C.uint r := C.nvmlDeviceGetTemperature(d.dev, C.NVML_TEMPERATURE_GPU, &n) return uint(n), errorString(r) }
[ "func", "(", "d", "Device", ")", "Temperature", "(", ")", "(", "uint", ",", "error", ")", "{", "if", "C", ".", "nvmlHandle", "==", "nil", "{", "return", "0", ",", "errLibraryNotLoaded", "\n", "}", "\n", "var", "n", "C", ".", "uint", "\n", "r", ":=", "C", ".", "nvmlDeviceGetTemperature", "(", "d", ".", "dev", ",", "C", ".", "NVML_TEMPERATURE_GPU", ",", "&", "n", ")", "\n", "return", "uint", "(", "n", ")", ",", "errorString", "(", "r", ")", "\n", "}" ]
// Temperature returns the temperature for this GPU in Celsius.
[ "Temperature", "returns", "the", "temperature", "for", "this", "GPU", "in", "Celsius", "." ]
b364b296c7320f5d3dc084aa536a3dba33b68f90
https://github.com/mindprince/gonvml/blob/b364b296c7320f5d3dc084aa536a3dba33b68f90/bindings.go#L482-L489
9,598
mindprince/gonvml
bindings.go
FanSpeed
func (d Device) FanSpeed() (uint, error) { if C.nvmlHandle == nil { return 0, errLibraryNotLoaded } var n C.uint r := C.nvmlDeviceGetFanSpeed(d.dev, &n) return uint(n), errorString(r) }
go
func (d Device) FanSpeed() (uint, error) { if C.nvmlHandle == nil { return 0, errLibraryNotLoaded } var n C.uint r := C.nvmlDeviceGetFanSpeed(d.dev, &n) return uint(n), errorString(r) }
[ "func", "(", "d", "Device", ")", "FanSpeed", "(", ")", "(", "uint", ",", "error", ")", "{", "if", "C", ".", "nvmlHandle", "==", "nil", "{", "return", "0", ",", "errLibraryNotLoaded", "\n", "}", "\n", "var", "n", "C", ".", "uint", "\n", "r", ":=", "C", ".", "nvmlDeviceGetFanSpeed", "(", "d", ".", "dev", ",", "&", "n", ")", "\n", "return", "uint", "(", "n", ")", ",", "errorString", "(", "r", ")", "\n", "}" ]
// FanSpeed returns the temperature for this GPU in the percentage of its full // speed, with 100 being the maximum.
[ "FanSpeed", "returns", "the", "temperature", "for", "this", "GPU", "in", "the", "percentage", "of", "its", "full", "speed", "with", "100", "being", "the", "maximum", "." ]
b364b296c7320f5d3dc084aa536a3dba33b68f90
https://github.com/mindprince/gonvml/blob/b364b296c7320f5d3dc084aa536a3dba33b68f90/bindings.go#L493-L500
9,599
mindprince/gonvml
bindings.go
EncoderUtilization
func (d Device) EncoderUtilization() (uint, uint, error) { if C.nvmlHandle == nil { return 0, 0, errLibraryNotLoaded } var n C.uint var sp C.uint r := C.nvmlDeviceGetEncoderUtilization(d.dev, &n, &sp) return uint(n), uint(sp), errorString(r) }
go
func (d Device) EncoderUtilization() (uint, uint, error) { if C.nvmlHandle == nil { return 0, 0, errLibraryNotLoaded } var n C.uint var sp C.uint r := C.nvmlDeviceGetEncoderUtilization(d.dev, &n, &sp) return uint(n), uint(sp), errorString(r) }
[ "func", "(", "d", "Device", ")", "EncoderUtilization", "(", ")", "(", "uint", ",", "uint", ",", "error", ")", "{", "if", "C", ".", "nvmlHandle", "==", "nil", "{", "return", "0", ",", "0", ",", "errLibraryNotLoaded", "\n", "}", "\n", "var", "n", "C", ".", "uint", "\n", "var", "sp", "C", ".", "uint", "\n", "r", ":=", "C", ".", "nvmlDeviceGetEncoderUtilization", "(", "d", ".", "dev", ",", "&", "n", ",", "&", "sp", ")", "\n", "return", "uint", "(", "n", ")", ",", "uint", "(", "sp", ")", ",", "errorString", "(", "r", ")", "\n", "}" ]
// EncoderUtilization returns the percent of time over the last sample period during which the GPU video encoder was being used. // The sampling period is variable and is returned in the second return argument in microseconds.
[ "EncoderUtilization", "returns", "the", "percent", "of", "time", "over", "the", "last", "sample", "period", "during", "which", "the", "GPU", "video", "encoder", "was", "being", "used", ".", "The", "sampling", "period", "is", "variable", "and", "is", "returned", "in", "the", "second", "return", "argument", "in", "microseconds", "." ]
b364b296c7320f5d3dc084aa536a3dba33b68f90
https://github.com/mindprince/gonvml/blob/b364b296c7320f5d3dc084aa536a3dba33b68f90/bindings.go#L504-L512