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
listlengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
listlengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
11,800 |
newrelic/sidecar
|
sidecarhttp/http_api.go
|
oneServiceHandler
|
func (s *SidecarApi) oneServiceHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
defer req.Body.Close()
response.Header().Set("Access-Control-Allow-Origin", "*")
response.Header().Set("Access-Control-Allow-Methods", "GET")
response.Header().Set("Content-Type", "application/json")
if params["extension"] != "json" {
sendJsonError(response, 404, "Not Found - Invalid content type extension")
return
}
name, ok := params["name"]
if !ok {
sendJsonError(response, 404, "Not Found - No service name provided")
return
}
if s.state == nil {
sendJsonError(response, 500, "Internal Server Error - Something went terribly wrong")
return
}
var instances []*service.Service
// Enter critical section
s.state.RLock()
defer s.state.RUnlock()
s.state.EachService(func(hostname *string, id *string, svc *service.Service) {
if svc.Name == name {
instances = append(instances, svc)
}
})
// Did we have any entries for this service in the catalog?
if len(instances) == 0 {
sendJsonError(response, 404, fmt.Sprintf("no instances of %s found", name))
return
}
clusterName := ""
if s.list != nil {
clusterName = s.list.ClusterName()
}
// Everything went fine, we found entries for this service.
// Send the json back.
svcInstances := make(map[string][]*service.Service)
svcInstances[name] = instances
result := ApiServices{
Services: svcInstances,
ClusterName: clusterName,
}
jsonBytes, err := json.MarshalIndent(&result, "", " ")
if err != nil {
log.Errorf("Error marshaling state in oneServiceHandler: %s", err.Error())
sendJsonError(response, 500, "Internal server error")
return
}
response.Write(jsonBytes)
}
|
go
|
func (s *SidecarApi) oneServiceHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
defer req.Body.Close()
response.Header().Set("Access-Control-Allow-Origin", "*")
response.Header().Set("Access-Control-Allow-Methods", "GET")
response.Header().Set("Content-Type", "application/json")
if params["extension"] != "json" {
sendJsonError(response, 404, "Not Found - Invalid content type extension")
return
}
name, ok := params["name"]
if !ok {
sendJsonError(response, 404, "Not Found - No service name provided")
return
}
if s.state == nil {
sendJsonError(response, 500, "Internal Server Error - Something went terribly wrong")
return
}
var instances []*service.Service
// Enter critical section
s.state.RLock()
defer s.state.RUnlock()
s.state.EachService(func(hostname *string, id *string, svc *service.Service) {
if svc.Name == name {
instances = append(instances, svc)
}
})
// Did we have any entries for this service in the catalog?
if len(instances) == 0 {
sendJsonError(response, 404, fmt.Sprintf("no instances of %s found", name))
return
}
clusterName := ""
if s.list != nil {
clusterName = s.list.ClusterName()
}
// Everything went fine, we found entries for this service.
// Send the json back.
svcInstances := make(map[string][]*service.Service)
svcInstances[name] = instances
result := ApiServices{
Services: svcInstances,
ClusterName: clusterName,
}
jsonBytes, err := json.MarshalIndent(&result, "", " ")
if err != nil {
log.Errorf("Error marshaling state in oneServiceHandler: %s", err.Error())
sendJsonError(response, 500, "Internal server error")
return
}
response.Write(jsonBytes)
}
|
[
"func",
"(",
"s",
"*",
"SidecarApi",
")",
"oneServiceHandler",
"(",
"response",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"map",
"[",
"string",
"]",
"string",
")",
"{",
"defer",
"req",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"params",
"[",
"\"",
"\"",
"]",
"!=",
"\"",
"\"",
"{",
"sendJsonError",
"(",
"response",
",",
"404",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"name",
",",
"ok",
":=",
"params",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"sendJsonError",
"(",
"response",
",",
"404",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"s",
".",
"state",
"==",
"nil",
"{",
"sendJsonError",
"(",
"response",
",",
"500",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"var",
"instances",
"[",
"]",
"*",
"service",
".",
"Service",
"\n",
"// Enter critical section",
"s",
".",
"state",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"state",
".",
"RUnlock",
"(",
")",
"\n",
"s",
".",
"state",
".",
"EachService",
"(",
"func",
"(",
"hostname",
"*",
"string",
",",
"id",
"*",
"string",
",",
"svc",
"*",
"service",
".",
"Service",
")",
"{",
"if",
"svc",
".",
"Name",
"==",
"name",
"{",
"instances",
"=",
"append",
"(",
"instances",
",",
"svc",
")",
"\n",
"}",
"\n",
"}",
")",
"\n\n",
"// Did we have any entries for this service in the catalog?",
"if",
"len",
"(",
"instances",
")",
"==",
"0",
"{",
"sendJsonError",
"(",
"response",
",",
"404",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"clusterName",
":=",
"\"",
"\"",
"\n",
"if",
"s",
".",
"list",
"!=",
"nil",
"{",
"clusterName",
"=",
"s",
".",
"list",
".",
"ClusterName",
"(",
")",
"\n",
"}",
"\n\n",
"// Everything went fine, we found entries for this service.",
"// Send the json back.",
"svcInstances",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"service",
".",
"Service",
")",
"\n",
"svcInstances",
"[",
"name",
"]",
"=",
"instances",
"\n",
"result",
":=",
"ApiServices",
"{",
"Services",
":",
"svcInstances",
",",
"ClusterName",
":",
"clusterName",
",",
"}",
"\n\n",
"jsonBytes",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"&",
"result",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"sendJsonError",
"(",
"response",
",",
"500",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"response",
".",
"Write",
"(",
"jsonBytes",
")",
"\n",
"}"
] |
// oneServiceHandler takes the name of a single service and returns results for just
// that service.
|
[
"oneServiceHandler",
"takes",
"the",
"name",
"of",
"a",
"single",
"service",
"and",
"returns",
"results",
"for",
"just",
"that",
"service",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/http_api.go#L129-L190
|
11,801 |
newrelic/sidecar
|
sidecarhttp/http_api.go
|
servicesHandler
|
func (s *SidecarApi) servicesHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
defer req.Body.Close()
response.Header().Set("Access-Control-Allow-Origin", "*")
response.Header().Set("Access-Control-Allow-Methods", "GET")
// We only support JSON
if params["extension"] != "json" {
sendJsonError(response, 404, "Not Found - Invalid content type extension")
return
}
response.Header().Set("Content-Type", "application/json")
var listMembers []*memberlist.Node
var clusterName string
if s.list != nil {
listMembers = s.list.Members()
sort.Sort(catalog.ListByName(listMembers))
clusterName = s.list.ClusterName()
}
members := make(map[string]*ApiServer, len(listMembers))
var jsonBytes []byte
var err error
func() { // Wrap critical section
s.state.RLock()
defer s.state.RUnlock()
for _, member := range listMembers {
if s.state.HasServer(member.Name) {
members[member.Name] = &ApiServer{
Name: member.Name,
LastUpdated: s.state.Servers[member.Name].LastUpdated,
ServiceCount: len(s.state.Servers[member.Name].Services),
}
} else {
members[member.Name] = &ApiServer{
Name: member.Name,
LastUpdated: time.Unix(0, 0),
ServiceCount: 0,
}
}
}
result := ApiServices{
Services: s.state.ByService(),
ClusterMembers: members,
ClusterName: clusterName,
}
jsonBytes, err = json.MarshalIndent(&result, "", " ")
}()
if err != nil {
log.Errorf("Error marshaling state in servicesHandler: %s", err.Error())
sendJsonError(response, 500, "Internal server error")
return
}
response.Write(jsonBytes)
}
|
go
|
func (s *SidecarApi) servicesHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
defer req.Body.Close()
response.Header().Set("Access-Control-Allow-Origin", "*")
response.Header().Set("Access-Control-Allow-Methods", "GET")
// We only support JSON
if params["extension"] != "json" {
sendJsonError(response, 404, "Not Found - Invalid content type extension")
return
}
response.Header().Set("Content-Type", "application/json")
var listMembers []*memberlist.Node
var clusterName string
if s.list != nil {
listMembers = s.list.Members()
sort.Sort(catalog.ListByName(listMembers))
clusterName = s.list.ClusterName()
}
members := make(map[string]*ApiServer, len(listMembers))
var jsonBytes []byte
var err error
func() { // Wrap critical section
s.state.RLock()
defer s.state.RUnlock()
for _, member := range listMembers {
if s.state.HasServer(member.Name) {
members[member.Name] = &ApiServer{
Name: member.Name,
LastUpdated: s.state.Servers[member.Name].LastUpdated,
ServiceCount: len(s.state.Servers[member.Name].Services),
}
} else {
members[member.Name] = &ApiServer{
Name: member.Name,
LastUpdated: time.Unix(0, 0),
ServiceCount: 0,
}
}
}
result := ApiServices{
Services: s.state.ByService(),
ClusterMembers: members,
ClusterName: clusterName,
}
jsonBytes, err = json.MarshalIndent(&result, "", " ")
}()
if err != nil {
log.Errorf("Error marshaling state in servicesHandler: %s", err.Error())
sendJsonError(response, 500, "Internal server error")
return
}
response.Write(jsonBytes)
}
|
[
"func",
"(",
"s",
"*",
"SidecarApi",
")",
"servicesHandler",
"(",
"response",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"map",
"[",
"string",
"]",
"string",
")",
"{",
"defer",
"req",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"// We only support JSON",
"if",
"params",
"[",
"\"",
"\"",
"]",
"!=",
"\"",
"\"",
"{",
"sendJsonError",
"(",
"response",
",",
"404",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"var",
"listMembers",
"[",
"]",
"*",
"memberlist",
".",
"Node",
"\n",
"var",
"clusterName",
"string",
"\n",
"if",
"s",
".",
"list",
"!=",
"nil",
"{",
"listMembers",
"=",
"s",
".",
"list",
".",
"Members",
"(",
")",
"\n",
"sort",
".",
"Sort",
"(",
"catalog",
".",
"ListByName",
"(",
"listMembers",
")",
")",
"\n",
"clusterName",
"=",
"s",
".",
"list",
".",
"ClusterName",
"(",
")",
"\n",
"}",
"\n\n",
"members",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"ApiServer",
",",
"len",
"(",
"listMembers",
")",
")",
"\n\n",
"var",
"jsonBytes",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n\n",
"func",
"(",
")",
"{",
"// Wrap critical section",
"s",
".",
"state",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"state",
".",
"RUnlock",
"(",
")",
"\n\n",
"for",
"_",
",",
"member",
":=",
"range",
"listMembers",
"{",
"if",
"s",
".",
"state",
".",
"HasServer",
"(",
"member",
".",
"Name",
")",
"{",
"members",
"[",
"member",
".",
"Name",
"]",
"=",
"&",
"ApiServer",
"{",
"Name",
":",
"member",
".",
"Name",
",",
"LastUpdated",
":",
"s",
".",
"state",
".",
"Servers",
"[",
"member",
".",
"Name",
"]",
".",
"LastUpdated",
",",
"ServiceCount",
":",
"len",
"(",
"s",
".",
"state",
".",
"Servers",
"[",
"member",
".",
"Name",
"]",
".",
"Services",
")",
",",
"}",
"\n",
"}",
"else",
"{",
"members",
"[",
"member",
".",
"Name",
"]",
"=",
"&",
"ApiServer",
"{",
"Name",
":",
"member",
".",
"Name",
",",
"LastUpdated",
":",
"time",
".",
"Unix",
"(",
"0",
",",
"0",
")",
",",
"ServiceCount",
":",
"0",
",",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"result",
":=",
"ApiServices",
"{",
"Services",
":",
"s",
".",
"state",
".",
"ByService",
"(",
")",
",",
"ClusterMembers",
":",
"members",
",",
"ClusterName",
":",
"clusterName",
",",
"}",
"\n\n",
"jsonBytes",
",",
"err",
"=",
"json",
".",
"MarshalIndent",
"(",
"&",
"result",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"sendJsonError",
"(",
"response",
",",
"500",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"response",
".",
"Write",
"(",
"jsonBytes",
")",
"\n",
"}"
] |
// serviceHandler returns the results for all the services we know about
|
[
"serviceHandler",
"returns",
"the",
"results",
"for",
"all",
"the",
"services",
"we",
"know",
"about"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/http_api.go#L193-L256
|
11,802 |
newrelic/sidecar
|
sidecarhttp/http_api.go
|
stateHandler
|
func (s *SidecarApi) stateHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
defer req.Body.Close()
s.state.RLock()
defer s.state.RUnlock()
if params["extension"] != "json" {
sendJsonError(response, 404, "Not Found - Invalid content type extension")
return
}
response.Header().Set("Content-Type", "application/json")
response.Header().Set("Access-Control-Allow-Origin", "*")
response.Header().Set("Access-Control-Allow-Methods", "GET")
response.Write(s.state.Encode())
return
}
|
go
|
func (s *SidecarApi) stateHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
defer req.Body.Close()
s.state.RLock()
defer s.state.RUnlock()
if params["extension"] != "json" {
sendJsonError(response, 404, "Not Found - Invalid content type extension")
return
}
response.Header().Set("Content-Type", "application/json")
response.Header().Set("Access-Control-Allow-Origin", "*")
response.Header().Set("Access-Control-Allow-Methods", "GET")
response.Write(s.state.Encode())
return
}
|
[
"func",
"(",
"s",
"*",
"SidecarApi",
")",
"stateHandler",
"(",
"response",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"map",
"[",
"string",
"]",
"string",
")",
"{",
"defer",
"req",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"s",
".",
"state",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"state",
".",
"RUnlock",
"(",
")",
"\n\n",
"if",
"params",
"[",
"\"",
"\"",
"]",
"!=",
"\"",
"\"",
"{",
"sendJsonError",
"(",
"response",
",",
"404",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"response",
".",
"Write",
"(",
"s",
".",
"state",
".",
"Encode",
"(",
")",
")",
"\n",
"return",
"\n",
"}"
] |
// stateHandler simply dumps the JSON output of the whole state object. This is
// useful for listeners or other clients that need a full state dump on startup.
|
[
"stateHandler",
"simply",
"dumps",
"the",
"JSON",
"output",
"of",
"the",
"whole",
"state",
"object",
".",
"This",
"is",
"useful",
"for",
"listeners",
"or",
"other",
"clients",
"that",
"need",
"a",
"full",
"state",
"dump",
"on",
"startup",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/http_api.go#L260-L276
|
11,803 |
newrelic/sidecar
|
sidecarhttp/http_api.go
|
sendJsonError
|
func sendJsonError(response http.ResponseWriter, status int, message string) {
output := map[string]string{
"status": "error",
"message": message,
}
jsonBytes, err := json.Marshal(output)
if err != nil {
log.Errorf("Error encoding json error response: %s", err.Error())
response.WriteHeader(500)
response.Write([]byte("Interval server error"))
return
}
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(status)
response.Write(jsonBytes)
}
|
go
|
func sendJsonError(response http.ResponseWriter, status int, message string) {
output := map[string]string{
"status": "error",
"message": message,
}
jsonBytes, err := json.Marshal(output)
if err != nil {
log.Errorf("Error encoding json error response: %s", err.Error())
response.WriteHeader(500)
response.Write([]byte("Interval server error"))
return
}
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(status)
response.Write(jsonBytes)
}
|
[
"func",
"sendJsonError",
"(",
"response",
"http",
".",
"ResponseWriter",
",",
"status",
"int",
",",
"message",
"string",
")",
"{",
"output",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"message",
",",
"}",
"\n\n",
"jsonBytes",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"output",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"response",
".",
"WriteHeader",
"(",
"500",
")",
"\n",
"response",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"response",
".",
"WriteHeader",
"(",
"status",
")",
"\n",
"response",
".",
"Write",
"(",
"jsonBytes",
")",
"\n",
"}"
] |
// Send back a JSON encoded error and message
|
[
"Send",
"back",
"a",
"JSON",
"encoded",
"error",
"and",
"message"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/http_api.go#L279-L297
|
11,804 |
newrelic/sidecar
|
healthy/service_bridge.go
|
defaultCheckForService
|
func (m *Monitor) defaultCheckForService(svc *service.Service) *Check {
port := findFirstTCPPort(svc)
if port == nil {
return &Check{ID: svc.ID, Command: &AlwaysSuccessfulCmd{}}
}
// Use the const default unless we've been provided something else
defaultCheckEndpoint := DEFAULT_STATUS_ENDPOINT
if len(m.DefaultCheckEndpoint) != 0 {
defaultCheckEndpoint = m.DefaultCheckEndpoint
}
url := fmt.Sprintf("http://%v:%v%v", m.DefaultCheckHost, port.Port, defaultCheckEndpoint)
return &Check{
ID: svc.ID,
Type: "HttpGet",
Args: url,
Status: FAILED,
Command: &HttpGetCmd{},
}
}
|
go
|
func (m *Monitor) defaultCheckForService(svc *service.Service) *Check {
port := findFirstTCPPort(svc)
if port == nil {
return &Check{ID: svc.ID, Command: &AlwaysSuccessfulCmd{}}
}
// Use the const default unless we've been provided something else
defaultCheckEndpoint := DEFAULT_STATUS_ENDPOINT
if len(m.DefaultCheckEndpoint) != 0 {
defaultCheckEndpoint = m.DefaultCheckEndpoint
}
url := fmt.Sprintf("http://%v:%v%v", m.DefaultCheckHost, port.Port, defaultCheckEndpoint)
return &Check{
ID: svc.ID,
Type: "HttpGet",
Args: url,
Status: FAILED,
Command: &HttpGetCmd{},
}
}
|
[
"func",
"(",
"m",
"*",
"Monitor",
")",
"defaultCheckForService",
"(",
"svc",
"*",
"service",
".",
"Service",
")",
"*",
"Check",
"{",
"port",
":=",
"findFirstTCPPort",
"(",
"svc",
")",
"\n",
"if",
"port",
"==",
"nil",
"{",
"return",
"&",
"Check",
"{",
"ID",
":",
"svc",
".",
"ID",
",",
"Command",
":",
"&",
"AlwaysSuccessfulCmd",
"{",
"}",
"}",
"\n",
"}",
"\n\n",
"// Use the const default unless we've been provided something else",
"defaultCheckEndpoint",
":=",
"DEFAULT_STATUS_ENDPOINT",
"\n",
"if",
"len",
"(",
"m",
".",
"DefaultCheckEndpoint",
")",
"!=",
"0",
"{",
"defaultCheckEndpoint",
"=",
"m",
".",
"DefaultCheckEndpoint",
"\n",
"}",
"\n\n",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"m",
".",
"DefaultCheckHost",
",",
"port",
".",
"Port",
",",
"defaultCheckEndpoint",
")",
"\n",
"return",
"&",
"Check",
"{",
"ID",
":",
"svc",
".",
"ID",
",",
"Type",
":",
"\"",
"\"",
",",
"Args",
":",
"url",
",",
"Status",
":",
"FAILED",
",",
"Command",
":",
"&",
"HttpGetCmd",
"{",
"}",
",",
"}",
"\n",
"}"
] |
// Configure a default check for a service. The default is to return an HTTP
// check on the first TCP port on the endpoint set in DEFAULT_STATUS_ENDPOINT.
|
[
"Configure",
"a",
"default",
"check",
"for",
"a",
"service",
".",
"The",
"default",
"is",
"to",
"return",
"an",
"HTTP",
"check",
"on",
"the",
"first",
"TCP",
"port",
"on",
"the",
"endpoint",
"set",
"in",
"DEFAULT_STATUS_ENDPOINT",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/healthy/service_bridge.go#L50-L70
|
11,805 |
newrelic/sidecar
|
healthy/service_bridge.go
|
fetchCheckForService
|
func (m *Monitor) fetchCheckForService(svc *service.Service, disco discovery.Discoverer) *Check {
check := &Check{}
check.Type, check.Args = disco.HealthCheck(svc)
if check.Type == "" {
log.Warnf("Got empty check type for service %s (id: %s) with args: %s!", svc.Name, svc.ID, check.Args)
return nil
}
// Setup some other parts of the check that don't come from discovery
check.ID = svc.ID
check.Command = m.GetCommandNamed(check.Type)
check.Status = FAILED
return check
}
|
go
|
func (m *Monitor) fetchCheckForService(svc *service.Service, disco discovery.Discoverer) *Check {
check := &Check{}
check.Type, check.Args = disco.HealthCheck(svc)
if check.Type == "" {
log.Warnf("Got empty check type for service %s (id: %s) with args: %s!", svc.Name, svc.ID, check.Args)
return nil
}
// Setup some other parts of the check that don't come from discovery
check.ID = svc.ID
check.Command = m.GetCommandNamed(check.Type)
check.Status = FAILED
return check
}
|
[
"func",
"(",
"m",
"*",
"Monitor",
")",
"fetchCheckForService",
"(",
"svc",
"*",
"service",
".",
"Service",
",",
"disco",
"discovery",
".",
"Discoverer",
")",
"*",
"Check",
"{",
"check",
":=",
"&",
"Check",
"{",
"}",
"\n",
"check",
".",
"Type",
",",
"check",
".",
"Args",
"=",
"disco",
".",
"HealthCheck",
"(",
"svc",
")",
"\n",
"if",
"check",
".",
"Type",
"==",
"\"",
"\"",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"svc",
".",
"Name",
",",
"svc",
".",
"ID",
",",
"check",
".",
"Args",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Setup some other parts of the check that don't come from discovery",
"check",
".",
"ID",
"=",
"svc",
".",
"ID",
"\n",
"check",
".",
"Command",
"=",
"m",
".",
"GetCommandNamed",
"(",
"check",
".",
"Type",
")",
"\n",
"check",
".",
"Status",
"=",
"FAILED",
"\n\n",
"return",
"check",
"\n",
"}"
] |
// Talks to a Discoverer and returns the configured check
|
[
"Talks",
"to",
"a",
"Discoverer",
"and",
"returns",
"the",
"configured",
"check"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/healthy/service_bridge.go#L86-L101
|
11,806 |
newrelic/sidecar
|
healthy/service_bridge.go
|
templateCheckArgs
|
func (m *Monitor) templateCheckArgs(check *Check, svc *service.Service) string {
funcMap := template.FuncMap{
"tcp": func(p int64) int64 { return svc.PortForServicePort(p, "tcp") },
"udp": func(p int64) int64 { return svc.PortForServicePort(p, "udp") },
"host": func() string { return m.DefaultCheckHost },
"container": func() string { return svc.Hostname },
}
t, err := template.New("check").Funcs(funcMap).Parse(check.Args)
if err != nil {
log.Errorf("Unable to parse check Args: '%s'", check.Args)
return check.Args
}
var output bytes.Buffer
t.Execute(&output, svc)
return output.String()
}
|
go
|
func (m *Monitor) templateCheckArgs(check *Check, svc *service.Service) string {
funcMap := template.FuncMap{
"tcp": func(p int64) int64 { return svc.PortForServicePort(p, "tcp") },
"udp": func(p int64) int64 { return svc.PortForServicePort(p, "udp") },
"host": func() string { return m.DefaultCheckHost },
"container": func() string { return svc.Hostname },
}
t, err := template.New("check").Funcs(funcMap).Parse(check.Args)
if err != nil {
log.Errorf("Unable to parse check Args: '%s'", check.Args)
return check.Args
}
var output bytes.Buffer
t.Execute(&output, svc)
return output.String()
}
|
[
"func",
"(",
"m",
"*",
"Monitor",
")",
"templateCheckArgs",
"(",
"check",
"*",
"Check",
",",
"svc",
"*",
"service",
".",
"Service",
")",
"string",
"{",
"funcMap",
":=",
"template",
".",
"FuncMap",
"{",
"\"",
"\"",
":",
"func",
"(",
"p",
"int64",
")",
"int64",
"{",
"return",
"svc",
".",
"PortForServicePort",
"(",
"p",
",",
"\"",
"\"",
")",
"}",
",",
"\"",
"\"",
":",
"func",
"(",
"p",
"int64",
")",
"int64",
"{",
"return",
"svc",
".",
"PortForServicePort",
"(",
"p",
",",
"\"",
"\"",
")",
"}",
",",
"\"",
"\"",
":",
"func",
"(",
")",
"string",
"{",
"return",
"m",
".",
"DefaultCheckHost",
"}",
",",
"\"",
"\"",
":",
"func",
"(",
")",
"string",
"{",
"return",
"svc",
".",
"Hostname",
"}",
",",
"}",
"\n\n",
"t",
",",
"err",
":=",
"template",
".",
"New",
"(",
"\"",
"\"",
")",
".",
"Funcs",
"(",
"funcMap",
")",
".",
"Parse",
"(",
"check",
".",
"Args",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"check",
".",
"Args",
")",
"\n",
"return",
"check",
".",
"Args",
"\n",
"}",
"\n\n",
"var",
"output",
"bytes",
".",
"Buffer",
"\n",
"t",
".",
"Execute",
"(",
"&",
"output",
",",
"svc",
")",
"\n\n",
"return",
"output",
".",
"String",
"(",
")",
"\n",
"}"
] |
// Use templating to substitute in some info about the service. Important because
// we won't know the actual Port that the container will bind to, for example.
|
[
"Use",
"templating",
"to",
"substitute",
"in",
"some",
"info",
"about",
"the",
"service",
".",
"Important",
"because",
"we",
"won",
"t",
"know",
"the",
"actual",
"Port",
"that",
"the",
"container",
"will",
"bind",
"to",
"for",
"example",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/healthy/service_bridge.go#L105-L123
|
11,807 |
newrelic/sidecar
|
healthy/service_bridge.go
|
CheckForService
|
func (m *Monitor) CheckForService(svc *service.Service, disco discovery.Discoverer) *Check {
check := m.fetchCheckForService(svc, disco)
if check == nil { // We got nothing
log.Warnf("Using default check for service %s (id: %s).", svc.Name, svc.ID)
check = m.defaultCheckForService(svc)
}
check.Args = m.templateCheckArgs(check, svc)
return check
}
|
go
|
func (m *Monitor) CheckForService(svc *service.Service, disco discovery.Discoverer) *Check {
check := m.fetchCheckForService(svc, disco)
if check == nil { // We got nothing
log.Warnf("Using default check for service %s (id: %s).", svc.Name, svc.ID)
check = m.defaultCheckForService(svc)
}
check.Args = m.templateCheckArgs(check, svc)
return check
}
|
[
"func",
"(",
"m",
"*",
"Monitor",
")",
"CheckForService",
"(",
"svc",
"*",
"service",
".",
"Service",
",",
"disco",
"discovery",
".",
"Discoverer",
")",
"*",
"Check",
"{",
"check",
":=",
"m",
".",
"fetchCheckForService",
"(",
"svc",
",",
"disco",
")",
"\n",
"if",
"check",
"==",
"nil",
"{",
"// We got nothing",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"svc",
".",
"Name",
",",
"svc",
".",
"ID",
")",
"\n",
"check",
"=",
"m",
".",
"defaultCheckForService",
"(",
"svc",
")",
"\n",
"}",
"\n\n",
"check",
".",
"Args",
"=",
"m",
".",
"templateCheckArgs",
"(",
"check",
",",
"svc",
")",
"\n\n",
"return",
"check",
"\n",
"}"
] |
// CheckForService returns a Check that has been properly configured for this
// particular service.
|
[
"CheckForService",
"returns",
"a",
"Check",
"that",
"has",
"been",
"properly",
"configured",
"for",
"this",
"particular",
"service",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/healthy/service_bridge.go#L127-L137
|
11,808 |
newrelic/sidecar
|
healthy/service_bridge.go
|
Watch
|
func (m *Monitor) Watch(disco discovery.Discoverer, looper director.Looper) {
m.DiscoveryFn = disco.Services // Store this so we can use it from Services()
looper.Loop(func() error {
services := disco.Services()
// Add checks when new services are found
for _, svc := range services {
if m.Checks[svc.ID] == nil {
check := m.CheckForService(&svc, disco)
if check.Command == nil {
log.Errorf(
"Attempted to add %s (id: %s) but no check configured!",
svc.Name, svc.ID,
)
} else {
m.AddCheck(check)
}
}
}
m.Lock()
defer m.Unlock()
OUTER:
// We remove checks when encountering a missing service. This
// prevents us from storing up checks forever. This is the only
// way we'll find out about a service going away.
for _, check := range m.Checks {
for _, svc := range services {
// Continue if we have a matching service/check pair
if svc.ID == check.ID {
continue OUTER
}
}
// Remove checks for services that are no longer running
delete(m.Checks, check.ID)
}
return nil
})
}
|
go
|
func (m *Monitor) Watch(disco discovery.Discoverer, looper director.Looper) {
m.DiscoveryFn = disco.Services // Store this so we can use it from Services()
looper.Loop(func() error {
services := disco.Services()
// Add checks when new services are found
for _, svc := range services {
if m.Checks[svc.ID] == nil {
check := m.CheckForService(&svc, disco)
if check.Command == nil {
log.Errorf(
"Attempted to add %s (id: %s) but no check configured!",
svc.Name, svc.ID,
)
} else {
m.AddCheck(check)
}
}
}
m.Lock()
defer m.Unlock()
OUTER:
// We remove checks when encountering a missing service. This
// prevents us from storing up checks forever. This is the only
// way we'll find out about a service going away.
for _, check := range m.Checks {
for _, svc := range services {
// Continue if we have a matching service/check pair
if svc.ID == check.ID {
continue OUTER
}
}
// Remove checks for services that are no longer running
delete(m.Checks, check.ID)
}
return nil
})
}
|
[
"func",
"(",
"m",
"*",
"Monitor",
")",
"Watch",
"(",
"disco",
"discovery",
".",
"Discoverer",
",",
"looper",
"director",
".",
"Looper",
")",
"{",
"m",
".",
"DiscoveryFn",
"=",
"disco",
".",
"Services",
"// Store this so we can use it from Services()",
"\n\n",
"looper",
".",
"Loop",
"(",
"func",
"(",
")",
"error",
"{",
"services",
":=",
"disco",
".",
"Services",
"(",
")",
"\n\n",
"// Add checks when new services are found",
"for",
"_",
",",
"svc",
":=",
"range",
"services",
"{",
"if",
"m",
".",
"Checks",
"[",
"svc",
".",
"ID",
"]",
"==",
"nil",
"{",
"check",
":=",
"m",
".",
"CheckForService",
"(",
"&",
"svc",
",",
"disco",
")",
"\n",
"if",
"check",
".",
"Command",
"==",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"svc",
".",
"Name",
",",
"svc",
".",
"ID",
",",
")",
"\n",
"}",
"else",
"{",
"m",
".",
"AddCheck",
"(",
"check",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"Unlock",
"(",
")",
"\n",
"OUTER",
":",
"// We remove checks when encountering a missing service. This",
"// prevents us from storing up checks forever. This is the only",
"// way we'll find out about a service going away.",
"for",
"_",
",",
"check",
":=",
"range",
"m",
".",
"Checks",
"{",
"for",
"_",
",",
"svc",
":=",
"range",
"services",
"{",
"// Continue if we have a matching service/check pair",
"if",
"svc",
".",
"ID",
"==",
"check",
".",
"ID",
"{",
"continue",
"OUTER",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Remove checks for services that are no longer running",
"delete",
"(",
"m",
".",
"Checks",
",",
"check",
".",
"ID",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] |
// Watch loops over a list of services and adds checks for services we don't already
// know about. It then removes any checks for services which have gone away. All
// services are expected to be local to this node.
|
[
"Watch",
"loops",
"over",
"a",
"list",
"of",
"services",
"and",
"adds",
"checks",
"for",
"services",
"we",
"don",
"t",
"already",
"know",
"about",
".",
"It",
"then",
"removes",
"any",
"checks",
"for",
"services",
"which",
"have",
"gone",
"away",
".",
"All",
"services",
"are",
"expected",
"to",
"be",
"local",
"to",
"this",
"node",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/healthy/service_bridge.go#L142-L183
|
11,809 |
newrelic/sidecar
|
discovery/static_discovery.go
|
Services
|
func (d *StaticDiscovery) Services() []service.Service {
var services []service.Service
for _, target := range d.Targets {
target.Service.Updated = time.Now().UTC()
services = append(services, target.Service)
}
return services
}
|
go
|
func (d *StaticDiscovery) Services() []service.Service {
var services []service.Service
for _, target := range d.Targets {
target.Service.Updated = time.Now().UTC()
services = append(services, target.Service)
}
return services
}
|
[
"func",
"(",
"d",
"*",
"StaticDiscovery",
")",
"Services",
"(",
")",
"[",
"]",
"service",
".",
"Service",
"{",
"var",
"services",
"[",
"]",
"service",
".",
"Service",
"\n",
"for",
"_",
",",
"target",
":=",
"range",
"d",
".",
"Targets",
"{",
"target",
".",
"Service",
".",
"Updated",
"=",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
"\n",
"services",
"=",
"append",
"(",
"services",
",",
"target",
".",
"Service",
")",
"\n",
"}",
"\n",
"return",
"services",
"\n",
"}"
] |
// Returns the list of services derived from the targets that were parsed
// out of the config file.
|
[
"Returns",
"the",
"list",
"of",
"services",
"derived",
"from",
"the",
"targets",
"that",
"were",
"parsed",
"out",
"of",
"the",
"config",
"file",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/static_discovery.go#L62-L69
|
11,810 |
newrelic/sidecar
|
discovery/static_discovery.go
|
Listeners
|
func (d *StaticDiscovery) Listeners() []ChangeListener {
var listeners []ChangeListener
for _, target := range d.Targets {
if target.ListenPort > 0 {
listener := ChangeListener{
Name: target.Service.ListenerName(),
Url: fmt.Sprintf("http://%s:%d/sidecar/update", d.Hostname, target.ListenPort),
}
listeners = append(listeners, listener)
}
}
return listeners
}
|
go
|
func (d *StaticDiscovery) Listeners() []ChangeListener {
var listeners []ChangeListener
for _, target := range d.Targets {
if target.ListenPort > 0 {
listener := ChangeListener{
Name: target.Service.ListenerName(),
Url: fmt.Sprintf("http://%s:%d/sidecar/update", d.Hostname, target.ListenPort),
}
listeners = append(listeners, listener)
}
}
return listeners
}
|
[
"func",
"(",
"d",
"*",
"StaticDiscovery",
")",
"Listeners",
"(",
")",
"[",
"]",
"ChangeListener",
"{",
"var",
"listeners",
"[",
"]",
"ChangeListener",
"\n",
"for",
"_",
",",
"target",
":=",
"range",
"d",
".",
"Targets",
"{",
"if",
"target",
".",
"ListenPort",
">",
"0",
"{",
"listener",
":=",
"ChangeListener",
"{",
"Name",
":",
"target",
".",
"Service",
".",
"ListenerName",
"(",
")",
",",
"Url",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"d",
".",
"Hostname",
",",
"target",
".",
"ListenPort",
")",
",",
"}",
"\n",
"listeners",
"=",
"append",
"(",
"listeners",
",",
"listener",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"listeners",
"\n",
"}"
] |
// Listeners returns the list of services configured to be ChangeEvent listeners
|
[
"Listeners",
"returns",
"the",
"list",
"of",
"services",
"configured",
"to",
"be",
"ChangeEvent",
"listeners"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/static_discovery.go#L72-L84
|
11,811 |
newrelic/sidecar
|
discovery/static_discovery.go
|
Run
|
func (d *StaticDiscovery) Run(looper director.Looper) {
var err error
d.Targets, err = d.ParseConfig(d.ConfigFile)
if err != nil {
log.Errorf("StaticDiscovery cannot parse: %s", err.Error())
looper.Done(nil)
}
}
|
go
|
func (d *StaticDiscovery) Run(looper director.Looper) {
var err error
d.Targets, err = d.ParseConfig(d.ConfigFile)
if err != nil {
log.Errorf("StaticDiscovery cannot parse: %s", err.Error())
looper.Done(nil)
}
}
|
[
"func",
"(",
"d",
"*",
"StaticDiscovery",
")",
"Run",
"(",
"looper",
"director",
".",
"Looper",
")",
"{",
"var",
"err",
"error",
"\n\n",
"d",
".",
"Targets",
",",
"err",
"=",
"d",
".",
"ParseConfig",
"(",
"d",
".",
"ConfigFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"looper",
".",
"Done",
"(",
"nil",
")",
"\n",
"}",
"\n",
"}"
] |
// Causes the configuration to be parsed and loaded. There is no background
// processing needed on an ongoing basis.
|
[
"Causes",
"the",
"configuration",
"to",
"be",
"parsed",
"and",
"loaded",
".",
"There",
"is",
"no",
"background",
"processing",
"needed",
"on",
"an",
"ongoing",
"basis",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/static_discovery.go#L88-L96
|
11,812 |
newrelic/sidecar
|
discovery/static_discovery.go
|
ParseConfig
|
func (d *StaticDiscovery) ParseConfig(filename string) ([]*Target, error) {
file, err := ioutil.ReadFile(filename)
if err != nil {
log.Errorf("Unable to read announcements file: '%s!'", err.Error())
return nil, err
}
var targets []*Target
err = json.Unmarshal(file, &targets)
if err != nil {
return nil, fmt.Errorf("Unable to unmarshal Target: %s", err)
}
// Have to loop with traditional 'for' loop so we can modify entries
for _, target := range targets {
idBytes, err := RandomHex(6)
if err != nil {
log.Errorf("ParseConfig(): Unable to get random bytes (%s)", err.Error())
return nil, err
}
target.Service.ID = string(idBytes)
target.Service.Created = time.Now().UTC()
// We _can_ export services for a 3rd party. If we don't specify
// the hostname, then it's for this host.
if target.Service.Hostname == "" {
target.Service.Hostname = d.Hostname
}
// Make sure we have an IP address on ports
for i, port := range target.Service.Ports {
if len(port.IP) == 0 {
target.Service.Ports[i].IP = d.DefaultIP
}
}
log.Printf("Discovered service: %s, ID: %s",
target.Service.Name,
target.Service.ID,
)
}
return targets, nil
}
|
go
|
func (d *StaticDiscovery) ParseConfig(filename string) ([]*Target, error) {
file, err := ioutil.ReadFile(filename)
if err != nil {
log.Errorf("Unable to read announcements file: '%s!'", err.Error())
return nil, err
}
var targets []*Target
err = json.Unmarshal(file, &targets)
if err != nil {
return nil, fmt.Errorf("Unable to unmarshal Target: %s", err)
}
// Have to loop with traditional 'for' loop so we can modify entries
for _, target := range targets {
idBytes, err := RandomHex(6)
if err != nil {
log.Errorf("ParseConfig(): Unable to get random bytes (%s)", err.Error())
return nil, err
}
target.Service.ID = string(idBytes)
target.Service.Created = time.Now().UTC()
// We _can_ export services for a 3rd party. If we don't specify
// the hostname, then it's for this host.
if target.Service.Hostname == "" {
target.Service.Hostname = d.Hostname
}
// Make sure we have an IP address on ports
for i, port := range target.Service.Ports {
if len(port.IP) == 0 {
target.Service.Ports[i].IP = d.DefaultIP
}
}
log.Printf("Discovered service: %s, ID: %s",
target.Service.Name,
target.Service.ID,
)
}
return targets, nil
}
|
[
"func",
"(",
"d",
"*",
"StaticDiscovery",
")",
"ParseConfig",
"(",
"filename",
"string",
")",
"(",
"[",
"]",
"*",
"Target",
",",
"error",
")",
"{",
"file",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"targets",
"[",
"]",
"*",
"Target",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"file",
",",
"&",
"targets",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Have to loop with traditional 'for' loop so we can modify entries",
"for",
"_",
",",
"target",
":=",
"range",
"targets",
"{",
"idBytes",
",",
"err",
":=",
"RandomHex",
"(",
"6",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"target",
".",
"Service",
".",
"ID",
"=",
"string",
"(",
"idBytes",
")",
"\n",
"target",
".",
"Service",
".",
"Created",
"=",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
"\n",
"// We _can_ export services for a 3rd party. If we don't specify",
"// the hostname, then it's for this host.",
"if",
"target",
".",
"Service",
".",
"Hostname",
"==",
"\"",
"\"",
"{",
"target",
".",
"Service",
".",
"Hostname",
"=",
"d",
".",
"Hostname",
"\n",
"}",
"\n\n",
"// Make sure we have an IP address on ports",
"for",
"i",
",",
"port",
":=",
"range",
"target",
".",
"Service",
".",
"Ports",
"{",
"if",
"len",
"(",
"port",
".",
"IP",
")",
"==",
"0",
"{",
"target",
".",
"Service",
".",
"Ports",
"[",
"i",
"]",
".",
"IP",
"=",
"d",
".",
"DefaultIP",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"target",
".",
"Service",
".",
"Name",
",",
"target",
".",
"Service",
".",
"ID",
",",
")",
"\n",
"}",
"\n",
"return",
"targets",
",",
"nil",
"\n",
"}"
] |
// Parses a JSON config file containing an array of Targets. These are
// then augmented with a random hex ID and stamped with the current
// UTC time as the creation time. The same hex ID is applied to the Check
// and the Service to make sure that they are matched by the healthy
// package later on.
|
[
"Parses",
"a",
"JSON",
"config",
"file",
"containing",
"an",
"array",
"of",
"Targets",
".",
"These",
"are",
"then",
"augmented",
"with",
"a",
"random",
"hex",
"ID",
"and",
"stamped",
"with",
"the",
"current",
"UTC",
"time",
"as",
"the",
"creation",
"time",
".",
"The",
"same",
"hex",
"ID",
"is",
"applied",
"to",
"the",
"Check",
"and",
"the",
"Service",
"to",
"make",
"sure",
"that",
"they",
"are",
"matched",
"by",
"the",
"healthy",
"package",
"later",
"on",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/static_discovery.go#L103-L145
|
11,813 |
newrelic/sidecar
|
discovery/static_discovery.go
|
RandomHex
|
func RandomHex(count int) ([]byte, error) {
raw := make([]byte, count)
_, err := rand.Read(raw)
if err != nil {
log.Errorf("RandomBytes(): Error %s", err.Error())
return nil, err
}
encoded := make([]byte, count*2)
hex.Encode(encoded, raw)
return encoded, nil
}
|
go
|
func RandomHex(count int) ([]byte, error) {
raw := make([]byte, count)
_, err := rand.Read(raw)
if err != nil {
log.Errorf("RandomBytes(): Error %s", err.Error())
return nil, err
}
encoded := make([]byte, count*2)
hex.Encode(encoded, raw)
return encoded, nil
}
|
[
"func",
"RandomHex",
"(",
"count",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"raw",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"count",
")",
"\n",
"_",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"raw",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"encoded",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"count",
"*",
"2",
")",
"\n",
"hex",
".",
"Encode",
"(",
"encoded",
",",
"raw",
")",
"\n",
"return",
"encoded",
",",
"nil",
"\n",
"}"
] |
// Return a defined number of random bytes as a slice
|
[
"Return",
"a",
"defined",
"number",
"of",
"random",
"bytes",
"as",
"a",
"slice"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/static_discovery.go#L148-L159
|
11,814 |
newrelic/sidecar
|
sidecarhttp/envoy_api.go
|
optionsHandler
|
func (s *EnvoyApi) optionsHandler(response http.ResponseWriter, req *http.Request) {
response.Header().Set("Access-Control-Allow-Origin", "*")
response.Header().Set("Access-Control-Allow-Methods", "GET")
return
}
|
go
|
func (s *EnvoyApi) optionsHandler(response http.ResponseWriter, req *http.Request) {
response.Header().Set("Access-Control-Allow-Origin", "*")
response.Header().Set("Access-Control-Allow-Methods", "GET")
return
}
|
[
"func",
"(",
"s",
"*",
"EnvoyApi",
")",
"optionsHandler",
"(",
"response",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}"
] |
// optionsHandler sends CORS headers
|
[
"optionsHandler",
"sends",
"CORS",
"headers"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/envoy_api.go#L108-L112
|
11,815 |
newrelic/sidecar
|
sidecarhttp/envoy_api.go
|
registrationHandler
|
func (s *EnvoyApi) registrationHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
defer req.Body.Close()
response.Header().Set("Content-Type", "application/json")
name, ok := params["service"]
if !ok {
log.Debug("No service name provided to Envoy registrationHandler")
sendJsonError(response, 404, "Not Found - No service name provided")
return
}
svcName, svcPort, err := SvcNameSplit(name)
if err != nil {
log.Debugf("Envoy Service '%s' not found in registrationHandler: %s", name, err)
sendJsonError(response, 404, "Not Found - "+err.Error())
return
}
instances := make([]*EnvoyService, 0)
// Enter critical section
func() {
s.state.RLock()
defer s.state.RUnlock()
s.state.EachService(func(hostname *string, id *string, svc *service.Service) {
if svc.Name == svcName && svc.IsAlive() {
newInstance := s.EnvoyServiceFromService(svc, svcPort)
if newInstance != nil {
instances = append(instances, newInstance)
}
}
})
}()
clusterName := ""
if s.list != nil {
clusterName = s.list.ClusterName()
}
result := SDSResult{
Env: clusterName,
Hosts: instances,
Service: name,
}
jsonBytes, err := result.MarshalJSON()
defer ffjson.Pool(jsonBytes)
if err != nil {
log.Errorf("Error marshaling state in registrationHandler: %s", err.Error())
sendJsonError(response, 500, "Internal server error")
return
}
response.Write(jsonBytes)
}
|
go
|
func (s *EnvoyApi) registrationHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
defer req.Body.Close()
response.Header().Set("Content-Type", "application/json")
name, ok := params["service"]
if !ok {
log.Debug("No service name provided to Envoy registrationHandler")
sendJsonError(response, 404, "Not Found - No service name provided")
return
}
svcName, svcPort, err := SvcNameSplit(name)
if err != nil {
log.Debugf("Envoy Service '%s' not found in registrationHandler: %s", name, err)
sendJsonError(response, 404, "Not Found - "+err.Error())
return
}
instances := make([]*EnvoyService, 0)
// Enter critical section
func() {
s.state.RLock()
defer s.state.RUnlock()
s.state.EachService(func(hostname *string, id *string, svc *service.Service) {
if svc.Name == svcName && svc.IsAlive() {
newInstance := s.EnvoyServiceFromService(svc, svcPort)
if newInstance != nil {
instances = append(instances, newInstance)
}
}
})
}()
clusterName := ""
if s.list != nil {
clusterName = s.list.ClusterName()
}
result := SDSResult{
Env: clusterName,
Hosts: instances,
Service: name,
}
jsonBytes, err := result.MarshalJSON()
defer ffjson.Pool(jsonBytes)
if err != nil {
log.Errorf("Error marshaling state in registrationHandler: %s", err.Error())
sendJsonError(response, 500, "Internal server error")
return
}
response.Write(jsonBytes)
}
|
[
"func",
"(",
"s",
"*",
"EnvoyApi",
")",
"registrationHandler",
"(",
"response",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"map",
"[",
"string",
"]",
"string",
")",
"{",
"defer",
"req",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"name",
",",
"ok",
":=",
"params",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"sendJsonError",
"(",
"response",
",",
"404",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"svcName",
",",
"svcPort",
",",
"err",
":=",
"SvcNameSplit",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
",",
"err",
")",
"\n",
"sendJsonError",
"(",
"response",
",",
"404",
",",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"instances",
":=",
"make",
"(",
"[",
"]",
"*",
"EnvoyService",
",",
"0",
")",
"\n",
"// Enter critical section",
"func",
"(",
")",
"{",
"s",
".",
"state",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"state",
".",
"RUnlock",
"(",
")",
"\n",
"s",
".",
"state",
".",
"EachService",
"(",
"func",
"(",
"hostname",
"*",
"string",
",",
"id",
"*",
"string",
",",
"svc",
"*",
"service",
".",
"Service",
")",
"{",
"if",
"svc",
".",
"Name",
"==",
"svcName",
"&&",
"svc",
".",
"IsAlive",
"(",
")",
"{",
"newInstance",
":=",
"s",
".",
"EnvoyServiceFromService",
"(",
"svc",
",",
"svcPort",
")",
"\n",
"if",
"newInstance",
"!=",
"nil",
"{",
"instances",
"=",
"append",
"(",
"instances",
",",
"newInstance",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"}",
"(",
")",
"\n\n",
"clusterName",
":=",
"\"",
"\"",
"\n",
"if",
"s",
".",
"list",
"!=",
"nil",
"{",
"clusterName",
"=",
"s",
".",
"list",
".",
"ClusterName",
"(",
")",
"\n",
"}",
"\n\n",
"result",
":=",
"SDSResult",
"{",
"Env",
":",
"clusterName",
",",
"Hosts",
":",
"instances",
",",
"Service",
":",
"name",
",",
"}",
"\n\n",
"jsonBytes",
",",
"err",
":=",
"result",
".",
"MarshalJSON",
"(",
")",
"\n",
"defer",
"ffjson",
".",
"Pool",
"(",
"jsonBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"sendJsonError",
"(",
"response",
",",
"500",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"response",
".",
"Write",
"(",
"jsonBytes",
")",
"\n",
"}"
] |
// registrationHandler takes the name of a single service and returns results for just
// that service. It implements the Envoy SDS API V1.
|
[
"registrationHandler",
"takes",
"the",
"name",
"of",
"a",
"single",
"service",
"and",
"returns",
"results",
"for",
"just",
"that",
"service",
".",
"It",
"implements",
"the",
"Envoy",
"SDS",
"API",
"V1",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/envoy_api.go#L122-L176
|
11,816 |
newrelic/sidecar
|
sidecarhttp/envoy_api.go
|
clustersHandler
|
func (s *EnvoyApi) clustersHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
defer req.Body.Close()
response.Header().Set("Content-Type", "application/json")
clusters := s.EnvoyClustersFromState()
log.Debugf("Reporting Envoy cluster information for cluster '%s' and node '%s'",
params["service_cluster"], params["service_node"])
result := CDSResult{clusters}
jsonBytes, err := result.MarshalJSON()
defer ffjson.Pool(jsonBytes)
if err != nil {
log.Errorf("Error marshaling state in servicesHandler: %s", err.Error())
sendJsonError(response, 500, "Internal server error")
return
}
response.Write(jsonBytes)
}
|
go
|
func (s *EnvoyApi) clustersHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
defer req.Body.Close()
response.Header().Set("Content-Type", "application/json")
clusters := s.EnvoyClustersFromState()
log.Debugf("Reporting Envoy cluster information for cluster '%s' and node '%s'",
params["service_cluster"], params["service_node"])
result := CDSResult{clusters}
jsonBytes, err := result.MarshalJSON()
defer ffjson.Pool(jsonBytes)
if err != nil {
log.Errorf("Error marshaling state in servicesHandler: %s", err.Error())
sendJsonError(response, 500, "Internal server error")
return
}
response.Write(jsonBytes)
}
|
[
"func",
"(",
"s",
"*",
"EnvoyApi",
")",
"clustersHandler",
"(",
"response",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"map",
"[",
"string",
"]",
"string",
")",
"{",
"defer",
"req",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"clusters",
":=",
"s",
".",
"EnvoyClustersFromState",
"(",
")",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"params",
"[",
"\"",
"\"",
"]",
",",
"params",
"[",
"\"",
"\"",
"]",
")",
"\n\n",
"result",
":=",
"CDSResult",
"{",
"clusters",
"}",
"\n\n",
"jsonBytes",
",",
"err",
":=",
"result",
".",
"MarshalJSON",
"(",
")",
"\n",
"defer",
"ffjson",
".",
"Pool",
"(",
"jsonBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"sendJsonError",
"(",
"response",
",",
"500",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"response",
".",
"Write",
"(",
"jsonBytes",
")",
"\n",
"}"
] |
// clustersHandler returns cluster information for all Sidecar services. It
// implements the Envoy CDS API V1.
|
[
"clustersHandler",
"returns",
"cluster",
"information",
"for",
"all",
"Sidecar",
"services",
".",
"It",
"implements",
"the",
"Envoy",
"CDS",
"API",
"V1",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/envoy_api.go#L184-L205
|
11,817 |
newrelic/sidecar
|
sidecarhttp/envoy_api.go
|
listenersHandler
|
func (s *EnvoyApi) listenersHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
defer req.Body.Close()
response.Header().Set("Content-Type", "application/json")
log.Debugf("Reporting Envoy cluster information for cluster '%s' and node '%s'",
params["service_cluster"], params["service_node"])
listeners := s.EnvoyListenersFromState()
result := LDSResult{listeners}
jsonBytes, err := result.MarshalJSON()
defer ffjson.Pool(jsonBytes)
if err != nil {
log.Errorf("Error marshaling state in servicesHandler: %s", err.Error())
sendJsonError(response, 500, "Internal server error")
return
}
response.Write(jsonBytes)
}
|
go
|
func (s *EnvoyApi) listenersHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
defer req.Body.Close()
response.Header().Set("Content-Type", "application/json")
log.Debugf("Reporting Envoy cluster information for cluster '%s' and node '%s'",
params["service_cluster"], params["service_node"])
listeners := s.EnvoyListenersFromState()
result := LDSResult{listeners}
jsonBytes, err := result.MarshalJSON()
defer ffjson.Pool(jsonBytes)
if err != nil {
log.Errorf("Error marshaling state in servicesHandler: %s", err.Error())
sendJsonError(response, 500, "Internal server error")
return
}
response.Write(jsonBytes)
}
|
[
"func",
"(",
"s",
"*",
"EnvoyApi",
")",
"listenersHandler",
"(",
"response",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
",",
"params",
"map",
"[",
"string",
"]",
"string",
")",
"{",
"defer",
"req",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"response",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"params",
"[",
"\"",
"\"",
"]",
",",
"params",
"[",
"\"",
"\"",
"]",
")",
"\n\n",
"listeners",
":=",
"s",
".",
"EnvoyListenersFromState",
"(",
")",
"\n\n",
"result",
":=",
"LDSResult",
"{",
"listeners",
"}",
"\n",
"jsonBytes",
",",
"err",
":=",
"result",
".",
"MarshalJSON",
"(",
")",
"\n",
"defer",
"ffjson",
".",
"Pool",
"(",
"jsonBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"sendJsonError",
"(",
"response",
",",
"500",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"response",
".",
"Write",
"(",
"jsonBytes",
")",
"\n",
"}"
] |
// listenersHandler returns a list of listeners for all ServicePorts. It
// implements the Envoy LDS API V1.
|
[
"listenersHandler",
"returns",
"a",
"list",
"of",
"listeners",
"for",
"all",
"ServicePorts",
".",
"It",
"implements",
"the",
"Envoy",
"LDS",
"API",
"V1",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/envoy_api.go#L213-L233
|
11,818 |
newrelic/sidecar
|
sidecarhttp/envoy_api.go
|
lookupHost
|
func lookupHost(hostname string) (string, error) {
addrs, err := net.LookupHost(hostname)
if err != nil {
return "", err
}
return addrs[0], nil
}
|
go
|
func lookupHost(hostname string) (string, error) {
addrs, err := net.LookupHost(hostname)
if err != nil {
return "", err
}
return addrs[0], nil
}
|
[
"func",
"lookupHost",
"(",
"hostname",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"addrs",
",",
"err",
":=",
"net",
".",
"LookupHost",
"(",
"hostname",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"addrs",
"[",
"0",
"]",
",",
"nil",
"\n",
"}"
] |
// lookupHost does a vv slow lookup of the DNS host for a service. Totally
// not optimized for high throughput. You should only do this in development
// scenarios.
|
[
"lookupHost",
"does",
"a",
"vv",
"slow",
"lookup",
"of",
"the",
"DNS",
"host",
"for",
"a",
"service",
".",
"Totally",
"not",
"optimized",
"for",
"high",
"throughput",
".",
"You",
"should",
"only",
"do",
"this",
"in",
"development",
"scenarios",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/envoy_api.go#L238-L245
|
11,819 |
newrelic/sidecar
|
sidecarhttp/envoy_api.go
|
EnvoyServiceFromService
|
func (s *EnvoyApi) EnvoyServiceFromService(svc *service.Service, svcPort int64) *EnvoyService {
if len(svc.Ports) < 1 {
return nil
}
for _, port := range svc.Ports {
// No sense worrying about unexposed ports
if port.ServicePort == svcPort {
address := port.IP
// NOT recommended... this is very slow. Useful in dev modes where you
// need to resolve to a different IP address only.
if s.config.UseHostnames {
var err error
address, err = lookupHost(svc.Hostname)
if err != nil {
log.Warnf("Unable to resolve %s, using IP address", svc.Hostname)
}
address = port.IP
}
return &EnvoyService{
IPAddress: address,
LastCheckIn: svc.Updated.String(),
Port: port.Port,
Revision: svc.Version(),
Service: SvcName(svc.Name, port.ServicePort),
ServiceRepoName: svc.Image,
Tags: map[string]string{},
}
}
}
return nil
}
|
go
|
func (s *EnvoyApi) EnvoyServiceFromService(svc *service.Service, svcPort int64) *EnvoyService {
if len(svc.Ports) < 1 {
return nil
}
for _, port := range svc.Ports {
// No sense worrying about unexposed ports
if port.ServicePort == svcPort {
address := port.IP
// NOT recommended... this is very slow. Useful in dev modes where you
// need to resolve to a different IP address only.
if s.config.UseHostnames {
var err error
address, err = lookupHost(svc.Hostname)
if err != nil {
log.Warnf("Unable to resolve %s, using IP address", svc.Hostname)
}
address = port.IP
}
return &EnvoyService{
IPAddress: address,
LastCheckIn: svc.Updated.String(),
Port: port.Port,
Revision: svc.Version(),
Service: SvcName(svc.Name, port.ServicePort),
ServiceRepoName: svc.Image,
Tags: map[string]string{},
}
}
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"EnvoyApi",
")",
"EnvoyServiceFromService",
"(",
"svc",
"*",
"service",
".",
"Service",
",",
"svcPort",
"int64",
")",
"*",
"EnvoyService",
"{",
"if",
"len",
"(",
"svc",
".",
"Ports",
")",
"<",
"1",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"port",
":=",
"range",
"svc",
".",
"Ports",
"{",
"// No sense worrying about unexposed ports",
"if",
"port",
".",
"ServicePort",
"==",
"svcPort",
"{",
"address",
":=",
"port",
".",
"IP",
"\n\n",
"// NOT recommended... this is very slow. Useful in dev modes where you",
"// need to resolve to a different IP address only.",
"if",
"s",
".",
"config",
".",
"UseHostnames",
"{",
"var",
"err",
"error",
"\n",
"address",
",",
"err",
"=",
"lookupHost",
"(",
"svc",
".",
"Hostname",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"svc",
".",
"Hostname",
")",
"\n",
"}",
"\n",
"address",
"=",
"port",
".",
"IP",
"\n",
"}",
"\n\n",
"return",
"&",
"EnvoyService",
"{",
"IPAddress",
":",
"address",
",",
"LastCheckIn",
":",
"svc",
".",
"Updated",
".",
"String",
"(",
")",
",",
"Port",
":",
"port",
".",
"Port",
",",
"Revision",
":",
"svc",
".",
"Version",
"(",
")",
",",
"Service",
":",
"SvcName",
"(",
"svc",
".",
"Name",
",",
"port",
".",
"ServicePort",
")",
",",
"ServiceRepoName",
":",
"svc",
".",
"Image",
",",
"Tags",
":",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
",",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// EnvoyServiceFromService converts a Sidecar service to an Envoy
// API service for reporting to the proxy
|
[
"EnvoyServiceFromService",
"converts",
"a",
"Sidecar",
"service",
"to",
"an",
"Envoy",
"API",
"service",
"for",
"reporting",
"to",
"the",
"proxy"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/envoy_api.go#L249-L283
|
11,820 |
newrelic/sidecar
|
sidecarhttp/envoy_api.go
|
EnvoyClustersFromState
|
func (s *EnvoyApi) EnvoyClustersFromState() []*EnvoyCluster {
clusters := make([]*EnvoyCluster, 0)
s.state.RLock()
defer s.state.RUnlock()
svcs := s.state.ByService()
for svcName, endpoints := range svcs {
if len(endpoints) < 1 {
continue
}
var svc *service.Service
for _, endpoint := range endpoints {
if endpoint.IsAlive() {
svc = endpoint
break
}
}
if svc == nil {
continue
}
for _, port := range svc.Ports {
if port.ServicePort < 1 {
continue
}
clusters = append(clusters, &EnvoyCluster{
Name: SvcName(svcName, port.ServicePort),
Type: "sds", // use Sidecar's SDS endpoint for the hosts
ConnectTimeoutMs: 500,
LBType: "round_robin", // TODO figure this out!
ServiceName: SvcName(svcName, port.ServicePort),
})
}
}
return clusters
}
|
go
|
func (s *EnvoyApi) EnvoyClustersFromState() []*EnvoyCluster {
clusters := make([]*EnvoyCluster, 0)
s.state.RLock()
defer s.state.RUnlock()
svcs := s.state.ByService()
for svcName, endpoints := range svcs {
if len(endpoints) < 1 {
continue
}
var svc *service.Service
for _, endpoint := range endpoints {
if endpoint.IsAlive() {
svc = endpoint
break
}
}
if svc == nil {
continue
}
for _, port := range svc.Ports {
if port.ServicePort < 1 {
continue
}
clusters = append(clusters, &EnvoyCluster{
Name: SvcName(svcName, port.ServicePort),
Type: "sds", // use Sidecar's SDS endpoint for the hosts
ConnectTimeoutMs: 500,
LBType: "round_robin", // TODO figure this out!
ServiceName: SvcName(svcName, port.ServicePort),
})
}
}
return clusters
}
|
[
"func",
"(",
"s",
"*",
"EnvoyApi",
")",
"EnvoyClustersFromState",
"(",
")",
"[",
"]",
"*",
"EnvoyCluster",
"{",
"clusters",
":=",
"make",
"(",
"[",
"]",
"*",
"EnvoyCluster",
",",
"0",
")",
"\n\n",
"s",
".",
"state",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"state",
".",
"RUnlock",
"(",
")",
"\n\n",
"svcs",
":=",
"s",
".",
"state",
".",
"ByService",
"(",
")",
"\n",
"for",
"svcName",
",",
"endpoints",
":=",
"range",
"svcs",
"{",
"if",
"len",
"(",
"endpoints",
")",
"<",
"1",
"{",
"continue",
"\n",
"}",
"\n\n",
"var",
"svc",
"*",
"service",
".",
"Service",
"\n",
"for",
"_",
",",
"endpoint",
":=",
"range",
"endpoints",
"{",
"if",
"endpoint",
".",
"IsAlive",
"(",
")",
"{",
"svc",
"=",
"endpoint",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"svc",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"port",
":=",
"range",
"svc",
".",
"Ports",
"{",
"if",
"port",
".",
"ServicePort",
"<",
"1",
"{",
"continue",
"\n",
"}",
"\n\n",
"clusters",
"=",
"append",
"(",
"clusters",
",",
"&",
"EnvoyCluster",
"{",
"Name",
":",
"SvcName",
"(",
"svcName",
",",
"port",
".",
"ServicePort",
")",
",",
"Type",
":",
"\"",
"\"",
",",
"// use Sidecar's SDS endpoint for the hosts",
"ConnectTimeoutMs",
":",
"500",
",",
"LBType",
":",
"\"",
"\"",
",",
"// TODO figure this out!",
"ServiceName",
":",
"SvcName",
"(",
"svcName",
",",
"port",
".",
"ServicePort",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"clusters",
"\n",
"}"
] |
// EnvoyClustersFromState genenerates a set of Envoy API cluster
// definitions from Sidecar state
|
[
"EnvoyClustersFromState",
"genenerates",
"a",
"set",
"of",
"Envoy",
"API",
"cluster",
"definitions",
"from",
"Sidecar",
"state"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/envoy_api.go#L287-L327
|
11,821 |
newrelic/sidecar
|
sidecarhttp/envoy_api.go
|
EnvoyListenersFromState
|
func (s *EnvoyApi) EnvoyListenersFromState() []*EnvoyListener {
listeners := make([]*EnvoyListener, 0)
s.state.RLock()
defer s.state.RUnlock()
svcs := s.state.ByService()
// Loop over all the services by service name
for _, endpoints := range svcs {
if len(endpoints) < 1 {
continue
}
var svc *service.Service
// Find the first alive service and use that as the definition.
// If none are alive, we won't open the port.
for _, endpoint := range endpoints {
if endpoint.IsAlive() {
svc = endpoint
break
}
}
if svc == nil {
continue
}
// Loop over the ports and generate a named listener for
// each port.
for _, port := range svc.Ports {
// Only listen on ServicePorts
if port.ServicePort < 1 {
continue
}
listeners = append(listeners, s.EnvoyListenerFromService(svc, port.ServicePort))
}
}
return listeners
}
|
go
|
func (s *EnvoyApi) EnvoyListenersFromState() []*EnvoyListener {
listeners := make([]*EnvoyListener, 0)
s.state.RLock()
defer s.state.RUnlock()
svcs := s.state.ByService()
// Loop over all the services by service name
for _, endpoints := range svcs {
if len(endpoints) < 1 {
continue
}
var svc *service.Service
// Find the first alive service and use that as the definition.
// If none are alive, we won't open the port.
for _, endpoint := range endpoints {
if endpoint.IsAlive() {
svc = endpoint
break
}
}
if svc == nil {
continue
}
// Loop over the ports and generate a named listener for
// each port.
for _, port := range svc.Ports {
// Only listen on ServicePorts
if port.ServicePort < 1 {
continue
}
listeners = append(listeners, s.EnvoyListenerFromService(svc, port.ServicePort))
}
}
return listeners
}
|
[
"func",
"(",
"s",
"*",
"EnvoyApi",
")",
"EnvoyListenersFromState",
"(",
")",
"[",
"]",
"*",
"EnvoyListener",
"{",
"listeners",
":=",
"make",
"(",
"[",
"]",
"*",
"EnvoyListener",
",",
"0",
")",
"\n\n",
"s",
".",
"state",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"state",
".",
"RUnlock",
"(",
")",
"\n\n",
"svcs",
":=",
"s",
".",
"state",
".",
"ByService",
"(",
")",
"\n",
"// Loop over all the services by service name",
"for",
"_",
",",
"endpoints",
":=",
"range",
"svcs",
"{",
"if",
"len",
"(",
"endpoints",
")",
"<",
"1",
"{",
"continue",
"\n",
"}",
"\n\n",
"var",
"svc",
"*",
"service",
".",
"Service",
"\n",
"// Find the first alive service and use that as the definition.",
"// If none are alive, we won't open the port.",
"for",
"_",
",",
"endpoint",
":=",
"range",
"endpoints",
"{",
"if",
"endpoint",
".",
"IsAlive",
"(",
")",
"{",
"svc",
"=",
"endpoint",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"svc",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"// Loop over the ports and generate a named listener for",
"// each port.",
"for",
"_",
",",
"port",
":=",
"range",
"svc",
".",
"Ports",
"{",
"// Only listen on ServicePorts",
"if",
"port",
".",
"ServicePort",
"<",
"1",
"{",
"continue",
"\n",
"}",
"\n\n",
"listeners",
"=",
"append",
"(",
"listeners",
",",
"s",
".",
"EnvoyListenerFromService",
"(",
"svc",
",",
"port",
".",
"ServicePort",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"listeners",
"\n",
"}"
] |
// EnvoyListenersFromState creates a set of Enovy API listener
// definitions from all the ServicePorts in the Sidecar state.
|
[
"EnvoyListenersFromState",
"creates",
"a",
"set",
"of",
"Enovy",
"API",
"listener",
"definitions",
"from",
"all",
"the",
"ServicePorts",
"in",
"the",
"Sidecar",
"state",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/envoy_api.go#L393-L433
|
11,822 |
newrelic/sidecar
|
sidecarhttp/envoy_api.go
|
SvcName
|
func SvcName(name string, port int64) string {
return fmt.Sprintf("%s%s%d", name, ServiceNameSeparator, port)
}
|
go
|
func SvcName(name string, port int64) string {
return fmt.Sprintf("%s%s%d", name, ServiceNameSeparator, port)
}
|
[
"func",
"SvcName",
"(",
"name",
"string",
",",
"port",
"int64",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
",",
"ServiceNameSeparator",
",",
"port",
")",
"\n",
"}"
] |
// Format an Envoy service name from our service name and port
|
[
"Format",
"an",
"Envoy",
"service",
"name",
"from",
"our",
"service",
"name",
"and",
"port"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/envoy_api.go#L436-L438
|
11,823 |
newrelic/sidecar
|
sidecarhttp/envoy_api.go
|
SvcNameSplit
|
func SvcNameSplit(name string) (string, int64, error) {
parts := strings.Split(name, ServiceNameSeparator)
if len(parts) < 2 {
return "", -1, fmt.Errorf("%s", "Unable to split service name and port!")
}
svcName := parts[0]
svcPort, err := strconv.ParseInt(parts[1], 10, 64)
if err != nil {
return "", -1, fmt.Errorf("%s", "Unable to parse port!")
}
return svcName, svcPort, nil
}
|
go
|
func SvcNameSplit(name string) (string, int64, error) {
parts := strings.Split(name, ServiceNameSeparator)
if len(parts) < 2 {
return "", -1, fmt.Errorf("%s", "Unable to split service name and port!")
}
svcName := parts[0]
svcPort, err := strconv.ParseInt(parts[1], 10, 64)
if err != nil {
return "", -1, fmt.Errorf("%s", "Unable to parse port!")
}
return svcName, svcPort, nil
}
|
[
"func",
"SvcNameSplit",
"(",
"name",
"string",
")",
"(",
"string",
",",
"int64",
",",
"error",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"name",
",",
"ServiceNameSeparator",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"<",
"2",
"{",
"return",
"\"",
"\"",
",",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"svcName",
":=",
"parts",
"[",
"0",
"]",
"\n",
"svcPort",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"parts",
"[",
"1",
"]",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"-",
"1",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"svcName",
",",
"svcPort",
",",
"nil",
"\n",
"}"
] |
// Split an Enovy service name into our service name and port
|
[
"Split",
"an",
"Enovy",
"service",
"name",
"into",
"our",
"service",
"name",
"and",
"port"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/envoy_api.go#L441-L454
|
11,824 |
newrelic/sidecar
|
sidecarhttp/envoy_api.go
|
HttpMux
|
func (s *EnvoyApi) HttpMux() http.Handler {
router := mux.NewRouter()
router.HandleFunc("/registration/{service}", wrap(s.registrationHandler)).Methods("GET")
router.HandleFunc("/clusters/{service_cluster}/{service_node}", wrap(s.clustersHandler)).Methods("GET")
router.HandleFunc("/clusters", wrap(s.clustersHandler)).Methods("GET")
router.HandleFunc("/listeners/{service_cluster}/{service_node}", wrap(s.listenersHandler)).Methods("GET")
router.HandleFunc("/listeners", wrap(s.listenersHandler)).Methods("GET")
router.HandleFunc("/{path}", s.optionsHandler).Methods("OPTIONS")
return router
}
|
go
|
func (s *EnvoyApi) HttpMux() http.Handler {
router := mux.NewRouter()
router.HandleFunc("/registration/{service}", wrap(s.registrationHandler)).Methods("GET")
router.HandleFunc("/clusters/{service_cluster}/{service_node}", wrap(s.clustersHandler)).Methods("GET")
router.HandleFunc("/clusters", wrap(s.clustersHandler)).Methods("GET")
router.HandleFunc("/listeners/{service_cluster}/{service_node}", wrap(s.listenersHandler)).Methods("GET")
router.HandleFunc("/listeners", wrap(s.listenersHandler)).Methods("GET")
router.HandleFunc("/{path}", s.optionsHandler).Methods("OPTIONS")
return router
}
|
[
"func",
"(",
"s",
"*",
"EnvoyApi",
")",
"HttpMux",
"(",
")",
"http",
".",
"Handler",
"{",
"router",
":=",
"mux",
".",
"NewRouter",
"(",
")",
"\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"wrap",
"(",
"s",
".",
"registrationHandler",
")",
")",
".",
"Methods",
"(",
"\"",
"\"",
")",
"\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"wrap",
"(",
"s",
".",
"clustersHandler",
")",
")",
".",
"Methods",
"(",
"\"",
"\"",
")",
"\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"wrap",
"(",
"s",
".",
"clustersHandler",
")",
")",
".",
"Methods",
"(",
"\"",
"\"",
")",
"\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"wrap",
"(",
"s",
".",
"listenersHandler",
")",
")",
".",
"Methods",
"(",
"\"",
"\"",
")",
"\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"wrap",
"(",
"s",
".",
"listenersHandler",
")",
")",
".",
"Methods",
"(",
"\"",
"\"",
")",
"\n",
"router",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"s",
".",
"optionsHandler",
")",
".",
"Methods",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"router",
"\n",
"}"
] |
// HttpMux returns a configured Gorilla mux to handle all the endpoints
// for the Envoy API.
|
[
"HttpMux",
"returns",
"a",
"configured",
"Gorilla",
"mux",
"to",
"handle",
"all",
"the",
"endpoints",
"for",
"the",
"Envoy",
"API",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/envoy_api.go#L458-L468
|
11,825 |
newrelic/sidecar
|
healthy/healthy.go
|
NewCheck
|
func NewCheck(id string) *Check {
check := Check{
ID: id,
Count: 0,
Type: "http",
Command: &HttpGetCmd{},
MaxCount: 1,
Status: UNKNOWN,
}
return &check
}
|
go
|
func NewCheck(id string) *Check {
check := Check{
ID: id,
Count: 0,
Type: "http",
Command: &HttpGetCmd{},
MaxCount: 1,
Status: UNKNOWN,
}
return &check
}
|
[
"func",
"NewCheck",
"(",
"id",
"string",
")",
"*",
"Check",
"{",
"check",
":=",
"Check",
"{",
"ID",
":",
"id",
",",
"Count",
":",
"0",
",",
"Type",
":",
"\"",
"\"",
",",
"Command",
":",
"&",
"HttpGetCmd",
"{",
"}",
",",
"MaxCount",
":",
"1",
",",
"Status",
":",
"UNKNOWN",
",",
"}",
"\n",
"return",
"&",
"check",
"\n",
"}"
] |
// NewCheck returns a properly configured default Check
|
[
"NewCheck",
"returns",
"a",
"properly",
"configured",
"default",
"Check"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/healthy/healthy.go#L81-L91
|
11,826 |
newrelic/sidecar
|
healthy/healthy.go
|
UpdateStatus
|
func (check *Check) UpdateStatus(status int, err error) {
if err != nil {
log.Debugf("Error executing check, status UNKNOWN: (id %s)", check.ID)
check.Status = UNKNOWN
check.LastError = err
} else {
check.Status = status
}
if status == HEALTHY {
check.Count = 0
return
}
check.Count = check.Count + 1
if check.Count >= check.MaxCount {
check.Status = FAILED
}
}
|
go
|
func (check *Check) UpdateStatus(status int, err error) {
if err != nil {
log.Debugf("Error executing check, status UNKNOWN: (id %s)", check.ID)
check.Status = UNKNOWN
check.LastError = err
} else {
check.Status = status
}
if status == HEALTHY {
check.Count = 0
return
}
check.Count = check.Count + 1
if check.Count >= check.MaxCount {
check.Status = FAILED
}
}
|
[
"func",
"(",
"check",
"*",
"Check",
")",
"UpdateStatus",
"(",
"status",
"int",
",",
"err",
"error",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"check",
".",
"ID",
")",
"\n",
"check",
".",
"Status",
"=",
"UNKNOWN",
"\n",
"check",
".",
"LastError",
"=",
"err",
"\n",
"}",
"else",
"{",
"check",
".",
"Status",
"=",
"status",
"\n",
"}",
"\n\n",
"if",
"status",
"==",
"HEALTHY",
"{",
"check",
".",
"Count",
"=",
"0",
"\n",
"return",
"\n",
"}",
"\n\n",
"check",
".",
"Count",
"=",
"check",
".",
"Count",
"+",
"1",
"\n\n",
"if",
"check",
".",
"Count",
">=",
"check",
".",
"MaxCount",
"{",
"check",
".",
"Status",
"=",
"FAILED",
"\n",
"}",
"\n",
"}"
] |
// UpdateStatus take the status integer and error and applies them to the status
// of the current Check.
|
[
"UpdateStatus",
"take",
"the",
"status",
"integer",
"and",
"error",
"and",
"applies",
"them",
"to",
"the",
"status",
"of",
"the",
"current",
"Check",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/healthy/healthy.go#L95-L114
|
11,827 |
newrelic/sidecar
|
healthy/healthy.go
|
NewMonitor
|
func NewMonitor(defaultCheckHost string, defaultCheckEndpoint string) *Monitor {
monitor := Monitor{
Checks: make(map[string]*Check, 5),
CheckInterval: HEALTH_INTERVAL,
DefaultCheckHost: defaultCheckHost,
DefaultCheckEndpoint: defaultCheckEndpoint,
}
return &monitor
}
|
go
|
func NewMonitor(defaultCheckHost string, defaultCheckEndpoint string) *Monitor {
monitor := Monitor{
Checks: make(map[string]*Check, 5),
CheckInterval: HEALTH_INTERVAL,
DefaultCheckHost: defaultCheckHost,
DefaultCheckEndpoint: defaultCheckEndpoint,
}
return &monitor
}
|
[
"func",
"NewMonitor",
"(",
"defaultCheckHost",
"string",
",",
"defaultCheckEndpoint",
"string",
")",
"*",
"Monitor",
"{",
"monitor",
":=",
"Monitor",
"{",
"Checks",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Check",
",",
"5",
")",
",",
"CheckInterval",
":",
"HEALTH_INTERVAL",
",",
"DefaultCheckHost",
":",
"defaultCheckHost",
",",
"DefaultCheckEndpoint",
":",
"defaultCheckEndpoint",
",",
"}",
"\n",
"return",
"&",
"monitor",
"\n",
"}"
] |
// NewMonitor returns a properly configured default configuration of a Monitor.
|
[
"NewMonitor",
"returns",
"a",
"properly",
"configured",
"default",
"configuration",
"of",
"a",
"Monitor",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/healthy/healthy.go#L130-L138
|
11,828 |
newrelic/sidecar
|
healthy/healthy.go
|
AddCheck
|
func (m *Monitor) AddCheck(check *Check) {
m.Lock()
defer m.Unlock()
log.Printf("Adding health check: %s (ID: %s), Args: %s", check.Type, check.ID, check.Args)
m.Checks[check.ID] = check
}
|
go
|
func (m *Monitor) AddCheck(check *Check) {
m.Lock()
defer m.Unlock()
log.Printf("Adding health check: %s (ID: %s), Args: %s", check.Type, check.ID, check.Args)
m.Checks[check.ID] = check
}
|
[
"func",
"(",
"m",
"*",
"Monitor",
")",
"AddCheck",
"(",
"check",
"*",
"Check",
")",
"{",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"Unlock",
"(",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"check",
".",
"Type",
",",
"check",
".",
"ID",
",",
"check",
".",
"Args",
")",
"\n",
"m",
".",
"Checks",
"[",
"check",
".",
"ID",
"]",
"=",
"check",
"\n",
"}"
] |
// Add a Check to the list. Handles synchronization.
|
[
"Add",
"a",
"Check",
"to",
"the",
"list",
".",
"Handles",
"synchronization",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/healthy/healthy.go#L141-L146
|
11,829 |
newrelic/sidecar
|
healthy/healthy.go
|
MarkService
|
func (m *Monitor) MarkService(svc *service.Service) {
// We remove checks when encountering a Tombstone record. This
// prevents us from storing up checks forever. The discovery
// mechanism must create tombstones when services go away, so
// this is the best signal we'll get that a check is no longer
// needed. Assumes we're only health checking _our own_ services.
m.RLock()
if _, ok := m.Checks[svc.ID]; ok {
svc.Status = m.Checks[svc.ID].ServiceStatus()
} else {
svc.Status = service.UNKNOWN
}
m.RUnlock()
}
|
go
|
func (m *Monitor) MarkService(svc *service.Service) {
// We remove checks when encountering a Tombstone record. This
// prevents us from storing up checks forever. The discovery
// mechanism must create tombstones when services go away, so
// this is the best signal we'll get that a check is no longer
// needed. Assumes we're only health checking _our own_ services.
m.RLock()
if _, ok := m.Checks[svc.ID]; ok {
svc.Status = m.Checks[svc.ID].ServiceStatus()
} else {
svc.Status = service.UNKNOWN
}
m.RUnlock()
}
|
[
"func",
"(",
"m",
"*",
"Monitor",
")",
"MarkService",
"(",
"svc",
"*",
"service",
".",
"Service",
")",
"{",
"// We remove checks when encountering a Tombstone record. This",
"// prevents us from storing up checks forever. The discovery",
"// mechanism must create tombstones when services go away, so",
"// this is the best signal we'll get that a check is no longer",
"// needed. Assumes we're only health checking _our own_ services.",
"m",
".",
"RLock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"m",
".",
"Checks",
"[",
"svc",
".",
"ID",
"]",
";",
"ok",
"{",
"svc",
".",
"Status",
"=",
"m",
".",
"Checks",
"[",
"svc",
".",
"ID",
"]",
".",
"ServiceStatus",
"(",
")",
"\n",
"}",
"else",
"{",
"svc",
".",
"Status",
"=",
"service",
".",
"UNKNOWN",
"\n",
"}",
"\n",
"m",
".",
"RUnlock",
"(",
")",
"\n",
"}"
] |
// MarkService takes a service and mark its Status appropriately based on the
// current check we have configured.
|
[
"MarkService",
"takes",
"a",
"service",
"and",
"mark",
"its",
"Status",
"appropriately",
"based",
"on",
"the",
"current",
"check",
"we",
"have",
"configured",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/healthy/healthy.go#L150-L163
|
11,830 |
newrelic/sidecar
|
healthy/healthy.go
|
Run
|
func (m *Monitor) Run(looper director.Looper) {
looper.Loop(func() error {
log.Debugf("Running checks")
var wg sync.WaitGroup
// Make immutable copy of m.Checks (checks are still mutable)
m.RLock()
checks := make(map[string]*Check, len(m.Checks))
for k, v := range m.Checks {
checks[k] = v
}
m.RUnlock()
wg.Add(len(checks))
for _, check := range checks {
// Run all checks in parallel in goroutines
resultChan := make(chan checkResult, 1)
go func(check *Check, resultChan chan checkResult) {
result, err := check.Command.Run(check.Args)
resultChan <- checkResult{result, err}
}(check, resultChan) // copy check pointer for the goroutine
go func(check *Check, resultChan chan checkResult) {
defer wg.Done()
// We make the call but we time out if it gets too close to the
// m.CheckInterval.
select {
case result := <-resultChan:
check.UpdateStatus(result.status, result.err)
case <-time.After(m.CheckInterval - 1*time.Millisecond):
log.Errorf("Error, check %s timed out! (%v)", check.ID, check.Args)
check.UpdateStatus(UNKNOWN, errors.New("Timed out!"))
}
}(check, resultChan) // copy check pointer for the goroutine
}
// Let's make sure we don't continue to spool up
// huge quantities of goroutines. Wait on all of them
// to complete before moving on. This could slow down
// our check loop if something doesn't time out properly.
wg.Wait()
return nil
})
}
|
go
|
func (m *Monitor) Run(looper director.Looper) {
looper.Loop(func() error {
log.Debugf("Running checks")
var wg sync.WaitGroup
// Make immutable copy of m.Checks (checks are still mutable)
m.RLock()
checks := make(map[string]*Check, len(m.Checks))
for k, v := range m.Checks {
checks[k] = v
}
m.RUnlock()
wg.Add(len(checks))
for _, check := range checks {
// Run all checks in parallel in goroutines
resultChan := make(chan checkResult, 1)
go func(check *Check, resultChan chan checkResult) {
result, err := check.Command.Run(check.Args)
resultChan <- checkResult{result, err}
}(check, resultChan) // copy check pointer for the goroutine
go func(check *Check, resultChan chan checkResult) {
defer wg.Done()
// We make the call but we time out if it gets too close to the
// m.CheckInterval.
select {
case result := <-resultChan:
check.UpdateStatus(result.status, result.err)
case <-time.After(m.CheckInterval - 1*time.Millisecond):
log.Errorf("Error, check %s timed out! (%v)", check.ID, check.Args)
check.UpdateStatus(UNKNOWN, errors.New("Timed out!"))
}
}(check, resultChan) // copy check pointer for the goroutine
}
// Let's make sure we don't continue to spool up
// huge quantities of goroutines. Wait on all of them
// to complete before moving on. This could slow down
// our check loop if something doesn't time out properly.
wg.Wait()
return nil
})
}
|
[
"func",
"(",
"m",
"*",
"Monitor",
")",
"Run",
"(",
"looper",
"director",
".",
"Looper",
")",
"{",
"looper",
".",
"Loop",
"(",
"func",
"(",
")",
"error",
"{",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n\n",
"var",
"wg",
"sync",
".",
"WaitGroup",
"\n\n",
"// Make immutable copy of m.Checks (checks are still mutable)",
"m",
".",
"RLock",
"(",
")",
"\n",
"checks",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Check",
",",
"len",
"(",
"m",
".",
"Checks",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"m",
".",
"Checks",
"{",
"checks",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"m",
".",
"RUnlock",
"(",
")",
"\n\n",
"wg",
".",
"Add",
"(",
"len",
"(",
"checks",
")",
")",
"\n",
"for",
"_",
",",
"check",
":=",
"range",
"checks",
"{",
"// Run all checks in parallel in goroutines",
"resultChan",
":=",
"make",
"(",
"chan",
"checkResult",
",",
"1",
")",
"\n\n",
"go",
"func",
"(",
"check",
"*",
"Check",
",",
"resultChan",
"chan",
"checkResult",
")",
"{",
"result",
",",
"err",
":=",
"check",
".",
"Command",
".",
"Run",
"(",
"check",
".",
"Args",
")",
"\n",
"resultChan",
"<-",
"checkResult",
"{",
"result",
",",
"err",
"}",
"\n",
"}",
"(",
"check",
",",
"resultChan",
")",
"// copy check pointer for the goroutine",
"\n\n",
"go",
"func",
"(",
"check",
"*",
"Check",
",",
"resultChan",
"chan",
"checkResult",
")",
"{",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"// We make the call but we time out if it gets too close to the",
"// m.CheckInterval.",
"select",
"{",
"case",
"result",
":=",
"<-",
"resultChan",
":",
"check",
".",
"UpdateStatus",
"(",
"result",
".",
"status",
",",
"result",
".",
"err",
")",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"m",
".",
"CheckInterval",
"-",
"1",
"*",
"time",
".",
"Millisecond",
")",
":",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"check",
".",
"ID",
",",
"check",
".",
"Args",
")",
"\n",
"check",
".",
"UpdateStatus",
"(",
"UNKNOWN",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"}",
"(",
"check",
",",
"resultChan",
")",
"// copy check pointer for the goroutine",
"\n",
"}",
"\n\n",
"// Let's make sure we don't continue to spool up",
"// huge quantities of goroutines. Wait on all of them",
"// to complete before moving on. This could slow down",
"// our check loop if something doesn't time out properly.",
"wg",
".",
"Wait",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] |
// Run runs the main monitoring loop. The looper controls the actual run behavior.
|
[
"Run",
"runs",
"the",
"main",
"monitoring",
"loop",
".",
"The",
"looper",
"controls",
"the",
"actual",
"run",
"behavior",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/healthy/healthy.go#L166-L213
|
11,831 |
newrelic/sidecar
|
discovery/service_namer.go
|
ServiceName
|
func (r *RegexpNamer) ServiceName(container *docker.APIContainers) string {
if container == nil {
log.Warn("ServiceName() called with nil service passed!")
return ""
}
if r.expression == nil {
log.Errorf("Invalid regex can't match using: %s", r.ServiceNameMatch)
return container.Image
}
var svcName string
toMatch := []byte(container.Names[0])
matches := r.expression.FindSubmatch(toMatch)
if len(matches) < 1 {
svcName = container.Image
} else {
svcName = string(matches[1])
}
return svcName
}
|
go
|
func (r *RegexpNamer) ServiceName(container *docker.APIContainers) string {
if container == nil {
log.Warn("ServiceName() called with nil service passed!")
return ""
}
if r.expression == nil {
log.Errorf("Invalid regex can't match using: %s", r.ServiceNameMatch)
return container.Image
}
var svcName string
toMatch := []byte(container.Names[0])
matches := r.expression.FindSubmatch(toMatch)
if len(matches) < 1 {
svcName = container.Image
} else {
svcName = string(matches[1])
}
return svcName
}
|
[
"func",
"(",
"r",
"*",
"RegexpNamer",
")",
"ServiceName",
"(",
"container",
"*",
"docker",
".",
"APIContainers",
")",
"string",
"{",
"if",
"container",
"==",
"nil",
"{",
"log",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"if",
"r",
".",
"expression",
"==",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"r",
".",
"ServiceNameMatch",
")",
"\n",
"return",
"container",
".",
"Image",
"\n",
"}",
"\n\n",
"var",
"svcName",
"string",
"\n\n",
"toMatch",
":=",
"[",
"]",
"byte",
"(",
"container",
".",
"Names",
"[",
"0",
"]",
")",
"\n",
"matches",
":=",
"r",
".",
"expression",
".",
"FindSubmatch",
"(",
"toMatch",
")",
"\n",
"if",
"len",
"(",
"matches",
")",
"<",
"1",
"{",
"svcName",
"=",
"container",
".",
"Image",
"\n",
"}",
"else",
"{",
"svcName",
"=",
"string",
"(",
"matches",
"[",
"1",
"]",
")",
"\n",
"}",
"\n\n",
"return",
"svcName",
"\n",
"}"
] |
// Return a properly regex-matched name for the service, or failing that,
// the Image ID which we use to stand in for the name of the service.
|
[
"Return",
"a",
"properly",
"regex",
"-",
"matched",
"name",
"for",
"the",
"service",
"or",
"failing",
"that",
"the",
"Image",
"ID",
"which",
"we",
"use",
"to",
"stand",
"in",
"for",
"the",
"name",
"of",
"the",
"service",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/service_namer.go#L35-L57
|
11,832 |
newrelic/sidecar
|
discovery/service_namer.go
|
ServiceName
|
func (d *DockerLabelNamer) ServiceName(container *docker.APIContainers) string {
if container == nil {
log.Warn("ServiceName() called with nil service passed!")
return ""
}
for label, value := range container.Labels {
if label == d.Label {
return value
}
}
log.Debugf(
"Found container with no '%s' label: %s (%s), returning '%s'", d.Label,
container.ID, container.Names[0], container.Image,
)
return container.Image
}
|
go
|
func (d *DockerLabelNamer) ServiceName(container *docker.APIContainers) string {
if container == nil {
log.Warn("ServiceName() called with nil service passed!")
return ""
}
for label, value := range container.Labels {
if label == d.Label {
return value
}
}
log.Debugf(
"Found container with no '%s' label: %s (%s), returning '%s'", d.Label,
container.ID, container.Names[0], container.Image,
)
return container.Image
}
|
[
"func",
"(",
"d",
"*",
"DockerLabelNamer",
")",
"ServiceName",
"(",
"container",
"*",
"docker",
".",
"APIContainers",
")",
"string",
"{",
"if",
"container",
"==",
"nil",
"{",
"log",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"for",
"label",
",",
"value",
":=",
"range",
"container",
".",
"Labels",
"{",
"if",
"label",
"==",
"d",
".",
"Label",
"{",
"return",
"value",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"d",
".",
"Label",
",",
"container",
".",
"ID",
",",
"container",
".",
"Names",
"[",
"0",
"]",
",",
"container",
".",
"Image",
",",
")",
"\n\n",
"return",
"container",
".",
"Image",
"\n",
"}"
] |
// Return the value of the configured Docker label, or default to the image
// name.
|
[
"Return",
"the",
"value",
"of",
"the",
"configured",
"Docker",
"label",
"or",
"default",
"to",
"the",
"image",
"name",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/discovery/service_namer.go#L67-L85
|
11,833 |
newrelic/sidecar
|
sidecarhttp/envoy_api_ffjson.go
|
UnmarshalJSON
|
func (j *EnvoyListener) UnmarshalJSON(input []byte) error {
fs := fflib.NewFFLexer(input)
return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)
}
|
go
|
func (j *EnvoyListener) UnmarshalJSON(input []byte) error {
fs := fflib.NewFFLexer(input)
return j.UnmarshalJSONFFLexer(fs, fflib.FFParse_map_start)
}
|
[
"func",
"(",
"j",
"*",
"EnvoyListener",
")",
"UnmarshalJSON",
"(",
"input",
"[",
"]",
"byte",
")",
"error",
"{",
"fs",
":=",
"fflib",
".",
"NewFFLexer",
"(",
"input",
")",
"\n",
"return",
"j",
".",
"UnmarshalJSONFFLexer",
"(",
"fs",
",",
"fflib",
".",
"FFParse_map_start",
")",
"\n",
"}"
] |
// UnmarshalJSON umarshall json - template of ffjson
|
[
"UnmarshalJSON",
"umarshall",
"json",
"-",
"template",
"of",
"ffjson"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/envoy_api_ffjson.go#L2012-L2015
|
11,834 |
newrelic/sidecar
|
sidecarhttp/envoy_api_ffjson.go
|
MarshalJSON
|
func (j *EnvoyRoute) MarshalJSON() ([]byte, error) {
var buf fflib.Buffer
if j == nil {
buf.WriteString("null")
return buf.Bytes(), nil
}
err := j.MarshalJSONBuf(&buf)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
|
go
|
func (j *EnvoyRoute) MarshalJSON() ([]byte, error) {
var buf fflib.Buffer
if j == nil {
buf.WriteString("null")
return buf.Bytes(), nil
}
err := j.MarshalJSONBuf(&buf)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
|
[
"func",
"(",
"j",
"*",
"EnvoyRoute",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"buf",
"fflib",
".",
"Buffer",
"\n",
"if",
"j",
"==",
"nil",
"{",
"buf",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"err",
":=",
"j",
".",
"MarshalJSONBuf",
"(",
"&",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] |
// MarshalJSON marshal bytes to json - template
|
[
"MarshalJSON",
"marshal",
"bytes",
"to",
"json",
"-",
"template"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/sidecarhttp/envoy_api_ffjson.go#L2301-L2312
|
11,835 |
newrelic/sidecar
|
services_delegate.go
|
Start
|
func (d *servicesDelegate) Start() {
go func() {
for message := range d.notifications {
entry := service.Decode(message)
if entry == nil {
log.Errorf("NotifyMsg(): error decoding!")
continue
}
d.state.ServiceMsgs <- *entry
}
}()
d.Started = true
d.StartedAt = time.Now().UTC()
}
|
go
|
func (d *servicesDelegate) Start() {
go func() {
for message := range d.notifications {
entry := service.Decode(message)
if entry == nil {
log.Errorf("NotifyMsg(): error decoding!")
continue
}
d.state.ServiceMsgs <- *entry
}
}()
d.Started = true
d.StartedAt = time.Now().UTC()
}
|
[
"func",
"(",
"d",
"*",
"servicesDelegate",
")",
"Start",
"(",
")",
"{",
"go",
"func",
"(",
")",
"{",
"for",
"message",
":=",
"range",
"d",
".",
"notifications",
"{",
"entry",
":=",
"service",
".",
"Decode",
"(",
"message",
")",
"\n",
"if",
"entry",
"==",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"d",
".",
"state",
".",
"ServiceMsgs",
"<-",
"*",
"entry",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"d",
".",
"Started",
"=",
"true",
"\n",
"d",
".",
"StartedAt",
"=",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
"\n",
"}"
] |
// Start kicks off the goroutine that will process incoming notifications of services
|
[
"Start",
"kicks",
"off",
"the",
"goroutine",
"that",
"will",
"process",
"incoming",
"notifications",
"of",
"services"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/services_delegate.go#L45-L59
|
11,836 |
newrelic/sidecar
|
services_delegate.go
|
packPacket
|
func (d *servicesDelegate) packPacket(broadcasts [][]byte, limit int, overhead int) (packet [][]byte, leftover [][]byte) {
total := 0
lastItem := -1
// Find the index of the last item that fits into the packet we're building
for i, message := range broadcasts {
if total+len(message)+overhead > limit {
break
}
lastItem = i
total += len(message) + overhead
}
if lastItem < 0 && len(broadcasts) > 0 {
// Don't warn on startup... it's fairly normal
gracePeriod := time.Now().UTC().Add(0 - (5 * time.Second))
if d.StartedAt.Before(gracePeriod) {
log.Warnf("All messages were too long to fit! No broadcasts!")
}
// There could be a scenario here where one hugely long broadcast could
// get stuck forever and prevent anything else from going out. There
// may be a better way to handle this. Scanning for the next message that
// does fit results in lots of memory copying and doesn't perform at scale.
return nil, broadcasts
}
// Save the leftover messages after the last one that fit. If this is too
// much, then set it to the lastItem.
firstLeftover := lastItem + 1
return broadcasts[:lastItem+1], broadcasts[firstLeftover:]
}
|
go
|
func (d *servicesDelegate) packPacket(broadcasts [][]byte, limit int, overhead int) (packet [][]byte, leftover [][]byte) {
total := 0
lastItem := -1
// Find the index of the last item that fits into the packet we're building
for i, message := range broadcasts {
if total+len(message)+overhead > limit {
break
}
lastItem = i
total += len(message) + overhead
}
if lastItem < 0 && len(broadcasts) > 0 {
// Don't warn on startup... it's fairly normal
gracePeriod := time.Now().UTC().Add(0 - (5 * time.Second))
if d.StartedAt.Before(gracePeriod) {
log.Warnf("All messages were too long to fit! No broadcasts!")
}
// There could be a scenario here where one hugely long broadcast could
// get stuck forever and prevent anything else from going out. There
// may be a better way to handle this. Scanning for the next message that
// does fit results in lots of memory copying and doesn't perform at scale.
return nil, broadcasts
}
// Save the leftover messages after the last one that fit. If this is too
// much, then set it to the lastItem.
firstLeftover := lastItem + 1
return broadcasts[:lastItem+1], broadcasts[firstLeftover:]
}
|
[
"func",
"(",
"d",
"*",
"servicesDelegate",
")",
"packPacket",
"(",
"broadcasts",
"[",
"]",
"[",
"]",
"byte",
",",
"limit",
"int",
",",
"overhead",
"int",
")",
"(",
"packet",
"[",
"]",
"[",
"]",
"byte",
",",
"leftover",
"[",
"]",
"[",
"]",
"byte",
")",
"{",
"total",
":=",
"0",
"\n",
"lastItem",
":=",
"-",
"1",
"\n\n",
"// Find the index of the last item that fits into the packet we're building",
"for",
"i",
",",
"message",
":=",
"range",
"broadcasts",
"{",
"if",
"total",
"+",
"len",
"(",
"message",
")",
"+",
"overhead",
">",
"limit",
"{",
"break",
"\n",
"}",
"\n\n",
"lastItem",
"=",
"i",
"\n",
"total",
"+=",
"len",
"(",
"message",
")",
"+",
"overhead",
"\n",
"}",
"\n\n",
"if",
"lastItem",
"<",
"0",
"&&",
"len",
"(",
"broadcasts",
")",
">",
"0",
"{",
"// Don't warn on startup... it's fairly normal",
"gracePeriod",
":=",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"Add",
"(",
"0",
"-",
"(",
"5",
"*",
"time",
".",
"Second",
")",
")",
"\n",
"if",
"d",
".",
"StartedAt",
".",
"Before",
"(",
"gracePeriod",
")",
"{",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// There could be a scenario here where one hugely long broadcast could",
"// get stuck forever and prevent anything else from going out. There",
"// may be a better way to handle this. Scanning for the next message that",
"// does fit results in lots of memory copying and doesn't perform at scale.",
"return",
"nil",
",",
"broadcasts",
"\n",
"}",
"\n\n",
"// Save the leftover messages after the last one that fit. If this is too",
"// much, then set it to the lastItem.",
"firstLeftover",
":=",
"lastItem",
"+",
"1",
"\n\n",
"return",
"broadcasts",
"[",
":",
"lastItem",
"+",
"1",
"]",
",",
"broadcasts",
"[",
"firstLeftover",
":",
"]",
"\n",
"}"
] |
// Try to pack as many messages into the packet as we can. Note that this
// assumes that no messages will be longer than the normal UDP packet size.
// This means that max message length is somewhere around 1398 when taking
// messaging overhead into account.
|
[
"Try",
"to",
"pack",
"as",
"many",
"messages",
"into",
"the",
"packet",
"as",
"we",
"can",
".",
"Note",
"that",
"this",
"assumes",
"that",
"no",
"messages",
"will",
"be",
"longer",
"than",
"the",
"normal",
"UDP",
"packet",
"size",
".",
"This",
"means",
"that",
"max",
"message",
"length",
"is",
"somewhere",
"around",
"1398",
"when",
"taking",
"messaging",
"overhead",
"into",
"account",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/services_delegate.go#L189-L222
|
11,837 |
newrelic/sidecar
|
service/service.go
|
Version
|
func (svc *Service) Version() string {
parts := strings.Split(svc.Image, ":")
if len(parts) > 1 {
return parts[1]
}
return parts[0]
}
|
go
|
func (svc *Service) Version() string {
parts := strings.Split(svc.Image, ":")
if len(parts) > 1 {
return parts[1]
}
return parts[0]
}
|
[
"func",
"(",
"svc",
"*",
"Service",
")",
"Version",
"(",
")",
"string",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"svc",
".",
"Image",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
">",
"1",
"{",
"return",
"parts",
"[",
"1",
"]",
"\n",
"}",
"\n\n",
"return",
"parts",
"[",
"0",
"]",
"\n",
"}"
] |
// Version attempts to extract a version from the image. Otherwise it returns
// the full image name.
|
[
"Version",
"attempts",
"to",
"extract",
"a",
"version",
"from",
"the",
"image",
".",
"Otherwise",
"it",
"returns",
"the",
"full",
"image",
"name",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/service/service.go#L104-L111
|
11,838 |
newrelic/sidecar
|
service/service.go
|
ToService
|
func ToService(container *docker.APIContainers, ip string) Service {
var svc Service
hostname, _ := os.Hostname()
svc.ID = container.ID[0:12] // Use short IDs
svc.Name = container.Names[0] // Use the first name
svc.Image = container.Image
svc.Created = time.Unix(container.Created, 0).UTC()
svc.Updated = time.Now().UTC()
svc.Hostname = hostname
svc.Status = ALIVE
if _, ok := container.Labels["ProxyMode"]; ok {
svc.ProxyMode = container.Labels["ProxyMode"]
} else {
svc.ProxyMode = "http"
}
svc.Ports = make([]Port, 0)
for _, port := range container.Ports {
if port.PublicPort != 0 {
svc.Ports = append(svc.Ports, buildPortFor(&port, container, ip))
}
}
return svc
}
|
go
|
func ToService(container *docker.APIContainers, ip string) Service {
var svc Service
hostname, _ := os.Hostname()
svc.ID = container.ID[0:12] // Use short IDs
svc.Name = container.Names[0] // Use the first name
svc.Image = container.Image
svc.Created = time.Unix(container.Created, 0).UTC()
svc.Updated = time.Now().UTC()
svc.Hostname = hostname
svc.Status = ALIVE
if _, ok := container.Labels["ProxyMode"]; ok {
svc.ProxyMode = container.Labels["ProxyMode"]
} else {
svc.ProxyMode = "http"
}
svc.Ports = make([]Port, 0)
for _, port := range container.Ports {
if port.PublicPort != 0 {
svc.Ports = append(svc.Ports, buildPortFor(&port, container, ip))
}
}
return svc
}
|
[
"func",
"ToService",
"(",
"container",
"*",
"docker",
".",
"APIContainers",
",",
"ip",
"string",
")",
"Service",
"{",
"var",
"svc",
"Service",
"\n",
"hostname",
",",
"_",
":=",
"os",
".",
"Hostname",
"(",
")",
"\n\n",
"svc",
".",
"ID",
"=",
"container",
".",
"ID",
"[",
"0",
":",
"12",
"]",
"// Use short IDs",
"\n",
"svc",
".",
"Name",
"=",
"container",
".",
"Names",
"[",
"0",
"]",
"// Use the first name",
"\n",
"svc",
".",
"Image",
"=",
"container",
".",
"Image",
"\n",
"svc",
".",
"Created",
"=",
"time",
".",
"Unix",
"(",
"container",
".",
"Created",
",",
"0",
")",
".",
"UTC",
"(",
")",
"\n",
"svc",
".",
"Updated",
"=",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
"\n",
"svc",
".",
"Hostname",
"=",
"hostname",
"\n",
"svc",
".",
"Status",
"=",
"ALIVE",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"container",
".",
"Labels",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"svc",
".",
"ProxyMode",
"=",
"container",
".",
"Labels",
"[",
"\"",
"\"",
"]",
"\n",
"}",
"else",
"{",
"svc",
".",
"ProxyMode",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"svc",
".",
"Ports",
"=",
"make",
"(",
"[",
"]",
"Port",
",",
"0",
")",
"\n\n",
"for",
"_",
",",
"port",
":=",
"range",
"container",
".",
"Ports",
"{",
"if",
"port",
".",
"PublicPort",
"!=",
"0",
"{",
"svc",
".",
"Ports",
"=",
"append",
"(",
"svc",
".",
"Ports",
",",
"buildPortFor",
"(",
"&",
"port",
",",
"container",
",",
"ip",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"svc",
"\n",
"}"
] |
// Format an APIContainers struct into a more compact struct we
// can ship over the wire in a broadcast.
|
[
"Format",
"an",
"APIContainers",
"struct",
"into",
"a",
"more",
"compact",
"struct",
"we",
"can",
"ship",
"over",
"the",
"wire",
"in",
"a",
"broadcast",
"."
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/service/service.go#L122-L149
|
11,839 |
newrelic/sidecar
|
service/service.go
|
buildPortFor
|
func buildPortFor(port *docker.APIPort, container *docker.APIContainers, ip string) Port {
// We look up service port labels by convention in the format "ServicePort_80=8080"
svcPortLabel := fmt.Sprintf("ServicePort_%d", port.PrivatePort)
// You can override the default IP by binding your container on a specific IP
if port.IP != "0.0.0.0" && port.IP != "" {
ip = port.IP
}
returnPort := Port{Port: port.PublicPort, Type: port.Type, IP: ip}
if svcPort, ok := container.Labels[svcPortLabel]; ok {
svcPortInt, err := strconv.Atoi(svcPort)
if err != nil {
log.Errorf("Error converting label value for %s to integer: %s",
svcPortLabel,
err.Error(),
)
return returnPort
}
// Everything was good, set the service port
returnPort.ServicePort = int64(svcPortInt)
}
return returnPort
}
|
go
|
func buildPortFor(port *docker.APIPort, container *docker.APIContainers, ip string) Port {
// We look up service port labels by convention in the format "ServicePort_80=8080"
svcPortLabel := fmt.Sprintf("ServicePort_%d", port.PrivatePort)
// You can override the default IP by binding your container on a specific IP
if port.IP != "0.0.0.0" && port.IP != "" {
ip = port.IP
}
returnPort := Port{Port: port.PublicPort, Type: port.Type, IP: ip}
if svcPort, ok := container.Labels[svcPortLabel]; ok {
svcPortInt, err := strconv.Atoi(svcPort)
if err != nil {
log.Errorf("Error converting label value for %s to integer: %s",
svcPortLabel,
err.Error(),
)
return returnPort
}
// Everything was good, set the service port
returnPort.ServicePort = int64(svcPortInt)
}
return returnPort
}
|
[
"func",
"buildPortFor",
"(",
"port",
"*",
"docker",
".",
"APIPort",
",",
"container",
"*",
"docker",
".",
"APIContainers",
",",
"ip",
"string",
")",
"Port",
"{",
"// We look up service port labels by convention in the format \"ServicePort_80=8080\"",
"svcPortLabel",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"port",
".",
"PrivatePort",
")",
"\n\n",
"// You can override the default IP by binding your container on a specific IP",
"if",
"port",
".",
"IP",
"!=",
"\"",
"\"",
"&&",
"port",
".",
"IP",
"!=",
"\"",
"\"",
"{",
"ip",
"=",
"port",
".",
"IP",
"\n",
"}",
"\n\n",
"returnPort",
":=",
"Port",
"{",
"Port",
":",
"port",
".",
"PublicPort",
",",
"Type",
":",
"port",
".",
"Type",
",",
"IP",
":",
"ip",
"}",
"\n\n",
"if",
"svcPort",
",",
"ok",
":=",
"container",
".",
"Labels",
"[",
"svcPortLabel",
"]",
";",
"ok",
"{",
"svcPortInt",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"svcPort",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"svcPortLabel",
",",
"err",
".",
"Error",
"(",
")",
",",
")",
"\n",
"return",
"returnPort",
"\n",
"}",
"\n\n",
"// Everything was good, set the service port",
"returnPort",
".",
"ServicePort",
"=",
"int64",
"(",
"svcPortInt",
")",
"\n",
"}",
"\n\n",
"return",
"returnPort",
"\n",
"}"
] |
// Figure out the correct port configuration for a service
|
[
"Figure",
"out",
"the",
"correct",
"port",
"configuration",
"for",
"a",
"service"
] |
8327834c20bca8a155ccac8bc42ab2f42ca925a6
|
https://github.com/newrelic/sidecar/blob/8327834c20bca8a155ccac8bc42ab2f42ca925a6/service/service.go#L165-L191
|
11,840 |
lytics/anomalyzer
|
anomalyze.go
|
Eval
|
func (a Anomalyzer) Eval() float64 {
threshold := a.Conf.referenceSize + a.Conf.ActiveSize
if a.Conf.Delay && len(a.Data) < threshold {
return 0.0
}
probmap := make(map[string]float64)
for _, method := range a.Conf.Methods {
algorithm := Algorithms[method]
prob := cap(algorithm(a.Data, *a.Conf), 0, 1)
if prob != NA {
// if highrank and lowrank methods exist then only listen to
// the max of either
if method == "highrank" || method == "lowrank" {
if math.IsNaN(probmap["rank"]) {
probmap["rank"] = 0
}
probmap["rank"] = math.Max(probmap["rank"], prob)
} else {
probmap[method] = prob
}
}
}
probs := make(govector.Vector, 0, len(probmap))
weights := make(govector.Vector, 0, len(probmap))
for method, prob := range probmap {
if method == "magnitude" && prob < a.Conf.Sensitivity {
return 0.0
}
probs = append(probs, prob)
weights = append(weights, a.getWeight(method, prob))
}
// ignore the error since we force the length of probs
// and the weights to be equal
weighted, _ := probs.WeightedMean(weights)
// if all the weights are zero, then our weighted mean
// function attempts to divide by zero which returns a
// NaN. we'd like it to return 0.
if math.IsNaN(weighted) {
weighted = 0
}
return weighted
}
|
go
|
func (a Anomalyzer) Eval() float64 {
threshold := a.Conf.referenceSize + a.Conf.ActiveSize
if a.Conf.Delay && len(a.Data) < threshold {
return 0.0
}
probmap := make(map[string]float64)
for _, method := range a.Conf.Methods {
algorithm := Algorithms[method]
prob := cap(algorithm(a.Data, *a.Conf), 0, 1)
if prob != NA {
// if highrank and lowrank methods exist then only listen to
// the max of either
if method == "highrank" || method == "lowrank" {
if math.IsNaN(probmap["rank"]) {
probmap["rank"] = 0
}
probmap["rank"] = math.Max(probmap["rank"], prob)
} else {
probmap[method] = prob
}
}
}
probs := make(govector.Vector, 0, len(probmap))
weights := make(govector.Vector, 0, len(probmap))
for method, prob := range probmap {
if method == "magnitude" && prob < a.Conf.Sensitivity {
return 0.0
}
probs = append(probs, prob)
weights = append(weights, a.getWeight(method, prob))
}
// ignore the error since we force the length of probs
// and the weights to be equal
weighted, _ := probs.WeightedMean(weights)
// if all the weights are zero, then our weighted mean
// function attempts to divide by zero which returns a
// NaN. we'd like it to return 0.
if math.IsNaN(weighted) {
weighted = 0
}
return weighted
}
|
[
"func",
"(",
"a",
"Anomalyzer",
")",
"Eval",
"(",
")",
"float64",
"{",
"threshold",
":=",
"a",
".",
"Conf",
".",
"referenceSize",
"+",
"a",
".",
"Conf",
".",
"ActiveSize",
"\n",
"if",
"a",
".",
"Conf",
".",
"Delay",
"&&",
"len",
"(",
"a",
".",
"Data",
")",
"<",
"threshold",
"{",
"return",
"0.0",
"\n",
"}",
"\n",
"probmap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"float64",
")",
"\n",
"for",
"_",
",",
"method",
":=",
"range",
"a",
".",
"Conf",
".",
"Methods",
"{",
"algorithm",
":=",
"Algorithms",
"[",
"method",
"]",
"\n",
"prob",
":=",
"cap",
"(",
"algorithm",
"(",
"a",
".",
"Data",
",",
"*",
"a",
".",
"Conf",
")",
",",
"0",
",",
"1",
")",
"\n",
"if",
"prob",
"!=",
"NA",
"{",
"// if highrank and lowrank methods exist then only listen to",
"// the max of either",
"if",
"method",
"==",
"\"",
"\"",
"||",
"method",
"==",
"\"",
"\"",
"{",
"if",
"math",
".",
"IsNaN",
"(",
"probmap",
"[",
"\"",
"\"",
"]",
")",
"{",
"probmap",
"[",
"\"",
"\"",
"]",
"=",
"0",
"\n",
"}",
"\n",
"probmap",
"[",
"\"",
"\"",
"]",
"=",
"math",
".",
"Max",
"(",
"probmap",
"[",
"\"",
"\"",
"]",
",",
"prob",
")",
"\n",
"}",
"else",
"{",
"probmap",
"[",
"method",
"]",
"=",
"prob",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"probs",
":=",
"make",
"(",
"govector",
".",
"Vector",
",",
"0",
",",
"len",
"(",
"probmap",
")",
")",
"\n",
"weights",
":=",
"make",
"(",
"govector",
".",
"Vector",
",",
"0",
",",
"len",
"(",
"probmap",
")",
")",
"\n\n",
"for",
"method",
",",
"prob",
":=",
"range",
"probmap",
"{",
"if",
"method",
"==",
"\"",
"\"",
"&&",
"prob",
"<",
"a",
".",
"Conf",
".",
"Sensitivity",
"{",
"return",
"0.0",
"\n",
"}",
"\n",
"probs",
"=",
"append",
"(",
"probs",
",",
"prob",
")",
"\n",
"weights",
"=",
"append",
"(",
"weights",
",",
"a",
".",
"getWeight",
"(",
"method",
",",
"prob",
")",
")",
"\n",
"}",
"\n\n",
"// ignore the error since we force the length of probs",
"// and the weights to be equal",
"weighted",
",",
"_",
":=",
"probs",
".",
"WeightedMean",
"(",
"weights",
")",
"\n\n",
"// if all the weights are zero, then our weighted mean",
"// function attempts to divide by zero which returns a",
"// NaN. we'd like it to return 0.",
"if",
"math",
".",
"IsNaN",
"(",
"weighted",
")",
"{",
"weighted",
"=",
"0",
"\n",
"}",
"\n\n",
"return",
"weighted",
"\n",
"}"
] |
// Return the weighted average of all statistical tests
// for anomaly detection, which yields the probability that
// the currently observed behavior is anomalous.
|
[
"Return",
"the",
"weighted",
"average",
"of",
"all",
"statistical",
"tests",
"for",
"anomaly",
"detection",
"which",
"yields",
"the",
"probability",
"that",
"the",
"currently",
"observed",
"behavior",
"is",
"anomalous",
"."
] |
13cee106170131d4088721db299d09b42db508ac
|
https://github.com/lytics/anomalyzer/blob/13cee106170131d4088721db299d09b42db508ac/anomalyze.go#L145-L192
|
11,841 |
lytics/anomalyzer
|
anomalyze.go
|
getWeight
|
func (a Anomalyzer) getWeight(name string, prob float64) float64 {
weight := 0.5
dynamicWeights := []string{"magnitude", "fence"}
// If either the magnitude and fence methods don't have any
// probability to contribute, we don't want to hear about it.
// If they do, we upweight them substantially.
if exists(name, dynamicWeights) {
if prob > 0.8 {
weight = 5.0
} else {
weight = 0.5
}
}
return weight
}
|
go
|
func (a Anomalyzer) getWeight(name string, prob float64) float64 {
weight := 0.5
dynamicWeights := []string{"magnitude", "fence"}
// If either the magnitude and fence methods don't have any
// probability to contribute, we don't want to hear about it.
// If they do, we upweight them substantially.
if exists(name, dynamicWeights) {
if prob > 0.8 {
weight = 5.0
} else {
weight = 0.5
}
}
return weight
}
|
[
"func",
"(",
"a",
"Anomalyzer",
")",
"getWeight",
"(",
"name",
"string",
",",
"prob",
"float64",
")",
"float64",
"{",
"weight",
":=",
"0.5",
"\n\n",
"dynamicWeights",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"\n",
"// If either the magnitude and fence methods don't have any",
"// probability to contribute, we don't want to hear about it.",
"// If they do, we upweight them substantially.",
"if",
"exists",
"(",
"name",
",",
"dynamicWeights",
")",
"{",
"if",
"prob",
">",
"0.8",
"{",
"weight",
"=",
"5.0",
"\n",
"}",
"else",
"{",
"weight",
"=",
"0.5",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"weight",
"\n",
"}"
] |
// Use essentially similar weights. However, if either the magnitude
// or fence methods have high probabilities, upweight them significantly.
|
[
"Use",
"essentially",
"similar",
"weights",
".",
"However",
"if",
"either",
"the",
"magnitude",
"or",
"fence",
"methods",
"have",
"high",
"probabilities",
"upweight",
"them",
"significantly",
"."
] |
13cee106170131d4088721db299d09b42db508ac
|
https://github.com/lytics/anomalyzer/blob/13cee106170131d4088721db299d09b42db508ac/anomalyze.go#L225-L241
|
11,842 |
lytics/anomalyzer
|
algorithms.go
|
extractWindows
|
func extractWindows(vector govector.Vector, refSize, activeSize, minRefSize int) (govector.Vector, govector.Vector, error) {
n := len(vector)
activeSize = min(activeSize, n)
refSize = min(refSize, n-activeSize)
// make sure the reference size is at least as big as the active size
// note that this penalty might be overly severe for some tests
if refSize < minRefSize {
return nil, nil, fmt.Errorf("Reference size must be at least as big as active size")
}
// return reference and active windows
return vector[n-activeSize-refSize : n-activeSize], vector[n-activeSize:], nil
}
|
go
|
func extractWindows(vector govector.Vector, refSize, activeSize, minRefSize int) (govector.Vector, govector.Vector, error) {
n := len(vector)
activeSize = min(activeSize, n)
refSize = min(refSize, n-activeSize)
// make sure the reference size is at least as big as the active size
// note that this penalty might be overly severe for some tests
if refSize < minRefSize {
return nil, nil, fmt.Errorf("Reference size must be at least as big as active size")
}
// return reference and active windows
return vector[n-activeSize-refSize : n-activeSize], vector[n-activeSize:], nil
}
|
[
"func",
"extractWindows",
"(",
"vector",
"govector",
".",
"Vector",
",",
"refSize",
",",
"activeSize",
",",
"minRefSize",
"int",
")",
"(",
"govector",
".",
"Vector",
",",
"govector",
".",
"Vector",
",",
"error",
")",
"{",
"n",
":=",
"len",
"(",
"vector",
")",
"\n",
"activeSize",
"=",
"min",
"(",
"activeSize",
",",
"n",
")",
"\n",
"refSize",
"=",
"min",
"(",
"refSize",
",",
"n",
"-",
"activeSize",
")",
"\n\n",
"// make sure the reference size is at least as big as the active size",
"// note that this penalty might be overly severe for some tests",
"if",
"refSize",
"<",
"minRefSize",
"{",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// return reference and active windows",
"return",
"vector",
"[",
"n",
"-",
"activeSize",
"-",
"refSize",
":",
"n",
"-",
"activeSize",
"]",
",",
"vector",
"[",
"n",
"-",
"activeSize",
":",
"]",
",",
"nil",
"\n",
"}"
] |
// Return a vector slice for the active window and reference window.
// Some tests require different minimum thresholds for sizes of reference windows.
// This can be specified in the minRefSize parameter. If size isn't important, use -1
|
[
"Return",
"a",
"vector",
"slice",
"for",
"the",
"active",
"window",
"and",
"reference",
"window",
".",
"Some",
"tests",
"require",
"different",
"minimum",
"thresholds",
"for",
"sizes",
"of",
"reference",
"windows",
".",
"This",
"can",
"be",
"specified",
"in",
"the",
"minRefSize",
"parameter",
".",
"If",
"size",
"isn",
"t",
"important",
"use",
"-",
"1"
] |
13cee106170131d4088721db299d09b42db508ac
|
https://github.com/lytics/anomalyzer/blob/13cee106170131d4088721db299d09b42db508ac/algorithms.go#L56-L69
|
11,843 |
lytics/anomalyzer
|
algorithms.go
|
weightExp
|
func weightExp(x, base float64) float64 {
return (math.Pow(base, x) - 1) / (math.Pow(base, 1) - 1)
}
|
go
|
func weightExp(x, base float64) float64 {
return (math.Pow(base, x) - 1) / (math.Pow(base, 1) - 1)
}
|
[
"func",
"weightExp",
"(",
"x",
",",
"base",
"float64",
")",
"float64",
"{",
"return",
"(",
"math",
".",
"Pow",
"(",
"base",
",",
"x",
")",
"-",
"1",
")",
"/",
"(",
"math",
".",
"Pow",
"(",
"base",
",",
"1",
")",
"-",
"1",
")",
"\n",
"}"
] |
// This is a function will sharply scale values between 0 and 1 such that
// smaller values are weighted more towards 0. A larger base value means a
// more horshoe type function.
|
[
"This",
"is",
"a",
"function",
"will",
"sharply",
"scale",
"values",
"between",
"0",
"and",
"1",
"such",
"that",
"smaller",
"values",
"are",
"weighted",
"more",
"towards",
"0",
".",
"A",
"larger",
"base",
"value",
"means",
"a",
"more",
"horshoe",
"type",
"function",
"."
] |
13cee106170131d4088721db299d09b42db508ac
|
https://github.com/lytics/anomalyzer/blob/13cee106170131d4088721db299d09b42db508ac/algorithms.go#L98-L100
|
11,844 |
lytics/anomalyzer
|
algorithms.go
|
KsStat
|
func KsStat(vector govector.Vector, conf AnomalyzerConf) float64 {
reference, active, err := extractWindows(vector, conf.referenceSize, conf.ActiveSize, conf.ActiveSize)
if err != nil {
return NA
}
n1 := len(reference)
n2 := len(active)
if n1%n2 != 0 {
return NA
}
// First sort the active data and generate a cummulative distribution function
// using that data. Do the same for the reference data.
activeEcdf := active.Ecdf()
refEcdf := reference.Ecdf()
// We want the reference and active vectors to have the same length n, so we
// consider the min and max for each and interpolated the points between.
min := math.Min(reference.Min(), active.Min())
max := math.Max(reference.Max(), active.Max())
interpolated := interpolate(min, max, n1+n2)
// Then we apply the distribution function over the interpolated data.
activeDist := interpolated.Apply(activeEcdf)
refDist := interpolated.Apply(refEcdf)
// Find the maximum displacement between both distributions.
d := 0.0
for i := 0; i < n1+n2; i++ {
d = math.Max(d, math.Abs(activeDist[i]-refDist[i]))
}
return d
}
|
go
|
func KsStat(vector govector.Vector, conf AnomalyzerConf) float64 {
reference, active, err := extractWindows(vector, conf.referenceSize, conf.ActiveSize, conf.ActiveSize)
if err != nil {
return NA
}
n1 := len(reference)
n2 := len(active)
if n1%n2 != 0 {
return NA
}
// First sort the active data and generate a cummulative distribution function
// using that data. Do the same for the reference data.
activeEcdf := active.Ecdf()
refEcdf := reference.Ecdf()
// We want the reference and active vectors to have the same length n, so we
// consider the min and max for each and interpolated the points between.
min := math.Min(reference.Min(), active.Min())
max := math.Max(reference.Max(), active.Max())
interpolated := interpolate(min, max, n1+n2)
// Then we apply the distribution function over the interpolated data.
activeDist := interpolated.Apply(activeEcdf)
refDist := interpolated.Apply(refEcdf)
// Find the maximum displacement between both distributions.
d := 0.0
for i := 0; i < n1+n2; i++ {
d = math.Max(d, math.Abs(activeDist[i]-refDist[i]))
}
return d
}
|
[
"func",
"KsStat",
"(",
"vector",
"govector",
".",
"Vector",
",",
"conf",
"AnomalyzerConf",
")",
"float64",
"{",
"reference",
",",
"active",
",",
"err",
":=",
"extractWindows",
"(",
"vector",
",",
"conf",
".",
"referenceSize",
",",
"conf",
".",
"ActiveSize",
",",
"conf",
".",
"ActiveSize",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"NA",
"\n",
"}",
"\n",
"n1",
":=",
"len",
"(",
"reference",
")",
"\n",
"n2",
":=",
"len",
"(",
"active",
")",
"\n",
"if",
"n1",
"%",
"n2",
"!=",
"0",
"{",
"return",
"NA",
"\n",
"}",
"\n\n",
"// First sort the active data and generate a cummulative distribution function",
"// using that data. Do the same for the reference data.",
"activeEcdf",
":=",
"active",
".",
"Ecdf",
"(",
")",
"\n",
"refEcdf",
":=",
"reference",
".",
"Ecdf",
"(",
")",
"\n\n",
"// We want the reference and active vectors to have the same length n, so we",
"// consider the min and max for each and interpolated the points between.",
"min",
":=",
"math",
".",
"Min",
"(",
"reference",
".",
"Min",
"(",
")",
",",
"active",
".",
"Min",
"(",
")",
")",
"\n",
"max",
":=",
"math",
".",
"Max",
"(",
"reference",
".",
"Max",
"(",
")",
",",
"active",
".",
"Max",
"(",
")",
")",
"\n\n",
"interpolated",
":=",
"interpolate",
"(",
"min",
",",
"max",
",",
"n1",
"+",
"n2",
")",
"\n\n",
"// Then we apply the distribution function over the interpolated data.",
"activeDist",
":=",
"interpolated",
".",
"Apply",
"(",
"activeEcdf",
")",
"\n",
"refDist",
":=",
"interpolated",
".",
"Apply",
"(",
"refEcdf",
")",
"\n\n",
"// Find the maximum displacement between both distributions.",
"d",
":=",
"0.0",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n1",
"+",
"n2",
";",
"i",
"++",
"{",
"d",
"=",
"math",
".",
"Max",
"(",
"d",
",",
"math",
".",
"Abs",
"(",
"activeDist",
"[",
"i",
"]",
"-",
"refDist",
"[",
"i",
"]",
")",
")",
"\n",
"}",
"\n",
"return",
"d",
"\n",
"}"
] |
// Calculate a Kolmogorov-Smirnov test statistic.
|
[
"Calculate",
"a",
"Kolmogorov",
"-",
"Smirnov",
"test",
"statistic",
"."
] |
13cee106170131d4088721db299d09b42db508ac
|
https://github.com/lytics/anomalyzer/blob/13cee106170131d4088721db299d09b42db508ac/algorithms.go#L255-L288
|
11,845 |
lytics/anomalyzer
|
algorithms.go
|
interpolate
|
func interpolate(min, max float64, npoints int) govector.Vector {
interp := make(govector.Vector, npoints)
step := (max - min) / (float64(npoints) - 1)
interp[0] = min
i := 1
for i < npoints {
interp[i] = interp[i-1] + step
i++
}
return interp
}
|
go
|
func interpolate(min, max float64, npoints int) govector.Vector {
interp := make(govector.Vector, npoints)
step := (max - min) / (float64(npoints) - 1)
interp[0] = min
i := 1
for i < npoints {
interp[i] = interp[i-1] + step
i++
}
return interp
}
|
[
"func",
"interpolate",
"(",
"min",
",",
"max",
"float64",
",",
"npoints",
"int",
")",
"govector",
".",
"Vector",
"{",
"interp",
":=",
"make",
"(",
"govector",
".",
"Vector",
",",
"npoints",
")",
"\n\n",
"step",
":=",
"(",
"max",
"-",
"min",
")",
"/",
"(",
"float64",
"(",
"npoints",
")",
"-",
"1",
")",
"\n",
"interp",
"[",
"0",
"]",
"=",
"min",
"\n",
"i",
":=",
"1",
"\n",
"for",
"i",
"<",
"npoints",
"{",
"interp",
"[",
"i",
"]",
"=",
"interp",
"[",
"i",
"-",
"1",
"]",
"+",
"step",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"return",
"interp",
"\n",
"}"
] |
// A helper function for KS that rescales a vector to the desired length npoints.
|
[
"A",
"helper",
"function",
"for",
"KS",
"that",
"rescales",
"a",
"vector",
"to",
"the",
"desired",
"length",
"npoints",
"."
] |
13cee106170131d4088721db299d09b42db508ac
|
https://github.com/lytics/anomalyzer/blob/13cee106170131d4088721db299d09b42db508ac/algorithms.go#L312-L323
|
11,846 |
liip/sheriff
|
sheriff.go
|
marshalValue
|
func marshalValue(options *Options, v reflect.Value) (interface{}, error) {
// return nil on nil pointer struct fields
if !v.IsValid() || !v.CanInterface() {
return nil, nil
}
val := v.Interface()
if marshaller, ok := val.(Marshaller); ok {
return marshaller.Marshal(options)
}
// types which are e.g. structs, slices or maps and implement one of the following interfaces should not be
// marshalled by sheriff because they'll be correctly marshalled by json.Marshal instead.
// Otherwise (e.g. net.IP) a byte slice may be output as a list of uints instead of as an IP string.
switch val.(type) {
case json.Marshaler, encoding.TextMarshaler, fmt.Stringer:
return val, nil
}
k := v.Kind()
if k == reflect.Ptr {
v = v.Elem()
val = v.Interface()
k = v.Kind()
}
if k == reflect.Interface || k == reflect.Struct {
return Marshal(options, val)
}
if k == reflect.Slice {
l := v.Len()
dest := make([]interface{}, l)
for i := 0; i < l; i++ {
d, err := marshalValue(options, v.Index(i))
if err != nil {
return nil, err
}
dest[i] = d
}
return dest, nil
}
if k == reflect.Map {
mapKeys := v.MapKeys()
if len(mapKeys) == 0 {
return nil, nil
}
if mapKeys[0].Kind() != reflect.String {
return nil, MarshalInvalidTypeError{t: mapKeys[0].Kind(), data: val}
}
dest := make(map[string]interface{})
for _, key := range mapKeys {
d, err := marshalValue(options, v.MapIndex(key))
if err != nil {
return nil, err
}
dest[key.Interface().(string)] = d
}
return dest, nil
}
return val, nil
}
|
go
|
func marshalValue(options *Options, v reflect.Value) (interface{}, error) {
// return nil on nil pointer struct fields
if !v.IsValid() || !v.CanInterface() {
return nil, nil
}
val := v.Interface()
if marshaller, ok := val.(Marshaller); ok {
return marshaller.Marshal(options)
}
// types which are e.g. structs, slices or maps and implement one of the following interfaces should not be
// marshalled by sheriff because they'll be correctly marshalled by json.Marshal instead.
// Otherwise (e.g. net.IP) a byte slice may be output as a list of uints instead of as an IP string.
switch val.(type) {
case json.Marshaler, encoding.TextMarshaler, fmt.Stringer:
return val, nil
}
k := v.Kind()
if k == reflect.Ptr {
v = v.Elem()
val = v.Interface()
k = v.Kind()
}
if k == reflect.Interface || k == reflect.Struct {
return Marshal(options, val)
}
if k == reflect.Slice {
l := v.Len()
dest := make([]interface{}, l)
for i := 0; i < l; i++ {
d, err := marshalValue(options, v.Index(i))
if err != nil {
return nil, err
}
dest[i] = d
}
return dest, nil
}
if k == reflect.Map {
mapKeys := v.MapKeys()
if len(mapKeys) == 0 {
return nil, nil
}
if mapKeys[0].Kind() != reflect.String {
return nil, MarshalInvalidTypeError{t: mapKeys[0].Kind(), data: val}
}
dest := make(map[string]interface{})
for _, key := range mapKeys {
d, err := marshalValue(options, v.MapIndex(key))
if err != nil {
return nil, err
}
dest[key.Interface().(string)] = d
}
return dest, nil
}
return val, nil
}
|
[
"func",
"marshalValue",
"(",
"options",
"*",
"Options",
",",
"v",
"reflect",
".",
"Value",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"// return nil on nil pointer struct fields",
"if",
"!",
"v",
".",
"IsValid",
"(",
")",
"||",
"!",
"v",
".",
"CanInterface",
"(",
")",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"val",
":=",
"v",
".",
"Interface",
"(",
")",
"\n\n",
"if",
"marshaller",
",",
"ok",
":=",
"val",
".",
"(",
"Marshaller",
")",
";",
"ok",
"{",
"return",
"marshaller",
".",
"Marshal",
"(",
"options",
")",
"\n",
"}",
"\n",
"// types which are e.g. structs, slices or maps and implement one of the following interfaces should not be",
"// marshalled by sheriff because they'll be correctly marshalled by json.Marshal instead.",
"// Otherwise (e.g. net.IP) a byte slice may be output as a list of uints instead of as an IP string.",
"switch",
"val",
".",
"(",
"type",
")",
"{",
"case",
"json",
".",
"Marshaler",
",",
"encoding",
".",
"TextMarshaler",
",",
"fmt",
".",
"Stringer",
":",
"return",
"val",
",",
"nil",
"\n",
"}",
"\n",
"k",
":=",
"v",
".",
"Kind",
"(",
")",
"\n\n",
"if",
"k",
"==",
"reflect",
".",
"Ptr",
"{",
"v",
"=",
"v",
".",
"Elem",
"(",
")",
"\n",
"val",
"=",
"v",
".",
"Interface",
"(",
")",
"\n",
"k",
"=",
"v",
".",
"Kind",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"k",
"==",
"reflect",
".",
"Interface",
"||",
"k",
"==",
"reflect",
".",
"Struct",
"{",
"return",
"Marshal",
"(",
"options",
",",
"val",
")",
"\n",
"}",
"\n",
"if",
"k",
"==",
"reflect",
".",
"Slice",
"{",
"l",
":=",
"v",
".",
"Len",
"(",
")",
"\n",
"dest",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"l",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"l",
";",
"i",
"++",
"{",
"d",
",",
"err",
":=",
"marshalValue",
"(",
"options",
",",
"v",
".",
"Index",
"(",
"i",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"dest",
"[",
"i",
"]",
"=",
"d",
"\n",
"}",
"\n",
"return",
"dest",
",",
"nil",
"\n",
"}",
"\n",
"if",
"k",
"==",
"reflect",
".",
"Map",
"{",
"mapKeys",
":=",
"v",
".",
"MapKeys",
"(",
")",
"\n",
"if",
"len",
"(",
"mapKeys",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"if",
"mapKeys",
"[",
"0",
"]",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"String",
"{",
"return",
"nil",
",",
"MarshalInvalidTypeError",
"{",
"t",
":",
"mapKeys",
"[",
"0",
"]",
".",
"Kind",
"(",
")",
",",
"data",
":",
"val",
"}",
"\n",
"}",
"\n",
"dest",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"mapKeys",
"{",
"d",
",",
"err",
":=",
"marshalValue",
"(",
"options",
",",
"v",
".",
"MapIndex",
"(",
"key",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"dest",
"[",
"key",
".",
"Interface",
"(",
")",
".",
"(",
"string",
")",
"]",
"=",
"d",
"\n",
"}",
"\n",
"return",
"dest",
",",
"nil",
"\n",
"}",
"\n",
"return",
"val",
",",
"nil",
"\n",
"}"
] |
// marshalValue is being used for getting the actual value of a field.
//
// There is support for types implementing the Marshaller interface, arbitrary structs, slices, maps and base types.
|
[
"marshalValue",
"is",
"being",
"used",
"for",
"getting",
"the",
"actual",
"value",
"of",
"a",
"field",
".",
"There",
"is",
"support",
"for",
"types",
"implementing",
"the",
"Marshaller",
"interface",
"arbitrary",
"structs",
"slices",
"maps",
"and",
"base",
"types",
"."
] |
91aa83a45a3d4550ade9b3f6ee70f10dc4e984ef
|
https://github.com/liip/sheriff/blob/91aa83a45a3d4550ade9b3f6ee70f10dc4e984ef/sheriff.go#L181-L240
|
11,847 |
liip/sheriff
|
sheriff.go
|
contains
|
func contains(key string, list []string) bool {
for _, innerKey := range list {
if key == innerKey {
return true
}
}
return false
}
|
go
|
func contains(key string, list []string) bool {
for _, innerKey := range list {
if key == innerKey {
return true
}
}
return false
}
|
[
"func",
"contains",
"(",
"key",
"string",
",",
"list",
"[",
"]",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"innerKey",
":=",
"range",
"list",
"{",
"if",
"key",
"==",
"innerKey",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// contains check if a given key is contained in a slice of strings.
|
[
"contains",
"check",
"if",
"a",
"given",
"key",
"is",
"contained",
"in",
"a",
"slice",
"of",
"strings",
"."
] |
91aa83a45a3d4550ade9b3f6ee70f10dc4e984ef
|
https://github.com/liip/sheriff/blob/91aa83a45a3d4550ade9b3f6ee70f10dc4e984ef/sheriff.go#L243-L250
|
11,848 |
liip/sheriff
|
sheriff.go
|
listContains
|
func listContains(a []string, b []string) bool {
for _, key := range a {
if contains(key, b) {
return true
}
}
return false
}
|
go
|
func listContains(a []string, b []string) bool {
for _, key := range a {
if contains(key, b) {
return true
}
}
return false
}
|
[
"func",
"listContains",
"(",
"a",
"[",
"]",
"string",
",",
"b",
"[",
"]",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"key",
":=",
"range",
"a",
"{",
"if",
"contains",
"(",
"key",
",",
"b",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// listContains operates on two string slices and checks if one of the strings in `a`
// is contained in `b`.
|
[
"listContains",
"operates",
"on",
"two",
"string",
"slices",
"and",
"checks",
"if",
"one",
"of",
"the",
"strings",
"in",
"a",
"is",
"contained",
"in",
"b",
"."
] |
91aa83a45a3d4550ade9b3f6ee70f10dc4e984ef
|
https://github.com/liip/sheriff/blob/91aa83a45a3d4550ade9b3f6ee70f10dc4e984ef/sheriff.go#L254-L261
|
11,849 |
ybbus/jsonrpc
|
jsonrpc.go
|
Error
|
func (e *RPCError) Error() string {
return strconv.Itoa(e.Code) + ":" + e.Message
}
|
go
|
func (e *RPCError) Error() string {
return strconv.Itoa(e.Code) + ":" + e.Message
}
|
[
"func",
"(",
"e",
"*",
"RPCError",
")",
"Error",
"(",
")",
"string",
"{",
"return",
"strconv",
".",
"Itoa",
"(",
"e",
".",
"Code",
")",
"+",
"\"",
"\"",
"+",
"e",
".",
"Message",
"\n",
"}"
] |
// Error function is provided to be used as error object.
|
[
"Error",
"function",
"is",
"provided",
"to",
"be",
"used",
"as",
"error",
"object",
"."
] |
94088458a1e880219bd312fc0ccb8548993ebf80
|
https://github.com/ybbus/jsonrpc/blob/94088458a1e880219bd312fc0ccb8548993ebf80/jsonrpc.go#L207-L209
|
11,850 |
ybbus/jsonrpc
|
jsonrpc.go
|
AsMap
|
func (res RPCResponses) AsMap() map[int]*RPCResponse {
resMap := make(map[int]*RPCResponse, 0)
for _, r := range res {
resMap[r.ID] = r
}
return resMap
}
|
go
|
func (res RPCResponses) AsMap() map[int]*RPCResponse {
resMap := make(map[int]*RPCResponse, 0)
for _, r := range res {
resMap[r.ID] = r
}
return resMap
}
|
[
"func",
"(",
"res",
"RPCResponses",
")",
"AsMap",
"(",
")",
"map",
"[",
"int",
"]",
"*",
"RPCResponse",
"{",
"resMap",
":=",
"make",
"(",
"map",
"[",
"int",
"]",
"*",
"RPCResponse",
",",
"0",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"res",
"{",
"resMap",
"[",
"r",
".",
"ID",
"]",
"=",
"r",
"\n",
"}",
"\n\n",
"return",
"resMap",
"\n",
"}"
] |
// AsMap returns the responses as map with response id as key.
|
[
"AsMap",
"returns",
"the",
"responses",
"as",
"map",
"with",
"response",
"id",
"as",
"key",
"."
] |
94088458a1e880219bd312fc0ccb8548993ebf80
|
https://github.com/ybbus/jsonrpc/blob/94088458a1e880219bd312fc0ccb8548993ebf80/jsonrpc.go#L248-L255
|
11,851 |
ybbus/jsonrpc
|
jsonrpc.go
|
GetByID
|
func (res RPCResponses) GetByID(id int) *RPCResponse {
for _, r := range res {
if r.ID == id {
return r
}
}
return nil
}
|
go
|
func (res RPCResponses) GetByID(id int) *RPCResponse {
for _, r := range res {
if r.ID == id {
return r
}
}
return nil
}
|
[
"func",
"(",
"res",
"RPCResponses",
")",
"GetByID",
"(",
"id",
"int",
")",
"*",
"RPCResponse",
"{",
"for",
"_",
",",
"r",
":=",
"range",
"res",
"{",
"if",
"r",
".",
"ID",
"==",
"id",
"{",
"return",
"r",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// GetByID returns the response object of the given id, nil if it does not exist.
|
[
"GetByID",
"returns",
"the",
"response",
"object",
"of",
"the",
"given",
"id",
"nil",
"if",
"it",
"does",
"not",
"exist",
"."
] |
94088458a1e880219bd312fc0ccb8548993ebf80
|
https://github.com/ybbus/jsonrpc/blob/94088458a1e880219bd312fc0ccb8548993ebf80/jsonrpc.go#L258-L266
|
11,852 |
ybbus/jsonrpc
|
jsonrpc.go
|
HasError
|
func (res RPCResponses) HasError() bool {
for _, res := range res {
if res.Error != nil {
return true
}
}
return false
}
|
go
|
func (res RPCResponses) HasError() bool {
for _, res := range res {
if res.Error != nil {
return true
}
}
return false
}
|
[
"func",
"(",
"res",
"RPCResponses",
")",
"HasError",
"(",
")",
"bool",
"{",
"for",
"_",
",",
"res",
":=",
"range",
"res",
"{",
"if",
"res",
".",
"Error",
"!=",
"nil",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// HasError returns true if one of the response objects has Error field != nil
|
[
"HasError",
"returns",
"true",
"if",
"one",
"of",
"the",
"response",
"objects",
"has",
"Error",
"field",
"!",
"=",
"nil"
] |
94088458a1e880219bd312fc0ccb8548993ebf80
|
https://github.com/ybbus/jsonrpc/blob/94088458a1e880219bd312fc0ccb8548993ebf80/jsonrpc.go#L269-L276
|
11,853 |
ybbus/jsonrpc
|
jsonrpc.go
|
GetInt
|
func (RPCResponse *RPCResponse) GetInt() (int64, error) {
val, ok := RPCResponse.Result.(json.Number)
if !ok {
return 0, fmt.Errorf("could not parse int64 from %s", RPCResponse.Result)
}
i, err := val.Int64()
if err != nil {
return 0, err
}
return i, nil
}
|
go
|
func (RPCResponse *RPCResponse) GetInt() (int64, error) {
val, ok := RPCResponse.Result.(json.Number)
if !ok {
return 0, fmt.Errorf("could not parse int64 from %s", RPCResponse.Result)
}
i, err := val.Int64()
if err != nil {
return 0, err
}
return i, nil
}
|
[
"func",
"(",
"RPCResponse",
"*",
"RPCResponse",
")",
"GetInt",
"(",
")",
"(",
"int64",
",",
"error",
")",
"{",
"val",
",",
"ok",
":=",
"RPCResponse",
".",
"Result",
".",
"(",
"json",
".",
"Number",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"RPCResponse",
".",
"Result",
")",
"\n",
"}",
"\n\n",
"i",
",",
"err",
":=",
"val",
".",
"Int64",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"i",
",",
"nil",
"\n",
"}"
] |
// GetInt converts the rpc response to an int64 and returns it.
//
// If result was not an integer an error is returned.
|
[
"GetInt",
"converts",
"the",
"rpc",
"response",
"to",
"an",
"int64",
"and",
"returns",
"it",
".",
"If",
"result",
"was",
"not",
"an",
"integer",
"an",
"error",
"is",
"returned",
"."
] |
94088458a1e880219bd312fc0ccb8548993ebf80
|
https://github.com/ybbus/jsonrpc/blob/94088458a1e880219bd312fc0ccb8548993ebf80/jsonrpc.go#L550-L562
|
11,854 |
ybbus/jsonrpc
|
jsonrpc.go
|
GetFloat
|
func (RPCResponse *RPCResponse) GetFloat() (float64, error) {
val, ok := RPCResponse.Result.(json.Number)
if !ok {
return 0, fmt.Errorf("could not parse float64 from %s", RPCResponse.Result)
}
f, err := val.Float64()
if err != nil {
return 0, err
}
return f, nil
}
|
go
|
func (RPCResponse *RPCResponse) GetFloat() (float64, error) {
val, ok := RPCResponse.Result.(json.Number)
if !ok {
return 0, fmt.Errorf("could not parse float64 from %s", RPCResponse.Result)
}
f, err := val.Float64()
if err != nil {
return 0, err
}
return f, nil
}
|
[
"func",
"(",
"RPCResponse",
"*",
"RPCResponse",
")",
"GetFloat",
"(",
")",
"(",
"float64",
",",
"error",
")",
"{",
"val",
",",
"ok",
":=",
"RPCResponse",
".",
"Result",
".",
"(",
"json",
".",
"Number",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"RPCResponse",
".",
"Result",
")",
"\n",
"}",
"\n\n",
"f",
",",
"err",
":=",
"val",
".",
"Float64",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"f",
",",
"nil",
"\n",
"}"
] |
// GetFloat converts the rpc response to float64 and returns it.
//
// If result was not an float64 an error is returned.
|
[
"GetFloat",
"converts",
"the",
"rpc",
"response",
"to",
"float64",
"and",
"returns",
"it",
".",
"If",
"result",
"was",
"not",
"an",
"float64",
"an",
"error",
"is",
"returned",
"."
] |
94088458a1e880219bd312fc0ccb8548993ebf80
|
https://github.com/ybbus/jsonrpc/blob/94088458a1e880219bd312fc0ccb8548993ebf80/jsonrpc.go#L567-L579
|
11,855 |
ybbus/jsonrpc
|
jsonrpc.go
|
GetBool
|
func (RPCResponse *RPCResponse) GetBool() (bool, error) {
val, ok := RPCResponse.Result.(bool)
if !ok {
return false, fmt.Errorf("could not parse bool from %s", RPCResponse.Result)
}
return val, nil
}
|
go
|
func (RPCResponse *RPCResponse) GetBool() (bool, error) {
val, ok := RPCResponse.Result.(bool)
if !ok {
return false, fmt.Errorf("could not parse bool from %s", RPCResponse.Result)
}
return val, nil
}
|
[
"func",
"(",
"RPCResponse",
"*",
"RPCResponse",
")",
"GetBool",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"val",
",",
"ok",
":=",
"RPCResponse",
".",
"Result",
".",
"(",
"bool",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"RPCResponse",
".",
"Result",
")",
"\n",
"}",
"\n\n",
"return",
"val",
",",
"nil",
"\n",
"}"
] |
// GetBool converts the rpc response to a bool and returns it.
//
// If result was not a bool an error is returned.
|
[
"GetBool",
"converts",
"the",
"rpc",
"response",
"to",
"a",
"bool",
"and",
"returns",
"it",
".",
"If",
"result",
"was",
"not",
"a",
"bool",
"an",
"error",
"is",
"returned",
"."
] |
94088458a1e880219bd312fc0ccb8548993ebf80
|
https://github.com/ybbus/jsonrpc/blob/94088458a1e880219bd312fc0ccb8548993ebf80/jsonrpc.go#L584-L591
|
11,856 |
ybbus/jsonrpc
|
jsonrpc.go
|
GetString
|
func (RPCResponse *RPCResponse) GetString() (string, error) {
val, ok := RPCResponse.Result.(string)
if !ok {
return "", fmt.Errorf("could not parse string from %s", RPCResponse.Result)
}
return val, nil
}
|
go
|
func (RPCResponse *RPCResponse) GetString() (string, error) {
val, ok := RPCResponse.Result.(string)
if !ok {
return "", fmt.Errorf("could not parse string from %s", RPCResponse.Result)
}
return val, nil
}
|
[
"func",
"(",
"RPCResponse",
"*",
"RPCResponse",
")",
"GetString",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"val",
",",
"ok",
":=",
"RPCResponse",
".",
"Result",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"RPCResponse",
".",
"Result",
")",
"\n",
"}",
"\n\n",
"return",
"val",
",",
"nil",
"\n",
"}"
] |
// GetString converts the rpc response to a string and returns it.
//
// If result was not a string an error is returned.
|
[
"GetString",
"converts",
"the",
"rpc",
"response",
"to",
"a",
"string",
"and",
"returns",
"it",
".",
"If",
"result",
"was",
"not",
"a",
"string",
"an",
"error",
"is",
"returned",
"."
] |
94088458a1e880219bd312fc0ccb8548993ebf80
|
https://github.com/ybbus/jsonrpc/blob/94088458a1e880219bd312fc0ccb8548993ebf80/jsonrpc.go#L596-L603
|
11,857 |
lightningnetwork/lightning-onion
|
batch.go
|
NewBatch
|
func NewBatch(id []byte) *Batch {
return &Batch{
ID: id,
ReplaySet: NewReplaySet(),
entries: make(map[uint16]batchEntry),
replayCache: make(map[HashPrefix]struct{}),
}
}
|
go
|
func NewBatch(id []byte) *Batch {
return &Batch{
ID: id,
ReplaySet: NewReplaySet(),
entries: make(map[uint16]batchEntry),
replayCache: make(map[HashPrefix]struct{}),
}
}
|
[
"func",
"NewBatch",
"(",
"id",
"[",
"]",
"byte",
")",
"*",
"Batch",
"{",
"return",
"&",
"Batch",
"{",
"ID",
":",
"id",
",",
"ReplaySet",
":",
"NewReplaySet",
"(",
")",
",",
"entries",
":",
"make",
"(",
"map",
"[",
"uint16",
"]",
"batchEntry",
")",
",",
"replayCache",
":",
"make",
"(",
"map",
"[",
"HashPrefix",
"]",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"}"
] |
// NewBatch initializes an object for constructing a set of entries to
// atomically add to a replay log. Batches are identified by byte slice, which
// allows the caller to safely process the same batch twice and get an
// idempotent result.
|
[
"NewBatch",
"initializes",
"an",
"object",
"for",
"constructing",
"a",
"set",
"of",
"entries",
"to",
"atomically",
"add",
"to",
"a",
"replay",
"log",
".",
"Batches",
"are",
"identified",
"by",
"byte",
"slice",
"which",
"allows",
"the",
"caller",
"to",
"safely",
"process",
"the",
"same",
"batch",
"twice",
"and",
"get",
"an",
"idempotent",
"result",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/batch.go#L41-L48
|
11,858 |
lightningnetwork/lightning-onion
|
batch.go
|
ForEach
|
func (b *Batch) ForEach(fn func(seqNum uint16, hashPrefix *HashPrefix, cltv uint32) error) error {
for seqNum, entry := range b.entries {
if err := fn(seqNum, &entry.hashPrefix, entry.cltv); err != nil {
return err
}
}
return nil
}
|
go
|
func (b *Batch) ForEach(fn func(seqNum uint16, hashPrefix *HashPrefix, cltv uint32) error) error {
for seqNum, entry := range b.entries {
if err := fn(seqNum, &entry.hashPrefix, entry.cltv); err != nil {
return err
}
}
return nil
}
|
[
"func",
"(",
"b",
"*",
"Batch",
")",
"ForEach",
"(",
"fn",
"func",
"(",
"seqNum",
"uint16",
",",
"hashPrefix",
"*",
"HashPrefix",
",",
"cltv",
"uint32",
")",
"error",
")",
"error",
"{",
"for",
"seqNum",
",",
"entry",
":=",
"range",
"b",
".",
"entries",
"{",
"if",
"err",
":=",
"fn",
"(",
"seqNum",
",",
"&",
"entry",
".",
"hashPrefix",
",",
"entry",
".",
"cltv",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ForEach iterates through each entry in the batch and calls the provided
// function with the sequence number and entry contents as arguments.
|
[
"ForEach",
"iterates",
"through",
"each",
"entry",
"in",
"the",
"batch",
"and",
"calls",
"the",
"provided",
"function",
"with",
"the",
"sequence",
"number",
"and",
"entry",
"contents",
"as",
"arguments",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/batch.go#L86-L93
|
11,859 |
lightningnetwork/lightning-onion
|
replaylog.go
|
hashSharedSecret
|
func hashSharedSecret(sharedSecret *Hash256) *HashPrefix {
// Sha256 hash of sharedSecret
h := sha256.New()
h.Write(sharedSecret[:])
var sharedHash HashPrefix
// Copy bytes to sharedHash
copy(sharedHash[:], h.Sum(nil))
return &sharedHash
}
|
go
|
func hashSharedSecret(sharedSecret *Hash256) *HashPrefix {
// Sha256 hash of sharedSecret
h := sha256.New()
h.Write(sharedSecret[:])
var sharedHash HashPrefix
// Copy bytes to sharedHash
copy(sharedHash[:], h.Sum(nil))
return &sharedHash
}
|
[
"func",
"hashSharedSecret",
"(",
"sharedSecret",
"*",
"Hash256",
")",
"*",
"HashPrefix",
"{",
"// Sha256 hash of sharedSecret",
"h",
":=",
"sha256",
".",
"New",
"(",
")",
"\n",
"h",
".",
"Write",
"(",
"sharedSecret",
"[",
":",
"]",
")",
"\n\n",
"var",
"sharedHash",
"HashPrefix",
"\n\n",
"// Copy bytes to sharedHash",
"copy",
"(",
"sharedHash",
"[",
":",
"]",
",",
"h",
".",
"Sum",
"(",
"nil",
")",
")",
"\n",
"return",
"&",
"sharedHash",
"\n",
"}"
] |
// hashSharedSecret Sha-256 hashes the shared secret and returns the first
// HashPrefixSize bytes of the hash.
|
[
"hashSharedSecret",
"Sha",
"-",
"256",
"hashes",
"the",
"shared",
"secret",
"and",
"returns",
"the",
"first",
"HashPrefixSize",
"bytes",
"of",
"the",
"hash",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/replaylog.go#L31-L41
|
11,860 |
lightningnetwork/lightning-onion
|
replaylog.go
|
Start
|
func (rl *MemoryReplayLog) Start() error {
rl.batches = make(map[string]*ReplaySet)
rl.entries = make(map[HashPrefix]uint32)
return nil
}
|
go
|
func (rl *MemoryReplayLog) Start() error {
rl.batches = make(map[string]*ReplaySet)
rl.entries = make(map[HashPrefix]uint32)
return nil
}
|
[
"func",
"(",
"rl",
"*",
"MemoryReplayLog",
")",
"Start",
"(",
")",
"error",
"{",
"rl",
".",
"batches",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"ReplaySet",
")",
"\n",
"rl",
".",
"entries",
"=",
"make",
"(",
"map",
"[",
"HashPrefix",
"]",
"uint32",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Start initializes the log and must be called before any other methods.
|
[
"Start",
"initializes",
"the",
"log",
"and",
"must",
"be",
"called",
"before",
"any",
"other",
"methods",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/replaylog.go#L88-L92
|
11,861 |
lightningnetwork/lightning-onion
|
replaylog.go
|
Stop
|
func (rl *MemoryReplayLog) Stop() error {
if rl.entries == nil || rl.batches == nil {
return errReplayLogNotStarted
}
rl.batches = nil
rl.entries = nil
return nil
}
|
go
|
func (rl *MemoryReplayLog) Stop() error {
if rl.entries == nil || rl.batches == nil {
return errReplayLogNotStarted
}
rl.batches = nil
rl.entries = nil
return nil
}
|
[
"func",
"(",
"rl",
"*",
"MemoryReplayLog",
")",
"Stop",
"(",
")",
"error",
"{",
"if",
"rl",
".",
"entries",
"==",
"nil",
"||",
"rl",
".",
"batches",
"==",
"nil",
"{",
"return",
"errReplayLogNotStarted",
"\n",
"}",
"\n\n",
"rl",
".",
"batches",
"=",
"nil",
"\n",
"rl",
".",
"entries",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Stop wipes the state of the log.
|
[
"Stop",
"wipes",
"the",
"state",
"of",
"the",
"log",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/replaylog.go#L95-L103
|
11,862 |
lightningnetwork/lightning-onion
|
replaylog.go
|
Get
|
func (rl *MemoryReplayLog) Get(hash *HashPrefix) (uint32, error) {
if rl.entries == nil || rl.batches == nil {
return 0, errReplayLogNotStarted
}
cltv, exists := rl.entries[*hash]
if !exists {
return 0, ErrLogEntryNotFound
}
return cltv, nil
}
|
go
|
func (rl *MemoryReplayLog) Get(hash *HashPrefix) (uint32, error) {
if rl.entries == nil || rl.batches == nil {
return 0, errReplayLogNotStarted
}
cltv, exists := rl.entries[*hash]
if !exists {
return 0, ErrLogEntryNotFound
}
return cltv, nil
}
|
[
"func",
"(",
"rl",
"*",
"MemoryReplayLog",
")",
"Get",
"(",
"hash",
"*",
"HashPrefix",
")",
"(",
"uint32",
",",
"error",
")",
"{",
"if",
"rl",
".",
"entries",
"==",
"nil",
"||",
"rl",
".",
"batches",
"==",
"nil",
"{",
"return",
"0",
",",
"errReplayLogNotStarted",
"\n",
"}",
"\n\n",
"cltv",
",",
"exists",
":=",
"rl",
".",
"entries",
"[",
"*",
"hash",
"]",
"\n",
"if",
"!",
"exists",
"{",
"return",
"0",
",",
"ErrLogEntryNotFound",
"\n",
"}",
"\n\n",
"return",
"cltv",
",",
"nil",
"\n",
"}"
] |
// Get retrieves an entry from the log given its hash prefix. It returns the
// value stored and an error if one occurs. It returns ErrLogEntryNotFound
// if the entry is not in the log.
|
[
"Get",
"retrieves",
"an",
"entry",
"from",
"the",
"log",
"given",
"its",
"hash",
"prefix",
".",
"It",
"returns",
"the",
"value",
"stored",
"and",
"an",
"error",
"if",
"one",
"occurs",
".",
"It",
"returns",
"ErrLogEntryNotFound",
"if",
"the",
"entry",
"is",
"not",
"in",
"the",
"log",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/replaylog.go#L108-L119
|
11,863 |
lightningnetwork/lightning-onion
|
replaylog.go
|
Put
|
func (rl *MemoryReplayLog) Put(hash *HashPrefix, cltv uint32) error {
if rl.entries == nil || rl.batches == nil {
return errReplayLogNotStarted
}
_, exists := rl.entries[*hash]
if exists {
return ErrReplayedPacket
}
rl.entries[*hash] = cltv
return nil
}
|
go
|
func (rl *MemoryReplayLog) Put(hash *HashPrefix, cltv uint32) error {
if rl.entries == nil || rl.batches == nil {
return errReplayLogNotStarted
}
_, exists := rl.entries[*hash]
if exists {
return ErrReplayedPacket
}
rl.entries[*hash] = cltv
return nil
}
|
[
"func",
"(",
"rl",
"*",
"MemoryReplayLog",
")",
"Put",
"(",
"hash",
"*",
"HashPrefix",
",",
"cltv",
"uint32",
")",
"error",
"{",
"if",
"rl",
".",
"entries",
"==",
"nil",
"||",
"rl",
".",
"batches",
"==",
"nil",
"{",
"return",
"errReplayLogNotStarted",
"\n",
"}",
"\n\n",
"_",
",",
"exists",
":=",
"rl",
".",
"entries",
"[",
"*",
"hash",
"]",
"\n",
"if",
"exists",
"{",
"return",
"ErrReplayedPacket",
"\n",
"}",
"\n\n",
"rl",
".",
"entries",
"[",
"*",
"hash",
"]",
"=",
"cltv",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Put stores an entry into the log given its hash prefix and an accompanying
// purposefully general type. It returns ErrReplayedPacket if the provided hash
// prefix already exists in the log.
|
[
"Put",
"stores",
"an",
"entry",
"into",
"the",
"log",
"given",
"its",
"hash",
"prefix",
"and",
"an",
"accompanying",
"purposefully",
"general",
"type",
".",
"It",
"returns",
"ErrReplayedPacket",
"if",
"the",
"provided",
"hash",
"prefix",
"already",
"exists",
"in",
"the",
"log",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/replaylog.go#L124-L136
|
11,864 |
lightningnetwork/lightning-onion
|
replaylog.go
|
Delete
|
func (rl *MemoryReplayLog) Delete(hash *HashPrefix) error {
if rl.entries == nil || rl.batches == nil {
return errReplayLogNotStarted
}
delete(rl.entries, *hash)
return nil
}
|
go
|
func (rl *MemoryReplayLog) Delete(hash *HashPrefix) error {
if rl.entries == nil || rl.batches == nil {
return errReplayLogNotStarted
}
delete(rl.entries, *hash)
return nil
}
|
[
"func",
"(",
"rl",
"*",
"MemoryReplayLog",
")",
"Delete",
"(",
"hash",
"*",
"HashPrefix",
")",
"error",
"{",
"if",
"rl",
".",
"entries",
"==",
"nil",
"||",
"rl",
".",
"batches",
"==",
"nil",
"{",
"return",
"errReplayLogNotStarted",
"\n",
"}",
"\n\n",
"delete",
"(",
"rl",
".",
"entries",
",",
"*",
"hash",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Delete deletes an entry from the log given its hash prefix.
|
[
"Delete",
"deletes",
"an",
"entry",
"from",
"the",
"log",
"given",
"its",
"hash",
"prefix",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/replaylog.go#L139-L146
|
11,865 |
lightningnetwork/lightning-onion
|
replaylog.go
|
PutBatch
|
func (rl *MemoryReplayLog) PutBatch(batch *Batch) (*ReplaySet, error) {
if rl.entries == nil || rl.batches == nil {
return nil, errReplayLogNotStarted
}
// Return the result when the batch was first processed to provide
// idempotence.
replays, exists := rl.batches[string(batch.ID)]
if !exists {
replays = NewReplaySet()
err := batch.ForEach(func(seqNum uint16, hashPrefix *HashPrefix, cltv uint32) error {
err := rl.Put(hashPrefix, cltv)
if err == ErrReplayedPacket {
replays.Add(seqNum)
return nil
}
// An error would be bad because we have already updated the entries
// map, but no errors other than ErrReplayedPacket should occur.
return err
})
if err != nil {
return nil, err
}
replays.Merge(batch.ReplaySet)
rl.batches[string(batch.ID)] = replays
}
batch.ReplaySet = replays
batch.IsCommitted = true
return replays, nil
}
|
go
|
func (rl *MemoryReplayLog) PutBatch(batch *Batch) (*ReplaySet, error) {
if rl.entries == nil || rl.batches == nil {
return nil, errReplayLogNotStarted
}
// Return the result when the batch was first processed to provide
// idempotence.
replays, exists := rl.batches[string(batch.ID)]
if !exists {
replays = NewReplaySet()
err := batch.ForEach(func(seqNum uint16, hashPrefix *HashPrefix, cltv uint32) error {
err := rl.Put(hashPrefix, cltv)
if err == ErrReplayedPacket {
replays.Add(seqNum)
return nil
}
// An error would be bad because we have already updated the entries
// map, but no errors other than ErrReplayedPacket should occur.
return err
})
if err != nil {
return nil, err
}
replays.Merge(batch.ReplaySet)
rl.batches[string(batch.ID)] = replays
}
batch.ReplaySet = replays
batch.IsCommitted = true
return replays, nil
}
|
[
"func",
"(",
"rl",
"*",
"MemoryReplayLog",
")",
"PutBatch",
"(",
"batch",
"*",
"Batch",
")",
"(",
"*",
"ReplaySet",
",",
"error",
")",
"{",
"if",
"rl",
".",
"entries",
"==",
"nil",
"||",
"rl",
".",
"batches",
"==",
"nil",
"{",
"return",
"nil",
",",
"errReplayLogNotStarted",
"\n",
"}",
"\n\n",
"// Return the result when the batch was first processed to provide",
"// idempotence.",
"replays",
",",
"exists",
":=",
"rl",
".",
"batches",
"[",
"string",
"(",
"batch",
".",
"ID",
")",
"]",
"\n\n",
"if",
"!",
"exists",
"{",
"replays",
"=",
"NewReplaySet",
"(",
")",
"\n",
"err",
":=",
"batch",
".",
"ForEach",
"(",
"func",
"(",
"seqNum",
"uint16",
",",
"hashPrefix",
"*",
"HashPrefix",
",",
"cltv",
"uint32",
")",
"error",
"{",
"err",
":=",
"rl",
".",
"Put",
"(",
"hashPrefix",
",",
"cltv",
")",
"\n",
"if",
"err",
"==",
"ErrReplayedPacket",
"{",
"replays",
".",
"Add",
"(",
"seqNum",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// An error would be bad because we have already updated the entries",
"// map, but no errors other than ErrReplayedPacket should occur.",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"replays",
".",
"Merge",
"(",
"batch",
".",
"ReplaySet",
")",
"\n",
"rl",
".",
"batches",
"[",
"string",
"(",
"batch",
".",
"ID",
")",
"]",
"=",
"replays",
"\n",
"}",
"\n\n",
"batch",
".",
"ReplaySet",
"=",
"replays",
"\n",
"batch",
".",
"IsCommitted",
"=",
"true",
"\n\n",
"return",
"replays",
",",
"nil",
"\n",
"}"
] |
// PutBatch stores a batch of sphinx packets into the log given their hash
// prefixes and accompanying values. Returns the set of entries in the batch
// that are replays and an error if one occurs.
|
[
"PutBatch",
"stores",
"a",
"batch",
"of",
"sphinx",
"packets",
"into",
"the",
"log",
"given",
"their",
"hash",
"prefixes",
"and",
"accompanying",
"values",
".",
"Returns",
"the",
"set",
"of",
"entries",
"in",
"the",
"batch",
"that",
"are",
"replays",
"and",
"an",
"error",
"if",
"one",
"occurs",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/replaylog.go#L151-L185
|
11,866 |
lightningnetwork/lightning-onion
|
cmd/main.go
|
main
|
func main() {
args := os.Args
assocData := bytes.Repeat([]byte{'B'}, 32)
if len(args) == 1 {
fmt.Printf("Usage: %s (generate|decode) <private-keys>\n", args[0])
} else if args[1] == "generate" {
var path sphinx.PaymentPath
for i, hexKey := range args[2:] {
binKey, err := hex.DecodeString(hexKey)
if err != nil || len(binKey) != 33 {
log.Fatalf("%s is not a valid hex pubkey %s", hexKey, err)
}
pubkey, err := btcec.ParsePubKey(binKey, btcec.S256())
if err != nil {
panic(err)
}
path[i] = sphinx.OnionHop{
NodePub: *pubkey,
HopData: sphinx.HopData{
Realm: [1]byte{0x00},
ForwardAmount: uint64(i),
OutgoingCltv: uint32(i),
},
}
copy(path[i].HopData.NextAddress[:], bytes.Repeat([]byte{byte(i)}, 8))
fmt.Fprintf(os.Stderr, "Node %d pubkey %x\n", i, pubkey.SerializeCompressed())
}
sessionKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), bytes.Repeat([]byte{'A'}, 32))
msg, err := sphinx.NewOnionPacket(&path, sessionKey, assocData)
if err != nil {
log.Fatalf("Error creating message: %v", err)
}
w := bytes.NewBuffer([]byte{})
err = msg.Encode(w)
if err != nil {
log.Fatalf("Error serializing message: %v", err)
}
fmt.Printf("%x\n", w.Bytes())
} else if args[1] == "decode" {
binKey, err := hex.DecodeString(args[2])
if len(binKey) != 32 || err != nil {
log.Fatalf("Argument not a valid hex private key")
}
hexBytes, _ := ioutil.ReadAll(os.Stdin)
binMsg, err := hex.DecodeString(strings.TrimSpace(string(hexBytes)))
if err != nil {
log.Fatalf("Error decoding message: %s", err)
}
privkey, _ := btcec.PrivKeyFromBytes(btcec.S256(), binKey)
s := sphinx.NewRouter(privkey, &chaincfg.TestNet3Params,
sphinx.NewMemoryReplayLog())
var packet sphinx.OnionPacket
err = packet.Decode(bytes.NewBuffer(binMsg))
if err != nil {
log.Fatalf("Error parsing message: %v", err)
}
p, err := s.ProcessOnionPacket(&packet, assocData, 10)
if err != nil {
log.Fatalf("Failed to decode message: %s", err)
}
w := bytes.NewBuffer([]byte{})
err = p.NextPacket.Encode(w)
if err != nil {
log.Fatalf("Error serializing message: %v", err)
}
fmt.Printf("%x\n", w.Bytes())
}
}
|
go
|
func main() {
args := os.Args
assocData := bytes.Repeat([]byte{'B'}, 32)
if len(args) == 1 {
fmt.Printf("Usage: %s (generate|decode) <private-keys>\n", args[0])
} else if args[1] == "generate" {
var path sphinx.PaymentPath
for i, hexKey := range args[2:] {
binKey, err := hex.DecodeString(hexKey)
if err != nil || len(binKey) != 33 {
log.Fatalf("%s is not a valid hex pubkey %s", hexKey, err)
}
pubkey, err := btcec.ParsePubKey(binKey, btcec.S256())
if err != nil {
panic(err)
}
path[i] = sphinx.OnionHop{
NodePub: *pubkey,
HopData: sphinx.HopData{
Realm: [1]byte{0x00},
ForwardAmount: uint64(i),
OutgoingCltv: uint32(i),
},
}
copy(path[i].HopData.NextAddress[:], bytes.Repeat([]byte{byte(i)}, 8))
fmt.Fprintf(os.Stderr, "Node %d pubkey %x\n", i, pubkey.SerializeCompressed())
}
sessionKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), bytes.Repeat([]byte{'A'}, 32))
msg, err := sphinx.NewOnionPacket(&path, sessionKey, assocData)
if err != nil {
log.Fatalf("Error creating message: %v", err)
}
w := bytes.NewBuffer([]byte{})
err = msg.Encode(w)
if err != nil {
log.Fatalf("Error serializing message: %v", err)
}
fmt.Printf("%x\n", w.Bytes())
} else if args[1] == "decode" {
binKey, err := hex.DecodeString(args[2])
if len(binKey) != 32 || err != nil {
log.Fatalf("Argument not a valid hex private key")
}
hexBytes, _ := ioutil.ReadAll(os.Stdin)
binMsg, err := hex.DecodeString(strings.TrimSpace(string(hexBytes)))
if err != nil {
log.Fatalf("Error decoding message: %s", err)
}
privkey, _ := btcec.PrivKeyFromBytes(btcec.S256(), binKey)
s := sphinx.NewRouter(privkey, &chaincfg.TestNet3Params,
sphinx.NewMemoryReplayLog())
var packet sphinx.OnionPacket
err = packet.Decode(bytes.NewBuffer(binMsg))
if err != nil {
log.Fatalf("Error parsing message: %v", err)
}
p, err := s.ProcessOnionPacket(&packet, assocData, 10)
if err != nil {
log.Fatalf("Failed to decode message: %s", err)
}
w := bytes.NewBuffer([]byte{})
err = p.NextPacket.Encode(w)
if err != nil {
log.Fatalf("Error serializing message: %v", err)
}
fmt.Printf("%x\n", w.Bytes())
}
}
|
[
"func",
"main",
"(",
")",
"{",
"args",
":=",
"os",
".",
"Args",
"\n\n",
"assocData",
":=",
"bytes",
".",
"Repeat",
"(",
"[",
"]",
"byte",
"{",
"'B'",
"}",
",",
"32",
")",
"\n\n",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"args",
"[",
"0",
"]",
")",
"\n",
"}",
"else",
"if",
"args",
"[",
"1",
"]",
"==",
"\"",
"\"",
"{",
"var",
"path",
"sphinx",
".",
"PaymentPath",
"\n",
"for",
"i",
",",
"hexKey",
":=",
"range",
"args",
"[",
"2",
":",
"]",
"{",
"binKey",
",",
"err",
":=",
"hex",
".",
"DecodeString",
"(",
"hexKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"len",
"(",
"binKey",
")",
"!=",
"33",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"hexKey",
",",
"err",
")",
"\n",
"}",
"\n\n",
"pubkey",
",",
"err",
":=",
"btcec",
".",
"ParsePubKey",
"(",
"binKey",
",",
"btcec",
".",
"S256",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"path",
"[",
"i",
"]",
"=",
"sphinx",
".",
"OnionHop",
"{",
"NodePub",
":",
"*",
"pubkey",
",",
"HopData",
":",
"sphinx",
".",
"HopData",
"{",
"Realm",
":",
"[",
"1",
"]",
"byte",
"{",
"0x00",
"}",
",",
"ForwardAmount",
":",
"uint64",
"(",
"i",
")",
",",
"OutgoingCltv",
":",
"uint32",
"(",
"i",
")",
",",
"}",
",",
"}",
"\n",
"copy",
"(",
"path",
"[",
"i",
"]",
".",
"HopData",
".",
"NextAddress",
"[",
":",
"]",
",",
"bytes",
".",
"Repeat",
"(",
"[",
"]",
"byte",
"{",
"byte",
"(",
"i",
")",
"}",
",",
"8",
")",
")",
"\n\n",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"i",
",",
"pubkey",
".",
"SerializeCompressed",
"(",
")",
")",
"\n",
"}",
"\n\n",
"sessionKey",
",",
"_",
":=",
"btcec",
".",
"PrivKeyFromBytes",
"(",
"btcec",
".",
"S256",
"(",
")",
",",
"bytes",
".",
"Repeat",
"(",
"[",
"]",
"byte",
"{",
"'A'",
"}",
",",
"32",
")",
")",
"\n\n",
"msg",
",",
"err",
":=",
"sphinx",
".",
"NewOnionPacket",
"(",
"&",
"path",
",",
"sessionKey",
",",
"assocData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"w",
":=",
"bytes",
".",
"NewBuffer",
"(",
"[",
"]",
"byte",
"{",
"}",
")",
"\n",
"err",
"=",
"msg",
".",
"Encode",
"(",
"w",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"w",
".",
"Bytes",
"(",
")",
")",
"\n",
"}",
"else",
"if",
"args",
"[",
"1",
"]",
"==",
"\"",
"\"",
"{",
"binKey",
",",
"err",
":=",
"hex",
".",
"DecodeString",
"(",
"args",
"[",
"2",
"]",
")",
"\n",
"if",
"len",
"(",
"binKey",
")",
"!=",
"32",
"||",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"hexBytes",
",",
"_",
":=",
"ioutil",
".",
"ReadAll",
"(",
"os",
".",
"Stdin",
")",
"\n",
"binMsg",
",",
"err",
":=",
"hex",
".",
"DecodeString",
"(",
"strings",
".",
"TrimSpace",
"(",
"string",
"(",
"hexBytes",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"privkey",
",",
"_",
":=",
"btcec",
".",
"PrivKeyFromBytes",
"(",
"btcec",
".",
"S256",
"(",
")",
",",
"binKey",
")",
"\n",
"s",
":=",
"sphinx",
".",
"NewRouter",
"(",
"privkey",
",",
"&",
"chaincfg",
".",
"TestNet3Params",
",",
"sphinx",
".",
"NewMemoryReplayLog",
"(",
")",
")",
"\n\n",
"var",
"packet",
"sphinx",
".",
"OnionPacket",
"\n",
"err",
"=",
"packet",
".",
"Decode",
"(",
"bytes",
".",
"NewBuffer",
"(",
"binMsg",
")",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"p",
",",
"err",
":=",
"s",
".",
"ProcessOnionPacket",
"(",
"&",
"packet",
",",
"assocData",
",",
"10",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"w",
":=",
"bytes",
".",
"NewBuffer",
"(",
"[",
"]",
"byte",
"{",
"}",
")",
"\n",
"err",
"=",
"p",
".",
"NextPacket",
".",
"Encode",
"(",
"w",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"w",
".",
"Bytes",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// main implements a simple command line utility that can be used in order to
// either generate a fresh mix-header or decode and fully process an existing
// one given a private key.
|
[
"main",
"implements",
"a",
"simple",
"command",
"line",
"utility",
"that",
"can",
"be",
"used",
"in",
"order",
"to",
"either",
"generate",
"a",
"fresh",
"mix",
"-",
"header",
"or",
"decode",
"and",
"fully",
"process",
"an",
"existing",
"one",
"given",
"a",
"private",
"key",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/cmd/main.go#L20-L103
|
11,867 |
lightningnetwork/lightning-onion
|
sphinx.go
|
Encode
|
func (hd *HopData) Encode(w io.Writer) error {
if _, err := w.Write(hd.Realm[:]); err != nil {
return err
}
if _, err := w.Write(hd.NextAddress[:]); err != nil {
return err
}
if err := binary.Write(w, binary.BigEndian, hd.ForwardAmount); err != nil {
return err
}
if err := binary.Write(w, binary.BigEndian, hd.OutgoingCltv); err != nil {
return err
}
if _, err := w.Write(hd.ExtraBytes[:]); err != nil {
return err
}
if _, err := w.Write(hd.HMAC[:]); err != nil {
return err
}
return nil
}
|
go
|
func (hd *HopData) Encode(w io.Writer) error {
if _, err := w.Write(hd.Realm[:]); err != nil {
return err
}
if _, err := w.Write(hd.NextAddress[:]); err != nil {
return err
}
if err := binary.Write(w, binary.BigEndian, hd.ForwardAmount); err != nil {
return err
}
if err := binary.Write(w, binary.BigEndian, hd.OutgoingCltv); err != nil {
return err
}
if _, err := w.Write(hd.ExtraBytes[:]); err != nil {
return err
}
if _, err := w.Write(hd.HMAC[:]); err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"hd",
"*",
"HopData",
")",
"Encode",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"hd",
".",
"Realm",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"hd",
".",
"NextAddress",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"binary",
".",
"Write",
"(",
"w",
",",
"binary",
".",
"BigEndian",
",",
"hd",
".",
"ForwardAmount",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"binary",
".",
"Write",
"(",
"w",
",",
"binary",
".",
"BigEndian",
",",
"hd",
".",
"OutgoingCltv",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"hd",
".",
"ExtraBytes",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"hd",
".",
"HMAC",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Encode writes the serialized version of the target HopData into the passed
// io.Writer.
|
[
"Encode",
"writes",
"the",
"serialized",
"version",
"of",
"the",
"target",
"HopData",
"into",
"the",
"passed",
"io",
".",
"Writer",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/sphinx.go#L147-L173
|
11,868 |
lightningnetwork/lightning-onion
|
sphinx.go
|
Decode
|
func (hd *HopData) Decode(r io.Reader) error {
if _, err := io.ReadFull(r, hd.Realm[:]); err != nil {
return err
}
if _, err := io.ReadFull(r, hd.NextAddress[:]); err != nil {
return err
}
if err := binary.Read(r, binary.BigEndian, &hd.ForwardAmount); err != nil {
return err
}
if err := binary.Read(r, binary.BigEndian, &hd.OutgoingCltv); err != nil {
return err
}
if _, err := io.ReadFull(r, hd.ExtraBytes[:]); err != nil {
return err
}
if _, err := io.ReadFull(r, hd.HMAC[:]); err != nil {
return err
}
return nil
}
|
go
|
func (hd *HopData) Decode(r io.Reader) error {
if _, err := io.ReadFull(r, hd.Realm[:]); err != nil {
return err
}
if _, err := io.ReadFull(r, hd.NextAddress[:]); err != nil {
return err
}
if err := binary.Read(r, binary.BigEndian, &hd.ForwardAmount); err != nil {
return err
}
if err := binary.Read(r, binary.BigEndian, &hd.OutgoingCltv); err != nil {
return err
}
if _, err := io.ReadFull(r, hd.ExtraBytes[:]); err != nil {
return err
}
if _, err := io.ReadFull(r, hd.HMAC[:]); err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"hd",
"*",
"HopData",
")",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"error",
"{",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"hd",
".",
"Realm",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"hd",
".",
"NextAddress",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"binary",
".",
"Read",
"(",
"r",
",",
"binary",
".",
"BigEndian",
",",
"&",
"hd",
".",
"ForwardAmount",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"binary",
".",
"Read",
"(",
"r",
",",
"binary",
".",
"BigEndian",
",",
"&",
"hd",
".",
"OutgoingCltv",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"hd",
".",
"ExtraBytes",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"hd",
".",
"HMAC",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Decode deserializes the encoded HopData contained int he passed io.Reader
// instance to the target empty HopData instance.
|
[
"Decode",
"deserializes",
"the",
"encoded",
"HopData",
"contained",
"int",
"he",
"passed",
"io",
".",
"Reader",
"instance",
"to",
"the",
"target",
"empty",
"HopData",
"instance",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/sphinx.go#L177-L203
|
11,869 |
lightningnetwork/lightning-onion
|
sphinx.go
|
generateSharedSecrets
|
func generateSharedSecrets(paymentPath []*btcec.PublicKey,
sessionKey *btcec.PrivateKey) []Hash256 {
// Each hop performs ECDH with our ephemeral key pair to arrive at a
// shared secret. Additionally, each hop randomizes the group element
// for the next hop by multiplying it by the blinding factor. This way
// we only need to transmit a single group element, and hops can't link
// a session back to us if they have several nodes in the path.
numHops := len(paymentPath)
hopSharedSecrets := make([]Hash256, numHops)
// Compute the triplet for the first hop outside of the main loop.
// Within the loop each new triplet will be computed recursively based
// off of the blinding factor of the last hop.
lastEphemeralPubKey := sessionKey.PubKey()
hopSharedSecrets[0] = generateSharedSecret(paymentPath[0], sessionKey)
lastBlindingFactor := computeBlindingFactor(lastEphemeralPubKey, hopSharedSecrets[0][:])
// The cached blinding factor will contain the running product of the
// session private key x and blinding factors b_i, computed as
// c_0 = x
// c_i = c_{i-1} * b_{i-1} (mod |F(G)|).
// = x * b_0 * b_1 * ... * b_{i-1} (mod |F(G)|).
//
// We begin with just the session private key x, so that base case
// c_0 = x. At the beginning of each iteration, the previous blinding
// factor is aggregated into the modular product, and used as the scalar
// value in deriving the hop ephemeral keys and shared secrets.
var cachedBlindingFactor big.Int
cachedBlindingFactor.SetBytes(sessionKey.D.Bytes())
// Now recursively compute the cached blinding factor, ephemeral ECDH
// pub keys, and shared secret for each hop.
var nextBlindingFactor big.Int
for i := 1; i <= numHops-1; i++ {
// Update the cached blinding factor with b_{i-1}.
nextBlindingFactor.SetBytes(lastBlindingFactor[:])
cachedBlindingFactor.Mul(&cachedBlindingFactor, &nextBlindingFactor)
cachedBlindingFactor.Mod(&cachedBlindingFactor, btcec.S256().Params().N)
// a_i = g ^ c_i
// = g^( x * b_0 * ... * b_{i-1} )
// = X^( b_0 * ... * b_{i-1} )
// X_our_session_pub_key x all prev blinding factors
lastEphemeralPubKey = blindBaseElement(cachedBlindingFactor.Bytes())
// e_i = Y_i ^ c_i
// = ( Y_i ^ x )^( b_0 * ... * b_{i-1} )
// (Y_their_pub_key x x_our_priv) x all prev blinding factors
hopBlindedPubKey := blindGroupElement(
paymentPath[i], cachedBlindingFactor.Bytes(),
)
// s_i = sha256( e_i )
// = sha256( Y_i ^ (x * b_0 * ... * b_{i-1} )
hopSharedSecrets[i] = sha256.Sum256(hopBlindedPubKey.SerializeCompressed())
// Only need to evaluate up to the penultimate blinding factor.
if i >= numHops-1 {
break
}
// b_i = sha256( a_i || s_i )
lastBlindingFactor = computeBlindingFactor(
lastEphemeralPubKey, hopSharedSecrets[i][:],
)
}
return hopSharedSecrets
}
|
go
|
func generateSharedSecrets(paymentPath []*btcec.PublicKey,
sessionKey *btcec.PrivateKey) []Hash256 {
// Each hop performs ECDH with our ephemeral key pair to arrive at a
// shared secret. Additionally, each hop randomizes the group element
// for the next hop by multiplying it by the blinding factor. This way
// we only need to transmit a single group element, and hops can't link
// a session back to us if they have several nodes in the path.
numHops := len(paymentPath)
hopSharedSecrets := make([]Hash256, numHops)
// Compute the triplet for the first hop outside of the main loop.
// Within the loop each new triplet will be computed recursively based
// off of the blinding factor of the last hop.
lastEphemeralPubKey := sessionKey.PubKey()
hopSharedSecrets[0] = generateSharedSecret(paymentPath[0], sessionKey)
lastBlindingFactor := computeBlindingFactor(lastEphemeralPubKey, hopSharedSecrets[0][:])
// The cached blinding factor will contain the running product of the
// session private key x and blinding factors b_i, computed as
// c_0 = x
// c_i = c_{i-1} * b_{i-1} (mod |F(G)|).
// = x * b_0 * b_1 * ... * b_{i-1} (mod |F(G)|).
//
// We begin with just the session private key x, so that base case
// c_0 = x. At the beginning of each iteration, the previous blinding
// factor is aggregated into the modular product, and used as the scalar
// value in deriving the hop ephemeral keys and shared secrets.
var cachedBlindingFactor big.Int
cachedBlindingFactor.SetBytes(sessionKey.D.Bytes())
// Now recursively compute the cached blinding factor, ephemeral ECDH
// pub keys, and shared secret for each hop.
var nextBlindingFactor big.Int
for i := 1; i <= numHops-1; i++ {
// Update the cached blinding factor with b_{i-1}.
nextBlindingFactor.SetBytes(lastBlindingFactor[:])
cachedBlindingFactor.Mul(&cachedBlindingFactor, &nextBlindingFactor)
cachedBlindingFactor.Mod(&cachedBlindingFactor, btcec.S256().Params().N)
// a_i = g ^ c_i
// = g^( x * b_0 * ... * b_{i-1} )
// = X^( b_0 * ... * b_{i-1} )
// X_our_session_pub_key x all prev blinding factors
lastEphemeralPubKey = blindBaseElement(cachedBlindingFactor.Bytes())
// e_i = Y_i ^ c_i
// = ( Y_i ^ x )^( b_0 * ... * b_{i-1} )
// (Y_their_pub_key x x_our_priv) x all prev blinding factors
hopBlindedPubKey := blindGroupElement(
paymentPath[i], cachedBlindingFactor.Bytes(),
)
// s_i = sha256( e_i )
// = sha256( Y_i ^ (x * b_0 * ... * b_{i-1} )
hopSharedSecrets[i] = sha256.Sum256(hopBlindedPubKey.SerializeCompressed())
// Only need to evaluate up to the penultimate blinding factor.
if i >= numHops-1 {
break
}
// b_i = sha256( a_i || s_i )
lastBlindingFactor = computeBlindingFactor(
lastEphemeralPubKey, hopSharedSecrets[i][:],
)
}
return hopSharedSecrets
}
|
[
"func",
"generateSharedSecrets",
"(",
"paymentPath",
"[",
"]",
"*",
"btcec",
".",
"PublicKey",
",",
"sessionKey",
"*",
"btcec",
".",
"PrivateKey",
")",
"[",
"]",
"Hash256",
"{",
"// Each hop performs ECDH with our ephemeral key pair to arrive at a",
"// shared secret. Additionally, each hop randomizes the group element",
"// for the next hop by multiplying it by the blinding factor. This way",
"// we only need to transmit a single group element, and hops can't link",
"// a session back to us if they have several nodes in the path.",
"numHops",
":=",
"len",
"(",
"paymentPath",
")",
"\n",
"hopSharedSecrets",
":=",
"make",
"(",
"[",
"]",
"Hash256",
",",
"numHops",
")",
"\n\n",
"// Compute the triplet for the first hop outside of the main loop.",
"// Within the loop each new triplet will be computed recursively based",
"// off of the blinding factor of the last hop.",
"lastEphemeralPubKey",
":=",
"sessionKey",
".",
"PubKey",
"(",
")",
"\n",
"hopSharedSecrets",
"[",
"0",
"]",
"=",
"generateSharedSecret",
"(",
"paymentPath",
"[",
"0",
"]",
",",
"sessionKey",
")",
"\n",
"lastBlindingFactor",
":=",
"computeBlindingFactor",
"(",
"lastEphemeralPubKey",
",",
"hopSharedSecrets",
"[",
"0",
"]",
"[",
":",
"]",
")",
"\n\n",
"// The cached blinding factor will contain the running product of the",
"// session private key x and blinding factors b_i, computed as",
"// c_0 = x",
"// c_i = c_{i-1} * b_{i-1} \t\t (mod |F(G)|).",
"// = x * b_0 * b_1 * ... * b_{i-1} (mod |F(G)|).",
"//",
"// We begin with just the session private key x, so that base case",
"// c_0 = x. At the beginning of each iteration, the previous blinding",
"// factor is aggregated into the modular product, and used as the scalar",
"// value in deriving the hop ephemeral keys and shared secrets.",
"var",
"cachedBlindingFactor",
"big",
".",
"Int",
"\n",
"cachedBlindingFactor",
".",
"SetBytes",
"(",
"sessionKey",
".",
"D",
".",
"Bytes",
"(",
")",
")",
"\n\n",
"// Now recursively compute the cached blinding factor, ephemeral ECDH",
"// pub keys, and shared secret for each hop.",
"var",
"nextBlindingFactor",
"big",
".",
"Int",
"\n",
"for",
"i",
":=",
"1",
";",
"i",
"<=",
"numHops",
"-",
"1",
";",
"i",
"++",
"{",
"// Update the cached blinding factor with b_{i-1}.",
"nextBlindingFactor",
".",
"SetBytes",
"(",
"lastBlindingFactor",
"[",
":",
"]",
")",
"\n",
"cachedBlindingFactor",
".",
"Mul",
"(",
"&",
"cachedBlindingFactor",
",",
"&",
"nextBlindingFactor",
")",
"\n",
"cachedBlindingFactor",
".",
"Mod",
"(",
"&",
"cachedBlindingFactor",
",",
"btcec",
".",
"S256",
"(",
")",
".",
"Params",
"(",
")",
".",
"N",
")",
"\n\n",
"// a_i = g ^ c_i",
"// = g^( x * b_0 * ... * b_{i-1} )",
"// = X^( b_0 * ... * b_{i-1} )",
"// X_our_session_pub_key x all prev blinding factors",
"lastEphemeralPubKey",
"=",
"blindBaseElement",
"(",
"cachedBlindingFactor",
".",
"Bytes",
"(",
")",
")",
"\n\n",
"// e_i = Y_i ^ c_i",
"// = ( Y_i ^ x )^( b_0 * ... * b_{i-1} )",
"// (Y_their_pub_key x x_our_priv) x all prev blinding factors",
"hopBlindedPubKey",
":=",
"blindGroupElement",
"(",
"paymentPath",
"[",
"i",
"]",
",",
"cachedBlindingFactor",
".",
"Bytes",
"(",
")",
",",
")",
"\n\n",
"// s_i = sha256( e_i )",
"// = sha256( Y_i ^ (x * b_0 * ... * b_{i-1} )",
"hopSharedSecrets",
"[",
"i",
"]",
"=",
"sha256",
".",
"Sum256",
"(",
"hopBlindedPubKey",
".",
"SerializeCompressed",
"(",
")",
")",
"\n\n",
"// Only need to evaluate up to the penultimate blinding factor.",
"if",
"i",
">=",
"numHops",
"-",
"1",
"{",
"break",
"\n",
"}",
"\n\n",
"// b_i = sha256( a_i || s_i )",
"lastBlindingFactor",
"=",
"computeBlindingFactor",
"(",
"lastEphemeralPubKey",
",",
"hopSharedSecrets",
"[",
"i",
"]",
"[",
":",
"]",
",",
")",
"\n",
"}",
"\n\n",
"return",
"hopSharedSecrets",
"\n",
"}"
] |
// generateSharedSecrets by the given nodes pubkeys, generates the shared
// secrets.
|
[
"generateSharedSecrets",
"by",
"the",
"given",
"nodes",
"pubkeys",
"generates",
"the",
"shared",
"secrets",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/sphinx.go#L207-L276
|
11,870 |
lightningnetwork/lightning-onion
|
sphinx.go
|
NewOnionPacket
|
func NewOnionPacket(paymentPath *PaymentPath, sessionKey *btcec.PrivateKey,
assocData []byte) (*OnionPacket, error) {
numHops := paymentPath.TrueRouteLength()
hopSharedSecrets := generateSharedSecrets(
paymentPath.NodeKeys(), sessionKey,
)
// Generate the padding, called "filler strings" in the paper.
filler := generateHeaderPadding(
"rho", numHops, HopDataSize, hopSharedSecrets,
)
// Allocate zero'd out byte slices to store the final mix header packet
// and the hmac for each hop.
var (
mixHeader [routingInfoSize]byte
nextHmac [HMACSize]byte
hopDataBuf bytes.Buffer
)
// Now we compute the routing information for each hop, along with a
// MAC of the routing info using the shared key for that hop.
for i := numHops - 1; i >= 0; i-- {
// We'll derive the two keys we need for each hop in order to:
// generate our stream cipher bytes for the mixHeader, and
// calculate the MAC over the entire constructed packet.
rhoKey := generateKey("rho", &hopSharedSecrets[i])
muKey := generateKey("mu", &hopSharedSecrets[i])
// The HMAC for the final hop is simply zeroes. This allows the
// last hop to recognize that it is the destination for a
// particular payment.
paymentPath[i].HopData.HMAC = nextHmac
// Next, using the key dedicated for our stream cipher, we'll
// generate enough bytes to obfuscate this layer of the onion
// packet.
streamBytes := generateCipherStream(rhoKey, numStreamBytes)
// Before we assemble the packet, we'll shift the current
// mix-header to the write in order to make room for this next
// per-hop data.
rightShift(mixHeader[:], HopDataSize)
// With the mix header right-shifted, we'll encode the current
// hop data into a buffer we'll re-use during the packet
// construction.
err := paymentPath[i].HopData.Encode(&hopDataBuf)
if err != nil {
return nil, err
}
copy(mixHeader[:], hopDataBuf.Bytes())
// Once the packet for this hop has been assembled, we'll
// re-encrypt the packet by XOR'ing with a stream of bytes
// generated using our shared secret.
xor(mixHeader[:], mixHeader[:], streamBytes[:routingInfoSize])
// If this is the "last" hop, then we'll override the tail of
// the hop data.
if i == numHops-1 {
copy(mixHeader[len(mixHeader)-len(filler):], filler)
}
// The packet for this hop consists of: mixHeader. When
// calculating the MAC, we'll also include the optional
// associated data which can allow higher level applications to
// prevent replay attacks.
packet := append(mixHeader[:], assocData...)
nextHmac = calcMac(muKey, packet)
hopDataBuf.Reset()
}
return &OnionPacket{
Version: baseVersion,
EphemeralKey: sessionKey.PubKey(),
RoutingInfo: mixHeader,
HeaderMAC: nextHmac,
}, nil
}
|
go
|
func NewOnionPacket(paymentPath *PaymentPath, sessionKey *btcec.PrivateKey,
assocData []byte) (*OnionPacket, error) {
numHops := paymentPath.TrueRouteLength()
hopSharedSecrets := generateSharedSecrets(
paymentPath.NodeKeys(), sessionKey,
)
// Generate the padding, called "filler strings" in the paper.
filler := generateHeaderPadding(
"rho", numHops, HopDataSize, hopSharedSecrets,
)
// Allocate zero'd out byte slices to store the final mix header packet
// and the hmac for each hop.
var (
mixHeader [routingInfoSize]byte
nextHmac [HMACSize]byte
hopDataBuf bytes.Buffer
)
// Now we compute the routing information for each hop, along with a
// MAC of the routing info using the shared key for that hop.
for i := numHops - 1; i >= 0; i-- {
// We'll derive the two keys we need for each hop in order to:
// generate our stream cipher bytes for the mixHeader, and
// calculate the MAC over the entire constructed packet.
rhoKey := generateKey("rho", &hopSharedSecrets[i])
muKey := generateKey("mu", &hopSharedSecrets[i])
// The HMAC for the final hop is simply zeroes. This allows the
// last hop to recognize that it is the destination for a
// particular payment.
paymentPath[i].HopData.HMAC = nextHmac
// Next, using the key dedicated for our stream cipher, we'll
// generate enough bytes to obfuscate this layer of the onion
// packet.
streamBytes := generateCipherStream(rhoKey, numStreamBytes)
// Before we assemble the packet, we'll shift the current
// mix-header to the write in order to make room for this next
// per-hop data.
rightShift(mixHeader[:], HopDataSize)
// With the mix header right-shifted, we'll encode the current
// hop data into a buffer we'll re-use during the packet
// construction.
err := paymentPath[i].HopData.Encode(&hopDataBuf)
if err != nil {
return nil, err
}
copy(mixHeader[:], hopDataBuf.Bytes())
// Once the packet for this hop has been assembled, we'll
// re-encrypt the packet by XOR'ing with a stream of bytes
// generated using our shared secret.
xor(mixHeader[:], mixHeader[:], streamBytes[:routingInfoSize])
// If this is the "last" hop, then we'll override the tail of
// the hop data.
if i == numHops-1 {
copy(mixHeader[len(mixHeader)-len(filler):], filler)
}
// The packet for this hop consists of: mixHeader. When
// calculating the MAC, we'll also include the optional
// associated data which can allow higher level applications to
// prevent replay attacks.
packet := append(mixHeader[:], assocData...)
nextHmac = calcMac(muKey, packet)
hopDataBuf.Reset()
}
return &OnionPacket{
Version: baseVersion,
EphemeralKey: sessionKey.PubKey(),
RoutingInfo: mixHeader,
HeaderMAC: nextHmac,
}, nil
}
|
[
"func",
"NewOnionPacket",
"(",
"paymentPath",
"*",
"PaymentPath",
",",
"sessionKey",
"*",
"btcec",
".",
"PrivateKey",
",",
"assocData",
"[",
"]",
"byte",
")",
"(",
"*",
"OnionPacket",
",",
"error",
")",
"{",
"numHops",
":=",
"paymentPath",
".",
"TrueRouteLength",
"(",
")",
"\n\n",
"hopSharedSecrets",
":=",
"generateSharedSecrets",
"(",
"paymentPath",
".",
"NodeKeys",
"(",
")",
",",
"sessionKey",
",",
")",
"\n\n",
"// Generate the padding, called \"filler strings\" in the paper.",
"filler",
":=",
"generateHeaderPadding",
"(",
"\"",
"\"",
",",
"numHops",
",",
"HopDataSize",
",",
"hopSharedSecrets",
",",
")",
"\n\n",
"// Allocate zero'd out byte slices to store the final mix header packet",
"// and the hmac for each hop.",
"var",
"(",
"mixHeader",
"[",
"routingInfoSize",
"]",
"byte",
"\n",
"nextHmac",
"[",
"HMACSize",
"]",
"byte",
"\n",
"hopDataBuf",
"bytes",
".",
"Buffer",
"\n",
")",
"\n\n",
"// Now we compute the routing information for each hop, along with a",
"// MAC of the routing info using the shared key for that hop.",
"for",
"i",
":=",
"numHops",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"// We'll derive the two keys we need for each hop in order to:",
"// generate our stream cipher bytes for the mixHeader, and",
"// calculate the MAC over the entire constructed packet.",
"rhoKey",
":=",
"generateKey",
"(",
"\"",
"\"",
",",
"&",
"hopSharedSecrets",
"[",
"i",
"]",
")",
"\n",
"muKey",
":=",
"generateKey",
"(",
"\"",
"\"",
",",
"&",
"hopSharedSecrets",
"[",
"i",
"]",
")",
"\n\n",
"// The HMAC for the final hop is simply zeroes. This allows the",
"// last hop to recognize that it is the destination for a",
"// particular payment.",
"paymentPath",
"[",
"i",
"]",
".",
"HopData",
".",
"HMAC",
"=",
"nextHmac",
"\n\n",
"// Next, using the key dedicated for our stream cipher, we'll",
"// generate enough bytes to obfuscate this layer of the onion",
"// packet.",
"streamBytes",
":=",
"generateCipherStream",
"(",
"rhoKey",
",",
"numStreamBytes",
")",
"\n\n",
"// Before we assemble the packet, we'll shift the current",
"// mix-header to the write in order to make room for this next",
"// per-hop data.",
"rightShift",
"(",
"mixHeader",
"[",
":",
"]",
",",
"HopDataSize",
")",
"\n\n",
"// With the mix header right-shifted, we'll encode the current",
"// hop data into a buffer we'll re-use during the packet",
"// construction.",
"err",
":=",
"paymentPath",
"[",
"i",
"]",
".",
"HopData",
".",
"Encode",
"(",
"&",
"hopDataBuf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"copy",
"(",
"mixHeader",
"[",
":",
"]",
",",
"hopDataBuf",
".",
"Bytes",
"(",
")",
")",
"\n\n",
"// Once the packet for this hop has been assembled, we'll",
"// re-encrypt the packet by XOR'ing with a stream of bytes",
"// generated using our shared secret.",
"xor",
"(",
"mixHeader",
"[",
":",
"]",
",",
"mixHeader",
"[",
":",
"]",
",",
"streamBytes",
"[",
":",
"routingInfoSize",
"]",
")",
"\n\n",
"// If this is the \"last\" hop, then we'll override the tail of",
"// the hop data.",
"if",
"i",
"==",
"numHops",
"-",
"1",
"{",
"copy",
"(",
"mixHeader",
"[",
"len",
"(",
"mixHeader",
")",
"-",
"len",
"(",
"filler",
")",
":",
"]",
",",
"filler",
")",
"\n",
"}",
"\n\n",
"// The packet for this hop consists of: mixHeader. When",
"// calculating the MAC, we'll also include the optional",
"// associated data which can allow higher level applications to",
"// prevent replay attacks.",
"packet",
":=",
"append",
"(",
"mixHeader",
"[",
":",
"]",
",",
"assocData",
"...",
")",
"\n",
"nextHmac",
"=",
"calcMac",
"(",
"muKey",
",",
"packet",
")",
"\n\n",
"hopDataBuf",
".",
"Reset",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"OnionPacket",
"{",
"Version",
":",
"baseVersion",
",",
"EphemeralKey",
":",
"sessionKey",
".",
"PubKey",
"(",
")",
",",
"RoutingInfo",
":",
"mixHeader",
",",
"HeaderMAC",
":",
"nextHmac",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewOnionPacket creates a new onion packet which is capable of obliviously
// routing a message through the mix-net path outline by 'paymentPath'.
|
[
"NewOnionPacket",
"creates",
"a",
"new",
"onion",
"packet",
"which",
"is",
"capable",
"of",
"obliviously",
"routing",
"a",
"message",
"through",
"the",
"mix",
"-",
"net",
"path",
"outline",
"by",
"paymentPath",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/sphinx.go#L280-L362
|
11,871 |
lightningnetwork/lightning-onion
|
sphinx.go
|
rightShift
|
func rightShift(slice []byte, num int) {
for i := len(slice) - num - 1; i >= 0; i-- {
slice[num+i] = slice[i]
}
for i := 0; i < num; i++ {
slice[i] = 0
}
}
|
go
|
func rightShift(slice []byte, num int) {
for i := len(slice) - num - 1; i >= 0; i-- {
slice[num+i] = slice[i]
}
for i := 0; i < num; i++ {
slice[i] = 0
}
}
|
[
"func",
"rightShift",
"(",
"slice",
"[",
"]",
"byte",
",",
"num",
"int",
")",
"{",
"for",
"i",
":=",
"len",
"(",
"slice",
")",
"-",
"num",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"slice",
"[",
"num",
"+",
"i",
"]",
"=",
"slice",
"[",
"i",
"]",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"num",
";",
"i",
"++",
"{",
"slice",
"[",
"i",
"]",
"=",
"0",
"\n",
"}",
"\n",
"}"
] |
// rightShift shifts the byte-slice by the given number of bytes to the right
// and 0-fill the resulting gap.
|
[
"rightShift",
"shifts",
"the",
"byte",
"-",
"slice",
"by",
"the",
"given",
"number",
"of",
"bytes",
"to",
"the",
"right",
"and",
"0",
"-",
"fill",
"the",
"resulting",
"gap",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/sphinx.go#L366-L374
|
11,872 |
lightningnetwork/lightning-onion
|
sphinx.go
|
Encode
|
func (f *OnionPacket) Encode(w io.Writer) error {
ephemeral := f.EphemeralKey.SerializeCompressed()
if _, err := w.Write([]byte{f.Version}); err != nil {
return err
}
if _, err := w.Write(ephemeral); err != nil {
return err
}
if _, err := w.Write(f.RoutingInfo[:]); err != nil {
return err
}
if _, err := w.Write(f.HeaderMAC[:]); err != nil {
return err
}
return nil
}
|
go
|
func (f *OnionPacket) Encode(w io.Writer) error {
ephemeral := f.EphemeralKey.SerializeCompressed()
if _, err := w.Write([]byte{f.Version}); err != nil {
return err
}
if _, err := w.Write(ephemeral); err != nil {
return err
}
if _, err := w.Write(f.RoutingInfo[:]); err != nil {
return err
}
if _, err := w.Write(f.HeaderMAC[:]); err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"f",
"*",
"OnionPacket",
")",
"Encode",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"ephemeral",
":=",
"f",
".",
"EphemeralKey",
".",
"SerializeCompressed",
"(",
")",
"\n\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"{",
"f",
".",
"Version",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"ephemeral",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"f",
".",
"RoutingInfo",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"f",
".",
"HeaderMAC",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Encode serializes the raw bytes of the onion packet into the passed
// io.Writer. The form encoded within the passed io.Writer is suitable for
// either storing on disk, or sending over the network.
|
[
"Encode",
"serializes",
"the",
"raw",
"bytes",
"of",
"the",
"onion",
"packet",
"into",
"the",
"passed",
"io",
".",
"Writer",
".",
"The",
"form",
"encoded",
"within",
"the",
"passed",
"io",
".",
"Writer",
"is",
"suitable",
"for",
"either",
"storing",
"on",
"disk",
"or",
"sending",
"over",
"the",
"network",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/sphinx.go#L404-L424
|
11,873 |
lightningnetwork/lightning-onion
|
sphinx.go
|
Decode
|
func (f *OnionPacket) Decode(r io.Reader) error {
var err error
var buf [1]byte
if _, err := io.ReadFull(r, buf[:]); err != nil {
return err
}
f.Version = buf[0]
// If version of the onion packet protocol unknown for us than in might
// lead to improperly decoded data.
if f.Version != baseVersion {
return ErrInvalidOnionVersion
}
var ephemeral [33]byte
if _, err := io.ReadFull(r, ephemeral[:]); err != nil {
return err
}
f.EphemeralKey, err = btcec.ParsePubKey(ephemeral[:], btcec.S256())
if err != nil {
return ErrInvalidOnionKey
}
if _, err := io.ReadFull(r, f.RoutingInfo[:]); err != nil {
return err
}
if _, err := io.ReadFull(r, f.HeaderMAC[:]); err != nil {
return err
}
return nil
}
|
go
|
func (f *OnionPacket) Decode(r io.Reader) error {
var err error
var buf [1]byte
if _, err := io.ReadFull(r, buf[:]); err != nil {
return err
}
f.Version = buf[0]
// If version of the onion packet protocol unknown for us than in might
// lead to improperly decoded data.
if f.Version != baseVersion {
return ErrInvalidOnionVersion
}
var ephemeral [33]byte
if _, err := io.ReadFull(r, ephemeral[:]); err != nil {
return err
}
f.EphemeralKey, err = btcec.ParsePubKey(ephemeral[:], btcec.S256())
if err != nil {
return ErrInvalidOnionKey
}
if _, err := io.ReadFull(r, f.RoutingInfo[:]); err != nil {
return err
}
if _, err := io.ReadFull(r, f.HeaderMAC[:]); err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"f",
"*",
"OnionPacket",
")",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"error",
"{",
"var",
"err",
"error",
"\n\n",
"var",
"buf",
"[",
"1",
"]",
"byte",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"buf",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"f",
".",
"Version",
"=",
"buf",
"[",
"0",
"]",
"\n\n",
"// If version of the onion packet protocol unknown for us than in might",
"// lead to improperly decoded data.",
"if",
"f",
".",
"Version",
"!=",
"baseVersion",
"{",
"return",
"ErrInvalidOnionVersion",
"\n",
"}",
"\n\n",
"var",
"ephemeral",
"[",
"33",
"]",
"byte",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"ephemeral",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"f",
".",
"EphemeralKey",
",",
"err",
"=",
"btcec",
".",
"ParsePubKey",
"(",
"ephemeral",
"[",
":",
"]",
",",
"btcec",
".",
"S256",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"ErrInvalidOnionKey",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"f",
".",
"RoutingInfo",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"f",
".",
"HeaderMAC",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Decode fully populates the target ForwardingMessage from the raw bytes
// encoded within the io.Reader. In the case of any decoding errors, an error
// will be returned. If the method success, then the new OnionPacket is ready
// to be processed by an instance of SphinxNode.
|
[
"Decode",
"fully",
"populates",
"the",
"target",
"ForwardingMessage",
"from",
"the",
"raw",
"bytes",
"encoded",
"within",
"the",
"io",
".",
"Reader",
".",
"In",
"the",
"case",
"of",
"any",
"decoding",
"errors",
"an",
"error",
"will",
"be",
"returned",
".",
"If",
"the",
"method",
"success",
"then",
"the",
"new",
"OnionPacket",
"is",
"ready",
"to",
"be",
"processed",
"by",
"an",
"instance",
"of",
"SphinxNode",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/sphinx.go#L430-L463
|
11,874 |
lightningnetwork/lightning-onion
|
sphinx.go
|
NewRouter
|
func NewRouter(nodeKey *btcec.PrivateKey, net *chaincfg.Params, log ReplayLog) *Router {
var nodeID [AddressSize]byte
copy(nodeID[:], btcutil.Hash160(nodeKey.PubKey().SerializeCompressed()))
// Safe to ignore the error here, nodeID is 20 bytes.
nodeAddr, _ := btcutil.NewAddressPubKeyHash(nodeID[:], net)
return &Router{
nodeID: nodeID,
nodeAddr: nodeAddr,
onionKey: &btcec.PrivateKey{
PublicKey: ecdsa.PublicKey{
Curve: btcec.S256(),
X: nodeKey.X,
Y: nodeKey.Y,
},
D: nodeKey.D,
},
log: log,
}
}
|
go
|
func NewRouter(nodeKey *btcec.PrivateKey, net *chaincfg.Params, log ReplayLog) *Router {
var nodeID [AddressSize]byte
copy(nodeID[:], btcutil.Hash160(nodeKey.PubKey().SerializeCompressed()))
// Safe to ignore the error here, nodeID is 20 bytes.
nodeAddr, _ := btcutil.NewAddressPubKeyHash(nodeID[:], net)
return &Router{
nodeID: nodeID,
nodeAddr: nodeAddr,
onionKey: &btcec.PrivateKey{
PublicKey: ecdsa.PublicKey{
Curve: btcec.S256(),
X: nodeKey.X,
Y: nodeKey.Y,
},
D: nodeKey.D,
},
log: log,
}
}
|
[
"func",
"NewRouter",
"(",
"nodeKey",
"*",
"btcec",
".",
"PrivateKey",
",",
"net",
"*",
"chaincfg",
".",
"Params",
",",
"log",
"ReplayLog",
")",
"*",
"Router",
"{",
"var",
"nodeID",
"[",
"AddressSize",
"]",
"byte",
"\n",
"copy",
"(",
"nodeID",
"[",
":",
"]",
",",
"btcutil",
".",
"Hash160",
"(",
"nodeKey",
".",
"PubKey",
"(",
")",
".",
"SerializeCompressed",
"(",
")",
")",
")",
"\n\n",
"// Safe to ignore the error here, nodeID is 20 bytes.",
"nodeAddr",
",",
"_",
":=",
"btcutil",
".",
"NewAddressPubKeyHash",
"(",
"nodeID",
"[",
":",
"]",
",",
"net",
")",
"\n\n",
"return",
"&",
"Router",
"{",
"nodeID",
":",
"nodeID",
",",
"nodeAddr",
":",
"nodeAddr",
",",
"onionKey",
":",
"&",
"btcec",
".",
"PrivateKey",
"{",
"PublicKey",
":",
"ecdsa",
".",
"PublicKey",
"{",
"Curve",
":",
"btcec",
".",
"S256",
"(",
")",
",",
"X",
":",
"nodeKey",
".",
"X",
",",
"Y",
":",
"nodeKey",
".",
"Y",
",",
"}",
",",
"D",
":",
"nodeKey",
".",
"D",
",",
"}",
",",
"log",
":",
"log",
",",
"}",
"\n",
"}"
] |
// NewRouter creates a new instance of a Sphinx onion Router given the node's
// currently advertised onion private key, and the target Bitcoin network.
|
[
"NewRouter",
"creates",
"a",
"new",
"instance",
"of",
"a",
"Sphinx",
"onion",
"Router",
"given",
"the",
"node",
"s",
"currently",
"advertised",
"onion",
"private",
"key",
"and",
"the",
"target",
"Bitcoin",
"network",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/sphinx.go#L536-L556
|
11,875 |
lightningnetwork/lightning-onion
|
sphinx.go
|
unwrapPacket
|
func unwrapPacket(onionPkt *OnionPacket, sharedSecret *Hash256,
assocData []byte) (*OnionPacket, *HopData, error) {
dhKey := onionPkt.EphemeralKey
routeInfo := onionPkt.RoutingInfo
headerMac := onionPkt.HeaderMAC
// Using the derived shared secret, ensure the integrity of the routing
// information by checking the attached MAC without leaking timing
// information.
message := append(routeInfo[:], assocData...)
calculatedMac := calcMac(generateKey("mu", sharedSecret), message)
if !hmac.Equal(headerMac[:], calculatedMac[:]) {
return nil, nil, ErrInvalidOnionHMAC
}
// Attach the padding zeroes in order to properly strip an encryption
// layer off the routing info revealing the routing information for the
// next hop.
streamBytes := generateCipherStream(
generateKey("rho", sharedSecret),
numStreamBytes,
)
zeroBytes := bytes.Repeat([]byte{0}, HopDataSize)
headerWithPadding := append(routeInfo[:], zeroBytes...)
var hopInfo [numStreamBytes]byte
xor(hopInfo[:], headerWithPadding, streamBytes)
// Randomize the DH group element for the next hop using the
// deterministic blinding factor.
blindingFactor := computeBlindingFactor(dhKey, sharedSecret[:])
nextDHKey := blindGroupElement(dhKey, blindingFactor[:])
// With the MAC checked, and the payload decrypted, we can now parse
// out the per-hop data so we can derive the specified forwarding
// instructions.
var hopData HopData
if err := hopData.Decode(bytes.NewReader(hopInfo[:])); err != nil {
return nil, nil, err
}
// With the necessary items extracted, we'll copy of the onion packet
// for the next node, snipping off our per-hop data.
var nextMixHeader [routingInfoSize]byte
copy(nextMixHeader[:], hopInfo[HopDataSize:])
innerPkt := &OnionPacket{
Version: onionPkt.Version,
EphemeralKey: nextDHKey,
RoutingInfo: nextMixHeader,
HeaderMAC: hopData.HMAC,
}
return innerPkt, &hopData, nil
}
|
go
|
func unwrapPacket(onionPkt *OnionPacket, sharedSecret *Hash256,
assocData []byte) (*OnionPacket, *HopData, error) {
dhKey := onionPkt.EphemeralKey
routeInfo := onionPkt.RoutingInfo
headerMac := onionPkt.HeaderMAC
// Using the derived shared secret, ensure the integrity of the routing
// information by checking the attached MAC without leaking timing
// information.
message := append(routeInfo[:], assocData...)
calculatedMac := calcMac(generateKey("mu", sharedSecret), message)
if !hmac.Equal(headerMac[:], calculatedMac[:]) {
return nil, nil, ErrInvalidOnionHMAC
}
// Attach the padding zeroes in order to properly strip an encryption
// layer off the routing info revealing the routing information for the
// next hop.
streamBytes := generateCipherStream(
generateKey("rho", sharedSecret),
numStreamBytes,
)
zeroBytes := bytes.Repeat([]byte{0}, HopDataSize)
headerWithPadding := append(routeInfo[:], zeroBytes...)
var hopInfo [numStreamBytes]byte
xor(hopInfo[:], headerWithPadding, streamBytes)
// Randomize the DH group element for the next hop using the
// deterministic blinding factor.
blindingFactor := computeBlindingFactor(dhKey, sharedSecret[:])
nextDHKey := blindGroupElement(dhKey, blindingFactor[:])
// With the MAC checked, and the payload decrypted, we can now parse
// out the per-hop data so we can derive the specified forwarding
// instructions.
var hopData HopData
if err := hopData.Decode(bytes.NewReader(hopInfo[:])); err != nil {
return nil, nil, err
}
// With the necessary items extracted, we'll copy of the onion packet
// for the next node, snipping off our per-hop data.
var nextMixHeader [routingInfoSize]byte
copy(nextMixHeader[:], hopInfo[HopDataSize:])
innerPkt := &OnionPacket{
Version: onionPkt.Version,
EphemeralKey: nextDHKey,
RoutingInfo: nextMixHeader,
HeaderMAC: hopData.HMAC,
}
return innerPkt, &hopData, nil
}
|
[
"func",
"unwrapPacket",
"(",
"onionPkt",
"*",
"OnionPacket",
",",
"sharedSecret",
"*",
"Hash256",
",",
"assocData",
"[",
"]",
"byte",
")",
"(",
"*",
"OnionPacket",
",",
"*",
"HopData",
",",
"error",
")",
"{",
"dhKey",
":=",
"onionPkt",
".",
"EphemeralKey",
"\n",
"routeInfo",
":=",
"onionPkt",
".",
"RoutingInfo",
"\n",
"headerMac",
":=",
"onionPkt",
".",
"HeaderMAC",
"\n\n",
"// Using the derived shared secret, ensure the integrity of the routing",
"// information by checking the attached MAC without leaking timing",
"// information.",
"message",
":=",
"append",
"(",
"routeInfo",
"[",
":",
"]",
",",
"assocData",
"...",
")",
"\n",
"calculatedMac",
":=",
"calcMac",
"(",
"generateKey",
"(",
"\"",
"\"",
",",
"sharedSecret",
")",
",",
"message",
")",
"\n",
"if",
"!",
"hmac",
".",
"Equal",
"(",
"headerMac",
"[",
":",
"]",
",",
"calculatedMac",
"[",
":",
"]",
")",
"{",
"return",
"nil",
",",
"nil",
",",
"ErrInvalidOnionHMAC",
"\n",
"}",
"\n\n",
"// Attach the padding zeroes in order to properly strip an encryption",
"// layer off the routing info revealing the routing information for the",
"// next hop.",
"streamBytes",
":=",
"generateCipherStream",
"(",
"generateKey",
"(",
"\"",
"\"",
",",
"sharedSecret",
")",
",",
"numStreamBytes",
",",
")",
"\n",
"zeroBytes",
":=",
"bytes",
".",
"Repeat",
"(",
"[",
"]",
"byte",
"{",
"0",
"}",
",",
"HopDataSize",
")",
"\n",
"headerWithPadding",
":=",
"append",
"(",
"routeInfo",
"[",
":",
"]",
",",
"zeroBytes",
"...",
")",
"\n\n",
"var",
"hopInfo",
"[",
"numStreamBytes",
"]",
"byte",
"\n",
"xor",
"(",
"hopInfo",
"[",
":",
"]",
",",
"headerWithPadding",
",",
"streamBytes",
")",
"\n\n",
"// Randomize the DH group element for the next hop using the",
"// deterministic blinding factor.",
"blindingFactor",
":=",
"computeBlindingFactor",
"(",
"dhKey",
",",
"sharedSecret",
"[",
":",
"]",
")",
"\n",
"nextDHKey",
":=",
"blindGroupElement",
"(",
"dhKey",
",",
"blindingFactor",
"[",
":",
"]",
")",
"\n\n",
"// With the MAC checked, and the payload decrypted, we can now parse",
"// out the per-hop data so we can derive the specified forwarding",
"// instructions.",
"var",
"hopData",
"HopData",
"\n",
"if",
"err",
":=",
"hopData",
".",
"Decode",
"(",
"bytes",
".",
"NewReader",
"(",
"hopInfo",
"[",
":",
"]",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// With the necessary items extracted, we'll copy of the onion packet",
"// for the next node, snipping off our per-hop data.",
"var",
"nextMixHeader",
"[",
"routingInfoSize",
"]",
"byte",
"\n",
"copy",
"(",
"nextMixHeader",
"[",
":",
"]",
",",
"hopInfo",
"[",
"HopDataSize",
":",
"]",
")",
"\n",
"innerPkt",
":=",
"&",
"OnionPacket",
"{",
"Version",
":",
"onionPkt",
".",
"Version",
",",
"EphemeralKey",
":",
"nextDHKey",
",",
"RoutingInfo",
":",
"nextMixHeader",
",",
"HeaderMAC",
":",
"hopData",
".",
"HMAC",
",",
"}",
"\n\n",
"return",
"innerPkt",
",",
"&",
"hopData",
",",
"nil",
"\n",
"}"
] |
// unwrapPacket wraps a layer of the passed onion packet using the specified
// shared secret and associated data. The associated data will be used to check
// the HMAC at each hop to ensure the same data is passed along with the onion
// packet. This function returns the next inner onion packet layer, along with
// the hop data extracted from the outer onion packet.
|
[
"unwrapPacket",
"wraps",
"a",
"layer",
"of",
"the",
"passed",
"onion",
"packet",
"using",
"the",
"specified",
"shared",
"secret",
"and",
"associated",
"data",
".",
"The",
"associated",
"data",
"will",
"be",
"used",
"to",
"check",
"the",
"HMAC",
"at",
"each",
"hop",
"to",
"ensure",
"the",
"same",
"data",
"is",
"passed",
"along",
"with",
"the",
"onion",
"packet",
".",
"This",
"function",
"returns",
"the",
"next",
"inner",
"onion",
"packet",
"layer",
"along",
"with",
"the",
"hop",
"data",
"extracted",
"from",
"the",
"outer",
"onion",
"packet",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/sphinx.go#L630-L684
|
11,876 |
lightningnetwork/lightning-onion
|
sphinx.go
|
processOnionPacket
|
func processOnionPacket(onionPkt *OnionPacket, sharedSecret *Hash256,
assocData []byte,
sharedSecretGen sharedSecretGenerator) (*ProcessedPacket, error) {
// First, we'll unwrap an initial layer of the onion packet. Typically,
// we'll only have a single layer to unwrap, However, if the sender has
// additional data for us within the Extra Onion Blobs (EOBs), then we
// may have to unwrap additional layers. By default, the inner most
// mix header is the one that we'll want to pass onto the next hop so
// they can properly check the HMAC and unwrap a layer for their
// handoff hop.
innerPkt, outerHopData, err := unwrapPacket(
onionPkt, sharedSecret, assocData,
)
if err != nil {
return nil, err
}
// By default we'll assume that there are additional hops in the route.
// However if the uncovered 'nextMac' is all zeroes, then this
// indicates that we're the final hop in the route.
var action ProcessCode = MoreHops
if bytes.Compare(zeroHMAC[:], outerHopData.HMAC[:]) == 0 {
action = ExitNode
}
// Finally, we'll return a fully processed packet with the outer most
// hop data (where the primary forwarding instructions lie) and the
// inner most onion packet that we unwrapped.
return &ProcessedPacket{
Action: action,
ForwardingInstructions: *outerHopData,
NextPacket: innerPkt,
}, nil
}
|
go
|
func processOnionPacket(onionPkt *OnionPacket, sharedSecret *Hash256,
assocData []byte,
sharedSecretGen sharedSecretGenerator) (*ProcessedPacket, error) {
// First, we'll unwrap an initial layer of the onion packet. Typically,
// we'll only have a single layer to unwrap, However, if the sender has
// additional data for us within the Extra Onion Blobs (EOBs), then we
// may have to unwrap additional layers. By default, the inner most
// mix header is the one that we'll want to pass onto the next hop so
// they can properly check the HMAC and unwrap a layer for their
// handoff hop.
innerPkt, outerHopData, err := unwrapPacket(
onionPkt, sharedSecret, assocData,
)
if err != nil {
return nil, err
}
// By default we'll assume that there are additional hops in the route.
// However if the uncovered 'nextMac' is all zeroes, then this
// indicates that we're the final hop in the route.
var action ProcessCode = MoreHops
if bytes.Compare(zeroHMAC[:], outerHopData.HMAC[:]) == 0 {
action = ExitNode
}
// Finally, we'll return a fully processed packet with the outer most
// hop data (where the primary forwarding instructions lie) and the
// inner most onion packet that we unwrapped.
return &ProcessedPacket{
Action: action,
ForwardingInstructions: *outerHopData,
NextPacket: innerPkt,
}, nil
}
|
[
"func",
"processOnionPacket",
"(",
"onionPkt",
"*",
"OnionPacket",
",",
"sharedSecret",
"*",
"Hash256",
",",
"assocData",
"[",
"]",
"byte",
",",
"sharedSecretGen",
"sharedSecretGenerator",
")",
"(",
"*",
"ProcessedPacket",
",",
"error",
")",
"{",
"// First, we'll unwrap an initial layer of the onion packet. Typically,",
"// we'll only have a single layer to unwrap, However, if the sender has",
"// additional data for us within the Extra Onion Blobs (EOBs), then we",
"// may have to unwrap additional layers. By default, the inner most",
"// mix header is the one that we'll want to pass onto the next hop so",
"// they can properly check the HMAC and unwrap a layer for their",
"// handoff hop.",
"innerPkt",
",",
"outerHopData",
",",
"err",
":=",
"unwrapPacket",
"(",
"onionPkt",
",",
"sharedSecret",
",",
"assocData",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// By default we'll assume that there are additional hops in the route.",
"// However if the uncovered 'nextMac' is all zeroes, then this",
"// indicates that we're the final hop in the route.",
"var",
"action",
"ProcessCode",
"=",
"MoreHops",
"\n",
"if",
"bytes",
".",
"Compare",
"(",
"zeroHMAC",
"[",
":",
"]",
",",
"outerHopData",
".",
"HMAC",
"[",
":",
"]",
")",
"==",
"0",
"{",
"action",
"=",
"ExitNode",
"\n",
"}",
"\n\n",
"// Finally, we'll return a fully processed packet with the outer most",
"// hop data (where the primary forwarding instructions lie) and the",
"// inner most onion packet that we unwrapped.",
"return",
"&",
"ProcessedPacket",
"{",
"Action",
":",
"action",
",",
"ForwardingInstructions",
":",
"*",
"outerHopData",
",",
"NextPacket",
":",
"innerPkt",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// processOnionPacket performs the primary key derivation and handling of onion
// packets. The processed packets returned from this method should only be used
// if the packet was not flagged as a replayed packet.
|
[
"processOnionPacket",
"performs",
"the",
"primary",
"key",
"derivation",
"and",
"handling",
"of",
"onion",
"packets",
".",
"The",
"processed",
"packets",
"returned",
"from",
"this",
"method",
"should",
"only",
"be",
"used",
"if",
"the",
"packet",
"was",
"not",
"flagged",
"as",
"a",
"replayed",
"packet",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/sphinx.go#L689-L723
|
11,877 |
lightningnetwork/lightning-onion
|
sphinx.go
|
Commit
|
func (t *Tx) Commit() ([]ProcessedPacket, *ReplaySet, error) {
if t.batch.IsCommitted {
return t.packets, t.batch.ReplaySet, nil
}
rs, err := t.router.log.PutBatch(t.batch)
return t.packets, rs, err
}
|
go
|
func (t *Tx) Commit() ([]ProcessedPacket, *ReplaySet, error) {
if t.batch.IsCommitted {
return t.packets, t.batch.ReplaySet, nil
}
rs, err := t.router.log.PutBatch(t.batch)
return t.packets, rs, err
}
|
[
"func",
"(",
"t",
"*",
"Tx",
")",
"Commit",
"(",
")",
"(",
"[",
"]",
"ProcessedPacket",
",",
"*",
"ReplaySet",
",",
"error",
")",
"{",
"if",
"t",
".",
"batch",
".",
"IsCommitted",
"{",
"return",
"t",
".",
"packets",
",",
"t",
".",
"batch",
".",
"ReplaySet",
",",
"nil",
"\n",
"}",
"\n\n",
"rs",
",",
"err",
":=",
"t",
".",
"router",
".",
"log",
".",
"PutBatch",
"(",
"t",
".",
"batch",
")",
"\n\n",
"return",
"t",
".",
"packets",
",",
"rs",
",",
"err",
"\n",
"}"
] |
// Commit writes this transaction's batch of sphinx packets to the replay log,
// performing a final check against the log for replays.
|
[
"Commit",
"writes",
"this",
"transaction",
"s",
"batch",
"of",
"sphinx",
"packets",
"to",
"the",
"replay",
"log",
"performing",
"a",
"final",
"check",
"against",
"the",
"log",
"for",
"replays",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/sphinx.go#L812-L820
|
11,878 |
lightningnetwork/lightning-onion
|
path.go
|
IsEmpty
|
func (o OnionHop) IsEmpty() bool {
return o.NodePub.X == nil || o.NodePub.Y == nil
}
|
go
|
func (o OnionHop) IsEmpty() bool {
return o.NodePub.X == nil || o.NodePub.Y == nil
}
|
[
"func",
"(",
"o",
"OnionHop",
")",
"IsEmpty",
"(",
")",
"bool",
"{",
"return",
"o",
".",
"NodePub",
".",
"X",
"==",
"nil",
"||",
"o",
".",
"NodePub",
".",
"Y",
"==",
"nil",
"\n",
"}"
] |
// IsEmpty returns true if the hop isn't populated.
|
[
"IsEmpty",
"returns",
"true",
"if",
"the",
"hop",
"isn",
"t",
"populated",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/path.go#L37-L39
|
11,879 |
lightningnetwork/lightning-onion
|
crypto.go
|
calcMac
|
func calcMac(key [keyLen]byte, msg []byte) [HMACSize]byte {
hmac := hmac.New(sha256.New, key[:])
hmac.Write(msg)
h := hmac.Sum(nil)
var mac [HMACSize]byte
copy(mac[:], h[:HMACSize])
return mac
}
|
go
|
func calcMac(key [keyLen]byte, msg []byte) [HMACSize]byte {
hmac := hmac.New(sha256.New, key[:])
hmac.Write(msg)
h := hmac.Sum(nil)
var mac [HMACSize]byte
copy(mac[:], h[:HMACSize])
return mac
}
|
[
"func",
"calcMac",
"(",
"key",
"[",
"keyLen",
"]",
"byte",
",",
"msg",
"[",
"]",
"byte",
")",
"[",
"HMACSize",
"]",
"byte",
"{",
"hmac",
":=",
"hmac",
".",
"New",
"(",
"sha256",
".",
"New",
",",
"key",
"[",
":",
"]",
")",
"\n",
"hmac",
".",
"Write",
"(",
"msg",
")",
"\n",
"h",
":=",
"hmac",
".",
"Sum",
"(",
"nil",
")",
"\n\n",
"var",
"mac",
"[",
"HMACSize",
"]",
"byte",
"\n",
"copy",
"(",
"mac",
"[",
":",
"]",
",",
"h",
"[",
":",
"HMACSize",
"]",
")",
"\n\n",
"return",
"mac",
"\n",
"}"
] |
// calcMac calculates HMAC-SHA-256 over the message using the passed secret key
// as input to the HMAC.
|
[
"calcMac",
"calculates",
"HMAC",
"-",
"SHA",
"-",
"256",
"over",
"the",
"message",
"using",
"the",
"passed",
"secret",
"key",
"as",
"input",
"to",
"the",
"HMAC",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/crypto.go#L31-L40
|
11,880 |
lightningnetwork/lightning-onion
|
crypto.go
|
generateCipherStream
|
func generateCipherStream(key [keyLen]byte, numBytes uint) []byte {
var (
nonce [8]byte
)
cipher, err := chacha20.NewCipher(nonce[:], key[:])
if err != nil {
panic(err)
}
output := make([]byte, numBytes)
cipher.XORKeyStream(output, output)
return output
}
|
go
|
func generateCipherStream(key [keyLen]byte, numBytes uint) []byte {
var (
nonce [8]byte
)
cipher, err := chacha20.NewCipher(nonce[:], key[:])
if err != nil {
panic(err)
}
output := make([]byte, numBytes)
cipher.XORKeyStream(output, output)
return output
}
|
[
"func",
"generateCipherStream",
"(",
"key",
"[",
"keyLen",
"]",
"byte",
",",
"numBytes",
"uint",
")",
"[",
"]",
"byte",
"{",
"var",
"(",
"nonce",
"[",
"8",
"]",
"byte",
"\n",
")",
"\n",
"cipher",
",",
"err",
":=",
"chacha20",
".",
"NewCipher",
"(",
"nonce",
"[",
":",
"]",
",",
"key",
"[",
":",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"output",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"numBytes",
")",
"\n",
"cipher",
".",
"XORKeyStream",
"(",
"output",
",",
"output",
")",
"\n\n",
"return",
"output",
"\n",
"}"
] |
// generateCipherStream generates a stream of cryptographic psuedo-random bytes
// intended to be used to encrypt a message using a one-time-pad like
// construction.
|
[
"generateCipherStream",
"generates",
"a",
"stream",
"of",
"cryptographic",
"psuedo",
"-",
"random",
"bytes",
"intended",
"to",
"be",
"used",
"to",
"encrypt",
"a",
"message",
"using",
"a",
"one",
"-",
"time",
"-",
"pad",
"like",
"construction",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/crypto.go#L73-L85
|
11,881 |
lightningnetwork/lightning-onion
|
crypto.go
|
generateSharedSecret
|
func (r *Router) generateSharedSecret(dhKey *btcec.PublicKey) (Hash256, error) {
var sharedSecret Hash256
// Ensure that the public key is on our curve.
if !btcec.S256().IsOnCurve(dhKey.X, dhKey.Y) {
return sharedSecret, ErrInvalidOnionKey
}
// Compute our shared secret.
sharedSecret = generateSharedSecret(dhKey, r.onionKey)
return sharedSecret, nil
}
|
go
|
func (r *Router) generateSharedSecret(dhKey *btcec.PublicKey) (Hash256, error) {
var sharedSecret Hash256
// Ensure that the public key is on our curve.
if !btcec.S256().IsOnCurve(dhKey.X, dhKey.Y) {
return sharedSecret, ErrInvalidOnionKey
}
// Compute our shared secret.
sharedSecret = generateSharedSecret(dhKey, r.onionKey)
return sharedSecret, nil
}
|
[
"func",
"(",
"r",
"*",
"Router",
")",
"generateSharedSecret",
"(",
"dhKey",
"*",
"btcec",
".",
"PublicKey",
")",
"(",
"Hash256",
",",
"error",
")",
"{",
"var",
"sharedSecret",
"Hash256",
"\n\n",
"// Ensure that the public key is on our curve.",
"if",
"!",
"btcec",
".",
"S256",
"(",
")",
".",
"IsOnCurve",
"(",
"dhKey",
".",
"X",
",",
"dhKey",
".",
"Y",
")",
"{",
"return",
"sharedSecret",
",",
"ErrInvalidOnionKey",
"\n",
"}",
"\n\n",
"// Compute our shared secret.",
"sharedSecret",
"=",
"generateSharedSecret",
"(",
"dhKey",
",",
"r",
".",
"onionKey",
")",
"\n",
"return",
"sharedSecret",
",",
"nil",
"\n",
"}"
] |
// generateSharedSecret generates the shared secret by given ephemeral key.
|
[
"generateSharedSecret",
"generates",
"the",
"shared",
"secret",
"by",
"given",
"ephemeral",
"key",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/crypto.go#L127-L138
|
11,882 |
lightningnetwork/lightning-onion
|
crypto.go
|
generateSharedSecret
|
func generateSharedSecret(pub *btcec.PublicKey, priv *btcec.PrivateKey) Hash256 {
s := &btcec.PublicKey{}
s.X, s.Y = btcec.S256().ScalarMult(pub.X, pub.Y, priv.D.Bytes())
return sha256.Sum256(s.SerializeCompressed())
}
|
go
|
func generateSharedSecret(pub *btcec.PublicKey, priv *btcec.PrivateKey) Hash256 {
s := &btcec.PublicKey{}
s.X, s.Y = btcec.S256().ScalarMult(pub.X, pub.Y, priv.D.Bytes())
return sha256.Sum256(s.SerializeCompressed())
}
|
[
"func",
"generateSharedSecret",
"(",
"pub",
"*",
"btcec",
".",
"PublicKey",
",",
"priv",
"*",
"btcec",
".",
"PrivateKey",
")",
"Hash256",
"{",
"s",
":=",
"&",
"btcec",
".",
"PublicKey",
"{",
"}",
"\n",
"s",
".",
"X",
",",
"s",
".",
"Y",
"=",
"btcec",
".",
"S256",
"(",
")",
".",
"ScalarMult",
"(",
"pub",
".",
"X",
",",
"pub",
".",
"Y",
",",
"priv",
".",
"D",
".",
"Bytes",
"(",
")",
")",
"\n\n",
"return",
"sha256",
".",
"Sum256",
"(",
"s",
".",
"SerializeCompressed",
"(",
")",
")",
"\n",
"}"
] |
// generateSharedSecret generates the shared secret for a particular hop. The
// shared secret is generated by taking the group element contained in the
// mix-header, and performing an ECDH operation with the node's long term onion
// key. We then take the _entire_ point generated by the ECDH operation,
// serialize that using a compressed format, then feed the raw bytes through a
// single SHA256 invocation. The resulting value is the shared secret.
|
[
"generateSharedSecret",
"generates",
"the",
"shared",
"secret",
"for",
"a",
"particular",
"hop",
".",
"The",
"shared",
"secret",
"is",
"generated",
"by",
"taking",
"the",
"group",
"element",
"contained",
"in",
"the",
"mix",
"-",
"header",
"and",
"performing",
"an",
"ECDH",
"operation",
"with",
"the",
"node",
"s",
"long",
"term",
"onion",
"key",
".",
"We",
"then",
"take",
"the",
"_entire_",
"point",
"generated",
"by",
"the",
"ECDH",
"operation",
"serialize",
"that",
"using",
"a",
"compressed",
"format",
"then",
"feed",
"the",
"raw",
"bytes",
"through",
"a",
"single",
"SHA256",
"invocation",
".",
"The",
"resulting",
"value",
"is",
"the",
"shared",
"secret",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/crypto.go#L146-L151
|
11,883 |
lightningnetwork/lightning-onion
|
crypto.go
|
DecryptError
|
func (o *OnionErrorDecrypter) DecryptError(encryptedData []byte) (*btcec.PublicKey, []byte, error) {
// Ensure the error message length is as expected.
if len(encryptedData) != onionErrorLength {
return nil, nil, fmt.Errorf("invalid error length: "+
"expected %v got %v", onionErrorLength,
len(encryptedData))
}
sharedSecrets := generateSharedSecrets(
o.circuit.PaymentPath,
o.circuit.SessionKey,
)
var (
sender *btcec.PublicKey
msg []byte
dummySecret Hash256
)
copy(dummySecret[:], bytes.Repeat([]byte{1}, 32))
// We'll iterate a constant amount of hops to ensure that we don't give
// away an timing information pertaining to the position in the route
// that the error emanated from.
for i := 0; i < NumMaxHops; i++ {
var sharedSecret Hash256
// If we've already found the sender, then we'll use our dummy
// secret to continue decryption attempts to fill out the rest
// of the loop. Otherwise, we'll use the next shared secret in
// line.
if sender != nil || i > len(sharedSecrets)-1 {
sharedSecret = dummySecret
} else {
sharedSecret = sharedSecrets[i]
}
// With the shared secret, we'll now strip off a layer of
// encryption from the encrypted error payload.
encryptedData = onionEncrypt(&sharedSecret, encryptedData)
// Next, we'll need to separate the data, from the MAC itself
// so we can reconstruct and verify it.
expectedMac := encryptedData[:sha256.Size]
data := encryptedData[sha256.Size:]
// With the data split, we'll now re-generate the MAC using its
// specified key.
umKey := generateKey("um", &sharedSecret)
h := hmac.New(sha256.New, umKey[:])
h.Write(data)
// If the MAC matches up, then we've found the sender of the
// error and have also obtained the fully decrypted message.
realMac := h.Sum(nil)
if hmac.Equal(realMac, expectedMac) && sender == nil {
sender = o.circuit.PaymentPath[i]
msg = data
}
}
// If the sender pointer is still nil, then we haven't found the
// sender, meaning we've failed to decrypt.
if sender == nil {
return nil, nil, errors.New("unable to retrieve onion failure")
}
return sender, msg, nil
}
|
go
|
func (o *OnionErrorDecrypter) DecryptError(encryptedData []byte) (*btcec.PublicKey, []byte, error) {
// Ensure the error message length is as expected.
if len(encryptedData) != onionErrorLength {
return nil, nil, fmt.Errorf("invalid error length: "+
"expected %v got %v", onionErrorLength,
len(encryptedData))
}
sharedSecrets := generateSharedSecrets(
o.circuit.PaymentPath,
o.circuit.SessionKey,
)
var (
sender *btcec.PublicKey
msg []byte
dummySecret Hash256
)
copy(dummySecret[:], bytes.Repeat([]byte{1}, 32))
// We'll iterate a constant amount of hops to ensure that we don't give
// away an timing information pertaining to the position in the route
// that the error emanated from.
for i := 0; i < NumMaxHops; i++ {
var sharedSecret Hash256
// If we've already found the sender, then we'll use our dummy
// secret to continue decryption attempts to fill out the rest
// of the loop. Otherwise, we'll use the next shared secret in
// line.
if sender != nil || i > len(sharedSecrets)-1 {
sharedSecret = dummySecret
} else {
sharedSecret = sharedSecrets[i]
}
// With the shared secret, we'll now strip off a layer of
// encryption from the encrypted error payload.
encryptedData = onionEncrypt(&sharedSecret, encryptedData)
// Next, we'll need to separate the data, from the MAC itself
// so we can reconstruct and verify it.
expectedMac := encryptedData[:sha256.Size]
data := encryptedData[sha256.Size:]
// With the data split, we'll now re-generate the MAC using its
// specified key.
umKey := generateKey("um", &sharedSecret)
h := hmac.New(sha256.New, umKey[:])
h.Write(data)
// If the MAC matches up, then we've found the sender of the
// error and have also obtained the fully decrypted message.
realMac := h.Sum(nil)
if hmac.Equal(realMac, expectedMac) && sender == nil {
sender = o.circuit.PaymentPath[i]
msg = data
}
}
// If the sender pointer is still nil, then we haven't found the
// sender, meaning we've failed to decrypt.
if sender == nil {
return nil, nil, errors.New("unable to retrieve onion failure")
}
return sender, msg, nil
}
|
[
"func",
"(",
"o",
"*",
"OnionErrorDecrypter",
")",
"DecryptError",
"(",
"encryptedData",
"[",
"]",
"byte",
")",
"(",
"*",
"btcec",
".",
"PublicKey",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Ensure the error message length is as expected.",
"if",
"len",
"(",
"encryptedData",
")",
"!=",
"onionErrorLength",
"{",
"return",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
",",
"onionErrorLength",
",",
"len",
"(",
"encryptedData",
")",
")",
"\n",
"}",
"\n\n",
"sharedSecrets",
":=",
"generateSharedSecrets",
"(",
"o",
".",
"circuit",
".",
"PaymentPath",
",",
"o",
".",
"circuit",
".",
"SessionKey",
",",
")",
"\n\n",
"var",
"(",
"sender",
"*",
"btcec",
".",
"PublicKey",
"\n",
"msg",
"[",
"]",
"byte",
"\n",
"dummySecret",
"Hash256",
"\n",
")",
"\n",
"copy",
"(",
"dummySecret",
"[",
":",
"]",
",",
"bytes",
".",
"Repeat",
"(",
"[",
"]",
"byte",
"{",
"1",
"}",
",",
"32",
")",
")",
"\n\n",
"// We'll iterate a constant amount of hops to ensure that we don't give",
"// away an timing information pertaining to the position in the route",
"// that the error emanated from.",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"NumMaxHops",
";",
"i",
"++",
"{",
"var",
"sharedSecret",
"Hash256",
"\n\n",
"// If we've already found the sender, then we'll use our dummy",
"// secret to continue decryption attempts to fill out the rest",
"// of the loop. Otherwise, we'll use the next shared secret in",
"// line.",
"if",
"sender",
"!=",
"nil",
"||",
"i",
">",
"len",
"(",
"sharedSecrets",
")",
"-",
"1",
"{",
"sharedSecret",
"=",
"dummySecret",
"\n",
"}",
"else",
"{",
"sharedSecret",
"=",
"sharedSecrets",
"[",
"i",
"]",
"\n",
"}",
"\n\n",
"// With the shared secret, we'll now strip off a layer of",
"// encryption from the encrypted error payload.",
"encryptedData",
"=",
"onionEncrypt",
"(",
"&",
"sharedSecret",
",",
"encryptedData",
")",
"\n\n",
"// Next, we'll need to separate the data, from the MAC itself",
"// so we can reconstruct and verify it.",
"expectedMac",
":=",
"encryptedData",
"[",
":",
"sha256",
".",
"Size",
"]",
"\n",
"data",
":=",
"encryptedData",
"[",
"sha256",
".",
"Size",
":",
"]",
"\n\n",
"// With the data split, we'll now re-generate the MAC using its",
"// specified key.",
"umKey",
":=",
"generateKey",
"(",
"\"",
"\"",
",",
"&",
"sharedSecret",
")",
"\n",
"h",
":=",
"hmac",
".",
"New",
"(",
"sha256",
".",
"New",
",",
"umKey",
"[",
":",
"]",
")",
"\n",
"h",
".",
"Write",
"(",
"data",
")",
"\n\n",
"// If the MAC matches up, then we've found the sender of the",
"// error and have also obtained the fully decrypted message.",
"realMac",
":=",
"h",
".",
"Sum",
"(",
"nil",
")",
"\n",
"if",
"hmac",
".",
"Equal",
"(",
"realMac",
",",
"expectedMac",
")",
"&&",
"sender",
"==",
"nil",
"{",
"sender",
"=",
"o",
".",
"circuit",
".",
"PaymentPath",
"[",
"i",
"]",
"\n",
"msg",
"=",
"data",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If the sender pointer is still nil, then we haven't found the",
"// sender, meaning we've failed to decrypt.",
"if",
"sender",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"sender",
",",
"msg",
",",
"nil",
"\n",
"}"
] |
// DecryptError attempts to decrypt the passed encrypted error response. The
// onion failure is encrypted in backward manner, starting from the node where
// error have occurred. As a result, in order to decrypt the error we need get
// all shared secret and apply decryption in the reverse order.
|
[
"DecryptError",
"attempts",
"to",
"decrypt",
"the",
"passed",
"encrypted",
"error",
"response",
".",
"The",
"onion",
"failure",
"is",
"encrypted",
"in",
"backward",
"manner",
"starting",
"from",
"the",
"node",
"where",
"error",
"have",
"occurred",
".",
"As",
"a",
"result",
"in",
"order",
"to",
"decrypt",
"the",
"error",
"we",
"need",
"get",
"all",
"shared",
"secret",
"and",
"apply",
"decryption",
"in",
"the",
"reverse",
"order",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/crypto.go#L175-L242
|
11,884 |
lightningnetwork/lightning-onion
|
crypto.go
|
EncryptError
|
func (o *OnionErrorEncrypter) EncryptError(initial bool, data []byte) []byte {
if initial {
umKey := generateKey("um", &o.sharedSecret)
hash := hmac.New(sha256.New, umKey[:])
hash.Write(data)
h := hash.Sum(nil)
data = append(h, data...)
}
return onionEncrypt(&o.sharedSecret, data)
}
|
go
|
func (o *OnionErrorEncrypter) EncryptError(initial bool, data []byte) []byte {
if initial {
umKey := generateKey("um", &o.sharedSecret)
hash := hmac.New(sha256.New, umKey[:])
hash.Write(data)
h := hash.Sum(nil)
data = append(h, data...)
}
return onionEncrypt(&o.sharedSecret, data)
}
|
[
"func",
"(",
"o",
"*",
"OnionErrorEncrypter",
")",
"EncryptError",
"(",
"initial",
"bool",
",",
"data",
"[",
"]",
"byte",
")",
"[",
"]",
"byte",
"{",
"if",
"initial",
"{",
"umKey",
":=",
"generateKey",
"(",
"\"",
"\"",
",",
"&",
"o",
".",
"sharedSecret",
")",
"\n",
"hash",
":=",
"hmac",
".",
"New",
"(",
"sha256",
".",
"New",
",",
"umKey",
"[",
":",
"]",
")",
"\n",
"hash",
".",
"Write",
"(",
"data",
")",
"\n",
"h",
":=",
"hash",
".",
"Sum",
"(",
"nil",
")",
"\n",
"data",
"=",
"append",
"(",
"h",
",",
"data",
"...",
")",
"\n",
"}",
"\n\n",
"return",
"onionEncrypt",
"(",
"&",
"o",
".",
"sharedSecret",
",",
"data",
")",
"\n",
"}"
] |
// EncryptError is used to make data obfuscation using the generated shared
// secret.
//
// In context of Lightning Network is either used by the nodes in order to make
// initial obfuscation with the creation of the hmac or by the forwarding nodes
// for backward failure obfuscation of the onion failure blob. By obfuscating
// the onion failure on every node in the path we are adding additional step of
// the security and barrier for malware nodes to retrieve valuable information.
// The reason for using onion obfuscation is to not give
// away to the nodes in the payment path the information about the exact
// failure and its origin.
|
[
"EncryptError",
"is",
"used",
"to",
"make",
"data",
"obfuscation",
"using",
"the",
"generated",
"shared",
"secret",
".",
"In",
"context",
"of",
"Lightning",
"Network",
"is",
"either",
"used",
"by",
"the",
"nodes",
"in",
"order",
"to",
"make",
"initial",
"obfuscation",
"with",
"the",
"creation",
"of",
"the",
"hmac",
"or",
"by",
"the",
"forwarding",
"nodes",
"for",
"backward",
"failure",
"obfuscation",
"of",
"the",
"onion",
"failure",
"blob",
".",
"By",
"obfuscating",
"the",
"onion",
"failure",
"on",
"every",
"node",
"in",
"the",
"path",
"we",
"are",
"adding",
"additional",
"step",
"of",
"the",
"security",
"and",
"barrier",
"for",
"malware",
"nodes",
"to",
"retrieve",
"valuable",
"information",
".",
"The",
"reason",
"for",
"using",
"onion",
"obfuscation",
"is",
"to",
"not",
"give",
"away",
"to",
"the",
"nodes",
"in",
"the",
"payment",
"path",
"the",
"information",
"about",
"the",
"exact",
"failure",
"and",
"its",
"origin",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/crypto.go#L255-L265
|
11,885 |
lightningnetwork/lightning-onion
|
obfuscation.go
|
NewOnionErrorEncrypter
|
func NewOnionErrorEncrypter(router *Router,
ephemeralKey *btcec.PublicKey) (*OnionErrorEncrypter, error) {
sharedSecret, err := router.generateSharedSecret(ephemeralKey)
if err != nil {
return nil, err
}
return &OnionErrorEncrypter{
sharedSecret: sharedSecret,
}, nil
}
|
go
|
func NewOnionErrorEncrypter(router *Router,
ephemeralKey *btcec.PublicKey) (*OnionErrorEncrypter, error) {
sharedSecret, err := router.generateSharedSecret(ephemeralKey)
if err != nil {
return nil, err
}
return &OnionErrorEncrypter{
sharedSecret: sharedSecret,
}, nil
}
|
[
"func",
"NewOnionErrorEncrypter",
"(",
"router",
"*",
"Router",
",",
"ephemeralKey",
"*",
"btcec",
".",
"PublicKey",
")",
"(",
"*",
"OnionErrorEncrypter",
",",
"error",
")",
"{",
"sharedSecret",
",",
"err",
":=",
"router",
".",
"generateSharedSecret",
"(",
"ephemeralKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"OnionErrorEncrypter",
"{",
"sharedSecret",
":",
"sharedSecret",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewOnionErrorEncrypter creates new instance of the onion encrypter backed by
// the passed router, with encryption to be doing using the passed
// ephemeralKey.
|
[
"NewOnionErrorEncrypter",
"creates",
"new",
"instance",
"of",
"the",
"onion",
"encrypter",
"backed",
"by",
"the",
"passed",
"router",
"with",
"encryption",
"to",
"be",
"doing",
"using",
"the",
"passed",
"ephemeralKey",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/obfuscation.go#L18-L29
|
11,886 |
lightningnetwork/lightning-onion
|
obfuscation.go
|
Encode
|
func (o *OnionErrorEncrypter) Encode(w io.Writer) error {
_, err := w.Write(o.sharedSecret[:])
return err
}
|
go
|
func (o *OnionErrorEncrypter) Encode(w io.Writer) error {
_, err := w.Write(o.sharedSecret[:])
return err
}
|
[
"func",
"(",
"o",
"*",
"OnionErrorEncrypter",
")",
"Encode",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"o",
".",
"sharedSecret",
"[",
":",
"]",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// Encode writes the encrypter's shared secret to the provided io.Writer.
|
[
"Encode",
"writes",
"the",
"encrypter",
"s",
"shared",
"secret",
"to",
"the",
"provided",
"io",
".",
"Writer",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/obfuscation.go#L32-L35
|
11,887 |
lightningnetwork/lightning-onion
|
obfuscation.go
|
Decode
|
func (o *OnionErrorEncrypter) Decode(r io.Reader) error {
_, err := io.ReadFull(r, o.sharedSecret[:])
return err
}
|
go
|
func (o *OnionErrorEncrypter) Decode(r io.Reader) error {
_, err := io.ReadFull(r, o.sharedSecret[:])
return err
}
|
[
"func",
"(",
"o",
"*",
"OnionErrorEncrypter",
")",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"error",
"{",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"r",
",",
"o",
".",
"sharedSecret",
"[",
":",
"]",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// Decode restores the encrypter's share secret from the provided io.Reader.
|
[
"Decode",
"restores",
"the",
"encrypter",
"s",
"share",
"secret",
"from",
"the",
"provided",
"io",
".",
"Reader",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/obfuscation.go#L38-L41
|
11,888 |
lightningnetwork/lightning-onion
|
obfuscation.go
|
Decode
|
func (c *Circuit) Decode(r io.Reader) error {
var keyLength [1]byte
if _, err := r.Read(keyLength[:]); err != nil {
return err
}
sessionKeyData := make([]byte, uint8(keyLength[0]))
if _, err := r.Read(sessionKeyData[:]); err != nil {
return err
}
c.SessionKey, _ = btcec.PrivKeyFromBytes(btcec.S256(), sessionKeyData)
var pathLength [1]byte
if _, err := r.Read(pathLength[:]); err != nil {
return err
}
c.PaymentPath = make([]*btcec.PublicKey, uint8(pathLength[0]))
for i := 0; i < len(c.PaymentPath); i++ {
var pubKeyData [btcec.PubKeyBytesLenCompressed]byte
if _, err := r.Read(pubKeyData[:]); err != nil {
return err
}
pubKey, err := btcec.ParsePubKey(pubKeyData[:], btcec.S256())
if err != nil {
return err
}
c.PaymentPath[i] = pubKey
}
return nil
}
|
go
|
func (c *Circuit) Decode(r io.Reader) error {
var keyLength [1]byte
if _, err := r.Read(keyLength[:]); err != nil {
return err
}
sessionKeyData := make([]byte, uint8(keyLength[0]))
if _, err := r.Read(sessionKeyData[:]); err != nil {
return err
}
c.SessionKey, _ = btcec.PrivKeyFromBytes(btcec.S256(), sessionKeyData)
var pathLength [1]byte
if _, err := r.Read(pathLength[:]); err != nil {
return err
}
c.PaymentPath = make([]*btcec.PublicKey, uint8(pathLength[0]))
for i := 0; i < len(c.PaymentPath); i++ {
var pubKeyData [btcec.PubKeyBytesLenCompressed]byte
if _, err := r.Read(pubKeyData[:]); err != nil {
return err
}
pubKey, err := btcec.ParsePubKey(pubKeyData[:], btcec.S256())
if err != nil {
return err
}
c.PaymentPath[i] = pubKey
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Circuit",
")",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"error",
"{",
"var",
"keyLength",
"[",
"1",
"]",
"byte",
"\n",
"if",
"_",
",",
"err",
":=",
"r",
".",
"Read",
"(",
"keyLength",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"sessionKeyData",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"uint8",
"(",
"keyLength",
"[",
"0",
"]",
")",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"r",
".",
"Read",
"(",
"sessionKeyData",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"c",
".",
"SessionKey",
",",
"_",
"=",
"btcec",
".",
"PrivKeyFromBytes",
"(",
"btcec",
".",
"S256",
"(",
")",
",",
"sessionKeyData",
")",
"\n",
"var",
"pathLength",
"[",
"1",
"]",
"byte",
"\n",
"if",
"_",
",",
"err",
":=",
"r",
".",
"Read",
"(",
"pathLength",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"c",
".",
"PaymentPath",
"=",
"make",
"(",
"[",
"]",
"*",
"btcec",
".",
"PublicKey",
",",
"uint8",
"(",
"pathLength",
"[",
"0",
"]",
")",
")",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"c",
".",
"PaymentPath",
")",
";",
"i",
"++",
"{",
"var",
"pubKeyData",
"[",
"btcec",
".",
"PubKeyBytesLenCompressed",
"]",
"byte",
"\n",
"if",
"_",
",",
"err",
":=",
"r",
".",
"Read",
"(",
"pubKeyData",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"pubKey",
",",
"err",
":=",
"btcec",
".",
"ParsePubKey",
"(",
"pubKeyData",
"[",
":",
"]",
",",
"btcec",
".",
"S256",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"c",
".",
"PaymentPath",
"[",
"i",
"]",
"=",
"pubKey",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Decode initializes the circuit from the byte stream.
|
[
"Decode",
"initializes",
"the",
"circuit",
"from",
"the",
"byte",
"stream",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/obfuscation.go#L54-L86
|
11,889 |
lightningnetwork/lightning-onion
|
obfuscation.go
|
Encode
|
func (c *Circuit) Encode(w io.Writer) error {
var keyLength [1]byte
keyLength[0] = uint8(len(c.SessionKey.Serialize()))
if _, err := w.Write(keyLength[:]); err != nil {
return err
}
if _, err := w.Write(c.SessionKey.Serialize()); err != nil {
return err
}
var pathLength [1]byte
pathLength[0] = uint8(len(c.PaymentPath))
if _, err := w.Write(pathLength[:]); err != nil {
return err
}
for _, pubKey := range c.PaymentPath {
if _, err := w.Write(pubKey.SerializeCompressed()); err != nil {
return err
}
}
return nil
}
|
go
|
func (c *Circuit) Encode(w io.Writer) error {
var keyLength [1]byte
keyLength[0] = uint8(len(c.SessionKey.Serialize()))
if _, err := w.Write(keyLength[:]); err != nil {
return err
}
if _, err := w.Write(c.SessionKey.Serialize()); err != nil {
return err
}
var pathLength [1]byte
pathLength[0] = uint8(len(c.PaymentPath))
if _, err := w.Write(pathLength[:]); err != nil {
return err
}
for _, pubKey := range c.PaymentPath {
if _, err := w.Write(pubKey.SerializeCompressed()); err != nil {
return err
}
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Circuit",
")",
"Encode",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"var",
"keyLength",
"[",
"1",
"]",
"byte",
"\n",
"keyLength",
"[",
"0",
"]",
"=",
"uint8",
"(",
"len",
"(",
"c",
".",
"SessionKey",
".",
"Serialize",
"(",
")",
")",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"keyLength",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"c",
".",
"SessionKey",
".",
"Serialize",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"pathLength",
"[",
"1",
"]",
"byte",
"\n",
"pathLength",
"[",
"0",
"]",
"=",
"uint8",
"(",
"len",
"(",
"c",
".",
"PaymentPath",
")",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"pathLength",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"pubKey",
":=",
"range",
"c",
".",
"PaymentPath",
"{",
"if",
"_",
",",
"err",
":=",
"w",
".",
"Write",
"(",
"pubKey",
".",
"SerializeCompressed",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Encode writes converted circuit in the byte stream.
|
[
"Encode",
"writes",
"converted",
"circuit",
"in",
"the",
"byte",
"stream",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/obfuscation.go#L89-L113
|
11,890 |
lightningnetwork/lightning-onion
|
replay_set.go
|
Contains
|
func (rs *ReplaySet) Contains(idx uint16) bool {
_, ok := rs.replays[idx]
return ok
}
|
go
|
func (rs *ReplaySet) Contains(idx uint16) bool {
_, ok := rs.replays[idx]
return ok
}
|
[
"func",
"(",
"rs",
"*",
"ReplaySet",
")",
"Contains",
"(",
"idx",
"uint16",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"rs",
".",
"replays",
"[",
"idx",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] |
// Contains queries the contents of the replay set for membership of a
// particular index.
|
[
"Contains",
"queries",
"the",
"contents",
"of",
"the",
"replay",
"set",
"for",
"membership",
"of",
"a",
"particular",
"index",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/replay_set.go#L35-L38
|
11,891 |
lightningnetwork/lightning-onion
|
replay_set.go
|
Merge
|
func (rs *ReplaySet) Merge(rs2 *ReplaySet) {
for seqNum := range rs2.replays {
rs.Add(seqNum)
}
}
|
go
|
func (rs *ReplaySet) Merge(rs2 *ReplaySet) {
for seqNum := range rs2.replays {
rs.Add(seqNum)
}
}
|
[
"func",
"(",
"rs",
"*",
"ReplaySet",
")",
"Merge",
"(",
"rs2",
"*",
"ReplaySet",
")",
"{",
"for",
"seqNum",
":=",
"range",
"rs2",
".",
"replays",
"{",
"rs",
".",
"Add",
"(",
"seqNum",
")",
"\n",
"}",
"\n",
"}"
] |
// Merge adds the contents of the provided replay set to the receiver's set.
|
[
"Merge",
"adds",
"the",
"contents",
"of",
"the",
"provided",
"replay",
"set",
"to",
"the",
"receiver",
"s",
"set",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/replay_set.go#L41-L45
|
11,892 |
lightningnetwork/lightning-onion
|
replay_set.go
|
Encode
|
func (rs *ReplaySet) Encode(w io.Writer) error {
for seqNum := range rs.replays {
err := binary.Write(w, binary.BigEndian, seqNum)
if err != nil {
return err
}
}
return nil
}
|
go
|
func (rs *ReplaySet) Encode(w io.Writer) error {
for seqNum := range rs.replays {
err := binary.Write(w, binary.BigEndian, seqNum)
if err != nil {
return err
}
}
return nil
}
|
[
"func",
"(",
"rs",
"*",
"ReplaySet",
")",
"Encode",
"(",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"for",
"seqNum",
":=",
"range",
"rs",
".",
"replays",
"{",
"err",
":=",
"binary",
".",
"Write",
"(",
"w",
",",
"binary",
".",
"BigEndian",
",",
"seqNum",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Encode serializes the replay set into an io.Writer suitable for storage. The
// replay set can be recovered using Decode.
|
[
"Encode",
"serializes",
"the",
"replay",
"set",
"into",
"an",
"io",
".",
"Writer",
"suitable",
"for",
"storage",
".",
"The",
"replay",
"set",
"can",
"be",
"recovered",
"using",
"Decode",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/replay_set.go#L49-L58
|
11,893 |
lightningnetwork/lightning-onion
|
replay_set.go
|
Decode
|
func (rs *ReplaySet) Decode(r io.Reader) error {
for {
// seqNum provides to buffer to read the next uint16 index.
var seqNum uint16
err := binary.Read(r, binary.BigEndian, &seqNum)
switch err {
case nil:
// Successful read, proceed.
case io.EOF:
return nil
default:
// Can return ErrShortBuffer or ErrUnexpectedEOF.
return err
}
// Add this decoded sequence number to the set.
rs.Add(seqNum)
}
}
|
go
|
func (rs *ReplaySet) Decode(r io.Reader) error {
for {
// seqNum provides to buffer to read the next uint16 index.
var seqNum uint16
err := binary.Read(r, binary.BigEndian, &seqNum)
switch err {
case nil:
// Successful read, proceed.
case io.EOF:
return nil
default:
// Can return ErrShortBuffer or ErrUnexpectedEOF.
return err
}
// Add this decoded sequence number to the set.
rs.Add(seqNum)
}
}
|
[
"func",
"(",
"rs",
"*",
"ReplaySet",
")",
"Decode",
"(",
"r",
"io",
".",
"Reader",
")",
"error",
"{",
"for",
"{",
"// seqNum provides to buffer to read the next uint16 index.",
"var",
"seqNum",
"uint16",
"\n\n",
"err",
":=",
"binary",
".",
"Read",
"(",
"r",
",",
"binary",
".",
"BigEndian",
",",
"&",
"seqNum",
")",
"\n",
"switch",
"err",
"{",
"case",
"nil",
":",
"// Successful read, proceed.",
"case",
"io",
".",
"EOF",
":",
"return",
"nil",
"\n",
"default",
":",
"// Can return ErrShortBuffer or ErrUnexpectedEOF.",
"return",
"err",
"\n",
"}",
"\n\n",
"// Add this decoded sequence number to the set.",
"rs",
".",
"Add",
"(",
"seqNum",
")",
"\n",
"}",
"\n",
"}"
] |
// Decode reconstructs a replay set given a io.Reader. The byte
// slice is assumed to be even in length, otherwise resulting in failure.
|
[
"Decode",
"reconstructs",
"a",
"replay",
"set",
"given",
"a",
"io",
".",
"Reader",
".",
"The",
"byte",
"slice",
"is",
"assumed",
"to",
"be",
"even",
"in",
"length",
"otherwise",
"resulting",
"in",
"failure",
"."
] |
751fb4dd8b72bbaec93889249a6c6ca9f71a5598
|
https://github.com/lightningnetwork/lightning-onion/blob/751fb4dd8b72bbaec93889249a6c6ca9f71a5598/replay_set.go#L62-L81
|
11,894 |
evalphobia/logrus_sentry
|
sentry_setter.go
|
SetHttpContext
|
func (hook *SentryHook) SetHttpContext(h *raven.Http) {
hook.client.SetHttpContext(h)
}
|
go
|
func (hook *SentryHook) SetHttpContext(h *raven.Http) {
hook.client.SetHttpContext(h)
}
|
[
"func",
"(",
"hook",
"*",
"SentryHook",
")",
"SetHttpContext",
"(",
"h",
"*",
"raven",
".",
"Http",
")",
"{",
"hook",
".",
"client",
".",
"SetHttpContext",
"(",
"h",
")",
"\n",
"}"
] |
// SetHttpContext sets http client.
|
[
"SetHttpContext",
"sets",
"http",
"client",
"."
] |
ab0fa2ee9517a8e8c1de1c07e492e8164f852529
|
https://github.com/evalphobia/logrus_sentry/blob/ab0fa2ee9517a8e8c1de1c07e492e8164f852529/sentry_setter.go#L18-L20
|
11,895 |
evalphobia/logrus_sentry
|
sentry_setter.go
|
SetIgnoreErrors
|
func (hook *SentryHook) SetIgnoreErrors(errs ...string) error {
return hook.client.SetIgnoreErrors(errs)
}
|
go
|
func (hook *SentryHook) SetIgnoreErrors(errs ...string) error {
return hook.client.SetIgnoreErrors(errs)
}
|
[
"func",
"(",
"hook",
"*",
"SentryHook",
")",
"SetIgnoreErrors",
"(",
"errs",
"...",
"string",
")",
"error",
"{",
"return",
"hook",
".",
"client",
".",
"SetIgnoreErrors",
"(",
"errs",
")",
"\n",
"}"
] |
// SetIgnoreErrors sets ignoreErrorsRegexp.
|
[
"SetIgnoreErrors",
"sets",
"ignoreErrorsRegexp",
"."
] |
ab0fa2ee9517a8e8c1de1c07e492e8164f852529
|
https://github.com/evalphobia/logrus_sentry/blob/ab0fa2ee9517a8e8c1de1c07e492e8164f852529/sentry_setter.go#L23-L25
|
11,896 |
evalphobia/logrus_sentry
|
sentry_setter.go
|
SetSampleRate
|
func (hook *SentryHook) SetSampleRate(rate float32) error {
return hook.client.SetSampleRate(rate)
}
|
go
|
func (hook *SentryHook) SetSampleRate(rate float32) error {
return hook.client.SetSampleRate(rate)
}
|
[
"func",
"(",
"hook",
"*",
"SentryHook",
")",
"SetSampleRate",
"(",
"rate",
"float32",
")",
"error",
"{",
"return",
"hook",
".",
"client",
".",
"SetSampleRate",
"(",
"rate",
")",
"\n",
"}"
] |
// SetSampleRate sets sampling rate.
|
[
"SetSampleRate",
"sets",
"sampling",
"rate",
"."
] |
ab0fa2ee9517a8e8c1de1c07e492e8164f852529
|
https://github.com/evalphobia/logrus_sentry/blob/ab0fa2ee9517a8e8c1de1c07e492e8164f852529/sentry_setter.go#L38-L40
|
11,897 |
evalphobia/logrus_sentry
|
sentry_setter.go
|
SetTagsContext
|
func (hook *SentryHook) SetTagsContext(t map[string]string) {
hook.client.SetTagsContext(t)
}
|
go
|
func (hook *SentryHook) SetTagsContext(t map[string]string) {
hook.client.SetTagsContext(t)
}
|
[
"func",
"(",
"hook",
"*",
"SentryHook",
")",
"SetTagsContext",
"(",
"t",
"map",
"[",
"string",
"]",
"string",
")",
"{",
"hook",
".",
"client",
".",
"SetTagsContext",
"(",
"t",
")",
"\n",
"}"
] |
// SetTagsContext sets tags.
|
[
"SetTagsContext",
"sets",
"tags",
"."
] |
ab0fa2ee9517a8e8c1de1c07e492e8164f852529
|
https://github.com/evalphobia/logrus_sentry/blob/ab0fa2ee9517a8e8c1de1c07e492e8164f852529/sentry_setter.go#L43-L45
|
11,898 |
evalphobia/logrus_sentry
|
sentry_setter.go
|
SetUserContext
|
func (hook *SentryHook) SetUserContext(u *raven.User) {
hook.client.SetUserContext(u)
}
|
go
|
func (hook *SentryHook) SetUserContext(u *raven.User) {
hook.client.SetUserContext(u)
}
|
[
"func",
"(",
"hook",
"*",
"SentryHook",
")",
"SetUserContext",
"(",
"u",
"*",
"raven",
".",
"User",
")",
"{",
"hook",
".",
"client",
".",
"SetUserContext",
"(",
"u",
")",
"\n",
"}"
] |
// SetUserContext sets user.
|
[
"SetUserContext",
"sets",
"user",
"."
] |
ab0fa2ee9517a8e8c1de1c07e492e8164f852529
|
https://github.com/evalphobia/logrus_sentry/blob/ab0fa2ee9517a8e8c1de1c07e492e8164f852529/sentry_setter.go#L48-L50
|
11,899 |
evalphobia/logrus_sentry
|
utils.go
|
xtob
|
func xtob(x string) (byte, bool) {
b1 := xvalues[x[0]]
b2 := xvalues[x[1]]
return (b1 << 4) | b2, b1 != 255 && b2 != 255
}
|
go
|
func xtob(x string) (byte, bool) {
b1 := xvalues[x[0]]
b2 := xvalues[x[1]]
return (b1 << 4) | b2, b1 != 255 && b2 != 255
}
|
[
"func",
"xtob",
"(",
"x",
"string",
")",
"(",
"byte",
",",
"bool",
")",
"{",
"b1",
":=",
"xvalues",
"[",
"x",
"[",
"0",
"]",
"]",
"\n",
"b2",
":=",
"xvalues",
"[",
"x",
"[",
"1",
"]",
"]",
"\n",
"return",
"(",
"b1",
"<<",
"4",
")",
"|",
"b2",
",",
"b1",
"!=",
"255",
"&&",
"b2",
"!=",
"255",
"\n",
"}"
] |
// xtob converts the the first two hex bytes of x into a byte.
|
[
"xtob",
"converts",
"the",
"the",
"first",
"two",
"hex",
"bytes",
"of",
"x",
"into",
"a",
"byte",
"."
] |
ab0fa2ee9517a8e8c1de1c07e492e8164f852529
|
https://github.com/evalphobia/logrus_sentry/blob/ab0fa2ee9517a8e8c1de1c07e492e8164f852529/utils.go#L131-L135
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.