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