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
list | docstring
stringlengths 6
2.61k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/scheduler.go
|
UpdateIntervalAction
|
func (c *Client) UpdateIntervalAction(from contract.IntervalAction) (err error) {
check, err := c.IntervalActionByName(from.Name)
if err != nil && err != redis.ErrNil {
return err
}
if err == nil && from.ID != check.ID {
// IDs are different -> name not unique
return db.ErrNotUnique
}
from.Modified = db.MakeTimestamp()
err = mergo.Merge(&from, check)
if err != nil {
return err
}
action := models.NewIntervalAction(from)
data, err := json.Marshal(action)
if err != nil {
return err
}
conn := c.Pool.Get()
defer conn.Close()
_ = conn.Send("MULTI")
deleteObject(action, action.ID, conn)
addObject(data, action, action.ID, conn)
_, err = conn.Do("EXEC")
return err
}
|
go
|
func (c *Client) UpdateIntervalAction(from contract.IntervalAction) (err error) {
check, err := c.IntervalActionByName(from.Name)
if err != nil && err != redis.ErrNil {
return err
}
if err == nil && from.ID != check.ID {
// IDs are different -> name not unique
return db.ErrNotUnique
}
from.Modified = db.MakeTimestamp()
err = mergo.Merge(&from, check)
if err != nil {
return err
}
action := models.NewIntervalAction(from)
data, err := json.Marshal(action)
if err != nil {
return err
}
conn := c.Pool.Get()
defer conn.Close()
_ = conn.Send("MULTI")
deleteObject(action, action.ID, conn)
addObject(data, action, action.ID, conn)
_, err = conn.Do("EXEC")
return err
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"UpdateIntervalAction",
"(",
"from",
"contract",
".",
"IntervalAction",
")",
"(",
"err",
"error",
")",
"{",
"check",
",",
"err",
":=",
"c",
".",
"IntervalActionByName",
"(",
"from",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"redis",
".",
"ErrNil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"from",
".",
"ID",
"!=",
"check",
".",
"ID",
"{",
"// IDs are different -> name not unique",
"return",
"db",
".",
"ErrNotUnique",
"\n",
"}",
"\n\n",
"from",
".",
"Modified",
"=",
"db",
".",
"MakeTimestamp",
"(",
")",
"\n",
"err",
"=",
"mergo",
".",
"Merge",
"(",
"&",
"from",
",",
"check",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"action",
":=",
"models",
".",
"NewIntervalAction",
"(",
"from",
")",
"\n",
"data",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"action",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"_",
"=",
"conn",
".",
"Send",
"(",
"\"",
"\"",
")",
"\n",
"deleteObject",
"(",
"action",
",",
"action",
".",
"ID",
",",
"conn",
")",
"\n",
"addObject",
"(",
"data",
",",
"action",
",",
"action",
".",
"ID",
",",
"conn",
")",
"\n",
"_",
",",
"err",
"=",
"conn",
".",
"Do",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] |
// Update schedule interval action
|
[
"Update",
"schedule",
"interval",
"action"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/scheduler.go#L358-L389
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/scheduler.go
|
DeleteIntervalActionById
|
func (c *Client) DeleteIntervalActionById(id string) (err error) {
check, err := c.IntervalActionById(id)
if err != nil {
if err == db.ErrNotFound {
return nil
}
return
}
action := models.NewIntervalAction(check)
conn := c.Pool.Get()
defer conn.Close()
_ = conn.Send("MULTI")
deleteObject(action, id, conn)
_, err = conn.Do("EXEC")
return err
}
|
go
|
func (c *Client) DeleteIntervalActionById(id string) (err error) {
check, err := c.IntervalActionById(id)
if err != nil {
if err == db.ErrNotFound {
return nil
}
return
}
action := models.NewIntervalAction(check)
conn := c.Pool.Get()
defer conn.Close()
_ = conn.Send("MULTI")
deleteObject(action, id, conn)
_, err = conn.Do("EXEC")
return err
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"DeleteIntervalActionById",
"(",
"id",
"string",
")",
"(",
"err",
"error",
")",
"{",
"check",
",",
"err",
":=",
"c",
".",
"IntervalActionById",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"db",
".",
"ErrNotFound",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n\n",
"action",
":=",
"models",
".",
"NewIntervalAction",
"(",
"check",
")",
"\n",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"_",
"=",
"conn",
".",
"Send",
"(",
"\"",
"\"",
")",
"\n",
"deleteObject",
"(",
"action",
",",
"id",
",",
"conn",
")",
"\n\n",
"_",
",",
"err",
"=",
"conn",
".",
"Do",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] |
// Remove schedule interval action by id
|
[
"Remove",
"schedule",
"interval",
"action",
"by",
"id"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/scheduler.go#L392-L411
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/data.go
|
EventCount
|
func (c *Client) EventCount() (count int, err error) {
conn := c.Pool.Get()
defer conn.Close()
count, err = redis.Int(conn.Do("ZCARD", db.EventsCollection))
if err != nil {
return 0, err
}
return count, nil
}
|
go
|
func (c *Client) EventCount() (count int, err error) {
conn := c.Pool.Get()
defer conn.Close()
count, err = redis.Int(conn.Do("ZCARD", db.EventsCollection))
if err != nil {
return 0, err
}
return count, nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"EventCount",
"(",
")",
"(",
"count",
"int",
",",
"err",
"error",
")",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"count",
",",
"err",
"=",
"redis",
".",
"Int",
"(",
"conn",
".",
"Do",
"(",
"\"",
"\"",
",",
"db",
".",
"EventsCollection",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"count",
",",
"nil",
"\n",
"}"
] |
// Get the number of events in Core Data
|
[
"Get",
"the",
"number",
"of",
"events",
"in",
"Core",
"Data"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L135-L145
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/data.go
|
DeleteEventById
|
func (c *Client) DeleteEventById(id string) (err error) {
conn := c.Pool.Get()
defer conn.Close()
err = deleteEvent(conn, id)
if err != nil {
if err == redis.ErrNil {
return db.ErrNotFound
}
return err
}
return nil
}
|
go
|
func (c *Client) DeleteEventById(id string) (err error) {
conn := c.Pool.Get()
defer conn.Close()
err = deleteEvent(conn, id)
if err != nil {
if err == redis.ErrNil {
return db.ErrNotFound
}
return err
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"DeleteEventById",
"(",
"id",
"string",
")",
"(",
"err",
"error",
")",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"err",
"=",
"deleteEvent",
"(",
"conn",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"redis",
".",
"ErrNil",
"{",
"return",
"db",
".",
"ErrNotFound",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Delete an event by ID. Readings are not deleted as this should be handled by the contract layer
// 404 - Event not found
// 503 - Unexpected problems
|
[
"Delete",
"an",
"event",
"by",
"ID",
".",
"Readings",
"are",
"not",
"deleted",
"as",
"this",
"should",
"be",
"handled",
"by",
"the",
"contract",
"layer",
"404",
"-",
"Event",
"not",
"found",
"503",
"-",
"Unexpected",
"problems"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L163-L176
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/data.go
|
ScrubAllEvents
|
func (c *Client) ScrubAllEvents() (err error) {
conn := c.Pool.Get()
defer conn.Close()
err = unlinkCollection(conn, db.EventsCollection)
if err != nil {
return err
}
err = unlinkCollection(conn, db.ReadingsCollection)
if err != nil {
return err
}
return nil
}
|
go
|
func (c *Client) ScrubAllEvents() (err error) {
conn := c.Pool.Get()
defer conn.Close()
err = unlinkCollection(conn, db.EventsCollection)
if err != nil {
return err
}
err = unlinkCollection(conn, db.ReadingsCollection)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"ScrubAllEvents",
"(",
")",
"(",
"err",
"error",
")",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"err",
"=",
"unlinkCollection",
"(",
"conn",
",",
"db",
".",
"EventsCollection",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"unlinkCollection",
"(",
"conn",
",",
"db",
".",
"ReadingsCollection",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Delete all readings and events
|
[
"Delete",
"all",
"readings",
"and",
"events"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L297-L312
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/data.go
|
AddReading
|
func (c *Client) AddReading(r contract.Reading) (id string, err error) {
conn := c.Pool.Get()
defer conn.Close()
if r.Id != "" {
_, err = uuid.Parse(r.Id)
if err != nil {
return "", db.ErrInvalidObjectId
}
}
return addReading(conn, true, r)
}
|
go
|
func (c *Client) AddReading(r contract.Reading) (id string, err error) {
conn := c.Pool.Get()
defer conn.Close()
if r.Id != "" {
_, err = uuid.Parse(r.Id)
if err != nil {
return "", db.ErrInvalidObjectId
}
}
return addReading(conn, true, r)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"AddReading",
"(",
"r",
"contract",
".",
"Reading",
")",
"(",
"id",
"string",
",",
"err",
"error",
")",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"if",
"r",
".",
"Id",
"!=",
"\"",
"\"",
"{",
"_",
",",
"err",
"=",
"uuid",
".",
"Parse",
"(",
"r",
".",
"Id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"db",
".",
"ErrInvalidObjectId",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"addReading",
"(",
"conn",
",",
"true",
",",
"r",
")",
"\n",
"}"
] |
// Post a new reading
// Check if valuedescriptor exists in the database
|
[
"Post",
"a",
"new",
"reading",
"Check",
"if",
"valuedescriptor",
"exists",
"in",
"the",
"database"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L338-L349
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/data.go
|
ReadingCount
|
func (c *Client) ReadingCount() (int, error) {
conn := c.Pool.Get()
defer conn.Close()
count, err := redis.Int(conn.Do("ZCARD", db.ReadingsCollection))
if err != nil {
return 0, err
}
return count, nil
}
|
go
|
func (c *Client) ReadingCount() (int, error) {
conn := c.Pool.Get()
defer conn.Close()
count, err := redis.Int(conn.Do("ZCARD", db.ReadingsCollection))
if err != nil {
return 0, err
}
return count, nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"ReadingCount",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"count",
",",
"err",
":=",
"redis",
".",
"Int",
"(",
"conn",
".",
"Do",
"(",
"\"",
"\"",
",",
"db",
".",
"ReadingsCollection",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"count",
",",
"nil",
"\n",
"}"
] |
// Get the number of readings in core data
|
[
"Get",
"the",
"number",
"of",
"readings",
"in",
"core",
"data"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L407-L417
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/data.go
|
ReadingsByCreationTime
|
func (c *Client) ReadingsByCreationTime(start, end int64, limit int) (readings []contract.Reading, err error) {
conn := c.Pool.Get()
defer conn.Close()
if limit == 0 {
return readings, nil
}
objects, err := getObjectsByScore(conn, db.ReadingsCollection+":created", start, end, limit)
if err != nil {
return readings, err
}
readings = make([]contract.Reading, len(objects))
for i, in := range objects {
err = unmarshalObject(in, &readings[i])
if err != nil {
return readings, err
}
}
return readings, nil
}
|
go
|
func (c *Client) ReadingsByCreationTime(start, end int64, limit int) (readings []contract.Reading, err error) {
conn := c.Pool.Get()
defer conn.Close()
if limit == 0 {
return readings, nil
}
objects, err := getObjectsByScore(conn, db.ReadingsCollection+":created", start, end, limit)
if err != nil {
return readings, err
}
readings = make([]contract.Reading, len(objects))
for i, in := range objects {
err = unmarshalObject(in, &readings[i])
if err != nil {
return readings, err
}
}
return readings, nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"ReadingsByCreationTime",
"(",
"start",
",",
"end",
"int64",
",",
"limit",
"int",
")",
"(",
"readings",
"[",
"]",
"contract",
".",
"Reading",
",",
"err",
"error",
")",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"if",
"limit",
"==",
"0",
"{",
"return",
"readings",
",",
"nil",
"\n",
"}",
"\n\n",
"objects",
",",
"err",
":=",
"getObjectsByScore",
"(",
"conn",
",",
"db",
".",
"ReadingsCollection",
"+",
"\"",
"\"",
",",
"start",
",",
"end",
",",
"limit",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"readings",
",",
"err",
"\n",
"}",
"\n\n",
"readings",
"=",
"make",
"(",
"[",
"]",
"contract",
".",
"Reading",
",",
"len",
"(",
"objects",
")",
")",
"\n",
"for",
"i",
",",
"in",
":=",
"range",
"objects",
"{",
"err",
"=",
"unmarshalObject",
"(",
"in",
",",
"&",
"readings",
"[",
"i",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"readings",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"readings",
",",
"nil",
"\n",
"}"
] |
// Return a list of readings whos created time is between the start and end times
|
[
"Return",
"a",
"list",
"of",
"readings",
"whos",
"created",
"time",
"is",
"between",
"the",
"start",
"and",
"end",
"times"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L520-L542
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/data.go
|
DeleteValueDescriptorById
|
func (c *Client) DeleteValueDescriptorById(id string) error {
conn := c.Pool.Get()
defer conn.Close()
err := deleteValue(conn, id)
if err != nil {
if err == redis.ErrNil {
return db.ErrNotFound
}
return err
}
return nil
}
|
go
|
func (c *Client) DeleteValueDescriptorById(id string) error {
conn := c.Pool.Get()
defer conn.Close()
err := deleteValue(conn, id)
if err != nil {
if err == redis.ErrNil {
return db.ErrNotFound
}
return err
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"DeleteValueDescriptorById",
"(",
"id",
"string",
")",
"error",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"err",
":=",
"deleteValue",
"(",
"conn",
",",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"redis",
".",
"ErrNil",
"{",
"return",
"db",
".",
"ErrNotFound",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Delete a value descriptor based on the ID
|
[
"Delete",
"a",
"value",
"descriptor",
"based",
"on",
"the",
"ID"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L618-L630
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/data.go
|
ValueDescriptorByName
|
func (c *Client) ValueDescriptorByName(name string) (value contract.ValueDescriptor, err error) {
conn := c.Pool.Get()
defer conn.Close()
value, err = valueByName(conn, name)
if err != nil {
if err == redis.ErrNil {
return value, db.ErrNotFound
}
return value, err
}
return value, nil
}
|
go
|
func (c *Client) ValueDescriptorByName(name string) (value contract.ValueDescriptor, err error) {
conn := c.Pool.Get()
defer conn.Close()
value, err = valueByName(conn, name)
if err != nil {
if err == redis.ErrNil {
return value, db.ErrNotFound
}
return value, err
}
return value, nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"ValueDescriptorByName",
"(",
"name",
"string",
")",
"(",
"value",
"contract",
".",
"ValueDescriptor",
",",
"err",
"error",
")",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"value",
",",
"err",
"=",
"valueByName",
"(",
"conn",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"redis",
".",
"ErrNil",
"{",
"return",
"value",
",",
"db",
".",
"ErrNotFound",
"\n",
"}",
"\n",
"return",
"value",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"value",
",",
"nil",
"\n",
"}"
] |
// Return a value descriptor based on the name
|
[
"Return",
"a",
"value",
"descriptor",
"based",
"on",
"the",
"name"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L633-L646
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/data.go
|
ValueDescriptorsByName
|
func (c *Client) ValueDescriptorsByName(names []string) (values []contract.ValueDescriptor, err error) {
conn := c.Pool.Get()
defer conn.Close()
for _, name := range names {
value, err := valueByName(conn, name)
if err != nil && err != redis.ErrNil {
return nil, err
}
if err == nil {
values = append(values, value)
}
}
return values, nil
}
|
go
|
func (c *Client) ValueDescriptorsByName(names []string) (values []contract.ValueDescriptor, err error) {
conn := c.Pool.Get()
defer conn.Close()
for _, name := range names {
value, err := valueByName(conn, name)
if err != nil && err != redis.ErrNil {
return nil, err
}
if err == nil {
values = append(values, value)
}
}
return values, nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"ValueDescriptorsByName",
"(",
"names",
"[",
"]",
"string",
")",
"(",
"values",
"[",
"]",
"contract",
".",
"ValueDescriptor",
",",
"err",
"error",
")",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"for",
"_",
",",
"name",
":=",
"range",
"names",
"{",
"value",
",",
"err",
":=",
"valueByName",
"(",
"conn",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"redis",
".",
"ErrNil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
"==",
"nil",
"{",
"values",
"=",
"append",
"(",
"values",
",",
"value",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"values",
",",
"nil",
"\n",
"}"
] |
// Return value descriptors based on the names
|
[
"Return",
"value",
"descriptors",
"based",
"on",
"the",
"names"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L649-L665
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/data.go
|
ValueDescriptorsByUomLabel
|
func (c *Client) ValueDescriptorsByUomLabel(uomLabel string) (values []contract.ValueDescriptor, err error) {
conn := c.Pool.Get()
defer conn.Close()
objects, err := getObjectsByRange(conn, db.ValueDescriptorCollection+":uomlabel:"+uomLabel, 0, -1)
if err != nil {
if err != redis.ErrNil {
return values, err
}
}
values = make([]contract.ValueDescriptor, len(objects))
for i, in := range objects {
err = unmarshalObject(in, &values[i])
if err != nil {
return values, err
}
}
return values, nil
}
|
go
|
func (c *Client) ValueDescriptorsByUomLabel(uomLabel string) (values []contract.ValueDescriptor, err error) {
conn := c.Pool.Get()
defer conn.Close()
objects, err := getObjectsByRange(conn, db.ValueDescriptorCollection+":uomlabel:"+uomLabel, 0, -1)
if err != nil {
if err != redis.ErrNil {
return values, err
}
}
values = make([]contract.ValueDescriptor, len(objects))
for i, in := range objects {
err = unmarshalObject(in, &values[i])
if err != nil {
return values, err
}
}
return values, nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"ValueDescriptorsByUomLabel",
"(",
"uomLabel",
"string",
")",
"(",
"values",
"[",
"]",
"contract",
".",
"ValueDescriptor",
",",
"err",
"error",
")",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"objects",
",",
"err",
":=",
"getObjectsByRange",
"(",
"conn",
",",
"db",
".",
"ValueDescriptorCollection",
"+",
"\"",
"\"",
"+",
"uomLabel",
",",
"0",
",",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"!=",
"redis",
".",
"ErrNil",
"{",
"return",
"values",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"values",
"=",
"make",
"(",
"[",
"]",
"contract",
".",
"ValueDescriptor",
",",
"len",
"(",
"objects",
")",
")",
"\n",
"for",
"i",
",",
"in",
":=",
"range",
"objects",
"{",
"err",
"=",
"unmarshalObject",
"(",
"in",
",",
"&",
"values",
"[",
"i",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"values",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"values",
",",
"nil",
"\n",
"}"
] |
// Return value descriptors based on the unit of measure label
|
[
"Return",
"value",
"descriptors",
"based",
"on",
"the",
"unit",
"of",
"measure",
"label"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L687-L707
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/data.go
|
ScrubAllValueDescriptors
|
func (c *Client) ScrubAllValueDescriptors() error {
conn := c.Pool.Get()
defer conn.Close()
err := unlinkCollection(conn, db.ValueDescriptorCollection)
if err != nil {
return err
}
return nil
}
|
go
|
func (c *Client) ScrubAllValueDescriptors() error {
conn := c.Pool.Get()
defer conn.Close()
err := unlinkCollection(conn, db.ValueDescriptorCollection)
if err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"ScrubAllValueDescriptors",
"(",
")",
"error",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"err",
":=",
"unlinkCollection",
"(",
"conn",
",",
"db",
".",
"ValueDescriptorCollection",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Delete all value descriptors
|
[
"Delete",
"all",
"value",
"descriptors"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L756-L766
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/data.go
|
addReading
|
func addReading(conn redis.Conn, tx bool, r contract.Reading) (id string, err error) {
if r.Created == 0 {
r.Created = db.MakeTimestamp()
}
if r.Id == "" {
r.Id = uuid.New().String()
}
m, err := marshalObject(r)
if err != nil {
return r.Id, err
}
if tx {
_ = conn.Send("MULTI")
}
_ = conn.Send("SET", r.Id, m)
_ = conn.Send("ZADD", db.ReadingsCollection, 0, r.Id)
_ = conn.Send("ZADD", db.ReadingsCollection+":created", r.Created, r.Id)
_ = conn.Send("ZADD", db.ReadingsCollection+":device:"+r.Device, r.Created, r.Id)
_ = conn.Send("ZADD", db.ReadingsCollection+":name:"+r.Name, r.Created, r.Id)
if tx {
_, err = conn.Do("EXEC")
}
return r.Id, err
}
|
go
|
func addReading(conn redis.Conn, tx bool, r contract.Reading) (id string, err error) {
if r.Created == 0 {
r.Created = db.MakeTimestamp()
}
if r.Id == "" {
r.Id = uuid.New().String()
}
m, err := marshalObject(r)
if err != nil {
return r.Id, err
}
if tx {
_ = conn.Send("MULTI")
}
_ = conn.Send("SET", r.Id, m)
_ = conn.Send("ZADD", db.ReadingsCollection, 0, r.Id)
_ = conn.Send("ZADD", db.ReadingsCollection+":created", r.Created, r.Id)
_ = conn.Send("ZADD", db.ReadingsCollection+":device:"+r.Device, r.Created, r.Id)
_ = conn.Send("ZADD", db.ReadingsCollection+":name:"+r.Name, r.Created, r.Id)
if tx {
_, err = conn.Do("EXEC")
}
return r.Id, err
}
|
[
"func",
"addReading",
"(",
"conn",
"redis",
".",
"Conn",
",",
"tx",
"bool",
",",
"r",
"contract",
".",
"Reading",
")",
"(",
"id",
"string",
",",
"err",
"error",
")",
"{",
"if",
"r",
".",
"Created",
"==",
"0",
"{",
"r",
".",
"Created",
"=",
"db",
".",
"MakeTimestamp",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"r",
".",
"Id",
"==",
"\"",
"\"",
"{",
"r",
".",
"Id",
"=",
"uuid",
".",
"New",
"(",
")",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"m",
",",
"err",
":=",
"marshalObject",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"r",
".",
"Id",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"tx",
"{",
"_",
"=",
"conn",
".",
"Send",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"_",
"=",
"conn",
".",
"Send",
"(",
"\"",
"\"",
",",
"r",
".",
"Id",
",",
"m",
")",
"\n",
"_",
"=",
"conn",
".",
"Send",
"(",
"\"",
"\"",
",",
"db",
".",
"ReadingsCollection",
",",
"0",
",",
"r",
".",
"Id",
")",
"\n",
"_",
"=",
"conn",
".",
"Send",
"(",
"\"",
"\"",
",",
"db",
".",
"ReadingsCollection",
"+",
"\"",
"\"",
",",
"r",
".",
"Created",
",",
"r",
".",
"Id",
")",
"\n",
"_",
"=",
"conn",
".",
"Send",
"(",
"\"",
"\"",
",",
"db",
".",
"ReadingsCollection",
"+",
"\"",
"\"",
"+",
"r",
".",
"Device",
",",
"r",
".",
"Created",
",",
"r",
".",
"Id",
")",
"\n",
"_",
"=",
"conn",
".",
"Send",
"(",
"\"",
"\"",
",",
"db",
".",
"ReadingsCollection",
"+",
"\"",
"\"",
"+",
"r",
".",
"Name",
",",
"r",
".",
"Created",
",",
"r",
".",
"Id",
")",
"\n",
"if",
"tx",
"{",
"_",
",",
"err",
"=",
"conn",
".",
"Do",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"r",
".",
"Id",
",",
"err",
"\n",
"}"
] |
// Add a reading to the database
|
[
"Add",
"a",
"reading",
"to",
"the",
"database"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/data.go#L856-L883
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/db/redis/metadata.go
|
DeleteCommandById
|
func (c *Client) DeleteCommandById(id string) error {
conn := c.Pool.Get()
defer conn.Close()
// TODO: ??? Check if the command is still in use by device profiles
return deleteCommand(conn, id)
}
|
go
|
func (c *Client) DeleteCommandById(id string) error {
conn := c.Pool.Get()
defer conn.Close()
// TODO: ??? Check if the command is still in use by device profiles
return deleteCommand(conn, id)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"DeleteCommandById",
"(",
"id",
"string",
")",
"error",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"// TODO: ??? Check if the command is still in use by device profiles",
"return",
"deleteCommand",
"(",
"conn",
",",
"id",
")",
"\n",
"}"
] |
// Delete the command by ID
|
[
"Delete",
"the",
"command",
"by",
"ID"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/metadata.go#L1250-L1257
|
train
|
edgexfoundry/edgex-go
|
internal/export/distro/format.go
|
newAzureMessage
|
func newAzureMessage() (*AzureMessage, error) {
msg := &AzureMessage{
Ack: none,
Properties: make(map[string]string),
Created: time.Now(),
}
id := uuid.New()
msg.ID = id.String()
correlationID := uuid.New()
msg.CorrelationID = correlationID.String()
return msg, nil
}
|
go
|
func newAzureMessage() (*AzureMessage, error) {
msg := &AzureMessage{
Ack: none,
Properties: make(map[string]string),
Created: time.Now(),
}
id := uuid.New()
msg.ID = id.String()
correlationID := uuid.New()
msg.CorrelationID = correlationID.String()
return msg, nil
}
|
[
"func",
"newAzureMessage",
"(",
")",
"(",
"*",
"AzureMessage",
",",
"error",
")",
"{",
"msg",
":=",
"&",
"AzureMessage",
"{",
"Ack",
":",
"none",
",",
"Properties",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
",",
"Created",
":",
"time",
".",
"Now",
"(",
")",
",",
"}",
"\n\n",
"id",
":=",
"uuid",
".",
"New",
"(",
")",
"\n",
"msg",
".",
"ID",
"=",
"id",
".",
"String",
"(",
")",
"\n\n",
"correlationID",
":=",
"uuid",
".",
"New",
"(",
")",
"\n",
"msg",
".",
"CorrelationID",
"=",
"correlationID",
".",
"String",
"(",
")",
"\n\n",
"return",
"msg",
",",
"nil",
"\n",
"}"
] |
// newAzureMessage creates a new Azure message and sets
// Body and default fields values.
|
[
"newAzureMessage",
"creates",
"a",
"new",
"Azure",
"message",
"and",
"sets",
"Body",
"and",
"default",
"fields",
"values",
"."
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/distro/format.go#L117-L131
|
train
|
edgexfoundry/edgex-go
|
internal/export/distro/format.go
|
AddProperty
|
func (am *AzureMessage) AddProperty(key, value string) error {
am.Properties[key] = value
return nil
}
|
go
|
func (am *AzureMessage) AddProperty(key, value string) error {
am.Properties[key] = value
return nil
}
|
[
"func",
"(",
"am",
"*",
"AzureMessage",
")",
"AddProperty",
"(",
"key",
",",
"value",
"string",
")",
"error",
"{",
"am",
".",
"Properties",
"[",
"key",
"]",
"=",
"value",
"\n",
"return",
"nil",
"\n",
"}"
] |
// AddProperty method ads property performing key check.
|
[
"AddProperty",
"method",
"ads",
"property",
"performing",
"key",
"check",
"."
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/distro/format.go#L134-L137
|
train
|
edgexfoundry/edgex-go
|
internal/export/distro/format.go
|
newBIoTMessage
|
func newBIoTMessage() (*BIoTMessage, error) {
msg := &BIoTMessage{
Severity: "1",
MsgType: "Q",
}
id := uuid.New()
msg.MsgId = id.String()
return msg, nil
}
|
go
|
func newBIoTMessage() (*BIoTMessage, error) {
msg := &BIoTMessage{
Severity: "1",
MsgType: "Q",
}
id := uuid.New()
msg.MsgId = id.String()
return msg, nil
}
|
[
"func",
"newBIoTMessage",
"(",
")",
"(",
"*",
"BIoTMessage",
",",
"error",
")",
"{",
"msg",
":=",
"&",
"BIoTMessage",
"{",
"Severity",
":",
"\"",
"\"",
",",
"MsgType",
":",
"\"",
"\"",
",",
"}",
"\n\n",
"id",
":=",
"uuid",
".",
"New",
"(",
")",
"\n",
"msg",
".",
"MsgId",
"=",
"id",
".",
"String",
"(",
")",
"\n\n",
"return",
"msg",
",",
"nil",
"\n",
"}"
] |
// newBIoTMessage creates a new Brightics IoT message and sets
// Body and default fields values.
|
[
"newBIoTMessage",
"creates",
"a",
"new",
"Brightics",
"IoT",
"message",
"and",
"sets",
"Body",
"and",
"default",
"fields",
"values",
"."
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/distro/format.go#L239-L249
|
train
|
edgexfoundry/edgex-go
|
internal/export/distro/iotcore.go
|
newIoTCoreSender
|
func newIoTCoreSender(addr models.Addressable) sender {
protocol := strings.ToLower(addr.Protocol)
broker := fmt.Sprintf("%s%s", addr.GetBaseURL(), addr.Path)
deviceID := extractDeviceID(addr.Publisher)
opts := MQTT.NewClientOptions()
opts.AddBroker(broker)
opts.SetClientID(addr.Publisher)
opts.SetUsername(addr.User)
opts.SetPassword(addr.Password)
opts.SetAutoReconnect(false)
if validateProtocol(protocol) {
c := Configuration.Certificates["MQTTS"]
cert, err := tls.LoadX509KeyPair(c.Cert, c.Key)
if err != nil {
LoggingClient.Error("Failed loading x509 data")
return nil
}
opts.SetTLSConfig(&tls.Config{
ClientCAs: nil,
InsecureSkipVerify: true,
Certificates: []tls.Certificate{cert},
})
}
if addr.Topic == "" {
addr.Topic = fmt.Sprintf("/devices/%s/events", deviceID)
}
return &mqttSender{
client: MQTT.NewClient(opts),
topic: addr.Topic,
}
}
|
go
|
func newIoTCoreSender(addr models.Addressable) sender {
protocol := strings.ToLower(addr.Protocol)
broker := fmt.Sprintf("%s%s", addr.GetBaseURL(), addr.Path)
deviceID := extractDeviceID(addr.Publisher)
opts := MQTT.NewClientOptions()
opts.AddBroker(broker)
opts.SetClientID(addr.Publisher)
opts.SetUsername(addr.User)
opts.SetPassword(addr.Password)
opts.SetAutoReconnect(false)
if validateProtocol(protocol) {
c := Configuration.Certificates["MQTTS"]
cert, err := tls.LoadX509KeyPair(c.Cert, c.Key)
if err != nil {
LoggingClient.Error("Failed loading x509 data")
return nil
}
opts.SetTLSConfig(&tls.Config{
ClientCAs: nil,
InsecureSkipVerify: true,
Certificates: []tls.Certificate{cert},
})
}
if addr.Topic == "" {
addr.Topic = fmt.Sprintf("/devices/%s/events", deviceID)
}
return &mqttSender{
client: MQTT.NewClient(opts),
topic: addr.Topic,
}
}
|
[
"func",
"newIoTCoreSender",
"(",
"addr",
"models",
".",
"Addressable",
")",
"sender",
"{",
"protocol",
":=",
"strings",
".",
"ToLower",
"(",
"addr",
".",
"Protocol",
")",
"\n",
"broker",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"addr",
".",
"GetBaseURL",
"(",
")",
",",
"addr",
".",
"Path",
")",
"\n",
"deviceID",
":=",
"extractDeviceID",
"(",
"addr",
".",
"Publisher",
")",
"\n\n",
"opts",
":=",
"MQTT",
".",
"NewClientOptions",
"(",
")",
"\n",
"opts",
".",
"AddBroker",
"(",
"broker",
")",
"\n",
"opts",
".",
"SetClientID",
"(",
"addr",
".",
"Publisher",
")",
"\n",
"opts",
".",
"SetUsername",
"(",
"addr",
".",
"User",
")",
"\n",
"opts",
".",
"SetPassword",
"(",
"addr",
".",
"Password",
")",
"\n",
"opts",
".",
"SetAutoReconnect",
"(",
"false",
")",
"\n\n",
"if",
"validateProtocol",
"(",
"protocol",
")",
"{",
"c",
":=",
"Configuration",
".",
"Certificates",
"[",
"\"",
"\"",
"]",
"\n",
"cert",
",",
"err",
":=",
"tls",
".",
"LoadX509KeyPair",
"(",
"c",
".",
"Cert",
",",
"c",
".",
"Key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"opts",
".",
"SetTLSConfig",
"(",
"&",
"tls",
".",
"Config",
"{",
"ClientCAs",
":",
"nil",
",",
"InsecureSkipVerify",
":",
"true",
",",
"Certificates",
":",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"cert",
"}",
",",
"}",
")",
"\n",
"}",
"\n\n",
"if",
"addr",
".",
"Topic",
"==",
"\"",
"\"",
"{",
"addr",
".",
"Topic",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"deviceID",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"mqttSender",
"{",
"client",
":",
"MQTT",
".",
"NewClient",
"(",
"opts",
")",
",",
"topic",
":",
"addr",
".",
"Topic",
",",
"}",
"\n",
"}"
] |
// newIoTCoreSender returns new Google IoT Core sender instance.
|
[
"newIoTCoreSender",
"returns",
"new",
"Google",
"IoT",
"Core",
"sender",
"instance",
"."
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/distro/iotcore.go#L32-L67
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/correlation/models/event.go
|
ToContract
|
func (e Event) ToContract() *contract.Event {
event := contract.Event{
ID: e.ID,
Pushed: e.Pushed,
Device: e.Device,
Created: e.Created,
Modified: e.Modified,
Origin: e.Origin,
}
for _, r := range e.Readings {
event.Readings = append(event.Readings, r)
}
return &event
}
|
go
|
func (e Event) ToContract() *contract.Event {
event := contract.Event{
ID: e.ID,
Pushed: e.Pushed,
Device: e.Device,
Created: e.Created,
Modified: e.Modified,
Origin: e.Origin,
}
for _, r := range e.Readings {
event.Readings = append(event.Readings, r)
}
return &event
}
|
[
"func",
"(",
"e",
"Event",
")",
"ToContract",
"(",
")",
"*",
"contract",
".",
"Event",
"{",
"event",
":=",
"contract",
".",
"Event",
"{",
"ID",
":",
"e",
".",
"ID",
",",
"Pushed",
":",
"e",
".",
"Pushed",
",",
"Device",
":",
"e",
".",
"Device",
",",
"Created",
":",
"e",
".",
"Created",
",",
"Modified",
":",
"e",
".",
"Modified",
",",
"Origin",
":",
"e",
".",
"Origin",
",",
"}",
"\n\n",
"for",
"_",
",",
"r",
":=",
"range",
"e",
".",
"Readings",
"{",
"event",
".",
"Readings",
"=",
"append",
"(",
"event",
".",
"Readings",
",",
"r",
")",
"\n",
"}",
"\n",
"return",
"&",
"event",
"\n",
"}"
] |
// Returns an instance of just the public contract portion of the model Event.
// I don't like returning a pointer from this method but I have to in order to
// satisfy the Filter, Format interfaces.
|
[
"Returns",
"an",
"instance",
"of",
"just",
"the",
"public",
"contract",
"portion",
"of",
"the",
"model",
"Event",
".",
"I",
"don",
"t",
"like",
"returning",
"a",
"pointer",
"from",
"this",
"method",
"but",
"I",
"have",
"to",
"in",
"order",
"to",
"satisfy",
"the",
"Filter",
"Format",
"interfaces",
"."
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/correlation/models/event.go#L31-L45
|
train
|
edgexfoundry/edgex-go
|
internal/core/metadata/rest_device.go
|
updateDeviceFields
|
func updateDeviceFields(from models.Device, to *models.Device) error {
if (from.Service.String() != models.DeviceService{}.String()) {
// Check if the new service exists
// Try ID first
ds, err := dbClient.GetDeviceServiceById(from.Service.Id)
if err != nil {
// Then try name
ds, err = dbClient.GetDeviceServiceByName(from.Service.Name)
if err != nil {
return errors.New("Device service not found for updated device")
}
}
to.Service = ds
}
if (from.Profile.String() != models.DeviceProfile{}.String()) {
// Check if the new profile exists
// Try ID first
dp, err := dbClient.GetDeviceProfileById(from.Profile.Id)
if err != nil {
// Then try Name
dp, err = dbClient.GetDeviceProfileByName(from.Profile.Name)
if err != nil {
return errors.New("Device profile not found for updated device")
}
}
to.Profile = dp
}
if len(from.Protocols) > 0 {
to.Protocols = from.Protocols
}
if len(from.AutoEvents) > 0 {
to.AutoEvents = from.AutoEvents
}
if from.AdminState != "" {
to.AdminState = from.AdminState
}
if from.Description != "" {
to.Description = from.Description
}
if from.Labels != nil {
to.Labels = from.Labels
}
if from.LastConnected != 0 {
to.LastConnected = from.LastConnected
}
if from.LastReported != 0 {
to.LastReported = from.LastReported
}
if from.Location != nil {
to.Location = from.Location
}
if from.OperatingState != models.OperatingState("") {
to.OperatingState = from.OperatingState
}
if from.Origin != 0 {
to.Origin = from.Origin
}
if from.Name != "" {
to.Name = from.Name
// Check if the name is unique
checkD, err := dbClient.GetDeviceByName(from.Name)
if err != nil {
// A problem occurred accessing database
if err != db.ErrNotFound {
LoggingClient.Error(err.Error())
return err
}
}
// Found a device, make sure its the one we're trying to update
if err != db.ErrNotFound {
// Different IDs -> Name is not unique
if checkD.Id != to.Id {
err = errors.New("Duplicate name for Device")
LoggingClient.Error(err.Error())
return err
}
}
}
return nil
}
|
go
|
func updateDeviceFields(from models.Device, to *models.Device) error {
if (from.Service.String() != models.DeviceService{}.String()) {
// Check if the new service exists
// Try ID first
ds, err := dbClient.GetDeviceServiceById(from.Service.Id)
if err != nil {
// Then try name
ds, err = dbClient.GetDeviceServiceByName(from.Service.Name)
if err != nil {
return errors.New("Device service not found for updated device")
}
}
to.Service = ds
}
if (from.Profile.String() != models.DeviceProfile{}.String()) {
// Check if the new profile exists
// Try ID first
dp, err := dbClient.GetDeviceProfileById(from.Profile.Id)
if err != nil {
// Then try Name
dp, err = dbClient.GetDeviceProfileByName(from.Profile.Name)
if err != nil {
return errors.New("Device profile not found for updated device")
}
}
to.Profile = dp
}
if len(from.Protocols) > 0 {
to.Protocols = from.Protocols
}
if len(from.AutoEvents) > 0 {
to.AutoEvents = from.AutoEvents
}
if from.AdminState != "" {
to.AdminState = from.AdminState
}
if from.Description != "" {
to.Description = from.Description
}
if from.Labels != nil {
to.Labels = from.Labels
}
if from.LastConnected != 0 {
to.LastConnected = from.LastConnected
}
if from.LastReported != 0 {
to.LastReported = from.LastReported
}
if from.Location != nil {
to.Location = from.Location
}
if from.OperatingState != models.OperatingState("") {
to.OperatingState = from.OperatingState
}
if from.Origin != 0 {
to.Origin = from.Origin
}
if from.Name != "" {
to.Name = from.Name
// Check if the name is unique
checkD, err := dbClient.GetDeviceByName(from.Name)
if err != nil {
// A problem occurred accessing database
if err != db.ErrNotFound {
LoggingClient.Error(err.Error())
return err
}
}
// Found a device, make sure its the one we're trying to update
if err != db.ErrNotFound {
// Different IDs -> Name is not unique
if checkD.Id != to.Id {
err = errors.New("Duplicate name for Device")
LoggingClient.Error(err.Error())
return err
}
}
}
return nil
}
|
[
"func",
"updateDeviceFields",
"(",
"from",
"models",
".",
"Device",
",",
"to",
"*",
"models",
".",
"Device",
")",
"error",
"{",
"if",
"(",
"from",
".",
"Service",
".",
"String",
"(",
")",
"!=",
"models",
".",
"DeviceService",
"{",
"}",
".",
"String",
"(",
")",
")",
"{",
"// Check if the new service exists",
"// Try ID first",
"ds",
",",
"err",
":=",
"dbClient",
".",
"GetDeviceServiceById",
"(",
"from",
".",
"Service",
".",
"Id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Then try name",
"ds",
",",
"err",
"=",
"dbClient",
".",
"GetDeviceServiceByName",
"(",
"from",
".",
"Service",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"to",
".",
"Service",
"=",
"ds",
"\n",
"}",
"\n",
"if",
"(",
"from",
".",
"Profile",
".",
"String",
"(",
")",
"!=",
"models",
".",
"DeviceProfile",
"{",
"}",
".",
"String",
"(",
")",
")",
"{",
"// Check if the new profile exists",
"// Try ID first",
"dp",
",",
"err",
":=",
"dbClient",
".",
"GetDeviceProfileById",
"(",
"from",
".",
"Profile",
".",
"Id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Then try Name",
"dp",
",",
"err",
"=",
"dbClient",
".",
"GetDeviceProfileByName",
"(",
"from",
".",
"Profile",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"to",
".",
"Profile",
"=",
"dp",
"\n",
"}",
"\n",
"if",
"len",
"(",
"from",
".",
"Protocols",
")",
">",
"0",
"{",
"to",
".",
"Protocols",
"=",
"from",
".",
"Protocols",
"\n",
"}",
"\n",
"if",
"len",
"(",
"from",
".",
"AutoEvents",
")",
">",
"0",
"{",
"to",
".",
"AutoEvents",
"=",
"from",
".",
"AutoEvents",
"\n",
"}",
"\n",
"if",
"from",
".",
"AdminState",
"!=",
"\"",
"\"",
"{",
"to",
".",
"AdminState",
"=",
"from",
".",
"AdminState",
"\n",
"}",
"\n",
"if",
"from",
".",
"Description",
"!=",
"\"",
"\"",
"{",
"to",
".",
"Description",
"=",
"from",
".",
"Description",
"\n",
"}",
"\n",
"if",
"from",
".",
"Labels",
"!=",
"nil",
"{",
"to",
".",
"Labels",
"=",
"from",
".",
"Labels",
"\n",
"}",
"\n",
"if",
"from",
".",
"LastConnected",
"!=",
"0",
"{",
"to",
".",
"LastConnected",
"=",
"from",
".",
"LastConnected",
"\n",
"}",
"\n",
"if",
"from",
".",
"LastReported",
"!=",
"0",
"{",
"to",
".",
"LastReported",
"=",
"from",
".",
"LastReported",
"\n",
"}",
"\n",
"if",
"from",
".",
"Location",
"!=",
"nil",
"{",
"to",
".",
"Location",
"=",
"from",
".",
"Location",
"\n",
"}",
"\n",
"if",
"from",
".",
"OperatingState",
"!=",
"models",
".",
"OperatingState",
"(",
"\"",
"\"",
")",
"{",
"to",
".",
"OperatingState",
"=",
"from",
".",
"OperatingState",
"\n",
"}",
"\n",
"if",
"from",
".",
"Origin",
"!=",
"0",
"{",
"to",
".",
"Origin",
"=",
"from",
".",
"Origin",
"\n",
"}",
"\n",
"if",
"from",
".",
"Name",
"!=",
"\"",
"\"",
"{",
"to",
".",
"Name",
"=",
"from",
".",
"Name",
"\n\n",
"// Check if the name is unique",
"checkD",
",",
"err",
":=",
"dbClient",
".",
"GetDeviceByName",
"(",
"from",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// A problem occurred accessing database",
"if",
"err",
"!=",
"db",
".",
"ErrNotFound",
"{",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Found a device, make sure its the one we're trying to update",
"if",
"err",
"!=",
"db",
".",
"ErrNotFound",
"{",
"// Different IDs -> Name is not unique",
"if",
"checkD",
".",
"Id",
"!=",
"to",
".",
"Id",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Update the device fields
|
[
"Update",
"the",
"device",
"fields"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L176-L261
|
train
|
edgexfoundry/edgex-go
|
internal/core/metadata/rest_device.go
|
restGetDeviceByServiceName
|
func restGetDeviceByServiceName(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
sn, err := url.QueryUnescape(vars[SERVICENAME])
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
// Check if the device service exists
ds, err := dbClient.GetDeviceServiceByName(sn)
if err != nil {
if err == db.ErrNotFound {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
LoggingClient.Error(err.Error())
return
}
// Find devices by service ID now that you have the Service object (and therefor the ID)
res, err := dbClient.GetDevicesByServiceId(ds.Id)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
LoggingClient.Error(err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
}
|
go
|
func restGetDeviceByServiceName(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
sn, err := url.QueryUnescape(vars[SERVICENAME])
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
// Check if the device service exists
ds, err := dbClient.GetDeviceServiceByName(sn)
if err != nil {
if err == db.ErrNotFound {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
LoggingClient.Error(err.Error())
return
}
// Find devices by service ID now that you have the Service object (and therefor the ID)
res, err := dbClient.GetDevicesByServiceId(ds.Id)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
LoggingClient.Error(err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(res)
}
|
[
"func",
"restGetDeviceByServiceName",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"vars",
":=",
"mux",
".",
"Vars",
"(",
"r",
")",
"\n",
"sn",
",",
"err",
":=",
"url",
".",
"QueryUnescape",
"(",
"vars",
"[",
"SERVICENAME",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Check if the device service exists",
"ds",
",",
"err",
":=",
"dbClient",
".",
"GetDeviceServiceByName",
"(",
"sn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"db",
".",
"ErrNotFound",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"}",
"else",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"}",
"\n",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Find devices by service ID now that you have the Service object (and therefor the ID)",
"res",
",",
"err",
":=",
"dbClient",
".",
"GetDevicesByServiceId",
"(",
"ds",
".",
"Id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"json",
".",
"NewEncoder",
"(",
"w",
")",
".",
"Encode",
"(",
"res",
")",
"\n",
"}"
] |
// If the result array is empty, don't return http.NotFound, just return empty array
|
[
"If",
"the",
"result",
"array",
"is",
"empty",
"don",
"t",
"return",
"http",
".",
"NotFound",
"just",
"return",
"empty",
"array"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L338-L369
|
train
|
edgexfoundry/edgex-go
|
internal/core/metadata/rest_device.go
|
restCheckForDevice
|
func restCheckForDevice(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
token := vars[ID] //referring to this as "token" for now since the source variable is double purposed
//Check for name first since we're using that meaning by default.
dev, err := dbClient.GetDeviceByName(token)
if err != nil {
if err != db.ErrNotFound {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else {
LoggingClient.Debug(fmt.Sprintf("device %s %v", token, err))
}
}
//If lookup by name failed, see if we were passed the ID
if len(dev.Name) == 0 {
if dev, err = dbClient.GetDeviceById(token); err != nil {
LoggingClient.Error(err.Error())
if err == db.ErrNotFound {
http.Error(w, err.Error(), http.StatusNotFound)
} else if err == db.ErrInvalidObjectId {
http.Error(w, err.Error(), http.StatusBadRequest)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(dev)
}
|
go
|
func restCheckForDevice(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
token := vars[ID] //referring to this as "token" for now since the source variable is double purposed
//Check for name first since we're using that meaning by default.
dev, err := dbClient.GetDeviceByName(token)
if err != nil {
if err != db.ErrNotFound {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else {
LoggingClient.Debug(fmt.Sprintf("device %s %v", token, err))
}
}
//If lookup by name failed, see if we were passed the ID
if len(dev.Name) == 0 {
if dev, err = dbClient.GetDeviceById(token); err != nil {
LoggingClient.Error(err.Error())
if err == db.ErrNotFound {
http.Error(w, err.Error(), http.StatusNotFound)
} else if err == db.ErrInvalidObjectId {
http.Error(w, err.Error(), http.StatusBadRequest)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(dev)
}
|
[
"func",
"restCheckForDevice",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"vars",
":=",
"mux",
".",
"Vars",
"(",
"r",
")",
"\n",
"token",
":=",
"vars",
"[",
"ID",
"]",
"//referring to this as \"token\" for now since the source variable is double purposed",
"\n\n",
"//Check for name first since we're using that meaning by default.",
"dev",
",",
"err",
":=",
"dbClient",
".",
"GetDeviceByName",
"(",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"!=",
"db",
".",
"ErrNotFound",
"{",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"else",
"{",
"LoggingClient",
".",
"Debug",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"token",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"//If lookup by name failed, see if we were passed the ID",
"if",
"len",
"(",
"dev",
".",
"Name",
")",
"==",
"0",
"{",
"if",
"dev",
",",
"err",
"=",
"dbClient",
".",
"GetDeviceById",
"(",
"token",
")",
";",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"if",
"err",
"==",
"db",
".",
"ErrNotFound",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"}",
"else",
"if",
"err",
"==",
"db",
".",
"ErrInvalidObjectId",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"}",
"else",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"json",
".",
"NewEncoder",
"(",
"w",
")",
".",
"Encode",
"(",
"dev",
")",
"\n",
"}"
] |
//Shouldn't need "rest" in any of these methods. Adding it here for consistency right now.
|
[
"Shouldn",
"t",
"need",
"rest",
"in",
"any",
"of",
"these",
"methods",
".",
"Adding",
"it",
"here",
"for",
"consistency",
"right",
"now",
"."
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L423-L456
|
train
|
edgexfoundry/edgex-go
|
internal/core/metadata/rest_device.go
|
deleteDevice
|
func deleteDevice(d models.Device, w http.ResponseWriter, ctx context.Context) error {
if err := deleteAssociatedReportsForDevice(d, w); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
if err := dbClient.DeleteDeviceById(d.Id); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
// Notify Associates
if err := notifyDeviceAssociates(d, http.MethodDelete, ctx); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
}
|
go
|
func deleteDevice(d models.Device, w http.ResponseWriter, ctx context.Context) error {
if err := deleteAssociatedReportsForDevice(d, w); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
if err := dbClient.DeleteDeviceById(d.Id); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
// Notify Associates
if err := notifyDeviceAssociates(d, http.MethodDelete, ctx); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
}
|
[
"func",
"deleteDevice",
"(",
"d",
"models",
".",
"Device",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"if",
"err",
":=",
"deleteAssociatedReportsForDevice",
"(",
"d",
",",
"w",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"dbClient",
".",
"DeleteDeviceById",
"(",
"d",
".",
"Id",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Notify Associates",
"if",
"err",
":=",
"notifyDeviceAssociates",
"(",
"d",
",",
"http",
".",
"MethodDelete",
",",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Delete the device
|
[
"Delete",
"the",
"device"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L695-L713
|
train
|
edgexfoundry/edgex-go
|
internal/core/metadata/rest_device.go
|
deleteAssociatedReportsForDevice
|
func deleteAssociatedReportsForDevice(d models.Device, w http.ResponseWriter) error {
reports, err := dbClient.GetDeviceReportByDeviceName(d.Name)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
LoggingClient.Error(err.Error())
return err
}
// Delete the associated reports
for _, report := range reports {
if err := dbClient.DeleteDeviceReportById(report.Id); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
LoggingClient.Error(err.Error())
return err
}
notifyDeviceReportAssociates(report, http.MethodDelete)
}
return nil
}
|
go
|
func deleteAssociatedReportsForDevice(d models.Device, w http.ResponseWriter) error {
reports, err := dbClient.GetDeviceReportByDeviceName(d.Name)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
LoggingClient.Error(err.Error())
return err
}
// Delete the associated reports
for _, report := range reports {
if err := dbClient.DeleteDeviceReportById(report.Id); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
LoggingClient.Error(err.Error())
return err
}
notifyDeviceReportAssociates(report, http.MethodDelete)
}
return nil
}
|
[
"func",
"deleteAssociatedReportsForDevice",
"(",
"d",
"models",
".",
"Device",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"reports",
",",
"err",
":=",
"dbClient",
".",
"GetDeviceReportByDeviceName",
"(",
"d",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// Delete the associated reports",
"for",
"_",
",",
"report",
":=",
"range",
"reports",
"{",
"if",
"err",
":=",
"dbClient",
".",
"DeleteDeviceReportById",
"(",
"report",
".",
"Id",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"notifyDeviceReportAssociates",
"(",
"report",
",",
"http",
".",
"MethodDelete",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Delete the associated device reports for the device
|
[
"Delete",
"the",
"associated",
"device",
"reports",
"for",
"the",
"device"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L716-L735
|
train
|
edgexfoundry/edgex-go
|
internal/core/metadata/rest_device.go
|
setLastConnected
|
func setLastConnected(d models.Device, time int64, notify bool, w http.ResponseWriter, ctx context.Context) error {
d.LastConnected = time
if err := dbClient.UpdateDevice(d); err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
if notify {
notifyDeviceAssociates(d, http.MethodPut, ctx)
}
return nil
}
|
go
|
func setLastConnected(d models.Device, time int64, notify bool, w http.ResponseWriter, ctx context.Context) error {
d.LastConnected = time
if err := dbClient.UpdateDevice(d); err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
if notify {
notifyDeviceAssociates(d, http.MethodPut, ctx)
}
return nil
}
|
[
"func",
"setLastConnected",
"(",
"d",
"models",
".",
"Device",
",",
"time",
"int64",
",",
"notify",
"bool",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"d",
".",
"LastConnected",
"=",
"time",
"\n",
"if",
"err",
":=",
"dbClient",
".",
"UpdateDevice",
"(",
"d",
")",
";",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"notify",
"{",
"notifyDeviceAssociates",
"(",
"d",
",",
"http",
".",
"MethodPut",
",",
"ctx",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Update the last connected value for the device
|
[
"Update",
"the",
"last",
"connected",
"value",
"for",
"the",
"device"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L893-L906
|
train
|
edgexfoundry/edgex-go
|
internal/core/metadata/rest_device.go
|
notifyDeviceAssociates
|
func notifyDeviceAssociates(d models.Device, action string, ctx context.Context) error {
// Post the notification to the notifications service
postNotification(d.Name, action, ctx)
// Callback for device service
ds, err := dbClient.GetDeviceServiceById(d.Service.Id)
if err != nil {
LoggingClient.Error(err.Error())
return err
}
if err := notifyAssociates([]models.DeviceService{ds}, d.Id, action, models.DEVICE); err != nil {
LoggingClient.Error(err.Error())
return err
}
return nil
}
|
go
|
func notifyDeviceAssociates(d models.Device, action string, ctx context.Context) error {
// Post the notification to the notifications service
postNotification(d.Name, action, ctx)
// Callback for device service
ds, err := dbClient.GetDeviceServiceById(d.Service.Id)
if err != nil {
LoggingClient.Error(err.Error())
return err
}
if err := notifyAssociates([]models.DeviceService{ds}, d.Id, action, models.DEVICE); err != nil {
LoggingClient.Error(err.Error())
return err
}
return nil
}
|
[
"func",
"notifyDeviceAssociates",
"(",
"d",
"models",
".",
"Device",
",",
"action",
"string",
",",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"// Post the notification to the notifications service",
"postNotification",
"(",
"d",
".",
"Name",
",",
"action",
",",
"ctx",
")",
"\n\n",
"// Callback for device service",
"ds",
",",
"err",
":=",
"dbClient",
".",
"GetDeviceServiceById",
"(",
"d",
".",
"Service",
".",
"Id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"notifyAssociates",
"(",
"[",
"]",
"models",
".",
"DeviceService",
"{",
"ds",
"}",
",",
"d",
".",
"Id",
",",
"action",
",",
"models",
".",
"DEVICE",
")",
";",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Notify the associated device service for the device
|
[
"Notify",
"the",
"associated",
"device",
"service",
"for",
"the",
"device"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_device.go#L1101-L1117
|
train
|
edgexfoundry/edgex-go
|
internal/seed/config/init.go
|
Retry
|
func Retry(useProfile string, timeout int, wait *sync.WaitGroup, ch chan error) {
until := time.Now().Add(time.Millisecond * time.Duration(timeout))
for time.Now().Before(until) {
var err error
//When looping, only handle configuration if it hasn't already been set.
if Configuration == nil {
Configuration, err = initializeConfiguration(useProfile)
if err != nil {
ch <- err
} else {
// Setup Logging
logTarget := setLoggingTarget()
LoggingClient = logger.NewClient(internal.ConfigSeedServiceKey, Configuration.EnableRemoteLogging, logTarget, Configuration.LoggingLevel)
}
}
//Check to verify Registry connectivity
if Registry == nil {
Registry, err = initRegistryClient("")
if err != nil {
ch <- err
}
} else {
if !Registry.IsAlive() {
ch <- fmt.Errorf("Registry (%s) is not running", Configuration.Registry.Type)
} else {
break
}
}
time.Sleep(time.Second * time.Duration(1))
}
close(ch)
wait.Done()
return
}
|
go
|
func Retry(useProfile string, timeout int, wait *sync.WaitGroup, ch chan error) {
until := time.Now().Add(time.Millisecond * time.Duration(timeout))
for time.Now().Before(until) {
var err error
//When looping, only handle configuration if it hasn't already been set.
if Configuration == nil {
Configuration, err = initializeConfiguration(useProfile)
if err != nil {
ch <- err
} else {
// Setup Logging
logTarget := setLoggingTarget()
LoggingClient = logger.NewClient(internal.ConfigSeedServiceKey, Configuration.EnableRemoteLogging, logTarget, Configuration.LoggingLevel)
}
}
//Check to verify Registry connectivity
if Registry == nil {
Registry, err = initRegistryClient("")
if err != nil {
ch <- err
}
} else {
if !Registry.IsAlive() {
ch <- fmt.Errorf("Registry (%s) is not running", Configuration.Registry.Type)
} else {
break
}
}
time.Sleep(time.Second * time.Duration(1))
}
close(ch)
wait.Done()
return
}
|
[
"func",
"Retry",
"(",
"useProfile",
"string",
",",
"timeout",
"int",
",",
"wait",
"*",
"sync",
".",
"WaitGroup",
",",
"ch",
"chan",
"error",
")",
"{",
"until",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"time",
".",
"Millisecond",
"*",
"time",
".",
"Duration",
"(",
"timeout",
")",
")",
"\n",
"for",
"time",
".",
"Now",
"(",
")",
".",
"Before",
"(",
"until",
")",
"{",
"var",
"err",
"error",
"\n",
"//When looping, only handle configuration if it hasn't already been set.",
"if",
"Configuration",
"==",
"nil",
"{",
"Configuration",
",",
"err",
"=",
"initializeConfiguration",
"(",
"useProfile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ch",
"<-",
"err",
"\n",
"}",
"else",
"{",
"// Setup Logging",
"logTarget",
":=",
"setLoggingTarget",
"(",
")",
"\n",
"LoggingClient",
"=",
"logger",
".",
"NewClient",
"(",
"internal",
".",
"ConfigSeedServiceKey",
",",
"Configuration",
".",
"EnableRemoteLogging",
",",
"logTarget",
",",
"Configuration",
".",
"LoggingLevel",
")",
"\n",
"}",
"\n",
"}",
"\n",
"//Check to verify Registry connectivity",
"if",
"Registry",
"==",
"nil",
"{",
"Registry",
",",
"err",
"=",
"initRegistryClient",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"ch",
"<-",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"!",
"Registry",
".",
"IsAlive",
"(",
")",
"{",
"ch",
"<-",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"Configuration",
".",
"Registry",
".",
"Type",
")",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"time",
".",
"Sleep",
"(",
"time",
".",
"Second",
"*",
"time",
".",
"Duration",
"(",
"1",
")",
")",
"\n",
"}",
"\n",
"close",
"(",
"ch",
")",
"\n",
"wait",
".",
"Done",
"(",
")",
"\n\n",
"return",
"\n",
"}"
] |
// The purpose of Retry is different here than in other services. In this case, we use a retry in order
// to initialize the RegistryClient that will be used to write configuration information. Other services
// use Retry to read their information. Config-seed writes information.
|
[
"The",
"purpose",
"of",
"Retry",
"is",
"different",
"here",
"than",
"in",
"other",
"services",
".",
"In",
"this",
"case",
"we",
"use",
"a",
"retry",
"in",
"order",
"to",
"initialize",
"the",
"RegistryClient",
"that",
"will",
"be",
"used",
"to",
"write",
"configuration",
"information",
".",
"Other",
"services",
"use",
"Retry",
"to",
"read",
"their",
"information",
".",
"Config",
"-",
"seed",
"writes",
"information",
"."
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/seed/config/init.go#L40-L76
|
train
|
edgexfoundry/edgex-go
|
internal/seed/config/init.go
|
getBody
|
func getBody(resp *http.Response) ([]byte, error) {
body, err := ioutil.ReadAll(resp.Body)
return body, err
}
|
go
|
func getBody(resp *http.Response) ([]byte, error) {
body, err := ioutil.ReadAll(resp.Body)
return body, err
}
|
[
"func",
"getBody",
"(",
"resp",
"*",
"http",
".",
"Response",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n\n",
"return",
"body",
",",
"err",
"\n",
"}"
] |
// Helper method to get the body from the response after making the request
|
[
"Helper",
"method",
"to",
"get",
"the",
"body",
"from",
"the",
"response",
"after",
"making",
"the",
"request"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/seed/config/init.go#L115-L119
|
train
|
edgexfoundry/edgex-go
|
internal/support/scheduler/loader.go
|
LoadScheduler
|
func LoadScheduler() error {
// ensure maps are clean
clearMaps()
// ensure queue is empty
clearQueue()
LoggingClient.Info("loading intervals, interval actions ...")
// load data from support-scheduler database
err := loadSupportSchedulerDBInformation()
if err != nil {
LoggingClient.Error("failed to load information from support-scheduler:" + err.Error())
return err
}
// load config intervals
errLCI := loadConfigIntervals()
if errLCI != nil {
LoggingClient.Error("failed to load scheduler config data:" + errLCI.Error())
return errLCI
}
// load config interval actions
errLCA := loadConfigIntervalActions()
if errLCA != nil {
LoggingClient.Error("failed to load interval actions config data:" + errLCA.Error())
return errLCA
}
LoggingClient.Info("finished loading intervals, interval actions")
return nil
}
|
go
|
func LoadScheduler() error {
// ensure maps are clean
clearMaps()
// ensure queue is empty
clearQueue()
LoggingClient.Info("loading intervals, interval actions ...")
// load data from support-scheduler database
err := loadSupportSchedulerDBInformation()
if err != nil {
LoggingClient.Error("failed to load information from support-scheduler:" + err.Error())
return err
}
// load config intervals
errLCI := loadConfigIntervals()
if errLCI != nil {
LoggingClient.Error("failed to load scheduler config data:" + errLCI.Error())
return errLCI
}
// load config interval actions
errLCA := loadConfigIntervalActions()
if errLCA != nil {
LoggingClient.Error("failed to load interval actions config data:" + errLCA.Error())
return errLCA
}
LoggingClient.Info("finished loading intervals, interval actions")
return nil
}
|
[
"func",
"LoadScheduler",
"(",
")",
"error",
"{",
"// ensure maps are clean",
"clearMaps",
"(",
")",
"\n\n",
"// ensure queue is empty",
"clearQueue",
"(",
")",
"\n\n",
"LoggingClient",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"// load data from support-scheduler database",
"err",
":=",
"loadSupportSchedulerDBInformation",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// load config intervals",
"errLCI",
":=",
"loadConfigIntervals",
"(",
")",
"\n",
"if",
"errLCI",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"errLCI",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"errLCI",
"\n",
"}",
"\n\n",
"// load config interval actions",
"errLCA",
":=",
"loadConfigIntervalActions",
"(",
")",
"\n",
"if",
"errLCA",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"errLCA",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"errLCA",
"\n",
"}",
"\n\n",
"LoggingClient",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Utility function for adding configured locally intervals and scheduled events
|
[
"Utility",
"function",
"for",
"adding",
"configured",
"locally",
"intervals",
"and",
"scheduled",
"events"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L21-L55
|
train
|
edgexfoundry/edgex-go
|
internal/support/scheduler/loader.go
|
getSchedulerDBIntervals
|
func getSchedulerDBIntervals() ([]contract.Interval, error) {
var err error
var intervals []contract.Interval
intervals, err = dbClient.Intervals()
if err != nil {
LoggingClient.Error("failed connecting to metadata and retrieving intervals:" + err.Error())
return intervals, err
}
if intervals != nil {
LoggingClient.Debug("successfully queried support-scheduler intervals...")
for _, v := range intervals {
LoggingClient.Debug("found interval", "name", v.Name, "id", v.ID, "start", v.Start)
}
}
return intervals, nil
}
|
go
|
func getSchedulerDBIntervals() ([]contract.Interval, error) {
var err error
var intervals []contract.Interval
intervals, err = dbClient.Intervals()
if err != nil {
LoggingClient.Error("failed connecting to metadata and retrieving intervals:" + err.Error())
return intervals, err
}
if intervals != nil {
LoggingClient.Debug("successfully queried support-scheduler intervals...")
for _, v := range intervals {
LoggingClient.Debug("found interval", "name", v.Name, "id", v.ID, "start", v.Start)
}
}
return intervals, nil
}
|
[
"func",
"getSchedulerDBIntervals",
"(",
")",
"(",
"[",
"]",
"contract",
".",
"Interval",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"var",
"intervals",
"[",
"]",
"contract",
".",
"Interval",
"\n\n",
"intervals",
",",
"err",
"=",
"dbClient",
".",
"Intervals",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"intervals",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"intervals",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"intervals",
"{",
"LoggingClient",
".",
"Debug",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"v",
".",
"Name",
",",
"\"",
"\"",
",",
"v",
".",
"ID",
",",
"\"",
"\"",
",",
"v",
".",
"Start",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"intervals",
",",
"nil",
"\n",
"}"
] |
// Query support-scheduler scheduler client get intervals
|
[
"Query",
"support",
"-",
"scheduler",
"scheduler",
"client",
"get",
"intervals"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L58-L76
|
train
|
edgexfoundry/edgex-go
|
internal/support/scheduler/loader.go
|
getSchedulerDBIntervalActions
|
func getSchedulerDBIntervalActions() ([]contract.IntervalAction, error) {
var err error
var intervalActions []contract.IntervalAction
intervalActions, err = dbClient.IntervalActions()
if err != nil {
LoggingClient.Error("error connecting to metadata and retrieving interval actions:" + err.Error())
return intervalActions, err
}
// debug information only
if intervalActions != nil {
LoggingClient.Debug("successfully queried support-scheduler interval actions...")
for _, v := range intervalActions {
LoggingClient.Debug("found interval action", "name", v.Name, "id", v.ID, "interval", v.Interval, "target", v.Target)
}
}
return intervalActions, nil
}
|
go
|
func getSchedulerDBIntervalActions() ([]contract.IntervalAction, error) {
var err error
var intervalActions []contract.IntervalAction
intervalActions, err = dbClient.IntervalActions()
if err != nil {
LoggingClient.Error("error connecting to metadata and retrieving interval actions:" + err.Error())
return intervalActions, err
}
// debug information only
if intervalActions != nil {
LoggingClient.Debug("successfully queried support-scheduler interval actions...")
for _, v := range intervalActions {
LoggingClient.Debug("found interval action", "name", v.Name, "id", v.ID, "interval", v.Interval, "target", v.Target)
}
}
return intervalActions, nil
}
|
[
"func",
"getSchedulerDBIntervalActions",
"(",
")",
"(",
"[",
"]",
"contract",
".",
"IntervalAction",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"var",
"intervalActions",
"[",
"]",
"contract",
".",
"IntervalAction",
"\n\n",
"intervalActions",
",",
"err",
"=",
"dbClient",
".",
"IntervalActions",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"intervalActions",
",",
"err",
"\n",
"}",
"\n\n",
"// debug information only",
"if",
"intervalActions",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"intervalActions",
"{",
"LoggingClient",
".",
"Debug",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"v",
".",
"Name",
",",
"\"",
"\"",
",",
"v",
".",
"ID",
",",
"\"",
"\"",
",",
"v",
".",
"Interval",
",",
"\"",
"\"",
",",
"v",
".",
"Target",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"intervalActions",
",",
"nil",
"\n",
"}"
] |
// Query support-scheduler schedulerEvent client get scheduledEvents
|
[
"Query",
"support",
"-",
"scheduler",
"schedulerEvent",
"client",
"get",
"scheduledEvents"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L79-L97
|
train
|
edgexfoundry/edgex-go
|
internal/support/scheduler/loader.go
|
addReceivedIntervals
|
func addReceivedIntervals(intervals []contract.Interval) error {
for _, interval := range intervals {
err := scClient.AddIntervalToQueue(interval)
if err != nil {
LoggingClient.Info("problem adding support-scheduler interval name: %s - %s", interval.Name, err.Error())
return err
}
LoggingClient.Info("added interval", "name", interval.Name, "id", interval.ID)
}
return nil
}
|
go
|
func addReceivedIntervals(intervals []contract.Interval) error {
for _, interval := range intervals {
err := scClient.AddIntervalToQueue(interval)
if err != nil {
LoggingClient.Info("problem adding support-scheduler interval name: %s - %s", interval.Name, err.Error())
return err
}
LoggingClient.Info("added interval", "name", interval.Name, "id", interval.ID)
}
return nil
}
|
[
"func",
"addReceivedIntervals",
"(",
"intervals",
"[",
"]",
"contract",
".",
"Interval",
")",
"error",
"{",
"for",
"_",
",",
"interval",
":=",
"range",
"intervals",
"{",
"err",
":=",
"scClient",
".",
"AddIntervalToQueue",
"(",
"interval",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Info",
"(",
"\"",
"\"",
",",
"interval",
".",
"Name",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"LoggingClient",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"interval",
".",
"Name",
",",
"\"",
"\"",
",",
"interval",
".",
"ID",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Iterate over the received intervals add them to scheduler memory queue
|
[
"Iterate",
"over",
"the",
"received",
"intervals",
"add",
"them",
"to",
"scheduler",
"memory",
"queue"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L100-L110
|
train
|
edgexfoundry/edgex-go
|
internal/support/scheduler/loader.go
|
addIntervalToSchedulerDB
|
func addIntervalToSchedulerDB(interval contract.Interval) (string, error) {
var err error
var id string
id, err = dbClient.AddInterval(interval)
if err != nil {
LoggingClient.Error("problem trying to add interval to support-scheduler service:" + err.Error())
return "", err
}
interval.ID = id
LoggingClient.Info("added interval to the support-scheduler database", "name", interval.Name, "id", ID)
return id, nil
}
|
go
|
func addIntervalToSchedulerDB(interval contract.Interval) (string, error) {
var err error
var id string
id, err = dbClient.AddInterval(interval)
if err != nil {
LoggingClient.Error("problem trying to add interval to support-scheduler service:" + err.Error())
return "", err
}
interval.ID = id
LoggingClient.Info("added interval to the support-scheduler database", "name", interval.Name, "id", ID)
return id, nil
}
|
[
"func",
"addIntervalToSchedulerDB",
"(",
"interval",
"contract",
".",
"Interval",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"var",
"id",
"string",
"\n\n",
"id",
",",
"err",
"=",
"dbClient",
".",
"AddInterval",
"(",
"interval",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"interval",
".",
"ID",
"=",
"id",
"\n\n",
"LoggingClient",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"interval",
".",
"Name",
",",
"\"",
"\"",
",",
"ID",
")",
"\n\n",
"return",
"id",
",",
"nil",
"\n",
"}"
] |
// Add interval to support-scheduler
|
[
"Add",
"interval",
"to",
"support",
"-",
"scheduler"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L126-L141
|
train
|
edgexfoundry/edgex-go
|
internal/support/scheduler/loader.go
|
addIntervalActionToSchedulerDB
|
func addIntervalActionToSchedulerDB(intervalAction contract.IntervalAction) (string, error) {
var err error
var id string
id, err = dbClient.AddIntervalAction(intervalAction)
if err != nil {
LoggingClient.Error("problem trying to add interval action to support-scheduler service:" + err.Error())
return "", err
}
LoggingClient.Info("added interval action to the support-scheduler", "name", intervalAction.Name, "id", id)
return id, nil
}
|
go
|
func addIntervalActionToSchedulerDB(intervalAction contract.IntervalAction) (string, error) {
var err error
var id string
id, err = dbClient.AddIntervalAction(intervalAction)
if err != nil {
LoggingClient.Error("problem trying to add interval action to support-scheduler service:" + err.Error())
return "", err
}
LoggingClient.Info("added interval action to the support-scheduler", "name", intervalAction.Name, "id", id)
return id, nil
}
|
[
"func",
"addIntervalActionToSchedulerDB",
"(",
"intervalAction",
"contract",
".",
"IntervalAction",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"var",
"id",
"string",
"\n\n",
"id",
",",
"err",
"=",
"dbClient",
".",
"AddIntervalAction",
"(",
"intervalAction",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"LoggingClient",
".",
"Info",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"intervalAction",
".",
"Name",
",",
"\"",
"\"",
",",
"id",
")",
"\n\n",
"return",
"id",
",",
"nil",
"\n",
"}"
] |
// Add interval event to support-scheduler
|
[
"Add",
"interval",
"event",
"to",
"support",
"-",
"scheduler"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L144-L156
|
train
|
edgexfoundry/edgex-go
|
internal/support/scheduler/loader.go
|
loadConfigIntervalActions
|
func loadConfigIntervalActions() error {
intervalActions := Configuration.IntervalActions
for ia := range intervalActions {
intervalAction := contract.IntervalAction{
Name: intervalActions[ia].Name,
Interval: intervalActions[ia].Interval,
Parameters: intervalActions[ia].Parameters,
Target: intervalActions[ia].Target,
Path: intervalActions[ia].Path,
Port: intervalActions[ia].Port,
Protocol: intervalActions[ia].Protocol,
HTTPMethod: intervalActions[ia].Method,
Address: intervalActions[ia].Host,
}
// query scheduler in memory queue and determine of intervalAction exists
_, err := scClient.QueryIntervalActionByName(intervalAction.Name)
if err != nil {
// add the interval action to support-scheduler database
newIntervalActionID, err := addIntervalActionToSchedulerDB(intervalAction)
if err != nil {
LoggingClient.Error("problem adding interval action into support-scheduler database:" + err.Error())
return err
}
// add the support-scheduler version of the intervalAction.ID
intervalAction.ID = newIntervalActionID
//TODO: Do we care about the Created,Modified, or Origin fields?
errAddIntervalAction := scClient.AddIntervalActionToQueue(intervalAction)
if errAddIntervalAction != nil {
LoggingClient.Error("problem loading interval action into support-scheduler:" + errAddIntervalAction.Error())
return errAddIntervalAction
}
} else {
LoggingClient.Debug("did not load interval action as it exists in the scheduler database:" + intervalAction.Name)
}
}
return nil
}
|
go
|
func loadConfigIntervalActions() error {
intervalActions := Configuration.IntervalActions
for ia := range intervalActions {
intervalAction := contract.IntervalAction{
Name: intervalActions[ia].Name,
Interval: intervalActions[ia].Interval,
Parameters: intervalActions[ia].Parameters,
Target: intervalActions[ia].Target,
Path: intervalActions[ia].Path,
Port: intervalActions[ia].Port,
Protocol: intervalActions[ia].Protocol,
HTTPMethod: intervalActions[ia].Method,
Address: intervalActions[ia].Host,
}
// query scheduler in memory queue and determine of intervalAction exists
_, err := scClient.QueryIntervalActionByName(intervalAction.Name)
if err != nil {
// add the interval action to support-scheduler database
newIntervalActionID, err := addIntervalActionToSchedulerDB(intervalAction)
if err != nil {
LoggingClient.Error("problem adding interval action into support-scheduler database:" + err.Error())
return err
}
// add the support-scheduler version of the intervalAction.ID
intervalAction.ID = newIntervalActionID
//TODO: Do we care about the Created,Modified, or Origin fields?
errAddIntervalAction := scClient.AddIntervalActionToQueue(intervalAction)
if errAddIntervalAction != nil {
LoggingClient.Error("problem loading interval action into support-scheduler:" + errAddIntervalAction.Error())
return errAddIntervalAction
}
} else {
LoggingClient.Debug("did not load interval action as it exists in the scheduler database:" + intervalAction.Name)
}
}
return nil
}
|
[
"func",
"loadConfigIntervalActions",
"(",
")",
"error",
"{",
"intervalActions",
":=",
"Configuration",
".",
"IntervalActions",
"\n\n",
"for",
"ia",
":=",
"range",
"intervalActions",
"{",
"intervalAction",
":=",
"contract",
".",
"IntervalAction",
"{",
"Name",
":",
"intervalActions",
"[",
"ia",
"]",
".",
"Name",
",",
"Interval",
":",
"intervalActions",
"[",
"ia",
"]",
".",
"Interval",
",",
"Parameters",
":",
"intervalActions",
"[",
"ia",
"]",
".",
"Parameters",
",",
"Target",
":",
"intervalActions",
"[",
"ia",
"]",
".",
"Target",
",",
"Path",
":",
"intervalActions",
"[",
"ia",
"]",
".",
"Path",
",",
"Port",
":",
"intervalActions",
"[",
"ia",
"]",
".",
"Port",
",",
"Protocol",
":",
"intervalActions",
"[",
"ia",
"]",
".",
"Protocol",
",",
"HTTPMethod",
":",
"intervalActions",
"[",
"ia",
"]",
".",
"Method",
",",
"Address",
":",
"intervalActions",
"[",
"ia",
"]",
".",
"Host",
",",
"}",
"\n\n",
"// query scheduler in memory queue and determine of intervalAction exists",
"_",
",",
"err",
":=",
"scClient",
".",
"QueryIntervalActionByName",
"(",
"intervalAction",
".",
"Name",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"// add the interval action to support-scheduler database",
"newIntervalActionID",
",",
"err",
":=",
"addIntervalActionToSchedulerDB",
"(",
"intervalAction",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"// add the support-scheduler version of the intervalAction.ID",
"intervalAction",
".",
"ID",
"=",
"newIntervalActionID",
"\n",
"//TODO: Do we care about the Created,Modified, or Origin fields?",
"errAddIntervalAction",
":=",
"scClient",
".",
"AddIntervalActionToQueue",
"(",
"intervalAction",
")",
"\n",
"if",
"errAddIntervalAction",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"errAddIntervalAction",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"errAddIntervalAction",
"\n\n",
"}",
"\n",
"}",
"else",
"{",
"LoggingClient",
".",
"Debug",
"(",
"\"",
"\"",
"+",
"intervalAction",
".",
"Name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Load interval actions if required
|
[
"Load",
"interval",
"actions",
"if",
"required"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L204-L248
|
train
|
edgexfoundry/edgex-go
|
internal/support/scheduler/loader.go
|
loadSupportSchedulerDBInformation
|
func loadSupportSchedulerDBInformation() error {
receivedIntervals, err := getSchedulerDBIntervals()
if err != nil {
LoggingClient.Error("failed to receive intervals from support-scheduler database:" + err.Error())
return err
}
err = addReceivedIntervals(receivedIntervals)
if err != nil {
LoggingClient.Error("failed to add received intervals from support-scheduler database:" + err.Error())
return err
}
intervalActions, err := getSchedulerDBIntervalActions()
if err != nil {
LoggingClient.Error("failed to receive interval actions from support-scheduler database:" + err.Error())
return err
}
err = addReceivedIntervalActions(intervalActions)
if err != nil {
LoggingClient.Error("failed to add received interval actions from support-scheduler database:" + err.Error())
return err
}
return nil
}
|
go
|
func loadSupportSchedulerDBInformation() error {
receivedIntervals, err := getSchedulerDBIntervals()
if err != nil {
LoggingClient.Error("failed to receive intervals from support-scheduler database:" + err.Error())
return err
}
err = addReceivedIntervals(receivedIntervals)
if err != nil {
LoggingClient.Error("failed to add received intervals from support-scheduler database:" + err.Error())
return err
}
intervalActions, err := getSchedulerDBIntervalActions()
if err != nil {
LoggingClient.Error("failed to receive interval actions from support-scheduler database:" + err.Error())
return err
}
err = addReceivedIntervalActions(intervalActions)
if err != nil {
LoggingClient.Error("failed to add received interval actions from support-scheduler database:" + err.Error())
return err
}
return nil
}
|
[
"func",
"loadSupportSchedulerDBInformation",
"(",
")",
"error",
"{",
"receivedIntervals",
",",
"err",
":=",
"getSchedulerDBIntervals",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"addReceivedIntervals",
"(",
"receivedIntervals",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"intervalActions",
",",
"err",
":=",
"getSchedulerDBIntervalActions",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"addReceivedIntervalActions",
"(",
"intervalActions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Query support-scheduler database information
|
[
"Query",
"support",
"-",
"scheduler",
"database",
"information"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/loader.go#L251-L278
|
train
|
edgexfoundry/edgex-go
|
internal/export/distro/mqtt.go
|
newMqttSender
|
func newMqttSender(addr contract.Addressable, cert string, key string) sender {
protocol := strings.ToLower(addr.Protocol)
opts := MQTT.NewClientOptions()
broker := protocol + "://" + addr.Address + ":" + strconv.Itoa(addr.Port) + addr.Path
opts.AddBroker(broker)
opts.SetClientID(addr.Publisher)
opts.SetUsername(addr.User)
opts.SetPassword(addr.Password)
opts.SetAutoReconnect(false)
if protocol == "tcps" || protocol == "ssl" || protocol == "tls" {
cert, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
LoggingClient.Error("Failed loading x509 data")
return nil
}
tlsConfig := &tls.Config{
ClientCAs: nil,
InsecureSkipVerify: true,
Certificates: []tls.Certificate{cert},
}
opts.SetTLSConfig(tlsConfig)
}
sender := &mqttSender{
client: MQTT.NewClient(opts),
topic: addr.Topic,
}
return sender
}
|
go
|
func newMqttSender(addr contract.Addressable, cert string, key string) sender {
protocol := strings.ToLower(addr.Protocol)
opts := MQTT.NewClientOptions()
broker := protocol + "://" + addr.Address + ":" + strconv.Itoa(addr.Port) + addr.Path
opts.AddBroker(broker)
opts.SetClientID(addr.Publisher)
opts.SetUsername(addr.User)
opts.SetPassword(addr.Password)
opts.SetAutoReconnect(false)
if protocol == "tcps" || protocol == "ssl" || protocol == "tls" {
cert, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
LoggingClient.Error("Failed loading x509 data")
return nil
}
tlsConfig := &tls.Config{
ClientCAs: nil,
InsecureSkipVerify: true,
Certificates: []tls.Certificate{cert},
}
opts.SetTLSConfig(tlsConfig)
}
sender := &mqttSender{
client: MQTT.NewClient(opts),
topic: addr.Topic,
}
return sender
}
|
[
"func",
"newMqttSender",
"(",
"addr",
"contract",
".",
"Addressable",
",",
"cert",
"string",
",",
"key",
"string",
")",
"sender",
"{",
"protocol",
":=",
"strings",
".",
"ToLower",
"(",
"addr",
".",
"Protocol",
")",
"\n\n",
"opts",
":=",
"MQTT",
".",
"NewClientOptions",
"(",
")",
"\n",
"broker",
":=",
"protocol",
"+",
"\"",
"\"",
"+",
"addr",
".",
"Address",
"+",
"\"",
"\"",
"+",
"strconv",
".",
"Itoa",
"(",
"addr",
".",
"Port",
")",
"+",
"addr",
".",
"Path",
"\n",
"opts",
".",
"AddBroker",
"(",
"broker",
")",
"\n",
"opts",
".",
"SetClientID",
"(",
"addr",
".",
"Publisher",
")",
"\n",
"opts",
".",
"SetUsername",
"(",
"addr",
".",
"User",
")",
"\n",
"opts",
".",
"SetPassword",
"(",
"addr",
".",
"Password",
")",
"\n",
"opts",
".",
"SetAutoReconnect",
"(",
"false",
")",
"\n\n",
"if",
"protocol",
"==",
"\"",
"\"",
"||",
"protocol",
"==",
"\"",
"\"",
"||",
"protocol",
"==",
"\"",
"\"",
"{",
"cert",
",",
"err",
":=",
"tls",
".",
"LoadX509KeyPair",
"(",
"cert",
",",
"key",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"tlsConfig",
":=",
"&",
"tls",
".",
"Config",
"{",
"ClientCAs",
":",
"nil",
",",
"InsecureSkipVerify",
":",
"true",
",",
"Certificates",
":",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"cert",
"}",
",",
"}",
"\n\n",
"opts",
".",
"SetTLSConfig",
"(",
"tlsConfig",
")",
"\n\n",
"}",
"\n\n",
"sender",
":=",
"&",
"mqttSender",
"{",
"client",
":",
"MQTT",
".",
"NewClient",
"(",
"opts",
")",
",",
"topic",
":",
"addr",
".",
"Topic",
",",
"}",
"\n\n",
"return",
"sender",
"\n",
"}"
] |
// newMqttSender - create new mqtt sender
|
[
"newMqttSender",
"-",
"create",
"new",
"mqtt",
"sender"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/distro/mqtt.go#L29-L64
|
train
|
edgexfoundry/edgex-go
|
internal/core/data/event.go
|
deleteEvent
|
func deleteEvent(e contract.Event) error {
for _, reading := range e.Readings {
if err := deleteReadingById(reading.Id); err != nil {
return err
}
}
if err := dbClient.DeleteEventById(e.ID); err != nil {
return err
}
return nil
}
|
go
|
func deleteEvent(e contract.Event) error {
for _, reading := range e.Readings {
if err := deleteReadingById(reading.Id); err != nil {
return err
}
}
if err := dbClient.DeleteEventById(e.ID); err != nil {
return err
}
return nil
}
|
[
"func",
"deleteEvent",
"(",
"e",
"contract",
".",
"Event",
")",
"error",
"{",
"for",
"_",
",",
"reading",
":=",
"range",
"e",
".",
"Readings",
"{",
"if",
"err",
":=",
"deleteReadingById",
"(",
"reading",
".",
"Id",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"dbClient",
".",
"DeleteEventById",
"(",
"e",
".",
"ID",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Delete the event and readings
|
[
"Delete",
"the",
"event",
"and",
"readings"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/data/event.go#L167-L178
|
train
|
edgexfoundry/edgex-go
|
internal/core/data/event.go
|
putEventOnQueue
|
func putEventOnQueue(e contract.Event, ctx context.Context) {
LoggingClient.Info("Putting event on message queue")
// Have multiple implementations (start with ZeroMQ)
evt := models.Event{}
evt.Event = e
evt.CorrelationId = correlation.FromContext(ctx)
payload, err := json.Marshal(evt)
if err != nil {
LoggingClient.Error(fmt.Sprintf("Unable to marshal event to json: %s", err.Error()))
return
}
ctx = context.WithValue(ctx, clients.ContentType, clients.ContentTypeJSON)
msgEnvelope := msgTypes.NewMessageEnvelope(payload, ctx)
err = msgClient.Publish(msgEnvelope, Configuration.MessageQueue.Topic)
if err != nil {
LoggingClient.Error(fmt.Sprintf("Unable to send message for event: %s", evt.String()))
} else {
LoggingClient.Info(fmt.Sprintf("Event Published on message queue. Topic: %s, Correlation-id: %s ", Configuration.MessageQueue.Topic, msgEnvelope.CorrelationID))
}
}
|
go
|
func putEventOnQueue(e contract.Event, ctx context.Context) {
LoggingClient.Info("Putting event on message queue")
// Have multiple implementations (start with ZeroMQ)
evt := models.Event{}
evt.Event = e
evt.CorrelationId = correlation.FromContext(ctx)
payload, err := json.Marshal(evt)
if err != nil {
LoggingClient.Error(fmt.Sprintf("Unable to marshal event to json: %s", err.Error()))
return
}
ctx = context.WithValue(ctx, clients.ContentType, clients.ContentTypeJSON)
msgEnvelope := msgTypes.NewMessageEnvelope(payload, ctx)
err = msgClient.Publish(msgEnvelope, Configuration.MessageQueue.Topic)
if err != nil {
LoggingClient.Error(fmt.Sprintf("Unable to send message for event: %s", evt.String()))
} else {
LoggingClient.Info(fmt.Sprintf("Event Published on message queue. Topic: %s, Correlation-id: %s ", Configuration.MessageQueue.Topic, msgEnvelope.CorrelationID))
}
}
|
[
"func",
"putEventOnQueue",
"(",
"e",
"contract",
".",
"Event",
",",
"ctx",
"context",
".",
"Context",
")",
"{",
"LoggingClient",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"//\tHave multiple implementations (start with ZeroMQ)",
"evt",
":=",
"models",
".",
"Event",
"{",
"}",
"\n",
"evt",
".",
"Event",
"=",
"e",
"\n",
"evt",
".",
"CorrelationId",
"=",
"correlation",
".",
"FromContext",
"(",
"ctx",
")",
"\n",
"payload",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"evt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"ctx",
"=",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"clients",
".",
"ContentType",
",",
"clients",
".",
"ContentTypeJSON",
")",
"\n",
"msgEnvelope",
":=",
"msgTypes",
".",
"NewMessageEnvelope",
"(",
"payload",
",",
"ctx",
")",
"\n\n",
"err",
"=",
"msgClient",
".",
"Publish",
"(",
"msgEnvelope",
",",
"Configuration",
".",
"MessageQueue",
".",
"Topic",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"evt",
".",
"String",
"(",
")",
")",
")",
"\n",
"}",
"else",
"{",
"LoggingClient",
".",
"Info",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"Configuration",
".",
"MessageQueue",
".",
"Topic",
",",
"msgEnvelope",
".",
"CorrelationID",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Put event on the message queue to be processed by the rules engine
|
[
"Put",
"event",
"on",
"the",
"message",
"queue",
"to",
"be",
"processed",
"by",
"the",
"rules",
"engine"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/data/event.go#L210-L231
|
train
|
edgexfoundry/edgex-go
|
internal/core/command/rest.go
|
pingHandler
|
func pingHandler(w http.ResponseWriter, _ *http.Request) {
w.Header().Set(CONTENTTYPE, TEXTPLAIN)
w.Write([]byte(PINGRESPONSE))
}
|
go
|
func pingHandler(w http.ResponseWriter, _ *http.Request) {
w.Header().Set(CONTENTTYPE, TEXTPLAIN)
w.Write([]byte(PINGRESPONSE))
}
|
[
"func",
"pingHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"_",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"CONTENTTYPE",
",",
"TEXTPLAIN",
")",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"PINGRESPONSE",
")",
")",
"\n",
"}"
] |
// Respond with PINGRESPONSE to see if the service is alive
|
[
"Respond",
"with",
"PINGRESPONSE",
"to",
"see",
"if",
"the",
"service",
"is",
"alive"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/command/rest.go#L72-L75
|
train
|
edgexfoundry/edgex-go
|
internal/core/data/valuedescriptor.go
|
validateFormatString
|
func validateFormatString(v contract.ValueDescriptor) error {
// No formatting specified
if v.Formatting == "" {
return nil
}
match, err := regexp.MatchString(formatSpecifier, v.Formatting)
if err != nil {
LoggingClient.Error("Error checking for format string for value descriptor " + v.Name)
return err
}
if !match {
err = fmt.Errorf("format is not a valid printf format")
LoggingClient.Error(fmt.Sprintf("Error posting value descriptor. %s", err.Error()))
return errors.NewErrValueDescriptorInvalid(v.Name, err)
}
return nil
}
|
go
|
func validateFormatString(v contract.ValueDescriptor) error {
// No formatting specified
if v.Formatting == "" {
return nil
}
match, err := regexp.MatchString(formatSpecifier, v.Formatting)
if err != nil {
LoggingClient.Error("Error checking for format string for value descriptor " + v.Name)
return err
}
if !match {
err = fmt.Errorf("format is not a valid printf format")
LoggingClient.Error(fmt.Sprintf("Error posting value descriptor. %s", err.Error()))
return errors.NewErrValueDescriptorInvalid(v.Name, err)
}
return nil
}
|
[
"func",
"validateFormatString",
"(",
"v",
"contract",
".",
"ValueDescriptor",
")",
"error",
"{",
"// No formatting specified",
"if",
"v",
".",
"Formatting",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"match",
",",
"err",
":=",
"regexp",
".",
"MatchString",
"(",
"formatSpecifier",
",",
"v",
".",
"Formatting",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"\"",
"\"",
"+",
"v",
".",
"Name",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"match",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"LoggingClient",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
")",
"\n",
"return",
"errors",
".",
"NewErrValueDescriptorInvalid",
"(",
"v",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Check if the value descriptor matches the format string regular expression
|
[
"Check",
"if",
"the",
"value",
"descriptor",
"matches",
"the",
"format",
"string",
"regular",
"expression"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/data/valuedescriptor.go#L34-L53
|
train
|
edgexfoundry/edgex-go
|
internal/core/metadata/rest_addressable.go
|
restAddAddressable
|
func restAddAddressable(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var a models.Addressable
err := json.NewDecoder(r.Body).Decode(&a)
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
id, err := addAddressable(a)
if err != nil {
switch err.(type) {
case *types.ErrDuplicateAddressableName:
http.Error(w, err.Error(), http.StatusConflict)
case *types.ErrEmptyAddressableName:
http.Error(w, err.Error(), http.StatusBadRequest)
default:
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
w.WriteHeader(http.StatusOK)
_, err = w.Write([]byte(id))
if err != nil {
LoggingClient.Error(err.Error())
return
}
}
|
go
|
func restAddAddressable(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var a models.Addressable
err := json.NewDecoder(r.Body).Decode(&a)
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
id, err := addAddressable(a)
if err != nil {
switch err.(type) {
case *types.ErrDuplicateAddressableName:
http.Error(w, err.Error(), http.StatusConflict)
case *types.ErrEmptyAddressableName:
http.Error(w, err.Error(), http.StatusBadRequest)
default:
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
w.WriteHeader(http.StatusOK)
_, err = w.Write([]byte(id))
if err != nil {
LoggingClient.Error(err.Error())
return
}
}
|
[
"func",
"restAddAddressable",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"var",
"a",
"models",
".",
"Addressable",
"\n",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"a",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"id",
",",
"err",
":=",
"addAddressable",
"(",
"a",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"*",
"types",
".",
"ErrDuplicateAddressableName",
":",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusConflict",
")",
"\n",
"case",
"*",
"types",
".",
"ErrEmptyAddressableName",
":",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"default",
":",
"http",
".",
"Error",
"(",
"w",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"_",
",",
"err",
"=",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"id",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"LoggingClient",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] |
// Add a new addressable
// The name must be unique
|
[
"Add",
"a",
"new",
"addressable",
"The",
"name",
"must",
"be",
"unique"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_addressable.go#L50-L78
|
train
|
edgexfoundry/edgex-go
|
internal/core/metadata/rest_addressable.go
|
isAddressableStillInUse
|
func isAddressableStillInUse(a models.Addressable) (bool, error) {
// Check device services
ds, err := dbClient.GetDeviceServicesByAddressableId(a.Id)
if err != nil {
return false, err
}
if len(ds) > 0 {
return true, nil
}
return false, nil
}
|
go
|
func isAddressableStillInUse(a models.Addressable) (bool, error) {
// Check device services
ds, err := dbClient.GetDeviceServicesByAddressableId(a.Id)
if err != nil {
return false, err
}
if len(ds) > 0 {
return true, nil
}
return false, nil
}
|
[
"func",
"isAddressableStillInUse",
"(",
"a",
"models",
".",
"Addressable",
")",
"(",
"bool",
",",
"error",
")",
"{",
"// Check device services",
"ds",
",",
"err",
":=",
"dbClient",
".",
"GetDeviceServicesByAddressableId",
"(",
"a",
".",
"Id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ds",
")",
">",
"0",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] |
// Helper function to determine if an addressable is still referenced by a device or device service
|
[
"Helper",
"function",
"to",
"determine",
"if",
"an",
"addressable",
"is",
"still",
"referenced",
"by",
"a",
"device",
"or",
"device",
"service"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_addressable.go#L208-L219
|
train
|
edgexfoundry/edgex-go
|
internal/pkg/telemetry/windows_cpu.go
|
getSystemTimes
|
func getSystemTimes(idleTime, kernelTime, userTime *FileTime) bool {
ret, _, _ := procGetSystemTimes.Call(
uintptr(unsafe.Pointer(idleTime)),
uintptr(unsafe.Pointer(kernelTime)),
uintptr(unsafe.Pointer(userTime)))
return ret != 0
}
|
go
|
func getSystemTimes(idleTime, kernelTime, userTime *FileTime) bool {
ret, _, _ := procGetSystemTimes.Call(
uintptr(unsafe.Pointer(idleTime)),
uintptr(unsafe.Pointer(kernelTime)),
uintptr(unsafe.Pointer(userTime)))
return ret != 0
}
|
[
"func",
"getSystemTimes",
"(",
"idleTime",
",",
"kernelTime",
",",
"userTime",
"*",
"FileTime",
")",
"bool",
"{",
"ret",
",",
"_",
",",
"_",
":=",
"procGetSystemTimes",
".",
"Call",
"(",
"uintptr",
"(",
"unsafe",
".",
"Pointer",
"(",
"idleTime",
")",
")",
",",
"uintptr",
"(",
"unsafe",
".",
"Pointer",
"(",
"kernelTime",
")",
")",
",",
"uintptr",
"(",
"unsafe",
".",
"Pointer",
"(",
"userTime",
")",
")",
")",
"\n\n",
"return",
"ret",
"!=",
"0",
"\n",
"}"
] |
// getSystemTimes makes the system call to windows to get the system data
|
[
"getSystemTimes",
"makes",
"the",
"system",
"call",
"to",
"windows",
"to",
"get",
"the",
"system",
"data"
] |
c67086fe10c4d34caeefffaee5379490103dd63f
|
https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/telemetry/windows_cpu.go#L63-L70
|
train
|
osrg/gobgp
|
internal/pkg/config/util.go
|
detectConfigFileType
|
func detectConfigFileType(path, def string) string {
switch ext := filepath.Ext(path); ext {
case ".toml":
return "toml"
case ".yaml", ".yml":
return "yaml"
case ".json":
return "json"
default:
return def
}
}
|
go
|
func detectConfigFileType(path, def string) string {
switch ext := filepath.Ext(path); ext {
case ".toml":
return "toml"
case ".yaml", ".yml":
return "yaml"
case ".json":
return "json"
default:
return def
}
}
|
[
"func",
"detectConfigFileType",
"(",
"path",
",",
"def",
"string",
")",
"string",
"{",
"switch",
"ext",
":=",
"filepath",
".",
"Ext",
"(",
"path",
")",
";",
"ext",
"{",
"case",
"\"",
"\"",
":",
"return",
"\"",
"\"",
"\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"return",
"\"",
"\"",
"\n",
"case",
"\"",
"\"",
":",
"return",
"\"",
"\"",
"\n",
"default",
":",
"return",
"def",
"\n",
"}",
"\n",
"}"
] |
// Returns config file type by retrieving extension from the given path.
// If no corresponding type found, returns the given def as the default value.
|
[
"Returns",
"config",
"file",
"type",
"by",
"retrieving",
"extension",
"from",
"the",
"given",
"path",
".",
"If",
"no",
"corresponding",
"type",
"found",
"returns",
"the",
"given",
"def",
"as",
"the",
"default",
"value",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/config/util.go#L36-L47
|
train
|
osrg/gobgp
|
pkg/packet/bgp/bgp.go
|
FlatUpdate
|
func FlatUpdate(f1, f2 map[string]string) error {
conflict := false
for k2, v2 := range f2 {
if v1, ok := f1[k2]; ok {
f1[k2] = v1 + ";" + v2
conflict = true
} else {
f1[k2] = v2
}
}
if conflict {
return fmt.Errorf("keys conflict")
} else {
return nil
}
}
|
go
|
func FlatUpdate(f1, f2 map[string]string) error {
conflict := false
for k2, v2 := range f2 {
if v1, ok := f1[k2]; ok {
f1[k2] = v1 + ";" + v2
conflict = true
} else {
f1[k2] = v2
}
}
if conflict {
return fmt.Errorf("keys conflict")
} else {
return nil
}
}
|
[
"func",
"FlatUpdate",
"(",
"f1",
",",
"f2",
"map",
"[",
"string",
"]",
"string",
")",
"error",
"{",
"conflict",
":=",
"false",
"\n",
"for",
"k2",
",",
"v2",
":=",
"range",
"f2",
"{",
"if",
"v1",
",",
"ok",
":=",
"f1",
"[",
"k2",
"]",
";",
"ok",
"{",
"f1",
"[",
"k2",
"]",
"=",
"v1",
"+",
"\"",
"\"",
"+",
"v2",
"\n",
"conflict",
"=",
"true",
"\n",
"}",
"else",
"{",
"f1",
"[",
"k2",
"]",
"=",
"v2",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"conflict",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] |
// Update a Flat representation by adding elements of the second
// one. If two elements use same keys, values are separated with
// ';'. In this case, it returns an error but the update has been
// realized.
|
[
"Update",
"a",
"Flat",
"representation",
"by",
"adding",
"elements",
"of",
"the",
"second",
"one",
".",
"If",
"two",
"elements",
"use",
"same",
"keys",
"values",
"are",
"separated",
"with",
";",
".",
"In",
"this",
"case",
"it",
"returns",
"an",
"error",
"but",
"the",
"update",
"has",
"been",
"realized",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/pkg/packet/bgp/bgp.go#L12968-L12983
|
train
|
osrg/gobgp
|
internal/pkg/table/destination.go
|
Calculate
|
func (dest *Destination) Calculate(newPath *Path) *Update {
oldKnownPathList := make([]*Path, len(dest.knownPathList))
copy(oldKnownPathList, dest.knownPathList)
if newPath.IsWithdraw {
p := dest.explicitWithdraw(newPath)
if p != nil {
if id := p.GetNlri().PathLocalIdentifier(); id != 0 {
dest.localIdMap.Unflag(uint(id))
}
}
} else {
dest.implicitWithdraw(newPath)
dest.knownPathList = append(dest.knownPathList, newPath)
}
for _, path := range dest.knownPathList {
if path.GetNlri().PathLocalIdentifier() == 0 {
id, err := dest.localIdMap.FindandSetZeroBit()
if err != nil {
dest.localIdMap.Expand()
id, _ = dest.localIdMap.FindandSetZeroBit()
}
path.GetNlri().SetPathLocalIdentifier(uint32(id))
}
}
// Compute new best path
dest.computeKnownBestPath()
l := make([]*Path, len(dest.knownPathList))
copy(l, dest.knownPathList)
return &Update{
KnownPathList: l,
OldKnownPathList: oldKnownPathList,
}
}
|
go
|
func (dest *Destination) Calculate(newPath *Path) *Update {
oldKnownPathList := make([]*Path, len(dest.knownPathList))
copy(oldKnownPathList, dest.knownPathList)
if newPath.IsWithdraw {
p := dest.explicitWithdraw(newPath)
if p != nil {
if id := p.GetNlri().PathLocalIdentifier(); id != 0 {
dest.localIdMap.Unflag(uint(id))
}
}
} else {
dest.implicitWithdraw(newPath)
dest.knownPathList = append(dest.knownPathList, newPath)
}
for _, path := range dest.knownPathList {
if path.GetNlri().PathLocalIdentifier() == 0 {
id, err := dest.localIdMap.FindandSetZeroBit()
if err != nil {
dest.localIdMap.Expand()
id, _ = dest.localIdMap.FindandSetZeroBit()
}
path.GetNlri().SetPathLocalIdentifier(uint32(id))
}
}
// Compute new best path
dest.computeKnownBestPath()
l := make([]*Path, len(dest.knownPathList))
copy(l, dest.knownPathList)
return &Update{
KnownPathList: l,
OldKnownPathList: oldKnownPathList,
}
}
|
[
"func",
"(",
"dest",
"*",
"Destination",
")",
"Calculate",
"(",
"newPath",
"*",
"Path",
")",
"*",
"Update",
"{",
"oldKnownPathList",
":=",
"make",
"(",
"[",
"]",
"*",
"Path",
",",
"len",
"(",
"dest",
".",
"knownPathList",
")",
")",
"\n",
"copy",
"(",
"oldKnownPathList",
",",
"dest",
".",
"knownPathList",
")",
"\n\n",
"if",
"newPath",
".",
"IsWithdraw",
"{",
"p",
":=",
"dest",
".",
"explicitWithdraw",
"(",
"newPath",
")",
"\n",
"if",
"p",
"!=",
"nil",
"{",
"if",
"id",
":=",
"p",
".",
"GetNlri",
"(",
")",
".",
"PathLocalIdentifier",
"(",
")",
";",
"id",
"!=",
"0",
"{",
"dest",
".",
"localIdMap",
".",
"Unflag",
"(",
"uint",
"(",
"id",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"dest",
".",
"implicitWithdraw",
"(",
"newPath",
")",
"\n",
"dest",
".",
"knownPathList",
"=",
"append",
"(",
"dest",
".",
"knownPathList",
",",
"newPath",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"path",
":=",
"range",
"dest",
".",
"knownPathList",
"{",
"if",
"path",
".",
"GetNlri",
"(",
")",
".",
"PathLocalIdentifier",
"(",
")",
"==",
"0",
"{",
"id",
",",
"err",
":=",
"dest",
".",
"localIdMap",
".",
"FindandSetZeroBit",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"dest",
".",
"localIdMap",
".",
"Expand",
"(",
")",
"\n",
"id",
",",
"_",
"=",
"dest",
".",
"localIdMap",
".",
"FindandSetZeroBit",
"(",
")",
"\n",
"}",
"\n",
"path",
".",
"GetNlri",
"(",
")",
".",
"SetPathLocalIdentifier",
"(",
"uint32",
"(",
"id",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Compute new best path",
"dest",
".",
"computeKnownBestPath",
"(",
")",
"\n\n",
"l",
":=",
"make",
"(",
"[",
"]",
"*",
"Path",
",",
"len",
"(",
"dest",
".",
"knownPathList",
")",
")",
"\n",
"copy",
"(",
"l",
",",
"dest",
".",
"knownPathList",
")",
"\n",
"return",
"&",
"Update",
"{",
"KnownPathList",
":",
"l",
",",
"OldKnownPathList",
":",
"oldKnownPathList",
",",
"}",
"\n",
"}"
] |
// Calculates best-path among known paths for this destination.
//
// Modifies destination's state related to stored paths. Removes withdrawn
// paths from known paths. Also, adds new paths to known paths.
|
[
"Calculates",
"best",
"-",
"path",
"among",
"known",
"paths",
"for",
"this",
"destination",
".",
"Modifies",
"destination",
"s",
"state",
"related",
"to",
"stored",
"paths",
".",
"Removes",
"withdrawn",
"paths",
"from",
"known",
"paths",
".",
"Also",
"adds",
"new",
"paths",
"to",
"known",
"paths",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/destination.go#L262-L297
|
train
|
osrg/gobgp
|
internal/pkg/table/destination.go
|
implicitWithdraw
|
func (dest *Destination) implicitWithdraw(newPath *Path) {
found := -1
for i, path := range dest.knownPathList {
if newPath.NoImplicitWithdraw() {
continue
}
// Here we just check if source is same and not check if path
// version num. as newPaths are implicit withdrawal of old
// paths and when doing RouteRefresh (not EnhancedRouteRefresh)
// we get same paths again.
if newPath.GetSource().Equal(path.GetSource()) && newPath.GetNlri().PathIdentifier() == path.GetNlri().PathIdentifier() {
log.WithFields(log.Fields{
"Topic": "Table",
"Key": dest.GetNlri().String(),
"Path": path,
}).Debug("Implicit withdrawal of old path, since we have learned new path from the same peer")
found = i
newPath.GetNlri().SetPathLocalIdentifier(path.GetNlri().PathLocalIdentifier())
break
}
}
if found != -1 {
dest.knownPathList = append(dest.knownPathList[:found], dest.knownPathList[found+1:]...)
}
}
|
go
|
func (dest *Destination) implicitWithdraw(newPath *Path) {
found := -1
for i, path := range dest.knownPathList {
if newPath.NoImplicitWithdraw() {
continue
}
// Here we just check if source is same and not check if path
// version num. as newPaths are implicit withdrawal of old
// paths and when doing RouteRefresh (not EnhancedRouteRefresh)
// we get same paths again.
if newPath.GetSource().Equal(path.GetSource()) && newPath.GetNlri().PathIdentifier() == path.GetNlri().PathIdentifier() {
log.WithFields(log.Fields{
"Topic": "Table",
"Key": dest.GetNlri().String(),
"Path": path,
}).Debug("Implicit withdrawal of old path, since we have learned new path from the same peer")
found = i
newPath.GetNlri().SetPathLocalIdentifier(path.GetNlri().PathLocalIdentifier())
break
}
}
if found != -1 {
dest.knownPathList = append(dest.knownPathList[:found], dest.knownPathList[found+1:]...)
}
}
|
[
"func",
"(",
"dest",
"*",
"Destination",
")",
"implicitWithdraw",
"(",
"newPath",
"*",
"Path",
")",
"{",
"found",
":=",
"-",
"1",
"\n",
"for",
"i",
",",
"path",
":=",
"range",
"dest",
".",
"knownPathList",
"{",
"if",
"newPath",
".",
"NoImplicitWithdraw",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"// Here we just check if source is same and not check if path",
"// version num. as newPaths are implicit withdrawal of old",
"// paths and when doing RouteRefresh (not EnhancedRouteRefresh)",
"// we get same paths again.",
"if",
"newPath",
".",
"GetSource",
"(",
")",
".",
"Equal",
"(",
"path",
".",
"GetSource",
"(",
")",
")",
"&&",
"newPath",
".",
"GetNlri",
"(",
")",
".",
"PathIdentifier",
"(",
")",
"==",
"path",
".",
"GetNlri",
"(",
")",
".",
"PathIdentifier",
"(",
")",
"{",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"dest",
".",
"GetNlri",
"(",
")",
".",
"String",
"(",
")",
",",
"\"",
"\"",
":",
"path",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"found",
"=",
"i",
"\n",
"newPath",
".",
"GetNlri",
"(",
")",
".",
"SetPathLocalIdentifier",
"(",
"path",
".",
"GetNlri",
"(",
")",
".",
"PathLocalIdentifier",
"(",
")",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"found",
"!=",
"-",
"1",
"{",
"dest",
".",
"knownPathList",
"=",
"append",
"(",
"dest",
".",
"knownPathList",
"[",
":",
"found",
"]",
",",
"dest",
".",
"knownPathList",
"[",
"found",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"\n",
"}"
] |
// Identifies which of known paths are old and removes them.
//
// Known paths will no longer have paths whose new version is present in
// new paths.
|
[
"Identifies",
"which",
"of",
"known",
"paths",
"are",
"old",
"and",
"removes",
"them",
".",
"Known",
"paths",
"will",
"no",
"longer",
"have",
"paths",
"whose",
"new",
"version",
"is",
"present",
"in",
"new",
"paths",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/destination.go#L352-L377
|
train
|
osrg/gobgp
|
pkg/server/server.go
|
newTCPListener
|
func newTCPListener(address string, port uint32, ch chan *net.TCPConn) (*tcpListener, error) {
proto := "tcp4"
if ip := net.ParseIP(address); ip == nil {
return nil, fmt.Errorf("can't listen on %s", address)
} else if ip.To4() == nil {
proto = "tcp6"
}
addr, err := net.ResolveTCPAddr(proto, net.JoinHostPort(address, strconv.Itoa(int(port))))
if err != nil {
return nil, err
}
l, err := net.ListenTCP(proto, addr)
if err != nil {
return nil, err
}
// Note: Set TTL=255 for incoming connection listener in order to accept
// connection in case for the neighbor has TTL Security settings.
if err := setListenTCPTTLSockopt(l, 255); err != nil {
log.WithFields(log.Fields{
"Topic": "Peer",
"Key": addr,
}).Warnf("cannot set TTL(=%d) for TCPListener: %s", 255, err)
}
closeCh := make(chan struct{})
go func() error {
for {
conn, err := l.AcceptTCP()
if err != nil {
close(closeCh)
log.WithFields(log.Fields{
"Topic": "Peer",
"Error": err,
}).Warn("Failed to AcceptTCP")
return err
}
ch <- conn
}
}()
return &tcpListener{
l: l,
ch: closeCh,
}, nil
}
|
go
|
func newTCPListener(address string, port uint32, ch chan *net.TCPConn) (*tcpListener, error) {
proto := "tcp4"
if ip := net.ParseIP(address); ip == nil {
return nil, fmt.Errorf("can't listen on %s", address)
} else if ip.To4() == nil {
proto = "tcp6"
}
addr, err := net.ResolveTCPAddr(proto, net.JoinHostPort(address, strconv.Itoa(int(port))))
if err != nil {
return nil, err
}
l, err := net.ListenTCP(proto, addr)
if err != nil {
return nil, err
}
// Note: Set TTL=255 for incoming connection listener in order to accept
// connection in case for the neighbor has TTL Security settings.
if err := setListenTCPTTLSockopt(l, 255); err != nil {
log.WithFields(log.Fields{
"Topic": "Peer",
"Key": addr,
}).Warnf("cannot set TTL(=%d) for TCPListener: %s", 255, err)
}
closeCh := make(chan struct{})
go func() error {
for {
conn, err := l.AcceptTCP()
if err != nil {
close(closeCh)
log.WithFields(log.Fields{
"Topic": "Peer",
"Error": err,
}).Warn("Failed to AcceptTCP")
return err
}
ch <- conn
}
}()
return &tcpListener{
l: l,
ch: closeCh,
}, nil
}
|
[
"func",
"newTCPListener",
"(",
"address",
"string",
",",
"port",
"uint32",
",",
"ch",
"chan",
"*",
"net",
".",
"TCPConn",
")",
"(",
"*",
"tcpListener",
",",
"error",
")",
"{",
"proto",
":=",
"\"",
"\"",
"\n",
"if",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"address",
")",
";",
"ip",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"address",
")",
"\n",
"}",
"else",
"if",
"ip",
".",
"To4",
"(",
")",
"==",
"nil",
"{",
"proto",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"addr",
",",
"err",
":=",
"net",
".",
"ResolveTCPAddr",
"(",
"proto",
",",
"net",
".",
"JoinHostPort",
"(",
"address",
",",
"strconv",
".",
"Itoa",
"(",
"int",
"(",
"port",
")",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"l",
",",
"err",
":=",
"net",
".",
"ListenTCP",
"(",
"proto",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// Note: Set TTL=255 for incoming connection listener in order to accept",
"// connection in case for the neighbor has TTL Security settings.",
"if",
"err",
":=",
"setListenTCPTTLSockopt",
"(",
"l",
",",
"255",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"addr",
",",
"}",
")",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"255",
",",
"err",
")",
"\n",
"}",
"\n\n",
"closeCh",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"go",
"func",
"(",
")",
"error",
"{",
"for",
"{",
"conn",
",",
"err",
":=",
"l",
".",
"AcceptTCP",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"close",
"(",
"closeCh",
")",
"\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"err",
",",
"}",
")",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"ch",
"<-",
"conn",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"&",
"tcpListener",
"{",
"l",
":",
"l",
",",
"ch",
":",
"closeCh",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// avoid mapped IPv6 address
|
[
"avoid",
"mapped",
"IPv6",
"address"
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/pkg/server/server.go#L55-L99
|
train
|
osrg/gobgp
|
pkg/server/bmp.go
|
update
|
func (r ribout) update(p *table.Path) bool {
key := p.GetNlri().String() // TODO expose (*Path).getPrefix()
l := r[key]
if p.IsWithdraw {
if len(l) == 0 {
return false
}
n := make([]*table.Path, 0, len(l))
for _, q := range l {
if p.GetSource() == q.GetSource() {
continue
}
n = append(n, q)
}
if len(n) == 0 {
delete(r, key)
} else {
r[key] = n
}
return true
}
if len(l) == 0 {
r[key] = []*table.Path{p}
return true
}
doAppend := true
for idx, q := range l {
if p.GetSource() == q.GetSource() {
// if we have sent the same path, don't send it again
if p.Equal(q) {
return false
}
l[idx] = p
doAppend = false
}
}
if doAppend {
r[key] = append(r[key], p)
}
return true
}
|
go
|
func (r ribout) update(p *table.Path) bool {
key := p.GetNlri().String() // TODO expose (*Path).getPrefix()
l := r[key]
if p.IsWithdraw {
if len(l) == 0 {
return false
}
n := make([]*table.Path, 0, len(l))
for _, q := range l {
if p.GetSource() == q.GetSource() {
continue
}
n = append(n, q)
}
if len(n) == 0 {
delete(r, key)
} else {
r[key] = n
}
return true
}
if len(l) == 0 {
r[key] = []*table.Path{p}
return true
}
doAppend := true
for idx, q := range l {
if p.GetSource() == q.GetSource() {
// if we have sent the same path, don't send it again
if p.Equal(q) {
return false
}
l[idx] = p
doAppend = false
}
}
if doAppend {
r[key] = append(r[key], p)
}
return true
}
|
[
"func",
"(",
"r",
"ribout",
")",
"update",
"(",
"p",
"*",
"table",
".",
"Path",
")",
"bool",
"{",
"key",
":=",
"p",
".",
"GetNlri",
"(",
")",
".",
"String",
"(",
")",
"// TODO expose (*Path).getPrefix()",
"\n",
"l",
":=",
"r",
"[",
"key",
"]",
"\n",
"if",
"p",
".",
"IsWithdraw",
"{",
"if",
"len",
"(",
"l",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"n",
":=",
"make",
"(",
"[",
"]",
"*",
"table",
".",
"Path",
",",
"0",
",",
"len",
"(",
"l",
")",
")",
"\n",
"for",
"_",
",",
"q",
":=",
"range",
"l",
"{",
"if",
"p",
".",
"GetSource",
"(",
")",
"==",
"q",
".",
"GetSource",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"n",
"=",
"append",
"(",
"n",
",",
"q",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"n",
")",
"==",
"0",
"{",
"delete",
"(",
"r",
",",
"key",
")",
"\n",
"}",
"else",
"{",
"r",
"[",
"key",
"]",
"=",
"n",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"l",
")",
"==",
"0",
"{",
"r",
"[",
"key",
"]",
"=",
"[",
"]",
"*",
"table",
".",
"Path",
"{",
"p",
"}",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"doAppend",
":=",
"true",
"\n",
"for",
"idx",
",",
"q",
":=",
"range",
"l",
"{",
"if",
"p",
".",
"GetSource",
"(",
")",
"==",
"q",
".",
"GetSource",
"(",
")",
"{",
"// if we have sent the same path, don't send it again",
"if",
"p",
".",
"Equal",
"(",
"q",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"l",
"[",
"idx",
"]",
"=",
"p",
"\n",
"doAppend",
"=",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"doAppend",
"{",
"r",
"[",
"key",
"]",
"=",
"append",
"(",
"r",
"[",
"key",
"]",
",",
"p",
")",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// return true if we need to send the path to the BMP server
|
[
"return",
"true",
"if",
"we",
"need",
"to",
"send",
"the",
"path",
"to",
"the",
"BMP",
"server"
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/pkg/server/bmp.go#L40-L82
|
train
|
osrg/gobgp
|
pkg/server/util.go
|
newAdministrativeCommunication
|
func newAdministrativeCommunication(communication string) (data []byte) {
if communication == "" {
return nil
}
com := []byte(communication)
if len(com) > bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX {
data = []byte{bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX}
data = append(data, com[:bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX]...)
} else {
data = []byte{byte(len(com))}
data = append(data, com...)
}
return data
}
|
go
|
func newAdministrativeCommunication(communication string) (data []byte) {
if communication == "" {
return nil
}
com := []byte(communication)
if len(com) > bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX {
data = []byte{bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX}
data = append(data, com[:bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX]...)
} else {
data = []byte{byte(len(com))}
data = append(data, com...)
}
return data
}
|
[
"func",
"newAdministrativeCommunication",
"(",
"communication",
"string",
")",
"(",
"data",
"[",
"]",
"byte",
")",
"{",
"if",
"communication",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"com",
":=",
"[",
"]",
"byte",
"(",
"communication",
")",
"\n",
"if",
"len",
"(",
"com",
")",
">",
"bgp",
".",
"BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX",
"{",
"data",
"=",
"[",
"]",
"byte",
"{",
"bgp",
".",
"BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX",
"}",
"\n",
"data",
"=",
"append",
"(",
"data",
",",
"com",
"[",
":",
"bgp",
".",
"BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX",
"]",
"...",
")",
"\n",
"}",
"else",
"{",
"data",
"=",
"[",
"]",
"byte",
"{",
"byte",
"(",
"len",
"(",
"com",
")",
")",
"}",
"\n",
"data",
"=",
"append",
"(",
"data",
",",
"com",
"...",
")",
"\n",
"}",
"\n",
"return",
"data",
"\n",
"}"
] |
// Returns the binary formatted Administrative Shutdown Communication from the
// given string value.
|
[
"Returns",
"the",
"binary",
"formatted",
"Administrative",
"Shutdown",
"Communication",
"from",
"the",
"given",
"string",
"value",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/pkg/server/util.go#L37-L50
|
train
|
osrg/gobgp
|
pkg/server/util.go
|
decodeAdministrativeCommunication
|
func decodeAdministrativeCommunication(data []byte) (string, []byte) {
if len(data) == 0 {
return "", data
}
communicationLen := int(data[0])
if communicationLen > bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX {
communicationLen = bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX
}
if communicationLen > len(data)+1 {
communicationLen = len(data) + 1
}
return string(data[1 : communicationLen+1]), data[communicationLen+1:]
}
|
go
|
func decodeAdministrativeCommunication(data []byte) (string, []byte) {
if len(data) == 0 {
return "", data
}
communicationLen := int(data[0])
if communicationLen > bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX {
communicationLen = bgp.BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX
}
if communicationLen > len(data)+1 {
communicationLen = len(data) + 1
}
return string(data[1 : communicationLen+1]), data[communicationLen+1:]
}
|
[
"func",
"decodeAdministrativeCommunication",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"string",
",",
"[",
"]",
"byte",
")",
"{",
"if",
"len",
"(",
"data",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"data",
"\n",
"}",
"\n",
"communicationLen",
":=",
"int",
"(",
"data",
"[",
"0",
"]",
")",
"\n",
"if",
"communicationLen",
">",
"bgp",
".",
"BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX",
"{",
"communicationLen",
"=",
"bgp",
".",
"BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX",
"\n",
"}",
"\n",
"if",
"communicationLen",
">",
"len",
"(",
"data",
")",
"+",
"1",
"{",
"communicationLen",
"=",
"len",
"(",
"data",
")",
"+",
"1",
"\n",
"}",
"\n",
"return",
"string",
"(",
"data",
"[",
"1",
":",
"communicationLen",
"+",
"1",
"]",
")",
",",
"data",
"[",
"communicationLen",
"+",
"1",
":",
"]",
"\n",
"}"
] |
// Parses the given NOTIFICATION message data as a binary value and returns
// the Administrative Shutdown Communication in string and the rest binary.
|
[
"Parses",
"the",
"given",
"NOTIFICATION",
"message",
"data",
"as",
"a",
"binary",
"value",
"and",
"returns",
"the",
"Administrative",
"Shutdown",
"Communication",
"in",
"string",
"and",
"the",
"rest",
"binary",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/pkg/server/util.go#L54-L66
|
train
|
osrg/gobgp
|
internal/pkg/table/path.go
|
Clone
|
func (path *Path) Clone(isWithdraw bool) *Path {
return &Path{
parent: path,
IsWithdraw: isWithdraw,
IsNexthopInvalid: path.IsNexthopInvalid,
attrsHash: path.attrsHash,
}
}
|
go
|
func (path *Path) Clone(isWithdraw bool) *Path {
return &Path{
parent: path,
IsWithdraw: isWithdraw,
IsNexthopInvalid: path.IsNexthopInvalid,
attrsHash: path.attrsHash,
}
}
|
[
"func",
"(",
"path",
"*",
"Path",
")",
"Clone",
"(",
"isWithdraw",
"bool",
")",
"*",
"Path",
"{",
"return",
"&",
"Path",
"{",
"parent",
":",
"path",
",",
"IsWithdraw",
":",
"isWithdraw",
",",
"IsNexthopInvalid",
":",
"path",
".",
"IsNexthopInvalid",
",",
"attrsHash",
":",
"path",
".",
"attrsHash",
",",
"}",
"\n",
"}"
] |
// create new PathAttributes
|
[
"create",
"new",
"PathAttributes"
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/path.go#L335-L342
|
train
|
osrg/gobgp
|
internal/pkg/table/path.go
|
String
|
func (path *Path) String() string {
s := bytes.NewBuffer(make([]byte, 0, 64))
if path.IsEOR() {
s.WriteString(fmt.Sprintf("{ %s EOR | src: %s }", path.GetRouteFamily(), path.GetSource()))
return s.String()
}
s.WriteString(fmt.Sprintf("{ %s | ", path.getPrefix()))
s.WriteString(fmt.Sprintf("src: %s", path.GetSource()))
s.WriteString(fmt.Sprintf(", nh: %s", path.GetNexthop()))
if path.IsNexthopInvalid {
s.WriteString(" (not reachable)")
}
if path.IsWithdraw {
s.WriteString(", withdraw")
}
s.WriteString(" }")
return s.String()
}
|
go
|
func (path *Path) String() string {
s := bytes.NewBuffer(make([]byte, 0, 64))
if path.IsEOR() {
s.WriteString(fmt.Sprintf("{ %s EOR | src: %s }", path.GetRouteFamily(), path.GetSource()))
return s.String()
}
s.WriteString(fmt.Sprintf("{ %s | ", path.getPrefix()))
s.WriteString(fmt.Sprintf("src: %s", path.GetSource()))
s.WriteString(fmt.Sprintf(", nh: %s", path.GetNexthop()))
if path.IsNexthopInvalid {
s.WriteString(" (not reachable)")
}
if path.IsWithdraw {
s.WriteString(", withdraw")
}
s.WriteString(" }")
return s.String()
}
|
[
"func",
"(",
"path",
"*",
"Path",
")",
"String",
"(",
")",
"string",
"{",
"s",
":=",
"bytes",
".",
"NewBuffer",
"(",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"64",
")",
")",
"\n",
"if",
"path",
".",
"IsEOR",
"(",
")",
"{",
"s",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
".",
"GetRouteFamily",
"(",
")",
",",
"path",
".",
"GetSource",
"(",
")",
")",
")",
"\n",
"return",
"s",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"s",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
".",
"getPrefix",
"(",
")",
")",
")",
"\n",
"s",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
".",
"GetSource",
"(",
")",
")",
")",
"\n",
"s",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
".",
"GetNexthop",
"(",
")",
")",
")",
"\n",
"if",
"path",
".",
"IsNexthopInvalid",
"{",
"s",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"path",
".",
"IsWithdraw",
"{",
"s",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"s",
".",
"WriteString",
"(",
"\"",
"\"",
")",
"\n",
"return",
"s",
".",
"String",
"(",
")",
"\n",
"}"
] |
// return Path's string representation
|
[
"return",
"Path",
"s",
"string",
"representation"
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/path.go#L567-L584
|
train
|
osrg/gobgp
|
internal/pkg/table/path.go
|
GetAsPathLen
|
func (path *Path) GetAsPathLen() int {
var length int = 0
if aspath := path.GetAsPath(); aspath != nil {
for _, as := range aspath.Value {
length += as.ASLen()
}
}
return length
}
|
go
|
func (path *Path) GetAsPathLen() int {
var length int = 0
if aspath := path.GetAsPath(); aspath != nil {
for _, as := range aspath.Value {
length += as.ASLen()
}
}
return length
}
|
[
"func",
"(",
"path",
"*",
"Path",
")",
"GetAsPathLen",
"(",
")",
"int",
"{",
"var",
"length",
"int",
"=",
"0",
"\n",
"if",
"aspath",
":=",
"path",
".",
"GetAsPath",
"(",
")",
";",
"aspath",
"!=",
"nil",
"{",
"for",
"_",
",",
"as",
":=",
"range",
"aspath",
".",
"Value",
"{",
"length",
"+=",
"as",
".",
"ASLen",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"length",
"\n",
"}"
] |
// GetAsPathLen returns the number of AS_PATH
|
[
"GetAsPathLen",
"returns",
"the",
"number",
"of",
"AS_PATH"
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/path.go#L599-L608
|
train
|
osrg/gobgp
|
internal/pkg/table/path.go
|
SetCommunities
|
func (path *Path) SetCommunities(communities []uint32, doReplace bool) {
if len(communities) == 0 && doReplace {
// clear communities
path.delPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES)
return
}
newList := make([]uint32, 0)
attr := path.getPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES)
if attr != nil {
c := attr.(*bgp.PathAttributeCommunities)
if doReplace {
newList = append(newList, communities...)
} else {
newList = append(newList, c.Value...)
newList = append(newList, communities...)
}
} else {
newList = append(newList, communities...)
}
path.setPathAttr(bgp.NewPathAttributeCommunities(newList))
}
|
go
|
func (path *Path) SetCommunities(communities []uint32, doReplace bool) {
if len(communities) == 0 && doReplace {
// clear communities
path.delPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES)
return
}
newList := make([]uint32, 0)
attr := path.getPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES)
if attr != nil {
c := attr.(*bgp.PathAttributeCommunities)
if doReplace {
newList = append(newList, communities...)
} else {
newList = append(newList, c.Value...)
newList = append(newList, communities...)
}
} else {
newList = append(newList, communities...)
}
path.setPathAttr(bgp.NewPathAttributeCommunities(newList))
}
|
[
"func",
"(",
"path",
"*",
"Path",
")",
"SetCommunities",
"(",
"communities",
"[",
"]",
"uint32",
",",
"doReplace",
"bool",
")",
"{",
"if",
"len",
"(",
"communities",
")",
"==",
"0",
"&&",
"doReplace",
"{",
"// clear communities",
"path",
".",
"delPathAttr",
"(",
"bgp",
".",
"BGP_ATTR_TYPE_COMMUNITIES",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"newList",
":=",
"make",
"(",
"[",
"]",
"uint32",
",",
"0",
")",
"\n",
"attr",
":=",
"path",
".",
"getPathAttr",
"(",
"bgp",
".",
"BGP_ATTR_TYPE_COMMUNITIES",
")",
"\n",
"if",
"attr",
"!=",
"nil",
"{",
"c",
":=",
"attr",
".",
"(",
"*",
"bgp",
".",
"PathAttributeCommunities",
")",
"\n",
"if",
"doReplace",
"{",
"newList",
"=",
"append",
"(",
"newList",
",",
"communities",
"...",
")",
"\n",
"}",
"else",
"{",
"newList",
"=",
"append",
"(",
"newList",
",",
"c",
".",
"Value",
"...",
")",
"\n",
"newList",
"=",
"append",
"(",
"newList",
",",
"communities",
"...",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"newList",
"=",
"append",
"(",
"newList",
",",
"communities",
"...",
")",
"\n",
"}",
"\n",
"path",
".",
"setPathAttr",
"(",
"bgp",
".",
"NewPathAttributeCommunities",
"(",
"newList",
")",
")",
"\n\n",
"}"
] |
// SetCommunities adds or replaces communities with new ones.
// If the length of communities is 0 and doReplace is true, it clears communities.
|
[
"SetCommunities",
"adds",
"or",
"replaces",
"communities",
"with",
"new",
"ones",
".",
"If",
"the",
"length",
"of",
"communities",
"is",
"0",
"and",
"doReplace",
"is",
"true",
"it",
"clears",
"communities",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/path.go#L800-L823
|
train
|
osrg/gobgp
|
internal/pkg/table/path.go
|
RemoveCommunities
|
func (path *Path) RemoveCommunities(communities []uint32) int {
if len(communities) == 0 {
// do nothing
return 0
}
find := func(val uint32) bool {
for _, com := range communities {
if com == val {
return true
}
}
return false
}
count := 0
attr := path.getPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES)
if attr != nil {
newList := make([]uint32, 0)
c := attr.(*bgp.PathAttributeCommunities)
for _, value := range c.Value {
if find(value) {
count += 1
} else {
newList = append(newList, value)
}
}
if len(newList) != 0 {
path.setPathAttr(bgp.NewPathAttributeCommunities(newList))
} else {
path.delPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES)
}
}
return count
}
|
go
|
func (path *Path) RemoveCommunities(communities []uint32) int {
if len(communities) == 0 {
// do nothing
return 0
}
find := func(val uint32) bool {
for _, com := range communities {
if com == val {
return true
}
}
return false
}
count := 0
attr := path.getPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES)
if attr != nil {
newList := make([]uint32, 0)
c := attr.(*bgp.PathAttributeCommunities)
for _, value := range c.Value {
if find(value) {
count += 1
} else {
newList = append(newList, value)
}
}
if len(newList) != 0 {
path.setPathAttr(bgp.NewPathAttributeCommunities(newList))
} else {
path.delPathAttr(bgp.BGP_ATTR_TYPE_COMMUNITIES)
}
}
return count
}
|
[
"func",
"(",
"path",
"*",
"Path",
")",
"RemoveCommunities",
"(",
"communities",
"[",
"]",
"uint32",
")",
"int",
"{",
"if",
"len",
"(",
"communities",
")",
"==",
"0",
"{",
"// do nothing",
"return",
"0",
"\n",
"}",
"\n\n",
"find",
":=",
"func",
"(",
"val",
"uint32",
")",
"bool",
"{",
"for",
"_",
",",
"com",
":=",
"range",
"communities",
"{",
"if",
"com",
"==",
"val",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"count",
":=",
"0",
"\n",
"attr",
":=",
"path",
".",
"getPathAttr",
"(",
"bgp",
".",
"BGP_ATTR_TYPE_COMMUNITIES",
")",
"\n",
"if",
"attr",
"!=",
"nil",
"{",
"newList",
":=",
"make",
"(",
"[",
"]",
"uint32",
",",
"0",
")",
"\n",
"c",
":=",
"attr",
".",
"(",
"*",
"bgp",
".",
"PathAttributeCommunities",
")",
"\n\n",
"for",
"_",
",",
"value",
":=",
"range",
"c",
".",
"Value",
"{",
"if",
"find",
"(",
"value",
")",
"{",
"count",
"+=",
"1",
"\n",
"}",
"else",
"{",
"newList",
"=",
"append",
"(",
"newList",
",",
"value",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"newList",
")",
"!=",
"0",
"{",
"path",
".",
"setPathAttr",
"(",
"bgp",
".",
"NewPathAttributeCommunities",
"(",
"newList",
")",
")",
"\n",
"}",
"else",
"{",
"path",
".",
"delPathAttr",
"(",
"bgp",
".",
"BGP_ATTR_TYPE_COMMUNITIES",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"count",
"\n",
"}"
] |
// RemoveCommunities removes specific communities.
// If the length of communities is 0, it does nothing.
// If all communities are removed, it removes Communities path attribute itself.
|
[
"RemoveCommunities",
"removes",
"specific",
"communities",
".",
"If",
"the",
"length",
"of",
"communities",
"is",
"0",
"it",
"does",
"nothing",
".",
"If",
"all",
"communities",
"are",
"removed",
"it",
"removes",
"Communities",
"path",
"attribute",
"itself",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/path.go#L828-L865
|
train
|
osrg/gobgp
|
internal/pkg/table/path.go
|
SetMed
|
func (path *Path) SetMed(med int64, doReplace bool) error {
parseMed := func(orgMed uint32, med int64, doReplace bool) (*bgp.PathAttributeMultiExitDisc, error) {
if doReplace {
return bgp.NewPathAttributeMultiExitDisc(uint32(med)), nil
}
medVal := int64(orgMed) + med
if medVal < 0 {
return nil, fmt.Errorf("med value invalid. it's underflow threshold: %v", medVal)
} else if medVal > int64(math.MaxUint32) {
return nil, fmt.Errorf("med value invalid. it's overflow threshold: %v", medVal)
}
return bgp.NewPathAttributeMultiExitDisc(uint32(int64(orgMed) + med)), nil
}
m := uint32(0)
if attr := path.getPathAttr(bgp.BGP_ATTR_TYPE_MULTI_EXIT_DISC); attr != nil {
m = attr.(*bgp.PathAttributeMultiExitDisc).Value
}
newMed, err := parseMed(m, med, doReplace)
if err != nil {
return err
}
path.setPathAttr(newMed)
return nil
}
|
go
|
func (path *Path) SetMed(med int64, doReplace bool) error {
parseMed := func(orgMed uint32, med int64, doReplace bool) (*bgp.PathAttributeMultiExitDisc, error) {
if doReplace {
return bgp.NewPathAttributeMultiExitDisc(uint32(med)), nil
}
medVal := int64(orgMed) + med
if medVal < 0 {
return nil, fmt.Errorf("med value invalid. it's underflow threshold: %v", medVal)
} else if medVal > int64(math.MaxUint32) {
return nil, fmt.Errorf("med value invalid. it's overflow threshold: %v", medVal)
}
return bgp.NewPathAttributeMultiExitDisc(uint32(int64(orgMed) + med)), nil
}
m := uint32(0)
if attr := path.getPathAttr(bgp.BGP_ATTR_TYPE_MULTI_EXIT_DISC); attr != nil {
m = attr.(*bgp.PathAttributeMultiExitDisc).Value
}
newMed, err := parseMed(m, med, doReplace)
if err != nil {
return err
}
path.setPathAttr(newMed)
return nil
}
|
[
"func",
"(",
"path",
"*",
"Path",
")",
"SetMed",
"(",
"med",
"int64",
",",
"doReplace",
"bool",
")",
"error",
"{",
"parseMed",
":=",
"func",
"(",
"orgMed",
"uint32",
",",
"med",
"int64",
",",
"doReplace",
"bool",
")",
"(",
"*",
"bgp",
".",
"PathAttributeMultiExitDisc",
",",
"error",
")",
"{",
"if",
"doReplace",
"{",
"return",
"bgp",
".",
"NewPathAttributeMultiExitDisc",
"(",
"uint32",
"(",
"med",
")",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"medVal",
":=",
"int64",
"(",
"orgMed",
")",
"+",
"med",
"\n",
"if",
"medVal",
"<",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"medVal",
")",
"\n",
"}",
"else",
"if",
"medVal",
">",
"int64",
"(",
"math",
".",
"MaxUint32",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"medVal",
")",
"\n",
"}",
"\n\n",
"return",
"bgp",
".",
"NewPathAttributeMultiExitDisc",
"(",
"uint32",
"(",
"int64",
"(",
"orgMed",
")",
"+",
"med",
")",
")",
",",
"nil",
"\n",
"}",
"\n\n",
"m",
":=",
"uint32",
"(",
"0",
")",
"\n",
"if",
"attr",
":=",
"path",
".",
"getPathAttr",
"(",
"bgp",
".",
"BGP_ATTR_TYPE_MULTI_EXIT_DISC",
")",
";",
"attr",
"!=",
"nil",
"{",
"m",
"=",
"attr",
".",
"(",
"*",
"bgp",
".",
"PathAttributeMultiExitDisc",
")",
".",
"Value",
"\n",
"}",
"\n",
"newMed",
",",
"err",
":=",
"parseMed",
"(",
"m",
",",
"med",
",",
"doReplace",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"path",
".",
"setPathAttr",
"(",
"newMed",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SetMed replace, add or subtraction med with new ones.
|
[
"SetMed",
"replace",
"add",
"or",
"subtraction",
"med",
"with",
"new",
"ones",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/path.go#L926-L952
|
train
|
osrg/gobgp
|
internal/pkg/table/policy.go
|
Evaluate
|
func (c *NextHopCondition) Evaluate(path *Path, options *PolicyOptions) bool {
if len(c.set.list) == 0 {
log.WithFields(log.Fields{
"Topic": "Policy",
}).Debug("NextHop doesn't have elements")
return true
}
nexthop := path.GetNexthop()
// In cases where we advertise routes from iBGP to eBGP, we want to filter
// on the "original" nexthop. The current paths' nexthop has already been
// set and is ready to be advertised as per:
// https://tools.ietf.org/html/rfc4271#section-5.1.3
if options != nil && options.OldNextHop != nil &&
!options.OldNextHop.IsUnspecified() && !options.OldNextHop.Equal(nexthop) {
nexthop = options.OldNextHop
}
if nexthop == nil {
return false
}
for _, n := range c.set.list {
if n.Contains(nexthop) {
return true
}
}
return false
}
|
go
|
func (c *NextHopCondition) Evaluate(path *Path, options *PolicyOptions) bool {
if len(c.set.list) == 0 {
log.WithFields(log.Fields{
"Topic": "Policy",
}).Debug("NextHop doesn't have elements")
return true
}
nexthop := path.GetNexthop()
// In cases where we advertise routes from iBGP to eBGP, we want to filter
// on the "original" nexthop. The current paths' nexthop has already been
// set and is ready to be advertised as per:
// https://tools.ietf.org/html/rfc4271#section-5.1.3
if options != nil && options.OldNextHop != nil &&
!options.OldNextHop.IsUnspecified() && !options.OldNextHop.Equal(nexthop) {
nexthop = options.OldNextHop
}
if nexthop == nil {
return false
}
for _, n := range c.set.list {
if n.Contains(nexthop) {
return true
}
}
return false
}
|
[
"func",
"(",
"c",
"*",
"NextHopCondition",
")",
"Evaluate",
"(",
"path",
"*",
"Path",
",",
"options",
"*",
"PolicyOptions",
")",
"bool",
"{",
"if",
"len",
"(",
"c",
".",
"set",
".",
"list",
")",
"==",
"0",
"{",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"nexthop",
":=",
"path",
".",
"GetNexthop",
"(",
")",
"\n\n",
"// In cases where we advertise routes from iBGP to eBGP, we want to filter",
"// on the \"original\" nexthop. The current paths' nexthop has already been",
"// set and is ready to be advertised as per:",
"// https://tools.ietf.org/html/rfc4271#section-5.1.3",
"if",
"options",
"!=",
"nil",
"&&",
"options",
".",
"OldNextHop",
"!=",
"nil",
"&&",
"!",
"options",
".",
"OldNextHop",
".",
"IsUnspecified",
"(",
")",
"&&",
"!",
"options",
".",
"OldNextHop",
".",
"Equal",
"(",
"nexthop",
")",
"{",
"nexthop",
"=",
"options",
".",
"OldNextHop",
"\n",
"}",
"\n\n",
"if",
"nexthop",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"n",
":=",
"range",
"c",
".",
"set",
".",
"list",
"{",
"if",
"n",
".",
"Contains",
"(",
"nexthop",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] |
// compare next-hop ipaddress of this condition and source address of path
// and, subsequent comparisons are skipped if that matches the conditions.
// If NextHopSet's length is zero, return true.
|
[
"compare",
"next",
"-",
"hop",
"ipaddress",
"of",
"this",
"condition",
"and",
"source",
"address",
"of",
"path",
"and",
"subsequent",
"comparisons",
"are",
"skipped",
"if",
"that",
"matches",
"the",
"conditions",
".",
"If",
"NextHopSet",
"s",
"length",
"is",
"zero",
"return",
"true",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L1387-L1417
|
train
|
osrg/gobgp
|
internal/pkg/table/policy.go
|
Evaluate
|
func (c *PrefixCondition) Evaluate(path *Path, _ *PolicyOptions) bool {
var key string
var masklen uint8
keyf := func(ip net.IP, ones int) string {
var buffer bytes.Buffer
for i := 0; i < len(ip) && i < ones; i++ {
buffer.WriteString(fmt.Sprintf("%08b", ip[i]))
}
return buffer.String()[:ones]
}
family := path.GetRouteFamily()
switch family {
case bgp.RF_IPv4_UC:
masklen = path.GetNlri().(*bgp.IPAddrPrefix).Length
key = keyf(path.GetNlri().(*bgp.IPAddrPrefix).Prefix, int(masklen))
case bgp.RF_IPv6_UC:
masklen = path.GetNlri().(*bgp.IPv6AddrPrefix).Length
key = keyf(path.GetNlri().(*bgp.IPv6AddrPrefix).Prefix, int(masklen))
default:
return false
}
if family != c.set.family {
return false
}
result := false
_, ps, ok := c.set.tree.LongestPrefix(key)
if ok {
for _, p := range ps.([]*Prefix) {
if p.MasklengthRangeMin <= masklen && masklen <= p.MasklengthRangeMax {
result = true
break
}
}
}
if c.option == MATCH_OPTION_INVERT {
result = !result
}
return result
}
|
go
|
func (c *PrefixCondition) Evaluate(path *Path, _ *PolicyOptions) bool {
var key string
var masklen uint8
keyf := func(ip net.IP, ones int) string {
var buffer bytes.Buffer
for i := 0; i < len(ip) && i < ones; i++ {
buffer.WriteString(fmt.Sprintf("%08b", ip[i]))
}
return buffer.String()[:ones]
}
family := path.GetRouteFamily()
switch family {
case bgp.RF_IPv4_UC:
masklen = path.GetNlri().(*bgp.IPAddrPrefix).Length
key = keyf(path.GetNlri().(*bgp.IPAddrPrefix).Prefix, int(masklen))
case bgp.RF_IPv6_UC:
masklen = path.GetNlri().(*bgp.IPv6AddrPrefix).Length
key = keyf(path.GetNlri().(*bgp.IPv6AddrPrefix).Prefix, int(masklen))
default:
return false
}
if family != c.set.family {
return false
}
result := false
_, ps, ok := c.set.tree.LongestPrefix(key)
if ok {
for _, p := range ps.([]*Prefix) {
if p.MasklengthRangeMin <= masklen && masklen <= p.MasklengthRangeMax {
result = true
break
}
}
}
if c.option == MATCH_OPTION_INVERT {
result = !result
}
return result
}
|
[
"func",
"(",
"c",
"*",
"PrefixCondition",
")",
"Evaluate",
"(",
"path",
"*",
"Path",
",",
"_",
"*",
"PolicyOptions",
")",
"bool",
"{",
"var",
"key",
"string",
"\n",
"var",
"masklen",
"uint8",
"\n",
"keyf",
":=",
"func",
"(",
"ip",
"net",
".",
"IP",
",",
"ones",
"int",
")",
"string",
"{",
"var",
"buffer",
"bytes",
".",
"Buffer",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"ip",
")",
"&&",
"i",
"<",
"ones",
";",
"i",
"++",
"{",
"buffer",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ip",
"[",
"i",
"]",
")",
")",
"\n",
"}",
"\n",
"return",
"buffer",
".",
"String",
"(",
")",
"[",
":",
"ones",
"]",
"\n",
"}",
"\n",
"family",
":=",
"path",
".",
"GetRouteFamily",
"(",
")",
"\n",
"switch",
"family",
"{",
"case",
"bgp",
".",
"RF_IPv4_UC",
":",
"masklen",
"=",
"path",
".",
"GetNlri",
"(",
")",
".",
"(",
"*",
"bgp",
".",
"IPAddrPrefix",
")",
".",
"Length",
"\n",
"key",
"=",
"keyf",
"(",
"path",
".",
"GetNlri",
"(",
")",
".",
"(",
"*",
"bgp",
".",
"IPAddrPrefix",
")",
".",
"Prefix",
",",
"int",
"(",
"masklen",
")",
")",
"\n",
"case",
"bgp",
".",
"RF_IPv6_UC",
":",
"masklen",
"=",
"path",
".",
"GetNlri",
"(",
")",
".",
"(",
"*",
"bgp",
".",
"IPv6AddrPrefix",
")",
".",
"Length",
"\n",
"key",
"=",
"keyf",
"(",
"path",
".",
"GetNlri",
"(",
")",
".",
"(",
"*",
"bgp",
".",
"IPv6AddrPrefix",
")",
".",
"Prefix",
",",
"int",
"(",
"masklen",
")",
")",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"if",
"family",
"!=",
"c",
".",
"set",
".",
"family",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"result",
":=",
"false",
"\n",
"_",
",",
"ps",
",",
"ok",
":=",
"c",
".",
"set",
".",
"tree",
".",
"LongestPrefix",
"(",
"key",
")",
"\n",
"if",
"ok",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"ps",
".",
"(",
"[",
"]",
"*",
"Prefix",
")",
"{",
"if",
"p",
".",
"MasklengthRangeMin",
"<=",
"masklen",
"&&",
"masklen",
"<=",
"p",
".",
"MasklengthRangeMax",
"{",
"result",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"option",
"==",
"MATCH_OPTION_INVERT",
"{",
"result",
"=",
"!",
"result",
"\n",
"}",
"\n\n",
"return",
"result",
"\n",
"}"
] |
// compare prefixes in this condition and nlri of path and
// subsequent comparison is skipped if that matches the conditions.
// If PrefixList's length is zero, return true.
|
[
"compare",
"prefixes",
"in",
"this",
"condition",
"and",
"nlri",
"of",
"path",
"and",
"subsequent",
"comparison",
"is",
"skipped",
"if",
"that",
"matches",
"the",
"conditions",
".",
"If",
"PrefixList",
"s",
"length",
"is",
"zero",
"return",
"true",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L1454-L1495
|
train
|
osrg/gobgp
|
internal/pkg/table/policy.go
|
Evaluate
|
func (c *NeighborCondition) Evaluate(path *Path, options *PolicyOptions) bool {
if len(c.set.list) == 0 {
log.WithFields(log.Fields{
"Topic": "Policy",
}).Debug("NeighborList doesn't have elements")
return true
}
neighbor := path.GetSource().Address
if options != nil && options.Info != nil && options.Info.Address != nil {
neighbor = options.Info.Address
}
if neighbor == nil {
return false
}
result := false
for _, n := range c.set.list {
if n.Contains(neighbor) {
result = true
break
}
}
if c.option == MATCH_OPTION_INVERT {
result = !result
}
return result
}
|
go
|
func (c *NeighborCondition) Evaluate(path *Path, options *PolicyOptions) bool {
if len(c.set.list) == 0 {
log.WithFields(log.Fields{
"Topic": "Policy",
}).Debug("NeighborList doesn't have elements")
return true
}
neighbor := path.GetSource().Address
if options != nil && options.Info != nil && options.Info.Address != nil {
neighbor = options.Info.Address
}
if neighbor == nil {
return false
}
result := false
for _, n := range c.set.list {
if n.Contains(neighbor) {
result = true
break
}
}
if c.option == MATCH_OPTION_INVERT {
result = !result
}
return result
}
|
[
"func",
"(",
"c",
"*",
"NeighborCondition",
")",
"Evaluate",
"(",
"path",
"*",
"Path",
",",
"options",
"*",
"PolicyOptions",
")",
"bool",
"{",
"if",
"len",
"(",
"c",
".",
"set",
".",
"list",
")",
"==",
"0",
"{",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"}",
")",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n\n",
"neighbor",
":=",
"path",
".",
"GetSource",
"(",
")",
".",
"Address",
"\n",
"if",
"options",
"!=",
"nil",
"&&",
"options",
".",
"Info",
"!=",
"nil",
"&&",
"options",
".",
"Info",
".",
"Address",
"!=",
"nil",
"{",
"neighbor",
"=",
"options",
".",
"Info",
".",
"Address",
"\n",
"}",
"\n\n",
"if",
"neighbor",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"result",
":=",
"false",
"\n",
"for",
"_",
",",
"n",
":=",
"range",
"c",
".",
"set",
".",
"list",
"{",
"if",
"n",
".",
"Contains",
"(",
"neighbor",
")",
"{",
"result",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"option",
"==",
"MATCH_OPTION_INVERT",
"{",
"result",
"=",
"!",
"result",
"\n",
"}",
"\n\n",
"return",
"result",
"\n",
"}"
] |
// compare neighbor ipaddress of this condition and source address of path
// and, subsequent comparisons are skipped if that matches the conditions.
// If NeighborList's length is zero, return true.
|
[
"compare",
"neighbor",
"ipaddress",
"of",
"this",
"condition",
"and",
"source",
"address",
"of",
"path",
"and",
"subsequent",
"comparisons",
"are",
"skipped",
"if",
"that",
"matches",
"the",
"conditions",
".",
"If",
"NeighborList",
"s",
"length",
"is",
"zero",
"return",
"true",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L1535-L1564
|
train
|
osrg/gobgp
|
internal/pkg/table/policy.go
|
Evaluate
|
func (c *AsPathLengthCondition) Evaluate(path *Path, _ *PolicyOptions) bool {
length := uint32(path.GetAsPathLen())
result := false
switch c.operator {
case ATTRIBUTE_EQ:
result = c.length == length
case ATTRIBUTE_GE:
result = c.length <= length
case ATTRIBUTE_LE:
result = c.length >= length
}
return result
}
|
go
|
func (c *AsPathLengthCondition) Evaluate(path *Path, _ *PolicyOptions) bool {
length := uint32(path.GetAsPathLen())
result := false
switch c.operator {
case ATTRIBUTE_EQ:
result = c.length == length
case ATTRIBUTE_GE:
result = c.length <= length
case ATTRIBUTE_LE:
result = c.length >= length
}
return result
}
|
[
"func",
"(",
"c",
"*",
"AsPathLengthCondition",
")",
"Evaluate",
"(",
"path",
"*",
"Path",
",",
"_",
"*",
"PolicyOptions",
")",
"bool",
"{",
"length",
":=",
"uint32",
"(",
"path",
".",
"GetAsPathLen",
"(",
")",
")",
"\n",
"result",
":=",
"false",
"\n",
"switch",
"c",
".",
"operator",
"{",
"case",
"ATTRIBUTE_EQ",
":",
"result",
"=",
"c",
".",
"length",
"==",
"length",
"\n",
"case",
"ATTRIBUTE_GE",
":",
"result",
"=",
"c",
".",
"length",
"<=",
"length",
"\n",
"case",
"ATTRIBUTE_LE",
":",
"result",
"=",
"c",
".",
"length",
">=",
"length",
"\n",
"}",
"\n\n",
"return",
"result",
"\n",
"}"
] |
// compare AS_PATH length in the message's AS_PATH attribute with
// the one in condition.
|
[
"compare",
"AS_PATH",
"length",
"in",
"the",
"message",
"s",
"AS_PATH",
"attribute",
"with",
"the",
"one",
"in",
"condition",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L1855-L1869
|
train
|
osrg/gobgp
|
internal/pkg/table/policy.go
|
NewAsPathPrependAction
|
func NewAsPathPrependAction(action config.SetAsPathPrepend) (*AsPathPrependAction, error) {
a := &AsPathPrependAction{
repeat: action.RepeatN,
}
switch action.As {
case "":
if a.repeat == 0 {
return nil, nil
}
return nil, fmt.Errorf("specify as to prepend")
case "last-as":
a.useLeftMost = true
default:
asn, err := strconv.ParseUint(action.As, 10, 32)
if err != nil {
return nil, fmt.Errorf("AS number string invalid")
}
a.asn = uint32(asn)
}
return a, nil
}
|
go
|
func NewAsPathPrependAction(action config.SetAsPathPrepend) (*AsPathPrependAction, error) {
a := &AsPathPrependAction{
repeat: action.RepeatN,
}
switch action.As {
case "":
if a.repeat == 0 {
return nil, nil
}
return nil, fmt.Errorf("specify as to prepend")
case "last-as":
a.useLeftMost = true
default:
asn, err := strconv.ParseUint(action.As, 10, 32)
if err != nil {
return nil, fmt.Errorf("AS number string invalid")
}
a.asn = uint32(asn)
}
return a, nil
}
|
[
"func",
"NewAsPathPrependAction",
"(",
"action",
"config",
".",
"SetAsPathPrepend",
")",
"(",
"*",
"AsPathPrependAction",
",",
"error",
")",
"{",
"a",
":=",
"&",
"AsPathPrependAction",
"{",
"repeat",
":",
"action",
".",
"RepeatN",
",",
"}",
"\n",
"switch",
"action",
".",
"As",
"{",
"case",
"\"",
"\"",
":",
"if",
"a",
".",
"repeat",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"case",
"\"",
"\"",
":",
"a",
".",
"useLeftMost",
"=",
"true",
"\n",
"default",
":",
"asn",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"action",
".",
"As",
",",
"10",
",",
"32",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"a",
".",
"asn",
"=",
"uint32",
"(",
"asn",
")",
"\n",
"}",
"\n",
"return",
"a",
",",
"nil",
"\n",
"}"
] |
// NewAsPathPrependAction creates AsPathPrependAction object.
// If ASN cannot be parsed, nil will be returned.
|
[
"NewAsPathPrependAction",
"creates",
"AsPathPrependAction",
"object",
".",
"If",
"ASN",
"cannot",
"be",
"parsed",
"nil",
"will",
"be",
"returned",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L2574-L2594
|
train
|
osrg/gobgp
|
internal/pkg/table/policy.go
|
Evaluate
|
func (s *Statement) Evaluate(p *Path, options *PolicyOptions) bool {
for _, c := range s.Conditions {
if !c.Evaluate(p, options) {
return false
}
}
return true
}
|
go
|
func (s *Statement) Evaluate(p *Path, options *PolicyOptions) bool {
for _, c := range s.Conditions {
if !c.Evaluate(p, options) {
return false
}
}
return true
}
|
[
"func",
"(",
"s",
"*",
"Statement",
")",
"Evaluate",
"(",
"p",
"*",
"Path",
",",
"options",
"*",
"PolicyOptions",
")",
"bool",
"{",
"for",
"_",
",",
"c",
":=",
"range",
"s",
".",
"Conditions",
"{",
"if",
"!",
"c",
".",
"Evaluate",
"(",
"p",
",",
"options",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// evaluate each condition in the statement according to MatchSetOptions
|
[
"evaluate",
"each",
"condition",
"in",
"the",
"statement",
"according",
"to",
"MatchSetOptions"
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L2657-L2664
|
train
|
osrg/gobgp
|
internal/pkg/table/policy.go
|
Apply
|
func (p *Policy) Apply(path *Path, options *PolicyOptions) (RouteType, *Path) {
for _, stmt := range p.Statements {
var result RouteType
result, path = stmt.Apply(path, options)
if result != ROUTE_TYPE_NONE {
return result, path
}
}
return ROUTE_TYPE_NONE, path
}
|
go
|
func (p *Policy) Apply(path *Path, options *PolicyOptions) (RouteType, *Path) {
for _, stmt := range p.Statements {
var result RouteType
result, path = stmt.Apply(path, options)
if result != ROUTE_TYPE_NONE {
return result, path
}
}
return ROUTE_TYPE_NONE, path
}
|
[
"func",
"(",
"p",
"*",
"Policy",
")",
"Apply",
"(",
"path",
"*",
"Path",
",",
"options",
"*",
"PolicyOptions",
")",
"(",
"RouteType",
",",
"*",
"Path",
")",
"{",
"for",
"_",
",",
"stmt",
":=",
"range",
"p",
".",
"Statements",
"{",
"var",
"result",
"RouteType",
"\n",
"result",
",",
"path",
"=",
"stmt",
".",
"Apply",
"(",
"path",
",",
"options",
")",
"\n",
"if",
"result",
"!=",
"ROUTE_TYPE_NONE",
"{",
"return",
"result",
",",
"path",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"ROUTE_TYPE_NONE",
",",
"path",
"\n",
"}"
] |
// Compare path with a policy's condition in stored order in the policy.
// If a condition match, then this function stops evaluation and
// subsequent conditions are skipped.
|
[
"Compare",
"path",
"with",
"a",
"policy",
"s",
"condition",
"in",
"stored",
"order",
"in",
"the",
"policy",
".",
"If",
"a",
"condition",
"match",
"then",
"this",
"function",
"stops",
"evaluation",
"and",
"subsequent",
"conditions",
"are",
"skipped",
"."
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/table/policy.go#L2990-L2999
|
train
|
osrg/gobgp
|
internal/pkg/zebra/zapi.go
|
ChannelClose
|
func ChannelClose(ch chan *Message) bool {
select {
case _, ok := <-ch:
if ok {
close(ch)
return true
}
default:
}
return false
}
|
go
|
func ChannelClose(ch chan *Message) bool {
select {
case _, ok := <-ch:
if ok {
close(ch)
return true
}
default:
}
return false
}
|
[
"func",
"ChannelClose",
"(",
"ch",
"chan",
"*",
"Message",
")",
"bool",
"{",
"select",
"{",
"case",
"_",
",",
"ok",
":=",
"<-",
"ch",
":",
"if",
"ok",
"{",
"close",
"(",
"ch",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"default",
":",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// for avoiding double close
|
[
"for",
"avoiding",
"double",
"close"
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/internal/pkg/zebra/zapi.go#L1415-L1425
|
train
|
osrg/gobgp
|
pkg/packet/bgp/validate.go
|
validatePathAttributeFlags
|
func validatePathAttributeFlags(t BGPAttrType, flags BGPAttrFlag) string {
/*
* RFC 4271 P.17 For well-known attributes, the Transitive bit MUST be set to 1.
*/
if flags&BGP_ATTR_FLAG_OPTIONAL == 0 && flags&BGP_ATTR_FLAG_TRANSITIVE == 0 {
eMsg := fmt.Sprintf("well-known attribute %s must have transitive flag 1", t)
return eMsg
}
/*
* RFC 4271 P.17 For well-known attributes and for optional non-transitive attributes,
* the Partial bit MUST be set to 0.
*/
if flags&BGP_ATTR_FLAG_OPTIONAL == 0 && flags&BGP_ATTR_FLAG_PARTIAL != 0 {
eMsg := fmt.Sprintf("well-known attribute %s must have partial bit 0", t)
return eMsg
}
if flags&BGP_ATTR_FLAG_OPTIONAL != 0 && flags&BGP_ATTR_FLAG_TRANSITIVE == 0 && flags&BGP_ATTR_FLAG_PARTIAL != 0 {
eMsg := fmt.Sprintf("optional non-transitive attribute %s must have partial bit 0", t)
return eMsg
}
// check flags are correct
if f, ok := PathAttrFlags[t]; ok {
if f != flags & ^BGP_ATTR_FLAG_EXTENDED_LENGTH & ^BGP_ATTR_FLAG_PARTIAL {
eMsg := fmt.Sprintf("flags are invalid. attribute type: %s, expect: %s, actual: %s", t, f, flags)
return eMsg
}
}
return ""
}
|
go
|
func validatePathAttributeFlags(t BGPAttrType, flags BGPAttrFlag) string {
/*
* RFC 4271 P.17 For well-known attributes, the Transitive bit MUST be set to 1.
*/
if flags&BGP_ATTR_FLAG_OPTIONAL == 0 && flags&BGP_ATTR_FLAG_TRANSITIVE == 0 {
eMsg := fmt.Sprintf("well-known attribute %s must have transitive flag 1", t)
return eMsg
}
/*
* RFC 4271 P.17 For well-known attributes and for optional non-transitive attributes,
* the Partial bit MUST be set to 0.
*/
if flags&BGP_ATTR_FLAG_OPTIONAL == 0 && flags&BGP_ATTR_FLAG_PARTIAL != 0 {
eMsg := fmt.Sprintf("well-known attribute %s must have partial bit 0", t)
return eMsg
}
if flags&BGP_ATTR_FLAG_OPTIONAL != 0 && flags&BGP_ATTR_FLAG_TRANSITIVE == 0 && flags&BGP_ATTR_FLAG_PARTIAL != 0 {
eMsg := fmt.Sprintf("optional non-transitive attribute %s must have partial bit 0", t)
return eMsg
}
// check flags are correct
if f, ok := PathAttrFlags[t]; ok {
if f != flags & ^BGP_ATTR_FLAG_EXTENDED_LENGTH & ^BGP_ATTR_FLAG_PARTIAL {
eMsg := fmt.Sprintf("flags are invalid. attribute type: %s, expect: %s, actual: %s", t, f, flags)
return eMsg
}
}
return ""
}
|
[
"func",
"validatePathAttributeFlags",
"(",
"t",
"BGPAttrType",
",",
"flags",
"BGPAttrFlag",
")",
"string",
"{",
"/*\n\t * RFC 4271 P.17 For well-known attributes, the Transitive bit MUST be set to 1.\n\t */",
"if",
"flags",
"&",
"BGP_ATTR_FLAG_OPTIONAL",
"==",
"0",
"&&",
"flags",
"&",
"BGP_ATTR_FLAG_TRANSITIVE",
"==",
"0",
"{",
"eMsg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
")",
"\n",
"return",
"eMsg",
"\n",
"}",
"\n",
"/*\n\t * RFC 4271 P.17 For well-known attributes and for optional non-transitive attributes,\n\t * the Partial bit MUST be set to 0.\n\t */",
"if",
"flags",
"&",
"BGP_ATTR_FLAG_OPTIONAL",
"==",
"0",
"&&",
"flags",
"&",
"BGP_ATTR_FLAG_PARTIAL",
"!=",
"0",
"{",
"eMsg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
")",
"\n",
"return",
"eMsg",
"\n",
"}",
"\n",
"if",
"flags",
"&",
"BGP_ATTR_FLAG_OPTIONAL",
"!=",
"0",
"&&",
"flags",
"&",
"BGP_ATTR_FLAG_TRANSITIVE",
"==",
"0",
"&&",
"flags",
"&",
"BGP_ATTR_FLAG_PARTIAL",
"!=",
"0",
"{",
"eMsg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
")",
"\n",
"return",
"eMsg",
"\n",
"}",
"\n\n",
"// check flags are correct",
"if",
"f",
",",
"ok",
":=",
"PathAttrFlags",
"[",
"t",
"]",
";",
"ok",
"{",
"if",
"f",
"!=",
"flags",
"&",
"^",
"BGP_ATTR_FLAG_EXTENDED_LENGTH",
"&",
"^",
"BGP_ATTR_FLAG_PARTIAL",
"{",
"eMsg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
",",
"f",
",",
"flags",
")",
"\n",
"return",
"eMsg",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] |
// validator for PathAttribute
|
[
"validator",
"for",
"PathAttribute"
] |
cc267fad9e6410705420af220d73d25d288e8a58
|
https://github.com/osrg/gobgp/blob/cc267fad9e6410705420af220d73d25d288e8a58/pkg/packet/bgp/validate.go#L227-L257
|
train
|
rs/cors
|
wrapper/gin/gin.go
|
build
|
func (c corsWrapper) build() gin.HandlerFunc {
return func(ctx *gin.Context) {
c.HandlerFunc(ctx.Writer, ctx.Request)
if !c.optionPassthrough &&
ctx.Request.Method == http.MethodOptions &&
ctx.GetHeader("Access-Control-Request-Method") != "" {
// Abort processing next Gin middlewares.
ctx.AbortWithStatus(http.StatusOK)
}
}
}
|
go
|
func (c corsWrapper) build() gin.HandlerFunc {
return func(ctx *gin.Context) {
c.HandlerFunc(ctx.Writer, ctx.Request)
if !c.optionPassthrough &&
ctx.Request.Method == http.MethodOptions &&
ctx.GetHeader("Access-Control-Request-Method") != "" {
// Abort processing next Gin middlewares.
ctx.AbortWithStatus(http.StatusOK)
}
}
}
|
[
"func",
"(",
"c",
"corsWrapper",
")",
"build",
"(",
")",
"gin",
".",
"HandlerFunc",
"{",
"return",
"func",
"(",
"ctx",
"*",
"gin",
".",
"Context",
")",
"{",
"c",
".",
"HandlerFunc",
"(",
"ctx",
".",
"Writer",
",",
"ctx",
".",
"Request",
")",
"\n",
"if",
"!",
"c",
".",
"optionPassthrough",
"&&",
"ctx",
".",
"Request",
".",
"Method",
"==",
"http",
".",
"MethodOptions",
"&&",
"ctx",
".",
"GetHeader",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"// Abort processing next Gin middlewares.",
"ctx",
".",
"AbortWithStatus",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// build transforms wrapped cors.Cors handler into Gin middleware.
|
[
"build",
"transforms",
"wrapped",
"cors",
".",
"Cors",
"handler",
"into",
"Gin",
"middleware",
"."
] |
76f58f330d76a55c5badc74f6212e8a15e742c77
|
https://github.com/rs/cors/blob/76f58f330d76a55c5badc74f6212e8a15e742c77/wrapper/gin/gin.go#L23-L33
|
train
|
rs/cors
|
wrapper/gin/gin.go
|
New
|
func New(options Options) gin.HandlerFunc {
return corsWrapper{cors.New(options), options.OptionsPassthrough}.build()
}
|
go
|
func New(options Options) gin.HandlerFunc {
return corsWrapper{cors.New(options), options.OptionsPassthrough}.build()
}
|
[
"func",
"New",
"(",
"options",
"Options",
")",
"gin",
".",
"HandlerFunc",
"{",
"return",
"corsWrapper",
"{",
"cors",
".",
"New",
"(",
"options",
")",
",",
"options",
".",
"OptionsPassthrough",
"}",
".",
"build",
"(",
")",
"\n",
"}"
] |
// New creates a new CORS Gin middleware with the provided options.
|
[
"New",
"creates",
"a",
"new",
"CORS",
"Gin",
"middleware",
"with",
"the",
"provided",
"options",
"."
] |
76f58f330d76a55c5badc74f6212e8a15e742c77
|
https://github.com/rs/cors/blob/76f58f330d76a55c5badc74f6212e8a15e742c77/wrapper/gin/gin.go#L48-L50
|
train
|
rs/cors
|
cors.go
|
AllowAll
|
func AllowAll() *Cors {
return New(Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{
http.MethodHead,
http.MethodGet,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
},
AllowedHeaders: []string{"*"},
AllowCredentials: false,
})
}
|
go
|
func AllowAll() *Cors {
return New(Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{
http.MethodHead,
http.MethodGet,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
},
AllowedHeaders: []string{"*"},
AllowCredentials: false,
})
}
|
[
"func",
"AllowAll",
"(",
")",
"*",
"Cors",
"{",
"return",
"New",
"(",
"Options",
"{",
"AllowedOrigins",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"AllowedMethods",
":",
"[",
"]",
"string",
"{",
"http",
".",
"MethodHead",
",",
"http",
".",
"MethodGet",
",",
"http",
".",
"MethodPost",
",",
"http",
".",
"MethodPut",
",",
"http",
".",
"MethodPatch",
",",
"http",
".",
"MethodDelete",
",",
"}",
",",
"AllowedHeaders",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"AllowCredentials",
":",
"false",
",",
"}",
")",
"\n",
"}"
] |
// AllowAll create a new Cors handler with permissive configuration allowing all
// origins with all standard methods with any header and credentials.
|
[
"AllowAll",
"create",
"a",
"new",
"Cors",
"handler",
"with",
"permissive",
"configuration",
"allowing",
"all",
"origins",
"with",
"all",
"standard",
"methods",
"with",
"any",
"header",
"and",
"credentials",
"."
] |
76f58f330d76a55c5badc74f6212e8a15e742c77
|
https://github.com/rs/cors/blob/76f58f330d76a55c5badc74f6212e8a15e742c77/cors.go#L179-L193
|
train
|
rs/cors
|
cors.go
|
Handler
|
func (c *Cors) Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
c.logf("Handler: Preflight request")
c.handlePreflight(w, r)
// Preflight requests are standalone and should stop the chain as some other
// middleware may not handle OPTIONS requests correctly. One typical example
// is authentication middleware ; OPTIONS requests won't carry authentication
// headers (see #1)
if c.optionPassthrough {
h.ServeHTTP(w, r)
} else {
w.WriteHeader(http.StatusOK)
}
} else {
c.logf("Handler: Actual request")
c.handleActualRequest(w, r)
h.ServeHTTP(w, r)
}
})
}
|
go
|
func (c *Cors) Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
c.logf("Handler: Preflight request")
c.handlePreflight(w, r)
// Preflight requests are standalone and should stop the chain as some other
// middleware may not handle OPTIONS requests correctly. One typical example
// is authentication middleware ; OPTIONS requests won't carry authentication
// headers (see #1)
if c.optionPassthrough {
h.ServeHTTP(w, r)
} else {
w.WriteHeader(http.StatusOK)
}
} else {
c.logf("Handler: Actual request")
c.handleActualRequest(w, r)
h.ServeHTTP(w, r)
}
})
}
|
[
"func",
"(",
"c",
"*",
"Cors",
")",
"Handler",
"(",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Method",
"==",
"http",
".",
"MethodOptions",
"&&",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"c",
".",
"logf",
"(",
"\"",
"\"",
")",
"\n",
"c",
".",
"handlePreflight",
"(",
"w",
",",
"r",
")",
"\n",
"// Preflight requests are standalone and should stop the chain as some other",
"// middleware may not handle OPTIONS requests correctly. One typical example",
"// is authentication middleware ; OPTIONS requests won't carry authentication",
"// headers (see #1)",
"if",
"c",
".",
"optionPassthrough",
"{",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"else",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"c",
".",
"logf",
"(",
"\"",
"\"",
")",
"\n",
"c",
".",
"handleActualRequest",
"(",
"w",
",",
"r",
")",
"\n",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
")",
"\n",
"}"
] |
// Handler apply the CORS specification on the request, and add relevant CORS headers
// as necessary.
|
[
"Handler",
"apply",
"the",
"CORS",
"specification",
"on",
"the",
"request",
"and",
"add",
"relevant",
"CORS",
"headers",
"as",
"necessary",
"."
] |
76f58f330d76a55c5badc74f6212e8a15e742c77
|
https://github.com/rs/cors/blob/76f58f330d76a55c5badc74f6212e8a15e742c77/cors.go#L197-L217
|
train
|
rs/cors
|
cors.go
|
HandlerFunc
|
func (c *Cors) HandlerFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
c.logf("HandlerFunc: Preflight request")
c.handlePreflight(w, r)
} else {
c.logf("HandlerFunc: Actual request")
c.handleActualRequest(w, r)
}
}
|
go
|
func (c *Cors) HandlerFunc(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
c.logf("HandlerFunc: Preflight request")
c.handlePreflight(w, r)
} else {
c.logf("HandlerFunc: Actual request")
c.handleActualRequest(w, r)
}
}
|
[
"func",
"(",
"c",
"*",
"Cors",
")",
"HandlerFunc",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Method",
"==",
"http",
".",
"MethodOptions",
"&&",
"r",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"c",
".",
"logf",
"(",
"\"",
"\"",
")",
"\n",
"c",
".",
"handlePreflight",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"else",
"{",
"c",
".",
"logf",
"(",
"\"",
"\"",
")",
"\n",
"c",
".",
"handleActualRequest",
"(",
"w",
",",
"r",
")",
"\n",
"}",
"\n",
"}"
] |
// HandlerFunc provides Martini compatible handler
|
[
"HandlerFunc",
"provides",
"Martini",
"compatible",
"handler"
] |
76f58f330d76a55c5badc74f6212e8a15e742c77
|
https://github.com/rs/cors/blob/76f58f330d76a55c5badc74f6212e8a15e742c77/cors.go#L220-L228
|
train
|
rs/cors
|
cors.go
|
areHeadersAllowed
|
func (c *Cors) areHeadersAllowed(requestedHeaders []string) bool {
if c.allowedHeadersAll || len(requestedHeaders) == 0 {
return true
}
for _, header := range requestedHeaders {
header = http.CanonicalHeaderKey(header)
found := false
for _, h := range c.allowedHeaders {
if h == header {
found = true
}
}
if !found {
return false
}
}
return true
}
|
go
|
func (c *Cors) areHeadersAllowed(requestedHeaders []string) bool {
if c.allowedHeadersAll || len(requestedHeaders) == 0 {
return true
}
for _, header := range requestedHeaders {
header = http.CanonicalHeaderKey(header)
found := false
for _, h := range c.allowedHeaders {
if h == header {
found = true
}
}
if !found {
return false
}
}
return true
}
|
[
"func",
"(",
"c",
"*",
"Cors",
")",
"areHeadersAllowed",
"(",
"requestedHeaders",
"[",
"]",
"string",
")",
"bool",
"{",
"if",
"c",
".",
"allowedHeadersAll",
"||",
"len",
"(",
"requestedHeaders",
")",
"==",
"0",
"{",
"return",
"true",
"\n",
"}",
"\n",
"for",
"_",
",",
"header",
":=",
"range",
"requestedHeaders",
"{",
"header",
"=",
"http",
".",
"CanonicalHeaderKey",
"(",
"header",
")",
"\n",
"found",
":=",
"false",
"\n",
"for",
"_",
",",
"h",
":=",
"range",
"c",
".",
"allowedHeaders",
"{",
"if",
"h",
"==",
"header",
"{",
"found",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"found",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// areHeadersAllowed checks if a given list of headers are allowed to used within
// a cross-domain request.
|
[
"areHeadersAllowed",
"checks",
"if",
"a",
"given",
"list",
"of",
"headers",
"are",
"allowed",
"to",
"used",
"within",
"a",
"cross",
"-",
"domain",
"request",
"."
] |
76f58f330d76a55c5badc74f6212e8a15e742c77
|
https://github.com/rs/cors/blob/76f58f330d76a55c5badc74f6212e8a15e742c77/cors.go#L407-L424
|
train
|
shiyanhui/dht
|
routingtable.go
|
newNode
|
func newNode(id, network, address string) (*node, error) {
if len(id) != 20 {
return nil, errors.New("node id should be a 20-length string")
}
addr, err := net.ResolveUDPAddr(network, address)
if err != nil {
return nil, err
}
return &node{newBitmapFromString(id), addr, time.Now()}, nil
}
|
go
|
func newNode(id, network, address string) (*node, error) {
if len(id) != 20 {
return nil, errors.New("node id should be a 20-length string")
}
addr, err := net.ResolveUDPAddr(network, address)
if err != nil {
return nil, err
}
return &node{newBitmapFromString(id), addr, time.Now()}, nil
}
|
[
"func",
"newNode",
"(",
"id",
",",
"network",
",",
"address",
"string",
")",
"(",
"*",
"node",
",",
"error",
")",
"{",
"if",
"len",
"(",
"id",
")",
"!=",
"20",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"addr",
",",
"err",
":=",
"net",
".",
"ResolveUDPAddr",
"(",
"network",
",",
"address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"node",
"{",
"newBitmapFromString",
"(",
"id",
")",
",",
"addr",
",",
"time",
".",
"Now",
"(",
")",
"}",
",",
"nil",
"\n",
"}"
] |
// newNode returns a node pointer.
|
[
"newNode",
"returns",
"a",
"node",
"pointer",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L23-L34
|
train
|
shiyanhui/dht
|
routingtable.go
|
newNodeFromCompactInfo
|
func newNodeFromCompactInfo(
compactNodeInfo string, network string) (*node, error) {
if len(compactNodeInfo) != 26 {
return nil, errors.New("compactNodeInfo should be a 26-length string")
}
id := compactNodeInfo[:20]
ip, port, _ := decodeCompactIPPortInfo(compactNodeInfo[20:])
return newNode(id, network, genAddress(ip.String(), port))
}
|
go
|
func newNodeFromCompactInfo(
compactNodeInfo string, network string) (*node, error) {
if len(compactNodeInfo) != 26 {
return nil, errors.New("compactNodeInfo should be a 26-length string")
}
id := compactNodeInfo[:20]
ip, port, _ := decodeCompactIPPortInfo(compactNodeInfo[20:])
return newNode(id, network, genAddress(ip.String(), port))
}
|
[
"func",
"newNodeFromCompactInfo",
"(",
"compactNodeInfo",
"string",
",",
"network",
"string",
")",
"(",
"*",
"node",
",",
"error",
")",
"{",
"if",
"len",
"(",
"compactNodeInfo",
")",
"!=",
"26",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"id",
":=",
"compactNodeInfo",
"[",
":",
"20",
"]",
"\n",
"ip",
",",
"port",
",",
"_",
":=",
"decodeCompactIPPortInfo",
"(",
"compactNodeInfo",
"[",
"20",
":",
"]",
")",
"\n\n",
"return",
"newNode",
"(",
"id",
",",
"network",
",",
"genAddress",
"(",
"ip",
".",
"String",
"(",
")",
",",
"port",
")",
")",
"\n",
"}"
] |
// newNodeFromCompactInfo parses compactNodeInfo and returns a node pointer.
|
[
"newNodeFromCompactInfo",
"parses",
"compactNodeInfo",
"and",
"returns",
"a",
"node",
"pointer",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L37-L48
|
train
|
shiyanhui/dht
|
routingtable.go
|
newPeer
|
func newPeer(ip net.IP, port int, token string) *Peer {
return &Peer{
IP: ip,
Port: port,
token: token,
}
}
|
go
|
func newPeer(ip net.IP, port int, token string) *Peer {
return &Peer{
IP: ip,
Port: port,
token: token,
}
}
|
[
"func",
"newPeer",
"(",
"ip",
"net",
".",
"IP",
",",
"port",
"int",
",",
"token",
"string",
")",
"*",
"Peer",
"{",
"return",
"&",
"Peer",
"{",
"IP",
":",
"ip",
",",
"Port",
":",
"port",
",",
"token",
":",
"token",
",",
"}",
"\n",
"}"
] |
// newPeer returns a new peer pointer.
|
[
"newPeer",
"returns",
"a",
"new",
"peer",
"pointer",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L73-L79
|
train
|
shiyanhui/dht
|
routingtable.go
|
Insert
|
func (pm *peersManager) Insert(infoHash string, peer *Peer) {
pm.Lock()
if _, ok := pm.table.Get(infoHash); !ok {
pm.table.Set(infoHash, newKeyedDeque())
}
pm.Unlock()
v, _ := pm.table.Get(infoHash)
queue := v.(*keyedDeque)
queue.Push(peer.CompactIPPortInfo(), peer)
if queue.Len() > pm.dht.K {
queue.Remove(queue.Front())
}
}
|
go
|
func (pm *peersManager) Insert(infoHash string, peer *Peer) {
pm.Lock()
if _, ok := pm.table.Get(infoHash); !ok {
pm.table.Set(infoHash, newKeyedDeque())
}
pm.Unlock()
v, _ := pm.table.Get(infoHash)
queue := v.(*keyedDeque)
queue.Push(peer.CompactIPPortInfo(), peer)
if queue.Len() > pm.dht.K {
queue.Remove(queue.Front())
}
}
|
[
"func",
"(",
"pm",
"*",
"peersManager",
")",
"Insert",
"(",
"infoHash",
"string",
",",
"peer",
"*",
"Peer",
")",
"{",
"pm",
".",
"Lock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"pm",
".",
"table",
".",
"Get",
"(",
"infoHash",
")",
";",
"!",
"ok",
"{",
"pm",
".",
"table",
".",
"Set",
"(",
"infoHash",
",",
"newKeyedDeque",
"(",
")",
")",
"\n",
"}",
"\n",
"pm",
".",
"Unlock",
"(",
")",
"\n\n",
"v",
",",
"_",
":=",
"pm",
".",
"table",
".",
"Get",
"(",
"infoHash",
")",
"\n",
"queue",
":=",
"v",
".",
"(",
"*",
"keyedDeque",
")",
"\n\n",
"queue",
".",
"Push",
"(",
"peer",
".",
"CompactIPPortInfo",
"(",
")",
",",
"peer",
")",
"\n",
"if",
"queue",
".",
"Len",
"(",
")",
">",
"pm",
".",
"dht",
".",
"K",
"{",
"queue",
".",
"Remove",
"(",
"queue",
".",
"Front",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Insert adds a peer into peersManager.
|
[
"Insert",
"adds",
"a",
"peer",
"into",
"peersManager",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L114-L128
|
train
|
shiyanhui/dht
|
routingtable.go
|
GetPeers
|
func (pm *peersManager) GetPeers(infoHash string, size int) []*Peer {
peers := make([]*Peer, 0, size)
v, ok := pm.table.Get(infoHash)
if !ok {
return peers
}
for e := range v.(*keyedDeque).Iter() {
peers = append(peers, e.Value.(*Peer))
}
if len(peers) > size {
peers = peers[len(peers)-size:]
}
return peers
}
|
go
|
func (pm *peersManager) GetPeers(infoHash string, size int) []*Peer {
peers := make([]*Peer, 0, size)
v, ok := pm.table.Get(infoHash)
if !ok {
return peers
}
for e := range v.(*keyedDeque).Iter() {
peers = append(peers, e.Value.(*Peer))
}
if len(peers) > size {
peers = peers[len(peers)-size:]
}
return peers
}
|
[
"func",
"(",
"pm",
"*",
"peersManager",
")",
"GetPeers",
"(",
"infoHash",
"string",
",",
"size",
"int",
")",
"[",
"]",
"*",
"Peer",
"{",
"peers",
":=",
"make",
"(",
"[",
"]",
"*",
"Peer",
",",
"0",
",",
"size",
")",
"\n\n",
"v",
",",
"ok",
":=",
"pm",
".",
"table",
".",
"Get",
"(",
"infoHash",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"peers",
"\n",
"}",
"\n\n",
"for",
"e",
":=",
"range",
"v",
".",
"(",
"*",
"keyedDeque",
")",
".",
"Iter",
"(",
")",
"{",
"peers",
"=",
"append",
"(",
"peers",
",",
"e",
".",
"Value",
".",
"(",
"*",
"Peer",
")",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"peers",
")",
">",
"size",
"{",
"peers",
"=",
"peers",
"[",
"len",
"(",
"peers",
")",
"-",
"size",
":",
"]",
"\n",
"}",
"\n",
"return",
"peers",
"\n",
"}"
] |
// GetPeers returns size-length peers who announces having infoHash.
|
[
"GetPeers",
"returns",
"size",
"-",
"length",
"peers",
"who",
"announces",
"having",
"infoHash",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L131-L147
|
train
|
shiyanhui/dht
|
routingtable.go
|
newKBucket
|
func newKBucket(prefix *bitmap) *kbucket {
bucket := &kbucket{
nodes: newKeyedDeque(),
candidates: newKeyedDeque(),
lastChanged: time.Now(),
prefix: prefix,
}
return bucket
}
|
go
|
func newKBucket(prefix *bitmap) *kbucket {
bucket := &kbucket{
nodes: newKeyedDeque(),
candidates: newKeyedDeque(),
lastChanged: time.Now(),
prefix: prefix,
}
return bucket
}
|
[
"func",
"newKBucket",
"(",
"prefix",
"*",
"bitmap",
")",
"*",
"kbucket",
"{",
"bucket",
":=",
"&",
"kbucket",
"{",
"nodes",
":",
"newKeyedDeque",
"(",
")",
",",
"candidates",
":",
"newKeyedDeque",
"(",
")",
",",
"lastChanged",
":",
"time",
".",
"Now",
"(",
")",
",",
"prefix",
":",
"prefix",
",",
"}",
"\n",
"return",
"bucket",
"\n",
"}"
] |
// newKBucket returns a new kbucket pointer.
|
[
"newKBucket",
"returns",
"a",
"new",
"kbucket",
"pointer",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L158-L166
|
train
|
shiyanhui/dht
|
routingtable.go
|
LastChanged
|
func (bucket *kbucket) LastChanged() time.Time {
bucket.RLock()
defer bucket.RUnlock()
return bucket.lastChanged
}
|
go
|
func (bucket *kbucket) LastChanged() time.Time {
bucket.RLock()
defer bucket.RUnlock()
return bucket.lastChanged
}
|
[
"func",
"(",
"bucket",
"*",
"kbucket",
")",
"LastChanged",
"(",
")",
"time",
".",
"Time",
"{",
"bucket",
".",
"RLock",
"(",
")",
"\n",
"defer",
"bucket",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"bucket",
".",
"lastChanged",
"\n",
"}"
] |
// LastChanged return the last time when it changes.
|
[
"LastChanged",
"return",
"the",
"last",
"time",
"when",
"it",
"changes",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L169-L174
|
train
|
shiyanhui/dht
|
routingtable.go
|
RandomChildID
|
func (bucket *kbucket) RandomChildID() string {
prefixLen := bucket.prefix.Size / 8
return strings.Join([]string{
bucket.prefix.RawString()[:prefixLen],
randomString(20 - prefixLen),
}, "")
}
|
go
|
func (bucket *kbucket) RandomChildID() string {
prefixLen := bucket.prefix.Size / 8
return strings.Join([]string{
bucket.prefix.RawString()[:prefixLen],
randomString(20 - prefixLen),
}, "")
}
|
[
"func",
"(",
"bucket",
"*",
"kbucket",
")",
"RandomChildID",
"(",
")",
"string",
"{",
"prefixLen",
":=",
"bucket",
".",
"prefix",
".",
"Size",
"/",
"8",
"\n\n",
"return",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"bucket",
".",
"prefix",
".",
"RawString",
"(",
")",
"[",
":",
"prefixLen",
"]",
",",
"randomString",
"(",
"20",
"-",
"prefixLen",
")",
",",
"}",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// RandomChildID returns a random id that has the same prefix with bucket.
|
[
"RandomChildID",
"returns",
"a",
"random",
"id",
"that",
"has",
"the",
"same",
"prefix",
"with",
"bucket",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L177-L184
|
train
|
shiyanhui/dht
|
routingtable.go
|
UpdateTimestamp
|
func (bucket *kbucket) UpdateTimestamp() {
bucket.Lock()
defer bucket.Unlock()
bucket.lastChanged = time.Now()
}
|
go
|
func (bucket *kbucket) UpdateTimestamp() {
bucket.Lock()
defer bucket.Unlock()
bucket.lastChanged = time.Now()
}
|
[
"func",
"(",
"bucket",
"*",
"kbucket",
")",
"UpdateTimestamp",
"(",
")",
"{",
"bucket",
".",
"Lock",
"(",
")",
"\n",
"defer",
"bucket",
".",
"Unlock",
"(",
")",
"\n\n",
"bucket",
".",
"lastChanged",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"}"
] |
// UpdateTimestamp update bucket's last changed time..
|
[
"UpdateTimestamp",
"update",
"bucket",
"s",
"last",
"changed",
"time",
".."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L187-L192
|
train
|
shiyanhui/dht
|
routingtable.go
|
Insert
|
func (bucket *kbucket) Insert(no *node) bool {
isNew := !bucket.nodes.HasKey(no.id.RawString())
bucket.nodes.Push(no.id.RawString(), no)
bucket.UpdateTimestamp()
return isNew
}
|
go
|
func (bucket *kbucket) Insert(no *node) bool {
isNew := !bucket.nodes.HasKey(no.id.RawString())
bucket.nodes.Push(no.id.RawString(), no)
bucket.UpdateTimestamp()
return isNew
}
|
[
"func",
"(",
"bucket",
"*",
"kbucket",
")",
"Insert",
"(",
"no",
"*",
"node",
")",
"bool",
"{",
"isNew",
":=",
"!",
"bucket",
".",
"nodes",
".",
"HasKey",
"(",
"no",
".",
"id",
".",
"RawString",
"(",
")",
")",
"\n\n",
"bucket",
".",
"nodes",
".",
"Push",
"(",
"no",
".",
"id",
".",
"RawString",
"(",
")",
",",
"no",
")",
"\n",
"bucket",
".",
"UpdateTimestamp",
"(",
")",
"\n\n",
"return",
"isNew",
"\n",
"}"
] |
// Insert inserts node to the bucket. It returns whether the node is new in
// the bucket.
|
[
"Insert",
"inserts",
"node",
"to",
"the",
"bucket",
".",
"It",
"returns",
"whether",
"the",
"node",
"is",
"new",
"in",
"the",
"bucket",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L196-L203
|
train
|
shiyanhui/dht
|
routingtable.go
|
Fresh
|
func (bucket *kbucket) Fresh(dht *DHT) {
for e := range bucket.nodes.Iter() {
no := e.Value.(*node)
if time.Since(no.lastActiveTime) > dht.NodeExpriedAfter {
dht.transactionManager.ping(no)
}
}
}
|
go
|
func (bucket *kbucket) Fresh(dht *DHT) {
for e := range bucket.nodes.Iter() {
no := e.Value.(*node)
if time.Since(no.lastActiveTime) > dht.NodeExpriedAfter {
dht.transactionManager.ping(no)
}
}
}
|
[
"func",
"(",
"bucket",
"*",
"kbucket",
")",
"Fresh",
"(",
"dht",
"*",
"DHT",
")",
"{",
"for",
"e",
":=",
"range",
"bucket",
".",
"nodes",
".",
"Iter",
"(",
")",
"{",
"no",
":=",
"e",
".",
"Value",
".",
"(",
"*",
"node",
")",
"\n",
"if",
"time",
".",
"Since",
"(",
"no",
".",
"lastActiveTime",
")",
">",
"dht",
".",
"NodeExpriedAfter",
"{",
"dht",
".",
"transactionManager",
".",
"ping",
"(",
"no",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// Fresh pings the expired nodes in the bucket.
|
[
"Fresh",
"pings",
"the",
"expired",
"nodes",
"in",
"the",
"bucket",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L233-L240
|
train
|
shiyanhui/dht
|
routingtable.go
|
newRoutingTableNode
|
func newRoutingTableNode(prefix *bitmap) *routingTableNode {
return &routingTableNode{
children: make([]*routingTableNode, 2),
bucket: newKBucket(prefix),
}
}
|
go
|
func newRoutingTableNode(prefix *bitmap) *routingTableNode {
return &routingTableNode{
children: make([]*routingTableNode, 2),
bucket: newKBucket(prefix),
}
}
|
[
"func",
"newRoutingTableNode",
"(",
"prefix",
"*",
"bitmap",
")",
"*",
"routingTableNode",
"{",
"return",
"&",
"routingTableNode",
"{",
"children",
":",
"make",
"(",
"[",
"]",
"*",
"routingTableNode",
",",
"2",
")",
",",
"bucket",
":",
"newKBucket",
"(",
"prefix",
")",
",",
"}",
"\n",
"}"
] |
// newRoutingTableNode returns a new routingTableNode pointer.
|
[
"newRoutingTableNode",
"returns",
"a",
"new",
"routingTableNode",
"pointer",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L250-L255
|
train
|
shiyanhui/dht
|
routingtable.go
|
Child
|
func (tableNode *routingTableNode) Child(index int) *routingTableNode {
if index >= 2 {
return nil
}
tableNode.RLock()
defer tableNode.RUnlock()
return tableNode.children[index]
}
|
go
|
func (tableNode *routingTableNode) Child(index int) *routingTableNode {
if index >= 2 {
return nil
}
tableNode.RLock()
defer tableNode.RUnlock()
return tableNode.children[index]
}
|
[
"func",
"(",
"tableNode",
"*",
"routingTableNode",
")",
"Child",
"(",
"index",
"int",
")",
"*",
"routingTableNode",
"{",
"if",
"index",
">=",
"2",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"tableNode",
".",
"RLock",
"(",
")",
"\n",
"defer",
"tableNode",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"tableNode",
".",
"children",
"[",
"index",
"]",
"\n",
"}"
] |
// Child returns routingTableNode's left or right child.
|
[
"Child",
"returns",
"routingTableNode",
"s",
"left",
"or",
"right",
"child",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L258-L267
|
train
|
shiyanhui/dht
|
routingtable.go
|
SetChild
|
func (tableNode *routingTableNode) SetChild(index int, c *routingTableNode) {
tableNode.Lock()
defer tableNode.Unlock()
tableNode.children[index] = c
}
|
go
|
func (tableNode *routingTableNode) SetChild(index int, c *routingTableNode) {
tableNode.Lock()
defer tableNode.Unlock()
tableNode.children[index] = c
}
|
[
"func",
"(",
"tableNode",
"*",
"routingTableNode",
")",
"SetChild",
"(",
"index",
"int",
",",
"c",
"*",
"routingTableNode",
")",
"{",
"tableNode",
".",
"Lock",
"(",
")",
"\n",
"defer",
"tableNode",
".",
"Unlock",
"(",
")",
"\n\n",
"tableNode",
".",
"children",
"[",
"index",
"]",
"=",
"c",
"\n",
"}"
] |
// SetChild sets routingTableNode's left or right child. When index is 0, it's
// the left child, if 1, it's the right child.
|
[
"SetChild",
"sets",
"routingTableNode",
"s",
"left",
"or",
"right",
"child",
".",
"When",
"index",
"is",
"0",
"it",
"s",
"the",
"left",
"child",
"if",
"1",
"it",
"s",
"the",
"right",
"child",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L271-L276
|
train
|
shiyanhui/dht
|
routingtable.go
|
KBucket
|
func (tableNode *routingTableNode) KBucket() *kbucket {
tableNode.RLock()
defer tableNode.RUnlock()
return tableNode.bucket
}
|
go
|
func (tableNode *routingTableNode) KBucket() *kbucket {
tableNode.RLock()
defer tableNode.RUnlock()
return tableNode.bucket
}
|
[
"func",
"(",
"tableNode",
"*",
"routingTableNode",
")",
"KBucket",
"(",
")",
"*",
"kbucket",
"{",
"tableNode",
".",
"RLock",
"(",
")",
"\n",
"defer",
"tableNode",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"tableNode",
".",
"bucket",
"\n",
"}"
] |
// KBucket returns the bucket routingTableNode holds.
|
[
"KBucket",
"returns",
"the",
"bucket",
"routingTableNode",
"holds",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L279-L284
|
train
|
shiyanhui/dht
|
routingtable.go
|
SetKBucket
|
func (tableNode *routingTableNode) SetKBucket(bucket *kbucket) {
tableNode.Lock()
defer tableNode.Unlock()
tableNode.bucket = bucket
}
|
go
|
func (tableNode *routingTableNode) SetKBucket(bucket *kbucket) {
tableNode.Lock()
defer tableNode.Unlock()
tableNode.bucket = bucket
}
|
[
"func",
"(",
"tableNode",
"*",
"routingTableNode",
")",
"SetKBucket",
"(",
"bucket",
"*",
"kbucket",
")",
"{",
"tableNode",
".",
"Lock",
"(",
")",
"\n",
"defer",
"tableNode",
".",
"Unlock",
"(",
")",
"\n\n",
"tableNode",
".",
"bucket",
"=",
"bucket",
"\n",
"}"
] |
// SetKBucket sets the bucket.
|
[
"SetKBucket",
"sets",
"the",
"bucket",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L287-L292
|
train
|
shiyanhui/dht
|
routingtable.go
|
Split
|
func (tableNode *routingTableNode) Split() {
prefixLen := tableNode.KBucket().prefix.Size
if prefixLen == maxPrefixLength {
return
}
for i := 0; i < 2; i++ {
tableNode.SetChild(i, newRoutingTableNode(newBitmapFrom(
tableNode.KBucket().prefix, prefixLen+1)))
}
tableNode.Lock()
tableNode.children[1].bucket.prefix.Set(prefixLen)
tableNode.Unlock()
for e := range tableNode.KBucket().nodes.Iter() {
nd := e.Value.(*node)
tableNode.Child(nd.id.Bit(prefixLen)).KBucket().nodes.PushBack(nd)
}
for e := range tableNode.KBucket().candidates.Iter() {
nd := e.Value.(*node)
tableNode.Child(nd.id.Bit(prefixLen)).KBucket().candidates.PushBack(nd)
}
for i := 0; i < 2; i++ {
tableNode.Child(i).KBucket().UpdateTimestamp()
}
}
|
go
|
func (tableNode *routingTableNode) Split() {
prefixLen := tableNode.KBucket().prefix.Size
if prefixLen == maxPrefixLength {
return
}
for i := 0; i < 2; i++ {
tableNode.SetChild(i, newRoutingTableNode(newBitmapFrom(
tableNode.KBucket().prefix, prefixLen+1)))
}
tableNode.Lock()
tableNode.children[1].bucket.prefix.Set(prefixLen)
tableNode.Unlock()
for e := range tableNode.KBucket().nodes.Iter() {
nd := e.Value.(*node)
tableNode.Child(nd.id.Bit(prefixLen)).KBucket().nodes.PushBack(nd)
}
for e := range tableNode.KBucket().candidates.Iter() {
nd := e.Value.(*node)
tableNode.Child(nd.id.Bit(prefixLen)).KBucket().candidates.PushBack(nd)
}
for i := 0; i < 2; i++ {
tableNode.Child(i).KBucket().UpdateTimestamp()
}
}
|
[
"func",
"(",
"tableNode",
"*",
"routingTableNode",
")",
"Split",
"(",
")",
"{",
"prefixLen",
":=",
"tableNode",
".",
"KBucket",
"(",
")",
".",
"prefix",
".",
"Size",
"\n\n",
"if",
"prefixLen",
"==",
"maxPrefixLength",
"{",
"return",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"2",
";",
"i",
"++",
"{",
"tableNode",
".",
"SetChild",
"(",
"i",
",",
"newRoutingTableNode",
"(",
"newBitmapFrom",
"(",
"tableNode",
".",
"KBucket",
"(",
")",
".",
"prefix",
",",
"prefixLen",
"+",
"1",
")",
")",
")",
"\n",
"}",
"\n\n",
"tableNode",
".",
"Lock",
"(",
")",
"\n",
"tableNode",
".",
"children",
"[",
"1",
"]",
".",
"bucket",
".",
"prefix",
".",
"Set",
"(",
"prefixLen",
")",
"\n",
"tableNode",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"e",
":=",
"range",
"tableNode",
".",
"KBucket",
"(",
")",
".",
"nodes",
".",
"Iter",
"(",
")",
"{",
"nd",
":=",
"e",
".",
"Value",
".",
"(",
"*",
"node",
")",
"\n",
"tableNode",
".",
"Child",
"(",
"nd",
".",
"id",
".",
"Bit",
"(",
"prefixLen",
")",
")",
".",
"KBucket",
"(",
")",
".",
"nodes",
".",
"PushBack",
"(",
"nd",
")",
"\n",
"}",
"\n\n",
"for",
"e",
":=",
"range",
"tableNode",
".",
"KBucket",
"(",
")",
".",
"candidates",
".",
"Iter",
"(",
")",
"{",
"nd",
":=",
"e",
".",
"Value",
".",
"(",
"*",
"node",
")",
"\n",
"tableNode",
".",
"Child",
"(",
"nd",
".",
"id",
".",
"Bit",
"(",
"prefixLen",
")",
")",
".",
"KBucket",
"(",
")",
".",
"candidates",
".",
"PushBack",
"(",
"nd",
")",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"2",
";",
"i",
"++",
"{",
"tableNode",
".",
"Child",
"(",
"i",
")",
".",
"KBucket",
"(",
")",
".",
"UpdateTimestamp",
"(",
")",
"\n",
"}",
"\n",
"}"
] |
// Split splits current routingTableNode and sets it's two children.
|
[
"Split",
"splits",
"current",
"routingTableNode",
"and",
"sets",
"it",
"s",
"two",
"children",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L295-L324
|
train
|
shiyanhui/dht
|
routingtable.go
|
newRoutingTable
|
func newRoutingTable(k int, dht *DHT) *routingTable {
root := newRoutingTableNode(newBitmap(0))
rt := &routingTable{
RWMutex: &sync.RWMutex{},
k: k,
root: root,
cachedNodes: newSyncedMap(),
cachedKBuckets: newKeyedDeque(),
dht: dht,
clearQueue: newSyncedList(),
}
rt.cachedKBuckets.Push(root.bucket.prefix.String(), root.bucket)
return rt
}
|
go
|
func newRoutingTable(k int, dht *DHT) *routingTable {
root := newRoutingTableNode(newBitmap(0))
rt := &routingTable{
RWMutex: &sync.RWMutex{},
k: k,
root: root,
cachedNodes: newSyncedMap(),
cachedKBuckets: newKeyedDeque(),
dht: dht,
clearQueue: newSyncedList(),
}
rt.cachedKBuckets.Push(root.bucket.prefix.String(), root.bucket)
return rt
}
|
[
"func",
"newRoutingTable",
"(",
"k",
"int",
",",
"dht",
"*",
"DHT",
")",
"*",
"routingTable",
"{",
"root",
":=",
"newRoutingTableNode",
"(",
"newBitmap",
"(",
"0",
")",
")",
"\n\n",
"rt",
":=",
"&",
"routingTable",
"{",
"RWMutex",
":",
"&",
"sync",
".",
"RWMutex",
"{",
"}",
",",
"k",
":",
"k",
",",
"root",
":",
"root",
",",
"cachedNodes",
":",
"newSyncedMap",
"(",
")",
",",
"cachedKBuckets",
":",
"newKeyedDeque",
"(",
")",
",",
"dht",
":",
"dht",
",",
"clearQueue",
":",
"newSyncedList",
"(",
")",
",",
"}",
"\n\n",
"rt",
".",
"cachedKBuckets",
".",
"Push",
"(",
"root",
".",
"bucket",
".",
"prefix",
".",
"String",
"(",
")",
",",
"root",
".",
"bucket",
")",
"\n",
"return",
"rt",
"\n",
"}"
] |
// newRoutingTable returns a new routingTable pointer.
|
[
"newRoutingTable",
"returns",
"a",
"new",
"routingTable",
"pointer",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L338-L353
|
train
|
shiyanhui/dht
|
routingtable.go
|
Insert
|
func (rt *routingTable) Insert(nd *node) bool {
rt.Lock()
defer rt.Unlock()
if rt.dht.blackList.in(nd.addr.IP.String(), nd.addr.Port) ||
rt.cachedNodes.Len() >= rt.dht.MaxNodes {
return false
}
var (
next *routingTableNode
bucket *kbucket
)
root := rt.root
for prefixLen := 1; prefixLen <= maxPrefixLength; prefixLen++ {
next = root.Child(nd.id.Bit(prefixLen - 1))
if next != nil {
// If next is not the leaf.
root = next
} else if root.KBucket().nodes.Len() < rt.k ||
root.KBucket().nodes.HasKey(nd.id.RawString()) {
bucket = root.KBucket()
isNew := bucket.Insert(nd)
rt.cachedNodes.Set(nd.addr.String(), nd)
rt.cachedKBuckets.Push(bucket.prefix.String(), bucket)
return isNew
} else if root.KBucket().prefix.Compare(nd.id, prefixLen-1) == 0 {
// If node has the same prefix with bucket, split it.
root.Split()
rt.cachedKBuckets.Delete(root.KBucket().prefix.String())
root.SetKBucket(nil)
for i := 0; i < 2; i++ {
bucket = root.Child(i).KBucket()
rt.cachedKBuckets.Push(bucket.prefix.String(), bucket)
}
root = root.Child(nd.id.Bit(prefixLen - 1))
} else {
// Finally, store node as a candidate and fresh the bucket.
root.KBucket().candidates.PushBack(nd)
if root.KBucket().candidates.Len() > rt.k {
root.KBucket().candidates.Remove(
root.KBucket().candidates.Front())
}
go root.KBucket().Fresh(rt.dht)
return false
}
}
return false
}
|
go
|
func (rt *routingTable) Insert(nd *node) bool {
rt.Lock()
defer rt.Unlock()
if rt.dht.blackList.in(nd.addr.IP.String(), nd.addr.Port) ||
rt.cachedNodes.Len() >= rt.dht.MaxNodes {
return false
}
var (
next *routingTableNode
bucket *kbucket
)
root := rt.root
for prefixLen := 1; prefixLen <= maxPrefixLength; prefixLen++ {
next = root.Child(nd.id.Bit(prefixLen - 1))
if next != nil {
// If next is not the leaf.
root = next
} else if root.KBucket().nodes.Len() < rt.k ||
root.KBucket().nodes.HasKey(nd.id.RawString()) {
bucket = root.KBucket()
isNew := bucket.Insert(nd)
rt.cachedNodes.Set(nd.addr.String(), nd)
rt.cachedKBuckets.Push(bucket.prefix.String(), bucket)
return isNew
} else if root.KBucket().prefix.Compare(nd.id, prefixLen-1) == 0 {
// If node has the same prefix with bucket, split it.
root.Split()
rt.cachedKBuckets.Delete(root.KBucket().prefix.String())
root.SetKBucket(nil)
for i := 0; i < 2; i++ {
bucket = root.Child(i).KBucket()
rt.cachedKBuckets.Push(bucket.prefix.String(), bucket)
}
root = root.Child(nd.id.Bit(prefixLen - 1))
} else {
// Finally, store node as a candidate and fresh the bucket.
root.KBucket().candidates.PushBack(nd)
if root.KBucket().candidates.Len() > rt.k {
root.KBucket().candidates.Remove(
root.KBucket().candidates.Front())
}
go root.KBucket().Fresh(rt.dht)
return false
}
}
return false
}
|
[
"func",
"(",
"rt",
"*",
"routingTable",
")",
"Insert",
"(",
"nd",
"*",
"node",
")",
"bool",
"{",
"rt",
".",
"Lock",
"(",
")",
"\n",
"defer",
"rt",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"rt",
".",
"dht",
".",
"blackList",
".",
"in",
"(",
"nd",
".",
"addr",
".",
"IP",
".",
"String",
"(",
")",
",",
"nd",
".",
"addr",
".",
"Port",
")",
"||",
"rt",
".",
"cachedNodes",
".",
"Len",
"(",
")",
">=",
"rt",
".",
"dht",
".",
"MaxNodes",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"var",
"(",
"next",
"*",
"routingTableNode",
"\n",
"bucket",
"*",
"kbucket",
"\n",
")",
"\n",
"root",
":=",
"rt",
".",
"root",
"\n\n",
"for",
"prefixLen",
":=",
"1",
";",
"prefixLen",
"<=",
"maxPrefixLength",
";",
"prefixLen",
"++",
"{",
"next",
"=",
"root",
".",
"Child",
"(",
"nd",
".",
"id",
".",
"Bit",
"(",
"prefixLen",
"-",
"1",
")",
")",
"\n\n",
"if",
"next",
"!=",
"nil",
"{",
"// If next is not the leaf.",
"root",
"=",
"next",
"\n",
"}",
"else",
"if",
"root",
".",
"KBucket",
"(",
")",
".",
"nodes",
".",
"Len",
"(",
")",
"<",
"rt",
".",
"k",
"||",
"root",
".",
"KBucket",
"(",
")",
".",
"nodes",
".",
"HasKey",
"(",
"nd",
".",
"id",
".",
"RawString",
"(",
")",
")",
"{",
"bucket",
"=",
"root",
".",
"KBucket",
"(",
")",
"\n",
"isNew",
":=",
"bucket",
".",
"Insert",
"(",
"nd",
")",
"\n\n",
"rt",
".",
"cachedNodes",
".",
"Set",
"(",
"nd",
".",
"addr",
".",
"String",
"(",
")",
",",
"nd",
")",
"\n",
"rt",
".",
"cachedKBuckets",
".",
"Push",
"(",
"bucket",
".",
"prefix",
".",
"String",
"(",
")",
",",
"bucket",
")",
"\n\n",
"return",
"isNew",
"\n",
"}",
"else",
"if",
"root",
".",
"KBucket",
"(",
")",
".",
"prefix",
".",
"Compare",
"(",
"nd",
".",
"id",
",",
"prefixLen",
"-",
"1",
")",
"==",
"0",
"{",
"// If node has the same prefix with bucket, split it.",
"root",
".",
"Split",
"(",
")",
"\n\n",
"rt",
".",
"cachedKBuckets",
".",
"Delete",
"(",
"root",
".",
"KBucket",
"(",
")",
".",
"prefix",
".",
"String",
"(",
")",
")",
"\n",
"root",
".",
"SetKBucket",
"(",
"nil",
")",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"2",
";",
"i",
"++",
"{",
"bucket",
"=",
"root",
".",
"Child",
"(",
"i",
")",
".",
"KBucket",
"(",
")",
"\n",
"rt",
".",
"cachedKBuckets",
".",
"Push",
"(",
"bucket",
".",
"prefix",
".",
"String",
"(",
")",
",",
"bucket",
")",
"\n",
"}",
"\n\n",
"root",
"=",
"root",
".",
"Child",
"(",
"nd",
".",
"id",
".",
"Bit",
"(",
"prefixLen",
"-",
"1",
")",
")",
"\n",
"}",
"else",
"{",
"// Finally, store node as a candidate and fresh the bucket.",
"root",
".",
"KBucket",
"(",
")",
".",
"candidates",
".",
"PushBack",
"(",
"nd",
")",
"\n",
"if",
"root",
".",
"KBucket",
"(",
")",
".",
"candidates",
".",
"Len",
"(",
")",
">",
"rt",
".",
"k",
"{",
"root",
".",
"KBucket",
"(",
")",
".",
"candidates",
".",
"Remove",
"(",
"root",
".",
"KBucket",
"(",
")",
".",
"candidates",
".",
"Front",
"(",
")",
")",
"\n",
"}",
"\n\n",
"go",
"root",
".",
"KBucket",
"(",
")",
".",
"Fresh",
"(",
"rt",
".",
"dht",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Insert adds a node to routing table. It returns whether the node is new
// in the routingtable.
|
[
"Insert",
"adds",
"a",
"node",
"to",
"routing",
"table",
".",
"It",
"returns",
"whether",
"the",
"node",
"is",
"new",
"in",
"the",
"routingtable",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L357-L415
|
train
|
shiyanhui/dht
|
routingtable.go
|
GetNeighbors
|
func (rt *routingTable) GetNeighbors(id *bitmap, size int) []*node {
rt.RLock()
nodes := make([]interface{}, 0, rt.cachedNodes.Len())
for item := range rt.cachedNodes.Iter() {
nodes = append(nodes, item.val.(*node))
}
rt.RUnlock()
neighbors := getTopK(nodes, id, size)
result := make([]*node, len(neighbors))
for i, nd := range neighbors {
result[i] = nd.(*node)
}
return result
}
|
go
|
func (rt *routingTable) GetNeighbors(id *bitmap, size int) []*node {
rt.RLock()
nodes := make([]interface{}, 0, rt.cachedNodes.Len())
for item := range rt.cachedNodes.Iter() {
nodes = append(nodes, item.val.(*node))
}
rt.RUnlock()
neighbors := getTopK(nodes, id, size)
result := make([]*node, len(neighbors))
for i, nd := range neighbors {
result[i] = nd.(*node)
}
return result
}
|
[
"func",
"(",
"rt",
"*",
"routingTable",
")",
"GetNeighbors",
"(",
"id",
"*",
"bitmap",
",",
"size",
"int",
")",
"[",
"]",
"*",
"node",
"{",
"rt",
".",
"RLock",
"(",
")",
"\n",
"nodes",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"0",
",",
"rt",
".",
"cachedNodes",
".",
"Len",
"(",
")",
")",
"\n",
"for",
"item",
":=",
"range",
"rt",
".",
"cachedNodes",
".",
"Iter",
"(",
")",
"{",
"nodes",
"=",
"append",
"(",
"nodes",
",",
"item",
".",
"val",
".",
"(",
"*",
"node",
")",
")",
"\n",
"}",
"\n",
"rt",
".",
"RUnlock",
"(",
")",
"\n\n",
"neighbors",
":=",
"getTopK",
"(",
"nodes",
",",
"id",
",",
"size",
")",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"*",
"node",
",",
"len",
"(",
"neighbors",
")",
")",
"\n\n",
"for",
"i",
",",
"nd",
":=",
"range",
"neighbors",
"{",
"result",
"[",
"i",
"]",
"=",
"nd",
".",
"(",
"*",
"node",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] |
// GetNeighbors returns the size-length nodes closest to id.
|
[
"GetNeighbors",
"returns",
"the",
"size",
"-",
"length",
"nodes",
"closest",
"to",
"id",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L418-L433
|
train
|
shiyanhui/dht
|
routingtable.go
|
GetNeighborCompactInfos
|
func (rt *routingTable) GetNeighborCompactInfos(id *bitmap, size int) []string {
neighbors := rt.GetNeighbors(id, size)
infos := make([]string, len(neighbors))
for i, no := range neighbors {
infos[i] = no.CompactNodeInfo()
}
return infos
}
|
go
|
func (rt *routingTable) GetNeighborCompactInfos(id *bitmap, size int) []string {
neighbors := rt.GetNeighbors(id, size)
infos := make([]string, len(neighbors))
for i, no := range neighbors {
infos[i] = no.CompactNodeInfo()
}
return infos
}
|
[
"func",
"(",
"rt",
"*",
"routingTable",
")",
"GetNeighborCompactInfos",
"(",
"id",
"*",
"bitmap",
",",
"size",
"int",
")",
"[",
"]",
"string",
"{",
"neighbors",
":=",
"rt",
".",
"GetNeighbors",
"(",
"id",
",",
"size",
")",
"\n",
"infos",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"neighbors",
")",
")",
"\n\n",
"for",
"i",
",",
"no",
":=",
"range",
"neighbors",
"{",
"infos",
"[",
"i",
"]",
"=",
"no",
".",
"CompactNodeInfo",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"infos",
"\n",
"}"
] |
// GetNeighborIds return the size-length compact node info closest to id.
|
[
"GetNeighborIds",
"return",
"the",
"size",
"-",
"length",
"compact",
"node",
"info",
"closest",
"to",
"id",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L436-L445
|
train
|
shiyanhui/dht
|
routingtable.go
|
GetNodeKBucktByID
|
func (rt *routingTable) GetNodeKBucktByID(id *bitmap) (
nd *node, bucket *kbucket) {
rt.RLock()
defer rt.RUnlock()
var next *routingTableNode
root := rt.root
for prefixLen := 1; prefixLen <= maxPrefixLength; prefixLen++ {
next = root.Child(id.Bit(prefixLen - 1))
if next == nil {
v, ok := root.KBucket().nodes.Get(id.RawString())
if !ok {
return
}
nd, bucket = v.Value.(*node), root.KBucket()
return
}
root = next
}
return
}
|
go
|
func (rt *routingTable) GetNodeKBucktByID(id *bitmap) (
nd *node, bucket *kbucket) {
rt.RLock()
defer rt.RUnlock()
var next *routingTableNode
root := rt.root
for prefixLen := 1; prefixLen <= maxPrefixLength; prefixLen++ {
next = root.Child(id.Bit(prefixLen - 1))
if next == nil {
v, ok := root.KBucket().nodes.Get(id.RawString())
if !ok {
return
}
nd, bucket = v.Value.(*node), root.KBucket()
return
}
root = next
}
return
}
|
[
"func",
"(",
"rt",
"*",
"routingTable",
")",
"GetNodeKBucktByID",
"(",
"id",
"*",
"bitmap",
")",
"(",
"nd",
"*",
"node",
",",
"bucket",
"*",
"kbucket",
")",
"{",
"rt",
".",
"RLock",
"(",
")",
"\n",
"defer",
"rt",
".",
"RUnlock",
"(",
")",
"\n\n",
"var",
"next",
"*",
"routingTableNode",
"\n",
"root",
":=",
"rt",
".",
"root",
"\n\n",
"for",
"prefixLen",
":=",
"1",
";",
"prefixLen",
"<=",
"maxPrefixLength",
";",
"prefixLen",
"++",
"{",
"next",
"=",
"root",
".",
"Child",
"(",
"id",
".",
"Bit",
"(",
"prefixLen",
"-",
"1",
")",
")",
"\n",
"if",
"next",
"==",
"nil",
"{",
"v",
",",
"ok",
":=",
"root",
".",
"KBucket",
"(",
")",
".",
"nodes",
".",
"Get",
"(",
"id",
".",
"RawString",
"(",
")",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"nd",
",",
"bucket",
"=",
"v",
".",
"Value",
".",
"(",
"*",
"node",
")",
",",
"root",
".",
"KBucket",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"root",
"=",
"next",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// GetNodeKBucktById returns node whose id is `id` and the bucket it
// belongs to.
|
[
"GetNodeKBucktById",
"returns",
"node",
"whose",
"id",
"is",
"id",
"and",
"the",
"bucket",
"it",
"belongs",
"to",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L449-L471
|
train
|
shiyanhui/dht
|
routingtable.go
|
GetNodeByAddress
|
func (rt *routingTable) GetNodeByAddress(address string) (no *node, ok bool) {
rt.RLock()
defer rt.RUnlock()
v, ok := rt.cachedNodes.Get(address)
if ok {
no = v.(*node)
}
return
}
|
go
|
func (rt *routingTable) GetNodeByAddress(address string) (no *node, ok bool) {
rt.RLock()
defer rt.RUnlock()
v, ok := rt.cachedNodes.Get(address)
if ok {
no = v.(*node)
}
return
}
|
[
"func",
"(",
"rt",
"*",
"routingTable",
")",
"GetNodeByAddress",
"(",
"address",
"string",
")",
"(",
"no",
"*",
"node",
",",
"ok",
"bool",
")",
"{",
"rt",
".",
"RLock",
"(",
")",
"\n",
"defer",
"rt",
".",
"RUnlock",
"(",
")",
"\n\n",
"v",
",",
"ok",
":=",
"rt",
".",
"cachedNodes",
".",
"Get",
"(",
"address",
")",
"\n",
"if",
"ok",
"{",
"no",
"=",
"v",
".",
"(",
"*",
"node",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// GetNodeByAddress finds node by address.
|
[
"GetNodeByAddress",
"finds",
"node",
"by",
"address",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L474-L483
|
train
|
shiyanhui/dht
|
routingtable.go
|
Remove
|
func (rt *routingTable) Remove(id *bitmap) {
if nd, bucket := rt.GetNodeKBucktByID(id); nd != nil {
bucket.Replace(nd)
rt.cachedNodes.Delete(nd.addr.String())
rt.cachedKBuckets.Push(bucket.prefix.String(), bucket)
}
}
|
go
|
func (rt *routingTable) Remove(id *bitmap) {
if nd, bucket := rt.GetNodeKBucktByID(id); nd != nil {
bucket.Replace(nd)
rt.cachedNodes.Delete(nd.addr.String())
rt.cachedKBuckets.Push(bucket.prefix.String(), bucket)
}
}
|
[
"func",
"(",
"rt",
"*",
"routingTable",
")",
"Remove",
"(",
"id",
"*",
"bitmap",
")",
"{",
"if",
"nd",
",",
"bucket",
":=",
"rt",
".",
"GetNodeKBucktByID",
"(",
"id",
")",
";",
"nd",
"!=",
"nil",
"{",
"bucket",
".",
"Replace",
"(",
"nd",
")",
"\n",
"rt",
".",
"cachedNodes",
".",
"Delete",
"(",
"nd",
".",
"addr",
".",
"String",
"(",
")",
")",
"\n",
"rt",
".",
"cachedKBuckets",
".",
"Push",
"(",
"bucket",
".",
"prefix",
".",
"String",
"(",
")",
",",
"bucket",
")",
"\n",
"}",
"\n",
"}"
] |
// Remove deletes the node whose id is `id`.
|
[
"Remove",
"deletes",
"the",
"node",
"whose",
"id",
"is",
"id",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L486-L492
|
train
|
shiyanhui/dht
|
routingtable.go
|
Fresh
|
func (rt *routingTable) Fresh() {
now := time.Now()
for e := range rt.cachedKBuckets.Iter() {
bucket := e.Value.(*kbucket)
if now.Sub(bucket.LastChanged()) < rt.dht.KBucketExpiredAfter ||
bucket.nodes.Len() == 0 {
continue
}
i := 0
for e := range bucket.nodes.Iter() {
if i < rt.dht.RefreshNodeNum {
no := e.Value.(*node)
rt.dht.transactionManager.findNode(no, bucket.RandomChildID())
rt.clearQueue.PushBack(no)
}
i++
}
}
if rt.dht.IsCrawlMode() {
for e := range rt.clearQueue.Iter() {
rt.Remove(e.Value.(*node).id)
}
}
rt.clearQueue.Clear()
}
|
go
|
func (rt *routingTable) Fresh() {
now := time.Now()
for e := range rt.cachedKBuckets.Iter() {
bucket := e.Value.(*kbucket)
if now.Sub(bucket.LastChanged()) < rt.dht.KBucketExpiredAfter ||
bucket.nodes.Len() == 0 {
continue
}
i := 0
for e := range bucket.nodes.Iter() {
if i < rt.dht.RefreshNodeNum {
no := e.Value.(*node)
rt.dht.transactionManager.findNode(no, bucket.RandomChildID())
rt.clearQueue.PushBack(no)
}
i++
}
}
if rt.dht.IsCrawlMode() {
for e := range rt.clearQueue.Iter() {
rt.Remove(e.Value.(*node).id)
}
}
rt.clearQueue.Clear()
}
|
[
"func",
"(",
"rt",
"*",
"routingTable",
")",
"Fresh",
"(",
")",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"for",
"e",
":=",
"range",
"rt",
".",
"cachedKBuckets",
".",
"Iter",
"(",
")",
"{",
"bucket",
":=",
"e",
".",
"Value",
".",
"(",
"*",
"kbucket",
")",
"\n",
"if",
"now",
".",
"Sub",
"(",
"bucket",
".",
"LastChanged",
"(",
")",
")",
"<",
"rt",
".",
"dht",
".",
"KBucketExpiredAfter",
"||",
"bucket",
".",
"nodes",
".",
"Len",
"(",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n\n",
"i",
":=",
"0",
"\n",
"for",
"e",
":=",
"range",
"bucket",
".",
"nodes",
".",
"Iter",
"(",
")",
"{",
"if",
"i",
"<",
"rt",
".",
"dht",
".",
"RefreshNodeNum",
"{",
"no",
":=",
"e",
".",
"Value",
".",
"(",
"*",
"node",
")",
"\n",
"rt",
".",
"dht",
".",
"transactionManager",
".",
"findNode",
"(",
"no",
",",
"bucket",
".",
"RandomChildID",
"(",
")",
")",
"\n",
"rt",
".",
"clearQueue",
".",
"PushBack",
"(",
"no",
")",
"\n",
"}",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"rt",
".",
"dht",
".",
"IsCrawlMode",
"(",
")",
"{",
"for",
"e",
":=",
"range",
"rt",
".",
"clearQueue",
".",
"Iter",
"(",
")",
"{",
"rt",
".",
"Remove",
"(",
"e",
".",
"Value",
".",
"(",
"*",
"node",
")",
".",
"id",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"rt",
".",
"clearQueue",
".",
"Clear",
"(",
")",
"\n",
"}"
] |
// Fresh sends findNode to all nodes in the expired nodes.
|
[
"Fresh",
"sends",
"findNode",
"to",
"all",
"nodes",
"in",
"the",
"expired",
"nodes",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L503-L531
|
train
|
shiyanhui/dht
|
routingtable.go
|
Len
|
func (rt *routingTable) Len() int {
rt.RLock()
defer rt.RUnlock()
return rt.cachedNodes.Len()
}
|
go
|
func (rt *routingTable) Len() int {
rt.RLock()
defer rt.RUnlock()
return rt.cachedNodes.Len()
}
|
[
"func",
"(",
"rt",
"*",
"routingTable",
")",
"Len",
"(",
")",
"int",
"{",
"rt",
".",
"RLock",
"(",
")",
"\n",
"defer",
"rt",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"rt",
".",
"cachedNodes",
".",
"Len",
"(",
")",
"\n",
"}"
] |
// Len returns the number of nodes in table.
|
[
"Len",
"returns",
"the",
"number",
"of",
"nodes",
"in",
"table",
"."
] |
1b3b78ecf279a28409577382c3ae95df5703cf50
|
https://github.com/shiyanhui/dht/blob/1b3b78ecf279a28409577382c3ae95df5703cf50/routingtable.go#L534-L539
|
train
|
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.