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 |
---|---|---|---|---|---|---|---|---|---|---|---|
brocaar/loraserver
|
internal/storage/multicast_group.go
|
GetSchedulableMulticastQueueItems
|
func GetSchedulableMulticastQueueItems(db sqlx.Ext, count int) ([]MulticastQueueItem, error) {
var items []MulticastQueueItem
err := sqlx.Select(db, &items, `
select
*
from
multicast_queue
where
schedule_at <= $2
order by
id
limit $1
for update skip locked
`, count, time.Now())
if err != nil {
return nil, handlePSQLError(err, "select error")
}
return items, nil
}
|
go
|
func GetSchedulableMulticastQueueItems(db sqlx.Ext, count int) ([]MulticastQueueItem, error) {
var items []MulticastQueueItem
err := sqlx.Select(db, &items, `
select
*
from
multicast_queue
where
schedule_at <= $2
order by
id
limit $1
for update skip locked
`, count, time.Now())
if err != nil {
return nil, handlePSQLError(err, "select error")
}
return items, nil
}
|
[
"func",
"GetSchedulableMulticastQueueItems",
"(",
"db",
"sqlx",
".",
"Ext",
",",
"count",
"int",
")",
"(",
"[",
"]",
"MulticastQueueItem",
",",
"error",
")",
"{",
"var",
"items",
"[",
"]",
"MulticastQueueItem",
"\n",
"err",
":=",
"sqlx",
".",
"Select",
"(",
"db",
",",
"&",
"items",
",",
"`\t\tselect\t\t\t*\t\tfrom\t\t\tmulticast_queue\t\twhere\t\t\tschedule_at <= $2\t\torder by\t\t\tid\t\tlimit $1\t\tfor update skip locked\t`",
",",
"count",
",",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"handlePSQLError",
"(",
"err",
",",
"\"select error\"",
")",
"\n",
"}",
"\n",
"return",
"items",
",",
"nil",
"\n",
"}"
] |
// GetSchedulableMulticastQueueItems returns a slice of multicast-queue items
// for scheduling.
// The returned queue-items will be locked for update so that this query can
// be executed in parallel.
|
[
"GetSchedulableMulticastQueueItems",
"returns",
"a",
"slice",
"of",
"multicast",
"-",
"queue",
"items",
"for",
"scheduling",
".",
"The",
"returned",
"queue",
"-",
"items",
"will",
"be",
"locked",
"for",
"update",
"so",
"that",
"this",
"query",
"can",
"be",
"executed",
"in",
"parallel",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/multicast_group.go#L332-L351
|
train
|
brocaar/loraserver
|
internal/storage/multicast_group.go
|
GetMaxScheduleAtForMulticastGroup
|
func GetMaxScheduleAtForMulticastGroup(db sqlx.Queryer, multicastGroupID uuid.UUID) (time.Time, error) {
ts := new(time.Time)
err := sqlx.Get(db, &ts, `
select
max(schedule_at)
from
multicast_queue
where
multicast_group_id = $1
`, multicastGroupID)
if err != nil {
return time.Time{}, handlePSQLError(err, "select error")
}
if ts != nil {
return *ts, nil
}
return time.Time{}, nil
}
|
go
|
func GetMaxScheduleAtForMulticastGroup(db sqlx.Queryer, multicastGroupID uuid.UUID) (time.Time, error) {
ts := new(time.Time)
err := sqlx.Get(db, &ts, `
select
max(schedule_at)
from
multicast_queue
where
multicast_group_id = $1
`, multicastGroupID)
if err != nil {
return time.Time{}, handlePSQLError(err, "select error")
}
if ts != nil {
return *ts, nil
}
return time.Time{}, nil
}
|
[
"func",
"GetMaxScheduleAtForMulticastGroup",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"multicastGroupID",
"uuid",
".",
"UUID",
")",
"(",
"time",
".",
"Time",
",",
"error",
")",
"{",
"ts",
":=",
"new",
"(",
"time",
".",
"Time",
")",
"\n",
"err",
":=",
"sqlx",
".",
"Get",
"(",
"db",
",",
"&",
"ts",
",",
"`\t\tselect\t\t\tmax(schedule_at)\t\tfrom\t\t\tmulticast_queue\t\twhere\t\t\tmulticast_group_id = $1\t`",
",",
"multicastGroupID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"handlePSQLError",
"(",
"err",
",",
"\"select error\"",
")",
"\n",
"}",
"\n",
"if",
"ts",
"!=",
"nil",
"{",
"return",
"*",
"ts",
",",
"nil",
"\n",
"}",
"\n",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"nil",
"\n",
"}"
] |
// GetMaxScheduleAtForMulticastGroup returns the maximum schedule at timestamp
// for the given multicast-group.
|
[
"GetMaxScheduleAtForMulticastGroup",
"returns",
"the",
"maximum",
"schedule",
"at",
"timestamp",
"for",
"the",
"given",
"multicast",
"-",
"group",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/multicast_group.go#L374-L393
|
train
|
brocaar/loraserver
|
internal/gateway/gateway.go
|
Start
|
func (s *StatsHandler) Start() error {
go func() {
s.wg.Add(1)
defer s.wg.Done()
for stats := range gateway.Backend().StatsPacketChan() {
go func(stats gw.GatewayStats) {
s.wg.Add(1)
defer s.wg.Done()
if err := updateGatewayState(storage.DB(), storage.RedisPool(), stats); err != nil {
log.WithError(err).Error("update gateway state error")
}
if err := handleGatewayStats(storage.RedisPool(), stats); err != nil {
log.WithError(err).Error("handle gateway stats error")
}
}(stats)
}
}()
return nil
}
|
go
|
func (s *StatsHandler) Start() error {
go func() {
s.wg.Add(1)
defer s.wg.Done()
for stats := range gateway.Backend().StatsPacketChan() {
go func(stats gw.GatewayStats) {
s.wg.Add(1)
defer s.wg.Done()
if err := updateGatewayState(storage.DB(), storage.RedisPool(), stats); err != nil {
log.WithError(err).Error("update gateway state error")
}
if err := handleGatewayStats(storage.RedisPool(), stats); err != nil {
log.WithError(err).Error("handle gateway stats error")
}
}(stats)
}
}()
return nil
}
|
[
"func",
"(",
"s",
"*",
"StatsHandler",
")",
"Start",
"(",
")",
"error",
"{",
"go",
"func",
"(",
")",
"{",
"s",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"defer",
"s",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"for",
"stats",
":=",
"range",
"gateway",
".",
"Backend",
"(",
")",
".",
"StatsPacketChan",
"(",
")",
"{",
"go",
"func",
"(",
"stats",
"gw",
".",
"GatewayStats",
")",
"{",
"s",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"defer",
"s",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"if",
"err",
":=",
"updateGatewayState",
"(",
"storage",
".",
"DB",
"(",
")",
",",
"storage",
".",
"RedisPool",
"(",
")",
",",
"stats",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"update gateway state error\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"handleGatewayStats",
"(",
"storage",
".",
"RedisPool",
"(",
")",
",",
"stats",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"handle gateway stats error\"",
")",
"\n",
"}",
"\n",
"}",
"(",
"stats",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Start starts the stats handler.
|
[
"Start",
"starts",
"the",
"stats",
"handler",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/gateway/gateway.go#L37-L58
|
train
|
brocaar/loraserver
|
internal/uplink/data/data.go
|
Handle
|
func Handle(rxPacket models.RXPacket) error {
ctx := dataContext{
RXPacket: rxPacket,
}
for _, t := range tasks {
if err := t(&ctx); err != nil {
return err
}
}
return nil
}
|
go
|
func Handle(rxPacket models.RXPacket) error {
ctx := dataContext{
RXPacket: rxPacket,
}
for _, t := range tasks {
if err := t(&ctx); err != nil {
return err
}
}
return nil
}
|
[
"func",
"Handle",
"(",
"rxPacket",
"models",
".",
"RXPacket",
")",
"error",
"{",
"ctx",
":=",
"dataContext",
"{",
"RXPacket",
":",
"rxPacket",
",",
"}",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"tasks",
"{",
"if",
"err",
":=",
"t",
"(",
"&",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Handle handles an uplink data frame
|
[
"Handle",
"handles",
"an",
"uplink",
"data",
"frame"
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/uplink/data/data.go#L83-L95
|
train
|
brocaar/loraserver
|
internal/uplink/data/data.go
|
sendRXInfoPayload
|
func sendRXInfoPayload(ds storage.DeviceSession, rxPacket models.RXPacket) error {
rxInfoReq := nc.HandleUplinkMetaDataRequest{
DevEui: ds.DevEUI[:],
TxInfo: rxPacket.TXInfo,
RxInfo: rxPacket.RXInfoSet,
}
_, err := controller.Client().HandleUplinkMetaData(context.Background(), &rxInfoReq)
if err != nil {
return fmt.Errorf("publish rxinfo to network-controller error: %s", err)
}
log.WithFields(log.Fields{
"dev_eui": ds.DevEUI,
}).Info("rx info sent to network-controller")
return nil
}
|
go
|
func sendRXInfoPayload(ds storage.DeviceSession, rxPacket models.RXPacket) error {
rxInfoReq := nc.HandleUplinkMetaDataRequest{
DevEui: ds.DevEUI[:],
TxInfo: rxPacket.TXInfo,
RxInfo: rxPacket.RXInfoSet,
}
_, err := controller.Client().HandleUplinkMetaData(context.Background(), &rxInfoReq)
if err != nil {
return fmt.Errorf("publish rxinfo to network-controller error: %s", err)
}
log.WithFields(log.Fields{
"dev_eui": ds.DevEUI,
}).Info("rx info sent to network-controller")
return nil
}
|
[
"func",
"sendRXInfoPayload",
"(",
"ds",
"storage",
".",
"DeviceSession",
",",
"rxPacket",
"models",
".",
"RXPacket",
")",
"error",
"{",
"rxInfoReq",
":=",
"nc",
".",
"HandleUplinkMetaDataRequest",
"{",
"DevEui",
":",
"ds",
".",
"DevEUI",
"[",
":",
"]",
",",
"TxInfo",
":",
"rxPacket",
".",
"TXInfo",
",",
"RxInfo",
":",
"rxPacket",
".",
"RXInfoSet",
",",
"}",
"\n",
"_",
",",
"err",
":=",
"controller",
".",
"Client",
"(",
")",
".",
"HandleUplinkMetaData",
"(",
"context",
".",
"Background",
"(",
")",
",",
"&",
"rxInfoReq",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"publish rxinfo to network-controller error: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"dev_eui\"",
":",
"ds",
".",
"DevEUI",
",",
"}",
")",
".",
"Info",
"(",
"\"rx info sent to network-controller\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// sendRXInfoPayload sends the rx and tx meta-data to the network controller.
|
[
"sendRXInfoPayload",
"sends",
"the",
"rx",
"and",
"tx",
"meta",
"-",
"data",
"to",
"the",
"network",
"controller",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/uplink/data/data.go#L586-L601
|
train
|
brocaar/loraserver
|
internal/storage/gateway_profile.go
|
GetVersion
|
func (p GatewayProfile) GetVersion() string {
return p.UpdatedAt.UTC().Format(time.RFC3339Nano)
}
|
go
|
func (p GatewayProfile) GetVersion() string {
return p.UpdatedAt.UTC().Format(time.RFC3339Nano)
}
|
[
"func",
"(",
"p",
"GatewayProfile",
")",
"GetVersion",
"(",
")",
"string",
"{",
"return",
"p",
".",
"UpdatedAt",
".",
"UTC",
"(",
")",
".",
"Format",
"(",
"time",
".",
"RFC3339Nano",
")",
"\n",
"}"
] |
// GetVersion returns the gateway-profile version.
|
[
"GetVersion",
"returns",
"the",
"gateway",
"-",
"profile",
"version",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway_profile.go#L38-L40
|
train
|
brocaar/loraserver
|
internal/storage/gateway_profile.go
|
CreateGatewayProfile
|
func CreateGatewayProfile(db sqlx.Execer, c *GatewayProfile) error {
now := time.Now()
c.CreatedAt = now
c.UpdatedAt = now
if c.ID == uuid.Nil {
var err error
c.ID, err = uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid v4 error")
}
}
_, err := db.Exec(`
insert into gateway_profile (
gateway_profile_id,
created_at,
updated_at,
channels
) values ($1, $2, $3, $4)`,
c.ID,
c.CreatedAt,
c.UpdatedAt,
pq.Array(c.Channels),
)
if err != nil {
return handlePSQLError(err, "insert error")
}
for _, ec := range c.ExtraChannels {
_, err := db.Exec(`
insert into gateway_profile_extra_channel (
gateway_profile_id,
modulation,
frequency,
bandwidth,
bitrate,
spreading_factors
) values ($1, $2, $3, $4, $5, $6)`,
c.ID,
ec.Modulation,
ec.Frequency,
ec.Bandwidth,
ec.Bitrate,
pq.Array(ec.SpreadingFactors),
)
if err != nil {
return handlePSQLError(err, "insert error")
}
}
log.WithFields(log.Fields{
"id": c.ID,
}).Info("gateway-profile created")
return nil
}
|
go
|
func CreateGatewayProfile(db sqlx.Execer, c *GatewayProfile) error {
now := time.Now()
c.CreatedAt = now
c.UpdatedAt = now
if c.ID == uuid.Nil {
var err error
c.ID, err = uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid v4 error")
}
}
_, err := db.Exec(`
insert into gateway_profile (
gateway_profile_id,
created_at,
updated_at,
channels
) values ($1, $2, $3, $4)`,
c.ID,
c.CreatedAt,
c.UpdatedAt,
pq.Array(c.Channels),
)
if err != nil {
return handlePSQLError(err, "insert error")
}
for _, ec := range c.ExtraChannels {
_, err := db.Exec(`
insert into gateway_profile_extra_channel (
gateway_profile_id,
modulation,
frequency,
bandwidth,
bitrate,
spreading_factors
) values ($1, $2, $3, $4, $5, $6)`,
c.ID,
ec.Modulation,
ec.Frequency,
ec.Bandwidth,
ec.Bitrate,
pq.Array(ec.SpreadingFactors),
)
if err != nil {
return handlePSQLError(err, "insert error")
}
}
log.WithFields(log.Fields{
"id": c.ID,
}).Info("gateway-profile created")
return nil
}
|
[
"func",
"CreateGatewayProfile",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"c",
"*",
"GatewayProfile",
")",
"error",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"c",
".",
"CreatedAt",
"=",
"now",
"\n",
"c",
".",
"UpdatedAt",
"=",
"now",
"\n",
"if",
"c",
".",
"ID",
"==",
"uuid",
".",
"Nil",
"{",
"var",
"err",
"error",
"\n",
"c",
".",
"ID",
",",
"err",
"=",
"uuid",
".",
"NewV4",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"new uuid v4 error\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\t\tinsert into gateway_profile (\t\t\tgateway_profile_id,\t\t\tcreated_at,\t\t\tupdated_at,\t\t\tchannels\t\t) values ($1, $2, $3, $4)`",
",",
"c",
".",
"ID",
",",
"c",
".",
"CreatedAt",
",",
"c",
".",
"UpdatedAt",
",",
"pq",
".",
"Array",
"(",
"c",
".",
"Channels",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"insert error\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"ec",
":=",
"range",
"c",
".",
"ExtraChannels",
"{",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\t\t\tinsert into gateway_profile_extra_channel (\t\t\t\tgateway_profile_id,\t\t\t\tmodulation,\t\t\t\tfrequency,\t\t\t\tbandwidth,\t\t\t\tbitrate,\t\t\t\tspreading_factors\t\t\t) values ($1, $2, $3, $4, $5, $6)`",
",",
"c",
".",
"ID",
",",
"ec",
".",
"Modulation",
",",
"ec",
".",
"Frequency",
",",
"ec",
".",
"Bandwidth",
",",
"ec",
".",
"Bitrate",
",",
"pq",
".",
"Array",
"(",
"ec",
".",
"SpreadingFactors",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"insert error\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"id\"",
":",
"c",
".",
"ID",
",",
"}",
")",
".",
"Info",
"(",
"\"gateway-profile created\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// CreateGatewayProfile creates the given gateway-profile.
// As this will execute multiple SQL statements, it is recommended to perform
// this within a transaction.
|
[
"CreateGatewayProfile",
"creates",
"the",
"given",
"gateway",
"-",
"profile",
".",
"As",
"this",
"will",
"execute",
"multiple",
"SQL",
"statements",
"it",
"is",
"recommended",
"to",
"perform",
"this",
"within",
"a",
"transaction",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway_profile.go#L45-L101
|
train
|
brocaar/loraserver
|
internal/storage/gateway_profile.go
|
GetGatewayProfile
|
func GetGatewayProfile(db sqlx.Queryer, id uuid.UUID) (GatewayProfile, error) {
var c GatewayProfile
err := db.QueryRowx(`
select
gateway_profile_id,
created_at,
updated_at,
channels
from gateway_profile
where
gateway_profile_id = $1`,
id,
).Scan(
&c.ID,
&c.CreatedAt,
&c.UpdatedAt,
pq.Array(&c.Channels),
)
if err != nil {
return c, handlePSQLError(err, "select error")
}
rows, err := db.Query(`
select
modulation,
frequency,
bandwidth,
bitrate,
spreading_factors
from gateway_profile_extra_channel
where
gateway_profile_id = $1
order by id`,
id,
)
if err != nil {
return c, handlePSQLError(err, "select error")
}
defer rows.Close()
for rows.Next() {
var ec ExtraChannel
err := rows.Scan(
&ec.Modulation,
&ec.Frequency,
&ec.Bandwidth,
&ec.Bitrate,
pq.Array(&ec.SpreadingFactors),
)
if err != nil {
return c, handlePSQLError(err, "select error")
}
c.ExtraChannels = append(c.ExtraChannels, ec)
}
return c, nil
}
|
go
|
func GetGatewayProfile(db sqlx.Queryer, id uuid.UUID) (GatewayProfile, error) {
var c GatewayProfile
err := db.QueryRowx(`
select
gateway_profile_id,
created_at,
updated_at,
channels
from gateway_profile
where
gateway_profile_id = $1`,
id,
).Scan(
&c.ID,
&c.CreatedAt,
&c.UpdatedAt,
pq.Array(&c.Channels),
)
if err != nil {
return c, handlePSQLError(err, "select error")
}
rows, err := db.Query(`
select
modulation,
frequency,
bandwidth,
bitrate,
spreading_factors
from gateway_profile_extra_channel
where
gateway_profile_id = $1
order by id`,
id,
)
if err != nil {
return c, handlePSQLError(err, "select error")
}
defer rows.Close()
for rows.Next() {
var ec ExtraChannel
err := rows.Scan(
&ec.Modulation,
&ec.Frequency,
&ec.Bandwidth,
&ec.Bitrate,
pq.Array(&ec.SpreadingFactors),
)
if err != nil {
return c, handlePSQLError(err, "select error")
}
c.ExtraChannels = append(c.ExtraChannels, ec)
}
return c, nil
}
|
[
"func",
"GetGatewayProfile",
"(",
"db",
"sqlx",
".",
"Queryer",
",",
"id",
"uuid",
".",
"UUID",
")",
"(",
"GatewayProfile",
",",
"error",
")",
"{",
"var",
"c",
"GatewayProfile",
"\n",
"err",
":=",
"db",
".",
"QueryRowx",
"(",
"`\t\tselect\t\t\tgateway_profile_id,\t\t\tcreated_at,\t\t\tupdated_at,\t\t\tchannels\t\tfrom gateway_profile\t\twhere\t\t\tgateway_profile_id = $1`",
",",
"id",
",",
")",
".",
"Scan",
"(",
"&",
"c",
".",
"ID",
",",
"&",
"c",
".",
"CreatedAt",
",",
"&",
"c",
".",
"UpdatedAt",
",",
"pq",
".",
"Array",
"(",
"&",
"c",
".",
"Channels",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"c",
",",
"handlePSQLError",
"(",
"err",
",",
"\"select error\"",
")",
"\n",
"}",
"\n",
"rows",
",",
"err",
":=",
"db",
".",
"Query",
"(",
"`\t\tselect\t\t\tmodulation,\t\t\tfrequency,\t\t\tbandwidth,\t\t\tbitrate,\t\t\tspreading_factors\t\tfrom gateway_profile_extra_channel\t\twhere\t\t\tgateway_profile_id = $1\t\torder by id`",
",",
"id",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"c",
",",
"handlePSQLError",
"(",
"err",
",",
"\"select error\"",
")",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"for",
"rows",
".",
"Next",
"(",
")",
"{",
"var",
"ec",
"ExtraChannel",
"\n",
"err",
":=",
"rows",
".",
"Scan",
"(",
"&",
"ec",
".",
"Modulation",
",",
"&",
"ec",
".",
"Frequency",
",",
"&",
"ec",
".",
"Bandwidth",
",",
"&",
"ec",
".",
"Bitrate",
",",
"pq",
".",
"Array",
"(",
"&",
"ec",
".",
"SpreadingFactors",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"c",
",",
"handlePSQLError",
"(",
"err",
",",
"\"select error\"",
")",
"\n",
"}",
"\n",
"c",
".",
"ExtraChannels",
"=",
"append",
"(",
"c",
".",
"ExtraChannels",
",",
"ec",
")",
"\n",
"}",
"\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] |
// GetGatewayProfile returns the gateway-profile matching the
// given ID.
|
[
"GetGatewayProfile",
"returns",
"the",
"gateway",
"-",
"profile",
"matching",
"the",
"given",
"ID",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway_profile.go#L105-L161
|
train
|
brocaar/loraserver
|
internal/storage/gateway_profile.go
|
UpdateGatewayProfile
|
func UpdateGatewayProfile(db sqlx.Execer, c *GatewayProfile) error {
c.UpdatedAt = time.Now()
res, err := db.Exec(`
update gateway_profile
set
updated_at = $2,
channels = $3
where
gateway_profile_id = $1`,
c.ID,
c.UpdatedAt,
pq.Array(c.Channels),
)
if err != nil {
return handlePSQLError(err, "update error")
}
ra, err := res.RowsAffected()
if err != nil {
return handlePSQLError(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
// This could be optimized by creating a diff of the actual extra channels
// and the wanted. As it is not likely that this data changes really often
// the 'simple' solution of re-creating all the extra channels has been
// implemented.
_, err = db.Exec(`
delete from gateway_profile_extra_channel
where
gateway_profile_id = $1`,
c.ID,
)
if err != nil {
return handlePSQLError(err, "delete error")
}
for _, ec := range c.ExtraChannels {
_, err := db.Exec(`
insert into gateway_profile_extra_channel (
gateway_profile_id,
modulation,
frequency,
bandwidth,
bitrate,
spreading_factors
) values ($1, $2, $3, $4, $5, $6)`,
c.ID,
ec.Modulation,
ec.Frequency,
ec.Bandwidth,
ec.Bitrate,
pq.Array(ec.SpreadingFactors),
)
if err != nil {
return handlePSQLError(err, "insert error")
}
}
log.WithFields(log.Fields{
"id": c.ID,
}).Info("gateway-profile updated")
return nil
}
|
go
|
func UpdateGatewayProfile(db sqlx.Execer, c *GatewayProfile) error {
c.UpdatedAt = time.Now()
res, err := db.Exec(`
update gateway_profile
set
updated_at = $2,
channels = $3
where
gateway_profile_id = $1`,
c.ID,
c.UpdatedAt,
pq.Array(c.Channels),
)
if err != nil {
return handlePSQLError(err, "update error")
}
ra, err := res.RowsAffected()
if err != nil {
return handlePSQLError(err, "get rows affected error")
}
if ra == 0 {
return ErrDoesNotExist
}
// This could be optimized by creating a diff of the actual extra channels
// and the wanted. As it is not likely that this data changes really often
// the 'simple' solution of re-creating all the extra channels has been
// implemented.
_, err = db.Exec(`
delete from gateway_profile_extra_channel
where
gateway_profile_id = $1`,
c.ID,
)
if err != nil {
return handlePSQLError(err, "delete error")
}
for _, ec := range c.ExtraChannels {
_, err := db.Exec(`
insert into gateway_profile_extra_channel (
gateway_profile_id,
modulation,
frequency,
bandwidth,
bitrate,
spreading_factors
) values ($1, $2, $3, $4, $5, $6)`,
c.ID,
ec.Modulation,
ec.Frequency,
ec.Bandwidth,
ec.Bitrate,
pq.Array(ec.SpreadingFactors),
)
if err != nil {
return handlePSQLError(err, "insert error")
}
}
log.WithFields(log.Fields{
"id": c.ID,
}).Info("gateway-profile updated")
return nil
}
|
[
"func",
"UpdateGatewayProfile",
"(",
"db",
"sqlx",
".",
"Execer",
",",
"c",
"*",
"GatewayProfile",
")",
"error",
"{",
"c",
".",
"UpdatedAt",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"res",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\t\tupdate gateway_profile\t\tset\t\t\tupdated_at = $2,\t\t\tchannels = $3\t\twhere\t\t\tgateway_profile_id = $1`",
",",
"c",
".",
"ID",
",",
"c",
".",
"UpdatedAt",
",",
"pq",
".",
"Array",
"(",
"c",
".",
"Channels",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"update error\"",
")",
"\n",
"}",
"\n",
"ra",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"get rows affected error\"",
")",
"\n",
"}",
"\n",
"if",
"ra",
"==",
"0",
"{",
"return",
"ErrDoesNotExist",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"db",
".",
"Exec",
"(",
"`\t\tdelete from gateway_profile_extra_channel\t\twhere\t\t\tgateway_profile_id = $1`",
",",
"c",
".",
"ID",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"delete error\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"ec",
":=",
"range",
"c",
".",
"ExtraChannels",
"{",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"`\t\t\tinsert into gateway_profile_extra_channel (\t\t\t\tgateway_profile_id,\t\t\t\tmodulation,\t\t\t\tfrequency,\t\t\t\tbandwidth,\t\t\t\tbitrate,\t\t\t\tspreading_factors\t\t\t) values ($1, $2, $3, $4, $5, $6)`",
",",
"c",
".",
"ID",
",",
"ec",
".",
"Modulation",
",",
"ec",
".",
"Frequency",
",",
"ec",
".",
"Bandwidth",
",",
"ec",
".",
"Bitrate",
",",
"pq",
".",
"Array",
"(",
"ec",
".",
"SpreadingFactors",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"handlePSQLError",
"(",
"err",
",",
"\"insert error\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"id\"",
":",
"c",
".",
"ID",
",",
"}",
")",
".",
"Info",
"(",
"\"gateway-profile updated\"",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UpdateGatewayProfile updates the given gateway-profile.
// As this will execute multiple SQL statements, it is recommended to perform
// this within a transaction.
|
[
"UpdateGatewayProfile",
"updates",
"the",
"given",
"gateway",
"-",
"profile",
".",
"As",
"this",
"will",
"execute",
"multiple",
"SQL",
"statements",
"it",
"is",
"recommended",
"to",
"perform",
"this",
"within",
"a",
"transaction",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/gateway_profile.go#L166-L231
|
train
|
brocaar/loraserver
|
internal/maccommand/link_adr.go
|
handleLinkADRAns
|
func handleLinkADRAns(ds *storage.DeviceSession, block storage.MACCommandBlock, pendingBlock *storage.MACCommandBlock) ([]storage.MACCommandBlock, error) {
if len(block.MACCommands) == 0 {
return nil, errors.New("at least 1 mac-command expected, got none")
}
if pendingBlock == nil || len(pendingBlock.MACCommands) == 0 {
return nil, errors.New("expected pending mac-command")
}
channelMaskACK := true
dataRateACK := true
powerACK := true
for i := range block.MACCommands {
pl, ok := block.MACCommands[i].Payload.(*lorawan.LinkADRAnsPayload)
if !ok {
return nil, fmt.Errorf("expected *lorawan.LinkADRAnsPayload, got %T", block.MACCommands[i].Payload)
}
if !pl.ChannelMaskACK {
channelMaskACK = false
}
if !pl.DataRateACK {
dataRateACK = false
}
if !pl.PowerACK {
powerACK = false
}
}
var linkADRPayloads []lorawan.LinkADRReqPayload
for i := range pendingBlock.MACCommands {
linkADRPayloads = append(linkADRPayloads, *pendingBlock.MACCommands[i].Payload.(*lorawan.LinkADRReqPayload))
}
// as we're sending the same txpower and nbrep for each channel we
// take the last one
adrReq := linkADRPayloads[len(linkADRPayloads)-1]
if channelMaskACK && dataRateACK && powerACK {
chans, err := band.Band().GetEnabledUplinkChannelIndicesForLinkADRReqPayloads(ds.EnabledUplinkChannels, linkADRPayloads)
if err != nil {
return nil, errors.Wrap(err, "get enalbed channels for link_adr_req payloads error")
}
ds.TXPowerIndex = int(adrReq.TXPower)
ds.DR = int(adrReq.DataRate)
ds.NbTrans = adrReq.Redundancy.NbRep
ds.EnabledUplinkChannels = chans
log.WithFields(log.Fields{
"dev_eui": ds.DevEUI,
"tx_power_idx": ds.TXPowerIndex,
"dr": adrReq.DataRate,
"nb_trans": adrReq.Redundancy.NbRep,
"enabled_channels": chans,
}).Info("link_adr request acknowledged")
} else {
// TODO: remove workaround once all RN2483 nodes have the issue below
// fixed.
//
// This is a workaround for the RN2483 firmware (1.0.3) which sends
// a nACK on TXPower 0 (this is incorrect behaviour, following the
// specs). It should ACK and operate at its maximum possible power
// when TXPower 0 is not supported. See also section 5.2 in the
// LoRaWAN specs.
if !powerACK && adrReq.TXPower == 0 {
ds.TXPowerIndex = 1
ds.MinSupportedTXPowerIndex = 1
}
// It is possible that the node does not support all TXPower
// indices. In this case we set the MaxSupportedTXPowerIndex
// to the request - 1. If that index is not supported, it will
// be lowered by 1 at the next nACK.
if !powerACK && adrReq.TXPower > 0 {
ds.MaxSupportedTXPowerIndex = int(adrReq.TXPower) - 1
}
log.WithFields(log.Fields{
"dev_eui": ds.DevEUI,
"channel_mask_ack": channelMaskACK,
"data_rate_ack": dataRateACK,
"power_ack": powerACK,
}).Warning("link_adr request not acknowledged")
}
return nil, nil
}
|
go
|
func handleLinkADRAns(ds *storage.DeviceSession, block storage.MACCommandBlock, pendingBlock *storage.MACCommandBlock) ([]storage.MACCommandBlock, error) {
if len(block.MACCommands) == 0 {
return nil, errors.New("at least 1 mac-command expected, got none")
}
if pendingBlock == nil || len(pendingBlock.MACCommands) == 0 {
return nil, errors.New("expected pending mac-command")
}
channelMaskACK := true
dataRateACK := true
powerACK := true
for i := range block.MACCommands {
pl, ok := block.MACCommands[i].Payload.(*lorawan.LinkADRAnsPayload)
if !ok {
return nil, fmt.Errorf("expected *lorawan.LinkADRAnsPayload, got %T", block.MACCommands[i].Payload)
}
if !pl.ChannelMaskACK {
channelMaskACK = false
}
if !pl.DataRateACK {
dataRateACK = false
}
if !pl.PowerACK {
powerACK = false
}
}
var linkADRPayloads []lorawan.LinkADRReqPayload
for i := range pendingBlock.MACCommands {
linkADRPayloads = append(linkADRPayloads, *pendingBlock.MACCommands[i].Payload.(*lorawan.LinkADRReqPayload))
}
// as we're sending the same txpower and nbrep for each channel we
// take the last one
adrReq := linkADRPayloads[len(linkADRPayloads)-1]
if channelMaskACK && dataRateACK && powerACK {
chans, err := band.Band().GetEnabledUplinkChannelIndicesForLinkADRReqPayloads(ds.EnabledUplinkChannels, linkADRPayloads)
if err != nil {
return nil, errors.Wrap(err, "get enalbed channels for link_adr_req payloads error")
}
ds.TXPowerIndex = int(adrReq.TXPower)
ds.DR = int(adrReq.DataRate)
ds.NbTrans = adrReq.Redundancy.NbRep
ds.EnabledUplinkChannels = chans
log.WithFields(log.Fields{
"dev_eui": ds.DevEUI,
"tx_power_idx": ds.TXPowerIndex,
"dr": adrReq.DataRate,
"nb_trans": adrReq.Redundancy.NbRep,
"enabled_channels": chans,
}).Info("link_adr request acknowledged")
} else {
// TODO: remove workaround once all RN2483 nodes have the issue below
// fixed.
//
// This is a workaround for the RN2483 firmware (1.0.3) which sends
// a nACK on TXPower 0 (this is incorrect behaviour, following the
// specs). It should ACK and operate at its maximum possible power
// when TXPower 0 is not supported. See also section 5.2 in the
// LoRaWAN specs.
if !powerACK && adrReq.TXPower == 0 {
ds.TXPowerIndex = 1
ds.MinSupportedTXPowerIndex = 1
}
// It is possible that the node does not support all TXPower
// indices. In this case we set the MaxSupportedTXPowerIndex
// to the request - 1. If that index is not supported, it will
// be lowered by 1 at the next nACK.
if !powerACK && adrReq.TXPower > 0 {
ds.MaxSupportedTXPowerIndex = int(adrReq.TXPower) - 1
}
log.WithFields(log.Fields{
"dev_eui": ds.DevEUI,
"channel_mask_ack": channelMaskACK,
"data_rate_ack": dataRateACK,
"power_ack": powerACK,
}).Warning("link_adr request not acknowledged")
}
return nil, nil
}
|
[
"func",
"handleLinkADRAns",
"(",
"ds",
"*",
"storage",
".",
"DeviceSession",
",",
"block",
"storage",
".",
"MACCommandBlock",
",",
"pendingBlock",
"*",
"storage",
".",
"MACCommandBlock",
")",
"(",
"[",
"]",
"storage",
".",
"MACCommandBlock",
",",
"error",
")",
"{",
"if",
"len",
"(",
"block",
".",
"MACCommands",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"at least 1 mac-command expected, got none\"",
")",
"\n",
"}",
"\n",
"if",
"pendingBlock",
"==",
"nil",
"||",
"len",
"(",
"pendingBlock",
".",
"MACCommands",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"expected pending mac-command\"",
")",
"\n",
"}",
"\n",
"channelMaskACK",
":=",
"true",
"\n",
"dataRateACK",
":=",
"true",
"\n",
"powerACK",
":=",
"true",
"\n",
"for",
"i",
":=",
"range",
"block",
".",
"MACCommands",
"{",
"pl",
",",
"ok",
":=",
"block",
".",
"MACCommands",
"[",
"i",
"]",
".",
"Payload",
".",
"(",
"*",
"lorawan",
".",
"LinkADRAnsPayload",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"expected *lorawan.LinkADRAnsPayload, got %T\"",
",",
"block",
".",
"MACCommands",
"[",
"i",
"]",
".",
"Payload",
")",
"\n",
"}",
"\n",
"if",
"!",
"pl",
".",
"ChannelMaskACK",
"{",
"channelMaskACK",
"=",
"false",
"\n",
"}",
"\n",
"if",
"!",
"pl",
".",
"DataRateACK",
"{",
"dataRateACK",
"=",
"false",
"\n",
"}",
"\n",
"if",
"!",
"pl",
".",
"PowerACK",
"{",
"powerACK",
"=",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"linkADRPayloads",
"[",
"]",
"lorawan",
".",
"LinkADRReqPayload",
"\n",
"for",
"i",
":=",
"range",
"pendingBlock",
".",
"MACCommands",
"{",
"linkADRPayloads",
"=",
"append",
"(",
"linkADRPayloads",
",",
"*",
"pendingBlock",
".",
"MACCommands",
"[",
"i",
"]",
".",
"Payload",
".",
"(",
"*",
"lorawan",
".",
"LinkADRReqPayload",
")",
")",
"\n",
"}",
"\n",
"adrReq",
":=",
"linkADRPayloads",
"[",
"len",
"(",
"linkADRPayloads",
")",
"-",
"1",
"]",
"\n",
"if",
"channelMaskACK",
"&&",
"dataRateACK",
"&&",
"powerACK",
"{",
"chans",
",",
"err",
":=",
"band",
".",
"Band",
"(",
")",
".",
"GetEnabledUplinkChannelIndicesForLinkADRReqPayloads",
"(",
"ds",
".",
"EnabledUplinkChannels",
",",
"linkADRPayloads",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"get enalbed channels for link_adr_req payloads error\"",
")",
"\n",
"}",
"\n",
"ds",
".",
"TXPowerIndex",
"=",
"int",
"(",
"adrReq",
".",
"TXPower",
")",
"\n",
"ds",
".",
"DR",
"=",
"int",
"(",
"adrReq",
".",
"DataRate",
")",
"\n",
"ds",
".",
"NbTrans",
"=",
"adrReq",
".",
"Redundancy",
".",
"NbRep",
"\n",
"ds",
".",
"EnabledUplinkChannels",
"=",
"chans",
"\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"dev_eui\"",
":",
"ds",
".",
"DevEUI",
",",
"\"tx_power_idx\"",
":",
"ds",
".",
"TXPowerIndex",
",",
"\"dr\"",
":",
"adrReq",
".",
"DataRate",
",",
"\"nb_trans\"",
":",
"adrReq",
".",
"Redundancy",
".",
"NbRep",
",",
"\"enabled_channels\"",
":",
"chans",
",",
"}",
")",
".",
"Info",
"(",
"\"link_adr request acknowledged\"",
")",
"\n",
"}",
"else",
"{",
"if",
"!",
"powerACK",
"&&",
"adrReq",
".",
"TXPower",
"==",
"0",
"{",
"ds",
".",
"TXPowerIndex",
"=",
"1",
"\n",
"ds",
".",
"MinSupportedTXPowerIndex",
"=",
"1",
"\n",
"}",
"\n",
"if",
"!",
"powerACK",
"&&",
"adrReq",
".",
"TXPower",
">",
"0",
"{",
"ds",
".",
"MaxSupportedTXPowerIndex",
"=",
"int",
"(",
"adrReq",
".",
"TXPower",
")",
"-",
"1",
"\n",
"}",
"\n",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"dev_eui\"",
":",
"ds",
".",
"DevEUI",
",",
"\"channel_mask_ack\"",
":",
"channelMaskACK",
",",
"\"data_rate_ack\"",
":",
"dataRateACK",
",",
"\"power_ack\"",
":",
"powerACK",
",",
"}",
")",
".",
"Warning",
"(",
"\"link_adr request not acknowledged\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] |
// handleLinkADRAns handles the ack of an ADR request
|
[
"handleLinkADRAns",
"handles",
"the",
"ack",
"of",
"an",
"ADR",
"request"
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/maccommand/link_adr.go#L14-L103
|
train
|
brocaar/loraserver
|
internal/uplink/uplink.go
|
Start
|
func (s *Server) Start() error {
go func() {
s.wg.Add(1)
defer s.wg.Done()
HandleRXPackets(&s.wg)
}()
go func() {
s.wg.Add(1)
defer s.wg.Done()
HandleDownlinkTXAcks(&s.wg)
}()
return nil
}
|
go
|
func (s *Server) Start() error {
go func() {
s.wg.Add(1)
defer s.wg.Done()
HandleRXPackets(&s.wg)
}()
go func() {
s.wg.Add(1)
defer s.wg.Done()
HandleDownlinkTXAcks(&s.wg)
}()
return nil
}
|
[
"func",
"(",
"s",
"*",
"Server",
")",
"Start",
"(",
")",
"error",
"{",
"go",
"func",
"(",
")",
"{",
"s",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"defer",
"s",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"HandleRXPackets",
"(",
"&",
"s",
".",
"wg",
")",
"\n",
"}",
"(",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"s",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"defer",
"s",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"HandleDownlinkTXAcks",
"(",
"&",
"s",
".",
"wg",
")",
"\n",
"}",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Start starts the server.
|
[
"Start",
"starts",
"the",
"server",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/uplink/uplink.go#L62-L75
|
train
|
brocaar/loraserver
|
internal/uplink/uplink.go
|
Stop
|
func (s *Server) Stop() error {
if err := gwbackend.Backend().Close(); err != nil {
return fmt.Errorf("close gateway backend error: %s", err)
}
log.Info("waiting for pending actions to complete")
s.wg.Wait()
return nil
}
|
go
|
func (s *Server) Stop() error {
if err := gwbackend.Backend().Close(); err != nil {
return fmt.Errorf("close gateway backend error: %s", err)
}
log.Info("waiting for pending actions to complete")
s.wg.Wait()
return nil
}
|
[
"func",
"(",
"s",
"*",
"Server",
")",
"Stop",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"gwbackend",
".",
"Backend",
"(",
")",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"close gateway backend error: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"log",
".",
"Info",
"(",
"\"waiting for pending actions to complete\"",
")",
"\n",
"s",
".",
"wg",
".",
"Wait",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Stop closes the gateway backend and waits for the server to complete the
// pending packets.
|
[
"Stop",
"closes",
"the",
"gateway",
"backend",
"and",
"waits",
"for",
"the",
"server",
"to",
"complete",
"the",
"pending",
"packets",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/uplink/uplink.go#L79-L86
|
train
|
brocaar/loraserver
|
internal/uplink/uplink.go
|
HandleRXPackets
|
func HandleRXPackets(wg *sync.WaitGroup) {
for uplinkFrame := range gwbackend.Backend().RXPacketChan() {
go func(uplinkFrame gw.UplinkFrame) {
wg.Add(1)
defer wg.Done()
if err := HandleRXPacket(uplinkFrame); err != nil {
data := base64.StdEncoding.EncodeToString(uplinkFrame.PhyPayload)
log.WithField("data_base64", data).WithError(err).Error("processing uplink frame error")
}
}(uplinkFrame)
}
}
|
go
|
func HandleRXPackets(wg *sync.WaitGroup) {
for uplinkFrame := range gwbackend.Backend().RXPacketChan() {
go func(uplinkFrame gw.UplinkFrame) {
wg.Add(1)
defer wg.Done()
if err := HandleRXPacket(uplinkFrame); err != nil {
data := base64.StdEncoding.EncodeToString(uplinkFrame.PhyPayload)
log.WithField("data_base64", data).WithError(err).Error("processing uplink frame error")
}
}(uplinkFrame)
}
}
|
[
"func",
"HandleRXPackets",
"(",
"wg",
"*",
"sync",
".",
"WaitGroup",
")",
"{",
"for",
"uplinkFrame",
":=",
"range",
"gwbackend",
".",
"Backend",
"(",
")",
".",
"RXPacketChan",
"(",
")",
"{",
"go",
"func",
"(",
"uplinkFrame",
"gw",
".",
"UplinkFrame",
")",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"if",
"err",
":=",
"HandleRXPacket",
"(",
"uplinkFrame",
")",
";",
"err",
"!=",
"nil",
"{",
"data",
":=",
"base64",
".",
"StdEncoding",
".",
"EncodeToString",
"(",
"uplinkFrame",
".",
"PhyPayload",
")",
"\n",
"log",
".",
"WithField",
"(",
"\"data_base64\"",
",",
"data",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"processing uplink frame error\"",
")",
"\n",
"}",
"\n",
"}",
"(",
"uplinkFrame",
")",
"\n",
"}",
"\n",
"}"
] |
// HandleRXPackets consumes received packets by the gateway and handles them
// in a separate go-routine. Errors are logged.
|
[
"HandleRXPackets",
"consumes",
"received",
"packets",
"by",
"the",
"gateway",
"and",
"handles",
"them",
"in",
"a",
"separate",
"go",
"-",
"routine",
".",
"Errors",
"are",
"logged",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/uplink/uplink.go#L90-L101
|
train
|
brocaar/loraserver
|
internal/uplink/uplink.go
|
HandleDownlinkTXAcks
|
func HandleDownlinkTXAcks(wg *sync.WaitGroup) {
for downlinkTXAck := range gwbackend.Backend().DownlinkTXAckChan() {
go func(downlinkTXAck gw.DownlinkTXAck) {
wg.Add(1)
defer wg.Done()
if err := ack.HandleDownlinkTXAck(downlinkTXAck); err != nil {
log.WithFields(log.Fields{
"gateway_id": hex.EncodeToString(downlinkTXAck.GatewayId),
"token": downlinkTXAck.Token,
}).WithError(err).Error("handle downlink tx ack error")
}
}(downlinkTXAck)
}
}
|
go
|
func HandleDownlinkTXAcks(wg *sync.WaitGroup) {
for downlinkTXAck := range gwbackend.Backend().DownlinkTXAckChan() {
go func(downlinkTXAck gw.DownlinkTXAck) {
wg.Add(1)
defer wg.Done()
if err := ack.HandleDownlinkTXAck(downlinkTXAck); err != nil {
log.WithFields(log.Fields{
"gateway_id": hex.EncodeToString(downlinkTXAck.GatewayId),
"token": downlinkTXAck.Token,
}).WithError(err).Error("handle downlink tx ack error")
}
}(downlinkTXAck)
}
}
|
[
"func",
"HandleDownlinkTXAcks",
"(",
"wg",
"*",
"sync",
".",
"WaitGroup",
")",
"{",
"for",
"downlinkTXAck",
":=",
"range",
"gwbackend",
".",
"Backend",
"(",
")",
".",
"DownlinkTXAckChan",
"(",
")",
"{",
"go",
"func",
"(",
"downlinkTXAck",
"gw",
".",
"DownlinkTXAck",
")",
"{",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"defer",
"wg",
".",
"Done",
"(",
")",
"\n",
"if",
"err",
":=",
"ack",
".",
"HandleDownlinkTXAck",
"(",
"downlinkTXAck",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithFields",
"(",
"log",
".",
"Fields",
"{",
"\"gateway_id\"",
":",
"hex",
".",
"EncodeToString",
"(",
"downlinkTXAck",
".",
"GatewayId",
")",
",",
"\"token\"",
":",
"downlinkTXAck",
".",
"Token",
",",
"}",
")",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"handle downlink tx ack error\"",
")",
"\n",
"}",
"\n",
"}",
"(",
"downlinkTXAck",
")",
"\n",
"}",
"\n",
"}"
] |
// HandleDownlinkTXAcks consumes received downlink tx acknowledgements from
// the gateway.
|
[
"HandleDownlinkTXAcks",
"consumes",
"received",
"downlink",
"tx",
"acknowledgements",
"from",
"the",
"gateway",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/uplink/uplink.go#L110-L124
|
train
|
brocaar/loraserver
|
internal/downlink/scheduler.go
|
DeviceQueueSchedulerLoop
|
func DeviceQueueSchedulerLoop() {
for {
log.Debug("running class-b / class-c scheduler batch")
if err := ScheduleDeviceQueueBatch(schedulerBatchSize); err != nil {
log.WithError(err).Error("class-b / class-c scheduler error")
}
time.Sleep(schedulerInterval)
}
}
|
go
|
func DeviceQueueSchedulerLoop() {
for {
log.Debug("running class-b / class-c scheduler batch")
if err := ScheduleDeviceQueueBatch(schedulerBatchSize); err != nil {
log.WithError(err).Error("class-b / class-c scheduler error")
}
time.Sleep(schedulerInterval)
}
}
|
[
"func",
"DeviceQueueSchedulerLoop",
"(",
")",
"{",
"for",
"{",
"log",
".",
"Debug",
"(",
"\"running class-b / class-c scheduler batch\"",
")",
"\n",
"if",
"err",
":=",
"ScheduleDeviceQueueBatch",
"(",
"schedulerBatchSize",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"class-b / class-c scheduler error\"",
")",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"schedulerInterval",
")",
"\n",
"}",
"\n",
"}"
] |
// DeviceQueueSchedulerLoop starts an infinit loop calling the scheduler loop for Class-B
// and Class-C sheduling.
|
[
"DeviceQueueSchedulerLoop",
"starts",
"an",
"infinit",
"loop",
"calling",
"the",
"scheduler",
"loop",
"for",
"Class",
"-",
"B",
"and",
"Class",
"-",
"C",
"sheduling",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/scheduler.go#L17-L25
|
train
|
brocaar/loraserver
|
internal/downlink/scheduler.go
|
MulticastQueueSchedulerLoop
|
func MulticastQueueSchedulerLoop() {
for {
log.Debug("running multicast scheduler batch")
if err := ScheduleMulticastQueueBatch(schedulerBatchSize); err != nil {
log.WithError(err).Error("multicast scheduler error")
}
time.Sleep(schedulerInterval)
}
}
|
go
|
func MulticastQueueSchedulerLoop() {
for {
log.Debug("running multicast scheduler batch")
if err := ScheduleMulticastQueueBatch(schedulerBatchSize); err != nil {
log.WithError(err).Error("multicast scheduler error")
}
time.Sleep(schedulerInterval)
}
}
|
[
"func",
"MulticastQueueSchedulerLoop",
"(",
")",
"{",
"for",
"{",
"log",
".",
"Debug",
"(",
"\"running multicast scheduler batch\"",
")",
"\n",
"if",
"err",
":=",
"ScheduleMulticastQueueBatch",
"(",
"schedulerBatchSize",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"Error",
"(",
"\"multicast scheduler error\"",
")",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"schedulerInterval",
")",
"\n",
"}",
"\n",
"}"
] |
// MulticastQueueSchedulerLoop starts an infinit loop calling the multicast
// scheduler loop.
|
[
"MulticastQueueSchedulerLoop",
"starts",
"an",
"infinit",
"loop",
"calling",
"the",
"multicast",
"scheduler",
"loop",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/scheduler.go#L29-L37
|
train
|
brocaar/loraserver
|
internal/maccommand/new_channel.go
|
RequestNewChannels
|
func RequestNewChannels(devEUI lorawan.EUI64, maxChannels int, currentChannels, wantedChannels map[int]band.Channel) *storage.MACCommandBlock {
var out []lorawan.MACCommand
// sort by channel index
var wantedChannelNumbers []int
for i := range wantedChannels {
wantedChannelNumbers = append(wantedChannelNumbers, i)
}
sort.Ints(wantedChannelNumbers)
for _, i := range wantedChannelNumbers {
wanted := wantedChannels[i]
current, ok := currentChannels[i]
if !ok || current.Frequency != wanted.Frequency || current.MinDR != wanted.MinDR || current.MaxDR != wanted.MaxDR {
out = append(out, lorawan.MACCommand{
CID: lorawan.NewChannelReq,
Payload: &lorawan.NewChannelReqPayload{
ChIndex: uint8(i),
Freq: uint32(wanted.Frequency),
MinDR: uint8(wanted.MinDR),
MaxDR: uint8(wanted.MaxDR),
},
})
}
}
if len(out) > maxChannels {
out = out[0:maxChannels]
}
if len(out) == 0 {
return nil
}
return &storage.MACCommandBlock{
CID: lorawan.NewChannelReq,
MACCommands: storage.MACCommands(out),
}
}
|
go
|
func RequestNewChannels(devEUI lorawan.EUI64, maxChannels int, currentChannels, wantedChannels map[int]band.Channel) *storage.MACCommandBlock {
var out []lorawan.MACCommand
// sort by channel index
var wantedChannelNumbers []int
for i := range wantedChannels {
wantedChannelNumbers = append(wantedChannelNumbers, i)
}
sort.Ints(wantedChannelNumbers)
for _, i := range wantedChannelNumbers {
wanted := wantedChannels[i]
current, ok := currentChannels[i]
if !ok || current.Frequency != wanted.Frequency || current.MinDR != wanted.MinDR || current.MaxDR != wanted.MaxDR {
out = append(out, lorawan.MACCommand{
CID: lorawan.NewChannelReq,
Payload: &lorawan.NewChannelReqPayload{
ChIndex: uint8(i),
Freq: uint32(wanted.Frequency),
MinDR: uint8(wanted.MinDR),
MaxDR: uint8(wanted.MaxDR),
},
})
}
}
if len(out) > maxChannels {
out = out[0:maxChannels]
}
if len(out) == 0 {
return nil
}
return &storage.MACCommandBlock{
CID: lorawan.NewChannelReq,
MACCommands: storage.MACCommands(out),
}
}
|
[
"func",
"RequestNewChannels",
"(",
"devEUI",
"lorawan",
".",
"EUI64",
",",
"maxChannels",
"int",
",",
"currentChannels",
",",
"wantedChannels",
"map",
"[",
"int",
"]",
"band",
".",
"Channel",
")",
"*",
"storage",
".",
"MACCommandBlock",
"{",
"var",
"out",
"[",
"]",
"lorawan",
".",
"MACCommand",
"\n",
"var",
"wantedChannelNumbers",
"[",
"]",
"int",
"\n",
"for",
"i",
":=",
"range",
"wantedChannels",
"{",
"wantedChannelNumbers",
"=",
"append",
"(",
"wantedChannelNumbers",
",",
"i",
")",
"\n",
"}",
"\n",
"sort",
".",
"Ints",
"(",
"wantedChannelNumbers",
")",
"\n",
"for",
"_",
",",
"i",
":=",
"range",
"wantedChannelNumbers",
"{",
"wanted",
":=",
"wantedChannels",
"[",
"i",
"]",
"\n",
"current",
",",
"ok",
":=",
"currentChannels",
"[",
"i",
"]",
"\n",
"if",
"!",
"ok",
"||",
"current",
".",
"Frequency",
"!=",
"wanted",
".",
"Frequency",
"||",
"current",
".",
"MinDR",
"!=",
"wanted",
".",
"MinDR",
"||",
"current",
".",
"MaxDR",
"!=",
"wanted",
".",
"MaxDR",
"{",
"out",
"=",
"append",
"(",
"out",
",",
"lorawan",
".",
"MACCommand",
"{",
"CID",
":",
"lorawan",
".",
"NewChannelReq",
",",
"Payload",
":",
"&",
"lorawan",
".",
"NewChannelReqPayload",
"{",
"ChIndex",
":",
"uint8",
"(",
"i",
")",
",",
"Freq",
":",
"uint32",
"(",
"wanted",
".",
"Frequency",
")",
",",
"MinDR",
":",
"uint8",
"(",
"wanted",
".",
"MinDR",
")",
",",
"MaxDR",
":",
"uint8",
"(",
"wanted",
".",
"MaxDR",
")",
",",
"}",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"out",
")",
">",
"maxChannels",
"{",
"out",
"=",
"out",
"[",
"0",
":",
"maxChannels",
"]",
"\n",
"}",
"\n",
"if",
"len",
"(",
"out",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"storage",
".",
"MACCommandBlock",
"{",
"CID",
":",
"lorawan",
".",
"NewChannelReq",
",",
"MACCommands",
":",
"storage",
".",
"MACCommands",
"(",
"out",
")",
",",
"}",
"\n",
"}"
] |
// RequestNewChannels creates or modifies the non-common bi-directional
// channels in case of changes between the current and wanted channels.
// To avoid generating mac-command blocks which can't be sent, and to
// modify the channels in multiple batches, the max number of channels to
// modify must be given. In case of no changes, nil is returned.
|
[
"RequestNewChannels",
"creates",
"or",
"modifies",
"the",
"non",
"-",
"common",
"bi",
"-",
"directional",
"channels",
"in",
"case",
"of",
"changes",
"between",
"the",
"current",
"and",
"wanted",
"channels",
".",
"To",
"avoid",
"generating",
"mac",
"-",
"command",
"blocks",
"which",
"can",
"t",
"be",
"sent",
"and",
"to",
"modify",
"the",
"channels",
"in",
"multiple",
"batches",
"the",
"max",
"number",
"of",
"channels",
"to",
"modify",
"must",
"be",
"given",
".",
"In",
"case",
"of",
"no",
"changes",
"nil",
"is",
"returned",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/maccommand/new_channel.go#L20-L58
|
train
|
brocaar/loraserver
|
internal/storage/storage.go
|
Setup
|
func Setup(c config.Config) error {
log.Info("storage: setting up storage module")
deviceSessionTTL = c.NetworkServer.DeviceSessionTTL
schedulerInterval = c.NetworkServer.Scheduler.SchedulerInterval
log.Info("storage: setting up Redis connection pool")
redisPool = &redis.Pool{
MaxIdle: 10,
IdleTimeout: c.Redis.IdleTimeout,
Dial: func() (redis.Conn, error) {
c, err := redis.DialURL(c.Redis.URL,
redis.DialReadTimeout(redisDialReadTimeout),
redis.DialWriteTimeout(redisDialWriteTimeout),
)
if err != nil {
return nil, fmt.Errorf("redis connection error: %s", err)
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Now().Sub(t) < onBorrowPingInterval {
return nil
}
_, err := c.Do("PING")
if err != nil {
return fmt.Errorf("ping redis error: %s", err)
}
return nil
},
}
log.Info("storage: connecting to PostgreSQL")
d, err := sqlx.Open("postgres", c.PostgreSQL.DSN)
if err != nil {
return errors.Wrap(err, "storage: PostgreSQL connection error")
}
for {
if err := d.Ping(); err != nil {
log.WithError(err).Warning("storage: ping PostgreSQL database error, will retry in 2s")
time.Sleep(2 * time.Second)
} else {
break
}
}
db = &DBLogger{d}
if c.PostgreSQL.Automigrate {
log.Info("storage: applying PostgreSQL data migrations")
m := &migrate.AssetMigrationSource{
Asset: migrations.Asset,
AssetDir: migrations.AssetDir,
Dir: "",
}
n, err := migrate.Exec(db.DB.DB, "postgres", m, migrate.Up)
if err != nil {
return errors.Wrap(err, "storage: applying PostgreSQL data migrations error")
}
log.WithField("count", n).Info("storage: PostgreSQL data migrations applied")
}
return nil
}
|
go
|
func Setup(c config.Config) error {
log.Info("storage: setting up storage module")
deviceSessionTTL = c.NetworkServer.DeviceSessionTTL
schedulerInterval = c.NetworkServer.Scheduler.SchedulerInterval
log.Info("storage: setting up Redis connection pool")
redisPool = &redis.Pool{
MaxIdle: 10,
IdleTimeout: c.Redis.IdleTimeout,
Dial: func() (redis.Conn, error) {
c, err := redis.DialURL(c.Redis.URL,
redis.DialReadTimeout(redisDialReadTimeout),
redis.DialWriteTimeout(redisDialWriteTimeout),
)
if err != nil {
return nil, fmt.Errorf("redis connection error: %s", err)
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
if time.Now().Sub(t) < onBorrowPingInterval {
return nil
}
_, err := c.Do("PING")
if err != nil {
return fmt.Errorf("ping redis error: %s", err)
}
return nil
},
}
log.Info("storage: connecting to PostgreSQL")
d, err := sqlx.Open("postgres", c.PostgreSQL.DSN)
if err != nil {
return errors.Wrap(err, "storage: PostgreSQL connection error")
}
for {
if err := d.Ping(); err != nil {
log.WithError(err).Warning("storage: ping PostgreSQL database error, will retry in 2s")
time.Sleep(2 * time.Second)
} else {
break
}
}
db = &DBLogger{d}
if c.PostgreSQL.Automigrate {
log.Info("storage: applying PostgreSQL data migrations")
m := &migrate.AssetMigrationSource{
Asset: migrations.Asset,
AssetDir: migrations.AssetDir,
Dir: "",
}
n, err := migrate.Exec(db.DB.DB, "postgres", m, migrate.Up)
if err != nil {
return errors.Wrap(err, "storage: applying PostgreSQL data migrations error")
}
log.WithField("count", n).Info("storage: PostgreSQL data migrations applied")
}
return nil
}
|
[
"func",
"Setup",
"(",
"c",
"config",
".",
"Config",
")",
"error",
"{",
"log",
".",
"Info",
"(",
"\"storage: setting up storage module\"",
")",
"\n",
"deviceSessionTTL",
"=",
"c",
".",
"NetworkServer",
".",
"DeviceSessionTTL",
"\n",
"schedulerInterval",
"=",
"c",
".",
"NetworkServer",
".",
"Scheduler",
".",
"SchedulerInterval",
"\n",
"log",
".",
"Info",
"(",
"\"storage: setting up Redis connection pool\"",
")",
"\n",
"redisPool",
"=",
"&",
"redis",
".",
"Pool",
"{",
"MaxIdle",
":",
"10",
",",
"IdleTimeout",
":",
"c",
".",
"Redis",
".",
"IdleTimeout",
",",
"Dial",
":",
"func",
"(",
")",
"(",
"redis",
".",
"Conn",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"redis",
".",
"DialURL",
"(",
"c",
".",
"Redis",
".",
"URL",
",",
"redis",
".",
"DialReadTimeout",
"(",
"redisDialReadTimeout",
")",
",",
"redis",
".",
"DialWriteTimeout",
"(",
"redisDialWriteTimeout",
")",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"redis connection error: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"c",
",",
"err",
"\n",
"}",
",",
"TestOnBorrow",
":",
"func",
"(",
"c",
"redis",
".",
"Conn",
",",
"t",
"time",
".",
"Time",
")",
"error",
"{",
"if",
"time",
".",
"Now",
"(",
")",
".",
"Sub",
"(",
"t",
")",
"<",
"onBorrowPingInterval",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"c",
".",
"Do",
"(",
"\"PING\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"ping redis error: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
",",
"}",
"\n",
"log",
".",
"Info",
"(",
"\"storage: connecting to PostgreSQL\"",
")",
"\n",
"d",
",",
"err",
":=",
"sqlx",
".",
"Open",
"(",
"\"postgres\"",
",",
"c",
".",
"PostgreSQL",
".",
"DSN",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"storage: PostgreSQL connection error\"",
")",
"\n",
"}",
"\n",
"for",
"{",
"if",
"err",
":=",
"d",
".",
"Ping",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"WithError",
"(",
"err",
")",
".",
"Warning",
"(",
"\"storage: ping PostgreSQL database error, will retry in 2s\"",
")",
"\n",
"time",
".",
"Sleep",
"(",
"2",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"db",
"=",
"&",
"DBLogger",
"{",
"d",
"}",
"\n",
"if",
"c",
".",
"PostgreSQL",
".",
"Automigrate",
"{",
"log",
".",
"Info",
"(",
"\"storage: applying PostgreSQL data migrations\"",
")",
"\n",
"m",
":=",
"&",
"migrate",
".",
"AssetMigrationSource",
"{",
"Asset",
":",
"migrations",
".",
"Asset",
",",
"AssetDir",
":",
"migrations",
".",
"AssetDir",
",",
"Dir",
":",
"\"\"",
",",
"}",
"\n",
"n",
",",
"err",
":=",
"migrate",
".",
"Exec",
"(",
"db",
".",
"DB",
".",
"DB",
",",
"\"postgres\"",
",",
"m",
",",
"migrate",
".",
"Up",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"storage: applying PostgreSQL data migrations error\"",
")",
"\n",
"}",
"\n",
"log",
".",
"WithField",
"(",
"\"count\"",
",",
"n",
")",
".",
"Info",
"(",
"\"storage: PostgreSQL data migrations applied\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Setup configures the storage backend.
|
[
"Setup",
"configures",
"the",
"storage",
"backend",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/storage.go#L25-L89
|
train
|
brocaar/loraserver
|
internal/storage/storage.go
|
Transaction
|
func Transaction(f func(tx sqlx.Ext) error) error {
tx, err := db.Beginx()
if err != nil {
return errors.Wrap(err, "storage: begin transaction error")
}
err = f(tx)
if err != nil {
if rbErr := tx.Rollback(); rbErr != nil {
return errors.Wrap(rbErr, "storage: transaction rollback error")
}
return err
}
if err := tx.Commit(); err != nil {
return errors.Wrap(err, "storage: transaction commit error")
}
return nil
}
|
go
|
func Transaction(f func(tx sqlx.Ext) error) error {
tx, err := db.Beginx()
if err != nil {
return errors.Wrap(err, "storage: begin transaction error")
}
err = f(tx)
if err != nil {
if rbErr := tx.Rollback(); rbErr != nil {
return errors.Wrap(rbErr, "storage: transaction rollback error")
}
return err
}
if err := tx.Commit(); err != nil {
return errors.Wrap(err, "storage: transaction commit error")
}
return nil
}
|
[
"func",
"Transaction",
"(",
"f",
"func",
"(",
"tx",
"sqlx",
".",
"Ext",
")",
"error",
")",
"error",
"{",
"tx",
",",
"err",
":=",
"db",
".",
"Beginx",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"storage: begin transaction error\"",
")",
"\n",
"}",
"\n",
"err",
"=",
"f",
"(",
"tx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"rbErr",
":=",
"tx",
".",
"Rollback",
"(",
")",
";",
"rbErr",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"rbErr",
",",
"\"storage: transaction rollback error\"",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"tx",
".",
"Commit",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"storage: transaction commit error\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Transaction wraps the given function in a transaction. In case the given
// functions returns an error, the transaction will be rolled back.
|
[
"Transaction",
"wraps",
"the",
"given",
"function",
"in",
"a",
"transaction",
".",
"In",
"case",
"the",
"given",
"functions",
"returns",
"an",
"error",
"the",
"transaction",
"will",
"be",
"rolled",
"back",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/storage/storage.go#L93-L111
|
train
|
brocaar/loraserver
|
internal/downlink/join/join.go
|
Setup
|
func Setup(conf config.Config) error {
nsConfig := conf.NetworkServer.NetworkSettings
rxWindow = nsConfig.RXWindow
downlinkTXPower = nsConfig.DownlinkTXPower
return nil
}
|
go
|
func Setup(conf config.Config) error {
nsConfig := conf.NetworkServer.NetworkSettings
rxWindow = nsConfig.RXWindow
downlinkTXPower = nsConfig.DownlinkTXPower
return nil
}
|
[
"func",
"Setup",
"(",
"conf",
"config",
".",
"Config",
")",
"error",
"{",
"nsConfig",
":=",
"conf",
".",
"NetworkServer",
".",
"NetworkSettings",
"\n",
"rxWindow",
"=",
"nsConfig",
".",
"RXWindow",
"\n",
"downlinkTXPower",
"=",
"nsConfig",
".",
"DownlinkTXPower",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Setup sets up the join handler.
|
[
"Setup",
"sets",
"up",
"the",
"join",
"handler",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/join/join.go#L49-L55
|
train
|
brocaar/loraserver
|
internal/downlink/join/join.go
|
Handle
|
func Handle(ds storage.DeviceSession, rxPacket models.RXPacket, phy lorawan.PHYPayload) error {
ctx := joinContext{
DeviceSession: ds,
PHYPayload: phy,
RXPacket: rxPacket,
}
for _, t := range tasks {
if err := t(&ctx); err != nil {
return err
}
}
return nil
}
|
go
|
func Handle(ds storage.DeviceSession, rxPacket models.RXPacket, phy lorawan.PHYPayload) error {
ctx := joinContext{
DeviceSession: ds,
PHYPayload: phy,
RXPacket: rxPacket,
}
for _, t := range tasks {
if err := t(&ctx); err != nil {
return err
}
}
return nil
}
|
[
"func",
"Handle",
"(",
"ds",
"storage",
".",
"DeviceSession",
",",
"rxPacket",
"models",
".",
"RXPacket",
",",
"phy",
"lorawan",
".",
"PHYPayload",
")",
"error",
"{",
"ctx",
":=",
"joinContext",
"{",
"DeviceSession",
":",
"ds",
",",
"PHYPayload",
":",
"phy",
",",
"RXPacket",
":",
"rxPacket",
",",
"}",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"tasks",
"{",
"if",
"err",
":=",
"t",
"(",
"&",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Handle handles a downlink join-response.
|
[
"Handle",
"handles",
"a",
"downlink",
"join",
"-",
"response",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/downlink/join/join.go#L58-L72
|
train
|
brocaar/loraserver
|
internal/backend/gateway/marshaler/gateway_config.go
|
MarshalGatewayConfiguration
|
func MarshalGatewayConfiguration(t Type, gc gw.GatewayConfiguration) ([]byte, error) {
var b []byte
var err error
switch t {
case Protobuf:
b, err = proto.Marshal(&gc)
case JSON:
var str string
m := &jsonpb.Marshaler{
EmitDefaults: true,
}
str, err = m.MarshalToString(&gc)
b = []byte(str)
}
return b, err
}
|
go
|
func MarshalGatewayConfiguration(t Type, gc gw.GatewayConfiguration) ([]byte, error) {
var b []byte
var err error
switch t {
case Protobuf:
b, err = proto.Marshal(&gc)
case JSON:
var str string
m := &jsonpb.Marshaler{
EmitDefaults: true,
}
str, err = m.MarshalToString(&gc)
b = []byte(str)
}
return b, err
}
|
[
"func",
"MarshalGatewayConfiguration",
"(",
"t",
"Type",
",",
"gc",
"gw",
".",
"GatewayConfiguration",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"b",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n",
"switch",
"t",
"{",
"case",
"Protobuf",
":",
"b",
",",
"err",
"=",
"proto",
".",
"Marshal",
"(",
"&",
"gc",
")",
"\n",
"case",
"JSON",
":",
"var",
"str",
"string",
"\n",
"m",
":=",
"&",
"jsonpb",
".",
"Marshaler",
"{",
"EmitDefaults",
":",
"true",
",",
"}",
"\n",
"str",
",",
"err",
"=",
"m",
".",
"MarshalToString",
"(",
"&",
"gc",
")",
"\n",
"b",
"=",
"[",
"]",
"byte",
"(",
"str",
")",
"\n",
"}",
"\n",
"return",
"b",
",",
"err",
"\n",
"}"
] |
// MarshalGatewayConfiguration marshals the GatewayConfiguration.
|
[
"MarshalGatewayConfiguration",
"marshals",
"the",
"GatewayConfiguration",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/gateway/marshaler/gateway_config.go#L10-L27
|
train
|
brocaar/loraserver
|
internal/backend/gateway/mqtt/backend.go
|
SendTXPacket
|
func (b *Backend) SendTXPacket(txPacket gw.DownlinkFrame) error {
if txPacket.TxInfo == nil {
return errors.New("tx_info must not be nil")
}
gatewayID := helpers.GetGatewayID(txPacket.TxInfo)
return b.publishCommand(gatewayID, "down", &txPacket)
}
|
go
|
func (b *Backend) SendTXPacket(txPacket gw.DownlinkFrame) error {
if txPacket.TxInfo == nil {
return errors.New("tx_info must not be nil")
}
gatewayID := helpers.GetGatewayID(txPacket.TxInfo)
return b.publishCommand(gatewayID, "down", &txPacket)
}
|
[
"func",
"(",
"b",
"*",
"Backend",
")",
"SendTXPacket",
"(",
"txPacket",
"gw",
".",
"DownlinkFrame",
")",
"error",
"{",
"if",
"txPacket",
".",
"TxInfo",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"tx_info must not be nil\"",
")",
"\n",
"}",
"\n",
"gatewayID",
":=",
"helpers",
".",
"GetGatewayID",
"(",
"txPacket",
".",
"TxInfo",
")",
"\n",
"return",
"b",
".",
"publishCommand",
"(",
"gatewayID",
",",
"\"down\"",
",",
"&",
"txPacket",
")",
"\n",
"}"
] |
// SendTXPacket sends the given downlink-frame to the gateway.
|
[
"SendTXPacket",
"sends",
"the",
"given",
"downlink",
"-",
"frame",
"to",
"the",
"gateway",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/gateway/mqtt/backend.go#L149-L157
|
train
|
brocaar/loraserver
|
internal/backend/gateway/mqtt/backend.go
|
SendGatewayConfigPacket
|
func (b *Backend) SendGatewayConfigPacket(configPacket gw.GatewayConfiguration) error {
gatewayID := helpers.GetGatewayID(&configPacket)
return b.publishCommand(gatewayID, "config", &configPacket)
}
|
go
|
func (b *Backend) SendGatewayConfigPacket(configPacket gw.GatewayConfiguration) error {
gatewayID := helpers.GetGatewayID(&configPacket)
return b.publishCommand(gatewayID, "config", &configPacket)
}
|
[
"func",
"(",
"b",
"*",
"Backend",
")",
"SendGatewayConfigPacket",
"(",
"configPacket",
"gw",
".",
"GatewayConfiguration",
")",
"error",
"{",
"gatewayID",
":=",
"helpers",
".",
"GetGatewayID",
"(",
"&",
"configPacket",
")",
"\n",
"return",
"b",
".",
"publishCommand",
"(",
"gatewayID",
",",
"\"config\"",
",",
"&",
"configPacket",
")",
"\n",
"}"
] |
// SendGatewayConfigPacket sends the given GatewayConfigPacket to the gateway.
|
[
"SendGatewayConfigPacket",
"sends",
"the",
"given",
"GatewayConfigPacket",
"to",
"the",
"gateway",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/gateway/mqtt/backend.go#L160-L164
|
train
|
brocaar/loraserver
|
internal/helpers/helpers.go
|
SetDownlinkTXInfoDataRate
|
func SetDownlinkTXInfoDataRate(txInfo *gw.DownlinkTXInfo, dr int, b band.Band) error {
dataRate, err := b.GetDataRate(dr)
if err != nil {
return errors.Wrap(err, "get data-rate error")
}
switch dataRate.Modulation {
case band.LoRaModulation:
txInfo.Modulation = common.Modulation_LORA
txInfo.ModulationInfo = &gw.DownlinkTXInfo_LoraModulationInfo{
LoraModulationInfo: &gw.LoRaModulationInfo{
SpreadingFactor: uint32(dataRate.SpreadFactor),
Bandwidth: uint32(dataRate.Bandwidth),
CodeRate: defaultCodeRate,
PolarizationInversion: true,
},
}
case band.FSKModulation:
txInfo.Modulation = common.Modulation_FSK
txInfo.ModulationInfo = &gw.DownlinkTXInfo_FskModulationInfo{
FskModulationInfo: &gw.FSKModulationInfo{
Bitrate: uint32(dataRate.BitRate),
Bandwidth: uint32(dataRate.Bandwidth),
},
}
default:
return fmt.Errorf("unknown modulation: %s", dataRate.Modulation)
}
return nil
}
|
go
|
func SetDownlinkTXInfoDataRate(txInfo *gw.DownlinkTXInfo, dr int, b band.Band) error {
dataRate, err := b.GetDataRate(dr)
if err != nil {
return errors.Wrap(err, "get data-rate error")
}
switch dataRate.Modulation {
case band.LoRaModulation:
txInfo.Modulation = common.Modulation_LORA
txInfo.ModulationInfo = &gw.DownlinkTXInfo_LoraModulationInfo{
LoraModulationInfo: &gw.LoRaModulationInfo{
SpreadingFactor: uint32(dataRate.SpreadFactor),
Bandwidth: uint32(dataRate.Bandwidth),
CodeRate: defaultCodeRate,
PolarizationInversion: true,
},
}
case band.FSKModulation:
txInfo.Modulation = common.Modulation_FSK
txInfo.ModulationInfo = &gw.DownlinkTXInfo_FskModulationInfo{
FskModulationInfo: &gw.FSKModulationInfo{
Bitrate: uint32(dataRate.BitRate),
Bandwidth: uint32(dataRate.Bandwidth),
},
}
default:
return fmt.Errorf("unknown modulation: %s", dataRate.Modulation)
}
return nil
}
|
[
"func",
"SetDownlinkTXInfoDataRate",
"(",
"txInfo",
"*",
"gw",
".",
"DownlinkTXInfo",
",",
"dr",
"int",
",",
"b",
"band",
".",
"Band",
")",
"error",
"{",
"dataRate",
",",
"err",
":=",
"b",
".",
"GetDataRate",
"(",
"dr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"get data-rate error\"",
")",
"\n",
"}",
"\n",
"switch",
"dataRate",
".",
"Modulation",
"{",
"case",
"band",
".",
"LoRaModulation",
":",
"txInfo",
".",
"Modulation",
"=",
"common",
".",
"Modulation_LORA",
"\n",
"txInfo",
".",
"ModulationInfo",
"=",
"&",
"gw",
".",
"DownlinkTXInfo_LoraModulationInfo",
"{",
"LoraModulationInfo",
":",
"&",
"gw",
".",
"LoRaModulationInfo",
"{",
"SpreadingFactor",
":",
"uint32",
"(",
"dataRate",
".",
"SpreadFactor",
")",
",",
"Bandwidth",
":",
"uint32",
"(",
"dataRate",
".",
"Bandwidth",
")",
",",
"CodeRate",
":",
"defaultCodeRate",
",",
"PolarizationInversion",
":",
"true",
",",
"}",
",",
"}",
"\n",
"case",
"band",
".",
"FSKModulation",
":",
"txInfo",
".",
"Modulation",
"=",
"common",
".",
"Modulation_FSK",
"\n",
"txInfo",
".",
"ModulationInfo",
"=",
"&",
"gw",
".",
"DownlinkTXInfo_FskModulationInfo",
"{",
"FskModulationInfo",
":",
"&",
"gw",
".",
"FSKModulationInfo",
"{",
"Bitrate",
":",
"uint32",
"(",
"dataRate",
".",
"BitRate",
")",
",",
"Bandwidth",
":",
"uint32",
"(",
"dataRate",
".",
"Bandwidth",
")",
",",
"}",
",",
"}",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"unknown modulation: %s\"",
",",
"dataRate",
".",
"Modulation",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SetDownlinkTXInfoDataRate sets the DownlinkTXInfo data-rate.
|
[
"SetDownlinkTXInfoDataRate",
"sets",
"the",
"DownlinkTXInfo",
"data",
"-",
"rate",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/helpers/helpers.go#L29-L59
|
train
|
brocaar/loraserver
|
internal/helpers/helpers.go
|
GetGatewayID
|
func GetGatewayID(v GatewayIDGetter) lorawan.EUI64 {
var gatewayID lorawan.EUI64
copy(gatewayID[:], v.GetGatewayId())
return gatewayID
}
|
go
|
func GetGatewayID(v GatewayIDGetter) lorawan.EUI64 {
var gatewayID lorawan.EUI64
copy(gatewayID[:], v.GetGatewayId())
return gatewayID
}
|
[
"func",
"GetGatewayID",
"(",
"v",
"GatewayIDGetter",
")",
"lorawan",
".",
"EUI64",
"{",
"var",
"gatewayID",
"lorawan",
".",
"EUI64",
"\n",
"copy",
"(",
"gatewayID",
"[",
":",
"]",
",",
"v",
".",
"GetGatewayId",
"(",
")",
")",
"\n",
"return",
"gatewayID",
"\n",
"}"
] |
// GetGatewayID returns the typed gateway ID.
|
[
"GetGatewayID",
"returns",
"the",
"typed",
"gateway",
"ID",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/helpers/helpers.go#L95-L99
|
train
|
brocaar/loraserver
|
internal/helpers/helpers.go
|
GetDataRateIndex
|
func GetDataRateIndex(uplink bool, v DataRateGetter, b band.Band) (int, error) {
var dr band.DataRate
switch v.GetModulation() {
case common.Modulation_LORA:
modInfo := v.GetLoraModulationInfo()
if modInfo == nil {
return 0, errors.New("lora_modulation_info must not be nil")
}
dr.Modulation = band.LoRaModulation
dr.SpreadFactor = int(modInfo.SpreadingFactor)
dr.Bandwidth = int(modInfo.Bandwidth)
case common.Modulation_FSK:
modInfo := v.GetFskModulationInfo()
if modInfo == nil {
return 0, errors.New("fsk_modulation_info must not be nil")
}
dr.Modulation = band.FSKModulation
dr.Bandwidth = int(modInfo.Bandwidth)
dr.BitRate = int(modInfo.Bitrate)
default:
return 0, fmt.Errorf("unknown modulation: %s", v.GetModulation())
}
return b.GetDataRateIndex(uplink, dr)
}
|
go
|
func GetDataRateIndex(uplink bool, v DataRateGetter, b band.Band) (int, error) {
var dr band.DataRate
switch v.GetModulation() {
case common.Modulation_LORA:
modInfo := v.GetLoraModulationInfo()
if modInfo == nil {
return 0, errors.New("lora_modulation_info must not be nil")
}
dr.Modulation = band.LoRaModulation
dr.SpreadFactor = int(modInfo.SpreadingFactor)
dr.Bandwidth = int(modInfo.Bandwidth)
case common.Modulation_FSK:
modInfo := v.GetFskModulationInfo()
if modInfo == nil {
return 0, errors.New("fsk_modulation_info must not be nil")
}
dr.Modulation = band.FSKModulation
dr.Bandwidth = int(modInfo.Bandwidth)
dr.BitRate = int(modInfo.Bitrate)
default:
return 0, fmt.Errorf("unknown modulation: %s", v.GetModulation())
}
return b.GetDataRateIndex(uplink, dr)
}
|
[
"func",
"GetDataRateIndex",
"(",
"uplink",
"bool",
",",
"v",
"DataRateGetter",
",",
"b",
"band",
".",
"Band",
")",
"(",
"int",
",",
"error",
")",
"{",
"var",
"dr",
"band",
".",
"DataRate",
"\n",
"switch",
"v",
".",
"GetModulation",
"(",
")",
"{",
"case",
"common",
".",
"Modulation_LORA",
":",
"modInfo",
":=",
"v",
".",
"GetLoraModulationInfo",
"(",
")",
"\n",
"if",
"modInfo",
"==",
"nil",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"lora_modulation_info must not be nil\"",
")",
"\n",
"}",
"\n",
"dr",
".",
"Modulation",
"=",
"band",
".",
"LoRaModulation",
"\n",
"dr",
".",
"SpreadFactor",
"=",
"int",
"(",
"modInfo",
".",
"SpreadingFactor",
")",
"\n",
"dr",
".",
"Bandwidth",
"=",
"int",
"(",
"modInfo",
".",
"Bandwidth",
")",
"\n",
"case",
"common",
".",
"Modulation_FSK",
":",
"modInfo",
":=",
"v",
".",
"GetFskModulationInfo",
"(",
")",
"\n",
"if",
"modInfo",
"==",
"nil",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"fsk_modulation_info must not be nil\"",
")",
"\n",
"}",
"\n",
"dr",
".",
"Modulation",
"=",
"band",
".",
"FSKModulation",
"\n",
"dr",
".",
"Bandwidth",
"=",
"int",
"(",
"modInfo",
".",
"Bandwidth",
")",
"\n",
"dr",
".",
"BitRate",
"=",
"int",
"(",
"modInfo",
".",
"Bitrate",
")",
"\n",
"default",
":",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"unknown modulation: %s\"",
",",
"v",
".",
"GetModulation",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"b",
".",
"GetDataRateIndex",
"(",
"uplink",
",",
"dr",
")",
"\n",
"}"
] |
// GetDataRateIndex returns the data-rate index.
|
[
"GetDataRateIndex",
"returns",
"the",
"data",
"-",
"rate",
"index",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/helpers/helpers.go#L102-L127
|
train
|
brocaar/loraserver
|
internal/backend/gateway/gcppubsub/gcppubsub.go
|
Close
|
func (b *Backend) Close() error {
log.Info("gateway/gcp_pub_sub: closing backend")
b.cancel()
close(b.uplinkFrameChan)
close(b.gatewayStatsChan)
close(b.downlinkTXAckChan)
return b.client.Close()
}
|
go
|
func (b *Backend) Close() error {
log.Info("gateway/gcp_pub_sub: closing backend")
b.cancel()
close(b.uplinkFrameChan)
close(b.gatewayStatsChan)
close(b.downlinkTXAckChan)
return b.client.Close()
}
|
[
"func",
"(",
"b",
"*",
"Backend",
")",
"Close",
"(",
")",
"error",
"{",
"log",
".",
"Info",
"(",
"\"gateway/gcp_pub_sub: closing backend\"",
")",
"\n",
"b",
".",
"cancel",
"(",
")",
"\n",
"close",
"(",
"b",
".",
"uplinkFrameChan",
")",
"\n",
"close",
"(",
"b",
".",
"gatewayStatsChan",
")",
"\n",
"close",
"(",
"b",
".",
"downlinkTXAckChan",
")",
"\n",
"return",
"b",
".",
"client",
".",
"Close",
"(",
")",
"\n",
"}"
] |
// Close closes the backend.
|
[
"Close",
"closes",
"the",
"backend",
"."
] |
33ed6586ede637a540864142fcda0b7e3b90203d
|
https://github.com/brocaar/loraserver/blob/33ed6586ede637a540864142fcda0b7e3b90203d/internal/backend/gateway/gcppubsub/gcppubsub.go#L171-L178
|
train
|
hashicorp/memberlist
|
awareness.go
|
ApplyDelta
|
func (a *awareness) ApplyDelta(delta int) {
a.Lock()
initial := a.score
a.score += delta
if a.score < 0 {
a.score = 0
} else if a.score > (a.max - 1) {
a.score = (a.max - 1)
}
final := a.score
a.Unlock()
if initial != final {
metrics.SetGauge([]string{"memberlist", "health", "score"}, float32(final))
}
}
|
go
|
func (a *awareness) ApplyDelta(delta int) {
a.Lock()
initial := a.score
a.score += delta
if a.score < 0 {
a.score = 0
} else if a.score > (a.max - 1) {
a.score = (a.max - 1)
}
final := a.score
a.Unlock()
if initial != final {
metrics.SetGauge([]string{"memberlist", "health", "score"}, float32(final))
}
}
|
[
"func",
"(",
"a",
"*",
"awareness",
")",
"ApplyDelta",
"(",
"delta",
"int",
")",
"{",
"a",
".",
"Lock",
"(",
")",
"\n",
"initial",
":=",
"a",
".",
"score",
"\n",
"a",
".",
"score",
"+=",
"delta",
"\n",
"if",
"a",
".",
"score",
"<",
"0",
"{",
"a",
".",
"score",
"=",
"0",
"\n",
"}",
"else",
"if",
"a",
".",
"score",
">",
"(",
"a",
".",
"max",
"-",
"1",
")",
"{",
"a",
".",
"score",
"=",
"(",
"a",
".",
"max",
"-",
"1",
")",
"\n",
"}",
"\n",
"final",
":=",
"a",
".",
"score",
"\n",
"a",
".",
"Unlock",
"(",
")",
"\n",
"if",
"initial",
"!=",
"final",
"{",
"metrics",
".",
"SetGauge",
"(",
"[",
"]",
"string",
"{",
"\"memberlist\"",
",",
"\"health\"",
",",
"\"score\"",
"}",
",",
"float32",
"(",
"final",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// ApplyDelta takes the given delta and applies it to the score in a thread-safe
// manner. It also enforces a floor of zero and a max of max, so deltas may not
// change the overall score if it's railed at one of the extremes.
|
[
"ApplyDelta",
"takes",
"the",
"given",
"delta",
"and",
"applies",
"it",
"to",
"the",
"score",
"in",
"a",
"thread",
"-",
"safe",
"manner",
".",
"It",
"also",
"enforces",
"a",
"floor",
"of",
"zero",
"and",
"a",
"max",
"of",
"max",
"so",
"deltas",
"may",
"not",
"change",
"the",
"overall",
"score",
"if",
"it",
"s",
"railed",
"at",
"one",
"of",
"the",
"extremes",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/awareness.go#L37-L52
|
train
|
hashicorp/memberlist
|
awareness.go
|
GetHealthScore
|
func (a *awareness) GetHealthScore() int {
a.RLock()
score := a.score
a.RUnlock()
return score
}
|
go
|
func (a *awareness) GetHealthScore() int {
a.RLock()
score := a.score
a.RUnlock()
return score
}
|
[
"func",
"(",
"a",
"*",
"awareness",
")",
"GetHealthScore",
"(",
")",
"int",
"{",
"a",
".",
"RLock",
"(",
")",
"\n",
"score",
":=",
"a",
".",
"score",
"\n",
"a",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"score",
"\n",
"}"
] |
// GetHealthScore returns the raw health score.
|
[
"GetHealthScore",
"returns",
"the",
"raw",
"health",
"score",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/awareness.go#L55-L60
|
train
|
hashicorp/memberlist
|
awareness.go
|
ScaleTimeout
|
func (a *awareness) ScaleTimeout(timeout time.Duration) time.Duration {
a.RLock()
score := a.score
a.RUnlock()
return timeout * (time.Duration(score) + 1)
}
|
go
|
func (a *awareness) ScaleTimeout(timeout time.Duration) time.Duration {
a.RLock()
score := a.score
a.RUnlock()
return timeout * (time.Duration(score) + 1)
}
|
[
"func",
"(",
"a",
"*",
"awareness",
")",
"ScaleTimeout",
"(",
"timeout",
"time",
".",
"Duration",
")",
"time",
".",
"Duration",
"{",
"a",
".",
"RLock",
"(",
")",
"\n",
"score",
":=",
"a",
".",
"score",
"\n",
"a",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"timeout",
"*",
"(",
"time",
".",
"Duration",
"(",
"score",
")",
"+",
"1",
")",
"\n",
"}"
] |
// ScaleTimeout takes the given duration and scales it based on the current
// score. Less healthyness will lead to longer timeouts.
|
[
"ScaleTimeout",
"takes",
"the",
"given",
"duration",
"and",
"scales",
"it",
"based",
"on",
"the",
"current",
"score",
".",
"Less",
"healthyness",
"will",
"lead",
"to",
"longer",
"timeouts",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/awareness.go#L64-L69
|
train
|
hashicorp/memberlist
|
keyring.go
|
ValidateKey
|
func ValidateKey(key []byte) error {
if l := len(key); l != 16 && l != 24 && l != 32 {
return fmt.Errorf("key size must be 16, 24 or 32 bytes")
}
return nil
}
|
go
|
func ValidateKey(key []byte) error {
if l := len(key); l != 16 && l != 24 && l != 32 {
return fmt.Errorf("key size must be 16, 24 or 32 bytes")
}
return nil
}
|
[
"func",
"ValidateKey",
"(",
"key",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"l",
":=",
"len",
"(",
"key",
")",
";",
"l",
"!=",
"16",
"&&",
"l",
"!=",
"24",
"&&",
"l",
"!=",
"32",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"key size must be 16, 24 or 32 bytes\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ValidateKey will check to see if the key is valid and returns an error if not.
//
// key should be either 16, 24, or 32 bytes to select AES-128,
// AES-192, or AES-256.
|
[
"ValidateKey",
"will",
"check",
"to",
"see",
"if",
"the",
"key",
"is",
"valid",
"and",
"returns",
"an",
"error",
"if",
"not",
".",
"key",
"should",
"be",
"either",
"16",
"24",
"or",
"32",
"bytes",
"to",
"select",
"AES",
"-",
"128",
"AES",
"-",
"192",
"or",
"AES",
"-",
"256",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/keyring.go#L65-L70
|
train
|
hashicorp/memberlist
|
keyring.go
|
AddKey
|
func (k *Keyring) AddKey(key []byte) error {
if err := ValidateKey(key); err != nil {
return err
}
// No-op if key is already installed
for _, installedKey := range k.keys {
if bytes.Equal(installedKey, key) {
return nil
}
}
keys := append(k.keys, key)
primaryKey := k.GetPrimaryKey()
if primaryKey == nil {
primaryKey = key
}
k.installKeys(keys, primaryKey)
return nil
}
|
go
|
func (k *Keyring) AddKey(key []byte) error {
if err := ValidateKey(key); err != nil {
return err
}
// No-op if key is already installed
for _, installedKey := range k.keys {
if bytes.Equal(installedKey, key) {
return nil
}
}
keys := append(k.keys, key)
primaryKey := k.GetPrimaryKey()
if primaryKey == nil {
primaryKey = key
}
k.installKeys(keys, primaryKey)
return nil
}
|
[
"func",
"(",
"k",
"*",
"Keyring",
")",
"AddKey",
"(",
"key",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"err",
":=",
"ValidateKey",
"(",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"installedKey",
":=",
"range",
"k",
".",
"keys",
"{",
"if",
"bytes",
".",
"Equal",
"(",
"installedKey",
",",
"key",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"keys",
":=",
"append",
"(",
"k",
".",
"keys",
",",
"key",
")",
"\n",
"primaryKey",
":=",
"k",
".",
"GetPrimaryKey",
"(",
")",
"\n",
"if",
"primaryKey",
"==",
"nil",
"{",
"primaryKey",
"=",
"key",
"\n",
"}",
"\n",
"k",
".",
"installKeys",
"(",
"keys",
",",
"primaryKey",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// AddKey will install a new key on the ring. Adding a key to the ring will make
// it available for use in decryption. If the key already exists on the ring,
// this function will just return noop.
//
// key should be either 16, 24, or 32 bytes to select AES-128,
// AES-192, or AES-256.
|
[
"AddKey",
"will",
"install",
"a",
"new",
"key",
"on",
"the",
"ring",
".",
"Adding",
"a",
"key",
"to",
"the",
"ring",
"will",
"make",
"it",
"available",
"for",
"use",
"in",
"decryption",
".",
"If",
"the",
"key",
"already",
"exists",
"on",
"the",
"ring",
"this",
"function",
"will",
"just",
"return",
"noop",
".",
"key",
"should",
"be",
"either",
"16",
"24",
"or",
"32",
"bytes",
"to",
"select",
"AES",
"-",
"128",
"AES",
"-",
"192",
"or",
"AES",
"-",
"256",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/keyring.go#L78-L97
|
train
|
hashicorp/memberlist
|
keyring.go
|
UseKey
|
func (k *Keyring) UseKey(key []byte) error {
for _, installedKey := range k.keys {
if bytes.Equal(key, installedKey) {
k.installKeys(k.keys, key)
return nil
}
}
return fmt.Errorf("Requested key is not in the keyring")
}
|
go
|
func (k *Keyring) UseKey(key []byte) error {
for _, installedKey := range k.keys {
if bytes.Equal(key, installedKey) {
k.installKeys(k.keys, key)
return nil
}
}
return fmt.Errorf("Requested key is not in the keyring")
}
|
[
"func",
"(",
"k",
"*",
"Keyring",
")",
"UseKey",
"(",
"key",
"[",
"]",
"byte",
")",
"error",
"{",
"for",
"_",
",",
"installedKey",
":=",
"range",
"k",
".",
"keys",
"{",
"if",
"bytes",
".",
"Equal",
"(",
"key",
",",
"installedKey",
")",
"{",
"k",
".",
"installKeys",
"(",
"k",
".",
"keys",
",",
"key",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Requested key is not in the keyring\"",
")",
"\n",
"}"
] |
// UseKey changes the key used to encrypt messages. This is the only key used to
// encrypt messages, so peers should know this key before this method is called.
|
[
"UseKey",
"changes",
"the",
"key",
"used",
"to",
"encrypt",
"messages",
".",
"This",
"is",
"the",
"only",
"key",
"used",
"to",
"encrypt",
"messages",
"so",
"peers",
"should",
"know",
"this",
"key",
"before",
"this",
"method",
"is",
"called",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/keyring.go#L101-L109
|
train
|
hashicorp/memberlist
|
keyring.go
|
installKeys
|
func (k *Keyring) installKeys(keys [][]byte, primaryKey []byte) {
k.l.Lock()
defer k.l.Unlock()
newKeys := [][]byte{primaryKey}
for _, key := range keys {
if !bytes.Equal(key, primaryKey) {
newKeys = append(newKeys, key)
}
}
k.keys = newKeys
}
|
go
|
func (k *Keyring) installKeys(keys [][]byte, primaryKey []byte) {
k.l.Lock()
defer k.l.Unlock()
newKeys := [][]byte{primaryKey}
for _, key := range keys {
if !bytes.Equal(key, primaryKey) {
newKeys = append(newKeys, key)
}
}
k.keys = newKeys
}
|
[
"func",
"(",
"k",
"*",
"Keyring",
")",
"installKeys",
"(",
"keys",
"[",
"]",
"[",
"]",
"byte",
",",
"primaryKey",
"[",
"]",
"byte",
")",
"{",
"k",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"k",
".",
"l",
".",
"Unlock",
"(",
")",
"\n",
"newKeys",
":=",
"[",
"]",
"[",
"]",
"byte",
"{",
"primaryKey",
"}",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"{",
"if",
"!",
"bytes",
".",
"Equal",
"(",
"key",
",",
"primaryKey",
")",
"{",
"newKeys",
"=",
"append",
"(",
"newKeys",
",",
"key",
")",
"\n",
"}",
"\n",
"}",
"\n",
"k",
".",
"keys",
"=",
"newKeys",
"\n",
"}"
] |
// installKeys will take out a lock on the keyring, and replace the keys with a
// new set of keys. The key indicated by primaryKey will be installed as the new
// primary key.
|
[
"installKeys",
"will",
"take",
"out",
"a",
"lock",
"on",
"the",
"keyring",
"and",
"replace",
"the",
"keys",
"with",
"a",
"new",
"set",
"of",
"keys",
".",
"The",
"key",
"indicated",
"by",
"primaryKey",
"will",
"be",
"installed",
"as",
"the",
"new",
"primary",
"key",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/keyring.go#L129-L140
|
train
|
hashicorp/memberlist
|
keyring.go
|
GetKeys
|
func (k *Keyring) GetKeys() [][]byte {
k.l.Lock()
defer k.l.Unlock()
return k.keys
}
|
go
|
func (k *Keyring) GetKeys() [][]byte {
k.l.Lock()
defer k.l.Unlock()
return k.keys
}
|
[
"func",
"(",
"k",
"*",
"Keyring",
")",
"GetKeys",
"(",
")",
"[",
"]",
"[",
"]",
"byte",
"{",
"k",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"k",
".",
"l",
".",
"Unlock",
"(",
")",
"\n",
"return",
"k",
".",
"keys",
"\n",
"}"
] |
// GetKeys returns the current set of keys on the ring.
|
[
"GetKeys",
"returns",
"the",
"current",
"set",
"of",
"keys",
"on",
"the",
"ring",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/keyring.go#L143-L148
|
train
|
hashicorp/memberlist
|
keyring.go
|
GetPrimaryKey
|
func (k *Keyring) GetPrimaryKey() (key []byte) {
k.l.Lock()
defer k.l.Unlock()
if len(k.keys) > 0 {
key = k.keys[0]
}
return
}
|
go
|
func (k *Keyring) GetPrimaryKey() (key []byte) {
k.l.Lock()
defer k.l.Unlock()
if len(k.keys) > 0 {
key = k.keys[0]
}
return
}
|
[
"func",
"(",
"k",
"*",
"Keyring",
")",
"GetPrimaryKey",
"(",
")",
"(",
"key",
"[",
"]",
"byte",
")",
"{",
"k",
".",
"l",
".",
"Lock",
"(",
")",
"\n",
"defer",
"k",
".",
"l",
".",
"Unlock",
"(",
")",
"\n",
"if",
"len",
"(",
"k",
".",
"keys",
")",
">",
"0",
"{",
"key",
"=",
"k",
".",
"keys",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// GetPrimaryKey returns the key on the ring at position 0. This is the key used
// for encrypting messages, and is the first key tried for decrypting messages.
|
[
"GetPrimaryKey",
"returns",
"the",
"key",
"on",
"the",
"ring",
"at",
"position",
"0",
".",
"This",
"is",
"the",
"key",
"used",
"for",
"encrypting",
"messages",
"and",
"is",
"the",
"first",
"key",
"tried",
"for",
"decrypting",
"messages",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/keyring.go#L152-L160
|
train
|
hashicorp/memberlist
|
util.go
|
decode
|
func decode(buf []byte, out interface{}) error {
r := bytes.NewReader(buf)
hd := codec.MsgpackHandle{}
dec := codec.NewDecoder(r, &hd)
return dec.Decode(out)
}
|
go
|
func decode(buf []byte, out interface{}) error {
r := bytes.NewReader(buf)
hd := codec.MsgpackHandle{}
dec := codec.NewDecoder(r, &hd)
return dec.Decode(out)
}
|
[
"func",
"decode",
"(",
"buf",
"[",
"]",
"byte",
",",
"out",
"interface",
"{",
"}",
")",
"error",
"{",
"r",
":=",
"bytes",
".",
"NewReader",
"(",
"buf",
")",
"\n",
"hd",
":=",
"codec",
".",
"MsgpackHandle",
"{",
"}",
"\n",
"dec",
":=",
"codec",
".",
"NewDecoder",
"(",
"r",
",",
"&",
"hd",
")",
"\n",
"return",
"dec",
".",
"Decode",
"(",
"out",
")",
"\n",
"}"
] |
// Decode reverses the encode operation on a byte slice input
|
[
"Decode",
"reverses",
"the",
"encode",
"operation",
"on",
"a",
"byte",
"slice",
"input"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/util.go#L37-L42
|
train
|
hashicorp/memberlist
|
util.go
|
encode
|
func encode(msgType messageType, in interface{}) (*bytes.Buffer, error) {
buf := bytes.NewBuffer(nil)
buf.WriteByte(uint8(msgType))
hd := codec.MsgpackHandle{}
enc := codec.NewEncoder(buf, &hd)
err := enc.Encode(in)
return buf, err
}
|
go
|
func encode(msgType messageType, in interface{}) (*bytes.Buffer, error) {
buf := bytes.NewBuffer(nil)
buf.WriteByte(uint8(msgType))
hd := codec.MsgpackHandle{}
enc := codec.NewEncoder(buf, &hd)
err := enc.Encode(in)
return buf, err
}
|
[
"func",
"encode",
"(",
"msgType",
"messageType",
",",
"in",
"interface",
"{",
"}",
")",
"(",
"*",
"bytes",
".",
"Buffer",
",",
"error",
")",
"{",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n",
"buf",
".",
"WriteByte",
"(",
"uint8",
"(",
"msgType",
")",
")",
"\n",
"hd",
":=",
"codec",
".",
"MsgpackHandle",
"{",
"}",
"\n",
"enc",
":=",
"codec",
".",
"NewEncoder",
"(",
"buf",
",",
"&",
"hd",
")",
"\n",
"err",
":=",
"enc",
".",
"Encode",
"(",
"in",
")",
"\n",
"return",
"buf",
",",
"err",
"\n",
"}"
] |
// Encode writes an encoded object to a new bytes buffer
|
[
"Encode",
"writes",
"an",
"encoded",
"object",
"to",
"a",
"new",
"bytes",
"buffer"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/util.go#L45-L52
|
train
|
hashicorp/memberlist
|
util.go
|
suspicionTimeout
|
func suspicionTimeout(suspicionMult, n int, interval time.Duration) time.Duration {
nodeScale := math.Max(1.0, math.Log10(math.Max(1.0, float64(n))))
// multiply by 1000 to keep some precision because time.Duration is an int64 type
timeout := time.Duration(suspicionMult) * time.Duration(nodeScale*1000) * interval / 1000
return timeout
}
|
go
|
func suspicionTimeout(suspicionMult, n int, interval time.Duration) time.Duration {
nodeScale := math.Max(1.0, math.Log10(math.Max(1.0, float64(n))))
// multiply by 1000 to keep some precision because time.Duration is an int64 type
timeout := time.Duration(suspicionMult) * time.Duration(nodeScale*1000) * interval / 1000
return timeout
}
|
[
"func",
"suspicionTimeout",
"(",
"suspicionMult",
",",
"n",
"int",
",",
"interval",
"time",
".",
"Duration",
")",
"time",
".",
"Duration",
"{",
"nodeScale",
":=",
"math",
".",
"Max",
"(",
"1.0",
",",
"math",
".",
"Log10",
"(",
"math",
".",
"Max",
"(",
"1.0",
",",
"float64",
"(",
"n",
")",
")",
")",
")",
"\n",
"timeout",
":=",
"time",
".",
"Duration",
"(",
"suspicionMult",
")",
"*",
"time",
".",
"Duration",
"(",
"nodeScale",
"*",
"1000",
")",
"*",
"interval",
"/",
"1000",
"\n",
"return",
"timeout",
"\n",
"}"
] |
// suspicionTimeout computes the timeout that should be used when
// a node is suspected
|
[
"suspicionTimeout",
"computes",
"the",
"timeout",
"that",
"should",
"be",
"used",
"when",
"a",
"node",
"is",
"suspected"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/util.go#L64-L69
|
train
|
hashicorp/memberlist
|
util.go
|
retransmitLimit
|
func retransmitLimit(retransmitMult, n int) int {
nodeScale := math.Ceil(math.Log10(float64(n + 1)))
limit := retransmitMult * int(nodeScale)
return limit
}
|
go
|
func retransmitLimit(retransmitMult, n int) int {
nodeScale := math.Ceil(math.Log10(float64(n + 1)))
limit := retransmitMult * int(nodeScale)
return limit
}
|
[
"func",
"retransmitLimit",
"(",
"retransmitMult",
",",
"n",
"int",
")",
"int",
"{",
"nodeScale",
":=",
"math",
".",
"Ceil",
"(",
"math",
".",
"Log10",
"(",
"float64",
"(",
"n",
"+",
"1",
")",
")",
")",
"\n",
"limit",
":=",
"retransmitMult",
"*",
"int",
"(",
"nodeScale",
")",
"\n",
"return",
"limit",
"\n",
"}"
] |
// retransmitLimit computes the limit of retransmissions
|
[
"retransmitLimit",
"computes",
"the",
"limit",
"of",
"retransmissions"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/util.go#L72-L76
|
train
|
hashicorp/memberlist
|
util.go
|
shuffleNodes
|
func shuffleNodes(nodes []*nodeState) {
n := len(nodes)
rand.Shuffle(n, func(i, j int) {
nodes[i], nodes[j] = nodes[j], nodes[i]
})
}
|
go
|
func shuffleNodes(nodes []*nodeState) {
n := len(nodes)
rand.Shuffle(n, func(i, j int) {
nodes[i], nodes[j] = nodes[j], nodes[i]
})
}
|
[
"func",
"shuffleNodes",
"(",
"nodes",
"[",
"]",
"*",
"nodeState",
")",
"{",
"n",
":=",
"len",
"(",
"nodes",
")",
"\n",
"rand",
".",
"Shuffle",
"(",
"n",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"{",
"nodes",
"[",
"i",
"]",
",",
"nodes",
"[",
"j",
"]",
"=",
"nodes",
"[",
"j",
"]",
",",
"nodes",
"[",
"i",
"]",
"\n",
"}",
")",
"\n",
"}"
] |
// shuffleNodes randomly shuffles the input nodes using the Fisher-Yates shuffle
|
[
"shuffleNodes",
"randomly",
"shuffles",
"the",
"input",
"nodes",
"using",
"the",
"Fisher",
"-",
"Yates",
"shuffle"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/util.go#L79-L84
|
train
|
hashicorp/memberlist
|
util.go
|
moveDeadNodes
|
func moveDeadNodes(nodes []*nodeState, gossipToTheDeadTime time.Duration) int {
numDead := 0
n := len(nodes)
for i := 0; i < n-numDead; i++ {
if nodes[i].State != stateDead {
continue
}
// Respect the gossip to the dead interval
if time.Since(nodes[i].StateChange) <= gossipToTheDeadTime {
continue
}
// Move this node to the end
nodes[i], nodes[n-numDead-1] = nodes[n-numDead-1], nodes[i]
numDead++
i--
}
return n - numDead
}
|
go
|
func moveDeadNodes(nodes []*nodeState, gossipToTheDeadTime time.Duration) int {
numDead := 0
n := len(nodes)
for i := 0; i < n-numDead; i++ {
if nodes[i].State != stateDead {
continue
}
// Respect the gossip to the dead interval
if time.Since(nodes[i].StateChange) <= gossipToTheDeadTime {
continue
}
// Move this node to the end
nodes[i], nodes[n-numDead-1] = nodes[n-numDead-1], nodes[i]
numDead++
i--
}
return n - numDead
}
|
[
"func",
"moveDeadNodes",
"(",
"nodes",
"[",
"]",
"*",
"nodeState",
",",
"gossipToTheDeadTime",
"time",
".",
"Duration",
")",
"int",
"{",
"numDead",
":=",
"0",
"\n",
"n",
":=",
"len",
"(",
"nodes",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
"-",
"numDead",
";",
"i",
"++",
"{",
"if",
"nodes",
"[",
"i",
"]",
".",
"State",
"!=",
"stateDead",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"time",
".",
"Since",
"(",
"nodes",
"[",
"i",
"]",
".",
"StateChange",
")",
"<=",
"gossipToTheDeadTime",
"{",
"continue",
"\n",
"}",
"\n",
"nodes",
"[",
"i",
"]",
",",
"nodes",
"[",
"n",
"-",
"numDead",
"-",
"1",
"]",
"=",
"nodes",
"[",
"n",
"-",
"numDead",
"-",
"1",
"]",
",",
"nodes",
"[",
"i",
"]",
"\n",
"numDead",
"++",
"\n",
"i",
"--",
"\n",
"}",
"\n",
"return",
"n",
"-",
"numDead",
"\n",
"}"
] |
// moveDeadNodes moves nodes that are dead and beyond the gossip to the dead interval
// to the end of the slice and returns the index of the first moved node.
|
[
"moveDeadNodes",
"moves",
"nodes",
"that",
"are",
"dead",
"and",
"beyond",
"the",
"gossip",
"to",
"the",
"dead",
"interval",
"to",
"the",
"end",
"of",
"the",
"slice",
"and",
"returns",
"the",
"index",
"of",
"the",
"first",
"moved",
"node",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/util.go#L101-L120
|
train
|
hashicorp/memberlist
|
util.go
|
kRandomNodes
|
func kRandomNodes(k int, nodes []*nodeState, filterFn func(*nodeState) bool) []*nodeState {
n := len(nodes)
kNodes := make([]*nodeState, 0, k)
OUTER:
// Probe up to 3*n times, with large n this is not necessary
// since k << n, but with small n we want search to be
// exhaustive
for i := 0; i < 3*n && len(kNodes) < k; i++ {
// Get random node
idx := randomOffset(n)
node := nodes[idx]
// Give the filter a shot at it.
if filterFn != nil && filterFn(node) {
continue OUTER
}
// Check if we have this node already
for j := 0; j < len(kNodes); j++ {
if node == kNodes[j] {
continue OUTER
}
}
// Append the node
kNodes = append(kNodes, node)
}
return kNodes
}
|
go
|
func kRandomNodes(k int, nodes []*nodeState, filterFn func(*nodeState) bool) []*nodeState {
n := len(nodes)
kNodes := make([]*nodeState, 0, k)
OUTER:
// Probe up to 3*n times, with large n this is not necessary
// since k << n, but with small n we want search to be
// exhaustive
for i := 0; i < 3*n && len(kNodes) < k; i++ {
// Get random node
idx := randomOffset(n)
node := nodes[idx]
// Give the filter a shot at it.
if filterFn != nil && filterFn(node) {
continue OUTER
}
// Check if we have this node already
for j := 0; j < len(kNodes); j++ {
if node == kNodes[j] {
continue OUTER
}
}
// Append the node
kNodes = append(kNodes, node)
}
return kNodes
}
|
[
"func",
"kRandomNodes",
"(",
"k",
"int",
",",
"nodes",
"[",
"]",
"*",
"nodeState",
",",
"filterFn",
"func",
"(",
"*",
"nodeState",
")",
"bool",
")",
"[",
"]",
"*",
"nodeState",
"{",
"n",
":=",
"len",
"(",
"nodes",
")",
"\n",
"kNodes",
":=",
"make",
"(",
"[",
"]",
"*",
"nodeState",
",",
"0",
",",
"k",
")",
"\n",
"OUTER",
":",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"3",
"*",
"n",
"&&",
"len",
"(",
"kNodes",
")",
"<",
"k",
";",
"i",
"++",
"{",
"idx",
":=",
"randomOffset",
"(",
"n",
")",
"\n",
"node",
":=",
"nodes",
"[",
"idx",
"]",
"\n",
"if",
"filterFn",
"!=",
"nil",
"&&",
"filterFn",
"(",
"node",
")",
"{",
"continue",
"OUTER",
"\n",
"}",
"\n",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"len",
"(",
"kNodes",
")",
";",
"j",
"++",
"{",
"if",
"node",
"==",
"kNodes",
"[",
"j",
"]",
"{",
"continue",
"OUTER",
"\n",
"}",
"\n",
"}",
"\n",
"kNodes",
"=",
"append",
"(",
"kNodes",
",",
"node",
")",
"\n",
"}",
"\n",
"return",
"kNodes",
"\n",
"}"
] |
// kRandomNodes is used to select up to k random nodes, excluding any nodes where
// the filter function returns true. It is possible that less than k nodes are
// returned.
|
[
"kRandomNodes",
"is",
"used",
"to",
"select",
"up",
"to",
"k",
"random",
"nodes",
"excluding",
"any",
"nodes",
"where",
"the",
"filter",
"function",
"returns",
"true",
".",
"It",
"is",
"possible",
"that",
"less",
"than",
"k",
"nodes",
"are",
"returned",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/util.go#L125-L153
|
train
|
hashicorp/memberlist
|
util.go
|
decodeCompoundMessage
|
func decodeCompoundMessage(buf []byte) (trunc int, parts [][]byte, err error) {
if len(buf) < 1 {
err = fmt.Errorf("missing compound length byte")
return
}
numParts := uint8(buf[0])
buf = buf[1:]
// Check we have enough bytes
if len(buf) < int(numParts*2) {
err = fmt.Errorf("truncated len slice")
return
}
// Decode the lengths
lengths := make([]uint16, numParts)
for i := 0; i < int(numParts); i++ {
lengths[i] = binary.BigEndian.Uint16(buf[i*2 : i*2+2])
}
buf = buf[numParts*2:]
// Split each message
for idx, msgLen := range lengths {
if len(buf) < int(msgLen) {
trunc = int(numParts) - idx
return
}
// Extract the slice, seek past on the buffer
slice := buf[:msgLen]
buf = buf[msgLen:]
parts = append(parts, slice)
}
return
}
|
go
|
func decodeCompoundMessage(buf []byte) (trunc int, parts [][]byte, err error) {
if len(buf) < 1 {
err = fmt.Errorf("missing compound length byte")
return
}
numParts := uint8(buf[0])
buf = buf[1:]
// Check we have enough bytes
if len(buf) < int(numParts*2) {
err = fmt.Errorf("truncated len slice")
return
}
// Decode the lengths
lengths := make([]uint16, numParts)
for i := 0; i < int(numParts); i++ {
lengths[i] = binary.BigEndian.Uint16(buf[i*2 : i*2+2])
}
buf = buf[numParts*2:]
// Split each message
for idx, msgLen := range lengths {
if len(buf) < int(msgLen) {
trunc = int(numParts) - idx
return
}
// Extract the slice, seek past on the buffer
slice := buf[:msgLen]
buf = buf[msgLen:]
parts = append(parts, slice)
}
return
}
|
[
"func",
"decodeCompoundMessage",
"(",
"buf",
"[",
"]",
"byte",
")",
"(",
"trunc",
"int",
",",
"parts",
"[",
"]",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"buf",
")",
"<",
"1",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"missing compound length byte\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"numParts",
":=",
"uint8",
"(",
"buf",
"[",
"0",
"]",
")",
"\n",
"buf",
"=",
"buf",
"[",
"1",
":",
"]",
"\n",
"if",
"len",
"(",
"buf",
")",
"<",
"int",
"(",
"numParts",
"*",
"2",
")",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"truncated len slice\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"lengths",
":=",
"make",
"(",
"[",
"]",
"uint16",
",",
"numParts",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"int",
"(",
"numParts",
")",
";",
"i",
"++",
"{",
"lengths",
"[",
"i",
"]",
"=",
"binary",
".",
"BigEndian",
".",
"Uint16",
"(",
"buf",
"[",
"i",
"*",
"2",
":",
"i",
"*",
"2",
"+",
"2",
"]",
")",
"\n",
"}",
"\n",
"buf",
"=",
"buf",
"[",
"numParts",
"*",
"2",
":",
"]",
"\n",
"for",
"idx",
",",
"msgLen",
":=",
"range",
"lengths",
"{",
"if",
"len",
"(",
"buf",
")",
"<",
"int",
"(",
"msgLen",
")",
"{",
"trunc",
"=",
"int",
"(",
"numParts",
")",
"-",
"idx",
"\n",
"return",
"\n",
"}",
"\n",
"slice",
":=",
"buf",
"[",
":",
"msgLen",
"]",
"\n",
"buf",
"=",
"buf",
"[",
"msgLen",
":",
"]",
"\n",
"parts",
"=",
"append",
"(",
"parts",
",",
"slice",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// decodeCompoundMessage splits a compound message and returns
// the slices of individual messages. Also returns the number
// of truncated messages and any potential error
|
[
"decodeCompoundMessage",
"splits",
"a",
"compound",
"message",
"and",
"returns",
"the",
"slices",
"of",
"individual",
"messages",
".",
"Also",
"returns",
"the",
"number",
"of",
"truncated",
"messages",
"and",
"any",
"potential",
"error"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/util.go#L183-L217
|
train
|
hashicorp/memberlist
|
util.go
|
decompressBuffer
|
func decompressBuffer(c *compress) ([]byte, error) {
// Verify the algorithm
if c.Algo != lzwAlgo {
return nil, fmt.Errorf("Cannot decompress unknown algorithm %d", c.Algo)
}
// Create a uncompressor
uncomp := lzw.NewReader(bytes.NewReader(c.Buf), lzw.LSB, lzwLitWidth)
defer uncomp.Close()
// Read all the data
var b bytes.Buffer
_, err := io.Copy(&b, uncomp)
if err != nil {
return nil, err
}
// Return the uncompressed bytes
return b.Bytes(), nil
}
|
go
|
func decompressBuffer(c *compress) ([]byte, error) {
// Verify the algorithm
if c.Algo != lzwAlgo {
return nil, fmt.Errorf("Cannot decompress unknown algorithm %d", c.Algo)
}
// Create a uncompressor
uncomp := lzw.NewReader(bytes.NewReader(c.Buf), lzw.LSB, lzwLitWidth)
defer uncomp.Close()
// Read all the data
var b bytes.Buffer
_, err := io.Copy(&b, uncomp)
if err != nil {
return nil, err
}
// Return the uncompressed bytes
return b.Bytes(), nil
}
|
[
"func",
"decompressBuffer",
"(",
"c",
"*",
"compress",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"c",
".",
"Algo",
"!=",
"lzwAlgo",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Cannot decompress unknown algorithm %d\"",
",",
"c",
".",
"Algo",
")",
"\n",
"}",
"\n",
"uncomp",
":=",
"lzw",
".",
"NewReader",
"(",
"bytes",
".",
"NewReader",
"(",
"c",
".",
"Buf",
")",
",",
"lzw",
".",
"LSB",
",",
"lzwLitWidth",
")",
"\n",
"defer",
"uncomp",
".",
"Close",
"(",
")",
"\n",
"var",
"b",
"bytes",
".",
"Buffer",
"\n",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"&",
"b",
",",
"uncomp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"b",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] |
// decompressBuffer is used to decompress the buffer of
// a single compress message, handling multiple algorithms
|
[
"decompressBuffer",
"is",
"used",
"to",
"decompress",
"the",
"buffer",
"of",
"a",
"single",
"compress",
"message",
"handling",
"multiple",
"algorithms"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/util.go#L256-L275
|
train
|
hashicorp/memberlist
|
util.go
|
ensurePort
|
func ensurePort(s string, port int) string {
if hasPort(s) {
return s
}
// If this is an IPv6 address, the join call will add another set of
// brackets, so we have to trim before we add the default port.
s = strings.Trim(s, "[]")
s = net.JoinHostPort(s, strconv.Itoa(port))
return s
}
|
go
|
func ensurePort(s string, port int) string {
if hasPort(s) {
return s
}
// If this is an IPv6 address, the join call will add another set of
// brackets, so we have to trim before we add the default port.
s = strings.Trim(s, "[]")
s = net.JoinHostPort(s, strconv.Itoa(port))
return s
}
|
[
"func",
"ensurePort",
"(",
"s",
"string",
",",
"port",
"int",
")",
"string",
"{",
"if",
"hasPort",
"(",
"s",
")",
"{",
"return",
"s",
"\n",
"}",
"\n",
"s",
"=",
"strings",
".",
"Trim",
"(",
"s",
",",
"\"[]\"",
")",
"\n",
"s",
"=",
"net",
".",
"JoinHostPort",
"(",
"s",
",",
"strconv",
".",
"Itoa",
"(",
"port",
")",
")",
"\n",
"return",
"s",
"\n",
"}"
] |
// ensurePort makes sure the given string has a port number on it, otherwise it
// appends the given port as a default.
|
[
"ensurePort",
"makes",
"sure",
"the",
"given",
"string",
"has",
"a",
"port",
"number",
"on",
"it",
"otherwise",
"it",
"appends",
"the",
"given",
"port",
"as",
"a",
"default",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/util.go#L299-L309
|
train
|
hashicorp/memberlist
|
net_transport.go
|
NewNetTransport
|
func NewNetTransport(config *NetTransportConfig) (*NetTransport, error) {
// If we reject the empty list outright we can assume that there's at
// least one listener of each type later during operation.
if len(config.BindAddrs) == 0 {
return nil, fmt.Errorf("At least one bind address is required")
}
// Build out the new transport.
var ok bool
t := NetTransport{
config: config,
packetCh: make(chan *Packet),
streamCh: make(chan net.Conn),
logger: config.Logger,
}
// Clean up listeners if there's an error.
defer func() {
if !ok {
t.Shutdown()
}
}()
// Build all the TCP and UDP listeners.
port := config.BindPort
for _, addr := range config.BindAddrs {
ip := net.ParseIP(addr)
tcpAddr := &net.TCPAddr{IP: ip, Port: port}
tcpLn, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
return nil, fmt.Errorf("Failed to start TCP listener on %q port %d: %v", addr, port, err)
}
t.tcpListeners = append(t.tcpListeners, tcpLn)
// If the config port given was zero, use the first TCP listener
// to pick an available port and then apply that to everything
// else.
if port == 0 {
port = tcpLn.Addr().(*net.TCPAddr).Port
}
udpAddr := &net.UDPAddr{IP: ip, Port: port}
udpLn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return nil, fmt.Errorf("Failed to start UDP listener on %q port %d: %v", addr, port, err)
}
if err := setUDPRecvBuf(udpLn); err != nil {
return nil, fmt.Errorf("Failed to resize UDP buffer: %v", err)
}
t.udpListeners = append(t.udpListeners, udpLn)
}
// Fire them up now that we've been able to create them all.
for i := 0; i < len(config.BindAddrs); i++ {
t.wg.Add(2)
go t.tcpListen(t.tcpListeners[i])
go t.udpListen(t.udpListeners[i])
}
ok = true
return &t, nil
}
|
go
|
func NewNetTransport(config *NetTransportConfig) (*NetTransport, error) {
// If we reject the empty list outright we can assume that there's at
// least one listener of each type later during operation.
if len(config.BindAddrs) == 0 {
return nil, fmt.Errorf("At least one bind address is required")
}
// Build out the new transport.
var ok bool
t := NetTransport{
config: config,
packetCh: make(chan *Packet),
streamCh: make(chan net.Conn),
logger: config.Logger,
}
// Clean up listeners if there's an error.
defer func() {
if !ok {
t.Shutdown()
}
}()
// Build all the TCP and UDP listeners.
port := config.BindPort
for _, addr := range config.BindAddrs {
ip := net.ParseIP(addr)
tcpAddr := &net.TCPAddr{IP: ip, Port: port}
tcpLn, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
return nil, fmt.Errorf("Failed to start TCP listener on %q port %d: %v", addr, port, err)
}
t.tcpListeners = append(t.tcpListeners, tcpLn)
// If the config port given was zero, use the first TCP listener
// to pick an available port and then apply that to everything
// else.
if port == 0 {
port = tcpLn.Addr().(*net.TCPAddr).Port
}
udpAddr := &net.UDPAddr{IP: ip, Port: port}
udpLn, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return nil, fmt.Errorf("Failed to start UDP listener on %q port %d: %v", addr, port, err)
}
if err := setUDPRecvBuf(udpLn); err != nil {
return nil, fmt.Errorf("Failed to resize UDP buffer: %v", err)
}
t.udpListeners = append(t.udpListeners, udpLn)
}
// Fire them up now that we've been able to create them all.
for i := 0; i < len(config.BindAddrs); i++ {
t.wg.Add(2)
go t.tcpListen(t.tcpListeners[i])
go t.udpListen(t.udpListeners[i])
}
ok = true
return &t, nil
}
|
[
"func",
"NewNetTransport",
"(",
"config",
"*",
"NetTransportConfig",
")",
"(",
"*",
"NetTransport",
",",
"error",
")",
"{",
"if",
"len",
"(",
"config",
".",
"BindAddrs",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"At least one bind address is required\"",
")",
"\n",
"}",
"\n",
"var",
"ok",
"bool",
"\n",
"t",
":=",
"NetTransport",
"{",
"config",
":",
"config",
",",
"packetCh",
":",
"make",
"(",
"chan",
"*",
"Packet",
")",
",",
"streamCh",
":",
"make",
"(",
"chan",
"net",
".",
"Conn",
")",
",",
"logger",
":",
"config",
".",
"Logger",
",",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"!",
"ok",
"{",
"t",
".",
"Shutdown",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"port",
":=",
"config",
".",
"BindPort",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"config",
".",
"BindAddrs",
"{",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"addr",
")",
"\n",
"tcpAddr",
":=",
"&",
"net",
".",
"TCPAddr",
"{",
"IP",
":",
"ip",
",",
"Port",
":",
"port",
"}",
"\n",
"tcpLn",
",",
"err",
":=",
"net",
".",
"ListenTCP",
"(",
"\"tcp\"",
",",
"tcpAddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Failed to start TCP listener on %q port %d: %v\"",
",",
"addr",
",",
"port",
",",
"err",
")",
"\n",
"}",
"\n",
"t",
".",
"tcpListeners",
"=",
"append",
"(",
"t",
".",
"tcpListeners",
",",
"tcpLn",
")",
"\n",
"if",
"port",
"==",
"0",
"{",
"port",
"=",
"tcpLn",
".",
"Addr",
"(",
")",
".",
"(",
"*",
"net",
".",
"TCPAddr",
")",
".",
"Port",
"\n",
"}",
"\n",
"udpAddr",
":=",
"&",
"net",
".",
"UDPAddr",
"{",
"IP",
":",
"ip",
",",
"Port",
":",
"port",
"}",
"\n",
"udpLn",
",",
"err",
":=",
"net",
".",
"ListenUDP",
"(",
"\"udp\"",
",",
"udpAddr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Failed to start UDP listener on %q port %d: %v\"",
",",
"addr",
",",
"port",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"setUDPRecvBuf",
"(",
"udpLn",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Failed to resize UDP buffer: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"t",
".",
"udpListeners",
"=",
"append",
"(",
"t",
".",
"udpListeners",
",",
"udpLn",
")",
"\n",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"config",
".",
"BindAddrs",
")",
";",
"i",
"++",
"{",
"t",
".",
"wg",
".",
"Add",
"(",
"2",
")",
"\n",
"go",
"t",
".",
"tcpListen",
"(",
"t",
".",
"tcpListeners",
"[",
"i",
"]",
")",
"\n",
"go",
"t",
".",
"udpListen",
"(",
"t",
".",
"udpListeners",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"ok",
"=",
"true",
"\n",
"return",
"&",
"t",
",",
"nil",
"\n",
"}"
] |
// NewNetTransport returns a net transport with the given configuration. On
// success all the network listeners will be created and listening.
|
[
"NewNetTransport",
"returns",
"a",
"net",
"transport",
"with",
"the",
"given",
"configuration",
".",
"On",
"success",
"all",
"the",
"network",
"listeners",
"will",
"be",
"created",
"and",
"listening",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net_transport.go#L53-L115
|
train
|
hashicorp/memberlist
|
net_transport.go
|
GetAutoBindPort
|
func (t *NetTransport) GetAutoBindPort() int {
// We made sure there's at least one TCP listener, and that one's
// port was applied to all the others for the dynamic bind case.
return t.tcpListeners[0].Addr().(*net.TCPAddr).Port
}
|
go
|
func (t *NetTransport) GetAutoBindPort() int {
// We made sure there's at least one TCP listener, and that one's
// port was applied to all the others for the dynamic bind case.
return t.tcpListeners[0].Addr().(*net.TCPAddr).Port
}
|
[
"func",
"(",
"t",
"*",
"NetTransport",
")",
"GetAutoBindPort",
"(",
")",
"int",
"{",
"return",
"t",
".",
"tcpListeners",
"[",
"0",
"]",
".",
"Addr",
"(",
")",
".",
"(",
"*",
"net",
".",
"TCPAddr",
")",
".",
"Port",
"\n",
"}"
] |
// GetAutoBindPort returns the bind port that was automatically given by the
// kernel, if a bind port of 0 was given.
|
[
"GetAutoBindPort",
"returns",
"the",
"bind",
"port",
"that",
"was",
"automatically",
"given",
"by",
"the",
"kernel",
"if",
"a",
"bind",
"port",
"of",
"0",
"was",
"given",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net_transport.go#L119-L123
|
train
|
hashicorp/memberlist
|
net_transport.go
|
tcpListen
|
func (t *NetTransport) tcpListen(tcpLn *net.TCPListener) {
defer t.wg.Done()
// baseDelay is the initial delay after an AcceptTCP() error before attempting again
const baseDelay = 5 * time.Millisecond
// maxDelay is the maximum delay after an AcceptTCP() error before attempting again.
// In the case that tcpListen() is error-looping, it will delay the shutdown check.
// Therefore, changes to maxDelay may have an effect on the latency of shutdown.
const maxDelay = 1 * time.Second
var loopDelay time.Duration
for {
conn, err := tcpLn.AcceptTCP()
if err != nil {
if s := atomic.LoadInt32(&t.shutdown); s == 1 {
break
}
if loopDelay == 0 {
loopDelay = baseDelay
} else {
loopDelay *= 2
}
if loopDelay > maxDelay {
loopDelay = maxDelay
}
t.logger.Printf("[ERR] memberlist: Error accepting TCP connection: %v", err)
time.Sleep(loopDelay)
continue
}
// No error, reset loop delay
loopDelay = 0
t.streamCh <- conn
}
}
|
go
|
func (t *NetTransport) tcpListen(tcpLn *net.TCPListener) {
defer t.wg.Done()
// baseDelay is the initial delay after an AcceptTCP() error before attempting again
const baseDelay = 5 * time.Millisecond
// maxDelay is the maximum delay after an AcceptTCP() error before attempting again.
// In the case that tcpListen() is error-looping, it will delay the shutdown check.
// Therefore, changes to maxDelay may have an effect on the latency of shutdown.
const maxDelay = 1 * time.Second
var loopDelay time.Duration
for {
conn, err := tcpLn.AcceptTCP()
if err != nil {
if s := atomic.LoadInt32(&t.shutdown); s == 1 {
break
}
if loopDelay == 0 {
loopDelay = baseDelay
} else {
loopDelay *= 2
}
if loopDelay > maxDelay {
loopDelay = maxDelay
}
t.logger.Printf("[ERR] memberlist: Error accepting TCP connection: %v", err)
time.Sleep(loopDelay)
continue
}
// No error, reset loop delay
loopDelay = 0
t.streamCh <- conn
}
}
|
[
"func",
"(",
"t",
"*",
"NetTransport",
")",
"tcpListen",
"(",
"tcpLn",
"*",
"net",
".",
"TCPListener",
")",
"{",
"defer",
"t",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"const",
"baseDelay",
"=",
"5",
"*",
"time",
".",
"Millisecond",
"\n",
"const",
"maxDelay",
"=",
"1",
"*",
"time",
".",
"Second",
"\n",
"var",
"loopDelay",
"time",
".",
"Duration",
"\n",
"for",
"{",
"conn",
",",
"err",
":=",
"tcpLn",
".",
"AcceptTCP",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"s",
":=",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"shutdown",
")",
";",
"s",
"==",
"1",
"{",
"break",
"\n",
"}",
"\n",
"if",
"loopDelay",
"==",
"0",
"{",
"loopDelay",
"=",
"baseDelay",
"\n",
"}",
"else",
"{",
"loopDelay",
"*=",
"2",
"\n",
"}",
"\n",
"if",
"loopDelay",
">",
"maxDelay",
"{",
"loopDelay",
"=",
"maxDelay",
"\n",
"}",
"\n",
"t",
".",
"logger",
".",
"Printf",
"(",
"\"[ERR] memberlist: Error accepting TCP connection: %v\"",
",",
"err",
")",
"\n",
"time",
".",
"Sleep",
"(",
"loopDelay",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"loopDelay",
"=",
"0",
"\n",
"t",
".",
"streamCh",
"<-",
"conn",
"\n",
"}",
"\n",
"}"
] |
// tcpListen is a long running goroutine that accepts incoming TCP connections
// and hands them off to the stream channel.
|
[
"tcpListen",
"is",
"a",
"long",
"running",
"goroutine",
"that",
"accepts",
"incoming",
"TCP",
"connections",
"and",
"hands",
"them",
"off",
"to",
"the",
"stream",
"channel",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net_transport.go#L222-L260
|
train
|
hashicorp/memberlist
|
net_transport.go
|
udpListen
|
func (t *NetTransport) udpListen(udpLn *net.UDPConn) {
defer t.wg.Done()
for {
// Do a blocking read into a fresh buffer. Grab a time stamp as
// close as possible to the I/O.
buf := make([]byte, udpPacketBufSize)
n, addr, err := udpLn.ReadFrom(buf)
ts := time.Now()
if err != nil {
if s := atomic.LoadInt32(&t.shutdown); s == 1 {
break
}
t.logger.Printf("[ERR] memberlist: Error reading UDP packet: %v", err)
continue
}
// Check the length - it needs to have at least one byte to be a
// proper message.
if n < 1 {
t.logger.Printf("[ERR] memberlist: UDP packet too short (%d bytes) %s",
len(buf), LogAddress(addr))
continue
}
// Ingest the packet.
metrics.IncrCounter([]string{"memberlist", "udp", "received"}, float32(n))
t.packetCh <- &Packet{
Buf: buf[:n],
From: addr,
Timestamp: ts,
}
}
}
|
go
|
func (t *NetTransport) udpListen(udpLn *net.UDPConn) {
defer t.wg.Done()
for {
// Do a blocking read into a fresh buffer. Grab a time stamp as
// close as possible to the I/O.
buf := make([]byte, udpPacketBufSize)
n, addr, err := udpLn.ReadFrom(buf)
ts := time.Now()
if err != nil {
if s := atomic.LoadInt32(&t.shutdown); s == 1 {
break
}
t.logger.Printf("[ERR] memberlist: Error reading UDP packet: %v", err)
continue
}
// Check the length - it needs to have at least one byte to be a
// proper message.
if n < 1 {
t.logger.Printf("[ERR] memberlist: UDP packet too short (%d bytes) %s",
len(buf), LogAddress(addr))
continue
}
// Ingest the packet.
metrics.IncrCounter([]string{"memberlist", "udp", "received"}, float32(n))
t.packetCh <- &Packet{
Buf: buf[:n],
From: addr,
Timestamp: ts,
}
}
}
|
[
"func",
"(",
"t",
"*",
"NetTransport",
")",
"udpListen",
"(",
"udpLn",
"*",
"net",
".",
"UDPConn",
")",
"{",
"defer",
"t",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"for",
"{",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"udpPacketBufSize",
")",
"\n",
"n",
",",
"addr",
",",
"err",
":=",
"udpLn",
".",
"ReadFrom",
"(",
"buf",
")",
"\n",
"ts",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"s",
":=",
"atomic",
".",
"LoadInt32",
"(",
"&",
"t",
".",
"shutdown",
")",
";",
"s",
"==",
"1",
"{",
"break",
"\n",
"}",
"\n",
"t",
".",
"logger",
".",
"Printf",
"(",
"\"[ERR] memberlist: Error reading UDP packet: %v\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"n",
"<",
"1",
"{",
"t",
".",
"logger",
".",
"Printf",
"(",
"\"[ERR] memberlist: UDP packet too short (%d bytes) %s\"",
",",
"len",
"(",
"buf",
")",
",",
"LogAddress",
"(",
"addr",
")",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"metrics",
".",
"IncrCounter",
"(",
"[",
"]",
"string",
"{",
"\"memberlist\"",
",",
"\"udp\"",
",",
"\"received\"",
"}",
",",
"float32",
"(",
"n",
")",
")",
"\n",
"t",
".",
"packetCh",
"<-",
"&",
"Packet",
"{",
"Buf",
":",
"buf",
"[",
":",
"n",
"]",
",",
"From",
":",
"addr",
",",
"Timestamp",
":",
"ts",
",",
"}",
"\n",
"}",
"\n",
"}"
] |
// udpListen is a long running goroutine that accepts incoming UDP packets and
// hands them off to the packet channel.
|
[
"udpListen",
"is",
"a",
"long",
"running",
"goroutine",
"that",
"accepts",
"incoming",
"UDP",
"packets",
"and",
"hands",
"them",
"off",
"to",
"the",
"packet",
"channel",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net_transport.go#L264-L297
|
train
|
hashicorp/memberlist
|
net_transport.go
|
setUDPRecvBuf
|
func setUDPRecvBuf(c *net.UDPConn) error {
size := udpRecvBufSize
var err error
for size > 0 {
if err = c.SetReadBuffer(size); err == nil {
return nil
}
size = size / 2
}
return err
}
|
go
|
func setUDPRecvBuf(c *net.UDPConn) error {
size := udpRecvBufSize
var err error
for size > 0 {
if err = c.SetReadBuffer(size); err == nil {
return nil
}
size = size / 2
}
return err
}
|
[
"func",
"setUDPRecvBuf",
"(",
"c",
"*",
"net",
".",
"UDPConn",
")",
"error",
"{",
"size",
":=",
"udpRecvBufSize",
"\n",
"var",
"err",
"error",
"\n",
"for",
"size",
">",
"0",
"{",
"if",
"err",
"=",
"c",
".",
"SetReadBuffer",
"(",
"size",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"size",
"=",
"size",
"/",
"2",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// setUDPRecvBuf is used to resize the UDP receive window. The function
// attempts to set the read buffer to `udpRecvBuf` but backs off until
// the read buffer can be set.
|
[
"setUDPRecvBuf",
"is",
"used",
"to",
"resize",
"the",
"UDP",
"receive",
"window",
".",
"The",
"function",
"attempts",
"to",
"set",
"the",
"read",
"buffer",
"to",
"udpRecvBuf",
"but",
"backs",
"off",
"until",
"the",
"read",
"buffer",
"can",
"be",
"set",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net_transport.go#L302-L312
|
train
|
hashicorp/memberlist
|
net.go
|
streamListen
|
func (m *Memberlist) streamListen() {
for {
select {
case conn := <-m.transport.StreamCh():
go m.handleConn(conn)
case <-m.shutdownCh:
return
}
}
}
|
go
|
func (m *Memberlist) streamListen() {
for {
select {
case conn := <-m.transport.StreamCh():
go m.handleConn(conn)
case <-m.shutdownCh:
return
}
}
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"streamListen",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"conn",
":=",
"<-",
"m",
".",
"transport",
".",
"StreamCh",
"(",
")",
":",
"go",
"m",
".",
"handleConn",
"(",
"conn",
")",
"\n",
"case",
"<-",
"m",
".",
"shutdownCh",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// streamListen is a long running goroutine that pulls incoming streams from the
// transport and hands them off for processing.
|
[
"streamListen",
"is",
"a",
"long",
"running",
"goroutine",
"that",
"pulls",
"incoming",
"streams",
"from",
"the",
"transport",
"and",
"hands",
"them",
"off",
"for",
"processing",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L196-L206
|
train
|
hashicorp/memberlist
|
net.go
|
packetListen
|
func (m *Memberlist) packetListen() {
for {
select {
case packet := <-m.transport.PacketCh():
m.ingestPacket(packet.Buf, packet.From, packet.Timestamp)
case <-m.shutdownCh:
return
}
}
}
|
go
|
func (m *Memberlist) packetListen() {
for {
select {
case packet := <-m.transport.PacketCh():
m.ingestPacket(packet.Buf, packet.From, packet.Timestamp)
case <-m.shutdownCh:
return
}
}
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"packetListen",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"packet",
":=",
"<-",
"m",
".",
"transport",
".",
"PacketCh",
"(",
")",
":",
"m",
".",
"ingestPacket",
"(",
"packet",
".",
"Buf",
",",
"packet",
".",
"From",
",",
"packet",
".",
"Timestamp",
")",
"\n",
"case",
"<-",
"m",
".",
"shutdownCh",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// packetListen is a long running goroutine that pulls packets out of the
// transport and hands them off for processing.
|
[
"packetListen",
"is",
"a",
"long",
"running",
"goroutine",
"that",
"pulls",
"packets",
"out",
"of",
"the",
"transport",
"and",
"hands",
"them",
"off",
"for",
"processing",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L299-L309
|
train
|
hashicorp/memberlist
|
net.go
|
getNextMessage
|
func (m *Memberlist) getNextMessage() (msgHandoff, bool) {
m.msgQueueLock.Lock()
defer m.msgQueueLock.Unlock()
if el := m.highPriorityMsgQueue.Back(); el != nil {
m.highPriorityMsgQueue.Remove(el)
msg := el.Value.(msgHandoff)
return msg, true
} else if el := m.lowPriorityMsgQueue.Back(); el != nil {
m.lowPriorityMsgQueue.Remove(el)
msg := el.Value.(msgHandoff)
return msg, true
}
return msgHandoff{}, false
}
|
go
|
func (m *Memberlist) getNextMessage() (msgHandoff, bool) {
m.msgQueueLock.Lock()
defer m.msgQueueLock.Unlock()
if el := m.highPriorityMsgQueue.Back(); el != nil {
m.highPriorityMsgQueue.Remove(el)
msg := el.Value.(msgHandoff)
return msg, true
} else if el := m.lowPriorityMsgQueue.Back(); el != nil {
m.lowPriorityMsgQueue.Remove(el)
msg := el.Value.(msgHandoff)
return msg, true
}
return msgHandoff{}, false
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"getNextMessage",
"(",
")",
"(",
"msgHandoff",
",",
"bool",
")",
"{",
"m",
".",
"msgQueueLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"msgQueueLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"el",
":=",
"m",
".",
"highPriorityMsgQueue",
".",
"Back",
"(",
")",
";",
"el",
"!=",
"nil",
"{",
"m",
".",
"highPriorityMsgQueue",
".",
"Remove",
"(",
"el",
")",
"\n",
"msg",
":=",
"el",
".",
"Value",
".",
"(",
"msgHandoff",
")",
"\n",
"return",
"msg",
",",
"true",
"\n",
"}",
"else",
"if",
"el",
":=",
"m",
".",
"lowPriorityMsgQueue",
".",
"Back",
"(",
")",
";",
"el",
"!=",
"nil",
"{",
"m",
".",
"lowPriorityMsgQueue",
".",
"Remove",
"(",
"el",
")",
"\n",
"msg",
":=",
"el",
".",
"Value",
".",
"(",
"msgHandoff",
")",
"\n",
"return",
"msg",
",",
"true",
"\n",
"}",
"\n",
"return",
"msgHandoff",
"{",
"}",
",",
"false",
"\n",
"}"
] |
// getNextMessage returns the next message to process in priority order, using LIFO
|
[
"getNextMessage",
"returns",
"the",
"next",
"message",
"to",
"process",
"in",
"priority",
"order",
"using",
"LIFO"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L399-L413
|
train
|
hashicorp/memberlist
|
net.go
|
handleUser
|
func (m *Memberlist) handleUser(buf []byte, from net.Addr) {
d := m.config.Delegate
if d != nil {
d.NotifyMsg(buf)
}
}
|
go
|
func (m *Memberlist) handleUser(buf []byte, from net.Addr) {
d := m.config.Delegate
if d != nil {
d.NotifyMsg(buf)
}
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"handleUser",
"(",
"buf",
"[",
"]",
"byte",
",",
"from",
"net",
".",
"Addr",
")",
"{",
"d",
":=",
"m",
".",
"config",
".",
"Delegate",
"\n",
"if",
"d",
"!=",
"nil",
"{",
"d",
".",
"NotifyMsg",
"(",
"buf",
")",
"\n",
"}",
"\n",
"}"
] |
// handleUser is used to notify channels of incoming user data
|
[
"handleUser",
"is",
"used",
"to",
"notify",
"channels",
"of",
"incoming",
"user",
"data"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L597-L602
|
train
|
hashicorp/memberlist
|
net.go
|
handleCompressed
|
func (m *Memberlist) handleCompressed(buf []byte, from net.Addr, timestamp time.Time) {
// Try to decode the payload
payload, err := decompressPayload(buf)
if err != nil {
m.logger.Printf("[ERR] memberlist: Failed to decompress payload: %v %s", err, LogAddress(from))
return
}
// Recursively handle the payload
m.handleCommand(payload, from, timestamp)
}
|
go
|
func (m *Memberlist) handleCompressed(buf []byte, from net.Addr, timestamp time.Time) {
// Try to decode the payload
payload, err := decompressPayload(buf)
if err != nil {
m.logger.Printf("[ERR] memberlist: Failed to decompress payload: %v %s", err, LogAddress(from))
return
}
// Recursively handle the payload
m.handleCommand(payload, from, timestamp)
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"handleCompressed",
"(",
"buf",
"[",
"]",
"byte",
",",
"from",
"net",
".",
"Addr",
",",
"timestamp",
"time",
".",
"Time",
")",
"{",
"payload",
",",
"err",
":=",
"decompressPayload",
"(",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[ERR] memberlist: Failed to decompress payload: %v %s\"",
",",
"err",
",",
"LogAddress",
"(",
"from",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"m",
".",
"handleCommand",
"(",
"payload",
",",
"from",
",",
"timestamp",
")",
"\n",
"}"
] |
// handleCompressed is used to unpack a compressed message
|
[
"handleCompressed",
"is",
"used",
"to",
"unpack",
"a",
"compressed",
"message"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L605-L615
|
train
|
hashicorp/memberlist
|
net.go
|
encodeAndSendMsg
|
func (m *Memberlist) encodeAndSendMsg(addr string, msgType messageType, msg interface{}) error {
out, err := encode(msgType, msg)
if err != nil {
return err
}
if err := m.sendMsg(addr, out.Bytes()); err != nil {
return err
}
return nil
}
|
go
|
func (m *Memberlist) encodeAndSendMsg(addr string, msgType messageType, msg interface{}) error {
out, err := encode(msgType, msg)
if err != nil {
return err
}
if err := m.sendMsg(addr, out.Bytes()); err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"encodeAndSendMsg",
"(",
"addr",
"string",
",",
"msgType",
"messageType",
",",
"msg",
"interface",
"{",
"}",
")",
"error",
"{",
"out",
",",
"err",
":=",
"encode",
"(",
"msgType",
",",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"m",
".",
"sendMsg",
"(",
"addr",
",",
"out",
".",
"Bytes",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// encodeAndSendMsg is used to combine the encoding and sending steps
|
[
"encodeAndSendMsg",
"is",
"used",
"to",
"combine",
"the",
"encoding",
"and",
"sending",
"steps"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L618-L627
|
train
|
hashicorp/memberlist
|
net.go
|
sendMsg
|
func (m *Memberlist) sendMsg(addr string, msg []byte) error {
// Check if we can piggy back any messages
bytesAvail := m.config.UDPBufferSize - len(msg) - compoundHeaderOverhead
if m.config.EncryptionEnabled() && m.config.GossipVerifyOutgoing {
bytesAvail -= encryptOverhead(m.encryptionVersion())
}
extra := m.getBroadcasts(compoundOverhead, bytesAvail)
// Fast path if nothing to piggypack
if len(extra) == 0 {
return m.rawSendMsgPacket(addr, nil, msg)
}
// Join all the messages
msgs := make([][]byte, 0, 1+len(extra))
msgs = append(msgs, msg)
msgs = append(msgs, extra...)
// Create a compound message
compound := makeCompoundMessage(msgs)
// Send the message
return m.rawSendMsgPacket(addr, nil, compound.Bytes())
}
|
go
|
func (m *Memberlist) sendMsg(addr string, msg []byte) error {
// Check if we can piggy back any messages
bytesAvail := m.config.UDPBufferSize - len(msg) - compoundHeaderOverhead
if m.config.EncryptionEnabled() && m.config.GossipVerifyOutgoing {
bytesAvail -= encryptOverhead(m.encryptionVersion())
}
extra := m.getBroadcasts(compoundOverhead, bytesAvail)
// Fast path if nothing to piggypack
if len(extra) == 0 {
return m.rawSendMsgPacket(addr, nil, msg)
}
// Join all the messages
msgs := make([][]byte, 0, 1+len(extra))
msgs = append(msgs, msg)
msgs = append(msgs, extra...)
// Create a compound message
compound := makeCompoundMessage(msgs)
// Send the message
return m.rawSendMsgPacket(addr, nil, compound.Bytes())
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"sendMsg",
"(",
"addr",
"string",
",",
"msg",
"[",
"]",
"byte",
")",
"error",
"{",
"bytesAvail",
":=",
"m",
".",
"config",
".",
"UDPBufferSize",
"-",
"len",
"(",
"msg",
")",
"-",
"compoundHeaderOverhead",
"\n",
"if",
"m",
".",
"config",
".",
"EncryptionEnabled",
"(",
")",
"&&",
"m",
".",
"config",
".",
"GossipVerifyOutgoing",
"{",
"bytesAvail",
"-=",
"encryptOverhead",
"(",
"m",
".",
"encryptionVersion",
"(",
")",
")",
"\n",
"}",
"\n",
"extra",
":=",
"m",
".",
"getBroadcasts",
"(",
"compoundOverhead",
",",
"bytesAvail",
")",
"\n",
"if",
"len",
"(",
"extra",
")",
"==",
"0",
"{",
"return",
"m",
".",
"rawSendMsgPacket",
"(",
"addr",
",",
"nil",
",",
"msg",
")",
"\n",
"}",
"\n",
"msgs",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"0",
",",
"1",
"+",
"len",
"(",
"extra",
")",
")",
"\n",
"msgs",
"=",
"append",
"(",
"msgs",
",",
"msg",
")",
"\n",
"msgs",
"=",
"append",
"(",
"msgs",
",",
"extra",
"...",
")",
"\n",
"compound",
":=",
"makeCompoundMessage",
"(",
"msgs",
")",
"\n",
"return",
"m",
".",
"rawSendMsgPacket",
"(",
"addr",
",",
"nil",
",",
"compound",
".",
"Bytes",
"(",
")",
")",
"\n",
"}"
] |
// sendMsg is used to send a message via packet to another host. It will
// opportunistically create a compoundMsg and piggy back other broadcasts.
|
[
"sendMsg",
"is",
"used",
"to",
"send",
"a",
"message",
"via",
"packet",
"to",
"another",
"host",
".",
"It",
"will",
"opportunistically",
"create",
"a",
"compoundMsg",
"and",
"piggy",
"back",
"other",
"broadcasts",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L631-L654
|
train
|
hashicorp/memberlist
|
net.go
|
rawSendMsgPacket
|
func (m *Memberlist) rawSendMsgPacket(addr string, node *Node, msg []byte) error {
// Check if we have compression enabled
if m.config.EnableCompression {
buf, err := compressPayload(msg)
if err != nil {
m.logger.Printf("[WARN] memberlist: Failed to compress payload: %v", err)
} else {
// Only use compression if it reduced the size
if buf.Len() < len(msg) {
msg = buf.Bytes()
}
}
}
// Try to look up the destination node
if node == nil {
toAddr, _, err := net.SplitHostPort(addr)
if err != nil {
m.logger.Printf("[ERR] memberlist: Failed to parse address %q: %v", addr, err)
return err
}
m.nodeLock.RLock()
nodeState, ok := m.nodeMap[toAddr]
m.nodeLock.RUnlock()
if ok {
node = &nodeState.Node
}
}
// Add a CRC to the end of the payload if the recipient understands
// ProtocolVersion >= 5
if node != nil && node.PMax >= 5 {
crc := crc32.ChecksumIEEE(msg)
header := make([]byte, 5, 5+len(msg))
header[0] = byte(hasCrcMsg)
binary.BigEndian.PutUint32(header[1:], crc)
msg = append(header, msg...)
}
// Check if we have encryption enabled
if m.config.EncryptionEnabled() && m.config.GossipVerifyOutgoing {
// Encrypt the payload
var buf bytes.Buffer
primaryKey := m.config.Keyring.GetPrimaryKey()
err := encryptPayload(m.encryptionVersion(), primaryKey, msg, nil, &buf)
if err != nil {
m.logger.Printf("[ERR] memberlist: Encryption of message failed: %v", err)
return err
}
msg = buf.Bytes()
}
metrics.IncrCounter([]string{"memberlist", "udp", "sent"}, float32(len(msg)))
_, err := m.transport.WriteTo(msg, addr)
return err
}
|
go
|
func (m *Memberlist) rawSendMsgPacket(addr string, node *Node, msg []byte) error {
// Check if we have compression enabled
if m.config.EnableCompression {
buf, err := compressPayload(msg)
if err != nil {
m.logger.Printf("[WARN] memberlist: Failed to compress payload: %v", err)
} else {
// Only use compression if it reduced the size
if buf.Len() < len(msg) {
msg = buf.Bytes()
}
}
}
// Try to look up the destination node
if node == nil {
toAddr, _, err := net.SplitHostPort(addr)
if err != nil {
m.logger.Printf("[ERR] memberlist: Failed to parse address %q: %v", addr, err)
return err
}
m.nodeLock.RLock()
nodeState, ok := m.nodeMap[toAddr]
m.nodeLock.RUnlock()
if ok {
node = &nodeState.Node
}
}
// Add a CRC to the end of the payload if the recipient understands
// ProtocolVersion >= 5
if node != nil && node.PMax >= 5 {
crc := crc32.ChecksumIEEE(msg)
header := make([]byte, 5, 5+len(msg))
header[0] = byte(hasCrcMsg)
binary.BigEndian.PutUint32(header[1:], crc)
msg = append(header, msg...)
}
// Check if we have encryption enabled
if m.config.EncryptionEnabled() && m.config.GossipVerifyOutgoing {
// Encrypt the payload
var buf bytes.Buffer
primaryKey := m.config.Keyring.GetPrimaryKey()
err := encryptPayload(m.encryptionVersion(), primaryKey, msg, nil, &buf)
if err != nil {
m.logger.Printf("[ERR] memberlist: Encryption of message failed: %v", err)
return err
}
msg = buf.Bytes()
}
metrics.IncrCounter([]string{"memberlist", "udp", "sent"}, float32(len(msg)))
_, err := m.transport.WriteTo(msg, addr)
return err
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"rawSendMsgPacket",
"(",
"addr",
"string",
",",
"node",
"*",
"Node",
",",
"msg",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"m",
".",
"config",
".",
"EnableCompression",
"{",
"buf",
",",
"err",
":=",
"compressPayload",
"(",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[WARN] memberlist: Failed to compress payload: %v\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"if",
"buf",
".",
"Len",
"(",
")",
"<",
"len",
"(",
"msg",
")",
"{",
"msg",
"=",
"buf",
".",
"Bytes",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"node",
"==",
"nil",
"{",
"toAddr",
",",
"_",
",",
"err",
":=",
"net",
".",
"SplitHostPort",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[ERR] memberlist: Failed to parse address %q: %v\"",
",",
"addr",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"m",
".",
"nodeLock",
".",
"RLock",
"(",
")",
"\n",
"nodeState",
",",
"ok",
":=",
"m",
".",
"nodeMap",
"[",
"toAddr",
"]",
"\n",
"m",
".",
"nodeLock",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"ok",
"{",
"node",
"=",
"&",
"nodeState",
".",
"Node",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"node",
"!=",
"nil",
"&&",
"node",
".",
"PMax",
">=",
"5",
"{",
"crc",
":=",
"crc32",
".",
"ChecksumIEEE",
"(",
"msg",
")",
"\n",
"header",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"5",
",",
"5",
"+",
"len",
"(",
"msg",
")",
")",
"\n",
"header",
"[",
"0",
"]",
"=",
"byte",
"(",
"hasCrcMsg",
")",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint32",
"(",
"header",
"[",
"1",
":",
"]",
",",
"crc",
")",
"\n",
"msg",
"=",
"append",
"(",
"header",
",",
"msg",
"...",
")",
"\n",
"}",
"\n",
"if",
"m",
".",
"config",
".",
"EncryptionEnabled",
"(",
")",
"&&",
"m",
".",
"config",
".",
"GossipVerifyOutgoing",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"primaryKey",
":=",
"m",
".",
"config",
".",
"Keyring",
".",
"GetPrimaryKey",
"(",
")",
"\n",
"err",
":=",
"encryptPayload",
"(",
"m",
".",
"encryptionVersion",
"(",
")",
",",
"primaryKey",
",",
"msg",
",",
"nil",
",",
"&",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[ERR] memberlist: Encryption of message failed: %v\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"msg",
"=",
"buf",
".",
"Bytes",
"(",
")",
"\n",
"}",
"\n",
"metrics",
".",
"IncrCounter",
"(",
"[",
"]",
"string",
"{",
"\"memberlist\"",
",",
"\"udp\"",
",",
"\"sent\"",
"}",
",",
"float32",
"(",
"len",
"(",
"msg",
")",
")",
")",
"\n",
"_",
",",
"err",
":=",
"m",
".",
"transport",
".",
"WriteTo",
"(",
"msg",
",",
"addr",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// rawSendMsgPacket is used to send message via packet to another host without
// modification, other than compression or encryption if enabled.
|
[
"rawSendMsgPacket",
"is",
"used",
"to",
"send",
"message",
"via",
"packet",
"to",
"another",
"host",
"without",
"modification",
"other",
"than",
"compression",
"or",
"encryption",
"if",
"enabled",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L658-L713
|
train
|
hashicorp/memberlist
|
net.go
|
rawSendMsgStream
|
func (m *Memberlist) rawSendMsgStream(conn net.Conn, sendBuf []byte) error {
// Check if compresion is enabled
if m.config.EnableCompression {
compBuf, err := compressPayload(sendBuf)
if err != nil {
m.logger.Printf("[ERROR] memberlist: Failed to compress payload: %v", err)
} else {
sendBuf = compBuf.Bytes()
}
}
// Check if encryption is enabled
if m.config.EncryptionEnabled() && m.config.GossipVerifyOutgoing {
crypt, err := m.encryptLocalState(sendBuf)
if err != nil {
m.logger.Printf("[ERROR] memberlist: Failed to encrypt local state: %v", err)
return err
}
sendBuf = crypt
}
// Write out the entire send buffer
metrics.IncrCounter([]string{"memberlist", "tcp", "sent"}, float32(len(sendBuf)))
if n, err := conn.Write(sendBuf); err != nil {
return err
} else if n != len(sendBuf) {
return fmt.Errorf("only %d of %d bytes written", n, len(sendBuf))
}
return nil
}
|
go
|
func (m *Memberlist) rawSendMsgStream(conn net.Conn, sendBuf []byte) error {
// Check if compresion is enabled
if m.config.EnableCompression {
compBuf, err := compressPayload(sendBuf)
if err != nil {
m.logger.Printf("[ERROR] memberlist: Failed to compress payload: %v", err)
} else {
sendBuf = compBuf.Bytes()
}
}
// Check if encryption is enabled
if m.config.EncryptionEnabled() && m.config.GossipVerifyOutgoing {
crypt, err := m.encryptLocalState(sendBuf)
if err != nil {
m.logger.Printf("[ERROR] memberlist: Failed to encrypt local state: %v", err)
return err
}
sendBuf = crypt
}
// Write out the entire send buffer
metrics.IncrCounter([]string{"memberlist", "tcp", "sent"}, float32(len(sendBuf)))
if n, err := conn.Write(sendBuf); err != nil {
return err
} else if n != len(sendBuf) {
return fmt.Errorf("only %d of %d bytes written", n, len(sendBuf))
}
return nil
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"rawSendMsgStream",
"(",
"conn",
"net",
".",
"Conn",
",",
"sendBuf",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"m",
".",
"config",
".",
"EnableCompression",
"{",
"compBuf",
",",
"err",
":=",
"compressPayload",
"(",
"sendBuf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[ERROR] memberlist: Failed to compress payload: %v\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"sendBuf",
"=",
"compBuf",
".",
"Bytes",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"m",
".",
"config",
".",
"EncryptionEnabled",
"(",
")",
"&&",
"m",
".",
"config",
".",
"GossipVerifyOutgoing",
"{",
"crypt",
",",
"err",
":=",
"m",
".",
"encryptLocalState",
"(",
"sendBuf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[ERROR] memberlist: Failed to encrypt local state: %v\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"sendBuf",
"=",
"crypt",
"\n",
"}",
"\n",
"metrics",
".",
"IncrCounter",
"(",
"[",
"]",
"string",
"{",
"\"memberlist\"",
",",
"\"tcp\"",
",",
"\"sent\"",
"}",
",",
"float32",
"(",
"len",
"(",
"sendBuf",
")",
")",
")",
"\n",
"if",
"n",
",",
"err",
":=",
"conn",
".",
"Write",
"(",
"sendBuf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"n",
"!=",
"len",
"(",
"sendBuf",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"only %d of %d bytes written\"",
",",
"n",
",",
"len",
"(",
"sendBuf",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// rawSendMsgStream is used to stream a message to another host without
// modification, other than applying compression and encryption if enabled.
|
[
"rawSendMsgStream",
"is",
"used",
"to",
"stream",
"a",
"message",
"to",
"another",
"host",
"without",
"modification",
"other",
"than",
"applying",
"compression",
"and",
"encryption",
"if",
"enabled",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L717-L748
|
train
|
hashicorp/memberlist
|
net.go
|
sendUserMsg
|
func (m *Memberlist) sendUserMsg(addr string, sendBuf []byte) error {
conn, err := m.transport.DialTimeout(addr, m.config.TCPTimeout)
if err != nil {
return err
}
defer conn.Close()
bufConn := bytes.NewBuffer(nil)
if err := bufConn.WriteByte(byte(userMsg)); err != nil {
return err
}
header := userMsgHeader{UserMsgLen: len(sendBuf)}
hd := codec.MsgpackHandle{}
enc := codec.NewEncoder(bufConn, &hd)
if err := enc.Encode(&header); err != nil {
return err
}
if _, err := bufConn.Write(sendBuf); err != nil {
return err
}
return m.rawSendMsgStream(conn, bufConn.Bytes())
}
|
go
|
func (m *Memberlist) sendUserMsg(addr string, sendBuf []byte) error {
conn, err := m.transport.DialTimeout(addr, m.config.TCPTimeout)
if err != nil {
return err
}
defer conn.Close()
bufConn := bytes.NewBuffer(nil)
if err := bufConn.WriteByte(byte(userMsg)); err != nil {
return err
}
header := userMsgHeader{UserMsgLen: len(sendBuf)}
hd := codec.MsgpackHandle{}
enc := codec.NewEncoder(bufConn, &hd)
if err := enc.Encode(&header); err != nil {
return err
}
if _, err := bufConn.Write(sendBuf); err != nil {
return err
}
return m.rawSendMsgStream(conn, bufConn.Bytes())
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"sendUserMsg",
"(",
"addr",
"string",
",",
"sendBuf",
"[",
"]",
"byte",
")",
"error",
"{",
"conn",
",",
"err",
":=",
"m",
".",
"transport",
".",
"DialTimeout",
"(",
"addr",
",",
"m",
".",
"config",
".",
"TCPTimeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"bufConn",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n",
"if",
"err",
":=",
"bufConn",
".",
"WriteByte",
"(",
"byte",
"(",
"userMsg",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"header",
":=",
"userMsgHeader",
"{",
"UserMsgLen",
":",
"len",
"(",
"sendBuf",
")",
"}",
"\n",
"hd",
":=",
"codec",
".",
"MsgpackHandle",
"{",
"}",
"\n",
"enc",
":=",
"codec",
".",
"NewEncoder",
"(",
"bufConn",
",",
"&",
"hd",
")",
"\n",
"if",
"err",
":=",
"enc",
".",
"Encode",
"(",
"&",
"header",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"bufConn",
".",
"Write",
"(",
"sendBuf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"m",
".",
"rawSendMsgStream",
"(",
"conn",
",",
"bufConn",
".",
"Bytes",
"(",
")",
")",
"\n",
"}"
] |
// sendUserMsg is used to stream a user message to another host.
|
[
"sendUserMsg",
"is",
"used",
"to",
"stream",
"a",
"user",
"message",
"to",
"another",
"host",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L751-L773
|
train
|
hashicorp/memberlist
|
net.go
|
sendLocalState
|
func (m *Memberlist) sendLocalState(conn net.Conn, join bool) error {
// Setup a deadline
conn.SetDeadline(time.Now().Add(m.config.TCPTimeout))
// Prepare the local node state
m.nodeLock.RLock()
localNodes := make([]pushNodeState, len(m.nodes))
for idx, n := range m.nodes {
localNodes[idx].Name = n.Name
localNodes[idx].Addr = n.Addr
localNodes[idx].Port = n.Port
localNodes[idx].Incarnation = n.Incarnation
localNodes[idx].State = n.State
localNodes[idx].Meta = n.Meta
localNodes[idx].Vsn = []uint8{
n.PMin, n.PMax, n.PCur,
n.DMin, n.DMax, n.DCur,
}
}
m.nodeLock.RUnlock()
// Get the delegate state
var userData []byte
if m.config.Delegate != nil {
userData = m.config.Delegate.LocalState(join)
}
// Create a bytes buffer writer
bufConn := bytes.NewBuffer(nil)
// Send our node state
header := pushPullHeader{Nodes: len(localNodes), UserStateLen: len(userData), Join: join}
hd := codec.MsgpackHandle{}
enc := codec.NewEncoder(bufConn, &hd)
// Begin state push
if _, err := bufConn.Write([]byte{byte(pushPullMsg)}); err != nil {
return err
}
if err := enc.Encode(&header); err != nil {
return err
}
for i := 0; i < header.Nodes; i++ {
if err := enc.Encode(&localNodes[i]); err != nil {
return err
}
}
// Write the user state as well
if userData != nil {
if _, err := bufConn.Write(userData); err != nil {
return err
}
}
// Get the send buffer
return m.rawSendMsgStream(conn, bufConn.Bytes())
}
|
go
|
func (m *Memberlist) sendLocalState(conn net.Conn, join bool) error {
// Setup a deadline
conn.SetDeadline(time.Now().Add(m.config.TCPTimeout))
// Prepare the local node state
m.nodeLock.RLock()
localNodes := make([]pushNodeState, len(m.nodes))
for idx, n := range m.nodes {
localNodes[idx].Name = n.Name
localNodes[idx].Addr = n.Addr
localNodes[idx].Port = n.Port
localNodes[idx].Incarnation = n.Incarnation
localNodes[idx].State = n.State
localNodes[idx].Meta = n.Meta
localNodes[idx].Vsn = []uint8{
n.PMin, n.PMax, n.PCur,
n.DMin, n.DMax, n.DCur,
}
}
m.nodeLock.RUnlock()
// Get the delegate state
var userData []byte
if m.config.Delegate != nil {
userData = m.config.Delegate.LocalState(join)
}
// Create a bytes buffer writer
bufConn := bytes.NewBuffer(nil)
// Send our node state
header := pushPullHeader{Nodes: len(localNodes), UserStateLen: len(userData), Join: join}
hd := codec.MsgpackHandle{}
enc := codec.NewEncoder(bufConn, &hd)
// Begin state push
if _, err := bufConn.Write([]byte{byte(pushPullMsg)}); err != nil {
return err
}
if err := enc.Encode(&header); err != nil {
return err
}
for i := 0; i < header.Nodes; i++ {
if err := enc.Encode(&localNodes[i]); err != nil {
return err
}
}
// Write the user state as well
if userData != nil {
if _, err := bufConn.Write(userData); err != nil {
return err
}
}
// Get the send buffer
return m.rawSendMsgStream(conn, bufConn.Bytes())
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"sendLocalState",
"(",
"conn",
"net",
".",
"Conn",
",",
"join",
"bool",
")",
"error",
"{",
"conn",
".",
"SetDeadline",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"m",
".",
"config",
".",
"TCPTimeout",
")",
")",
"\n",
"m",
".",
"nodeLock",
".",
"RLock",
"(",
")",
"\n",
"localNodes",
":=",
"make",
"(",
"[",
"]",
"pushNodeState",
",",
"len",
"(",
"m",
".",
"nodes",
")",
")",
"\n",
"for",
"idx",
",",
"n",
":=",
"range",
"m",
".",
"nodes",
"{",
"localNodes",
"[",
"idx",
"]",
".",
"Name",
"=",
"n",
".",
"Name",
"\n",
"localNodes",
"[",
"idx",
"]",
".",
"Addr",
"=",
"n",
".",
"Addr",
"\n",
"localNodes",
"[",
"idx",
"]",
".",
"Port",
"=",
"n",
".",
"Port",
"\n",
"localNodes",
"[",
"idx",
"]",
".",
"Incarnation",
"=",
"n",
".",
"Incarnation",
"\n",
"localNodes",
"[",
"idx",
"]",
".",
"State",
"=",
"n",
".",
"State",
"\n",
"localNodes",
"[",
"idx",
"]",
".",
"Meta",
"=",
"n",
".",
"Meta",
"\n",
"localNodes",
"[",
"idx",
"]",
".",
"Vsn",
"=",
"[",
"]",
"uint8",
"{",
"n",
".",
"PMin",
",",
"n",
".",
"PMax",
",",
"n",
".",
"PCur",
",",
"n",
".",
"DMin",
",",
"n",
".",
"DMax",
",",
"n",
".",
"DCur",
",",
"}",
"\n",
"}",
"\n",
"m",
".",
"nodeLock",
".",
"RUnlock",
"(",
")",
"\n",
"var",
"userData",
"[",
"]",
"byte",
"\n",
"if",
"m",
".",
"config",
".",
"Delegate",
"!=",
"nil",
"{",
"userData",
"=",
"m",
".",
"config",
".",
"Delegate",
".",
"LocalState",
"(",
"join",
")",
"\n",
"}",
"\n",
"bufConn",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n",
"header",
":=",
"pushPullHeader",
"{",
"Nodes",
":",
"len",
"(",
"localNodes",
")",
",",
"UserStateLen",
":",
"len",
"(",
"userData",
")",
",",
"Join",
":",
"join",
"}",
"\n",
"hd",
":=",
"codec",
".",
"MsgpackHandle",
"{",
"}",
"\n",
"enc",
":=",
"codec",
".",
"NewEncoder",
"(",
"bufConn",
",",
"&",
"hd",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"bufConn",
".",
"Write",
"(",
"[",
"]",
"byte",
"{",
"byte",
"(",
"pushPullMsg",
")",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"enc",
".",
"Encode",
"(",
"&",
"header",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"header",
".",
"Nodes",
";",
"i",
"++",
"{",
"if",
"err",
":=",
"enc",
".",
"Encode",
"(",
"&",
"localNodes",
"[",
"i",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"userData",
"!=",
"nil",
"{",
"if",
"_",
",",
"err",
":=",
"bufConn",
".",
"Write",
"(",
"userData",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"m",
".",
"rawSendMsgStream",
"(",
"conn",
",",
"bufConn",
".",
"Bytes",
"(",
")",
")",
"\n",
"}"
] |
// sendLocalState is invoked to send our local state over a stream connection.
|
[
"sendLocalState",
"is",
"invoked",
"to",
"send",
"our",
"local",
"state",
"over",
"a",
"stream",
"connection",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L818-L876
|
train
|
hashicorp/memberlist
|
net.go
|
encryptLocalState
|
func (m *Memberlist) encryptLocalState(sendBuf []byte) ([]byte, error) {
var buf bytes.Buffer
// Write the encryptMsg byte
buf.WriteByte(byte(encryptMsg))
// Write the size of the message
sizeBuf := make([]byte, 4)
encVsn := m.encryptionVersion()
encLen := encryptedLength(encVsn, len(sendBuf))
binary.BigEndian.PutUint32(sizeBuf, uint32(encLen))
buf.Write(sizeBuf)
// Write the encrypted cipher text to the buffer
key := m.config.Keyring.GetPrimaryKey()
err := encryptPayload(encVsn, key, sendBuf, buf.Bytes()[:5], &buf)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
|
go
|
func (m *Memberlist) encryptLocalState(sendBuf []byte) ([]byte, error) {
var buf bytes.Buffer
// Write the encryptMsg byte
buf.WriteByte(byte(encryptMsg))
// Write the size of the message
sizeBuf := make([]byte, 4)
encVsn := m.encryptionVersion()
encLen := encryptedLength(encVsn, len(sendBuf))
binary.BigEndian.PutUint32(sizeBuf, uint32(encLen))
buf.Write(sizeBuf)
// Write the encrypted cipher text to the buffer
key := m.config.Keyring.GetPrimaryKey()
err := encryptPayload(encVsn, key, sendBuf, buf.Bytes()[:5], &buf)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"encryptLocalState",
"(",
"sendBuf",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"buf",
".",
"WriteByte",
"(",
"byte",
"(",
"encryptMsg",
")",
")",
"\n",
"sizeBuf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"4",
")",
"\n",
"encVsn",
":=",
"m",
".",
"encryptionVersion",
"(",
")",
"\n",
"encLen",
":=",
"encryptedLength",
"(",
"encVsn",
",",
"len",
"(",
"sendBuf",
")",
")",
"\n",
"binary",
".",
"BigEndian",
".",
"PutUint32",
"(",
"sizeBuf",
",",
"uint32",
"(",
"encLen",
")",
")",
"\n",
"buf",
".",
"Write",
"(",
"sizeBuf",
")",
"\n",
"key",
":=",
"m",
".",
"config",
".",
"Keyring",
".",
"GetPrimaryKey",
"(",
")",
"\n",
"err",
":=",
"encryptPayload",
"(",
"encVsn",
",",
"key",
",",
"sendBuf",
",",
"buf",
".",
"Bytes",
"(",
")",
"[",
":",
"5",
"]",
",",
"&",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] |
// encryptLocalState is used to help encrypt local state before sending
|
[
"encryptLocalState",
"is",
"used",
"to",
"help",
"encrypt",
"local",
"state",
"before",
"sending"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L879-L899
|
train
|
hashicorp/memberlist
|
net.go
|
decryptRemoteState
|
func (m *Memberlist) decryptRemoteState(bufConn io.Reader) ([]byte, error) {
// Read in enough to determine message length
cipherText := bytes.NewBuffer(nil)
cipherText.WriteByte(byte(encryptMsg))
_, err := io.CopyN(cipherText, bufConn, 4)
if err != nil {
return nil, err
}
// Ensure we aren't asked to download too much. This is to guard against
// an attack vector where a huge amount of state is sent
moreBytes := binary.BigEndian.Uint32(cipherText.Bytes()[1:5])
if moreBytes > maxPushStateBytes {
return nil, fmt.Errorf("Remote node state is larger than limit (%d)", moreBytes)
}
// Read in the rest of the payload
_, err = io.CopyN(cipherText, bufConn, int64(moreBytes))
if err != nil {
return nil, err
}
// Decrypt the cipherText
dataBytes := cipherText.Bytes()[:5]
cipherBytes := cipherText.Bytes()[5:]
// Decrypt the payload
keys := m.config.Keyring.GetKeys()
return decryptPayload(keys, cipherBytes, dataBytes)
}
|
go
|
func (m *Memberlist) decryptRemoteState(bufConn io.Reader) ([]byte, error) {
// Read in enough to determine message length
cipherText := bytes.NewBuffer(nil)
cipherText.WriteByte(byte(encryptMsg))
_, err := io.CopyN(cipherText, bufConn, 4)
if err != nil {
return nil, err
}
// Ensure we aren't asked to download too much. This is to guard against
// an attack vector where a huge amount of state is sent
moreBytes := binary.BigEndian.Uint32(cipherText.Bytes()[1:5])
if moreBytes > maxPushStateBytes {
return nil, fmt.Errorf("Remote node state is larger than limit (%d)", moreBytes)
}
// Read in the rest of the payload
_, err = io.CopyN(cipherText, bufConn, int64(moreBytes))
if err != nil {
return nil, err
}
// Decrypt the cipherText
dataBytes := cipherText.Bytes()[:5]
cipherBytes := cipherText.Bytes()[5:]
// Decrypt the payload
keys := m.config.Keyring.GetKeys()
return decryptPayload(keys, cipherBytes, dataBytes)
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"decryptRemoteState",
"(",
"bufConn",
"io",
".",
"Reader",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"cipherText",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n",
"cipherText",
".",
"WriteByte",
"(",
"byte",
"(",
"encryptMsg",
")",
")",
"\n",
"_",
",",
"err",
":=",
"io",
".",
"CopyN",
"(",
"cipherText",
",",
"bufConn",
",",
"4",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"moreBytes",
":=",
"binary",
".",
"BigEndian",
".",
"Uint32",
"(",
"cipherText",
".",
"Bytes",
"(",
")",
"[",
"1",
":",
"5",
"]",
")",
"\n",
"if",
"moreBytes",
">",
"maxPushStateBytes",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Remote node state is larger than limit (%d)\"",
",",
"moreBytes",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"CopyN",
"(",
"cipherText",
",",
"bufConn",
",",
"int64",
"(",
"moreBytes",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"dataBytes",
":=",
"cipherText",
".",
"Bytes",
"(",
")",
"[",
":",
"5",
"]",
"\n",
"cipherBytes",
":=",
"cipherText",
".",
"Bytes",
"(",
")",
"[",
"5",
":",
"]",
"\n",
"keys",
":=",
"m",
".",
"config",
".",
"Keyring",
".",
"GetKeys",
"(",
")",
"\n",
"return",
"decryptPayload",
"(",
"keys",
",",
"cipherBytes",
",",
"dataBytes",
")",
"\n",
"}"
] |
// decryptRemoteState is used to help decrypt the remote state
|
[
"decryptRemoteState",
"is",
"used",
"to",
"help",
"decrypt",
"the",
"remote",
"state"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L902-L931
|
train
|
hashicorp/memberlist
|
net.go
|
readStream
|
func (m *Memberlist) readStream(conn net.Conn) (messageType, io.Reader, *codec.Decoder, error) {
// Created a buffered reader
var bufConn io.Reader = bufio.NewReader(conn)
// Read the message type
buf := [1]byte{0}
if _, err := bufConn.Read(buf[:]); err != nil {
return 0, nil, nil, err
}
msgType := messageType(buf[0])
// Check if the message is encrypted
if msgType == encryptMsg {
if !m.config.EncryptionEnabled() {
return 0, nil, nil,
fmt.Errorf("Remote state is encrypted and encryption is not configured")
}
plain, err := m.decryptRemoteState(bufConn)
if err != nil {
return 0, nil, nil, err
}
// Reset message type and bufConn
msgType = messageType(plain[0])
bufConn = bytes.NewReader(plain[1:])
} else if m.config.EncryptionEnabled() && m.config.GossipVerifyIncoming {
return 0, nil, nil,
fmt.Errorf("Encryption is configured but remote state is not encrypted")
}
// Get the msgPack decoders
hd := codec.MsgpackHandle{}
dec := codec.NewDecoder(bufConn, &hd)
// Check if we have a compressed message
if msgType == compressMsg {
var c compress
if err := dec.Decode(&c); err != nil {
return 0, nil, nil, err
}
decomp, err := decompressBuffer(&c)
if err != nil {
return 0, nil, nil, err
}
// Reset the message type
msgType = messageType(decomp[0])
// Create a new bufConn
bufConn = bytes.NewReader(decomp[1:])
// Create a new decoder
dec = codec.NewDecoder(bufConn, &hd)
}
return msgType, bufConn, dec, nil
}
|
go
|
func (m *Memberlist) readStream(conn net.Conn) (messageType, io.Reader, *codec.Decoder, error) {
// Created a buffered reader
var bufConn io.Reader = bufio.NewReader(conn)
// Read the message type
buf := [1]byte{0}
if _, err := bufConn.Read(buf[:]); err != nil {
return 0, nil, nil, err
}
msgType := messageType(buf[0])
// Check if the message is encrypted
if msgType == encryptMsg {
if !m.config.EncryptionEnabled() {
return 0, nil, nil,
fmt.Errorf("Remote state is encrypted and encryption is not configured")
}
plain, err := m.decryptRemoteState(bufConn)
if err != nil {
return 0, nil, nil, err
}
// Reset message type and bufConn
msgType = messageType(plain[0])
bufConn = bytes.NewReader(plain[1:])
} else if m.config.EncryptionEnabled() && m.config.GossipVerifyIncoming {
return 0, nil, nil,
fmt.Errorf("Encryption is configured but remote state is not encrypted")
}
// Get the msgPack decoders
hd := codec.MsgpackHandle{}
dec := codec.NewDecoder(bufConn, &hd)
// Check if we have a compressed message
if msgType == compressMsg {
var c compress
if err := dec.Decode(&c); err != nil {
return 0, nil, nil, err
}
decomp, err := decompressBuffer(&c)
if err != nil {
return 0, nil, nil, err
}
// Reset the message type
msgType = messageType(decomp[0])
// Create a new bufConn
bufConn = bytes.NewReader(decomp[1:])
// Create a new decoder
dec = codec.NewDecoder(bufConn, &hd)
}
return msgType, bufConn, dec, nil
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"readStream",
"(",
"conn",
"net",
".",
"Conn",
")",
"(",
"messageType",
",",
"io",
".",
"Reader",
",",
"*",
"codec",
".",
"Decoder",
",",
"error",
")",
"{",
"var",
"bufConn",
"io",
".",
"Reader",
"=",
"bufio",
".",
"NewReader",
"(",
"conn",
")",
"\n",
"buf",
":=",
"[",
"1",
"]",
"byte",
"{",
"0",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"bufConn",
".",
"Read",
"(",
"buf",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"msgType",
":=",
"messageType",
"(",
"buf",
"[",
"0",
"]",
")",
"\n",
"if",
"msgType",
"==",
"encryptMsg",
"{",
"if",
"!",
"m",
".",
"config",
".",
"EncryptionEnabled",
"(",
")",
"{",
"return",
"0",
",",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Remote state is encrypted and encryption is not configured\"",
")",
"\n",
"}",
"\n",
"plain",
",",
"err",
":=",
"m",
".",
"decryptRemoteState",
"(",
"bufConn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"msgType",
"=",
"messageType",
"(",
"plain",
"[",
"0",
"]",
")",
"\n",
"bufConn",
"=",
"bytes",
".",
"NewReader",
"(",
"plain",
"[",
"1",
":",
"]",
")",
"\n",
"}",
"else",
"if",
"m",
".",
"config",
".",
"EncryptionEnabled",
"(",
")",
"&&",
"m",
".",
"config",
".",
"GossipVerifyIncoming",
"{",
"return",
"0",
",",
"nil",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Encryption is configured but remote state is not encrypted\"",
")",
"\n",
"}",
"\n",
"hd",
":=",
"codec",
".",
"MsgpackHandle",
"{",
"}",
"\n",
"dec",
":=",
"codec",
".",
"NewDecoder",
"(",
"bufConn",
",",
"&",
"hd",
")",
"\n",
"if",
"msgType",
"==",
"compressMsg",
"{",
"var",
"c",
"compress",
"\n",
"if",
"err",
":=",
"dec",
".",
"Decode",
"(",
"&",
"c",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"decomp",
",",
"err",
":=",
"decompressBuffer",
"(",
"&",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"msgType",
"=",
"messageType",
"(",
"decomp",
"[",
"0",
"]",
")",
"\n",
"bufConn",
"=",
"bytes",
".",
"NewReader",
"(",
"decomp",
"[",
"1",
":",
"]",
")",
"\n",
"dec",
"=",
"codec",
".",
"NewDecoder",
"(",
"bufConn",
",",
"&",
"hd",
")",
"\n",
"}",
"\n",
"return",
"msgType",
",",
"bufConn",
",",
"dec",
",",
"nil",
"\n",
"}"
] |
// readStream is used to read from a stream connection, decrypting and
// decompressing the stream if necessary.
|
[
"readStream",
"is",
"used",
"to",
"read",
"from",
"a",
"stream",
"connection",
"decrypting",
"and",
"decompressing",
"the",
"stream",
"if",
"necessary",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L935-L992
|
train
|
hashicorp/memberlist
|
net.go
|
readRemoteState
|
func (m *Memberlist) readRemoteState(bufConn io.Reader, dec *codec.Decoder) (bool, []pushNodeState, []byte, error) {
// Read the push/pull header
var header pushPullHeader
if err := dec.Decode(&header); err != nil {
return false, nil, nil, err
}
// Allocate space for the transfer
remoteNodes := make([]pushNodeState, header.Nodes)
// Try to decode all the states
for i := 0; i < header.Nodes; i++ {
if err := dec.Decode(&remoteNodes[i]); err != nil {
return false, nil, nil, err
}
}
// Read the remote user state into a buffer
var userBuf []byte
if header.UserStateLen > 0 {
userBuf = make([]byte, header.UserStateLen)
bytes, err := io.ReadAtLeast(bufConn, userBuf, header.UserStateLen)
if err == nil && bytes != header.UserStateLen {
err = fmt.Errorf(
"Failed to read full user state (%d / %d)",
bytes, header.UserStateLen)
}
if err != nil {
return false, nil, nil, err
}
}
// For proto versions < 2, there is no port provided. Mask old
// behavior by using the configured port
for idx := range remoteNodes {
if m.ProtocolVersion() < 2 || remoteNodes[idx].Port == 0 {
remoteNodes[idx].Port = uint16(m.config.BindPort)
}
}
return header.Join, remoteNodes, userBuf, nil
}
|
go
|
func (m *Memberlist) readRemoteState(bufConn io.Reader, dec *codec.Decoder) (bool, []pushNodeState, []byte, error) {
// Read the push/pull header
var header pushPullHeader
if err := dec.Decode(&header); err != nil {
return false, nil, nil, err
}
// Allocate space for the transfer
remoteNodes := make([]pushNodeState, header.Nodes)
// Try to decode all the states
for i := 0; i < header.Nodes; i++ {
if err := dec.Decode(&remoteNodes[i]); err != nil {
return false, nil, nil, err
}
}
// Read the remote user state into a buffer
var userBuf []byte
if header.UserStateLen > 0 {
userBuf = make([]byte, header.UserStateLen)
bytes, err := io.ReadAtLeast(bufConn, userBuf, header.UserStateLen)
if err == nil && bytes != header.UserStateLen {
err = fmt.Errorf(
"Failed to read full user state (%d / %d)",
bytes, header.UserStateLen)
}
if err != nil {
return false, nil, nil, err
}
}
// For proto versions < 2, there is no port provided. Mask old
// behavior by using the configured port
for idx := range remoteNodes {
if m.ProtocolVersion() < 2 || remoteNodes[idx].Port == 0 {
remoteNodes[idx].Port = uint16(m.config.BindPort)
}
}
return header.Join, remoteNodes, userBuf, nil
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"readRemoteState",
"(",
"bufConn",
"io",
".",
"Reader",
",",
"dec",
"*",
"codec",
".",
"Decoder",
")",
"(",
"bool",
",",
"[",
"]",
"pushNodeState",
",",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"header",
"pushPullHeader",
"\n",
"if",
"err",
":=",
"dec",
".",
"Decode",
"(",
"&",
"header",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"remoteNodes",
":=",
"make",
"(",
"[",
"]",
"pushNodeState",
",",
"header",
".",
"Nodes",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"header",
".",
"Nodes",
";",
"i",
"++",
"{",
"if",
"err",
":=",
"dec",
".",
"Decode",
"(",
"&",
"remoteNodes",
"[",
"i",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"userBuf",
"[",
"]",
"byte",
"\n",
"if",
"header",
".",
"UserStateLen",
">",
"0",
"{",
"userBuf",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"header",
".",
"UserStateLen",
")",
"\n",
"bytes",
",",
"err",
":=",
"io",
".",
"ReadAtLeast",
"(",
"bufConn",
",",
"userBuf",
",",
"header",
".",
"UserStateLen",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"bytes",
"!=",
"header",
".",
"UserStateLen",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"Failed to read full user state (%d / %d)\"",
",",
"bytes",
",",
"header",
".",
"UserStateLen",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"idx",
":=",
"range",
"remoteNodes",
"{",
"if",
"m",
".",
"ProtocolVersion",
"(",
")",
"<",
"2",
"||",
"remoteNodes",
"[",
"idx",
"]",
".",
"Port",
"==",
"0",
"{",
"remoteNodes",
"[",
"idx",
"]",
".",
"Port",
"=",
"uint16",
"(",
"m",
".",
"config",
".",
"BindPort",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"header",
".",
"Join",
",",
"remoteNodes",
",",
"userBuf",
",",
"nil",
"\n",
"}"
] |
// readRemoteState is used to read the remote state from a connection
|
[
"readRemoteState",
"is",
"used",
"to",
"read",
"the",
"remote",
"state",
"from",
"a",
"connection"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L995-L1036
|
train
|
hashicorp/memberlist
|
net.go
|
mergeRemoteState
|
func (m *Memberlist) mergeRemoteState(join bool, remoteNodes []pushNodeState, userBuf []byte) error {
if err := m.verifyProtocol(remoteNodes); err != nil {
return err
}
// Invoke the merge delegate if any
if join && m.config.Merge != nil {
nodes := make([]*Node, len(remoteNodes))
for idx, n := range remoteNodes {
nodes[idx] = &Node{
Name: n.Name,
Addr: n.Addr,
Port: n.Port,
Meta: n.Meta,
PMin: n.Vsn[0],
PMax: n.Vsn[1],
PCur: n.Vsn[2],
DMin: n.Vsn[3],
DMax: n.Vsn[4],
DCur: n.Vsn[5],
}
}
if err := m.config.Merge.NotifyMerge(nodes); err != nil {
return err
}
}
// Merge the membership state
m.mergeState(remoteNodes)
// Invoke the delegate for user state
if userBuf != nil && m.config.Delegate != nil {
m.config.Delegate.MergeRemoteState(userBuf, join)
}
return nil
}
|
go
|
func (m *Memberlist) mergeRemoteState(join bool, remoteNodes []pushNodeState, userBuf []byte) error {
if err := m.verifyProtocol(remoteNodes); err != nil {
return err
}
// Invoke the merge delegate if any
if join && m.config.Merge != nil {
nodes := make([]*Node, len(remoteNodes))
for idx, n := range remoteNodes {
nodes[idx] = &Node{
Name: n.Name,
Addr: n.Addr,
Port: n.Port,
Meta: n.Meta,
PMin: n.Vsn[0],
PMax: n.Vsn[1],
PCur: n.Vsn[2],
DMin: n.Vsn[3],
DMax: n.Vsn[4],
DCur: n.Vsn[5],
}
}
if err := m.config.Merge.NotifyMerge(nodes); err != nil {
return err
}
}
// Merge the membership state
m.mergeState(remoteNodes)
// Invoke the delegate for user state
if userBuf != nil && m.config.Delegate != nil {
m.config.Delegate.MergeRemoteState(userBuf, join)
}
return nil
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"mergeRemoteState",
"(",
"join",
"bool",
",",
"remoteNodes",
"[",
"]",
"pushNodeState",
",",
"userBuf",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"err",
":=",
"m",
".",
"verifyProtocol",
"(",
"remoteNodes",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"join",
"&&",
"m",
".",
"config",
".",
"Merge",
"!=",
"nil",
"{",
"nodes",
":=",
"make",
"(",
"[",
"]",
"*",
"Node",
",",
"len",
"(",
"remoteNodes",
")",
")",
"\n",
"for",
"idx",
",",
"n",
":=",
"range",
"remoteNodes",
"{",
"nodes",
"[",
"idx",
"]",
"=",
"&",
"Node",
"{",
"Name",
":",
"n",
".",
"Name",
",",
"Addr",
":",
"n",
".",
"Addr",
",",
"Port",
":",
"n",
".",
"Port",
",",
"Meta",
":",
"n",
".",
"Meta",
",",
"PMin",
":",
"n",
".",
"Vsn",
"[",
"0",
"]",
",",
"PMax",
":",
"n",
".",
"Vsn",
"[",
"1",
"]",
",",
"PCur",
":",
"n",
".",
"Vsn",
"[",
"2",
"]",
",",
"DMin",
":",
"n",
".",
"Vsn",
"[",
"3",
"]",
",",
"DMax",
":",
"n",
".",
"Vsn",
"[",
"4",
"]",
",",
"DCur",
":",
"n",
".",
"Vsn",
"[",
"5",
"]",
",",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"m",
".",
"config",
".",
"Merge",
".",
"NotifyMerge",
"(",
"nodes",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"m",
".",
"mergeState",
"(",
"remoteNodes",
")",
"\n",
"if",
"userBuf",
"!=",
"nil",
"&&",
"m",
".",
"config",
".",
"Delegate",
"!=",
"nil",
"{",
"m",
".",
"config",
".",
"Delegate",
".",
"MergeRemoteState",
"(",
"userBuf",
",",
"join",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// mergeRemoteState is used to merge the remote state with our local state
|
[
"mergeRemoteState",
"is",
"used",
"to",
"merge",
"the",
"remote",
"state",
"with",
"our",
"local",
"state"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L1039-L1074
|
train
|
hashicorp/memberlist
|
net.go
|
readUserMsg
|
func (m *Memberlist) readUserMsg(bufConn io.Reader, dec *codec.Decoder) error {
// Read the user message header
var header userMsgHeader
if err := dec.Decode(&header); err != nil {
return err
}
// Read the user message into a buffer
var userBuf []byte
if header.UserMsgLen > 0 {
userBuf = make([]byte, header.UserMsgLen)
bytes, err := io.ReadAtLeast(bufConn, userBuf, header.UserMsgLen)
if err == nil && bytes != header.UserMsgLen {
err = fmt.Errorf(
"Failed to read full user message (%d / %d)",
bytes, header.UserMsgLen)
}
if err != nil {
return err
}
d := m.config.Delegate
if d != nil {
d.NotifyMsg(userBuf)
}
}
return nil
}
|
go
|
func (m *Memberlist) readUserMsg(bufConn io.Reader, dec *codec.Decoder) error {
// Read the user message header
var header userMsgHeader
if err := dec.Decode(&header); err != nil {
return err
}
// Read the user message into a buffer
var userBuf []byte
if header.UserMsgLen > 0 {
userBuf = make([]byte, header.UserMsgLen)
bytes, err := io.ReadAtLeast(bufConn, userBuf, header.UserMsgLen)
if err == nil && bytes != header.UserMsgLen {
err = fmt.Errorf(
"Failed to read full user message (%d / %d)",
bytes, header.UserMsgLen)
}
if err != nil {
return err
}
d := m.config.Delegate
if d != nil {
d.NotifyMsg(userBuf)
}
}
return nil
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"readUserMsg",
"(",
"bufConn",
"io",
".",
"Reader",
",",
"dec",
"*",
"codec",
".",
"Decoder",
")",
"error",
"{",
"var",
"header",
"userMsgHeader",
"\n",
"if",
"err",
":=",
"dec",
".",
"Decode",
"(",
"&",
"header",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"var",
"userBuf",
"[",
"]",
"byte",
"\n",
"if",
"header",
".",
"UserMsgLen",
">",
"0",
"{",
"userBuf",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"header",
".",
"UserMsgLen",
")",
"\n",
"bytes",
",",
"err",
":=",
"io",
".",
"ReadAtLeast",
"(",
"bufConn",
",",
"userBuf",
",",
"header",
".",
"UserMsgLen",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"bytes",
"!=",
"header",
".",
"UserMsgLen",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"Failed to read full user message (%d / %d)\"",
",",
"bytes",
",",
"header",
".",
"UserMsgLen",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"d",
":=",
"m",
".",
"config",
".",
"Delegate",
"\n",
"if",
"d",
"!=",
"nil",
"{",
"d",
".",
"NotifyMsg",
"(",
"userBuf",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// readUserMsg is used to decode a userMsg from a stream.
|
[
"readUserMsg",
"is",
"used",
"to",
"decode",
"a",
"userMsg",
"from",
"a",
"stream",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L1077-L1105
|
train
|
hashicorp/memberlist
|
net.go
|
sendPingAndWaitForAck
|
func (m *Memberlist) sendPingAndWaitForAck(addr string, ping ping, deadline time.Time) (bool, error) {
conn, err := m.transport.DialTimeout(addr, deadline.Sub(time.Now()))
if err != nil {
// If the node is actually dead we expect this to fail, so we
// shouldn't spam the logs with it. After this point, errors
// with the connection are real, unexpected errors and should
// get propagated up.
return false, nil
}
defer conn.Close()
conn.SetDeadline(deadline)
out, err := encode(pingMsg, &ping)
if err != nil {
return false, err
}
if err = m.rawSendMsgStream(conn, out.Bytes()); err != nil {
return false, err
}
msgType, _, dec, err := m.readStream(conn)
if err != nil {
return false, err
}
if msgType != ackRespMsg {
return false, fmt.Errorf("Unexpected msgType (%d) from ping %s", msgType, LogConn(conn))
}
var ack ackResp
if err = dec.Decode(&ack); err != nil {
return false, err
}
if ack.SeqNo != ping.SeqNo {
return false, fmt.Errorf("Sequence number from ack (%d) doesn't match ping (%d)", ack.SeqNo, ping.SeqNo)
}
return true, nil
}
|
go
|
func (m *Memberlist) sendPingAndWaitForAck(addr string, ping ping, deadline time.Time) (bool, error) {
conn, err := m.transport.DialTimeout(addr, deadline.Sub(time.Now()))
if err != nil {
// If the node is actually dead we expect this to fail, so we
// shouldn't spam the logs with it. After this point, errors
// with the connection are real, unexpected errors and should
// get propagated up.
return false, nil
}
defer conn.Close()
conn.SetDeadline(deadline)
out, err := encode(pingMsg, &ping)
if err != nil {
return false, err
}
if err = m.rawSendMsgStream(conn, out.Bytes()); err != nil {
return false, err
}
msgType, _, dec, err := m.readStream(conn)
if err != nil {
return false, err
}
if msgType != ackRespMsg {
return false, fmt.Errorf("Unexpected msgType (%d) from ping %s", msgType, LogConn(conn))
}
var ack ackResp
if err = dec.Decode(&ack); err != nil {
return false, err
}
if ack.SeqNo != ping.SeqNo {
return false, fmt.Errorf("Sequence number from ack (%d) doesn't match ping (%d)", ack.SeqNo, ping.SeqNo)
}
return true, nil
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"sendPingAndWaitForAck",
"(",
"addr",
"string",
",",
"ping",
"ping",
",",
"deadline",
"time",
".",
"Time",
")",
"(",
"bool",
",",
"error",
")",
"{",
"conn",
",",
"err",
":=",
"m",
".",
"transport",
".",
"DialTimeout",
"(",
"addr",
",",
"deadline",
".",
"Sub",
"(",
"time",
".",
"Now",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"conn",
".",
"SetDeadline",
"(",
"deadline",
")",
"\n",
"out",
",",
"err",
":=",
"encode",
"(",
"pingMsg",
",",
"&",
"ping",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
"=",
"m",
".",
"rawSendMsgStream",
"(",
"conn",
",",
"out",
".",
"Bytes",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"msgType",
",",
"_",
",",
"dec",
",",
"err",
":=",
"m",
".",
"readStream",
"(",
"conn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"if",
"msgType",
"!=",
"ackRespMsg",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"Unexpected msgType (%d) from ping %s\"",
",",
"msgType",
",",
"LogConn",
"(",
"conn",
")",
")",
"\n",
"}",
"\n",
"var",
"ack",
"ackResp",
"\n",
"if",
"err",
"=",
"dec",
".",
"Decode",
"(",
"&",
"ack",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"if",
"ack",
".",
"SeqNo",
"!=",
"ping",
".",
"SeqNo",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"Sequence number from ack (%d) doesn't match ping (%d)\"",
",",
"ack",
".",
"SeqNo",
",",
"ping",
".",
"SeqNo",
")",
"\n",
"}",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] |
// sendPingAndWaitForAck makes a stream connection to the given address, sends
// a ping, and waits for an ack. All of this is done as a series of blocking
// operations, given the deadline. The bool return parameter is true if we
// we able to round trip a ping to the other node.
|
[
"sendPingAndWaitForAck",
"makes",
"a",
"stream",
"connection",
"to",
"the",
"given",
"address",
"sends",
"a",
"ping",
"and",
"waits",
"for",
"an",
"ack",
".",
"All",
"of",
"this",
"is",
"done",
"as",
"a",
"series",
"of",
"blocking",
"operations",
"given",
"the",
"deadline",
".",
"The",
"bool",
"return",
"parameter",
"is",
"true",
"if",
"we",
"we",
"able",
"to",
"round",
"trip",
"a",
"ping",
"to",
"the",
"other",
"node",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/net.go#L1111-L1151
|
train
|
hashicorp/memberlist
|
security.go
|
pkcs7encode
|
func pkcs7encode(buf *bytes.Buffer, ignore, blockSize int) {
n := buf.Len() - ignore
more := blockSize - (n % blockSize)
for i := 0; i < more; i++ {
buf.WriteByte(byte(more))
}
}
|
go
|
func pkcs7encode(buf *bytes.Buffer, ignore, blockSize int) {
n := buf.Len() - ignore
more := blockSize - (n % blockSize)
for i := 0; i < more; i++ {
buf.WriteByte(byte(more))
}
}
|
[
"func",
"pkcs7encode",
"(",
"buf",
"*",
"bytes",
".",
"Buffer",
",",
"ignore",
",",
"blockSize",
"int",
")",
"{",
"n",
":=",
"buf",
".",
"Len",
"(",
")",
"-",
"ignore",
"\n",
"more",
":=",
"blockSize",
"-",
"(",
"n",
"%",
"blockSize",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"more",
";",
"i",
"++",
"{",
"buf",
".",
"WriteByte",
"(",
"byte",
"(",
"more",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// pkcs7encode is used to pad a byte buffer to a specific block size using
// the PKCS7 algorithm. "Ignores" some bytes to compensate for IV
|
[
"pkcs7encode",
"is",
"used",
"to",
"pad",
"a",
"byte",
"buffer",
"to",
"a",
"specific",
"block",
"size",
"using",
"the",
"PKCS7",
"algorithm",
".",
"Ignores",
"some",
"bytes",
"to",
"compensate",
"for",
"IV"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/security.go#L39-L45
|
train
|
hashicorp/memberlist
|
security.go
|
pkcs7decode
|
func pkcs7decode(buf []byte, blockSize int) []byte {
if len(buf) == 0 {
panic("Cannot decode a PKCS7 buffer of zero length")
}
n := len(buf)
last := buf[n-1]
n -= int(last)
return buf[:n]
}
|
go
|
func pkcs7decode(buf []byte, blockSize int) []byte {
if len(buf) == 0 {
panic("Cannot decode a PKCS7 buffer of zero length")
}
n := len(buf)
last := buf[n-1]
n -= int(last)
return buf[:n]
}
|
[
"func",
"pkcs7decode",
"(",
"buf",
"[",
"]",
"byte",
",",
"blockSize",
"int",
")",
"[",
"]",
"byte",
"{",
"if",
"len",
"(",
"buf",
")",
"==",
"0",
"{",
"panic",
"(",
"\"Cannot decode a PKCS7 buffer of zero length\"",
")",
"\n",
"}",
"\n",
"n",
":=",
"len",
"(",
"buf",
")",
"\n",
"last",
":=",
"buf",
"[",
"n",
"-",
"1",
"]",
"\n",
"n",
"-=",
"int",
"(",
"last",
")",
"\n",
"return",
"buf",
"[",
":",
"n",
"]",
"\n",
"}"
] |
// pkcs7decode is used to decode a buffer that has been padded
|
[
"pkcs7decode",
"is",
"used",
"to",
"decode",
"a",
"buffer",
"that",
"has",
"been",
"padded"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/security.go#L48-L56
|
train
|
hashicorp/memberlist
|
security.go
|
encryptedLength
|
func encryptedLength(vsn encryptionVersion, inp int) int {
// If we are on version 1, there is no padding
if vsn >= 1 {
return versionSize + nonceSize + inp + tagSize
}
// Determine the padding size
padding := blockSize - (inp % blockSize)
// Sum the extra parts to get total size
return versionSize + nonceSize + inp + padding + tagSize
}
|
go
|
func encryptedLength(vsn encryptionVersion, inp int) int {
// If we are on version 1, there is no padding
if vsn >= 1 {
return versionSize + nonceSize + inp + tagSize
}
// Determine the padding size
padding := blockSize - (inp % blockSize)
// Sum the extra parts to get total size
return versionSize + nonceSize + inp + padding + tagSize
}
|
[
"func",
"encryptedLength",
"(",
"vsn",
"encryptionVersion",
",",
"inp",
"int",
")",
"int",
"{",
"if",
"vsn",
">=",
"1",
"{",
"return",
"versionSize",
"+",
"nonceSize",
"+",
"inp",
"+",
"tagSize",
"\n",
"}",
"\n",
"padding",
":=",
"blockSize",
"-",
"(",
"inp",
"%",
"blockSize",
")",
"\n",
"return",
"versionSize",
"+",
"nonceSize",
"+",
"inp",
"+",
"padding",
"+",
"tagSize",
"\n",
"}"
] |
// encryptedLength is used to compute the buffer size needed
// for a message of given length
|
[
"encryptedLength",
"is",
"used",
"to",
"compute",
"the",
"buffer",
"size",
"needed",
"for",
"a",
"message",
"of",
"given",
"length"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/security.go#L72-L83
|
train
|
hashicorp/memberlist
|
security.go
|
encryptPayload
|
func encryptPayload(vsn encryptionVersion, key []byte, msg []byte, data []byte, dst *bytes.Buffer) error {
// Get the AES block cipher
aesBlock, err := aes.NewCipher(key)
if err != nil {
return err
}
// Get the GCM cipher mode
gcm, err := cipher.NewGCM(aesBlock)
if err != nil {
return err
}
// Grow the buffer to make room for everything
offset := dst.Len()
dst.Grow(encryptedLength(vsn, len(msg)))
// Write the encryption version
dst.WriteByte(byte(vsn))
// Add a random nonce
io.CopyN(dst, rand.Reader, nonceSize)
afterNonce := dst.Len()
// Ensure we are correctly padded (only version 0)
if vsn == 0 {
io.Copy(dst, bytes.NewReader(msg))
pkcs7encode(dst, offset+versionSize+nonceSize, aes.BlockSize)
}
// Encrypt message using GCM
slice := dst.Bytes()[offset:]
nonce := slice[versionSize : versionSize+nonceSize]
// Message source depends on the encryption version.
// Version 0 uses padding, version 1 does not
var src []byte
if vsn == 0 {
src = slice[versionSize+nonceSize:]
} else {
src = msg
}
out := gcm.Seal(nil, nonce, src, data)
// Truncate the plaintext, and write the cipher text
dst.Truncate(afterNonce)
dst.Write(out)
return nil
}
|
go
|
func encryptPayload(vsn encryptionVersion, key []byte, msg []byte, data []byte, dst *bytes.Buffer) error {
// Get the AES block cipher
aesBlock, err := aes.NewCipher(key)
if err != nil {
return err
}
// Get the GCM cipher mode
gcm, err := cipher.NewGCM(aesBlock)
if err != nil {
return err
}
// Grow the buffer to make room for everything
offset := dst.Len()
dst.Grow(encryptedLength(vsn, len(msg)))
// Write the encryption version
dst.WriteByte(byte(vsn))
// Add a random nonce
io.CopyN(dst, rand.Reader, nonceSize)
afterNonce := dst.Len()
// Ensure we are correctly padded (only version 0)
if vsn == 0 {
io.Copy(dst, bytes.NewReader(msg))
pkcs7encode(dst, offset+versionSize+nonceSize, aes.BlockSize)
}
// Encrypt message using GCM
slice := dst.Bytes()[offset:]
nonce := slice[versionSize : versionSize+nonceSize]
// Message source depends on the encryption version.
// Version 0 uses padding, version 1 does not
var src []byte
if vsn == 0 {
src = slice[versionSize+nonceSize:]
} else {
src = msg
}
out := gcm.Seal(nil, nonce, src, data)
// Truncate the plaintext, and write the cipher text
dst.Truncate(afterNonce)
dst.Write(out)
return nil
}
|
[
"func",
"encryptPayload",
"(",
"vsn",
"encryptionVersion",
",",
"key",
"[",
"]",
"byte",
",",
"msg",
"[",
"]",
"byte",
",",
"data",
"[",
"]",
"byte",
",",
"dst",
"*",
"bytes",
".",
"Buffer",
")",
"error",
"{",
"aesBlock",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"gcm",
",",
"err",
":=",
"cipher",
".",
"NewGCM",
"(",
"aesBlock",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"offset",
":=",
"dst",
".",
"Len",
"(",
")",
"\n",
"dst",
".",
"Grow",
"(",
"encryptedLength",
"(",
"vsn",
",",
"len",
"(",
"msg",
")",
")",
")",
"\n",
"dst",
".",
"WriteByte",
"(",
"byte",
"(",
"vsn",
")",
")",
"\n",
"io",
".",
"CopyN",
"(",
"dst",
",",
"rand",
".",
"Reader",
",",
"nonceSize",
")",
"\n",
"afterNonce",
":=",
"dst",
".",
"Len",
"(",
")",
"\n",
"if",
"vsn",
"==",
"0",
"{",
"io",
".",
"Copy",
"(",
"dst",
",",
"bytes",
".",
"NewReader",
"(",
"msg",
")",
")",
"\n",
"pkcs7encode",
"(",
"dst",
",",
"offset",
"+",
"versionSize",
"+",
"nonceSize",
",",
"aes",
".",
"BlockSize",
")",
"\n",
"}",
"\n",
"slice",
":=",
"dst",
".",
"Bytes",
"(",
")",
"[",
"offset",
":",
"]",
"\n",
"nonce",
":=",
"slice",
"[",
"versionSize",
":",
"versionSize",
"+",
"nonceSize",
"]",
"\n",
"var",
"src",
"[",
"]",
"byte",
"\n",
"if",
"vsn",
"==",
"0",
"{",
"src",
"=",
"slice",
"[",
"versionSize",
"+",
"nonceSize",
":",
"]",
"\n",
"}",
"else",
"{",
"src",
"=",
"msg",
"\n",
"}",
"\n",
"out",
":=",
"gcm",
".",
"Seal",
"(",
"nil",
",",
"nonce",
",",
"src",
",",
"data",
")",
"\n",
"dst",
".",
"Truncate",
"(",
"afterNonce",
")",
"\n",
"dst",
".",
"Write",
"(",
"out",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// encryptPayload is used to encrypt a message with a given key.
// We make use of AES-128 in GCM mode. New byte buffer is the version,
// nonce, ciphertext and tag
|
[
"encryptPayload",
"is",
"used",
"to",
"encrypt",
"a",
"message",
"with",
"a",
"given",
"key",
".",
"We",
"make",
"use",
"of",
"AES",
"-",
"128",
"in",
"GCM",
"mode",
".",
"New",
"byte",
"buffer",
"is",
"the",
"version",
"nonce",
"ciphertext",
"and",
"tag"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/security.go#L88-L136
|
train
|
hashicorp/memberlist
|
security.go
|
decryptMessage
|
func decryptMessage(key, msg []byte, data []byte) ([]byte, error) {
// Get the AES block cipher
aesBlock, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// Get the GCM cipher mode
gcm, err := cipher.NewGCM(aesBlock)
if err != nil {
return nil, err
}
// Decrypt the message
nonce := msg[versionSize : versionSize+nonceSize]
ciphertext := msg[versionSize+nonceSize:]
plain, err := gcm.Open(nil, nonce, ciphertext, data)
if err != nil {
return nil, err
}
// Success!
return plain, nil
}
|
go
|
func decryptMessage(key, msg []byte, data []byte) ([]byte, error) {
// Get the AES block cipher
aesBlock, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// Get the GCM cipher mode
gcm, err := cipher.NewGCM(aesBlock)
if err != nil {
return nil, err
}
// Decrypt the message
nonce := msg[versionSize : versionSize+nonceSize]
ciphertext := msg[versionSize+nonceSize:]
plain, err := gcm.Open(nil, nonce, ciphertext, data)
if err != nil {
return nil, err
}
// Success!
return plain, nil
}
|
[
"func",
"decryptMessage",
"(",
"key",
",",
"msg",
"[",
"]",
"byte",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"aesBlock",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"gcm",
",",
"err",
":=",
"cipher",
".",
"NewGCM",
"(",
"aesBlock",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"nonce",
":=",
"msg",
"[",
"versionSize",
":",
"versionSize",
"+",
"nonceSize",
"]",
"\n",
"ciphertext",
":=",
"msg",
"[",
"versionSize",
"+",
"nonceSize",
":",
"]",
"\n",
"plain",
",",
"err",
":=",
"gcm",
".",
"Open",
"(",
"nil",
",",
"nonce",
",",
"ciphertext",
",",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"plain",
",",
"nil",
"\n",
"}"
] |
// decryptMessage performs the actual decryption of ciphertext. This is in its
// own function to allow it to be called on all keys easily.
|
[
"decryptMessage",
"performs",
"the",
"actual",
"decryption",
"of",
"ciphertext",
".",
"This",
"is",
"in",
"its",
"own",
"function",
"to",
"allow",
"it",
"to",
"be",
"called",
"on",
"all",
"keys",
"easily",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/security.go#L140-L163
|
train
|
hashicorp/memberlist
|
security.go
|
decryptPayload
|
func decryptPayload(keys [][]byte, msg []byte, data []byte) ([]byte, error) {
// Ensure we have at least one byte
if len(msg) == 0 {
return nil, fmt.Errorf("Cannot decrypt empty payload")
}
// Verify the version
vsn := encryptionVersion(msg[0])
if vsn > maxEncryptionVersion {
return nil, fmt.Errorf("Unsupported encryption version %d", msg[0])
}
// Ensure the length is sane
if len(msg) < encryptedLength(vsn, 0) {
return nil, fmt.Errorf("Payload is too small to decrypt: %d", len(msg))
}
for _, key := range keys {
plain, err := decryptMessage(key, msg, data)
if err == nil {
// Remove the PKCS7 padding for vsn 0
if vsn == 0 {
return pkcs7decode(plain, aes.BlockSize), nil
} else {
return plain, nil
}
}
}
return nil, fmt.Errorf("No installed keys could decrypt the message")
}
|
go
|
func decryptPayload(keys [][]byte, msg []byte, data []byte) ([]byte, error) {
// Ensure we have at least one byte
if len(msg) == 0 {
return nil, fmt.Errorf("Cannot decrypt empty payload")
}
// Verify the version
vsn := encryptionVersion(msg[0])
if vsn > maxEncryptionVersion {
return nil, fmt.Errorf("Unsupported encryption version %d", msg[0])
}
// Ensure the length is sane
if len(msg) < encryptedLength(vsn, 0) {
return nil, fmt.Errorf("Payload is too small to decrypt: %d", len(msg))
}
for _, key := range keys {
plain, err := decryptMessage(key, msg, data)
if err == nil {
// Remove the PKCS7 padding for vsn 0
if vsn == 0 {
return pkcs7decode(plain, aes.BlockSize), nil
} else {
return plain, nil
}
}
}
return nil, fmt.Errorf("No installed keys could decrypt the message")
}
|
[
"func",
"decryptPayload",
"(",
"keys",
"[",
"]",
"[",
"]",
"byte",
",",
"msg",
"[",
"]",
"byte",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"len",
"(",
"msg",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Cannot decrypt empty payload\"",
")",
"\n",
"}",
"\n",
"vsn",
":=",
"encryptionVersion",
"(",
"msg",
"[",
"0",
"]",
")",
"\n",
"if",
"vsn",
">",
"maxEncryptionVersion",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Unsupported encryption version %d\"",
",",
"msg",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"msg",
")",
"<",
"encryptedLength",
"(",
"vsn",
",",
"0",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Payload is too small to decrypt: %d\"",
",",
"len",
"(",
"msg",
")",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"{",
"plain",
",",
"err",
":=",
"decryptMessage",
"(",
"key",
",",
"msg",
",",
"data",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"if",
"vsn",
"==",
"0",
"{",
"return",
"pkcs7decode",
"(",
"plain",
",",
"aes",
".",
"BlockSize",
")",
",",
"nil",
"\n",
"}",
"else",
"{",
"return",
"plain",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"No installed keys could decrypt the message\"",
")",
"\n",
"}"
] |
// decryptPayload is used to decrypt a message with a given key,
// and verify it's contents. Any padding will be removed, and a
// slice to the plaintext is returned. Decryption is done IN PLACE!
|
[
"decryptPayload",
"is",
"used",
"to",
"decrypt",
"a",
"message",
"with",
"a",
"given",
"key",
"and",
"verify",
"it",
"s",
"contents",
".",
"Any",
"padding",
"will",
"be",
"removed",
"and",
"a",
"slice",
"to",
"the",
"plaintext",
"is",
"returned",
".",
"Decryption",
"is",
"done",
"IN",
"PLACE!"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/security.go#L168-L198
|
train
|
hashicorp/memberlist
|
state.go
|
schedule
|
func (m *Memberlist) schedule() {
m.tickerLock.Lock()
defer m.tickerLock.Unlock()
// If we already have tickers, then don't do anything, since we're
// scheduled
if len(m.tickers) > 0 {
return
}
// Create the stop tick channel, a blocking channel. We close this
// when we should stop the tickers.
stopCh := make(chan struct{})
// Create a new probeTicker
if m.config.ProbeInterval > 0 {
t := time.NewTicker(m.config.ProbeInterval)
go m.triggerFunc(m.config.ProbeInterval, t.C, stopCh, m.probe)
m.tickers = append(m.tickers, t)
}
// Create a push pull ticker if needed
if m.config.PushPullInterval > 0 {
go m.pushPullTrigger(stopCh)
}
// Create a gossip ticker if needed
if m.config.GossipInterval > 0 && m.config.GossipNodes > 0 {
t := time.NewTicker(m.config.GossipInterval)
go m.triggerFunc(m.config.GossipInterval, t.C, stopCh, m.gossip)
m.tickers = append(m.tickers, t)
}
// If we made any tickers, then record the stopTick channel for
// later.
if len(m.tickers) > 0 {
m.stopTick = stopCh
}
}
|
go
|
func (m *Memberlist) schedule() {
m.tickerLock.Lock()
defer m.tickerLock.Unlock()
// If we already have tickers, then don't do anything, since we're
// scheduled
if len(m.tickers) > 0 {
return
}
// Create the stop tick channel, a blocking channel. We close this
// when we should stop the tickers.
stopCh := make(chan struct{})
// Create a new probeTicker
if m.config.ProbeInterval > 0 {
t := time.NewTicker(m.config.ProbeInterval)
go m.triggerFunc(m.config.ProbeInterval, t.C, stopCh, m.probe)
m.tickers = append(m.tickers, t)
}
// Create a push pull ticker if needed
if m.config.PushPullInterval > 0 {
go m.pushPullTrigger(stopCh)
}
// Create a gossip ticker if needed
if m.config.GossipInterval > 0 && m.config.GossipNodes > 0 {
t := time.NewTicker(m.config.GossipInterval)
go m.triggerFunc(m.config.GossipInterval, t.C, stopCh, m.gossip)
m.tickers = append(m.tickers, t)
}
// If we made any tickers, then record the stopTick channel for
// later.
if len(m.tickers) > 0 {
m.stopTick = stopCh
}
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"schedule",
"(",
")",
"{",
"m",
".",
"tickerLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"tickerLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"len",
"(",
"m",
".",
"tickers",
")",
">",
"0",
"{",
"return",
"\n",
"}",
"\n",
"stopCh",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"if",
"m",
".",
"config",
".",
"ProbeInterval",
">",
"0",
"{",
"t",
":=",
"time",
".",
"NewTicker",
"(",
"m",
".",
"config",
".",
"ProbeInterval",
")",
"\n",
"go",
"m",
".",
"triggerFunc",
"(",
"m",
".",
"config",
".",
"ProbeInterval",
",",
"t",
".",
"C",
",",
"stopCh",
",",
"m",
".",
"probe",
")",
"\n",
"m",
".",
"tickers",
"=",
"append",
"(",
"m",
".",
"tickers",
",",
"t",
")",
"\n",
"}",
"\n",
"if",
"m",
".",
"config",
".",
"PushPullInterval",
">",
"0",
"{",
"go",
"m",
".",
"pushPullTrigger",
"(",
"stopCh",
")",
"\n",
"}",
"\n",
"if",
"m",
".",
"config",
".",
"GossipInterval",
">",
"0",
"&&",
"m",
".",
"config",
".",
"GossipNodes",
">",
"0",
"{",
"t",
":=",
"time",
".",
"NewTicker",
"(",
"m",
".",
"config",
".",
"GossipInterval",
")",
"\n",
"go",
"m",
".",
"triggerFunc",
"(",
"m",
".",
"config",
".",
"GossipInterval",
",",
"t",
".",
"C",
",",
"stopCh",
",",
"m",
".",
"gossip",
")",
"\n",
"m",
".",
"tickers",
"=",
"append",
"(",
"m",
".",
"tickers",
",",
"t",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"m",
".",
"tickers",
")",
">",
"0",
"{",
"m",
".",
"stopTick",
"=",
"stopCh",
"\n",
"}",
"\n",
"}"
] |
// Schedule is used to ensure the Tick is performed periodically. This
// function is safe to call multiple times. If the memberlist is already
// scheduled, then it won't do anything.
|
[
"Schedule",
"is",
"used",
"to",
"ensure",
"the",
"Tick",
"is",
"performed",
"periodically",
".",
"This",
"function",
"is",
"safe",
"to",
"call",
"multiple",
"times",
".",
"If",
"the",
"memberlist",
"is",
"already",
"scheduled",
"then",
"it",
"won",
"t",
"do",
"anything",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L82-L120
|
train
|
hashicorp/memberlist
|
state.go
|
triggerFunc
|
func (m *Memberlist) triggerFunc(stagger time.Duration, C <-chan time.Time, stop <-chan struct{}, f func()) {
// Use a random stagger to avoid syncronizing
randStagger := time.Duration(uint64(rand.Int63()) % uint64(stagger))
select {
case <-time.After(randStagger):
case <-stop:
return
}
for {
select {
case <-C:
f()
case <-stop:
return
}
}
}
|
go
|
func (m *Memberlist) triggerFunc(stagger time.Duration, C <-chan time.Time, stop <-chan struct{}, f func()) {
// Use a random stagger to avoid syncronizing
randStagger := time.Duration(uint64(rand.Int63()) % uint64(stagger))
select {
case <-time.After(randStagger):
case <-stop:
return
}
for {
select {
case <-C:
f()
case <-stop:
return
}
}
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"triggerFunc",
"(",
"stagger",
"time",
".",
"Duration",
",",
"C",
"<-",
"chan",
"time",
".",
"Time",
",",
"stop",
"<-",
"chan",
"struct",
"{",
"}",
",",
"f",
"func",
"(",
")",
")",
"{",
"randStagger",
":=",
"time",
".",
"Duration",
"(",
"uint64",
"(",
"rand",
".",
"Int63",
"(",
")",
")",
"%",
"uint64",
"(",
"stagger",
")",
")",
"\n",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"randStagger",
")",
":",
"case",
"<-",
"stop",
":",
"return",
"\n",
"}",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"C",
":",
"f",
"(",
")",
"\n",
"case",
"<-",
"stop",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// triggerFunc is used to trigger a function call each time a
// message is received until a stop tick arrives.
|
[
"triggerFunc",
"is",
"used",
"to",
"trigger",
"a",
"function",
"call",
"each",
"time",
"a",
"message",
"is",
"received",
"until",
"a",
"stop",
"tick",
"arrives",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L124-L140
|
train
|
hashicorp/memberlist
|
state.go
|
deschedule
|
func (m *Memberlist) deschedule() {
m.tickerLock.Lock()
defer m.tickerLock.Unlock()
// If we have no tickers, then we aren't scheduled.
if len(m.tickers) == 0 {
return
}
// Close the stop channel so all the ticker listeners stop.
close(m.stopTick)
// Explicitly stop all the tickers themselves so they don't take
// up any more resources, and get rid of the list.
for _, t := range m.tickers {
t.Stop()
}
m.tickers = nil
}
|
go
|
func (m *Memberlist) deschedule() {
m.tickerLock.Lock()
defer m.tickerLock.Unlock()
// If we have no tickers, then we aren't scheduled.
if len(m.tickers) == 0 {
return
}
// Close the stop channel so all the ticker listeners stop.
close(m.stopTick)
// Explicitly stop all the tickers themselves so they don't take
// up any more resources, and get rid of the list.
for _, t := range m.tickers {
t.Stop()
}
m.tickers = nil
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"deschedule",
"(",
")",
"{",
"m",
".",
"tickerLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"tickerLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"len",
"(",
"m",
".",
"tickers",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"close",
"(",
"m",
".",
"stopTick",
")",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"m",
".",
"tickers",
"{",
"t",
".",
"Stop",
"(",
")",
"\n",
"}",
"\n",
"m",
".",
"tickers",
"=",
"nil",
"\n",
"}"
] |
// Deschedule is used to stop the background maintenance. This is safe
// to call multiple times.
|
[
"Deschedule",
"is",
"used",
"to",
"stop",
"the",
"background",
"maintenance",
".",
"This",
"is",
"safe",
"to",
"call",
"multiple",
"times",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L171-L189
|
train
|
hashicorp/memberlist
|
state.go
|
probe
|
func (m *Memberlist) probe() {
// Track the number of indexes we've considered probing
numCheck := 0
START:
m.nodeLock.RLock()
// Make sure we don't wrap around infinitely
if numCheck >= len(m.nodes) {
m.nodeLock.RUnlock()
return
}
// Handle the wrap around case
if m.probeIndex >= len(m.nodes) {
m.nodeLock.RUnlock()
m.resetNodes()
m.probeIndex = 0
numCheck++
goto START
}
// Determine if we should probe this node
skip := false
var node nodeState
node = *m.nodes[m.probeIndex]
if node.Name == m.config.Name {
skip = true
} else if node.State == stateDead {
skip = true
}
// Potentially skip
m.nodeLock.RUnlock()
m.probeIndex++
if skip {
numCheck++
goto START
}
// Probe the specific node
m.probeNode(&node)
}
|
go
|
func (m *Memberlist) probe() {
// Track the number of indexes we've considered probing
numCheck := 0
START:
m.nodeLock.RLock()
// Make sure we don't wrap around infinitely
if numCheck >= len(m.nodes) {
m.nodeLock.RUnlock()
return
}
// Handle the wrap around case
if m.probeIndex >= len(m.nodes) {
m.nodeLock.RUnlock()
m.resetNodes()
m.probeIndex = 0
numCheck++
goto START
}
// Determine if we should probe this node
skip := false
var node nodeState
node = *m.nodes[m.probeIndex]
if node.Name == m.config.Name {
skip = true
} else if node.State == stateDead {
skip = true
}
// Potentially skip
m.nodeLock.RUnlock()
m.probeIndex++
if skip {
numCheck++
goto START
}
// Probe the specific node
m.probeNode(&node)
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"probe",
"(",
")",
"{",
"numCheck",
":=",
"0",
"\n",
"START",
":",
"m",
".",
"nodeLock",
".",
"RLock",
"(",
")",
"\n",
"if",
"numCheck",
">=",
"len",
"(",
"m",
".",
"nodes",
")",
"{",
"m",
".",
"nodeLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"m",
".",
"probeIndex",
">=",
"len",
"(",
"m",
".",
"nodes",
")",
"{",
"m",
".",
"nodeLock",
".",
"RUnlock",
"(",
")",
"\n",
"m",
".",
"resetNodes",
"(",
")",
"\n",
"m",
".",
"probeIndex",
"=",
"0",
"\n",
"numCheck",
"++",
"\n",
"goto",
"START",
"\n",
"}",
"\n",
"skip",
":=",
"false",
"\n",
"var",
"node",
"nodeState",
"\n",
"node",
"=",
"*",
"m",
".",
"nodes",
"[",
"m",
".",
"probeIndex",
"]",
"\n",
"if",
"node",
".",
"Name",
"==",
"m",
".",
"config",
".",
"Name",
"{",
"skip",
"=",
"true",
"\n",
"}",
"else",
"if",
"node",
".",
"State",
"==",
"stateDead",
"{",
"skip",
"=",
"true",
"\n",
"}",
"\n",
"m",
".",
"nodeLock",
".",
"RUnlock",
"(",
")",
"\n",
"m",
".",
"probeIndex",
"++",
"\n",
"if",
"skip",
"{",
"numCheck",
"++",
"\n",
"goto",
"START",
"\n",
"}",
"\n",
"m",
".",
"probeNode",
"(",
"&",
"node",
")",
"\n",
"}"
] |
// Tick is used to perform a single round of failure detection and gossip
|
[
"Tick",
"is",
"used",
"to",
"perform",
"a",
"single",
"round",
"of",
"failure",
"detection",
"and",
"gossip"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L192-L234
|
train
|
hashicorp/memberlist
|
state.go
|
Ping
|
func (m *Memberlist) Ping(node string, addr net.Addr) (time.Duration, error) {
// Prepare a ping message and setup an ack handler.
ping := ping{SeqNo: m.nextSeqNo(), Node: node}
ackCh := make(chan ackMessage, m.config.IndirectChecks+1)
m.setProbeChannels(ping.SeqNo, ackCh, nil, m.config.ProbeInterval)
// Send a ping to the node.
if err := m.encodeAndSendMsg(addr.String(), pingMsg, &ping); err != nil {
return 0, err
}
// Mark the sent time here, which should be after any pre-processing and
// system calls to do the actual send. This probably under-reports a bit,
// but it's the best we can do.
sent := time.Now()
// Wait for response or timeout.
select {
case v := <-ackCh:
if v.Complete == true {
return v.Timestamp.Sub(sent), nil
}
case <-time.After(m.config.ProbeTimeout):
// Timeout, return an error below.
}
m.logger.Printf("[DEBUG] memberlist: Failed UDP ping: %v (timeout reached)", node)
return 0, NoPingResponseError{ping.Node}
}
|
go
|
func (m *Memberlist) Ping(node string, addr net.Addr) (time.Duration, error) {
// Prepare a ping message and setup an ack handler.
ping := ping{SeqNo: m.nextSeqNo(), Node: node}
ackCh := make(chan ackMessage, m.config.IndirectChecks+1)
m.setProbeChannels(ping.SeqNo, ackCh, nil, m.config.ProbeInterval)
// Send a ping to the node.
if err := m.encodeAndSendMsg(addr.String(), pingMsg, &ping); err != nil {
return 0, err
}
// Mark the sent time here, which should be after any pre-processing and
// system calls to do the actual send. This probably under-reports a bit,
// but it's the best we can do.
sent := time.Now()
// Wait for response or timeout.
select {
case v := <-ackCh:
if v.Complete == true {
return v.Timestamp.Sub(sent), nil
}
case <-time.After(m.config.ProbeTimeout):
// Timeout, return an error below.
}
m.logger.Printf("[DEBUG] memberlist: Failed UDP ping: %v (timeout reached)", node)
return 0, NoPingResponseError{ping.Node}
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"Ping",
"(",
"node",
"string",
",",
"addr",
"net",
".",
"Addr",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"ping",
":=",
"ping",
"{",
"SeqNo",
":",
"m",
".",
"nextSeqNo",
"(",
")",
",",
"Node",
":",
"node",
"}",
"\n",
"ackCh",
":=",
"make",
"(",
"chan",
"ackMessage",
",",
"m",
".",
"config",
".",
"IndirectChecks",
"+",
"1",
")",
"\n",
"m",
".",
"setProbeChannels",
"(",
"ping",
".",
"SeqNo",
",",
"ackCh",
",",
"nil",
",",
"m",
".",
"config",
".",
"ProbeInterval",
")",
"\n",
"if",
"err",
":=",
"m",
".",
"encodeAndSendMsg",
"(",
"addr",
".",
"String",
"(",
")",
",",
"pingMsg",
",",
"&",
"ping",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"sent",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"select",
"{",
"case",
"v",
":=",
"<-",
"ackCh",
":",
"if",
"v",
".",
"Complete",
"==",
"true",
"{",
"return",
"v",
".",
"Timestamp",
".",
"Sub",
"(",
"sent",
")",
",",
"nil",
"\n",
"}",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"m",
".",
"config",
".",
"ProbeTimeout",
")",
":",
"}",
"\n",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[DEBUG] memberlist: Failed UDP ping: %v (timeout reached)\"",
",",
"node",
")",
"\n",
"return",
"0",
",",
"NoPingResponseError",
"{",
"ping",
".",
"Node",
"}",
"\n",
"}"
] |
// Ping initiates a ping to the node with the specified name.
|
[
"Ping",
"initiates",
"a",
"ping",
"to",
"the",
"node",
"with",
"the",
"specified",
"name",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L432-L460
|
train
|
hashicorp/memberlist
|
state.go
|
resetNodes
|
func (m *Memberlist) resetNodes() {
m.nodeLock.Lock()
defer m.nodeLock.Unlock()
// Move dead nodes, but respect gossip to the dead interval
deadIdx := moveDeadNodes(m.nodes, m.config.GossipToTheDeadTime)
// Deregister the dead nodes
for i := deadIdx; i < len(m.nodes); i++ {
delete(m.nodeMap, m.nodes[i].Name)
m.nodes[i] = nil
}
// Trim the nodes to exclude the dead nodes
m.nodes = m.nodes[0:deadIdx]
// Update numNodes after we've trimmed the dead nodes
atomic.StoreUint32(&m.numNodes, uint32(deadIdx))
// Shuffle live nodes
shuffleNodes(m.nodes)
}
|
go
|
func (m *Memberlist) resetNodes() {
m.nodeLock.Lock()
defer m.nodeLock.Unlock()
// Move dead nodes, but respect gossip to the dead interval
deadIdx := moveDeadNodes(m.nodes, m.config.GossipToTheDeadTime)
// Deregister the dead nodes
for i := deadIdx; i < len(m.nodes); i++ {
delete(m.nodeMap, m.nodes[i].Name)
m.nodes[i] = nil
}
// Trim the nodes to exclude the dead nodes
m.nodes = m.nodes[0:deadIdx]
// Update numNodes after we've trimmed the dead nodes
atomic.StoreUint32(&m.numNodes, uint32(deadIdx))
// Shuffle live nodes
shuffleNodes(m.nodes)
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"resetNodes",
"(",
")",
"{",
"m",
".",
"nodeLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"nodeLock",
".",
"Unlock",
"(",
")",
"\n",
"deadIdx",
":=",
"moveDeadNodes",
"(",
"m",
".",
"nodes",
",",
"m",
".",
"config",
".",
"GossipToTheDeadTime",
")",
"\n",
"for",
"i",
":=",
"deadIdx",
";",
"i",
"<",
"len",
"(",
"m",
".",
"nodes",
")",
";",
"i",
"++",
"{",
"delete",
"(",
"m",
".",
"nodeMap",
",",
"m",
".",
"nodes",
"[",
"i",
"]",
".",
"Name",
")",
"\n",
"m",
".",
"nodes",
"[",
"i",
"]",
"=",
"nil",
"\n",
"}",
"\n",
"m",
".",
"nodes",
"=",
"m",
".",
"nodes",
"[",
"0",
":",
"deadIdx",
"]",
"\n",
"atomic",
".",
"StoreUint32",
"(",
"&",
"m",
".",
"numNodes",
",",
"uint32",
"(",
"deadIdx",
")",
")",
"\n",
"shuffleNodes",
"(",
"m",
".",
"nodes",
")",
"\n",
"}"
] |
// resetNodes is used when the tick wraps around. It will reap the
// dead nodes and shuffle the node list.
|
[
"resetNodes",
"is",
"used",
"when",
"the",
"tick",
"wraps",
"around",
".",
"It",
"will",
"reap",
"the",
"dead",
"nodes",
"and",
"shuffle",
"the",
"node",
"list",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L464-L485
|
train
|
hashicorp/memberlist
|
state.go
|
gossip
|
func (m *Memberlist) gossip() {
defer metrics.MeasureSince([]string{"memberlist", "gossip"}, time.Now())
// Get some random live, suspect, or recently dead nodes
m.nodeLock.RLock()
kNodes := kRandomNodes(m.config.GossipNodes, m.nodes, func(n *nodeState) bool {
if n.Name == m.config.Name {
return true
}
switch n.State {
case stateAlive, stateSuspect:
return false
case stateDead:
return time.Since(n.StateChange) > m.config.GossipToTheDeadTime
default:
return true
}
})
m.nodeLock.RUnlock()
// Compute the bytes available
bytesAvail := m.config.UDPBufferSize - compoundHeaderOverhead
if m.config.EncryptionEnabled() {
bytesAvail -= encryptOverhead(m.encryptionVersion())
}
for _, node := range kNodes {
// Get any pending broadcasts
msgs := m.getBroadcasts(compoundOverhead, bytesAvail)
if len(msgs) == 0 {
return
}
addr := node.Address()
if len(msgs) == 1 {
// Send single message as is
if err := m.rawSendMsgPacket(addr, &node.Node, msgs[0]); err != nil {
m.logger.Printf("[ERR] memberlist: Failed to send gossip to %s: %s", addr, err)
}
} else {
// Otherwise create and send a compound message
compound := makeCompoundMessage(msgs)
if err := m.rawSendMsgPacket(addr, &node.Node, compound.Bytes()); err != nil {
m.logger.Printf("[ERR] memberlist: Failed to send gossip to %s: %s", addr, err)
}
}
}
}
|
go
|
func (m *Memberlist) gossip() {
defer metrics.MeasureSince([]string{"memberlist", "gossip"}, time.Now())
// Get some random live, suspect, or recently dead nodes
m.nodeLock.RLock()
kNodes := kRandomNodes(m.config.GossipNodes, m.nodes, func(n *nodeState) bool {
if n.Name == m.config.Name {
return true
}
switch n.State {
case stateAlive, stateSuspect:
return false
case stateDead:
return time.Since(n.StateChange) > m.config.GossipToTheDeadTime
default:
return true
}
})
m.nodeLock.RUnlock()
// Compute the bytes available
bytesAvail := m.config.UDPBufferSize - compoundHeaderOverhead
if m.config.EncryptionEnabled() {
bytesAvail -= encryptOverhead(m.encryptionVersion())
}
for _, node := range kNodes {
// Get any pending broadcasts
msgs := m.getBroadcasts(compoundOverhead, bytesAvail)
if len(msgs) == 0 {
return
}
addr := node.Address()
if len(msgs) == 1 {
// Send single message as is
if err := m.rawSendMsgPacket(addr, &node.Node, msgs[0]); err != nil {
m.logger.Printf("[ERR] memberlist: Failed to send gossip to %s: %s", addr, err)
}
} else {
// Otherwise create and send a compound message
compound := makeCompoundMessage(msgs)
if err := m.rawSendMsgPacket(addr, &node.Node, compound.Bytes()); err != nil {
m.logger.Printf("[ERR] memberlist: Failed to send gossip to %s: %s", addr, err)
}
}
}
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"gossip",
"(",
")",
"{",
"defer",
"metrics",
".",
"MeasureSince",
"(",
"[",
"]",
"string",
"{",
"\"memberlist\"",
",",
"\"gossip\"",
"}",
",",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"m",
".",
"nodeLock",
".",
"RLock",
"(",
")",
"\n",
"kNodes",
":=",
"kRandomNodes",
"(",
"m",
".",
"config",
".",
"GossipNodes",
",",
"m",
".",
"nodes",
",",
"func",
"(",
"n",
"*",
"nodeState",
")",
"bool",
"{",
"if",
"n",
".",
"Name",
"==",
"m",
".",
"config",
".",
"Name",
"{",
"return",
"true",
"\n",
"}",
"\n",
"switch",
"n",
".",
"State",
"{",
"case",
"stateAlive",
",",
"stateSuspect",
":",
"return",
"false",
"\n",
"case",
"stateDead",
":",
"return",
"time",
".",
"Since",
"(",
"n",
".",
"StateChange",
")",
">",
"m",
".",
"config",
".",
"GossipToTheDeadTime",
"\n",
"default",
":",
"return",
"true",
"\n",
"}",
"\n",
"}",
")",
"\n",
"m",
".",
"nodeLock",
".",
"RUnlock",
"(",
")",
"\n",
"bytesAvail",
":=",
"m",
".",
"config",
".",
"UDPBufferSize",
"-",
"compoundHeaderOverhead",
"\n",
"if",
"m",
".",
"config",
".",
"EncryptionEnabled",
"(",
")",
"{",
"bytesAvail",
"-=",
"encryptOverhead",
"(",
"m",
".",
"encryptionVersion",
"(",
")",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"node",
":=",
"range",
"kNodes",
"{",
"msgs",
":=",
"m",
".",
"getBroadcasts",
"(",
"compoundOverhead",
",",
"bytesAvail",
")",
"\n",
"if",
"len",
"(",
"msgs",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"addr",
":=",
"node",
".",
"Address",
"(",
")",
"\n",
"if",
"len",
"(",
"msgs",
")",
"==",
"1",
"{",
"if",
"err",
":=",
"m",
".",
"rawSendMsgPacket",
"(",
"addr",
",",
"&",
"node",
".",
"Node",
",",
"msgs",
"[",
"0",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[ERR] memberlist: Failed to send gossip to %s: %s\"",
",",
"addr",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"compound",
":=",
"makeCompoundMessage",
"(",
"msgs",
")",
"\n",
"if",
"err",
":=",
"m",
".",
"rawSendMsgPacket",
"(",
"addr",
",",
"&",
"node",
".",
"Node",
",",
"compound",
".",
"Bytes",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[ERR] memberlist: Failed to send gossip to %s: %s\"",
",",
"addr",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// gossip is invoked every GossipInterval period to broadcast our gossip
// messages to a few random nodes.
|
[
"gossip",
"is",
"invoked",
"every",
"GossipInterval",
"period",
"to",
"broadcast",
"our",
"gossip",
"messages",
"to",
"a",
"few",
"random",
"nodes",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L489-L539
|
train
|
hashicorp/memberlist
|
state.go
|
pushPull
|
func (m *Memberlist) pushPull() {
// Get a random live node
m.nodeLock.RLock()
nodes := kRandomNodes(1, m.nodes, func(n *nodeState) bool {
return n.Name == m.config.Name ||
n.State != stateAlive
})
m.nodeLock.RUnlock()
// If no nodes, bail
if len(nodes) == 0 {
return
}
node := nodes[0]
// Attempt a push pull
if err := m.pushPullNode(node.Address(), false); err != nil {
m.logger.Printf("[ERR] memberlist: Push/Pull with %s failed: %s", node.Name, err)
}
}
|
go
|
func (m *Memberlist) pushPull() {
// Get a random live node
m.nodeLock.RLock()
nodes := kRandomNodes(1, m.nodes, func(n *nodeState) bool {
return n.Name == m.config.Name ||
n.State != stateAlive
})
m.nodeLock.RUnlock()
// If no nodes, bail
if len(nodes) == 0 {
return
}
node := nodes[0]
// Attempt a push pull
if err := m.pushPullNode(node.Address(), false); err != nil {
m.logger.Printf("[ERR] memberlist: Push/Pull with %s failed: %s", node.Name, err)
}
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"pushPull",
"(",
")",
"{",
"m",
".",
"nodeLock",
".",
"RLock",
"(",
")",
"\n",
"nodes",
":=",
"kRandomNodes",
"(",
"1",
",",
"m",
".",
"nodes",
",",
"func",
"(",
"n",
"*",
"nodeState",
")",
"bool",
"{",
"return",
"n",
".",
"Name",
"==",
"m",
".",
"config",
".",
"Name",
"||",
"n",
".",
"State",
"!=",
"stateAlive",
"\n",
"}",
")",
"\n",
"m",
".",
"nodeLock",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"len",
"(",
"nodes",
")",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"node",
":=",
"nodes",
"[",
"0",
"]",
"\n",
"if",
"err",
":=",
"m",
".",
"pushPullNode",
"(",
"node",
".",
"Address",
"(",
")",
",",
"false",
")",
";",
"err",
"!=",
"nil",
"{",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[ERR] memberlist: Push/Pull with %s failed: %s\"",
",",
"node",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// pushPull is invoked periodically to randomly perform a complete state
// exchange. Used to ensure a high level of convergence, but is also
// reasonably expensive as the entire state of this node is exchanged
// with the other node.
|
[
"pushPull",
"is",
"invoked",
"periodically",
"to",
"randomly",
"perform",
"a",
"complete",
"state",
"exchange",
".",
"Used",
"to",
"ensure",
"a",
"high",
"level",
"of",
"convergence",
"but",
"is",
"also",
"reasonably",
"expensive",
"as",
"the",
"entire",
"state",
"of",
"this",
"node",
"is",
"exchanged",
"with",
"the",
"other",
"node",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L545-L564
|
train
|
hashicorp/memberlist
|
state.go
|
pushPullNode
|
func (m *Memberlist) pushPullNode(addr string, join bool) error {
defer metrics.MeasureSince([]string{"memberlist", "pushPullNode"}, time.Now())
// Attempt to send and receive with the node
remote, userState, err := m.sendAndReceiveState(addr, join)
if err != nil {
return err
}
if err := m.mergeRemoteState(join, remote, userState); err != nil {
return err
}
return nil
}
|
go
|
func (m *Memberlist) pushPullNode(addr string, join bool) error {
defer metrics.MeasureSince([]string{"memberlist", "pushPullNode"}, time.Now())
// Attempt to send and receive with the node
remote, userState, err := m.sendAndReceiveState(addr, join)
if err != nil {
return err
}
if err := m.mergeRemoteState(join, remote, userState); err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"pushPullNode",
"(",
"addr",
"string",
",",
"join",
"bool",
")",
"error",
"{",
"defer",
"metrics",
".",
"MeasureSince",
"(",
"[",
"]",
"string",
"{",
"\"memberlist\"",
",",
"\"pushPullNode\"",
"}",
",",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"remote",
",",
"userState",
",",
"err",
":=",
"m",
".",
"sendAndReceiveState",
"(",
"addr",
",",
"join",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"m",
".",
"mergeRemoteState",
"(",
"join",
",",
"remote",
",",
"userState",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// pushPullNode does a complete state exchange with a specific node.
|
[
"pushPullNode",
"does",
"a",
"complete",
"state",
"exchange",
"with",
"a",
"specific",
"node",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L567-L580
|
train
|
hashicorp/memberlist
|
state.go
|
skipIncarnation
|
func (m *Memberlist) skipIncarnation(offset uint32) uint32 {
return atomic.AddUint32(&m.incarnation, offset)
}
|
go
|
func (m *Memberlist) skipIncarnation(offset uint32) uint32 {
return atomic.AddUint32(&m.incarnation, offset)
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"skipIncarnation",
"(",
"offset",
"uint32",
")",
"uint32",
"{",
"return",
"atomic",
".",
"AddUint32",
"(",
"&",
"m",
".",
"incarnation",
",",
"offset",
")",
"\n",
"}"
] |
// skipIncarnation adds the positive offset to the incarnation number.
|
[
"skipIncarnation",
"adds",
"the",
"positive",
"offset",
"to",
"the",
"incarnation",
"number",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L712-L714
|
train
|
hashicorp/memberlist
|
state.go
|
setProbeChannels
|
func (m *Memberlist) setProbeChannels(seqNo uint32, ackCh chan ackMessage, nackCh chan struct{}, timeout time.Duration) {
// Create handler functions for acks and nacks
ackFn := func(payload []byte, timestamp time.Time) {
select {
case ackCh <- ackMessage{true, payload, timestamp}:
default:
}
}
nackFn := func() {
select {
case nackCh <- struct{}{}:
default:
}
}
// Add the handlers
ah := &ackHandler{ackFn, nackFn, nil}
m.ackLock.Lock()
m.ackHandlers[seqNo] = ah
m.ackLock.Unlock()
// Setup a reaping routing
ah.timer = time.AfterFunc(timeout, func() {
m.ackLock.Lock()
delete(m.ackHandlers, seqNo)
m.ackLock.Unlock()
select {
case ackCh <- ackMessage{false, nil, time.Now()}:
default:
}
})
}
|
go
|
func (m *Memberlist) setProbeChannels(seqNo uint32, ackCh chan ackMessage, nackCh chan struct{}, timeout time.Duration) {
// Create handler functions for acks and nacks
ackFn := func(payload []byte, timestamp time.Time) {
select {
case ackCh <- ackMessage{true, payload, timestamp}:
default:
}
}
nackFn := func() {
select {
case nackCh <- struct{}{}:
default:
}
}
// Add the handlers
ah := &ackHandler{ackFn, nackFn, nil}
m.ackLock.Lock()
m.ackHandlers[seqNo] = ah
m.ackLock.Unlock()
// Setup a reaping routing
ah.timer = time.AfterFunc(timeout, func() {
m.ackLock.Lock()
delete(m.ackHandlers, seqNo)
m.ackLock.Unlock()
select {
case ackCh <- ackMessage{false, nil, time.Now()}:
default:
}
})
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"setProbeChannels",
"(",
"seqNo",
"uint32",
",",
"ackCh",
"chan",
"ackMessage",
",",
"nackCh",
"chan",
"struct",
"{",
"}",
",",
"timeout",
"time",
".",
"Duration",
")",
"{",
"ackFn",
":=",
"func",
"(",
"payload",
"[",
"]",
"byte",
",",
"timestamp",
"time",
".",
"Time",
")",
"{",
"select",
"{",
"case",
"ackCh",
"<-",
"ackMessage",
"{",
"true",
",",
"payload",
",",
"timestamp",
"}",
":",
"default",
":",
"}",
"\n",
"}",
"\n",
"nackFn",
":=",
"func",
"(",
")",
"{",
"select",
"{",
"case",
"nackCh",
"<-",
"struct",
"{",
"}",
"{",
"}",
":",
"default",
":",
"}",
"\n",
"}",
"\n",
"ah",
":=",
"&",
"ackHandler",
"{",
"ackFn",
",",
"nackFn",
",",
"nil",
"}",
"\n",
"m",
".",
"ackLock",
".",
"Lock",
"(",
")",
"\n",
"m",
".",
"ackHandlers",
"[",
"seqNo",
"]",
"=",
"ah",
"\n",
"m",
".",
"ackLock",
".",
"Unlock",
"(",
")",
"\n",
"ah",
".",
"timer",
"=",
"time",
".",
"AfterFunc",
"(",
"timeout",
",",
"func",
"(",
")",
"{",
"m",
".",
"ackLock",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"m",
".",
"ackHandlers",
",",
"seqNo",
")",
"\n",
"m",
".",
"ackLock",
".",
"Unlock",
"(",
")",
"\n",
"select",
"{",
"case",
"ackCh",
"<-",
"ackMessage",
"{",
"false",
",",
"nil",
",",
"time",
".",
"Now",
"(",
")",
"}",
":",
"default",
":",
"}",
"\n",
"}",
")",
"\n",
"}"
] |
// setProbeChannels is used to attach the ackCh to receive a message when an ack
// with a given sequence number is received. The `complete` field of the message
// will be false on timeout. Any nack messages will cause an empty struct to be
// passed to the nackCh, which can be nil if not needed.
|
[
"setProbeChannels",
"is",
"used",
"to",
"attach",
"the",
"ackCh",
"to",
"receive",
"a",
"message",
"when",
"an",
"ack",
"with",
"a",
"given",
"sequence",
"number",
"is",
"received",
".",
"The",
"complete",
"field",
"of",
"the",
"message",
"will",
"be",
"false",
"on",
"timeout",
".",
"Any",
"nack",
"messages",
"will",
"cause",
"an",
"empty",
"struct",
"to",
"be",
"passed",
"to",
"the",
"nackCh",
"which",
"can",
"be",
"nil",
"if",
"not",
"needed",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L731-L762
|
train
|
hashicorp/memberlist
|
state.go
|
setAckHandler
|
func (m *Memberlist) setAckHandler(seqNo uint32, ackFn func([]byte, time.Time), timeout time.Duration) {
// Add the handler
ah := &ackHandler{ackFn, nil, nil}
m.ackLock.Lock()
m.ackHandlers[seqNo] = ah
m.ackLock.Unlock()
// Setup a reaping routing
ah.timer = time.AfterFunc(timeout, func() {
m.ackLock.Lock()
delete(m.ackHandlers, seqNo)
m.ackLock.Unlock()
})
}
|
go
|
func (m *Memberlist) setAckHandler(seqNo uint32, ackFn func([]byte, time.Time), timeout time.Duration) {
// Add the handler
ah := &ackHandler{ackFn, nil, nil}
m.ackLock.Lock()
m.ackHandlers[seqNo] = ah
m.ackLock.Unlock()
// Setup a reaping routing
ah.timer = time.AfterFunc(timeout, func() {
m.ackLock.Lock()
delete(m.ackHandlers, seqNo)
m.ackLock.Unlock()
})
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"setAckHandler",
"(",
"seqNo",
"uint32",
",",
"ackFn",
"func",
"(",
"[",
"]",
"byte",
",",
"time",
".",
"Time",
")",
",",
"timeout",
"time",
".",
"Duration",
")",
"{",
"ah",
":=",
"&",
"ackHandler",
"{",
"ackFn",
",",
"nil",
",",
"nil",
"}",
"\n",
"m",
".",
"ackLock",
".",
"Lock",
"(",
")",
"\n",
"m",
".",
"ackHandlers",
"[",
"seqNo",
"]",
"=",
"ah",
"\n",
"m",
".",
"ackLock",
".",
"Unlock",
"(",
")",
"\n",
"ah",
".",
"timer",
"=",
"time",
".",
"AfterFunc",
"(",
"timeout",
",",
"func",
"(",
")",
"{",
"m",
".",
"ackLock",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"m",
".",
"ackHandlers",
",",
"seqNo",
")",
"\n",
"m",
".",
"ackLock",
".",
"Unlock",
"(",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// setAckHandler is used to attach a handler to be invoked when an ack with a
// given sequence number is received. If a timeout is reached, the handler is
// deleted. This is used for indirect pings so does not configure a function
// for nacks.
|
[
"setAckHandler",
"is",
"used",
"to",
"attach",
"a",
"handler",
"to",
"be",
"invoked",
"when",
"an",
"ack",
"with",
"a",
"given",
"sequence",
"number",
"is",
"received",
".",
"If",
"a",
"timeout",
"is",
"reached",
"the",
"handler",
"is",
"deleted",
".",
"This",
"is",
"used",
"for",
"indirect",
"pings",
"so",
"does",
"not",
"configure",
"a",
"function",
"for",
"nacks",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L768-L781
|
train
|
hashicorp/memberlist
|
state.go
|
invokeAckHandler
|
func (m *Memberlist) invokeAckHandler(ack ackResp, timestamp time.Time) {
m.ackLock.Lock()
ah, ok := m.ackHandlers[ack.SeqNo]
delete(m.ackHandlers, ack.SeqNo)
m.ackLock.Unlock()
if !ok {
return
}
ah.timer.Stop()
ah.ackFn(ack.Payload, timestamp)
}
|
go
|
func (m *Memberlist) invokeAckHandler(ack ackResp, timestamp time.Time) {
m.ackLock.Lock()
ah, ok := m.ackHandlers[ack.SeqNo]
delete(m.ackHandlers, ack.SeqNo)
m.ackLock.Unlock()
if !ok {
return
}
ah.timer.Stop()
ah.ackFn(ack.Payload, timestamp)
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"invokeAckHandler",
"(",
"ack",
"ackResp",
",",
"timestamp",
"time",
".",
"Time",
")",
"{",
"m",
".",
"ackLock",
".",
"Lock",
"(",
")",
"\n",
"ah",
",",
"ok",
":=",
"m",
".",
"ackHandlers",
"[",
"ack",
".",
"SeqNo",
"]",
"\n",
"delete",
"(",
"m",
".",
"ackHandlers",
",",
"ack",
".",
"SeqNo",
")",
"\n",
"m",
".",
"ackLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"ah",
".",
"timer",
".",
"Stop",
"(",
")",
"\n",
"ah",
".",
"ackFn",
"(",
"ack",
".",
"Payload",
",",
"timestamp",
")",
"\n",
"}"
] |
// Invokes an ack handler if any is associated, and reaps the handler immediately
|
[
"Invokes",
"an",
"ack",
"handler",
"if",
"any",
"is",
"associated",
"and",
"reaps",
"the",
"handler",
"immediately"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L784-L794
|
train
|
hashicorp/memberlist
|
state.go
|
invokeNackHandler
|
func (m *Memberlist) invokeNackHandler(nack nackResp) {
m.ackLock.Lock()
ah, ok := m.ackHandlers[nack.SeqNo]
m.ackLock.Unlock()
if !ok || ah.nackFn == nil {
return
}
ah.nackFn()
}
|
go
|
func (m *Memberlist) invokeNackHandler(nack nackResp) {
m.ackLock.Lock()
ah, ok := m.ackHandlers[nack.SeqNo]
m.ackLock.Unlock()
if !ok || ah.nackFn == nil {
return
}
ah.nackFn()
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"invokeNackHandler",
"(",
"nack",
"nackResp",
")",
"{",
"m",
".",
"ackLock",
".",
"Lock",
"(",
")",
"\n",
"ah",
",",
"ok",
":=",
"m",
".",
"ackHandlers",
"[",
"nack",
".",
"SeqNo",
"]",
"\n",
"m",
".",
"ackLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"!",
"ok",
"||",
"ah",
".",
"nackFn",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"ah",
".",
"nackFn",
"(",
")",
"\n",
"}"
] |
// Invokes nack handler if any is associated.
|
[
"Invokes",
"nack",
"handler",
"if",
"any",
"is",
"associated",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L797-L805
|
train
|
hashicorp/memberlist
|
state.go
|
refute
|
func (m *Memberlist) refute(me *nodeState, accusedInc uint32) {
// Make sure the incarnation number beats the accusation.
inc := m.nextIncarnation()
if accusedInc >= inc {
inc = m.skipIncarnation(accusedInc - inc + 1)
}
me.Incarnation = inc
// Decrease our health because we are being asked to refute a problem.
m.awareness.ApplyDelta(1)
// Format and broadcast an alive message.
a := alive{
Incarnation: inc,
Node: me.Name,
Addr: me.Addr,
Port: me.Port,
Meta: me.Meta,
Vsn: []uint8{
me.PMin, me.PMax, me.PCur,
me.DMin, me.DMax, me.DCur,
},
}
m.encodeAndBroadcast(me.Addr.String(), aliveMsg, a)
}
|
go
|
func (m *Memberlist) refute(me *nodeState, accusedInc uint32) {
// Make sure the incarnation number beats the accusation.
inc := m.nextIncarnation()
if accusedInc >= inc {
inc = m.skipIncarnation(accusedInc - inc + 1)
}
me.Incarnation = inc
// Decrease our health because we are being asked to refute a problem.
m.awareness.ApplyDelta(1)
// Format and broadcast an alive message.
a := alive{
Incarnation: inc,
Node: me.Name,
Addr: me.Addr,
Port: me.Port,
Meta: me.Meta,
Vsn: []uint8{
me.PMin, me.PMax, me.PCur,
me.DMin, me.DMax, me.DCur,
},
}
m.encodeAndBroadcast(me.Addr.String(), aliveMsg, a)
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"refute",
"(",
"me",
"*",
"nodeState",
",",
"accusedInc",
"uint32",
")",
"{",
"inc",
":=",
"m",
".",
"nextIncarnation",
"(",
")",
"\n",
"if",
"accusedInc",
">=",
"inc",
"{",
"inc",
"=",
"m",
".",
"skipIncarnation",
"(",
"accusedInc",
"-",
"inc",
"+",
"1",
")",
"\n",
"}",
"\n",
"me",
".",
"Incarnation",
"=",
"inc",
"\n",
"m",
".",
"awareness",
".",
"ApplyDelta",
"(",
"1",
")",
"\n",
"a",
":=",
"alive",
"{",
"Incarnation",
":",
"inc",
",",
"Node",
":",
"me",
".",
"Name",
",",
"Addr",
":",
"me",
".",
"Addr",
",",
"Port",
":",
"me",
".",
"Port",
",",
"Meta",
":",
"me",
".",
"Meta",
",",
"Vsn",
":",
"[",
"]",
"uint8",
"{",
"me",
".",
"PMin",
",",
"me",
".",
"PMax",
",",
"me",
".",
"PCur",
",",
"me",
".",
"DMin",
",",
"me",
".",
"DMax",
",",
"me",
".",
"DCur",
",",
"}",
",",
"}",
"\n",
"m",
".",
"encodeAndBroadcast",
"(",
"me",
".",
"Addr",
".",
"String",
"(",
")",
",",
"aliveMsg",
",",
"a",
")",
"\n",
"}"
] |
// refute gossips an alive message in response to incoming information that we
// are suspect or dead. It will make sure the incarnation number beats the given
// accusedInc value, or you can supply 0 to just get the next incarnation number.
// This alters the node state that's passed in so this MUST be called while the
// nodeLock is held.
|
[
"refute",
"gossips",
"an",
"alive",
"message",
"in",
"response",
"to",
"incoming",
"information",
"that",
"we",
"are",
"suspect",
"or",
"dead",
".",
"It",
"will",
"make",
"sure",
"the",
"incarnation",
"number",
"beats",
"the",
"given",
"accusedInc",
"value",
"or",
"you",
"can",
"supply",
"0",
"to",
"just",
"get",
"the",
"next",
"incarnation",
"number",
".",
"This",
"alters",
"the",
"node",
"state",
"that",
"s",
"passed",
"in",
"so",
"this",
"MUST",
"be",
"called",
"while",
"the",
"nodeLock",
"is",
"held",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L812-L836
|
train
|
hashicorp/memberlist
|
state.go
|
suspectNode
|
func (m *Memberlist) suspectNode(s *suspect) {
m.nodeLock.Lock()
defer m.nodeLock.Unlock()
state, ok := m.nodeMap[s.Node]
// If we've never heard about this node before, ignore it
if !ok {
return
}
// Ignore old incarnation numbers
if s.Incarnation < state.Incarnation {
return
}
// See if there's a suspicion timer we can confirm. If the info is new
// to us we will go ahead and re-gossip it. This allows for multiple
// independent confirmations to flow even when a node probes a node
// that's already suspect.
if timer, ok := m.nodeTimers[s.Node]; ok {
if timer.Confirm(s.From) {
m.encodeAndBroadcast(s.Node, suspectMsg, s)
}
return
}
// Ignore non-alive nodes
if state.State != stateAlive {
return
}
// If this is us we need to refute, otherwise re-broadcast
if state.Name == m.config.Name {
m.refute(state, s.Incarnation)
m.logger.Printf("[WARN] memberlist: Refuting a suspect message (from: %s)", s.From)
return // Do not mark ourself suspect
} else {
m.encodeAndBroadcast(s.Node, suspectMsg, s)
}
// Update metrics
metrics.IncrCounter([]string{"memberlist", "msg", "suspect"}, 1)
// Update the state
state.Incarnation = s.Incarnation
state.State = stateSuspect
changeTime := time.Now()
state.StateChange = changeTime
// Setup a suspicion timer. Given that we don't have any known phase
// relationship with our peers, we set up k such that we hit the nominal
// timeout two probe intervals short of what we expect given the suspicion
// multiplier.
k := m.config.SuspicionMult - 2
// If there aren't enough nodes to give the expected confirmations, just
// set k to 0 to say that we don't expect any. Note we subtract 2 from n
// here to take out ourselves and the node being probed.
n := m.estNumNodes()
if n-2 < k {
k = 0
}
// Compute the timeouts based on the size of the cluster.
min := suspicionTimeout(m.config.SuspicionMult, n, m.config.ProbeInterval)
max := time.Duration(m.config.SuspicionMaxTimeoutMult) * min
fn := func(numConfirmations int) {
m.nodeLock.Lock()
state, ok := m.nodeMap[s.Node]
timeout := ok && state.State == stateSuspect && state.StateChange == changeTime
m.nodeLock.Unlock()
if timeout {
if k > 0 && numConfirmations < k {
metrics.IncrCounter([]string{"memberlist", "degraded", "timeout"}, 1)
}
m.logger.Printf("[INFO] memberlist: Marking %s as failed, suspect timeout reached (%d peer confirmations)",
state.Name, numConfirmations)
d := dead{Incarnation: state.Incarnation, Node: state.Name, From: m.config.Name}
m.deadNode(&d)
}
}
m.nodeTimers[s.Node] = newSuspicion(s.From, k, min, max, fn)
}
|
go
|
func (m *Memberlist) suspectNode(s *suspect) {
m.nodeLock.Lock()
defer m.nodeLock.Unlock()
state, ok := m.nodeMap[s.Node]
// If we've never heard about this node before, ignore it
if !ok {
return
}
// Ignore old incarnation numbers
if s.Incarnation < state.Incarnation {
return
}
// See if there's a suspicion timer we can confirm. If the info is new
// to us we will go ahead and re-gossip it. This allows for multiple
// independent confirmations to flow even when a node probes a node
// that's already suspect.
if timer, ok := m.nodeTimers[s.Node]; ok {
if timer.Confirm(s.From) {
m.encodeAndBroadcast(s.Node, suspectMsg, s)
}
return
}
// Ignore non-alive nodes
if state.State != stateAlive {
return
}
// If this is us we need to refute, otherwise re-broadcast
if state.Name == m.config.Name {
m.refute(state, s.Incarnation)
m.logger.Printf("[WARN] memberlist: Refuting a suspect message (from: %s)", s.From)
return // Do not mark ourself suspect
} else {
m.encodeAndBroadcast(s.Node, suspectMsg, s)
}
// Update metrics
metrics.IncrCounter([]string{"memberlist", "msg", "suspect"}, 1)
// Update the state
state.Incarnation = s.Incarnation
state.State = stateSuspect
changeTime := time.Now()
state.StateChange = changeTime
// Setup a suspicion timer. Given that we don't have any known phase
// relationship with our peers, we set up k such that we hit the nominal
// timeout two probe intervals short of what we expect given the suspicion
// multiplier.
k := m.config.SuspicionMult - 2
// If there aren't enough nodes to give the expected confirmations, just
// set k to 0 to say that we don't expect any. Note we subtract 2 from n
// here to take out ourselves and the node being probed.
n := m.estNumNodes()
if n-2 < k {
k = 0
}
// Compute the timeouts based on the size of the cluster.
min := suspicionTimeout(m.config.SuspicionMult, n, m.config.ProbeInterval)
max := time.Duration(m.config.SuspicionMaxTimeoutMult) * min
fn := func(numConfirmations int) {
m.nodeLock.Lock()
state, ok := m.nodeMap[s.Node]
timeout := ok && state.State == stateSuspect && state.StateChange == changeTime
m.nodeLock.Unlock()
if timeout {
if k > 0 && numConfirmations < k {
metrics.IncrCounter([]string{"memberlist", "degraded", "timeout"}, 1)
}
m.logger.Printf("[INFO] memberlist: Marking %s as failed, suspect timeout reached (%d peer confirmations)",
state.Name, numConfirmations)
d := dead{Incarnation: state.Incarnation, Node: state.Name, From: m.config.Name}
m.deadNode(&d)
}
}
m.nodeTimers[s.Node] = newSuspicion(s.From, k, min, max, fn)
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"suspectNode",
"(",
"s",
"*",
"suspect",
")",
"{",
"m",
".",
"nodeLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"nodeLock",
".",
"Unlock",
"(",
")",
"\n",
"state",
",",
"ok",
":=",
"m",
".",
"nodeMap",
"[",
"s",
".",
"Node",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"if",
"s",
".",
"Incarnation",
"<",
"state",
".",
"Incarnation",
"{",
"return",
"\n",
"}",
"\n",
"if",
"timer",
",",
"ok",
":=",
"m",
".",
"nodeTimers",
"[",
"s",
".",
"Node",
"]",
";",
"ok",
"{",
"if",
"timer",
".",
"Confirm",
"(",
"s",
".",
"From",
")",
"{",
"m",
".",
"encodeAndBroadcast",
"(",
"s",
".",
"Node",
",",
"suspectMsg",
",",
"s",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"state",
".",
"State",
"!=",
"stateAlive",
"{",
"return",
"\n",
"}",
"\n",
"if",
"state",
".",
"Name",
"==",
"m",
".",
"config",
".",
"Name",
"{",
"m",
".",
"refute",
"(",
"state",
",",
"s",
".",
"Incarnation",
")",
"\n",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[WARN] memberlist: Refuting a suspect message (from: %s)\"",
",",
"s",
".",
"From",
")",
"\n",
"return",
"\n",
"}",
"else",
"{",
"m",
".",
"encodeAndBroadcast",
"(",
"s",
".",
"Node",
",",
"suspectMsg",
",",
"s",
")",
"\n",
"}",
"\n",
"metrics",
".",
"IncrCounter",
"(",
"[",
"]",
"string",
"{",
"\"memberlist\"",
",",
"\"msg\"",
",",
"\"suspect\"",
"}",
",",
"1",
")",
"\n",
"state",
".",
"Incarnation",
"=",
"s",
".",
"Incarnation",
"\n",
"state",
".",
"State",
"=",
"stateSuspect",
"\n",
"changeTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"state",
".",
"StateChange",
"=",
"changeTime",
"\n",
"k",
":=",
"m",
".",
"config",
".",
"SuspicionMult",
"-",
"2",
"\n",
"n",
":=",
"m",
".",
"estNumNodes",
"(",
")",
"\n",
"if",
"n",
"-",
"2",
"<",
"k",
"{",
"k",
"=",
"0",
"\n",
"}",
"\n",
"min",
":=",
"suspicionTimeout",
"(",
"m",
".",
"config",
".",
"SuspicionMult",
",",
"n",
",",
"m",
".",
"config",
".",
"ProbeInterval",
")",
"\n",
"max",
":=",
"time",
".",
"Duration",
"(",
"m",
".",
"config",
".",
"SuspicionMaxTimeoutMult",
")",
"*",
"min",
"\n",
"fn",
":=",
"func",
"(",
"numConfirmations",
"int",
")",
"{",
"m",
".",
"nodeLock",
".",
"Lock",
"(",
")",
"\n",
"state",
",",
"ok",
":=",
"m",
".",
"nodeMap",
"[",
"s",
".",
"Node",
"]",
"\n",
"timeout",
":=",
"ok",
"&&",
"state",
".",
"State",
"==",
"stateSuspect",
"&&",
"state",
".",
"StateChange",
"==",
"changeTime",
"\n",
"m",
".",
"nodeLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"timeout",
"{",
"if",
"k",
">",
"0",
"&&",
"numConfirmations",
"<",
"k",
"{",
"metrics",
".",
"IncrCounter",
"(",
"[",
"]",
"string",
"{",
"\"memberlist\"",
",",
"\"degraded\"",
",",
"\"timeout\"",
"}",
",",
"1",
")",
"\n",
"}",
"\n",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[INFO] memberlist: Marking %s as failed, suspect timeout reached (%d peer confirmations)\"",
",",
"state",
".",
"Name",
",",
"numConfirmations",
")",
"\n",
"d",
":=",
"dead",
"{",
"Incarnation",
":",
"state",
".",
"Incarnation",
",",
"Node",
":",
"state",
".",
"Name",
",",
"From",
":",
"m",
".",
"config",
".",
"Name",
"}",
"\n",
"m",
".",
"deadNode",
"(",
"&",
"d",
")",
"\n",
"}",
"\n",
"}",
"\n",
"m",
".",
"nodeTimers",
"[",
"s",
".",
"Node",
"]",
"=",
"newSuspicion",
"(",
"s",
".",
"From",
",",
"k",
",",
"min",
",",
"max",
",",
"fn",
")",
"\n",
"}"
] |
// suspectNode is invoked by the network layer when we get a message
// about a suspect node
|
[
"suspectNode",
"is",
"invoked",
"by",
"the",
"network",
"layer",
"when",
"we",
"get",
"a",
"message",
"about",
"a",
"suspect",
"node"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L1033-L1117
|
train
|
hashicorp/memberlist
|
state.go
|
deadNode
|
func (m *Memberlist) deadNode(d *dead) {
m.nodeLock.Lock()
defer m.nodeLock.Unlock()
state, ok := m.nodeMap[d.Node]
// If we've never heard about this node before, ignore it
if !ok {
return
}
// Ignore old incarnation numbers
if d.Incarnation < state.Incarnation {
return
}
// Clear out any suspicion timer that may be in effect.
delete(m.nodeTimers, d.Node)
// Ignore if node is already dead
if state.State == stateDead {
return
}
// Check if this is us
if state.Name == m.config.Name {
// If we are not leaving we need to refute
if !m.hasLeft() {
m.refute(state, d.Incarnation)
m.logger.Printf("[WARN] memberlist: Refuting a dead message (from: %s)", d.From)
return // Do not mark ourself dead
}
// If we are leaving, we broadcast and wait
m.encodeBroadcastNotify(d.Node, deadMsg, d, m.leaveBroadcast)
} else {
m.encodeAndBroadcast(d.Node, deadMsg, d)
}
// Update metrics
metrics.IncrCounter([]string{"memberlist", "msg", "dead"}, 1)
// Update the state
state.Incarnation = d.Incarnation
state.State = stateDead
state.StateChange = time.Now()
// Notify of death
if m.config.Events != nil {
m.config.Events.NotifyLeave(&state.Node)
}
}
|
go
|
func (m *Memberlist) deadNode(d *dead) {
m.nodeLock.Lock()
defer m.nodeLock.Unlock()
state, ok := m.nodeMap[d.Node]
// If we've never heard about this node before, ignore it
if !ok {
return
}
// Ignore old incarnation numbers
if d.Incarnation < state.Incarnation {
return
}
// Clear out any suspicion timer that may be in effect.
delete(m.nodeTimers, d.Node)
// Ignore if node is already dead
if state.State == stateDead {
return
}
// Check if this is us
if state.Name == m.config.Name {
// If we are not leaving we need to refute
if !m.hasLeft() {
m.refute(state, d.Incarnation)
m.logger.Printf("[WARN] memberlist: Refuting a dead message (from: %s)", d.From)
return // Do not mark ourself dead
}
// If we are leaving, we broadcast and wait
m.encodeBroadcastNotify(d.Node, deadMsg, d, m.leaveBroadcast)
} else {
m.encodeAndBroadcast(d.Node, deadMsg, d)
}
// Update metrics
metrics.IncrCounter([]string{"memberlist", "msg", "dead"}, 1)
// Update the state
state.Incarnation = d.Incarnation
state.State = stateDead
state.StateChange = time.Now()
// Notify of death
if m.config.Events != nil {
m.config.Events.NotifyLeave(&state.Node)
}
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"deadNode",
"(",
"d",
"*",
"dead",
")",
"{",
"m",
".",
"nodeLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"nodeLock",
".",
"Unlock",
"(",
")",
"\n",
"state",
",",
"ok",
":=",
"m",
".",
"nodeMap",
"[",
"d",
".",
"Node",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"if",
"d",
".",
"Incarnation",
"<",
"state",
".",
"Incarnation",
"{",
"return",
"\n",
"}",
"\n",
"delete",
"(",
"m",
".",
"nodeTimers",
",",
"d",
".",
"Node",
")",
"\n",
"if",
"state",
".",
"State",
"==",
"stateDead",
"{",
"return",
"\n",
"}",
"\n",
"if",
"state",
".",
"Name",
"==",
"m",
".",
"config",
".",
"Name",
"{",
"if",
"!",
"m",
".",
"hasLeft",
"(",
")",
"{",
"m",
".",
"refute",
"(",
"state",
",",
"d",
".",
"Incarnation",
")",
"\n",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[WARN] memberlist: Refuting a dead message (from: %s)\"",
",",
"d",
".",
"From",
")",
"\n",
"return",
"\n",
"}",
"\n",
"m",
".",
"encodeBroadcastNotify",
"(",
"d",
".",
"Node",
",",
"deadMsg",
",",
"d",
",",
"m",
".",
"leaveBroadcast",
")",
"\n",
"}",
"else",
"{",
"m",
".",
"encodeAndBroadcast",
"(",
"d",
".",
"Node",
",",
"deadMsg",
",",
"d",
")",
"\n",
"}",
"\n",
"metrics",
".",
"IncrCounter",
"(",
"[",
"]",
"string",
"{",
"\"memberlist\"",
",",
"\"msg\"",
",",
"\"dead\"",
"}",
",",
"1",
")",
"\n",
"state",
".",
"Incarnation",
"=",
"d",
".",
"Incarnation",
"\n",
"state",
".",
"State",
"=",
"stateDead",
"\n",
"state",
".",
"StateChange",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"if",
"m",
".",
"config",
".",
"Events",
"!=",
"nil",
"{",
"m",
".",
"config",
".",
"Events",
".",
"NotifyLeave",
"(",
"&",
"state",
".",
"Node",
")",
"\n",
"}",
"\n",
"}"
] |
// deadNode is invoked by the network layer when we get a message
// about a dead node
|
[
"deadNode",
"is",
"invoked",
"by",
"the",
"network",
"layer",
"when",
"we",
"get",
"a",
"message",
"about",
"a",
"dead",
"node"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/state.go#L1121-L1171
|
train
|
hashicorp/memberlist
|
broadcast.go
|
encodeAndBroadcast
|
func (m *Memberlist) encodeAndBroadcast(node string, msgType messageType, msg interface{}) {
m.encodeBroadcastNotify(node, msgType, msg, nil)
}
|
go
|
func (m *Memberlist) encodeAndBroadcast(node string, msgType messageType, msg interface{}) {
m.encodeBroadcastNotify(node, msgType, msg, nil)
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"encodeAndBroadcast",
"(",
"node",
"string",
",",
"msgType",
"messageType",
",",
"msg",
"interface",
"{",
"}",
")",
"{",
"m",
".",
"encodeBroadcastNotify",
"(",
"node",
",",
"msgType",
",",
"msg",
",",
"nil",
")",
"\n",
"}"
] |
// encodeAndBroadcast encodes a message and enqueues it for broadcast. Fails
// silently if there is an encoding error.
|
[
"encodeAndBroadcast",
"encodes",
"a",
"message",
"and",
"enqueues",
"it",
"for",
"broadcast",
".",
"Fails",
"silently",
"if",
"there",
"is",
"an",
"encoding",
"error",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/broadcast.go#L50-L52
|
train
|
hashicorp/memberlist
|
broadcast.go
|
encodeBroadcastNotify
|
func (m *Memberlist) encodeBroadcastNotify(node string, msgType messageType, msg interface{}, notify chan struct{}) {
buf, err := encode(msgType, msg)
if err != nil {
m.logger.Printf("[ERR] memberlist: Failed to encode message for broadcast: %s", err)
} else {
m.queueBroadcast(node, buf.Bytes(), notify)
}
}
|
go
|
func (m *Memberlist) encodeBroadcastNotify(node string, msgType messageType, msg interface{}, notify chan struct{}) {
buf, err := encode(msgType, msg)
if err != nil {
m.logger.Printf("[ERR] memberlist: Failed to encode message for broadcast: %s", err)
} else {
m.queueBroadcast(node, buf.Bytes(), notify)
}
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"encodeBroadcastNotify",
"(",
"node",
"string",
",",
"msgType",
"messageType",
",",
"msg",
"interface",
"{",
"}",
",",
"notify",
"chan",
"struct",
"{",
"}",
")",
"{",
"buf",
",",
"err",
":=",
"encode",
"(",
"msgType",
",",
"msg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[ERR] memberlist: Failed to encode message for broadcast: %s\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"m",
".",
"queueBroadcast",
"(",
"node",
",",
"buf",
".",
"Bytes",
"(",
")",
",",
"notify",
")",
"\n",
"}",
"\n",
"}"
] |
// encodeBroadcastNotify encodes a message and enqueues it for broadcast
// and notifies the given channel when transmission is finished. Fails
// silently if there is an encoding error.
|
[
"encodeBroadcastNotify",
"encodes",
"a",
"message",
"and",
"enqueues",
"it",
"for",
"broadcast",
"and",
"notifies",
"the",
"given",
"channel",
"when",
"transmission",
"is",
"finished",
".",
"Fails",
"silently",
"if",
"there",
"is",
"an",
"encoding",
"error",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/broadcast.go#L57-L64
|
train
|
hashicorp/memberlist
|
broadcast.go
|
queueBroadcast
|
func (m *Memberlist) queueBroadcast(node string, msg []byte, notify chan struct{}) {
b := &memberlistBroadcast{node, msg, notify}
m.broadcasts.QueueBroadcast(b)
}
|
go
|
func (m *Memberlist) queueBroadcast(node string, msg []byte, notify chan struct{}) {
b := &memberlistBroadcast{node, msg, notify}
m.broadcasts.QueueBroadcast(b)
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"queueBroadcast",
"(",
"node",
"string",
",",
"msg",
"[",
"]",
"byte",
",",
"notify",
"chan",
"struct",
"{",
"}",
")",
"{",
"b",
":=",
"&",
"memberlistBroadcast",
"{",
"node",
",",
"msg",
",",
"notify",
"}",
"\n",
"m",
".",
"broadcasts",
".",
"QueueBroadcast",
"(",
"b",
")",
"\n",
"}"
] |
// queueBroadcast is used to start dissemination of a message. It will be
// sent up to a configured number of times. The message could potentially
// be invalidated by a future message about the same node
|
[
"queueBroadcast",
"is",
"used",
"to",
"start",
"dissemination",
"of",
"a",
"message",
".",
"It",
"will",
"be",
"sent",
"up",
"to",
"a",
"configured",
"number",
"of",
"times",
".",
"The",
"message",
"could",
"potentially",
"be",
"invalidated",
"by",
"a",
"future",
"message",
"about",
"the",
"same",
"node"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/broadcast.go#L69-L72
|
train
|
hashicorp/memberlist
|
broadcast.go
|
getBroadcasts
|
func (m *Memberlist) getBroadcasts(overhead, limit int) [][]byte {
// Get memberlist messages first
toSend := m.broadcasts.GetBroadcasts(overhead, limit)
// Check if the user has anything to broadcast
d := m.config.Delegate
if d != nil {
// Determine the bytes used already
bytesUsed := 0
for _, msg := range toSend {
bytesUsed += len(msg) + overhead
}
// Check space remaining for user messages
avail := limit - bytesUsed
if avail > overhead+userMsgOverhead {
userMsgs := d.GetBroadcasts(overhead+userMsgOverhead, avail)
// Frame each user message
for _, msg := range userMsgs {
buf := make([]byte, 1, len(msg)+1)
buf[0] = byte(userMsg)
buf = append(buf, msg...)
toSend = append(toSend, buf)
}
}
}
return toSend
}
|
go
|
func (m *Memberlist) getBroadcasts(overhead, limit int) [][]byte {
// Get memberlist messages first
toSend := m.broadcasts.GetBroadcasts(overhead, limit)
// Check if the user has anything to broadcast
d := m.config.Delegate
if d != nil {
// Determine the bytes used already
bytesUsed := 0
for _, msg := range toSend {
bytesUsed += len(msg) + overhead
}
// Check space remaining for user messages
avail := limit - bytesUsed
if avail > overhead+userMsgOverhead {
userMsgs := d.GetBroadcasts(overhead+userMsgOverhead, avail)
// Frame each user message
for _, msg := range userMsgs {
buf := make([]byte, 1, len(msg)+1)
buf[0] = byte(userMsg)
buf = append(buf, msg...)
toSend = append(toSend, buf)
}
}
}
return toSend
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"getBroadcasts",
"(",
"overhead",
",",
"limit",
"int",
")",
"[",
"]",
"[",
"]",
"byte",
"{",
"toSend",
":=",
"m",
".",
"broadcasts",
".",
"GetBroadcasts",
"(",
"overhead",
",",
"limit",
")",
"\n",
"d",
":=",
"m",
".",
"config",
".",
"Delegate",
"\n",
"if",
"d",
"!=",
"nil",
"{",
"bytesUsed",
":=",
"0",
"\n",
"for",
"_",
",",
"msg",
":=",
"range",
"toSend",
"{",
"bytesUsed",
"+=",
"len",
"(",
"msg",
")",
"+",
"overhead",
"\n",
"}",
"\n",
"avail",
":=",
"limit",
"-",
"bytesUsed",
"\n",
"if",
"avail",
">",
"overhead",
"+",
"userMsgOverhead",
"{",
"userMsgs",
":=",
"d",
".",
"GetBroadcasts",
"(",
"overhead",
"+",
"userMsgOverhead",
",",
"avail",
")",
"\n",
"for",
"_",
",",
"msg",
":=",
"range",
"userMsgs",
"{",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"1",
",",
"len",
"(",
"msg",
")",
"+",
"1",
")",
"\n",
"buf",
"[",
"0",
"]",
"=",
"byte",
"(",
"userMsg",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"msg",
"...",
")",
"\n",
"toSend",
"=",
"append",
"(",
"toSend",
",",
"buf",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"toSend",
"\n",
"}"
] |
// getBroadcasts is used to return a slice of broadcasts to send up to
// a maximum byte size, while imposing a per-broadcast overhead. This is used
// to fill a UDP packet with piggybacked data
|
[
"getBroadcasts",
"is",
"used",
"to",
"return",
"a",
"slice",
"of",
"broadcasts",
"to",
"send",
"up",
"to",
"a",
"maximum",
"byte",
"size",
"while",
"imposing",
"a",
"per",
"-",
"broadcast",
"overhead",
".",
"This",
"is",
"used",
"to",
"fill",
"a",
"UDP",
"packet",
"with",
"piggybacked",
"data"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/broadcast.go#L77-L105
|
train
|
hashicorp/memberlist
|
memberlist.go
|
BuildVsnArray
|
func (conf *Config) BuildVsnArray() []uint8 {
return []uint8{
ProtocolVersionMin, ProtocolVersionMax, conf.ProtocolVersion,
conf.DelegateProtocolMin, conf.DelegateProtocolMax,
conf.DelegateProtocolVersion,
}
}
|
go
|
func (conf *Config) BuildVsnArray() []uint8 {
return []uint8{
ProtocolVersionMin, ProtocolVersionMax, conf.ProtocolVersion,
conf.DelegateProtocolMin, conf.DelegateProtocolMax,
conf.DelegateProtocolVersion,
}
}
|
[
"func",
"(",
"conf",
"*",
"Config",
")",
"BuildVsnArray",
"(",
")",
"[",
"]",
"uint8",
"{",
"return",
"[",
"]",
"uint8",
"{",
"ProtocolVersionMin",
",",
"ProtocolVersionMax",
",",
"conf",
".",
"ProtocolVersion",
",",
"conf",
".",
"DelegateProtocolMin",
",",
"conf",
".",
"DelegateProtocolMax",
",",
"conf",
".",
"DelegateProtocolVersion",
",",
"}",
"\n",
"}"
] |
// BuildVsnArray creates the array of Vsn
|
[
"BuildVsnArray",
"creates",
"the",
"array",
"of",
"Vsn"
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/memberlist.go#L76-L82
|
train
|
hashicorp/memberlist
|
memberlist.go
|
Join
|
func (m *Memberlist) Join(existing []string) (int, error) {
numSuccess := 0
var errs error
for _, exist := range existing {
addrs, err := m.resolveAddr(exist)
if err != nil {
err = fmt.Errorf("Failed to resolve %s: %v", exist, err)
errs = multierror.Append(errs, err)
m.logger.Printf("[WARN] memberlist: %v", err)
continue
}
for _, addr := range addrs {
hp := joinHostPort(addr.ip.String(), addr.port)
if err := m.pushPullNode(hp, true); err != nil {
err = fmt.Errorf("Failed to join %s: %v", addr.ip, err)
errs = multierror.Append(errs, err)
m.logger.Printf("[DEBUG] memberlist: %v", err)
continue
}
numSuccess++
}
}
if numSuccess > 0 {
errs = nil
}
return numSuccess, errs
}
|
go
|
func (m *Memberlist) Join(existing []string) (int, error) {
numSuccess := 0
var errs error
for _, exist := range existing {
addrs, err := m.resolveAddr(exist)
if err != nil {
err = fmt.Errorf("Failed to resolve %s: %v", exist, err)
errs = multierror.Append(errs, err)
m.logger.Printf("[WARN] memberlist: %v", err)
continue
}
for _, addr := range addrs {
hp := joinHostPort(addr.ip.String(), addr.port)
if err := m.pushPullNode(hp, true); err != nil {
err = fmt.Errorf("Failed to join %s: %v", addr.ip, err)
errs = multierror.Append(errs, err)
m.logger.Printf("[DEBUG] memberlist: %v", err)
continue
}
numSuccess++
}
}
if numSuccess > 0 {
errs = nil
}
return numSuccess, errs
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"Join",
"(",
"existing",
"[",
"]",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"numSuccess",
":=",
"0",
"\n",
"var",
"errs",
"error",
"\n",
"for",
"_",
",",
"exist",
":=",
"range",
"existing",
"{",
"addrs",
",",
"err",
":=",
"m",
".",
"resolveAddr",
"(",
"exist",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"Failed to resolve %s: %v\"",
",",
"exist",
",",
"err",
")",
"\n",
"errs",
"=",
"multierror",
".",
"Append",
"(",
"errs",
",",
"err",
")",
"\n",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[WARN] memberlist: %v\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"for",
"_",
",",
"addr",
":=",
"range",
"addrs",
"{",
"hp",
":=",
"joinHostPort",
"(",
"addr",
".",
"ip",
".",
"String",
"(",
")",
",",
"addr",
".",
"port",
")",
"\n",
"if",
"err",
":=",
"m",
".",
"pushPullNode",
"(",
"hp",
",",
"true",
")",
";",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"Failed to join %s: %v\"",
",",
"addr",
".",
"ip",
",",
"err",
")",
"\n",
"errs",
"=",
"multierror",
".",
"Append",
"(",
"errs",
",",
"err",
")",
"\n",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[DEBUG] memberlist: %v\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"numSuccess",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"numSuccess",
">",
"0",
"{",
"errs",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"numSuccess",
",",
"errs",
"\n",
"}"
] |
// Join is used to take an existing Memberlist and attempt to join a cluster
// by contacting all the given hosts and performing a state sync. Initially,
// the Memberlist only contains our own state, so doing this will cause
// remote nodes to become aware of the existence of this node, effectively
// joining the cluster.
//
// This returns the number of hosts successfully contacted and an error if
// none could be reached. If an error is returned, the node did not successfully
// join the cluster.
|
[
"Join",
"is",
"used",
"to",
"take",
"an",
"existing",
"Memberlist",
"and",
"attempt",
"to",
"join",
"a",
"cluster",
"by",
"contacting",
"all",
"the",
"given",
"hosts",
"and",
"performing",
"a",
"state",
"sync",
".",
"Initially",
"the",
"Memberlist",
"only",
"contains",
"our",
"own",
"state",
"so",
"doing",
"this",
"will",
"cause",
"remote",
"nodes",
"to",
"become",
"aware",
"of",
"the",
"existence",
"of",
"this",
"node",
"effectively",
"joining",
"the",
"cluster",
".",
"This",
"returns",
"the",
"number",
"of",
"hosts",
"successfully",
"contacted",
"and",
"an",
"error",
"if",
"none",
"could",
"be",
"reached",
".",
"If",
"an",
"error",
"is",
"returned",
"the",
"node",
"did",
"not",
"successfully",
"join",
"the",
"cluster",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/memberlist.go#L228-L256
|
train
|
hashicorp/memberlist
|
memberlist.go
|
tcpLookupIP
|
func (m *Memberlist) tcpLookupIP(host string, defaultPort uint16) ([]ipPort, error) {
// Don't attempt any TCP lookups against non-fully qualified domain
// names, since those will likely come from the resolv.conf file.
if !strings.Contains(host, ".") {
return nil, nil
}
// Make sure the domain name is terminated with a dot (we know there's
// at least one character at this point).
dn := host
if dn[len(dn)-1] != '.' {
dn = dn + "."
}
// See if we can find a server to try.
cc, err := dns.ClientConfigFromFile(m.config.DNSConfigPath)
if err != nil {
return nil, err
}
if len(cc.Servers) > 0 {
// We support host:port in the DNS config, but need to add the
// default port if one is not supplied.
server := cc.Servers[0]
if !hasPort(server) {
server = net.JoinHostPort(server, cc.Port)
}
// Do the lookup.
c := new(dns.Client)
c.Net = "tcp"
msg := new(dns.Msg)
msg.SetQuestion(dn, dns.TypeANY)
in, _, err := c.Exchange(msg, server)
if err != nil {
return nil, err
}
// Handle any IPs we get back that we can attempt to join.
var ips []ipPort
for _, r := range in.Answer {
switch rr := r.(type) {
case (*dns.A):
ips = append(ips, ipPort{rr.A, defaultPort})
case (*dns.AAAA):
ips = append(ips, ipPort{rr.AAAA, defaultPort})
case (*dns.CNAME):
m.logger.Printf("[DEBUG] memberlist: Ignoring CNAME RR in TCP-first answer for '%s'", host)
}
}
return ips, nil
}
return nil, nil
}
|
go
|
func (m *Memberlist) tcpLookupIP(host string, defaultPort uint16) ([]ipPort, error) {
// Don't attempt any TCP lookups against non-fully qualified domain
// names, since those will likely come from the resolv.conf file.
if !strings.Contains(host, ".") {
return nil, nil
}
// Make sure the domain name is terminated with a dot (we know there's
// at least one character at this point).
dn := host
if dn[len(dn)-1] != '.' {
dn = dn + "."
}
// See if we can find a server to try.
cc, err := dns.ClientConfigFromFile(m.config.DNSConfigPath)
if err != nil {
return nil, err
}
if len(cc.Servers) > 0 {
// We support host:port in the DNS config, but need to add the
// default port if one is not supplied.
server := cc.Servers[0]
if !hasPort(server) {
server = net.JoinHostPort(server, cc.Port)
}
// Do the lookup.
c := new(dns.Client)
c.Net = "tcp"
msg := new(dns.Msg)
msg.SetQuestion(dn, dns.TypeANY)
in, _, err := c.Exchange(msg, server)
if err != nil {
return nil, err
}
// Handle any IPs we get back that we can attempt to join.
var ips []ipPort
for _, r := range in.Answer {
switch rr := r.(type) {
case (*dns.A):
ips = append(ips, ipPort{rr.A, defaultPort})
case (*dns.AAAA):
ips = append(ips, ipPort{rr.AAAA, defaultPort})
case (*dns.CNAME):
m.logger.Printf("[DEBUG] memberlist: Ignoring CNAME RR in TCP-first answer for '%s'", host)
}
}
return ips, nil
}
return nil, nil
}
|
[
"func",
"(",
"m",
"*",
"Memberlist",
")",
"tcpLookupIP",
"(",
"host",
"string",
",",
"defaultPort",
"uint16",
")",
"(",
"[",
"]",
"ipPort",
",",
"error",
")",
"{",
"if",
"!",
"strings",
".",
"Contains",
"(",
"host",
",",
"\".\"",
")",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"dn",
":=",
"host",
"\n",
"if",
"dn",
"[",
"len",
"(",
"dn",
")",
"-",
"1",
"]",
"!=",
"'.'",
"{",
"dn",
"=",
"dn",
"+",
"\".\"",
"\n",
"}",
"\n",
"cc",
",",
"err",
":=",
"dns",
".",
"ClientConfigFromFile",
"(",
"m",
".",
"config",
".",
"DNSConfigPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"cc",
".",
"Servers",
")",
">",
"0",
"{",
"server",
":=",
"cc",
".",
"Servers",
"[",
"0",
"]",
"\n",
"if",
"!",
"hasPort",
"(",
"server",
")",
"{",
"server",
"=",
"net",
".",
"JoinHostPort",
"(",
"server",
",",
"cc",
".",
"Port",
")",
"\n",
"}",
"\n",
"c",
":=",
"new",
"(",
"dns",
".",
"Client",
")",
"\n",
"c",
".",
"Net",
"=",
"\"tcp\"",
"\n",
"msg",
":=",
"new",
"(",
"dns",
".",
"Msg",
")",
"\n",
"msg",
".",
"SetQuestion",
"(",
"dn",
",",
"dns",
".",
"TypeANY",
")",
"\n",
"in",
",",
"_",
",",
"err",
":=",
"c",
".",
"Exchange",
"(",
"msg",
",",
"server",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"ips",
"[",
"]",
"ipPort",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"in",
".",
"Answer",
"{",
"switch",
"rr",
":=",
"r",
".",
"(",
"type",
")",
"{",
"case",
"(",
"*",
"dns",
".",
"A",
")",
":",
"ips",
"=",
"append",
"(",
"ips",
",",
"ipPort",
"{",
"rr",
".",
"A",
",",
"defaultPort",
"}",
")",
"\n",
"case",
"(",
"*",
"dns",
".",
"AAAA",
")",
":",
"ips",
"=",
"append",
"(",
"ips",
",",
"ipPort",
"{",
"rr",
".",
"AAAA",
",",
"defaultPort",
"}",
")",
"\n",
"case",
"(",
"*",
"dns",
".",
"CNAME",
")",
":",
"m",
".",
"logger",
".",
"Printf",
"(",
"\"[DEBUG] memberlist: Ignoring CNAME RR in TCP-first answer for '%s'\"",
",",
"host",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"ips",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}"
] |
// tcpLookupIP is a helper to initiate a TCP-based DNS lookup for the given host.
// The built-in Go resolver will do a UDP lookup first, and will only use TCP if
// the response has the truncate bit set, which isn't common on DNS servers like
// Consul's. By doing the TCP lookup directly, we get the best chance for the
// largest list of hosts to join. Since joins are relatively rare events, it's ok
// to do this rather expensive operation.
|
[
"tcpLookupIP",
"is",
"a",
"helper",
"to",
"initiate",
"a",
"TCP",
"-",
"based",
"DNS",
"lookup",
"for",
"the",
"given",
"host",
".",
"The",
"built",
"-",
"in",
"Go",
"resolver",
"will",
"do",
"a",
"UDP",
"lookup",
"first",
"and",
"will",
"only",
"use",
"TCP",
"if",
"the",
"response",
"has",
"the",
"truncate",
"bit",
"set",
"which",
"isn",
"t",
"common",
"on",
"DNS",
"servers",
"like",
"Consul",
"s",
".",
"By",
"doing",
"the",
"TCP",
"lookup",
"directly",
"we",
"get",
"the",
"best",
"chance",
"for",
"the",
"largest",
"list",
"of",
"hosts",
"to",
"join",
".",
"Since",
"joins",
"are",
"relatively",
"rare",
"events",
"it",
"s",
"ok",
"to",
"do",
"this",
"rather",
"expensive",
"operation",
"."
] |
a8f83c6403e0c718e9336784a270c09dc4613d3e
|
https://github.com/hashicorp/memberlist/blob/a8f83c6403e0c718e9336784a270c09dc4613d3e/memberlist.go#L270-L323
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.