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
RichardKnop/machinery
v1/server.go
SendChord
func (server *Server) SendChord(chord *tasks.Chord, sendConcurrency int) (*result.ChordAsyncResult, error) { return server.SendChordWithContext(context.Background(), chord, sendConcurrency) }
go
func (server *Server) SendChord(chord *tasks.Chord, sendConcurrency int) (*result.ChordAsyncResult, error) { return server.SendChordWithContext(context.Background(), chord, sendConcurrency) }
[ "func", "(", "server", "*", "Server", ")", "SendChord", "(", "chord", "*", "tasks", ".", "Chord", ",", "sendConcurrency", "int", ")", "(", "*", "result", ".", "ChordAsyncResult", ",", "error", ")", "{", "return", "server", ".", "SendChordWithContext", "(", "context", ".", "Background", "(", ")", ",", "chord", ",", "sendConcurrency", ")", "\n", "}" ]
// SendChord triggers a group of parallel tasks with a callback
[ "SendChord", "triggers", "a", "group", "of", "parallel", "tasks", "with", "a", "callback" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/server.go#L316-L318
train
RichardKnop/machinery
v1/server.go
GetRegisteredTaskNames
func (server *Server) GetRegisteredTaskNames() []string { taskNames := make([]string, len(server.registeredTasks)) var i = 0 for name := range server.registeredTasks { taskNames[i] = name i++ } return taskNames }
go
func (server *Server) GetRegisteredTaskNames() []string { taskNames := make([]string, len(server.registeredTasks)) var i = 0 for name := range server.registeredTasks { taskNames[i] = name i++ } return taskNames }
[ "func", "(", "server", "*", "Server", ")", "GetRegisteredTaskNames", "(", ")", "[", "]", "string", "{", "taskNames", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "server", ".", "registeredTasks", ")", ")", "\n", "var", "i", "=", "0", "\n", "for", "name", ":=", "range", "server", ".", "registeredTasks", "{", "taskNames", "[", "i", "]", "=", "name", "\n", "i", "++", "\n", "}", "\n", "return", "taskNames", "\n", "}" ]
// GetRegisteredTaskNames returns slice of registered task names
[ "GetRegisteredTaskNames", "returns", "slice", "of", "registered", "task", "names" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/server.go#L321-L329
train
RichardKnop/machinery
v1/log/log.go
Set
func Set(l logging.LoggerInterface) { DEBUG = l INFO = l WARNING = l ERROR = l FATAL = l }
go
func Set(l logging.LoggerInterface) { DEBUG = l INFO = l WARNING = l ERROR = l FATAL = l }
[ "func", "Set", "(", "l", "logging", ".", "LoggerInterface", ")", "{", "DEBUG", "=", "l", "\n", "INFO", "=", "l", "\n", "WARNING", "=", "l", "\n", "ERROR", "=", "l", "\n", "FATAL", "=", "l", "\n", "}" ]
// Set sets a custom logger for all log levels
[ "Set", "sets", "a", "custom", "logger", "for", "all", "log", "levels" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/log/log.go#L23-L29
train
RichardKnop/machinery
v1/brokers/redis/redis.go
GetPendingTasks
func (b *Broker) GetPendingTasks(queue string) ([]*tasks.Signature, error) { conn := b.open() defer conn.Close() if queue == "" { queue = b.GetConfig().DefaultQueue } dataBytes, err := conn.Do("LRANGE", queue, 0, -1) if err != nil { return nil, err } results, err := redis.ByteSlices(dataBytes, err) if err != nil { return nil, err } taskSignatures := make([]*tasks.Signature, len(results)) for i, result := range results { signature := new(tasks.Signature) decoder := json.NewDecoder(bytes.NewReader(result)) decoder.UseNumber() if err := decoder.Decode(signature); err != nil { return nil, err } taskSignatures[i] = signature } return taskSignatures, nil }
go
func (b *Broker) GetPendingTasks(queue string) ([]*tasks.Signature, error) { conn := b.open() defer conn.Close() if queue == "" { queue = b.GetConfig().DefaultQueue } dataBytes, err := conn.Do("LRANGE", queue, 0, -1) if err != nil { return nil, err } results, err := redis.ByteSlices(dataBytes, err) if err != nil { return nil, err } taskSignatures := make([]*tasks.Signature, len(results)) for i, result := range results { signature := new(tasks.Signature) decoder := json.NewDecoder(bytes.NewReader(result)) decoder.UseNumber() if err := decoder.Decode(signature); err != nil { return nil, err } taskSignatures[i] = signature } return taskSignatures, nil }
[ "func", "(", "b", "*", "Broker", ")", "GetPendingTasks", "(", "queue", "string", ")", "(", "[", "]", "*", "tasks", ".", "Signature", ",", "error", ")", "{", "conn", ":=", "b", ".", "open", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "if", "queue", "==", "\"\"", "{", "queue", "=", "b", ".", "GetConfig", "(", ")", ".", "DefaultQueue", "\n", "}", "\n", "dataBytes", ",", "err", ":=", "conn", ".", "Do", "(", "\"LRANGE\"", ",", "queue", ",", "0", ",", "-", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "results", ",", "err", ":=", "redis", ".", "ByteSlices", "(", "dataBytes", ",", "err", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "taskSignatures", ":=", "make", "(", "[", "]", "*", "tasks", ".", "Signature", ",", "len", "(", "results", ")", ")", "\n", "for", "i", ",", "result", ":=", "range", "results", "{", "signature", ":=", "new", "(", "tasks", ".", "Signature", ")", "\n", "decoder", ":=", "json", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "result", ")", ")", "\n", "decoder", ".", "UseNumber", "(", ")", "\n", "if", "err", ":=", "decoder", ".", "Decode", "(", "signature", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "taskSignatures", "[", "i", "]", "=", "signature", "\n", "}", "\n", "return", "taskSignatures", ",", "nil", "\n", "}" ]
// GetPendingTasks returns a slice of task signatures waiting in the queue
[ "GetPendingTasks", "returns", "a", "slice", "of", "task", "signatures", "waiting", "in", "the", "queue" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/brokers/redis/redis.go#L203-L230
train
RichardKnop/machinery
v1/brokers/redis/redis.go
nextTask
func (b *Broker) nextTask(queue string) (result []byte, err error) { conn := b.open() defer conn.Close() items, err := redis.ByteSlices(conn.Do("BLPOP", queue, 1000)) if err != nil { return []byte{}, err } // items[0] - the name of the key where an element was popped // items[1] - the value of the popped element if len(items) != 2 { return []byte{}, redis.ErrNil } result = items[1] return result, nil }
go
func (b *Broker) nextTask(queue string) (result []byte, err error) { conn := b.open() defer conn.Close() items, err := redis.ByteSlices(conn.Do("BLPOP", queue, 1000)) if err != nil { return []byte{}, err } // items[0] - the name of the key where an element was popped // items[1] - the value of the popped element if len(items) != 2 { return []byte{}, redis.ErrNil } result = items[1] return result, nil }
[ "func", "(", "b", "*", "Broker", ")", "nextTask", "(", "queue", "string", ")", "(", "result", "[", "]", "byte", ",", "err", "error", ")", "{", "conn", ":=", "b", ".", "open", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "items", ",", "err", ":=", "redis", ".", "ByteSlices", "(", "conn", ".", "Do", "(", "\"BLPOP\"", ",", "queue", ",", "1000", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "byte", "{", "}", ",", "err", "\n", "}", "\n", "if", "len", "(", "items", ")", "!=", "2", "{", "return", "[", "]", "byte", "{", "}", ",", "redis", ".", "ErrNil", "\n", "}", "\n", "result", "=", "items", "[", "1", "]", "\n", "return", "result", ",", "nil", "\n", "}" ]
// nextTask pops next available task from the default queue
[ "nextTask", "pops", "next", "available", "task", "from", "the", "default", "queue" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/brokers/redis/redis.go#L284-L302
train
RichardKnop/machinery
v1/brokers/redis/redis.go
open
func (b *Broker) open() redis.Conn { b.redisOnce.Do(func() { b.pool = b.NewPool(b.socketPath, b.host, b.password, b.db, b.GetConfig().Redis, b.GetConfig().TLSConfig) b.redsync = redsync.New([]redsync.Pool{b.pool}) }) return b.pool.Get() }
go
func (b *Broker) open() redis.Conn { b.redisOnce.Do(func() { b.pool = b.NewPool(b.socketPath, b.host, b.password, b.db, b.GetConfig().Redis, b.GetConfig().TLSConfig) b.redsync = redsync.New([]redsync.Pool{b.pool}) }) return b.pool.Get() }
[ "func", "(", "b", "*", "Broker", ")", "open", "(", ")", "redis", ".", "Conn", "{", "b", ".", "redisOnce", ".", "Do", "(", "func", "(", ")", "{", "b", ".", "pool", "=", "b", ".", "NewPool", "(", "b", ".", "socketPath", ",", "b", ".", "host", ",", "b", ".", "password", ",", "b", ".", "db", ",", "b", ".", "GetConfig", "(", ")", ".", "Redis", ",", "b", ".", "GetConfig", "(", ")", ".", "TLSConfig", ")", "\n", "b", ".", "redsync", "=", "redsync", ".", "New", "(", "[", "]", "redsync", ".", "Pool", "{", "b", ".", "pool", "}", ")", "\n", "}", ")", "\n", "return", "b", ".", "pool", ".", "Get", "(", ")", "\n", "}" ]
// open returns or creates instance of Redis connection
[ "open", "returns", "or", "creates", "instance", "of", "Redis", "connection" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/brokers/redis/redis.go#L378-L385
train
RichardKnop/machinery
v1/retry/fibonacci.go
Fibonacci
func Fibonacci() func() int { a, b := 0, 1 return func() int { a, b = b, a+b return a } }
go
func Fibonacci() func() int { a, b := 0, 1 return func() int { a, b = b, a+b return a } }
[ "func", "Fibonacci", "(", ")", "func", "(", ")", "int", "{", "a", ",", "b", ":=", "0", ",", "1", "\n", "return", "func", "(", ")", "int", "{", "a", ",", "b", "=", "b", ",", "a", "+", "b", "\n", "return", "a", "\n", "}", "\n", "}" ]
// Fibonacci returns successive Fibonacci numbers starting from 1
[ "Fibonacci", "returns", "successive", "Fibonacci", "numbers", "starting", "from", "1" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/retry/fibonacci.go#L4-L10
train
RichardKnop/machinery
v1/retry/fibonacci.go
FibonacciNext
func FibonacciNext(start int) int { fib := Fibonacci() num := fib() for num <= start { num = fib() } return num }
go
func FibonacciNext(start int) int { fib := Fibonacci() num := fib() for num <= start { num = fib() } return num }
[ "func", "FibonacciNext", "(", "start", "int", ")", "int", "{", "fib", ":=", "Fibonacci", "(", ")", "\n", "num", ":=", "fib", "(", ")", "\n", "for", "num", "<=", "start", "{", "num", "=", "fib", "(", ")", "\n", "}", "\n", "return", "num", "\n", "}" ]
// FibonacciNext returns next number in Fibonacci sequence greater than start
[ "FibonacciNext", "returns", "next", "number", "in", "Fibonacci", "sequence", "greater", "than", "start" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/retry/fibonacci.go#L13-L20
train
RichardKnop/machinery
v1/backends/mongo/mongodb.go
decodeResults
func (b *Backend) decodeResults(results []*tasks.TaskResult) []*tasks.TaskResult { l := len(results) jsonResults := make([]*tasks.TaskResult, l, l) for i, result := range results { jsonResult := new(bson.M) resultType := reflect.TypeOf(result.Value).Kind() if resultType == reflect.String { err := json.NewDecoder(strings.NewReader(result.Value.(string))).Decode(&jsonResult) if err == nil { jsonResults[i] = &tasks.TaskResult{ Type: "json", Value: jsonResult, } continue } } jsonResults[i] = result } return jsonResults }
go
func (b *Backend) decodeResults(results []*tasks.TaskResult) []*tasks.TaskResult { l := len(results) jsonResults := make([]*tasks.TaskResult, l, l) for i, result := range results { jsonResult := new(bson.M) resultType := reflect.TypeOf(result.Value).Kind() if resultType == reflect.String { err := json.NewDecoder(strings.NewReader(result.Value.(string))).Decode(&jsonResult) if err == nil { jsonResults[i] = &tasks.TaskResult{ Type: "json", Value: jsonResult, } continue } } jsonResults[i] = result } return jsonResults }
[ "func", "(", "b", "*", "Backend", ")", "decodeResults", "(", "results", "[", "]", "*", "tasks", ".", "TaskResult", ")", "[", "]", "*", "tasks", ".", "TaskResult", "{", "l", ":=", "len", "(", "results", ")", "\n", "jsonResults", ":=", "make", "(", "[", "]", "*", "tasks", ".", "TaskResult", ",", "l", ",", "l", ")", "\n", "for", "i", ",", "result", ":=", "range", "results", "{", "jsonResult", ":=", "new", "(", "bson", ".", "M", ")", "\n", "resultType", ":=", "reflect", ".", "TypeOf", "(", "result", ".", "Value", ")", ".", "Kind", "(", ")", "\n", "if", "resultType", "==", "reflect", ".", "String", "{", "err", ":=", "json", ".", "NewDecoder", "(", "strings", ".", "NewReader", "(", "result", ".", "Value", ".", "(", "string", ")", ")", ")", ".", "Decode", "(", "&", "jsonResult", ")", "\n", "if", "err", "==", "nil", "{", "jsonResults", "[", "i", "]", "=", "&", "tasks", ".", "TaskResult", "{", "Type", ":", "\"json\"", ",", "Value", ":", "jsonResult", ",", "}", "\n", "continue", "\n", "}", "\n", "}", "\n", "jsonResults", "[", "i", "]", "=", "result", "\n", "}", "\n", "return", "jsonResults", "\n", "}" ]
// decodeResults detects & decodes json strings in TaskResult.Value and returns a new slice
[ "decodeResults", "detects", "&", "decodes", "json", "strings", "in", "TaskResult", ".", "Value", "and", "returns", "a", "new", "slice" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/backends/mongo/mongodb.go#L148-L167
train
RichardKnop/machinery
v1/backends/mongo/mongodb.go
lockGroupMeta
func (b *Backend) lockGroupMeta(groupUUID string) error { query := bson.M{ "_id": groupUUID, "lock": false, } change := bson.M{ "$set": bson.M{ "lock": true, }, } _, err := b.groupMetasCollection.UpdateOne(context.Background(), query, change, options.Update().SetUpsert(true)) return err }
go
func (b *Backend) lockGroupMeta(groupUUID string) error { query := bson.M{ "_id": groupUUID, "lock": false, } change := bson.M{ "$set": bson.M{ "lock": true, }, } _, err := b.groupMetasCollection.UpdateOne(context.Background(), query, change, options.Update().SetUpsert(true)) return err }
[ "func", "(", "b", "*", "Backend", ")", "lockGroupMeta", "(", "groupUUID", "string", ")", "error", "{", "query", ":=", "bson", ".", "M", "{", "\"_id\"", ":", "groupUUID", ",", "\"lock\"", ":", "false", ",", "}", "\n", "change", ":=", "bson", ".", "M", "{", "\"$set\"", ":", "bson", ".", "M", "{", "\"lock\"", ":", "true", ",", "}", ",", "}", "\n", "_", ",", "err", ":=", "b", ".", "groupMetasCollection", ".", "UpdateOne", "(", "context", ".", "Background", "(", ")", ",", "query", ",", "change", ",", "options", ".", "Update", "(", ")", ".", "SetUpsert", "(", "true", ")", ")", "\n", "return", "err", "\n", "}" ]
// lockGroupMeta acquires lock on groupUUID document
[ "lockGroupMeta", "acquires", "lock", "on", "groupUUID", "document" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/backends/mongo/mongodb.go#L199-L213
train
RichardKnop/machinery
v1/backends/mongo/mongodb.go
unlockGroupMeta
func (b *Backend) unlockGroupMeta(groupUUID string) error { update := bson.M{"$set": bson.M{"lock": false}} _, err := b.groupMetasCollection.UpdateOne(context.Background(), bson.M{"_id": groupUUID}, update, options.Update()) return err }
go
func (b *Backend) unlockGroupMeta(groupUUID string) error { update := bson.M{"$set": bson.M{"lock": false}} _, err := b.groupMetasCollection.UpdateOne(context.Background(), bson.M{"_id": groupUUID}, update, options.Update()) return err }
[ "func", "(", "b", "*", "Backend", ")", "unlockGroupMeta", "(", "groupUUID", "string", ")", "error", "{", "update", ":=", "bson", ".", "M", "{", "\"$set\"", ":", "bson", ".", "M", "{", "\"lock\"", ":", "false", "}", "}", "\n", "_", ",", "err", ":=", "b", ".", "groupMetasCollection", ".", "UpdateOne", "(", "context", ".", "Background", "(", ")", ",", "bson", ".", "M", "{", "\"_id\"", ":", "groupUUID", "}", ",", "update", ",", "options", ".", "Update", "(", ")", ")", "\n", "return", "err", "\n", "}" ]
// unlockGroupMeta releases lock on groupUUID document
[ "unlockGroupMeta", "releases", "lock", "on", "groupUUID", "document" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/backends/mongo/mongodb.go#L216-L220
train
RichardKnop/machinery
v1/backends/mongo/mongodb.go
connect
func (b *Backend) connect() error { client, err := b.dial() if err != nil { return err } b.client = client database := "machinery" if b.GetConfig().MongoDB != nil { database = b.GetConfig().MongoDB.Database } b.tasksCollection = b.client.Database(database).Collection("tasks") b.groupMetasCollection = b.client.Database(database).Collection("group_metas") err = b.createMongoIndexes(database) if err != nil { return err } return nil }
go
func (b *Backend) connect() error { client, err := b.dial() if err != nil { return err } b.client = client database := "machinery" if b.GetConfig().MongoDB != nil { database = b.GetConfig().MongoDB.Database } b.tasksCollection = b.client.Database(database).Collection("tasks") b.groupMetasCollection = b.client.Database(database).Collection("group_metas") err = b.createMongoIndexes(database) if err != nil { return err } return nil }
[ "func", "(", "b", "*", "Backend", ")", "connect", "(", ")", "error", "{", "client", ",", "err", ":=", "b", ".", "dial", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "b", ".", "client", "=", "client", "\n", "database", ":=", "\"machinery\"", "\n", "if", "b", ".", "GetConfig", "(", ")", ".", "MongoDB", "!=", "nil", "{", "database", "=", "b", ".", "GetConfig", "(", ")", ".", "MongoDB", ".", "Database", "\n", "}", "\n", "b", ".", "tasksCollection", "=", "b", ".", "client", ".", "Database", "(", "database", ")", ".", "Collection", "(", "\"tasks\"", ")", "\n", "b", ".", "groupMetasCollection", "=", "b", ".", "client", ".", "Database", "(", "database", ")", ".", "Collection", "(", "\"group_metas\"", ")", "\n", "err", "=", "b", ".", "createMongoIndexes", "(", "database", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// connect creates the underlying mgo connection if it doesn't exist // creates required indexes for our collections
[ "connect", "creates", "the", "underlying", "mgo", "connection", "if", "it", "doesn", "t", "exist", "creates", "required", "indexes", "for", "our", "collections" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/backends/mongo/mongodb.go#L265-L286
train
RichardKnop/machinery
v1/backends/mongo/mongodb.go
dial
func (b *Backend) dial() (*mongo.Client, error) { if b.GetConfig().MongoDB != nil && b.GetConfig().MongoDB.Client != nil { return b.GetConfig().MongoDB.Client, nil } uri := b.GetConfig().ResultBackend if strings.HasPrefix(uri, "mongodb://") == false && strings.HasPrefix(uri, "mongodb+srv://") == false { uri = fmt.Sprintf("mongodb://%s", uri) } client, err := mongo.NewClient(options.Client().ApplyURI(uri)) if err != nil { return nil, err } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := client.Connect(ctx); err != nil { return nil, err } return client, nil }
go
func (b *Backend) dial() (*mongo.Client, error) { if b.GetConfig().MongoDB != nil && b.GetConfig().MongoDB.Client != nil { return b.GetConfig().MongoDB.Client, nil } uri := b.GetConfig().ResultBackend if strings.HasPrefix(uri, "mongodb://") == false && strings.HasPrefix(uri, "mongodb+srv://") == false { uri = fmt.Sprintf("mongodb://%s", uri) } client, err := mongo.NewClient(options.Client().ApplyURI(uri)) if err != nil { return nil, err } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := client.Connect(ctx); err != nil { return nil, err } return client, nil }
[ "func", "(", "b", "*", "Backend", ")", "dial", "(", ")", "(", "*", "mongo", ".", "Client", ",", "error", ")", "{", "if", "b", ".", "GetConfig", "(", ")", ".", "MongoDB", "!=", "nil", "&&", "b", ".", "GetConfig", "(", ")", ".", "MongoDB", ".", "Client", "!=", "nil", "{", "return", "b", ".", "GetConfig", "(", ")", ".", "MongoDB", ".", "Client", ",", "nil", "\n", "}", "\n", "uri", ":=", "b", ".", "GetConfig", "(", ")", ".", "ResultBackend", "\n", "if", "strings", ".", "HasPrefix", "(", "uri", ",", "\"mongodb://\"", ")", "==", "false", "&&", "strings", ".", "HasPrefix", "(", "uri", ",", "\"mongodb+srv://\"", ")", "==", "false", "{", "uri", "=", "fmt", ".", "Sprintf", "(", "\"mongodb://%s\"", ",", "uri", ")", "\n", "}", "\n", "client", ",", "err", ":=", "mongo", ".", "NewClient", "(", "options", ".", "Client", "(", ")", ".", "ApplyURI", "(", "uri", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "10", "*", "time", ".", "Second", ")", "\n", "defer", "cancel", "(", ")", "\n", "if", "err", ":=", "client", ".", "Connect", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "client", ",", "nil", "\n", "}" ]
// dial connects to mongo with TLSConfig if provided // else connects via ResultBackend uri
[ "dial", "connects", "to", "mongo", "with", "TLSConfig", "if", "provided", "else", "connects", "via", "ResultBackend", "uri" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/backends/mongo/mongodb.go#L290-L315
train
RichardKnop/machinery
v1/backends/mongo/mongodb.go
createMongoIndexes
func (b *Backend) createMongoIndexes(database string) error { tasksCollection := b.client.Database(database).Collection("tasks") expireIn := int32(b.GetConfig().ResultsExpireIn) _, err := tasksCollection.Indexes().CreateMany(context.Background(), []mongo.IndexModel{ { Keys: bson.M{"state": 1}, Options: options.Index().SetBackground(true).SetExpireAfterSeconds(expireIn), }, mongo.IndexModel{ Keys: bson.M{"lock": 1}, Options: options.Index().SetBackground(true).SetExpireAfterSeconds(expireIn), }, }) if err != nil { return err } return err }
go
func (b *Backend) createMongoIndexes(database string) error { tasksCollection := b.client.Database(database).Collection("tasks") expireIn := int32(b.GetConfig().ResultsExpireIn) _, err := tasksCollection.Indexes().CreateMany(context.Background(), []mongo.IndexModel{ { Keys: bson.M{"state": 1}, Options: options.Index().SetBackground(true).SetExpireAfterSeconds(expireIn), }, mongo.IndexModel{ Keys: bson.M{"lock": 1}, Options: options.Index().SetBackground(true).SetExpireAfterSeconds(expireIn), }, }) if err != nil { return err } return err }
[ "func", "(", "b", "*", "Backend", ")", "createMongoIndexes", "(", "database", "string", ")", "error", "{", "tasksCollection", ":=", "b", ".", "client", ".", "Database", "(", "database", ")", ".", "Collection", "(", "\"tasks\"", ")", "\n", "expireIn", ":=", "int32", "(", "b", ".", "GetConfig", "(", ")", ".", "ResultsExpireIn", ")", "\n", "_", ",", "err", ":=", "tasksCollection", ".", "Indexes", "(", ")", ".", "CreateMany", "(", "context", ".", "Background", "(", ")", ",", "[", "]", "mongo", ".", "IndexModel", "{", "{", "Keys", ":", "bson", ".", "M", "{", "\"state\"", ":", "1", "}", ",", "Options", ":", "options", ".", "Index", "(", ")", ".", "SetBackground", "(", "true", ")", ".", "SetExpireAfterSeconds", "(", "expireIn", ")", ",", "}", ",", "mongo", ".", "IndexModel", "{", "Keys", ":", "bson", ".", "M", "{", "\"lock\"", ":", "1", "}", ",", "Options", ":", "options", ".", "Index", "(", ")", ".", "SetBackground", "(", "true", ")", ".", "SetExpireAfterSeconds", "(", "expireIn", ")", ",", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "err", "\n", "}" ]
// createMongoIndexes ensures all indexes are in place
[ "createMongoIndexes", "ensures", "all", "indexes", "are", "in", "place" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/backends/mongo/mongodb.go#L318-L339
train
RichardKnop/machinery
v1/brokers/errs/errors.go
NewErrCouldNotUnmarshaTaskSignature
func NewErrCouldNotUnmarshaTaskSignature(msg []byte, err error) ErrCouldNotUnmarshaTaskSignature { return ErrCouldNotUnmarshaTaskSignature{msg: msg, reason: err.Error()} }
go
func NewErrCouldNotUnmarshaTaskSignature(msg []byte, err error) ErrCouldNotUnmarshaTaskSignature { return ErrCouldNotUnmarshaTaskSignature{msg: msg, reason: err.Error()} }
[ "func", "NewErrCouldNotUnmarshaTaskSignature", "(", "msg", "[", "]", "byte", ",", "err", "error", ")", "ErrCouldNotUnmarshaTaskSignature", "{", "return", "ErrCouldNotUnmarshaTaskSignature", "{", "msg", ":", "msg", ",", "reason", ":", "err", ".", "Error", "(", ")", "}", "\n", "}" ]
// NewErrCouldNotUnmarshaTaskSignature returns new ErrCouldNotUnmarshaTaskSignature instance
[ "NewErrCouldNotUnmarshaTaskSignature", "returns", "new", "ErrCouldNotUnmarshaTaskSignature", "instance" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/brokers/errs/errors.go#L19-L21
train
RichardKnop/machinery
v1/tasks/errors.go
NewErrRetryTaskLater
func NewErrRetryTaskLater(msg string, retryIn time.Duration) ErrRetryTaskLater { return ErrRetryTaskLater{msg: msg, retryIn: retryIn} }
go
func NewErrRetryTaskLater(msg string, retryIn time.Duration) ErrRetryTaskLater { return ErrRetryTaskLater{msg: msg, retryIn: retryIn} }
[ "func", "NewErrRetryTaskLater", "(", "msg", "string", ",", "retryIn", "time", ".", "Duration", ")", "ErrRetryTaskLater", "{", "return", "ErrRetryTaskLater", "{", "msg", ":", "msg", ",", "retryIn", ":", "retryIn", "}", "\n", "}" ]
// NewErrRetryTaskLater returns new ErrRetryTaskLater instance
[ "NewErrRetryTaskLater", "returns", "new", "ErrRetryTaskLater", "instance" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/tasks/errors.go#L25-L27
train
RichardKnop/machinery
v1/backends/redis/redis.go
setExpirationTime
func (b *Backend) setExpirationTime(key string) error { expiresIn := b.GetConfig().ResultsExpireIn if expiresIn == 0 { // // expire results after 1 hour by default expiresIn = config.DefaultResultsExpireIn } expirationTimestamp := int32(time.Now().Unix() + int64(expiresIn)) conn := b.open() defer conn.Close() _, err := conn.Do("EXPIREAT", key, expirationTimestamp) if err != nil { return err } return nil }
go
func (b *Backend) setExpirationTime(key string) error { expiresIn := b.GetConfig().ResultsExpireIn if expiresIn == 0 { // // expire results after 1 hour by default expiresIn = config.DefaultResultsExpireIn } expirationTimestamp := int32(time.Now().Unix() + int64(expiresIn)) conn := b.open() defer conn.Close() _, err := conn.Do("EXPIREAT", key, expirationTimestamp) if err != nil { return err } return nil }
[ "func", "(", "b", "*", "Backend", ")", "setExpirationTime", "(", "key", "string", ")", "error", "{", "expiresIn", ":=", "b", ".", "GetConfig", "(", ")", ".", "ResultsExpireIn", "\n", "if", "expiresIn", "==", "0", "{", "expiresIn", "=", "config", ".", "DefaultResultsExpireIn", "\n", "}", "\n", "expirationTimestamp", ":=", "int32", "(", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", "+", "int64", "(", "expiresIn", ")", ")", "\n", "conn", ":=", "b", ".", "open", "(", ")", "\n", "defer", "conn", ".", "Close", "(", ")", "\n", "_", ",", "err", ":=", "conn", ".", "Do", "(", "\"EXPIREAT\"", ",", "key", ",", "expirationTimestamp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// setExpirationTime sets expiration timestamp on a stored task state
[ "setExpirationTime", "sets", "expiration", "timestamp", "on", "a", "stored", "task", "state" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/backends/redis/redis.go#L312-L329
train
RichardKnop/machinery
v1/brokers/amqp/amqp.go
GetOrOpenConnection
func (b *Broker) GetOrOpenConnection(queueName string, queueBindingKey string, exchangeDeclareArgs, queueDeclareArgs, queueBindingArgs amqp.Table) (*AMQPConnection, error) { var err error b.connectionsMutex.Lock() defer b.connectionsMutex.Unlock() conn, ok := b.connections[queueName] if !ok { conn = &AMQPConnection{ queueName: queueName, cleanup: make(chan struct{}), } conn.connection, conn.channel, conn.queue, conn.confirmation, conn.errorchan, err = b.Connect( b.GetConfig().Broker, b.GetConfig().TLSConfig, b.GetConfig().AMQP.Exchange, // exchange name b.GetConfig().AMQP.ExchangeType, // exchange type queueName, // queue name true, // queue durable false, // queue delete when unused queueBindingKey, // queue binding key exchangeDeclareArgs, // exchange declare args queueDeclareArgs, // queue declare args queueBindingArgs, // queue binding args ) if err != nil { return nil, err } // Reconnect to the channel if it disconnects/errors out go func() { select { case err = <-conn.errorchan: log.INFO.Printf("Error occured on queue: %s. Reconnecting", queueName) _, err := b.GetOrOpenConnection(queueName, queueBindingKey, exchangeDeclareArgs, queueDeclareArgs, queueBindingArgs) if err != nil { log.ERROR.Printf("Failed to reopen queue: %s.", queueName) } case <-conn.cleanup: return } return }() b.connections[queueName] = conn } return conn, nil }
go
func (b *Broker) GetOrOpenConnection(queueName string, queueBindingKey string, exchangeDeclareArgs, queueDeclareArgs, queueBindingArgs amqp.Table) (*AMQPConnection, error) { var err error b.connectionsMutex.Lock() defer b.connectionsMutex.Unlock() conn, ok := b.connections[queueName] if !ok { conn = &AMQPConnection{ queueName: queueName, cleanup: make(chan struct{}), } conn.connection, conn.channel, conn.queue, conn.confirmation, conn.errorchan, err = b.Connect( b.GetConfig().Broker, b.GetConfig().TLSConfig, b.GetConfig().AMQP.Exchange, // exchange name b.GetConfig().AMQP.ExchangeType, // exchange type queueName, // queue name true, // queue durable false, // queue delete when unused queueBindingKey, // queue binding key exchangeDeclareArgs, // exchange declare args queueDeclareArgs, // queue declare args queueBindingArgs, // queue binding args ) if err != nil { return nil, err } // Reconnect to the channel if it disconnects/errors out go func() { select { case err = <-conn.errorchan: log.INFO.Printf("Error occured on queue: %s. Reconnecting", queueName) _, err := b.GetOrOpenConnection(queueName, queueBindingKey, exchangeDeclareArgs, queueDeclareArgs, queueBindingArgs) if err != nil { log.ERROR.Printf("Failed to reopen queue: %s.", queueName) } case <-conn.cleanup: return } return }() b.connections[queueName] = conn } return conn, nil }
[ "func", "(", "b", "*", "Broker", ")", "GetOrOpenConnection", "(", "queueName", "string", ",", "queueBindingKey", "string", ",", "exchangeDeclareArgs", ",", "queueDeclareArgs", ",", "queueBindingArgs", "amqp", ".", "Table", ")", "(", "*", "AMQPConnection", ",", "error", ")", "{", "var", "err", "error", "\n", "b", ".", "connectionsMutex", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "connectionsMutex", ".", "Unlock", "(", ")", "\n", "conn", ",", "ok", ":=", "b", ".", "connections", "[", "queueName", "]", "\n", "if", "!", "ok", "{", "conn", "=", "&", "AMQPConnection", "{", "queueName", ":", "queueName", ",", "cleanup", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "conn", ".", "connection", ",", "conn", ".", "channel", ",", "conn", ".", "queue", ",", "conn", ".", "confirmation", ",", "conn", ".", "errorchan", ",", "err", "=", "b", ".", "Connect", "(", "b", ".", "GetConfig", "(", ")", ".", "Broker", ",", "b", ".", "GetConfig", "(", ")", ".", "TLSConfig", ",", "b", ".", "GetConfig", "(", ")", ".", "AMQP", ".", "Exchange", ",", "b", ".", "GetConfig", "(", ")", ".", "AMQP", ".", "ExchangeType", ",", "queueName", ",", "true", ",", "false", ",", "queueBindingKey", ",", "exchangeDeclareArgs", ",", "queueDeclareArgs", ",", "queueBindingArgs", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "go", "func", "(", ")", "{", "select", "{", "case", "err", "=", "<-", "conn", ".", "errorchan", ":", "log", ".", "INFO", ".", "Printf", "(", "\"Error occured on queue: %s. Reconnecting\"", ",", "queueName", ")", "\n", "_", ",", "err", ":=", "b", ".", "GetOrOpenConnection", "(", "queueName", ",", "queueBindingKey", ",", "exchangeDeclareArgs", ",", "queueDeclareArgs", ",", "queueBindingArgs", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "ERROR", ".", "Printf", "(", "\"Failed to reopen queue: %s.\"", ",", "queueName", ")", "\n", "}", "\n", "case", "<-", "conn", ".", "cleanup", ":", "return", "\n", "}", "\n", "return", "\n", "}", "(", ")", "\n", "b", ".", "connections", "[", "queueName", "]", "=", "conn", "\n", "}", "\n", "return", "conn", ",", "nil", "\n", "}" ]
// GetOrOpenConnection will return a connection on a particular queue name. Open connections // are saved to avoid having to reopen connection for multiple queues
[ "GetOrOpenConnection", "will", "return", "a", "connection", "on", "a", "particular", "queue", "name", ".", "Open", "connections", "are", "saved", "to", "avoid", "having", "to", "reopen", "connection", "for", "multiple", "queues" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/brokers/amqp/amqp.go#L117-L163
train
RichardKnop/machinery
v1/brokers/amqp/amqp.go
delay
func (b *Broker) delay(signature *tasks.Signature, delayMs int64) error { if delayMs <= 0 { return errors.New("Cannot delay task by 0ms") } message, err := json.Marshal(signature) if err != nil { return fmt.Errorf("JSON marshal error: %s", err) } // It's necessary to redeclare the queue each time (to zero its TTL timer). queueName := fmt.Sprintf( "delay.%d.%s.%s", delayMs, // delay duration in mileseconds b.GetConfig().AMQP.Exchange, signature.RoutingKey, // routing key ) declareQueueArgs := amqp.Table{ // Exchange where to send messages after TTL expiration. "x-dead-letter-exchange": b.GetConfig().AMQP.Exchange, // Routing key which use when resending expired messages. "x-dead-letter-routing-key": signature.RoutingKey, // Time in milliseconds // after that message will expire and be sent to destination. "x-message-ttl": delayMs, // Time after that the queue will be deleted. "x-expires": delayMs * 2, } conn, channel, _, _, _, err := b.Connect( b.GetConfig().Broker, b.GetConfig().TLSConfig, b.GetConfig().AMQP.Exchange, // exchange name b.GetConfig().AMQP.ExchangeType, // exchange type queueName, // queue name true, // queue durable false, // queue delete when unused queueName, // queue binding key nil, // exchange declare args declareQueueArgs, // queue declare args amqp.Table(b.GetConfig().AMQP.QueueBindingArgs), // queue binding args ) if err != nil { return err } defer b.Close(channel, conn) if err := channel.Publish( b.GetConfig().AMQP.Exchange, // exchange queueName, // routing key false, // mandatory false, // immediate amqp.Publishing{ Headers: amqp.Table(signature.Headers), ContentType: "application/json", Body: message, DeliveryMode: amqp.Persistent, }, ); err != nil { return err } return nil }
go
func (b *Broker) delay(signature *tasks.Signature, delayMs int64) error { if delayMs <= 0 { return errors.New("Cannot delay task by 0ms") } message, err := json.Marshal(signature) if err != nil { return fmt.Errorf("JSON marshal error: %s", err) } // It's necessary to redeclare the queue each time (to zero its TTL timer). queueName := fmt.Sprintf( "delay.%d.%s.%s", delayMs, // delay duration in mileseconds b.GetConfig().AMQP.Exchange, signature.RoutingKey, // routing key ) declareQueueArgs := amqp.Table{ // Exchange where to send messages after TTL expiration. "x-dead-letter-exchange": b.GetConfig().AMQP.Exchange, // Routing key which use when resending expired messages. "x-dead-letter-routing-key": signature.RoutingKey, // Time in milliseconds // after that message will expire and be sent to destination. "x-message-ttl": delayMs, // Time after that the queue will be deleted. "x-expires": delayMs * 2, } conn, channel, _, _, _, err := b.Connect( b.GetConfig().Broker, b.GetConfig().TLSConfig, b.GetConfig().AMQP.Exchange, // exchange name b.GetConfig().AMQP.ExchangeType, // exchange type queueName, // queue name true, // queue durable false, // queue delete when unused queueName, // queue binding key nil, // exchange declare args declareQueueArgs, // queue declare args amqp.Table(b.GetConfig().AMQP.QueueBindingArgs), // queue binding args ) if err != nil { return err } defer b.Close(channel, conn) if err := channel.Publish( b.GetConfig().AMQP.Exchange, // exchange queueName, // routing key false, // mandatory false, // immediate amqp.Publishing{ Headers: amqp.Table(signature.Headers), ContentType: "application/json", Body: message, DeliveryMode: amqp.Persistent, }, ); err != nil { return err } return nil }
[ "func", "(", "b", "*", "Broker", ")", "delay", "(", "signature", "*", "tasks", ".", "Signature", ",", "delayMs", "int64", ")", "error", "{", "if", "delayMs", "<=", "0", "{", "return", "errors", ".", "New", "(", "\"Cannot delay task by 0ms\"", ")", "\n", "}", "\n", "message", ",", "err", ":=", "json", ".", "Marshal", "(", "signature", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"JSON marshal error: %s\"", ",", "err", ")", "\n", "}", "\n", "queueName", ":=", "fmt", ".", "Sprintf", "(", "\"delay.%d.%s.%s\"", ",", "delayMs", ",", "b", ".", "GetConfig", "(", ")", ".", "AMQP", ".", "Exchange", ",", "signature", ".", "RoutingKey", ",", ")", "\n", "declareQueueArgs", ":=", "amqp", ".", "Table", "{", "\"x-dead-letter-exchange\"", ":", "b", ".", "GetConfig", "(", ")", ".", "AMQP", ".", "Exchange", ",", "\"x-dead-letter-routing-key\"", ":", "signature", ".", "RoutingKey", ",", "\"x-message-ttl\"", ":", "delayMs", ",", "\"x-expires\"", ":", "delayMs", "*", "2", ",", "}", "\n", "conn", ",", "channel", ",", "_", ",", "_", ",", "_", ",", "err", ":=", "b", ".", "Connect", "(", "b", ".", "GetConfig", "(", ")", ".", "Broker", ",", "b", ".", "GetConfig", "(", ")", ".", "TLSConfig", ",", "b", ".", "GetConfig", "(", ")", ".", "AMQP", ".", "Exchange", ",", "b", ".", "GetConfig", "(", ")", ".", "AMQP", ".", "ExchangeType", ",", "queueName", ",", "true", ",", "false", ",", "queueName", ",", "nil", ",", "declareQueueArgs", ",", "amqp", ".", "Table", "(", "b", ".", "GetConfig", "(", ")", ".", "AMQP", ".", "QueueBindingArgs", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "b", ".", "Close", "(", "channel", ",", "conn", ")", "\n", "if", "err", ":=", "channel", ".", "Publish", "(", "b", ".", "GetConfig", "(", ")", ".", "AMQP", ".", "Exchange", ",", "queueName", ",", "false", ",", "false", ",", "amqp", ".", "Publishing", "{", "Headers", ":", "amqp", ".", "Table", "(", "signature", ".", "Headers", ")", ",", "ContentType", ":", "\"application/json\"", ",", "Body", ":", "message", ",", "DeliveryMode", ":", "amqp", ".", "Persistent", ",", "}", ",", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// delay a task by delayDuration miliseconds, the way it works is a new queue // is created without any consumers, the message is then published to this queue // with appropriate ttl expiration headers, after the expiration, it is sent to // the proper queue with consumers
[ "delay", "a", "task", "by", "delayDuration", "miliseconds", "the", "way", "it", "works", "is", "a", "new", "queue", "is", "created", "without", "any", "consumers", "the", "message", "is", "then", "published", "to", "this", "queue", "with", "appropriate", "ttl", "expiration", "headers", "after", "the", "expiration", "it", "is", "sent", "to", "the", "proper", "queue", "with", "consumers" ]
07418869e268a380aea5b9aefbb0b9f5bb715a12
https://github.com/RichardKnop/machinery/blob/07418869e268a380aea5b9aefbb0b9f5bb715a12/v1/brokers/amqp/amqp.go#L327-L390
train
cri-o/cri-o
server/version.go
Version
func (s *Server) Version(ctx context.Context, req *pb.VersionRequest) (resp *pb.VersionResponse, err error) { const operation = "version" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() return &pb.VersionResponse{ Version: kubeAPIVersion, RuntimeName: containerName, RuntimeVersion: version.Version, RuntimeApiVersion: runtimeAPIVersion, }, nil }
go
func (s *Server) Version(ctx context.Context, req *pb.VersionRequest) (resp *pb.VersionResponse, err error) { const operation = "version" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() return &pb.VersionResponse{ Version: kubeAPIVersion, RuntimeName: containerName, RuntimeVersion: version.Version, RuntimeApiVersion: runtimeAPIVersion, }, nil }
[ "func", "(", "s", "*", "Server", ")", "Version", "(", "ctx", "context", ".", "Context", ",", "req", "*", "pb", ".", "VersionRequest", ")", "(", "resp", "*", "pb", ".", "VersionResponse", ",", "err", "error", ")", "{", "const", "operation", "=", "\"version\"", "\n", "defer", "func", "(", ")", "{", "recordOperation", "(", "operation", ",", "time", ".", "Now", "(", ")", ")", "\n", "recordError", "(", "operation", ",", "err", ")", "\n", "}", "(", ")", "\n", "return", "&", "pb", ".", "VersionResponse", "{", "Version", ":", "kubeAPIVersion", ",", "RuntimeName", ":", "containerName", ",", "RuntimeVersion", ":", "version", ".", "Version", ",", "RuntimeApiVersion", ":", "runtimeAPIVersion", ",", "}", ",", "nil", "\n", "}" ]
// Version returns the runtime name, runtime version and runtime API version
[ "Version", "returns", "the", "runtime", "name", "runtime", "version", "and", "runtime", "API", "version" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/version.go#L22-L35
train
cri-o/cri-o
lib/sandbox/sandbox.go
NetNsGet
func (s *Sandbox) NetNsGet(nspath, name string) (*NetNs, error) { if err := ns.IsNSorErr(nspath); err != nil { return nil, ErrClosedNetNS } symlink, symlinkErr := isSymbolicLink(nspath) if symlinkErr != nil { return nil, symlinkErr } var resolvedNsPath string if symlink { path, err := os.Readlink(nspath) if err != nil { return nil, err } resolvedNsPath = path } else { resolvedNsPath = nspath } netNs, err := getNetNs(resolvedNsPath) if err != nil { return nil, err } if symlink { fd, err := os.Open(nspath) if err != nil { return nil, err } netNs.symlink = fd } else if err := netNs.SymlinkCreate(name); err != nil { return nil, err } return netNs, nil }
go
func (s *Sandbox) NetNsGet(nspath, name string) (*NetNs, error) { if err := ns.IsNSorErr(nspath); err != nil { return nil, ErrClosedNetNS } symlink, symlinkErr := isSymbolicLink(nspath) if symlinkErr != nil { return nil, symlinkErr } var resolvedNsPath string if symlink { path, err := os.Readlink(nspath) if err != nil { return nil, err } resolvedNsPath = path } else { resolvedNsPath = nspath } netNs, err := getNetNs(resolvedNsPath) if err != nil { return nil, err } if symlink { fd, err := os.Open(nspath) if err != nil { return nil, err } netNs.symlink = fd } else if err := netNs.SymlinkCreate(name); err != nil { return nil, err } return netNs, nil }
[ "func", "(", "s", "*", "Sandbox", ")", "NetNsGet", "(", "nspath", ",", "name", "string", ")", "(", "*", "NetNs", ",", "error", ")", "{", "if", "err", ":=", "ns", ".", "IsNSorErr", "(", "nspath", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "ErrClosedNetNS", "\n", "}", "\n", "symlink", ",", "symlinkErr", ":=", "isSymbolicLink", "(", "nspath", ")", "\n", "if", "symlinkErr", "!=", "nil", "{", "return", "nil", ",", "symlinkErr", "\n", "}", "\n", "var", "resolvedNsPath", "string", "\n", "if", "symlink", "{", "path", ",", "err", ":=", "os", ".", "Readlink", "(", "nspath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "resolvedNsPath", "=", "path", "\n", "}", "else", "{", "resolvedNsPath", "=", "nspath", "\n", "}", "\n", "netNs", ",", "err", ":=", "getNetNs", "(", "resolvedNsPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "symlink", "{", "fd", ",", "err", ":=", "os", ".", "Open", "(", "nspath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "netNs", ".", "symlink", "=", "fd", "\n", "}", "else", "if", "err", ":=", "netNs", ".", "SymlinkCreate", "(", "name", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "netNs", ",", "nil", "\n", "}" ]
// NetNsGet returns the NetNs associated with the given nspath and name
[ "NetNsGet", "returns", "the", "NetNs", "associated", "with", "the", "given", "nspath", "and", "name" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox.go#L28-L66
train
cri-o/cri-o
lib/sandbox/sandbox.go
New
func New(id, namespace, name, kubeName, logDir string, labels, annotations map[string]string, processLabel, mountLabel string, metadata *pb.PodSandboxMetadata, shmPath, cgroupParent string, privileged bool, runtimeHandler string, resolvPath, hostname string, portMappings []*hostport.PortMapping, hostNetwork bool) (*Sandbox, error) { sb := new(Sandbox) sb.id = id sb.namespace = namespace sb.name = name sb.kubeName = kubeName sb.logDir = logDir sb.labels = labels sb.annotations = annotations sb.containers = oci.NewMemoryStore() sb.processLabel = processLabel sb.mountLabel = mountLabel sb.metadata = metadata sb.shmPath = shmPath sb.cgroupParent = cgroupParent sb.privileged = privileged sb.runtimeHandler = runtimeHandler sb.resolvPath = resolvPath sb.hostname = hostname sb.portMappings = portMappings sb.createdAt = time.Now() sb.hostNetwork = hostNetwork return sb, nil }
go
func New(id, namespace, name, kubeName, logDir string, labels, annotations map[string]string, processLabel, mountLabel string, metadata *pb.PodSandboxMetadata, shmPath, cgroupParent string, privileged bool, runtimeHandler string, resolvPath, hostname string, portMappings []*hostport.PortMapping, hostNetwork bool) (*Sandbox, error) { sb := new(Sandbox) sb.id = id sb.namespace = namespace sb.name = name sb.kubeName = kubeName sb.logDir = logDir sb.labels = labels sb.annotations = annotations sb.containers = oci.NewMemoryStore() sb.processLabel = processLabel sb.mountLabel = mountLabel sb.metadata = metadata sb.shmPath = shmPath sb.cgroupParent = cgroupParent sb.privileged = privileged sb.runtimeHandler = runtimeHandler sb.resolvPath = resolvPath sb.hostname = hostname sb.portMappings = portMappings sb.createdAt = time.Now() sb.hostNetwork = hostNetwork return sb, nil }
[ "func", "New", "(", "id", ",", "namespace", ",", "name", ",", "kubeName", ",", "logDir", "string", ",", "labels", ",", "annotations", "map", "[", "string", "]", "string", ",", "processLabel", ",", "mountLabel", "string", ",", "metadata", "*", "pb", ".", "PodSandboxMetadata", ",", "shmPath", ",", "cgroupParent", "string", ",", "privileged", "bool", ",", "runtimeHandler", "string", ",", "resolvPath", ",", "hostname", "string", ",", "portMappings", "[", "]", "*", "hostport", ".", "PortMapping", ",", "hostNetwork", "bool", ")", "(", "*", "Sandbox", ",", "error", ")", "{", "sb", ":=", "new", "(", "Sandbox", ")", "\n", "sb", ".", "id", "=", "id", "\n", "sb", ".", "namespace", "=", "namespace", "\n", "sb", ".", "name", "=", "name", "\n", "sb", ".", "kubeName", "=", "kubeName", "\n", "sb", ".", "logDir", "=", "logDir", "\n", "sb", ".", "labels", "=", "labels", "\n", "sb", ".", "annotations", "=", "annotations", "\n", "sb", ".", "containers", "=", "oci", ".", "NewMemoryStore", "(", ")", "\n", "sb", ".", "processLabel", "=", "processLabel", "\n", "sb", ".", "mountLabel", "=", "mountLabel", "\n", "sb", ".", "metadata", "=", "metadata", "\n", "sb", ".", "shmPath", "=", "shmPath", "\n", "sb", ".", "cgroupParent", "=", "cgroupParent", "\n", "sb", ".", "privileged", "=", "privileged", "\n", "sb", ".", "runtimeHandler", "=", "runtimeHandler", "\n", "sb", ".", "resolvPath", "=", "resolvPath", "\n", "sb", ".", "hostname", "=", "hostname", "\n", "sb", ".", "portMappings", "=", "portMappings", "\n", "sb", ".", "createdAt", "=", "time", ".", "Now", "(", ")", "\n", "sb", ".", "hostNetwork", "=", "hostNetwork", "\n", "return", "sb", ",", "nil", "\n", "}" ]
// New creates and populates a new pod sandbox // New sandboxes have no containers, no infra container, and no network namespaces associated with them // An infra container must be attached before the sandbox is added to the state
[ "New", "creates", "and", "populates", "a", "new", "pod", "sandbox", "New", "sandboxes", "have", "no", "containers", "no", "infra", "container", "and", "no", "network", "namespaces", "associated", "with", "them", "An", "infra", "container", "must", "be", "attached", "before", "the", "sandbox", "is", "added", "to", "the", "state" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox.go#L152-L176
train
cri-o/cri-o
lib/sandbox/sandbox.go
AddContainer
func (s *Sandbox) AddContainer(c *oci.Container) { s.containers.Add(c.Name(), c) }
go
func (s *Sandbox) AddContainer(c *oci.Container) { s.containers.Add(c.Name(), c) }
[ "func", "(", "s", "*", "Sandbox", ")", "AddContainer", "(", "c", "*", "oci", ".", "Container", ")", "{", "s", ".", "containers", ".", "Add", "(", "c", ".", "Name", "(", ")", ",", "c", ")", "\n", "}" ]
// AddContainer adds a container to the sandbox
[ "AddContainer", "adds", "a", "container", "to", "the", "sandbox" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox.go#L328-L330
train
cri-o/cri-o
lib/sandbox/sandbox.go
GetContainer
func (s *Sandbox) GetContainer(name string) *oci.Container { return s.containers.Get(name) }
go
func (s *Sandbox) GetContainer(name string) *oci.Container { return s.containers.Get(name) }
[ "func", "(", "s", "*", "Sandbox", ")", "GetContainer", "(", "name", "string", ")", "*", "oci", ".", "Container", "{", "return", "s", ".", "containers", ".", "Get", "(", "name", ")", "\n", "}" ]
// GetContainer retrieves a container from the sandbox
[ "GetContainer", "retrieves", "a", "container", "from", "the", "sandbox" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox.go#L333-L335
train
cri-o/cri-o
lib/sandbox/sandbox.go
RemoveContainer
func (s *Sandbox) RemoveContainer(c *oci.Container) { s.containers.Delete(c.Name()) }
go
func (s *Sandbox) RemoveContainer(c *oci.Container) { s.containers.Delete(c.Name()) }
[ "func", "(", "s", "*", "Sandbox", ")", "RemoveContainer", "(", "c", "*", "oci", ".", "Container", ")", "{", "s", ".", "containers", ".", "Delete", "(", "c", ".", "Name", "(", ")", ")", "\n", "}" ]
// RemoveContainer deletes a container from the sandbox
[ "RemoveContainer", "deletes", "a", "container", "from", "the", "sandbox" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox.go#L338-L340
train
cri-o/cri-o
lib/sandbox/sandbox.go
SetInfraContainer
func (s *Sandbox) SetInfraContainer(infraCtr *oci.Container) error { if s.infraContainer != nil { return fmt.Errorf("sandbox already has an infra container") } else if infraCtr == nil { return fmt.Errorf("must provide non-nil infra container") } s.infraContainer = infraCtr return nil }
go
func (s *Sandbox) SetInfraContainer(infraCtr *oci.Container) error { if s.infraContainer != nil { return fmt.Errorf("sandbox already has an infra container") } else if infraCtr == nil { return fmt.Errorf("must provide non-nil infra container") } s.infraContainer = infraCtr return nil }
[ "func", "(", "s", "*", "Sandbox", ")", "SetInfraContainer", "(", "infraCtr", "*", "oci", ".", "Container", ")", "error", "{", "if", "s", ".", "infraContainer", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"sandbox already has an infra container\"", ")", "\n", "}", "else", "if", "infraCtr", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"must provide non-nil infra container\"", ")", "\n", "}", "\n", "s", ".", "infraContainer", "=", "infraCtr", "\n", "return", "nil", "\n", "}" ]
// SetInfraContainer sets the infrastructure container of a sandbox // Attempts to set the infrastructure container after one is already present will throw an error
[ "SetInfraContainer", "sets", "the", "infrastructure", "container", "of", "a", "sandbox", "Attempts", "to", "set", "the", "infrastructure", "container", "after", "one", "is", "already", "present", "will", "throw", "an", "error" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox.go#L344-L354
train
cri-o/cri-o
lib/sandbox/sandbox.go
NetNs
func (s *Sandbox) NetNs() *NetNs { if s.netns == nil { return nil } return s.netns.Get() }
go
func (s *Sandbox) NetNs() *NetNs { if s.netns == nil { return nil } return s.netns.Get() }
[ "func", "(", "s", "*", "Sandbox", ")", "NetNs", "(", ")", "*", "NetNs", "{", "if", "s", ".", "netns", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "s", ".", "netns", ".", "Get", "(", ")", "\n", "}" ]
// NetNs retrieves the network namespace of the sandbox // If the sandbox uses the host namespace, nil is returned
[ "NetNs", "retrieves", "the", "network", "namespace", "of", "the", "sandbox", "If", "the", "sandbox", "uses", "the", "host", "namespace", "nil", "is", "returned" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox.go#L363-L368
train
cri-o/cri-o
lib/sandbox/sandbox.go
NetNsPath
func (s *Sandbox) NetNsPath() string { if s.netns == nil || s.netns.Get() == nil || s.netns.Get().symlink == nil { if s.infraContainer != nil { return fmt.Sprintf("/proc/%v/ns/net", s.infraContainer.State().Pid) } return "" } return s.netns.Get().symlink.Name() }
go
func (s *Sandbox) NetNsPath() string { if s.netns == nil || s.netns.Get() == nil || s.netns.Get().symlink == nil { if s.infraContainer != nil { return fmt.Sprintf("/proc/%v/ns/net", s.infraContainer.State().Pid) } return "" } return s.netns.Get().symlink.Name() }
[ "func", "(", "s", "*", "Sandbox", ")", "NetNsPath", "(", ")", "string", "{", "if", "s", ".", "netns", "==", "nil", "||", "s", ".", "netns", ".", "Get", "(", ")", "==", "nil", "||", "s", ".", "netns", ".", "Get", "(", ")", ".", "symlink", "==", "nil", "{", "if", "s", ".", "infraContainer", "!=", "nil", "{", "return", "fmt", ".", "Sprintf", "(", "\"/proc/%v/ns/net\"", ",", "s", ".", "infraContainer", ".", "State", "(", ")", ".", "Pid", ")", "\n", "}", "\n", "return", "\"\"", "\n", "}", "\n", "return", "s", ".", "netns", ".", "Get", "(", ")", ".", "symlink", ".", "Name", "(", ")", "\n", "}" ]
// NetNsPath returns the path to the network namespace of the sandbox. // If the sandbox uses the host namespace, nil is returned
[ "NetNsPath", "returns", "the", "path", "to", "the", "network", "namespace", "of", "the", "sandbox", ".", "If", "the", "sandbox", "uses", "the", "host", "namespace", "nil", "is", "returned" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox.go#L372-L382
train
cri-o/cri-o
lib/sandbox/sandbox.go
UserNsPath
func (s *Sandbox) UserNsPath() string { if s.infraContainer != nil { return fmt.Sprintf("/proc/%v/ns/user", s.infraContainer.State().Pid) } return "" }
go
func (s *Sandbox) UserNsPath() string { if s.infraContainer != nil { return fmt.Sprintf("/proc/%v/ns/user", s.infraContainer.State().Pid) } return "" }
[ "func", "(", "s", "*", "Sandbox", ")", "UserNsPath", "(", ")", "string", "{", "if", "s", ".", "infraContainer", "!=", "nil", "{", "return", "fmt", ".", "Sprintf", "(", "\"/proc/%v/ns/user\"", ",", "s", ".", "infraContainer", ".", "State", "(", ")", ".", "Pid", ")", "\n", "}", "\n", "return", "\"\"", "\n", "}" ]
// UserNsPath returns the path to the user namespace of the sandbox. // If the sandbox uses the host namespace, nil is returned
[ "UserNsPath", "returns", "the", "path", "to", "the", "user", "namespace", "of", "the", "sandbox", ".", "If", "the", "sandbox", "uses", "the", "host", "namespace", "nil", "is", "returned" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox.go#L386-L391
train
cri-o/cri-o
lib/sandbox/sandbox.go
NetNsCreate
func (s *Sandbox) NetNsCreate(netNs NetNsIface) error { // Create a new netNs if nil provided if netNs == nil { netNs = &NetNs{} } // Check if interface is already initialized if netNs.Initialized() { return fmt.Errorf("net NS already initialized") } netNs, err := netNs.Initialize() if err != nil { return err } if err := netNs.SymlinkCreate(s.name); err != nil { logrus.Warnf("Could not create nentns symlink %v", err) if err1 := netNs.Close(); err1 != nil { return err1 } return err } s.netns = netNs return nil }
go
func (s *Sandbox) NetNsCreate(netNs NetNsIface) error { // Create a new netNs if nil provided if netNs == nil { netNs = &NetNs{} } // Check if interface is already initialized if netNs.Initialized() { return fmt.Errorf("net NS already initialized") } netNs, err := netNs.Initialize() if err != nil { return err } if err := netNs.SymlinkCreate(s.name); err != nil { logrus.Warnf("Could not create nentns symlink %v", err) if err1 := netNs.Close(); err1 != nil { return err1 } return err } s.netns = netNs return nil }
[ "func", "(", "s", "*", "Sandbox", ")", "NetNsCreate", "(", "netNs", "NetNsIface", ")", "error", "{", "if", "netNs", "==", "nil", "{", "netNs", "=", "&", "NetNs", "{", "}", "\n", "}", "\n", "if", "netNs", ".", "Initialized", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"net NS already initialized\"", ")", "\n", "}", "\n", "netNs", ",", "err", ":=", "netNs", ".", "Initialize", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "netNs", ".", "SymlinkCreate", "(", "s", ".", "name", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"Could not create nentns symlink %v\"", ",", "err", ")", "\n", "if", "err1", ":=", "netNs", ".", "Close", "(", ")", ";", "err1", "!=", "nil", "{", "return", "err1", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "s", ".", "netns", "=", "netNs", "\n", "return", "nil", "\n", "}" ]
// NetNsCreate creates a new network namespace for the sandbox
[ "NetNsCreate", "creates", "a", "new", "network", "namespace", "for", "the", "sandbox" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox.go#L394-L422
train
cri-o/cri-o
lib/sandbox/sandbox.go
NetNsJoin
func (s *Sandbox) NetNsJoin(nspath, name string) error { if s.netns != nil { return fmt.Errorf("sandbox already has a network namespace, cannot join another") } netNS, err := s.NetNsGet(nspath, name) if err != nil { return err } s.netns = netNS return nil }
go
func (s *Sandbox) NetNsJoin(nspath, name string) error { if s.netns != nil { return fmt.Errorf("sandbox already has a network namespace, cannot join another") } netNS, err := s.NetNsGet(nspath, name) if err != nil { return err } s.netns = netNS return nil }
[ "func", "(", "s", "*", "Sandbox", ")", "NetNsJoin", "(", "nspath", ",", "name", "string", ")", "error", "{", "if", "s", ".", "netns", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"sandbox already has a network namespace, cannot join another\"", ")", "\n", "}", "\n", "netNS", ",", "err", ":=", "s", ".", "NetNsGet", "(", "nspath", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "s", ".", "netns", "=", "netNS", "\n", "return", "nil", "\n", "}" ]
// NetNsJoin attempts to join the sandbox to an existing network namespace // This will fail if the sandbox is already part of a network namespace
[ "NetNsJoin", "attempts", "to", "join", "the", "sandbox", "to", "an", "existing", "network", "namespace", "This", "will", "fail", "if", "the", "sandbox", "is", "already", "part", "of", "a", "network", "namespace" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox.go#L439-L452
train
cri-o/cri-o
lib/sandbox/sandbox.go
NetNsRemove
func (s *Sandbox) NetNsRemove() error { if s.netns == nil { logrus.Warn("no networking namespace") return nil } return s.netns.Remove() }
go
func (s *Sandbox) NetNsRemove() error { if s.netns == nil { logrus.Warn("no networking namespace") return nil } return s.netns.Remove() }
[ "func", "(", "s", "*", "Sandbox", ")", "NetNsRemove", "(", ")", "error", "{", "if", "s", ".", "netns", "==", "nil", "{", "logrus", ".", "Warn", "(", "\"no networking namespace\"", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "s", ".", "netns", ".", "Remove", "(", ")", "\n", "}" ]
// NetNsRemove removes the network namespace associated with the sandbox
[ "NetNsRemove", "removes", "the", "network", "namespace", "associated", "with", "the", "sandbox" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/sandbox.go#L455-L462
train
cri-o/cri-o
client/client.go
New
func New(crioSocketPath string) (CrioClient, error) { tr := new(http.Transport) configureUnixTransport(tr, "unix", crioSocketPath) c := &http.Client{ Transport: tr, } return &crioClientImpl{ client: c, crioSocketPath: crioSocketPath, }, nil }
go
func New(crioSocketPath string) (CrioClient, error) { tr := new(http.Transport) configureUnixTransport(tr, "unix", crioSocketPath) c := &http.Client{ Transport: tr, } return &crioClientImpl{ client: c, crioSocketPath: crioSocketPath, }, nil }
[ "func", "New", "(", "crioSocketPath", "string", ")", "(", "CrioClient", ",", "error", ")", "{", "tr", ":=", "new", "(", "http", ".", "Transport", ")", "\n", "configureUnixTransport", "(", "tr", ",", "\"unix\"", ",", "crioSocketPath", ")", "\n", "c", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "tr", ",", "}", "\n", "return", "&", "crioClientImpl", "{", "client", ":", "c", ",", "crioSocketPath", ":", "crioSocketPath", ",", "}", ",", "nil", "\n", "}" ]
// New returns a crio client
[ "New", "returns", "a", "crio", "client" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/client/client.go#L43-L53
train
cri-o/cri-o
client/client.go
DaemonInfo
func (c *crioClientImpl) DaemonInfo() (types.CrioInfo, error) { info := types.CrioInfo{} req, err := c.getRequest("/info") if err != nil { return info, err } resp, err := c.client.Do(req) if err != nil { return info, err } defer resp.Body.Close() err = json.NewDecoder(resp.Body).Decode(&info) return info, err }
go
func (c *crioClientImpl) DaemonInfo() (types.CrioInfo, error) { info := types.CrioInfo{} req, err := c.getRequest("/info") if err != nil { return info, err } resp, err := c.client.Do(req) if err != nil { return info, err } defer resp.Body.Close() err = json.NewDecoder(resp.Body).Decode(&info) return info, err }
[ "func", "(", "c", "*", "crioClientImpl", ")", "DaemonInfo", "(", ")", "(", "types", ".", "CrioInfo", ",", "error", ")", "{", "info", ":=", "types", ".", "CrioInfo", "{", "}", "\n", "req", ",", "err", ":=", "c", ".", "getRequest", "(", "\"/info\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "info", ",", "err", "\n", "}", "\n", "resp", ",", "err", ":=", "c", ".", "client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "info", ",", "err", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "err", "=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "&", "info", ")", "\n", "return", "info", ",", "err", "\n", "}" ]
// DaemonInfo return cri-o daemon info from the cri-o // info endpoint.
[ "DaemonInfo", "return", "cri", "-", "o", "daemon", "info", "from", "the", "cri", "-", "o", "info", "endpoint", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/client/client.go#L70-L83
train
cri-o/cri-o
client/client.go
ContainerInfo
func (c *crioClientImpl) ContainerInfo(id string) (*types.ContainerInfo, error) { req, err := c.getRequest("/containers/" + id) if err != nil { return nil, err } resp, err := c.client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() cInfo := types.ContainerInfo{} if err := json.NewDecoder(resp.Body).Decode(&cInfo); err != nil { return nil, err } return &cInfo, nil }
go
func (c *crioClientImpl) ContainerInfo(id string) (*types.ContainerInfo, error) { req, err := c.getRequest("/containers/" + id) if err != nil { return nil, err } resp, err := c.client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() cInfo := types.ContainerInfo{} if err := json.NewDecoder(resp.Body).Decode(&cInfo); err != nil { return nil, err } return &cInfo, nil }
[ "func", "(", "c", "*", "crioClientImpl", ")", "ContainerInfo", "(", "id", "string", ")", "(", "*", "types", ".", "ContainerInfo", ",", "error", ")", "{", "req", ",", "err", ":=", "c", ".", "getRequest", "(", "\"/containers/\"", "+", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "resp", ",", "err", ":=", "c", ".", "client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "cInfo", ":=", "types", ".", "ContainerInfo", "{", "}", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "&", "cInfo", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "cInfo", ",", "nil", "\n", "}" ]
// ContainerInfo returns container info by querying // the cri-o container endpoint.
[ "ContainerInfo", "returns", "container", "info", "by", "querying", "the", "cri", "-", "o", "container", "endpoint", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/client/client.go#L87-L102
train
cri-o/cri-o
utils/fifo/fifo.go
Write
func (f *fifo) Write(b []byte) (int, error) { if f.flag&(syscall.O_WRONLY|syscall.O_RDWR) == 0 { return 0, errors.New("writing to read-only fifo") } select { case <-f.opened: return f.file.Write(b) default: } select { case <-f.opened: return f.file.Write(b) case <-f.closed: return 0, errors.New("writing to a closed fifo") } }
go
func (f *fifo) Write(b []byte) (int, error) { if f.flag&(syscall.O_WRONLY|syscall.O_RDWR) == 0 { return 0, errors.New("writing to read-only fifo") } select { case <-f.opened: return f.file.Write(b) default: } select { case <-f.opened: return f.file.Write(b) case <-f.closed: return 0, errors.New("writing to a closed fifo") } }
[ "func", "(", "f", "*", "fifo", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "f", ".", "flag", "&", "(", "syscall", ".", "O_WRONLY", "|", "syscall", ".", "O_RDWR", ")", "==", "0", "{", "return", "0", ",", "errors", ".", "New", "(", "\"writing to read-only fifo\"", ")", "\n", "}", "\n", "select", "{", "case", "<-", "f", ".", "opened", ":", "return", "f", ".", "file", ".", "Write", "(", "b", ")", "\n", "default", ":", "}", "\n", "select", "{", "case", "<-", "f", ".", "opened", ":", "return", "f", ".", "file", ".", "Write", "(", "b", ")", "\n", "case", "<-", "f", ".", "closed", ":", "return", "0", ",", "errors", ".", "New", "(", "\"writing to a closed fifo\"", ")", "\n", "}", "\n", "}" ]
// Write from byte array to a fifo.
[ "Write", "from", "byte", "array", "to", "a", "fifo", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/fifo/fifo.go#L166-L181
train
cri-o/cri-o
server/useragent/useragent.go
Get
func Get(ctx context.Context) string { httpVersion := make([]VersionInfo, 0, 4) httpVersion = append(httpVersion, VersionInfo{Name: "cri-o", Version: version.Version}) httpVersion = append(httpVersion, VersionInfo{Name: "go", Version: runtime.Version()}) httpVersion = append(httpVersion, VersionInfo{Name: "os", Version: runtime.GOOS}) httpVersion = append(httpVersion, VersionInfo{Name: "arch", Version: runtime.GOARCH}) return AppendVersions("", httpVersion...) }
go
func Get(ctx context.Context) string { httpVersion := make([]VersionInfo, 0, 4) httpVersion = append(httpVersion, VersionInfo{Name: "cri-o", Version: version.Version}) httpVersion = append(httpVersion, VersionInfo{Name: "go", Version: runtime.Version()}) httpVersion = append(httpVersion, VersionInfo{Name: "os", Version: runtime.GOOS}) httpVersion = append(httpVersion, VersionInfo{Name: "arch", Version: runtime.GOARCH}) return AppendVersions("", httpVersion...) }
[ "func", "Get", "(", "ctx", "context", ".", "Context", ")", "string", "{", "httpVersion", ":=", "make", "(", "[", "]", "VersionInfo", ",", "0", ",", "4", ")", "\n", "httpVersion", "=", "append", "(", "httpVersion", ",", "VersionInfo", "{", "Name", ":", "\"cri-o\"", ",", "Version", ":", "version", ".", "Version", "}", ")", "\n", "httpVersion", "=", "append", "(", "httpVersion", ",", "VersionInfo", "{", "Name", ":", "\"go\"", ",", "Version", ":", "runtime", ".", "Version", "(", ")", "}", ")", "\n", "httpVersion", "=", "append", "(", "httpVersion", ",", "VersionInfo", "{", "Name", ":", "\"os\"", ",", "Version", ":", "runtime", ".", "GOOS", "}", ")", "\n", "httpVersion", "=", "append", "(", "httpVersion", ",", "VersionInfo", "{", "Name", ":", "\"arch\"", ",", "Version", ":", "runtime", ".", "GOARCH", "}", ")", "\n", "return", "AppendVersions", "(", "\"\"", ",", "httpVersion", "...", ")", "\n", "}" ]
// Get is the User-Agent the CRI-O daemon uses to identify itself.
[ "Get", "is", "the", "User", "-", "Agent", "the", "CRI", "-", "O", "daemon", "uses", "to", "identify", "itself", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/useragent/useragent.go#L11-L19
train
cri-o/cri-o
server/secrets.go
SaveTo
func (s SecretData) SaveTo(dir string) error { path := filepath.Join(dir, s.Name) if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil && !os.IsExist(err) { return err } return ioutil.WriteFile(path, s.Data, 0700) }
go
func (s SecretData) SaveTo(dir string) error { path := filepath.Join(dir, s.Name) if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil && !os.IsExist(err) { return err } return ioutil.WriteFile(path, s.Data, 0700) }
[ "func", "(", "s", "SecretData", ")", "SaveTo", "(", "dir", "string", ")", "error", "{", "path", ":=", "filepath", ".", "Join", "(", "dir", ",", "s", ".", "Name", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "filepath", ".", "Dir", "(", "path", ")", ",", "0700", ")", ";", "err", "!=", "nil", "&&", "!", "os", ".", "IsExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "return", "ioutil", ".", "WriteFile", "(", "path", ",", "s", ".", "Data", ",", "0700", ")", "\n", "}" ]
// SaveTo saves secret data to given directory
[ "SaveTo", "saves", "secret", "data", "to", "given", "directory" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/secrets.go#L23-L29
train
cri-o/cri-o
server/secrets.go
secretMounts
func secretMounts(defaultMountsPaths []string, mountLabel, containerWorkingDir string, runtimeMounts []rspec.Mount) ([]rspec.Mount, error) { mounts := make([]rspec.Mount, 0, len(defaultMountsPaths)) for _, path := range defaultMountsPaths { hostDir, ctrDir, err := getMountsMap(path) if err != nil { return nil, err } // skip if the hostDir path doesn't exist if _, err := os.Stat(hostDir); os.IsNotExist(err) { logrus.Warnf("%q doesn't exist, skipping", hostDir) continue } ctrDirOnHost := filepath.Join(containerWorkingDir, ctrDir) // skip if ctrDir has already been mounted by caller if isAlreadyMounted(runtimeMounts, ctrDir) { logrus.Warnf("%q has already been mounted; cannot override mount", ctrDir) continue } if err := os.RemoveAll(ctrDirOnHost); err != nil { return nil, fmt.Errorf("remove container directory failed: %v", err) } if err := os.MkdirAll(ctrDirOnHost, 0755); err != nil { return nil, fmt.Errorf("making container directory failed: %v", err) } hostDir, err = resolveSymbolicLink(hostDir, "/") if err != nil { return nil, err } data, err := getHostSecretData(hostDir) if err != nil { return nil, errors.Wrapf(err, "getting host secret data failed") } for _, s := range data { if err := s.SaveTo(ctrDirOnHost); err != nil { return nil, err } } if err := label.Relabel(ctrDirOnHost, mountLabel, false); err != nil { return nil, err } m := rspec.Mount{ Source: ctrDirOnHost, Destination: ctrDir, } mounts = append(mounts, m) } return mounts, nil }
go
func secretMounts(defaultMountsPaths []string, mountLabel, containerWorkingDir string, runtimeMounts []rspec.Mount) ([]rspec.Mount, error) { mounts := make([]rspec.Mount, 0, len(defaultMountsPaths)) for _, path := range defaultMountsPaths { hostDir, ctrDir, err := getMountsMap(path) if err != nil { return nil, err } // skip if the hostDir path doesn't exist if _, err := os.Stat(hostDir); os.IsNotExist(err) { logrus.Warnf("%q doesn't exist, skipping", hostDir) continue } ctrDirOnHost := filepath.Join(containerWorkingDir, ctrDir) // skip if ctrDir has already been mounted by caller if isAlreadyMounted(runtimeMounts, ctrDir) { logrus.Warnf("%q has already been mounted; cannot override mount", ctrDir) continue } if err := os.RemoveAll(ctrDirOnHost); err != nil { return nil, fmt.Errorf("remove container directory failed: %v", err) } if err := os.MkdirAll(ctrDirOnHost, 0755); err != nil { return nil, fmt.Errorf("making container directory failed: %v", err) } hostDir, err = resolveSymbolicLink(hostDir, "/") if err != nil { return nil, err } data, err := getHostSecretData(hostDir) if err != nil { return nil, errors.Wrapf(err, "getting host secret data failed") } for _, s := range data { if err := s.SaveTo(ctrDirOnHost); err != nil { return nil, err } } if err := label.Relabel(ctrDirOnHost, mountLabel, false); err != nil { return nil, err } m := rspec.Mount{ Source: ctrDirOnHost, Destination: ctrDir, } mounts = append(mounts, m) } return mounts, nil }
[ "func", "secretMounts", "(", "defaultMountsPaths", "[", "]", "string", ",", "mountLabel", ",", "containerWorkingDir", "string", ",", "runtimeMounts", "[", "]", "rspec", ".", "Mount", ")", "(", "[", "]", "rspec", ".", "Mount", ",", "error", ")", "{", "mounts", ":=", "make", "(", "[", "]", "rspec", ".", "Mount", ",", "0", ",", "len", "(", "defaultMountsPaths", ")", ")", "\n", "for", "_", ",", "path", ":=", "range", "defaultMountsPaths", "{", "hostDir", ",", "ctrDir", ",", "err", ":=", "getMountsMap", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "hostDir", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "logrus", ".", "Warnf", "(", "\"%q doesn't exist, skipping\"", ",", "hostDir", ")", "\n", "continue", "\n", "}", "\n", "ctrDirOnHost", ":=", "filepath", ".", "Join", "(", "containerWorkingDir", ",", "ctrDir", ")", "\n", "if", "isAlreadyMounted", "(", "runtimeMounts", ",", "ctrDir", ")", "{", "logrus", ".", "Warnf", "(", "\"%q has already been mounted; cannot override mount\"", ",", "ctrDir", ")", "\n", "continue", "\n", "}", "\n", "if", "err", ":=", "os", ".", "RemoveAll", "(", "ctrDirOnHost", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"remove container directory failed: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "ctrDirOnHost", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"making container directory failed: %v\"", ",", "err", ")", "\n", "}", "\n", "hostDir", ",", "err", "=", "resolveSymbolicLink", "(", "hostDir", ",", "\"/\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "data", ",", "err", ":=", "getHostSecretData", "(", "hostDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"getting host secret data failed\"", ")", "\n", "}", "\n", "for", "_", ",", "s", ":=", "range", "data", "{", "if", "err", ":=", "s", ".", "SaveTo", "(", "ctrDirOnHost", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "label", ".", "Relabel", "(", "ctrDirOnHost", ",", "mountLabel", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "m", ":=", "rspec", ".", "Mount", "{", "Source", ":", "ctrDirOnHost", ",", "Destination", ":", "ctrDir", ",", "}", "\n", "mounts", "=", "append", "(", "mounts", ",", "m", ")", "\n", "}", "\n", "return", "mounts", ",", "nil", "\n", "}" ]
// secretMount copies the contents of host directory to container directory // and returns a list of mounts
[ "secretMount", "copies", "the", "contents", "of", "host", "directory", "to", "container", "directory", "and", "returns", "a", "list", "of", "mounts" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/secrets.go#L103-L157
train
cri-o/cri-o
utils/io/logger.go
NewCRILogger
func NewCRILogger(path string, w io.Writer, stream StreamType, maxLen int) (io.WriteCloser, <-chan struct{}) { logrus.Debugf("Start writing stream %q to log file %q", stream, path) prc, pwc := io.Pipe() stop := make(chan struct{}) go func() { redirectLogs(path, prc, w, stream, maxLen) close(stop) }() return pwc, stop }
go
func NewCRILogger(path string, w io.Writer, stream StreamType, maxLen int) (io.WriteCloser, <-chan struct{}) { logrus.Debugf("Start writing stream %q to log file %q", stream, path) prc, pwc := io.Pipe() stop := make(chan struct{}) go func() { redirectLogs(path, prc, w, stream, maxLen) close(stop) }() return pwc, stop }
[ "func", "NewCRILogger", "(", "path", "string", ",", "w", "io", ".", "Writer", ",", "stream", "StreamType", ",", "maxLen", "int", ")", "(", "io", ".", "WriteCloser", ",", "<-", "chan", "struct", "{", "}", ")", "{", "logrus", ".", "Debugf", "(", "\"Start writing stream %q to log file %q\"", ",", "stream", ",", "path", ")", "\n", "prc", ",", "pwc", ":=", "io", ".", "Pipe", "(", ")", "\n", "stop", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "redirectLogs", "(", "path", ",", "prc", ",", "w", ",", "stream", ",", "maxLen", ")", "\n", "close", "(", "stop", ")", "\n", "}", "(", ")", "\n", "return", "pwc", ",", "stop", "\n", "}" ]
// NewCRILogger returns a write closer which redirect container log into // log file, and decorate the log line into CRI defined format. It also // returns a channel which indicates whether the logger is stopped. // maxLen is the max length limit of a line. A line longer than the // limit will be cut into multiple lines.
[ "NewCRILogger", "returns", "a", "write", "closer", "which", "redirect", "container", "log", "into", "log", "file", "and", "decorate", "the", "log", "line", "into", "CRI", "defined", "format", ".", "It", "also", "returns", "a", "channel", "which", "indicates", "whether", "the", "logger", "is", "stopped", ".", "maxLen", "is", "the", "max", "length", "limit", "of", "a", "line", ".", "A", "line", "longer", "than", "the", "limit", "will", "be", "cut", "into", "multiple", "lines", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/io/logger.go#L53-L62
train
cri-o/cri-o
server/utils.go
inStringSlice
func inStringSlice(ss []string, str string) bool { for _, s := range ss { if strings.EqualFold(s, str) { return true } } return false }
go
func inStringSlice(ss []string, str string) bool { for _, s := range ss { if strings.EqualFold(s, str) { return true } } return false }
[ "func", "inStringSlice", "(", "ss", "[", "]", "string", ",", "str", "string", ")", "bool", "{", "for", "_", ",", "s", ":=", "range", "ss", "{", "if", "strings", ".", "EqualFold", "(", "s", ",", "str", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// inStringSlice checks whether a string is inside a string slice. // Comparison is case insensitive.
[ "inStringSlice", "checks", "whether", "a", "string", "is", "inside", "a", "string", "slice", ".", "Comparison", "is", "case", "insensitive", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/utils.go#L113-L120
train
cri-o/cri-o
server/utils.go
getOCICapabilitiesList
func getOCICapabilitiesList() []string { caps := make([]string, 0, len(capability.List())) for _, cap := range capability.List() { if cap > validate.LastCap() { continue } caps = append(caps, "CAP_"+strings.ToUpper(cap.String())) } return caps }
go
func getOCICapabilitiesList() []string { caps := make([]string, 0, len(capability.List())) for _, cap := range capability.List() { if cap > validate.LastCap() { continue } caps = append(caps, "CAP_"+strings.ToUpper(cap.String())) } return caps }
[ "func", "getOCICapabilitiesList", "(", ")", "[", "]", "string", "{", "caps", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "capability", ".", "List", "(", ")", ")", ")", "\n", "for", "_", ",", "cap", ":=", "range", "capability", ".", "List", "(", ")", "{", "if", "cap", ">", "validate", ".", "LastCap", "(", ")", "{", "continue", "\n", "}", "\n", "caps", "=", "append", "(", "caps", ",", "\"CAP_\"", "+", "strings", ".", "ToUpper", "(", "cap", ".", "String", "(", ")", ")", ")", "\n", "}", "\n", "return", "caps", "\n", "}" ]
// getOCICapabilitiesList returns a list of all available capabilities.
[ "getOCICapabilitiesList", "returns", "a", "list", "of", "all", "available", "capabilities", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/utils.go#L123-L132
train
cri-o/cri-o
server/utils.go
validateSysctl
func validateSysctl(sysctl string, hostNet, hostIPC bool) error { nsErrorFmt := "%q not allowed with host %s enabled" if ns, found := namespaces[sysctl]; found { if ns == IpcNamespace && hostIPC { return errors.Errorf(nsErrorFmt, sysctl, ns) } if ns == NetNamespace && hostNet { return errors.Errorf(nsErrorFmt, sysctl, ns) } return nil } for p, ns := range prefixNamespaces { if strings.HasPrefix(sysctl, p) { if ns == IpcNamespace && hostIPC { return errors.Errorf(nsErrorFmt, sysctl, ns) } if ns == NetNamespace && hostNet { return errors.Errorf(nsErrorFmt, sysctl, ns) } return nil } } return errors.Errorf("%q not whitelisted", sysctl) }
go
func validateSysctl(sysctl string, hostNet, hostIPC bool) error { nsErrorFmt := "%q not allowed with host %s enabled" if ns, found := namespaces[sysctl]; found { if ns == IpcNamespace && hostIPC { return errors.Errorf(nsErrorFmt, sysctl, ns) } if ns == NetNamespace && hostNet { return errors.Errorf(nsErrorFmt, sysctl, ns) } return nil } for p, ns := range prefixNamespaces { if strings.HasPrefix(sysctl, p) { if ns == IpcNamespace && hostIPC { return errors.Errorf(nsErrorFmt, sysctl, ns) } if ns == NetNamespace && hostNet { return errors.Errorf(nsErrorFmt, sysctl, ns) } return nil } } return errors.Errorf("%q not whitelisted", sysctl) }
[ "func", "validateSysctl", "(", "sysctl", "string", ",", "hostNet", ",", "hostIPC", "bool", ")", "error", "{", "nsErrorFmt", ":=", "\"%q not allowed with host %s enabled\"", "\n", "if", "ns", ",", "found", ":=", "namespaces", "[", "sysctl", "]", ";", "found", "{", "if", "ns", "==", "IpcNamespace", "&&", "hostIPC", "{", "return", "errors", ".", "Errorf", "(", "nsErrorFmt", ",", "sysctl", ",", "ns", ")", "\n", "}", "\n", "if", "ns", "==", "NetNamespace", "&&", "hostNet", "{", "return", "errors", ".", "Errorf", "(", "nsErrorFmt", ",", "sysctl", ",", "ns", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "for", "p", ",", "ns", ":=", "range", "prefixNamespaces", "{", "if", "strings", ".", "HasPrefix", "(", "sysctl", ",", "p", ")", "{", "if", "ns", "==", "IpcNamespace", "&&", "hostIPC", "{", "return", "errors", ".", "Errorf", "(", "nsErrorFmt", ",", "sysctl", ",", "ns", ")", "\n", "}", "\n", "if", "ns", "==", "NetNamespace", "&&", "hostNet", "{", "return", "errors", ".", "Errorf", "(", "nsErrorFmt", ",", "sysctl", ",", "ns", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "errors", ".", "Errorf", "(", "\"%q not whitelisted\"", ",", "sysctl", ")", "\n", "}" ]
// validateSysctl checks that a sysctl is whitelisted because it is known // to be namespaced by the Linux kernel. // The parameters hostNet and hostIPC are used to forbid sysctls for pod sharing the // respective namespaces with the host. This check is only used on sysctls defined by // the user in the crio.conf file.
[ "validateSysctl", "checks", "that", "a", "sysctl", "is", "whitelisted", "because", "it", "is", "known", "to", "be", "namespaced", "by", "the", "Linux", "kernel", ".", "The", "parameters", "hostNet", "and", "hostIPC", "are", "used", "to", "forbid", "sysctls", "for", "pod", "sharing", "the", "respective", "namespaces", "with", "the", "host", ".", "This", "check", "is", "only", "used", "on", "sysctls", "defined", "by", "the", "user", "in", "the", "crio", ".", "conf", "file", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/utils.go#L230-L253
train
cri-o/cri-o
server/utils.go
translateLabelsToDescription
func translateLabelsToDescription(labels map[string]string) string { return fmt.Sprintf("%s/%s/%s", labels[types.KubernetesPodNamespaceLabel], labels[types.KubernetesPodNameLabel], labels[types.KubernetesContainerNameLabel]) }
go
func translateLabelsToDescription(labels map[string]string) string { return fmt.Sprintf("%s/%s/%s", labels[types.KubernetesPodNamespaceLabel], labels[types.KubernetesPodNameLabel], labels[types.KubernetesContainerNameLabel]) }
[ "func", "translateLabelsToDescription", "(", "labels", "map", "[", "string", "]", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"%s/%s/%s\"", ",", "labels", "[", "types", ".", "KubernetesPodNamespaceLabel", "]", ",", "labels", "[", "types", ".", "KubernetesPodNameLabel", "]", ",", "labels", "[", "types", ".", "KubernetesContainerNameLabel", "]", ")", "\n", "}" ]
// Translate container labels to a description of the container
[ "Translate", "container", "labels", "to", "a", "description", "of", "the", "container" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/utils.go#L279-L281
train
cri-o/cri-o
lib/config.go
GetStore
func (c *Config) GetStore() (cstorage.Store, error) { return cstorage.GetStore(cstorage.StoreOptions{ RunRoot: c.RunRoot, GraphRoot: c.Root, GraphDriverName: c.Storage, GraphDriverOptions: c.StorageOptions, }) }
go
func (c *Config) GetStore() (cstorage.Store, error) { return cstorage.GetStore(cstorage.StoreOptions{ RunRoot: c.RunRoot, GraphRoot: c.Root, GraphDriverName: c.Storage, GraphDriverOptions: c.StorageOptions, }) }
[ "func", "(", "c", "*", "Config", ")", "GetStore", "(", ")", "(", "cstorage", ".", "Store", ",", "error", ")", "{", "return", "cstorage", ".", "GetStore", "(", "cstorage", ".", "StoreOptions", "{", "RunRoot", ":", "c", ".", "RunRoot", ",", "GraphRoot", ":", "c", ".", "Root", ",", "GraphDriverName", ":", "c", ".", "Storage", ",", "GraphDriverOptions", ":", "c", ".", "StorageOptions", ",", "}", ")", "\n", "}" ]
// GetStore returns the container storage for a given configuration
[ "GetStore", "returns", "the", "container", "storage", "for", "a", "given", "configuration" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/config.go#L49-L56
train
cri-o/cri-o
lib/config.go
UpdateFromFile
func (c *Config) UpdateFromFile(path string) error { data, err := ioutil.ReadFile(path) if err != nil { return err } t := new(tomlConfig) t.fromConfig(c) _, err = toml.Decode(string(data), t) if err != nil { return fmt.Errorf("unable to decode configuration %v: %v", path, err) } t.toConfig(c) return nil }
go
func (c *Config) UpdateFromFile(path string) error { data, err := ioutil.ReadFile(path) if err != nil { return err } t := new(tomlConfig) t.fromConfig(c) _, err = toml.Decode(string(data), t) if err != nil { return fmt.Errorf("unable to decode configuration %v: %v", path, err) } t.toConfig(c) return nil }
[ "func", "(", "c", "*", "Config", ")", "UpdateFromFile", "(", "path", "string", ")", "error", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "t", ":=", "new", "(", "tomlConfig", ")", "\n", "t", ".", "fromConfig", "(", "c", ")", "\n", "_", ",", "err", "=", "toml", ".", "Decode", "(", "string", "(", "data", ")", ",", "t", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to decode configuration %v: %v\"", ",", "path", ",", "err", ")", "\n", "}", "\n", "t", ".", "toConfig", "(", "c", ")", "\n", "return", "nil", "\n", "}" ]
// UpdateFromFile populates the Config from the TOML-encoded file at the given path. // Returns errors encountered when reading or parsing the files, or nil // otherwise.
[ "UpdateFromFile", "populates", "the", "Config", "from", "the", "TOML", "-", "encoded", "file", "at", "the", "given", "path", ".", "Returns", "errors", "encountered", "when", "reading", "or", "parsing", "the", "files", "or", "nil", "otherwise", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/config.go#L320-L336
train
cri-o/cri-o
lib/config.go
ToFile
func (c *Config) ToFile(path string) error { var w bytes.Buffer e := toml.NewEncoder(&w) t := new(tomlConfig) t.fromConfig(c) if err := e.Encode(*t); err != nil { return err } return ioutil.WriteFile(path, w.Bytes(), 0644) }
go
func (c *Config) ToFile(path string) error { var w bytes.Buffer e := toml.NewEncoder(&w) t := new(tomlConfig) t.fromConfig(c) if err := e.Encode(*t); err != nil { return err } return ioutil.WriteFile(path, w.Bytes(), 0644) }
[ "func", "(", "c", "*", "Config", ")", "ToFile", "(", "path", "string", ")", "error", "{", "var", "w", "bytes", ".", "Buffer", "\n", "e", ":=", "toml", ".", "NewEncoder", "(", "&", "w", ")", "\n", "t", ":=", "new", "(", "tomlConfig", ")", "\n", "t", ".", "fromConfig", "(", "c", ")", "\n", "if", "err", ":=", "e", ".", "Encode", "(", "*", "t", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "ioutil", ".", "WriteFile", "(", "path", ",", "w", ".", "Bytes", "(", ")", ",", "0644", ")", "\n", "}" ]
// ToFile outputs the given Config as a TOML-encoded file at the given path. // Returns errors encountered when generating or writing the file, or nil // otherwise.
[ "ToFile", "outputs", "the", "given", "Config", "as", "a", "TOML", "-", "encoded", "file", "at", "the", "given", "path", ".", "Returns", "errors", "encountered", "when", "generating", "or", "writing", "the", "file", "or", "nil", "otherwise", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/config.go#L341-L353
train
cri-o/cri-o
lib/config.go
Validate
func (c *Config) Validate(onExecution bool) error { if err := c.RootConfig.Validate(onExecution); err != nil { return errors.Wrapf(err, "root config") } if err := c.RuntimeConfig.Validate(onExecution); err != nil { return errors.Wrapf(err, "runtime config") } if err := c.NetworkConfig.Validate(onExecution); err != nil { return errors.Wrapf(err, "network config") } return nil }
go
func (c *Config) Validate(onExecution bool) error { if err := c.RootConfig.Validate(onExecution); err != nil { return errors.Wrapf(err, "root config") } if err := c.RuntimeConfig.Validate(onExecution); err != nil { return errors.Wrapf(err, "runtime config") } if err := c.NetworkConfig.Validate(onExecution); err != nil { return errors.Wrapf(err, "network config") } return nil }
[ "func", "(", "c", "*", "Config", ")", "Validate", "(", "onExecution", "bool", ")", "error", "{", "if", "err", ":=", "c", ".", "RootConfig", ".", "Validate", "(", "onExecution", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"root config\"", ")", "\n", "}", "\n", "if", "err", ":=", "c", ".", "RuntimeConfig", ".", "Validate", "(", "onExecution", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"runtime config\"", ")", "\n", "}", "\n", "if", "err", ":=", "c", ".", "NetworkConfig", ".", "Validate", "(", "onExecution", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"network config\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate is the main entry point for library configuration validation. // The parameter `onExecution` specifies if the validation should include // execution checks. It returns an `error` on validation failure, otherwise // `nil`.
[ "Validate", "is", "the", "main", "entry", "point", "for", "library", "configuration", "validation", ".", "The", "parameter", "onExecution", "specifies", "if", "the", "validation", "should", "include", "execution", "checks", ".", "It", "returns", "an", "error", "on", "validation", "failure", "otherwise", "nil", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/config.go#L422-L436
train
cri-o/cri-o
lib/config.go
Validate
func (c *RootConfig) Validate(onExecution bool) error { if onExecution { if err := os.MkdirAll(c.LogDir, 0700); err != nil { return errors.Wrapf(err, "invalid log_dir") } } return nil }
go
func (c *RootConfig) Validate(onExecution bool) error { if onExecution { if err := os.MkdirAll(c.LogDir, 0700); err != nil { return errors.Wrapf(err, "invalid log_dir") } } return nil }
[ "func", "(", "c", "*", "RootConfig", ")", "Validate", "(", "onExecution", "bool", ")", "error", "{", "if", "onExecution", "{", "if", "err", ":=", "os", ".", "MkdirAll", "(", "c", ".", "LogDir", ",", "0700", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"invalid log_dir\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate is the main entry point for root configuration validation. // The parameter `onExecution` specifies if the validation should include // execution checks. It returns an `error` on validation failure, otherwise // `nil`.
[ "Validate", "is", "the", "main", "entry", "point", "for", "root", "configuration", "validation", ".", "The", "parameter", "onExecution", "specifies", "if", "the", "validation", "should", "include", "execution", "checks", ".", "It", "returns", "an", "error", "on", "validation", "failure", "otherwise", "nil", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/config.go#L442-L450
train
cri-o/cri-o
lib/config.go
Validate
func (c *RuntimeConfig) Validate(onExecution bool) error { // This is somehow duplicated with server.getUlimitsFromConfig under server/utils.go // but I don't want to export that function for the sake of validation here // so, keep it in mind if things start to blow up. // Reason for having this here is that I don't want people to start crio // with invalid ulimits but realize that only after starting a couple of // containers and watching them fail. for _, u := range c.DefaultUlimits { ul, err := units.ParseUlimit(u) if err != nil { return fmt.Errorf("unrecognized ulimit %s: %v", u, err) } _, err = ul.GetRlimit() if err != nil { return err } } for _, d := range c.AdditionalDevices { split := strings.Split(d, ":") switch len(split) { case 3: if !createconfig.IsValidDeviceMode(split[2]) { return fmt.Errorf("invalid device mode: %s", split[2]) } fallthrough case 2: if (!createconfig.IsValidDeviceMode(split[1]) && !strings.HasPrefix(split[1], "/dev/")) || (len(split) == 3 && createconfig.IsValidDeviceMode(split[1])) { return fmt.Errorf("invalid device mode: %s", split[1]) } fallthrough case 1: if !strings.HasPrefix(split[0], "/dev/") { return fmt.Errorf("invalid device mode: %s", split[0]) } default: return fmt.Errorf("invalid device specification: %s", d) } } // check we do have at least a runtime if _, ok := c.Runtimes[c.DefaultRuntime]; !ok { return errors.New("no default runtime configured") } // check for validation on execution if onExecution { // Validate if runtime_path does exist for each runtime for runtime, handler := range c.Runtimes { if _, err := os.Stat(handler.RuntimePath); os.IsNotExist(err) { return fmt.Errorf("invalid runtime_path for runtime '%s': %q", runtime, err) } logrus.Debugf("found valid runtime '%s' for runtime_path '%s'\n", runtime, handler.RuntimePath) } // Validate the system registries configuration if _, err := sysregistriesv2.GetRegistries(nil); err != nil { return fmt.Errorf("invalid /etc/containers/registries.conf: %q", err) } for _, hooksDir := range c.HooksDir { if _, err := os.Stat(hooksDir); err != nil { return errors.Wrapf(err, "invalid hooks_dir entry") } } if _, err := os.Stat(c.Conmon); err != nil { return errors.Wrapf(err, "invalid conmon path") } } return nil }
go
func (c *RuntimeConfig) Validate(onExecution bool) error { // This is somehow duplicated with server.getUlimitsFromConfig under server/utils.go // but I don't want to export that function for the sake of validation here // so, keep it in mind if things start to blow up. // Reason for having this here is that I don't want people to start crio // with invalid ulimits but realize that only after starting a couple of // containers and watching them fail. for _, u := range c.DefaultUlimits { ul, err := units.ParseUlimit(u) if err != nil { return fmt.Errorf("unrecognized ulimit %s: %v", u, err) } _, err = ul.GetRlimit() if err != nil { return err } } for _, d := range c.AdditionalDevices { split := strings.Split(d, ":") switch len(split) { case 3: if !createconfig.IsValidDeviceMode(split[2]) { return fmt.Errorf("invalid device mode: %s", split[2]) } fallthrough case 2: if (!createconfig.IsValidDeviceMode(split[1]) && !strings.HasPrefix(split[1], "/dev/")) || (len(split) == 3 && createconfig.IsValidDeviceMode(split[1])) { return fmt.Errorf("invalid device mode: %s", split[1]) } fallthrough case 1: if !strings.HasPrefix(split[0], "/dev/") { return fmt.Errorf("invalid device mode: %s", split[0]) } default: return fmt.Errorf("invalid device specification: %s", d) } } // check we do have at least a runtime if _, ok := c.Runtimes[c.DefaultRuntime]; !ok { return errors.New("no default runtime configured") } // check for validation on execution if onExecution { // Validate if runtime_path does exist for each runtime for runtime, handler := range c.Runtimes { if _, err := os.Stat(handler.RuntimePath); os.IsNotExist(err) { return fmt.Errorf("invalid runtime_path for runtime '%s': %q", runtime, err) } logrus.Debugf("found valid runtime '%s' for runtime_path '%s'\n", runtime, handler.RuntimePath) } // Validate the system registries configuration if _, err := sysregistriesv2.GetRegistries(nil); err != nil { return fmt.Errorf("invalid /etc/containers/registries.conf: %q", err) } for _, hooksDir := range c.HooksDir { if _, err := os.Stat(hooksDir); err != nil { return errors.Wrapf(err, "invalid hooks_dir entry") } } if _, err := os.Stat(c.Conmon); err != nil { return errors.Wrapf(err, "invalid conmon path") } } return nil }
[ "func", "(", "c", "*", "RuntimeConfig", ")", "Validate", "(", "onExecution", "bool", ")", "error", "{", "for", "_", ",", "u", ":=", "range", "c", ".", "DefaultUlimits", "{", "ul", ",", "err", ":=", "units", ".", "ParseUlimit", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unrecognized ulimit %s: %v\"", ",", "u", ",", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "ul", ".", "GetRlimit", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "for", "_", ",", "d", ":=", "range", "c", ".", "AdditionalDevices", "{", "split", ":=", "strings", ".", "Split", "(", "d", ",", "\":\"", ")", "\n", "switch", "len", "(", "split", ")", "{", "case", "3", ":", "if", "!", "createconfig", ".", "IsValidDeviceMode", "(", "split", "[", "2", "]", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"invalid device mode: %s\"", ",", "split", "[", "2", "]", ")", "\n", "}", "\n", "fallthrough", "\n", "case", "2", ":", "if", "(", "!", "createconfig", ".", "IsValidDeviceMode", "(", "split", "[", "1", "]", ")", "&&", "!", "strings", ".", "HasPrefix", "(", "split", "[", "1", "]", ",", "\"/dev/\"", ")", ")", "||", "(", "len", "(", "split", ")", "==", "3", "&&", "createconfig", ".", "IsValidDeviceMode", "(", "split", "[", "1", "]", ")", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"invalid device mode: %s\"", ",", "split", "[", "1", "]", ")", "\n", "}", "\n", "fallthrough", "\n", "case", "1", ":", "if", "!", "strings", ".", "HasPrefix", "(", "split", "[", "0", "]", ",", "\"/dev/\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"invalid device mode: %s\"", ",", "split", "[", "0", "]", ")", "\n", "}", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"invalid device specification: %s\"", ",", "d", ")", "\n", "}", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "c", ".", "Runtimes", "[", "c", ".", "DefaultRuntime", "]", ";", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"no default runtime configured\"", ")", "\n", "}", "\n", "if", "onExecution", "{", "for", "runtime", ",", "handler", ":=", "range", "c", ".", "Runtimes", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "handler", ".", "RuntimePath", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"invalid runtime_path for runtime '%s': %q\"", ",", "runtime", ",", "err", ")", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"found valid runtime '%s' for runtime_path '%s'\\n\"", ",", "\\n", ",", "runtime", ")", "\n", "}", "\n", "handler", ".", "RuntimePath", "\n", "if", "_", ",", "err", ":=", "sysregistriesv2", ".", "GetRegistries", "(", "nil", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"invalid /etc/containers/registries.conf: %q\"", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "hooksDir", ":=", "range", "c", ".", "HooksDir", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "hooksDir", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"invalid hooks_dir entry\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "c", ".", "Conmon", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"invalid conmon path\"", ")", "\n", "}", "\n", "}" ]
// Validate is the main entry point for runtime configuration validation // The parameter `onExecution` specifies if the validation should include // execution checks. It returns an `error` on validation failure, otherwise // `nil`.
[ "Validate", "is", "the", "main", "entry", "point", "for", "runtime", "configuration", "validation", "The", "parameter", "onExecution", "specifies", "if", "the", "validation", "should", "include", "execution", "checks", ".", "It", "returns", "an", "error", "on", "validation", "failure", "otherwise", "nil", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/config.go#L456-L531
train
cri-o/cri-o
lib/config.go
Validate
func (c *NetworkConfig) Validate(onExecution bool) error { if onExecution { if _, err := os.Stat(c.NetworkDir); err != nil { return errors.Wrapf(err, "invalid network_dir") } for _, pluginDir := range c.PluginDir { if err := os.MkdirAll(pluginDir, 0755); err != nil { return errors.Wrapf(err, "invalid plugin_dir entry") } } } return nil }
go
func (c *NetworkConfig) Validate(onExecution bool) error { if onExecution { if _, err := os.Stat(c.NetworkDir); err != nil { return errors.Wrapf(err, "invalid network_dir") } for _, pluginDir := range c.PluginDir { if err := os.MkdirAll(pluginDir, 0755); err != nil { return errors.Wrapf(err, "invalid plugin_dir entry") } } } return nil }
[ "func", "(", "c", "*", "NetworkConfig", ")", "Validate", "(", "onExecution", "bool", ")", "error", "{", "if", "onExecution", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "c", ".", "NetworkDir", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"invalid network_dir\"", ")", "\n", "}", "\n", "for", "_", ",", "pluginDir", ":=", "range", "c", ".", "PluginDir", "{", "if", "err", ":=", "os", ".", "MkdirAll", "(", "pluginDir", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"invalid plugin_dir entry\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate is the main entry point for network configuration validation. // The parameter `onExecution` specifies if the validation should include // execution checks. It returns an `error` on validation failure, otherwise // `nil`.
[ "Validate", "is", "the", "main", "entry", "point", "for", "network", "configuration", "validation", ".", "The", "parameter", "onExecution", "specifies", "if", "the", "validation", "should", "include", "execution", "checks", ".", "It", "returns", "an", "error", "on", "validation", "failure", "otherwise", "nil", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/config.go#L537-L551
train
cri-o/cri-o
server/sandbox_run.go
privilegedSandbox
func (s *Server) privilegedSandbox(req *pb.RunPodSandboxRequest) bool { securityContext := req.GetConfig().GetLinux().GetSecurityContext() if securityContext == nil { return false } if securityContext.Privileged { return true } namespaceOptions := securityContext.GetNamespaceOptions() if namespaceOptions == nil { return false } if namespaceOptions.GetNetwork() == pb.NamespaceMode_NODE || namespaceOptions.GetPid() == pb.NamespaceMode_NODE || namespaceOptions.GetIpc() == pb.NamespaceMode_NODE { return true } return false }
go
func (s *Server) privilegedSandbox(req *pb.RunPodSandboxRequest) bool { securityContext := req.GetConfig().GetLinux().GetSecurityContext() if securityContext == nil { return false } if securityContext.Privileged { return true } namespaceOptions := securityContext.GetNamespaceOptions() if namespaceOptions == nil { return false } if namespaceOptions.GetNetwork() == pb.NamespaceMode_NODE || namespaceOptions.GetPid() == pb.NamespaceMode_NODE || namespaceOptions.GetIpc() == pb.NamespaceMode_NODE { return true } return false }
[ "func", "(", "s", "*", "Server", ")", "privilegedSandbox", "(", "req", "*", "pb", ".", "RunPodSandboxRequest", ")", "bool", "{", "securityContext", ":=", "req", ".", "GetConfig", "(", ")", ".", "GetLinux", "(", ")", ".", "GetSecurityContext", "(", ")", "\n", "if", "securityContext", "==", "nil", "{", "return", "false", "\n", "}", "\n", "if", "securityContext", ".", "Privileged", "{", "return", "true", "\n", "}", "\n", "namespaceOptions", ":=", "securityContext", ".", "GetNamespaceOptions", "(", ")", "\n", "if", "namespaceOptions", "==", "nil", "{", "return", "false", "\n", "}", "\n", "if", "namespaceOptions", ".", "GetNetwork", "(", ")", "==", "pb", ".", "NamespaceMode_NODE", "||", "namespaceOptions", ".", "GetPid", "(", ")", "==", "pb", ".", "NamespaceMode_NODE", "||", "namespaceOptions", ".", "GetIpc", "(", ")", "==", "pb", ".", "NamespaceMode_NODE", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// privilegedSandbox returns true if the sandbox configuration // requires additional host privileges for the sandbox.
[ "privilegedSandbox", "returns", "true", "if", "the", "sandbox", "configuration", "requires", "additional", "host", "privileges", "for", "the", "sandbox", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/sandbox_run.go#L28-L50
train
cri-o/cri-o
server/sandbox_run.go
runtimeHandler
func (s *Server) runtimeHandler(req *pb.RunPodSandboxRequest) (string, error) { handler := req.GetRuntimeHandler() if handler == "" { return handler, nil } runtime, ok := s.Runtime().(*oci.Runtime) if !ok { return "", fmt.Errorf("runtime interface conversion error") } if _, err := runtime.ValidateRuntimeHandler(handler); err != nil { return "", err } return handler, nil }
go
func (s *Server) runtimeHandler(req *pb.RunPodSandboxRequest) (string, error) { handler := req.GetRuntimeHandler() if handler == "" { return handler, nil } runtime, ok := s.Runtime().(*oci.Runtime) if !ok { return "", fmt.Errorf("runtime interface conversion error") } if _, err := runtime.ValidateRuntimeHandler(handler); err != nil { return "", err } return handler, nil }
[ "func", "(", "s", "*", "Server", ")", "runtimeHandler", "(", "req", "*", "pb", ".", "RunPodSandboxRequest", ")", "(", "string", ",", "error", ")", "{", "handler", ":=", "req", ".", "GetRuntimeHandler", "(", ")", "\n", "if", "handler", "==", "\"\"", "{", "return", "handler", ",", "nil", "\n", "}", "\n", "runtime", ",", "ok", ":=", "s", ".", "Runtime", "(", ")", ".", "(", "*", "oci", ".", "Runtime", ")", "\n", "if", "!", "ok", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"runtime interface conversion error\"", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "runtime", ".", "ValidateRuntimeHandler", "(", "handler", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "handler", ",", "nil", "\n", "}" ]
// runtimeHandler returns the runtime handler key provided by CRI if the key // does exist and the associated data are valid. If the key is empty, there // is nothing to do, and the empty key is returned. For every other case, this // function will return an empty string with the error associated.
[ "runtimeHandler", "returns", "the", "runtime", "handler", "key", "provided", "by", "CRI", "if", "the", "key", "does", "exist", "and", "the", "associated", "data", "are", "valid", ".", "If", "the", "key", "is", "empty", "there", "is", "nothing", "to", "do", "and", "the", "empty", "key", "is", "returned", ".", "For", "every", "other", "case", "this", "function", "will", "return", "an", "empty", "string", "with", "the", "error", "associated", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/sandbox_run.go#L56-L72
train
cri-o/cri-o
server/sandbox_run.go
RunPodSandbox
func (s *Server) RunPodSandbox(ctx context.Context, req *pb.RunPodSandboxRequest) (resp *pb.RunPodSandboxResponse, err error) { // platform dependent call return s.runPodSandbox(ctx, req) }
go
func (s *Server) RunPodSandbox(ctx context.Context, req *pb.RunPodSandboxRequest) (resp *pb.RunPodSandboxResponse, err error) { // platform dependent call return s.runPodSandbox(ctx, req) }
[ "func", "(", "s", "*", "Server", ")", "RunPodSandbox", "(", "ctx", "context", ".", "Context", ",", "req", "*", "pb", ".", "RunPodSandboxRequest", ")", "(", "resp", "*", "pb", ".", "RunPodSandboxResponse", ",", "err", "error", ")", "{", "return", "s", ".", "runPodSandbox", "(", "ctx", ",", "req", ")", "\n", "}" ]
// RunPodSandbox creates and runs a pod-level sandbox.
[ "RunPodSandbox", "creates", "and", "runs", "a", "pod", "-", "level", "sandbox", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/sandbox_run.go#L79-L82
train
cri-o/cri-o
server/sandbox_stop.go
StopPodSandbox
func (s *Server) StopPodSandbox(ctx context.Context, req *pb.StopPodSandboxRequest) (resp *pb.StopPodSandboxResponse, err error) { // platform dependent call return s.stopPodSandbox(ctx, req) }
go
func (s *Server) StopPodSandbox(ctx context.Context, req *pb.StopPodSandboxRequest) (resp *pb.StopPodSandboxResponse, err error) { // platform dependent call return s.stopPodSandbox(ctx, req) }
[ "func", "(", "s", "*", "Server", ")", "StopPodSandbox", "(", "ctx", "context", ".", "Context", ",", "req", "*", "pb", ".", "StopPodSandboxRequest", ")", "(", "resp", "*", "pb", ".", "StopPodSandboxResponse", ",", "err", "error", ")", "{", "return", "s", ".", "stopPodSandbox", "(", "ctx", ",", "req", ")", "\n", "}" ]
// StopPodSandbox stops the sandbox. If there are any running containers in the // sandbox, they should be force terminated.
[ "StopPodSandbox", "stops", "the", "sandbox", ".", "If", "there", "are", "any", "running", "containers", "in", "the", "sandbox", "they", "should", "be", "force", "terminated", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/sandbox_stop.go#L11-L14
train
cri-o/cri-o
server/sandbox_stop.go
stopAllPodSandboxes
func (s *Server) stopAllPodSandboxes(ctx context.Context) { logrus.Debugf("stopAllPodSandboxes") for _, sb := range s.ContainerServer.ListSandboxes() { pod := &pb.StopPodSandboxRequest{ PodSandboxId: sb.ID(), } if _, err := s.StopPodSandbox(ctx, pod); err != nil { logrus.Warnf("could not StopPodSandbox %s: %v", sb.ID(), err) } } }
go
func (s *Server) stopAllPodSandboxes(ctx context.Context) { logrus.Debugf("stopAllPodSandboxes") for _, sb := range s.ContainerServer.ListSandboxes() { pod := &pb.StopPodSandboxRequest{ PodSandboxId: sb.ID(), } if _, err := s.StopPodSandbox(ctx, pod); err != nil { logrus.Warnf("could not StopPodSandbox %s: %v", sb.ID(), err) } } }
[ "func", "(", "s", "*", "Server", ")", "stopAllPodSandboxes", "(", "ctx", "context", ".", "Context", ")", "{", "logrus", ".", "Debugf", "(", "\"stopAllPodSandboxes\"", ")", "\n", "for", "_", ",", "sb", ":=", "range", "s", ".", "ContainerServer", ".", "ListSandboxes", "(", ")", "{", "pod", ":=", "&", "pb", ".", "StopPodSandboxRequest", "{", "PodSandboxId", ":", "sb", ".", "ID", "(", ")", ",", "}", "\n", "if", "_", ",", "err", ":=", "s", ".", "StopPodSandbox", "(", "ctx", ",", "pod", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"could not StopPodSandbox %s: %v\"", ",", "sb", ".", "ID", "(", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}" ]
// stopAllPodSandboxes removes all pod sandboxes
[ "stopAllPodSandboxes", "removes", "all", "pod", "sandboxes" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/sandbox_stop.go#L17-L27
train
cri-o/cri-o
lib/container_server.go
localeToLanguage
func localeToLanguage(locale string) string { locale = strings.Replace(strings.SplitN(locale, ".", 2)[0], "_", "-", 1) langString, ok := localeToLanguageMap[strings.ToLower(locale)] if !ok { langString = locale } return langString }
go
func localeToLanguage(locale string) string { locale = strings.Replace(strings.SplitN(locale, ".", 2)[0], "_", "-", 1) langString, ok := localeToLanguageMap[strings.ToLower(locale)] if !ok { langString = locale } return langString }
[ "func", "localeToLanguage", "(", "locale", "string", ")", "string", "{", "locale", "=", "strings", ".", "Replace", "(", "strings", ".", "SplitN", "(", "locale", ",", "\".\"", ",", "2", ")", "[", "0", "]", ",", "\"_\"", ",", "\"-\"", ",", "1", ")", "\n", "langString", ",", "ok", ":=", "localeToLanguageMap", "[", "strings", ".", "ToLower", "(", "locale", ")", "]", "\n", "if", "!", "ok", "{", "langString", "=", "locale", "\n", "}", "\n", "return", "langString", "\n", "}" ]
// localeToLanguage translates POSIX locale strings to BCP 47 language tags.
[ "localeToLanguage", "translates", "POSIX", "locale", "strings", "to", "BCP", "47", "language", "tags", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L111-L118
train
cri-o/cri-o
lib/container_server.go
ContainerStateFromDisk
func (c *ContainerServer) ContainerStateFromDisk(ctr *oci.Container) error { if err := ctr.FromDisk(); err != nil { return err } // ignore errors, this is a best effort to have up-to-date info about // a given container before its state gets stored c.runtime.UpdateContainerStatus(ctr) return nil }
go
func (c *ContainerServer) ContainerStateFromDisk(ctr *oci.Container) error { if err := ctr.FromDisk(); err != nil { return err } // ignore errors, this is a best effort to have up-to-date info about // a given container before its state gets stored c.runtime.UpdateContainerStatus(ctr) return nil }
[ "func", "(", "c", "*", "ContainerServer", ")", "ContainerStateFromDisk", "(", "ctr", "*", "oci", ".", "Container", ")", "error", "{", "if", "err", ":=", "ctr", ".", "FromDisk", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "runtime", ".", "UpdateContainerStatus", "(", "ctr", ")", "\n", "return", "nil", "\n", "}" ]
// ContainerStateFromDisk retrieves information on the state of a running container // from the disk
[ "ContainerStateFromDisk", "retrieves", "information", "on", "the", "state", "of", "a", "running", "container", "from", "the", "disk" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L599-L608
train
cri-o/cri-o
lib/container_server.go
ContainerStateToDisk
func (c *ContainerServer) ContainerStateToDisk(ctr *oci.Container) error { // ignore errors, this is a best effort to have up-to-date info about // a given container before its state gets stored c.Runtime().UpdateContainerStatus(ctr) jsonSource, err := ioutils.NewAtomicFileWriter(ctr.StatePath(), 0644) if err != nil { return err } defer jsonSource.Close() enc := json.NewEncoder(jsonSource) return enc.Encode(ctr.State()) }
go
func (c *ContainerServer) ContainerStateToDisk(ctr *oci.Container) error { // ignore errors, this is a best effort to have up-to-date info about // a given container before its state gets stored c.Runtime().UpdateContainerStatus(ctr) jsonSource, err := ioutils.NewAtomicFileWriter(ctr.StatePath(), 0644) if err != nil { return err } defer jsonSource.Close() enc := json.NewEncoder(jsonSource) return enc.Encode(ctr.State()) }
[ "func", "(", "c", "*", "ContainerServer", ")", "ContainerStateToDisk", "(", "ctr", "*", "oci", ".", "Container", ")", "error", "{", "c", ".", "Runtime", "(", ")", ".", "UpdateContainerStatus", "(", "ctr", ")", "\n", "jsonSource", ",", "err", ":=", "ioutils", ".", "NewAtomicFileWriter", "(", "ctr", ".", "StatePath", "(", ")", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "jsonSource", ".", "Close", "(", ")", "\n", "enc", ":=", "json", ".", "NewEncoder", "(", "jsonSource", ")", "\n", "return", "enc", ".", "Encode", "(", "ctr", ".", "State", "(", ")", ")", "\n", "}" ]
// ContainerStateToDisk writes the container's state information to a JSON file // on disk
[ "ContainerStateToDisk", "writes", "the", "container", "s", "state", "information", "to", "a", "JSON", "file", "on", "disk" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L612-L624
train
cri-o/cri-o
lib/container_server.go
ReserveContainerName
func (c *ContainerServer) ReserveContainerName(id, name string) (string, error) { if err := c.ctrNameIndex.Reserve(name, id); err != nil { err = fmt.Errorf("error reserving ctr name %s for id %s", name, id) logrus.Warn(err) return "", err } return name, nil }
go
func (c *ContainerServer) ReserveContainerName(id, name string) (string, error) { if err := c.ctrNameIndex.Reserve(name, id); err != nil { err = fmt.Errorf("error reserving ctr name %s for id %s", name, id) logrus.Warn(err) return "", err } return name, nil }
[ "func", "(", "c", "*", "ContainerServer", ")", "ReserveContainerName", "(", "id", ",", "name", "string", ")", "(", "string", ",", "error", ")", "{", "if", "err", ":=", "c", ".", "ctrNameIndex", ".", "Reserve", "(", "name", ",", "id", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"error reserving ctr name %s for id %s\"", ",", "name", ",", "id", ")", "\n", "logrus", ".", "Warn", "(", "err", ")", "\n", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "name", ",", "nil", "\n", "}" ]
// ReserveContainerName holds a name for a container that is being created
[ "ReserveContainerName", "holds", "a", "name", "for", "a", "container", "that", "is", "being", "created" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L627-L634
train
cri-o/cri-o
lib/container_server.go
ReservePodName
func (c *ContainerServer) ReservePodName(id, name string) (string, error) { if err := c.podNameIndex.Reserve(name, id); err != nil { err = fmt.Errorf("error reserving pod name %s for id %s", name, id) logrus.Warn(err) return "", err } return name, nil }
go
func (c *ContainerServer) ReservePodName(id, name string) (string, error) { if err := c.podNameIndex.Reserve(name, id); err != nil { err = fmt.Errorf("error reserving pod name %s for id %s", name, id) logrus.Warn(err) return "", err } return name, nil }
[ "func", "(", "c", "*", "ContainerServer", ")", "ReservePodName", "(", "id", ",", "name", "string", ")", "(", "string", ",", "error", ")", "{", "if", "err", ":=", "c", ".", "podNameIndex", ".", "Reserve", "(", "name", ",", "id", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"error reserving pod name %s for id %s\"", ",", "name", ",", "id", ")", "\n", "logrus", ".", "Warn", "(", "err", ")", "\n", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "name", ",", "nil", "\n", "}" ]
// ReservePodName holds a name for a pod that is being created
[ "ReservePodName", "holds", "a", "name", "for", "a", "pod", "that", "is", "being", "created" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L643-L650
train
cri-o/cri-o
lib/container_server.go
AddContainer
func (c *ContainerServer) AddContainer(ctr *oci.Container) { sandbox := c.state.sandboxes.Get(ctr.Sandbox()) if sandbox == nil { return } sandbox.AddContainer(ctr) c.state.containers.Add(ctr.ID(), ctr) }
go
func (c *ContainerServer) AddContainer(ctr *oci.Container) { sandbox := c.state.sandboxes.Get(ctr.Sandbox()) if sandbox == nil { return } sandbox.AddContainer(ctr) c.state.containers.Add(ctr.ID(), ctr) }
[ "func", "(", "c", "*", "ContainerServer", ")", "AddContainer", "(", "ctr", "*", "oci", ".", "Container", ")", "{", "sandbox", ":=", "c", ".", "state", ".", "sandboxes", ".", "Get", "(", "ctr", ".", "Sandbox", "(", ")", ")", "\n", "if", "sandbox", "==", "nil", "{", "return", "\n", "}", "\n", "sandbox", ".", "AddContainer", "(", "ctr", ")", "\n", "c", ".", "state", ".", "containers", ".", "Add", "(", "ctr", ".", "ID", "(", ")", ",", "ctr", ")", "\n", "}" ]
// AddContainer adds a container to the container state store
[ "AddContainer", "adds", "a", "container", "to", "the", "container", "state", "store" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L676-L683
train
cri-o/cri-o
lib/container_server.go
AddInfraContainer
func (c *ContainerServer) AddInfraContainer(ctr *oci.Container) { c.state.infraContainers.Add(ctr.ID(), ctr) }
go
func (c *ContainerServer) AddInfraContainer(ctr *oci.Container) { c.state.infraContainers.Add(ctr.ID(), ctr) }
[ "func", "(", "c", "*", "ContainerServer", ")", "AddInfraContainer", "(", "ctr", "*", "oci", ".", "Container", ")", "{", "c", ".", "state", ".", "infraContainers", ".", "Add", "(", "ctr", ".", "ID", "(", ")", ",", "ctr", ")", "\n", "}" ]
// AddInfraContainer adds a container to the container state store
[ "AddInfraContainer", "adds", "a", "container", "to", "the", "container", "state", "store" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L686-L688
train
cri-o/cri-o
lib/container_server.go
GetContainer
func (c *ContainerServer) GetContainer(id string) *oci.Container { return c.state.containers.Get(id) }
go
func (c *ContainerServer) GetContainer(id string) *oci.Container { return c.state.containers.Get(id) }
[ "func", "(", "c", "*", "ContainerServer", ")", "GetContainer", "(", "id", "string", ")", "*", "oci", ".", "Container", "{", "return", "c", ".", "state", ".", "containers", ".", "Get", "(", "id", ")", "\n", "}" ]
// GetContainer returns a container by its ID
[ "GetContainer", "returns", "a", "container", "by", "its", "ID" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L691-L693
train
cri-o/cri-o
lib/container_server.go
GetInfraContainer
func (c *ContainerServer) GetInfraContainer(id string) *oci.Container { return c.state.infraContainers.Get(id) }
go
func (c *ContainerServer) GetInfraContainer(id string) *oci.Container { return c.state.infraContainers.Get(id) }
[ "func", "(", "c", "*", "ContainerServer", ")", "GetInfraContainer", "(", "id", "string", ")", "*", "oci", ".", "Container", "{", "return", "c", ".", "state", ".", "infraContainers", ".", "Get", "(", "id", ")", "\n", "}" ]
// GetInfraContainer returns a container by its ID
[ "GetInfraContainer", "returns", "a", "container", "by", "its", "ID" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L696-L698
train
cri-o/cri-o
lib/container_server.go
HasContainer
func (c *ContainerServer) HasContainer(id string) bool { return c.state.containers.Get(id) != nil }
go
func (c *ContainerServer) HasContainer(id string) bool { return c.state.containers.Get(id) != nil }
[ "func", "(", "c", "*", "ContainerServer", ")", "HasContainer", "(", "id", "string", ")", "bool", "{", "return", "c", ".", "state", ".", "containers", ".", "Get", "(", "id", ")", "!=", "nil", "\n", "}" ]
// HasContainer checks if a container exists in the state
[ "HasContainer", "checks", "if", "a", "container", "exists", "in", "the", "state" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L701-L703
train
cri-o/cri-o
lib/container_server.go
RemoveContainer
func (c *ContainerServer) RemoveContainer(ctr *oci.Container) { sbID := ctr.Sandbox() sb := c.state.sandboxes.Get(sbID) if sb == nil { return } sb.RemoveContainer(ctr) c.state.containers.Delete(ctr.ID()) }
go
func (c *ContainerServer) RemoveContainer(ctr *oci.Container) { sbID := ctr.Sandbox() sb := c.state.sandboxes.Get(sbID) if sb == nil { return } sb.RemoveContainer(ctr) c.state.containers.Delete(ctr.ID()) }
[ "func", "(", "c", "*", "ContainerServer", ")", "RemoveContainer", "(", "ctr", "*", "oci", ".", "Container", ")", "{", "sbID", ":=", "ctr", ".", "Sandbox", "(", ")", "\n", "sb", ":=", "c", ".", "state", ".", "sandboxes", ".", "Get", "(", "sbID", ")", "\n", "if", "sb", "==", "nil", "{", "return", "\n", "}", "\n", "sb", ".", "RemoveContainer", "(", "ctr", ")", "\n", "c", ".", "state", ".", "containers", ".", "Delete", "(", "ctr", ".", "ID", "(", ")", ")", "\n", "}" ]
// RemoveContainer removes a container from the container state store
[ "RemoveContainer", "removes", "a", "container", "from", "the", "container", "state", "store" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L706-L714
train
cri-o/cri-o
lib/container_server.go
RemoveInfraContainer
func (c *ContainerServer) RemoveInfraContainer(ctr *oci.Container) { c.state.infraContainers.Delete(ctr.ID()) }
go
func (c *ContainerServer) RemoveInfraContainer(ctr *oci.Container) { c.state.infraContainers.Delete(ctr.ID()) }
[ "func", "(", "c", "*", "ContainerServer", ")", "RemoveInfraContainer", "(", "ctr", "*", "oci", ".", "Container", ")", "{", "c", ".", "state", ".", "infraContainers", ".", "Delete", "(", "ctr", ".", "ID", "(", ")", ")", "\n", "}" ]
// RemoveInfraContainer removes a container from the container state store
[ "RemoveInfraContainer", "removes", "a", "container", "from", "the", "container", "state", "store" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L717-L719
train
cri-o/cri-o
lib/container_server.go
ListContainers
func (c *ContainerServer) ListContainers(filters ...func(*oci.Container) bool) ([]*oci.Container, error) { containers := c.listContainers() if len(filters) == 0 { return containers, nil } filteredContainers := make([]*oci.Container, 0, len(containers)) for _, container := range containers { for _, filter := range filters { if filter(container) { filteredContainers = append(filteredContainers, container) } } } return filteredContainers, nil }
go
func (c *ContainerServer) ListContainers(filters ...func(*oci.Container) bool) ([]*oci.Container, error) { containers := c.listContainers() if len(filters) == 0 { return containers, nil } filteredContainers := make([]*oci.Container, 0, len(containers)) for _, container := range containers { for _, filter := range filters { if filter(container) { filteredContainers = append(filteredContainers, container) } } } return filteredContainers, nil }
[ "func", "(", "c", "*", "ContainerServer", ")", "ListContainers", "(", "filters", "...", "func", "(", "*", "oci", ".", "Container", ")", "bool", ")", "(", "[", "]", "*", "oci", ".", "Container", ",", "error", ")", "{", "containers", ":=", "c", ".", "listContainers", "(", ")", "\n", "if", "len", "(", "filters", ")", "==", "0", "{", "return", "containers", ",", "nil", "\n", "}", "\n", "filteredContainers", ":=", "make", "(", "[", "]", "*", "oci", ".", "Container", ",", "0", ",", "len", "(", "containers", ")", ")", "\n", "for", "_", ",", "container", ":=", "range", "containers", "{", "for", "_", ",", "filter", ":=", "range", "filters", "{", "if", "filter", "(", "container", ")", "{", "filteredContainers", "=", "append", "(", "filteredContainers", ",", "container", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "filteredContainers", ",", "nil", "\n", "}" ]
// ListContainers returns a list of all containers stored by the server state // that match the given filter function
[ "ListContainers", "returns", "a", "list", "of", "all", "containers", "stored", "by", "the", "server", "state", "that", "match", "the", "given", "filter", "function" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L728-L742
train
cri-o/cri-o
lib/container_server.go
AddSandbox
func (c *ContainerServer) AddSandbox(sb *sandbox.Sandbox) error { c.state.sandboxes.Add(sb.ID(), sb) c.stateLock.Lock() defer c.stateLock.Unlock() return c.addSandboxPlatform(sb) }
go
func (c *ContainerServer) AddSandbox(sb *sandbox.Sandbox) error { c.state.sandboxes.Add(sb.ID(), sb) c.stateLock.Lock() defer c.stateLock.Unlock() return c.addSandboxPlatform(sb) }
[ "func", "(", "c", "*", "ContainerServer", ")", "AddSandbox", "(", "sb", "*", "sandbox", ".", "Sandbox", ")", "error", "{", "c", ".", "state", ".", "sandboxes", ".", "Add", "(", "sb", ".", "ID", "(", ")", ",", "sb", ")", "\n", "c", ".", "stateLock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "return", "c", ".", "addSandboxPlatform", "(", "sb", ")", "\n", "}" ]
// AddSandbox adds a sandbox to the sandbox state store
[ "AddSandbox", "adds", "a", "sandbox", "to", "the", "sandbox", "state", "store" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L745-L751
train
cri-o/cri-o
lib/container_server.go
GetSandbox
func (c *ContainerServer) GetSandbox(id string) *sandbox.Sandbox { return c.state.sandboxes.Get(id) }
go
func (c *ContainerServer) GetSandbox(id string) *sandbox.Sandbox { return c.state.sandboxes.Get(id) }
[ "func", "(", "c", "*", "ContainerServer", ")", "GetSandbox", "(", "id", "string", ")", "*", "sandbox", ".", "Sandbox", "{", "return", "c", ".", "state", ".", "sandboxes", ".", "Get", "(", "id", ")", "\n", "}" ]
// GetSandbox returns a sandbox by its ID
[ "GetSandbox", "returns", "a", "sandbox", "by", "its", "ID" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L754-L756
train
cri-o/cri-o
lib/container_server.go
GetSandboxContainer
func (c *ContainerServer) GetSandboxContainer(id string) *oci.Container { sb := c.state.sandboxes.Get(id) if sb == nil { return nil } return sb.InfraContainer() }
go
func (c *ContainerServer) GetSandboxContainer(id string) *oci.Container { sb := c.state.sandboxes.Get(id) if sb == nil { return nil } return sb.InfraContainer() }
[ "func", "(", "c", "*", "ContainerServer", ")", "GetSandboxContainer", "(", "id", "string", ")", "*", "oci", ".", "Container", "{", "sb", ":=", "c", ".", "state", ".", "sandboxes", ".", "Get", "(", "id", ")", "\n", "if", "sb", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "sb", ".", "InfraContainer", "(", ")", "\n", "}" ]
// GetSandboxContainer returns a sandbox's infra container
[ "GetSandboxContainer", "returns", "a", "sandbox", "s", "infra", "container" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L759-L765
train
cri-o/cri-o
lib/container_server.go
HasSandbox
func (c *ContainerServer) HasSandbox(id string) bool { return c.state.sandboxes.Get(id) != nil }
go
func (c *ContainerServer) HasSandbox(id string) bool { return c.state.sandboxes.Get(id) != nil }
[ "func", "(", "c", "*", "ContainerServer", ")", "HasSandbox", "(", "id", "string", ")", "bool", "{", "return", "c", ".", "state", ".", "sandboxes", ".", "Get", "(", "id", ")", "!=", "nil", "\n", "}" ]
// HasSandbox checks if a sandbox exists in the state
[ "HasSandbox", "checks", "if", "a", "sandbox", "exists", "in", "the", "state" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L768-L770
train
cri-o/cri-o
lib/container_server.go
RemoveSandbox
func (c *ContainerServer) RemoveSandbox(id string) error { sb := c.state.sandboxes.Get(id) if sb == nil { return nil } c.stateLock.Lock() defer c.stateLock.Unlock() if err := c.removeSandboxPlatform(sb); err != nil { return err } c.state.sandboxes.Delete(id) return nil }
go
func (c *ContainerServer) RemoveSandbox(id string) error { sb := c.state.sandboxes.Get(id) if sb == nil { return nil } c.stateLock.Lock() defer c.stateLock.Unlock() if err := c.removeSandboxPlatform(sb); err != nil { return err } c.state.sandboxes.Delete(id) return nil }
[ "func", "(", "c", "*", "ContainerServer", ")", "RemoveSandbox", "(", "id", "string", ")", "error", "{", "sb", ":=", "c", ".", "state", ".", "sandboxes", ".", "Get", "(", "id", ")", "\n", "if", "sb", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "c", ".", "stateLock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "stateLock", ".", "Unlock", "(", ")", "\n", "if", "err", ":=", "c", ".", "removeSandboxPlatform", "(", "sb", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "state", ".", "sandboxes", ".", "Delete", "(", "id", ")", "\n", "return", "nil", "\n", "}" ]
// RemoveSandbox removes a sandbox from the state store
[ "RemoveSandbox", "removes", "a", "sandbox", "from", "the", "state", "store" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/container_server.go#L773-L787
train
cri-o/cri-o
server/sandbox_status.go
PodSandboxStatus
func (s *Server) PodSandboxStatus(ctx context.Context, req *pb.PodSandboxStatusRequest) (resp *pb.PodSandboxStatusResponse, err error) { const operation = "pod_sandbox_status" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() logrus.Debugf("PodSandboxStatusRequest %+v", req) sb, err := s.getPodSandboxFromRequest(req.PodSandboxId) if err != nil { return nil, err } podInfraContainer := sb.InfraContainer() cState := podInfraContainer.State() rStatus := pb.PodSandboxState_SANDBOX_NOTREADY if cState.Status == oci.ContainerStateRunning { rStatus = pb.PodSandboxState_SANDBOX_READY } linux := &pb.LinuxPodSandboxStatus{ Namespaces: &pb.Namespace{ Options: &pb.NamespaceOption{ Network: sb.NamespaceOptions().GetNetwork(), Ipc: sb.NamespaceOptions().GetIpc(), Pid: sb.NamespaceOptions().GetPid(), }, }, } sandboxID := sb.ID() resp = &pb.PodSandboxStatusResponse{ Status: &pb.PodSandboxStatus{ Id: sandboxID, CreatedAt: podInfraContainer.CreatedAt().UnixNano(), Network: &pb.PodSandboxNetworkStatus{Ip: sb.IP()}, State: rStatus, Labels: sb.Labels(), Annotations: sb.Annotations(), Metadata: sb.Metadata(), Linux: linux, }, } logrus.Debugf("PodSandboxStatusResponse: %+v", resp) return resp, nil }
go
func (s *Server) PodSandboxStatus(ctx context.Context, req *pb.PodSandboxStatusRequest) (resp *pb.PodSandboxStatusResponse, err error) { const operation = "pod_sandbox_status" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() logrus.Debugf("PodSandboxStatusRequest %+v", req) sb, err := s.getPodSandboxFromRequest(req.PodSandboxId) if err != nil { return nil, err } podInfraContainer := sb.InfraContainer() cState := podInfraContainer.State() rStatus := pb.PodSandboxState_SANDBOX_NOTREADY if cState.Status == oci.ContainerStateRunning { rStatus = pb.PodSandboxState_SANDBOX_READY } linux := &pb.LinuxPodSandboxStatus{ Namespaces: &pb.Namespace{ Options: &pb.NamespaceOption{ Network: sb.NamespaceOptions().GetNetwork(), Ipc: sb.NamespaceOptions().GetIpc(), Pid: sb.NamespaceOptions().GetPid(), }, }, } sandboxID := sb.ID() resp = &pb.PodSandboxStatusResponse{ Status: &pb.PodSandboxStatus{ Id: sandboxID, CreatedAt: podInfraContainer.CreatedAt().UnixNano(), Network: &pb.PodSandboxNetworkStatus{Ip: sb.IP()}, State: rStatus, Labels: sb.Labels(), Annotations: sb.Annotations(), Metadata: sb.Metadata(), Linux: linux, }, } logrus.Debugf("PodSandboxStatusResponse: %+v", resp) return resp, nil }
[ "func", "(", "s", "*", "Server", ")", "PodSandboxStatus", "(", "ctx", "context", ".", "Context", ",", "req", "*", "pb", ".", "PodSandboxStatusRequest", ")", "(", "resp", "*", "pb", ".", "PodSandboxStatusResponse", ",", "err", "error", ")", "{", "const", "operation", "=", "\"pod_sandbox_status\"", "\n", "defer", "func", "(", ")", "{", "recordOperation", "(", "operation", ",", "time", ".", "Now", "(", ")", ")", "\n", "recordError", "(", "operation", ",", "err", ")", "\n", "}", "(", ")", "\n", "logrus", ".", "Debugf", "(", "\"PodSandboxStatusRequest %+v\"", ",", "req", ")", "\n", "sb", ",", "err", ":=", "s", ".", "getPodSandboxFromRequest", "(", "req", ".", "PodSandboxId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "podInfraContainer", ":=", "sb", ".", "InfraContainer", "(", ")", "\n", "cState", ":=", "podInfraContainer", ".", "State", "(", ")", "\n", "rStatus", ":=", "pb", ".", "PodSandboxState_SANDBOX_NOTREADY", "\n", "if", "cState", ".", "Status", "==", "oci", ".", "ContainerStateRunning", "{", "rStatus", "=", "pb", ".", "PodSandboxState_SANDBOX_READY", "\n", "}", "\n", "linux", ":=", "&", "pb", ".", "LinuxPodSandboxStatus", "{", "Namespaces", ":", "&", "pb", ".", "Namespace", "{", "Options", ":", "&", "pb", ".", "NamespaceOption", "{", "Network", ":", "sb", ".", "NamespaceOptions", "(", ")", ".", "GetNetwork", "(", ")", ",", "Ipc", ":", "sb", ".", "NamespaceOptions", "(", ")", ".", "GetIpc", "(", ")", ",", "Pid", ":", "sb", ".", "NamespaceOptions", "(", ")", ".", "GetPid", "(", ")", ",", "}", ",", "}", ",", "}", "\n", "sandboxID", ":=", "sb", ".", "ID", "(", ")", "\n", "resp", "=", "&", "pb", ".", "PodSandboxStatusResponse", "{", "Status", ":", "&", "pb", ".", "PodSandboxStatus", "{", "Id", ":", "sandboxID", ",", "CreatedAt", ":", "podInfraContainer", ".", "CreatedAt", "(", ")", ".", "UnixNano", "(", ")", ",", "Network", ":", "&", "pb", ".", "PodSandboxNetworkStatus", "{", "Ip", ":", "sb", ".", "IP", "(", ")", "}", ",", "State", ":", "rStatus", ",", "Labels", ":", "sb", ".", "Labels", "(", ")", ",", "Annotations", ":", "sb", ".", "Annotations", "(", ")", ",", "Metadata", ":", "sb", ".", "Metadata", "(", ")", ",", "Linux", ":", "linux", ",", "}", ",", "}", "\n", "logrus", ".", "Debugf", "(", "\"PodSandboxStatusResponse: %+v\"", ",", "resp", ")", "\n", "return", "resp", ",", "nil", "\n", "}" ]
// PodSandboxStatus returns the Status of the PodSandbox.
[ "PodSandboxStatus", "returns", "the", "Status", "of", "the", "PodSandbox", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/sandbox_status.go#L13-L60
train
cri-o/cri-o
server/runtime_status.go
Status
func (s *Server) Status(ctx context.Context, req *pb.StatusRequest) (resp *pb.StatusResponse, err error) { const operation = "status" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() runtimeCondition := &pb.RuntimeCondition{ Type: pb.RuntimeReady, Status: true, } networkCondition := &pb.RuntimeCondition{ Type: pb.NetworkReady, Status: true, } if err := s.netPlugin.Status(); err != nil { networkCondition.Status = false networkCondition.Reason = networkNotReadyReason networkCondition.Message = fmt.Sprintf("Network plugin returns error: %v", err) } resp = &pb.StatusResponse{ Status: &pb.RuntimeStatus{ Conditions: []*pb.RuntimeCondition{ runtimeCondition, networkCondition, }, }, } return resp, nil }
go
func (s *Server) Status(ctx context.Context, req *pb.StatusRequest) (resp *pb.StatusResponse, err error) { const operation = "status" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() runtimeCondition := &pb.RuntimeCondition{ Type: pb.RuntimeReady, Status: true, } networkCondition := &pb.RuntimeCondition{ Type: pb.NetworkReady, Status: true, } if err := s.netPlugin.Status(); err != nil { networkCondition.Status = false networkCondition.Reason = networkNotReadyReason networkCondition.Message = fmt.Sprintf("Network plugin returns error: %v", err) } resp = &pb.StatusResponse{ Status: &pb.RuntimeStatus{ Conditions: []*pb.RuntimeCondition{ runtimeCondition, networkCondition, }, }, } return resp, nil }
[ "func", "(", "s", "*", "Server", ")", "Status", "(", "ctx", "context", ".", "Context", ",", "req", "*", "pb", ".", "StatusRequest", ")", "(", "resp", "*", "pb", ".", "StatusResponse", ",", "err", "error", ")", "{", "const", "operation", "=", "\"status\"", "\n", "defer", "func", "(", ")", "{", "recordOperation", "(", "operation", ",", "time", ".", "Now", "(", ")", ")", "\n", "recordError", "(", "operation", ",", "err", ")", "\n", "}", "(", ")", "\n", "runtimeCondition", ":=", "&", "pb", ".", "RuntimeCondition", "{", "Type", ":", "pb", ".", "RuntimeReady", ",", "Status", ":", "true", ",", "}", "\n", "networkCondition", ":=", "&", "pb", ".", "RuntimeCondition", "{", "Type", ":", "pb", ".", "NetworkReady", ",", "Status", ":", "true", ",", "}", "\n", "if", "err", ":=", "s", ".", "netPlugin", ".", "Status", "(", ")", ";", "err", "!=", "nil", "{", "networkCondition", ".", "Status", "=", "false", "\n", "networkCondition", ".", "Reason", "=", "networkNotReadyReason", "\n", "networkCondition", ".", "Message", "=", "fmt", ".", "Sprintf", "(", "\"Network plugin returns error: %v\"", ",", "err", ")", "\n", "}", "\n", "resp", "=", "&", "pb", ".", "StatusResponse", "{", "Status", ":", "&", "pb", ".", "RuntimeStatus", "{", "Conditions", ":", "[", "]", "*", "pb", ".", "RuntimeCondition", "{", "runtimeCondition", ",", "networkCondition", ",", "}", ",", "}", ",", "}", "\n", "return", "resp", ",", "nil", "\n", "}" ]
// Status returns the status of the runtime
[ "Status", "returns", "the", "status", "of", "the", "runtime" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/runtime_status.go#L15-L47
train
cri-o/cri-o
server/metrics/metrics.go
Register
func Register() { registerMetrics.Do(func() { prometheus.MustRegister(CRIOOperations) prometheus.MustRegister(CRIOOperationsLatency) prometheus.MustRegister(CRIOOperationsErrors) }) }
go
func Register() { registerMetrics.Do(func() { prometheus.MustRegister(CRIOOperations) prometheus.MustRegister(CRIOOperationsLatency) prometheus.MustRegister(CRIOOperationsErrors) }) }
[ "func", "Register", "(", ")", "{", "registerMetrics", ".", "Do", "(", "func", "(", ")", "{", "prometheus", ".", "MustRegister", "(", "CRIOOperations", ")", "\n", "prometheus", ".", "MustRegister", "(", "CRIOOperationsLatency", ")", "\n", "prometheus", ".", "MustRegister", "(", "CRIOOperationsErrors", ")", "\n", "}", ")", "\n", "}" ]
// Register all metrics
[ "Register", "all", "metrics" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/metrics/metrics.go#L59-L65
train
cri-o/cri-o
pkg/storage/image.go
prepareReference
func (svc *imageService) prepareReference(imageName string, options *copy.Options) (types.ImageReference, error) { if imageName == "" { return nil, storage.ErrNotAnImage } srcRef, err := alltransports.ParseImageName(imageName) if err != nil { if svc.defaultTransport == "" { return nil, err } srcRef2, err2 := alltransports.ParseImageName(svc.defaultTransport + imageName) if err2 != nil { return nil, err } srcRef = srcRef2 } if options.SourceCtx == nil { options.SourceCtx = &types.SystemContext{} } if srcRef.DockerReference() != nil { hostname := reference.Domain(srcRef.DockerReference()) if secure := svc.isSecureIndex(hostname); !secure { options.SourceCtx.DockerInsecureSkipTLSVerify = types.NewOptionalBool(!secure) } } return srcRef, nil }
go
func (svc *imageService) prepareReference(imageName string, options *copy.Options) (types.ImageReference, error) { if imageName == "" { return nil, storage.ErrNotAnImage } srcRef, err := alltransports.ParseImageName(imageName) if err != nil { if svc.defaultTransport == "" { return nil, err } srcRef2, err2 := alltransports.ParseImageName(svc.defaultTransport + imageName) if err2 != nil { return nil, err } srcRef = srcRef2 } if options.SourceCtx == nil { options.SourceCtx = &types.SystemContext{} } if srcRef.DockerReference() != nil { hostname := reference.Domain(srcRef.DockerReference()) if secure := svc.isSecureIndex(hostname); !secure { options.SourceCtx.DockerInsecureSkipTLSVerify = types.NewOptionalBool(!secure) } } return srcRef, nil }
[ "func", "(", "svc", "*", "imageService", ")", "prepareReference", "(", "imageName", "string", ",", "options", "*", "copy", ".", "Options", ")", "(", "types", ".", "ImageReference", ",", "error", ")", "{", "if", "imageName", "==", "\"\"", "{", "return", "nil", ",", "storage", ".", "ErrNotAnImage", "\n", "}", "\n", "srcRef", ",", "err", ":=", "alltransports", ".", "ParseImageName", "(", "imageName", ")", "\n", "if", "err", "!=", "nil", "{", "if", "svc", ".", "defaultTransport", "==", "\"\"", "{", "return", "nil", ",", "err", "\n", "}", "\n", "srcRef2", ",", "err2", ":=", "alltransports", ".", "ParseImageName", "(", "svc", ".", "defaultTransport", "+", "imageName", ")", "\n", "if", "err2", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "srcRef", "=", "srcRef2", "\n", "}", "\n", "if", "options", ".", "SourceCtx", "==", "nil", "{", "options", ".", "SourceCtx", "=", "&", "types", ".", "SystemContext", "{", "}", "\n", "}", "\n", "if", "srcRef", ".", "DockerReference", "(", ")", "!=", "nil", "{", "hostname", ":=", "reference", ".", "Domain", "(", "srcRef", ".", "DockerReference", "(", ")", ")", "\n", "if", "secure", ":=", "svc", ".", "isSecureIndex", "(", "hostname", ")", ";", "!", "secure", "{", "options", ".", "SourceCtx", ".", "DockerInsecureSkipTLSVerify", "=", "types", ".", "NewOptionalBool", "(", "!", "secure", ")", "\n", "}", "\n", "}", "\n", "return", "srcRef", ",", "nil", "\n", "}" ]
// prepareReference creates an image reference from an image string and set options // for the source context
[ "prepareReference", "creates", "an", "image", "reference", "from", "an", "image", "string", "and", "set", "options", "for", "the", "source", "context" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/pkg/storage/image.go#L358-L386
train
cri-o/cri-o
server/container_updateruntimeconfig.go
UpdateRuntimeConfig
func (s *Server) UpdateRuntimeConfig(ctx context.Context, req *pb.UpdateRuntimeConfigRequest) (resp *pb.UpdateRuntimeConfigResponse, err error) { const operation = "update_runtime_config" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() return &pb.UpdateRuntimeConfigResponse{}, nil }
go
func (s *Server) UpdateRuntimeConfig(ctx context.Context, req *pb.UpdateRuntimeConfigRequest) (resp *pb.UpdateRuntimeConfigResponse, err error) { const operation = "update_runtime_config" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() return &pb.UpdateRuntimeConfigResponse{}, nil }
[ "func", "(", "s", "*", "Server", ")", "UpdateRuntimeConfig", "(", "ctx", "context", ".", "Context", ",", "req", "*", "pb", ".", "UpdateRuntimeConfigRequest", ")", "(", "resp", "*", "pb", ".", "UpdateRuntimeConfigResponse", ",", "err", "error", ")", "{", "const", "operation", "=", "\"update_runtime_config\"", "\n", "defer", "func", "(", ")", "{", "recordOperation", "(", "operation", ",", "time", ".", "Now", "(", ")", ")", "\n", "recordError", "(", "operation", ",", "err", ")", "\n", "}", "(", ")", "\n", "return", "&", "pb", ".", "UpdateRuntimeConfigResponse", "{", "}", ",", "nil", "\n", "}" ]
// UpdateRuntimeConfig updates the configuration of a running container.
[ "UpdateRuntimeConfig", "updates", "the", "configuration", "of", "a", "running", "container", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_updateruntimeconfig.go#L11-L19
train
cri-o/cri-o
server/container_attach.go
Attach
func (ss StreamService) Attach(containerID string, inputStream io.Reader, outputStream, errorStream io.WriteCloser, tty bool, resize <-chan remotecommand.TerminalSize) error { c, err := ss.runtimeServer.GetContainerFromShortID(containerID) if err != nil { return fmt.Errorf("could not find container %q: %v", containerID, err) } if err := ss.runtimeServer.Runtime().UpdateContainerStatus(c); err != nil { return err } cState := c.State() if !(cState.Status == oci.ContainerStateRunning || cState.Status == oci.ContainerStateCreated) { return fmt.Errorf("container is not created or running") } return ss.runtimeServer.Runtime().AttachContainer(c, inputStream, outputStream, errorStream, tty, resize) }
go
func (ss StreamService) Attach(containerID string, inputStream io.Reader, outputStream, errorStream io.WriteCloser, tty bool, resize <-chan remotecommand.TerminalSize) error { c, err := ss.runtimeServer.GetContainerFromShortID(containerID) if err != nil { return fmt.Errorf("could not find container %q: %v", containerID, err) } if err := ss.runtimeServer.Runtime().UpdateContainerStatus(c); err != nil { return err } cState := c.State() if !(cState.Status == oci.ContainerStateRunning || cState.Status == oci.ContainerStateCreated) { return fmt.Errorf("container is not created or running") } return ss.runtimeServer.Runtime().AttachContainer(c, inputStream, outputStream, errorStream, tty, resize) }
[ "func", "(", "ss", "StreamService", ")", "Attach", "(", "containerID", "string", ",", "inputStream", "io", ".", "Reader", ",", "outputStream", ",", "errorStream", "io", ".", "WriteCloser", ",", "tty", "bool", ",", "resize", "<-", "chan", "remotecommand", ".", "TerminalSize", ")", "error", "{", "c", ",", "err", ":=", "ss", ".", "runtimeServer", ".", "GetContainerFromShortID", "(", "containerID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"could not find container %q: %v\"", ",", "containerID", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "ss", ".", "runtimeServer", ".", "Runtime", "(", ")", ".", "UpdateContainerStatus", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cState", ":=", "c", ".", "State", "(", ")", "\n", "if", "!", "(", "cState", ".", "Status", "==", "oci", ".", "ContainerStateRunning", "||", "cState", ".", "Status", "==", "oci", ".", "ContainerStateCreated", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"container is not created or running\"", ")", "\n", "}", "\n", "return", "ss", ".", "runtimeServer", ".", "Runtime", "(", ")", ".", "AttachContainer", "(", "c", ",", "inputStream", ",", "outputStream", ",", "errorStream", ",", "tty", ",", "resize", ")", "\n", "}" ]
// Attach endpoint for streaming.Runtime
[ "Attach", "endpoint", "for", "streaming", ".", "Runtime" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_attach.go#L33-L49
train
cri-o/cri-o
server/sandbox_network.go
networkStart
func (s *Server) networkStart(sb *sandbox.Sandbox) (podIP string, result cnitypes.Result, err error) { if sb.HostNetwork() { return s.hostIP, nil, nil } // Ensure network resources are cleaned up if the plugin succeeded // but an error happened between plugin success and the end of networkStart() defer func() { if err != nil { s.networkStop(sb) } }() podNetwork := newPodNetwork(sb) _, err = s.netPlugin.SetUpPod(podNetwork) if err != nil { err = fmt.Errorf("failed to create pod network sandbox %s(%s): %v", sb.Name(), sb.ID(), err) return } tmp, err := s.netPlugin.GetPodNetworkStatus(podNetwork) if err != nil { err = fmt.Errorf("failed to get network status for pod sandbox %s(%s): %v", sb.Name(), sb.ID(), err) return } // only one cnitypes.Result is returned since newPodNetwork sets Networks list empty result = tmp[0] logrus.Debugf("CNI setup result: %v", result) network, err := cnicurrent.GetResult(result) if err != nil { err = fmt.Errorf("failed to get network JSON for pod sandbox %s(%s): %v", sb.Name(), sb.ID(), err) return } podIP = strings.Split(network.IPs[0].Address.String(), "/")[0] if len(sb.PortMappings()) > 0 { ip := net.ParseIP(podIP) if ip == nil { err = fmt.Errorf("failed to get valid ip address for sandbox %s(%s)", sb.Name(), sb.ID()) return } err = s.hostportManager.Add(sb.ID(), &hostport.PodPortMapping{ Name: sb.Name(), PortMappings: sb.PortMappings(), IP: ip, HostNetwork: false, }, "lo") if err != nil { err = fmt.Errorf("failed to add hostport mapping for sandbox %s(%s): %v", sb.Name(), sb.ID(), err) return } } return }
go
func (s *Server) networkStart(sb *sandbox.Sandbox) (podIP string, result cnitypes.Result, err error) { if sb.HostNetwork() { return s.hostIP, nil, nil } // Ensure network resources are cleaned up if the plugin succeeded // but an error happened between plugin success and the end of networkStart() defer func() { if err != nil { s.networkStop(sb) } }() podNetwork := newPodNetwork(sb) _, err = s.netPlugin.SetUpPod(podNetwork) if err != nil { err = fmt.Errorf("failed to create pod network sandbox %s(%s): %v", sb.Name(), sb.ID(), err) return } tmp, err := s.netPlugin.GetPodNetworkStatus(podNetwork) if err != nil { err = fmt.Errorf("failed to get network status for pod sandbox %s(%s): %v", sb.Name(), sb.ID(), err) return } // only one cnitypes.Result is returned since newPodNetwork sets Networks list empty result = tmp[0] logrus.Debugf("CNI setup result: %v", result) network, err := cnicurrent.GetResult(result) if err != nil { err = fmt.Errorf("failed to get network JSON for pod sandbox %s(%s): %v", sb.Name(), sb.ID(), err) return } podIP = strings.Split(network.IPs[0].Address.String(), "/")[0] if len(sb.PortMappings()) > 0 { ip := net.ParseIP(podIP) if ip == nil { err = fmt.Errorf("failed to get valid ip address for sandbox %s(%s)", sb.Name(), sb.ID()) return } err = s.hostportManager.Add(sb.ID(), &hostport.PodPortMapping{ Name: sb.Name(), PortMappings: sb.PortMappings(), IP: ip, HostNetwork: false, }, "lo") if err != nil { err = fmt.Errorf("failed to add hostport mapping for sandbox %s(%s): %v", sb.Name(), sb.ID(), err) return } } return }
[ "func", "(", "s", "*", "Server", ")", "networkStart", "(", "sb", "*", "sandbox", ".", "Sandbox", ")", "(", "podIP", "string", ",", "result", "cnitypes", ".", "Result", ",", "err", "error", ")", "{", "if", "sb", ".", "HostNetwork", "(", ")", "{", "return", "s", ".", "hostIP", ",", "nil", ",", "nil", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", "{", "s", ".", "networkStop", "(", "sb", ")", "\n", "}", "\n", "}", "(", ")", "\n", "podNetwork", ":=", "newPodNetwork", "(", "sb", ")", "\n", "_", ",", "err", "=", "s", ".", "netPlugin", ".", "SetUpPod", "(", "podNetwork", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"failed to create pod network sandbox %s(%s): %v\"", ",", "sb", ".", "Name", "(", ")", ",", "sb", ".", "ID", "(", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "tmp", ",", "err", ":=", "s", ".", "netPlugin", ".", "GetPodNetworkStatus", "(", "podNetwork", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"failed to get network status for pod sandbox %s(%s): %v\"", ",", "sb", ".", "Name", "(", ")", ",", "sb", ".", "ID", "(", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "result", "=", "tmp", "[", "0", "]", "\n", "logrus", ".", "Debugf", "(", "\"CNI setup result: %v\"", ",", "result", ")", "\n", "network", ",", "err", ":=", "cnicurrent", ".", "GetResult", "(", "result", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"failed to get network JSON for pod sandbox %s(%s): %v\"", ",", "sb", ".", "Name", "(", ")", ",", "sb", ".", "ID", "(", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "podIP", "=", "strings", ".", "Split", "(", "network", ".", "IPs", "[", "0", "]", ".", "Address", ".", "String", "(", ")", ",", "\"/\"", ")", "[", "0", "]", "\n", "if", "len", "(", "sb", ".", "PortMappings", "(", ")", ")", ">", "0", "{", "ip", ":=", "net", ".", "ParseIP", "(", "podIP", ")", "\n", "if", "ip", "==", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"failed to get valid ip address for sandbox %s(%s)\"", ",", "sb", ".", "Name", "(", ")", ",", "sb", ".", "ID", "(", ")", ")", "\n", "return", "\n", "}", "\n", "err", "=", "s", ".", "hostportManager", ".", "Add", "(", "sb", ".", "ID", "(", ")", ",", "&", "hostport", ".", "PodPortMapping", "{", "Name", ":", "sb", ".", "Name", "(", ")", ",", "PortMappings", ":", "sb", ".", "PortMappings", "(", ")", ",", "IP", ":", "ip", ",", "HostNetwork", ":", "false", ",", "}", ",", "\"lo\"", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"failed to add hostport mapping for sandbox %s(%s): %v\"", ",", "sb", ".", "Name", "(", ")", ",", "sb", ".", "ID", "(", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// networkStart sets up the sandbox's network and returns the pod IP on success // or an error
[ "networkStart", "sets", "up", "the", "sandbox", "s", "network", "and", "returns", "the", "pod", "IP", "on", "success", "or", "an", "error" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/sandbox_network.go#L17-L75
train
cri-o/cri-o
server/sandbox_network.go
getSandboxIP
func (s *Server) getSandboxIP(sb *sandbox.Sandbox) (string, error) { if sb.HostNetwork() { return s.hostIP, nil } podNetwork := newPodNetwork(sb) result, err := s.netPlugin.GetPodNetworkStatus(podNetwork) if err != nil { return "", fmt.Errorf("failed to get network status for pod sandbox %s(%s): %v", sb.Name(), sb.ID(), err) } res, err := cnicurrent.GetResult(result[0]) if err != nil { return "", fmt.Errorf("failed to get network JSON for pod sandbox %s(%s): %v", sb.Name(), sb.ID(), err) } return strings.Split(res.IPs[0].Address.String(), "/")[0], nil }
go
func (s *Server) getSandboxIP(sb *sandbox.Sandbox) (string, error) { if sb.HostNetwork() { return s.hostIP, nil } podNetwork := newPodNetwork(sb) result, err := s.netPlugin.GetPodNetworkStatus(podNetwork) if err != nil { return "", fmt.Errorf("failed to get network status for pod sandbox %s(%s): %v", sb.Name(), sb.ID(), err) } res, err := cnicurrent.GetResult(result[0]) if err != nil { return "", fmt.Errorf("failed to get network JSON for pod sandbox %s(%s): %v", sb.Name(), sb.ID(), err) } return strings.Split(res.IPs[0].Address.String(), "/")[0], nil }
[ "func", "(", "s", "*", "Server", ")", "getSandboxIP", "(", "sb", "*", "sandbox", ".", "Sandbox", ")", "(", "string", ",", "error", ")", "{", "if", "sb", ".", "HostNetwork", "(", ")", "{", "return", "s", ".", "hostIP", ",", "nil", "\n", "}", "\n", "podNetwork", ":=", "newPodNetwork", "(", "sb", ")", "\n", "result", ",", "err", ":=", "s", ".", "netPlugin", ".", "GetPodNetworkStatus", "(", "podNetwork", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"failed to get network status for pod sandbox %s(%s): %v\"", ",", "sb", ".", "Name", "(", ")", ",", "sb", ".", "ID", "(", ")", ",", "err", ")", "\n", "}", "\n", "res", ",", "err", ":=", "cnicurrent", ".", "GetResult", "(", "result", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"failed to get network JSON for pod sandbox %s(%s): %v\"", ",", "sb", ".", "Name", "(", ")", ",", "sb", ".", "ID", "(", ")", ",", "err", ")", "\n", "}", "\n", "return", "strings", ".", "Split", "(", "res", ".", "IPs", "[", "0", "]", ".", "Address", ".", "String", "(", ")", ",", "\"/\"", ")", "[", "0", "]", ",", "nil", "\n", "}" ]
// getSandboxIP retrieves the IP address for the sandbox
[ "getSandboxIP", "retrieves", "the", "IP", "address", "for", "the", "sandbox" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/sandbox_network.go#L78-L95
train
cri-o/cri-o
server/sandbox_network.go
networkStop
func (s *Server) networkStop(sb *sandbox.Sandbox) { if sb.HostNetwork() { return } if err := s.hostportManager.Remove(sb.ID(), &hostport.PodPortMapping{ Name: sb.Name(), PortMappings: sb.PortMappings(), HostNetwork: false, }); err != nil { logrus.Warnf("failed to remove hostport for pod sandbox %s(%s): %v", sb.Name(), sb.ID(), err) } podNetwork := newPodNetwork(sb) if err := s.netPlugin.TearDownPod(podNetwork); err != nil { logrus.Warnf("failed to destroy network for pod sandbox %s(%s): %v", sb.Name(), sb.ID(), err) } }
go
func (s *Server) networkStop(sb *sandbox.Sandbox) { if sb.HostNetwork() { return } if err := s.hostportManager.Remove(sb.ID(), &hostport.PodPortMapping{ Name: sb.Name(), PortMappings: sb.PortMappings(), HostNetwork: false, }); err != nil { logrus.Warnf("failed to remove hostport for pod sandbox %s(%s): %v", sb.Name(), sb.ID(), err) } podNetwork := newPodNetwork(sb) if err := s.netPlugin.TearDownPod(podNetwork); err != nil { logrus.Warnf("failed to destroy network for pod sandbox %s(%s): %v", sb.Name(), sb.ID(), err) } }
[ "func", "(", "s", "*", "Server", ")", "networkStop", "(", "sb", "*", "sandbox", ".", "Sandbox", ")", "{", "if", "sb", ".", "HostNetwork", "(", ")", "{", "return", "\n", "}", "\n", "if", "err", ":=", "s", ".", "hostportManager", ".", "Remove", "(", "sb", ".", "ID", "(", ")", ",", "&", "hostport", ".", "PodPortMapping", "{", "Name", ":", "sb", ".", "Name", "(", ")", ",", "PortMappings", ":", "sb", ".", "PortMappings", "(", ")", ",", "HostNetwork", ":", "false", ",", "}", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"failed to remove hostport for pod sandbox %s(%s): %v\"", ",", "sb", ".", "Name", "(", ")", ",", "sb", ".", "ID", "(", ")", ",", "err", ")", "\n", "}", "\n", "podNetwork", ":=", "newPodNetwork", "(", "sb", ")", "\n", "if", "err", ":=", "s", ".", "netPlugin", ".", "TearDownPod", "(", "podNetwork", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"failed to destroy network for pod sandbox %s(%s): %v\"", ",", "sb", ".", "Name", "(", ")", ",", "sb", ".", "ID", "(", ")", ",", "err", ")", "\n", "}", "\n", "}" ]
// networkStop cleans up and removes a pod's network. It is best-effort and // must call the network plugin even if the network namespace is already gone
[ "networkStop", "cleans", "up", "and", "removes", "a", "pod", "s", "network", ".", "It", "is", "best", "-", "effort", "and", "must", "call", "the", "network", "plugin", "even", "if", "the", "network", "namespace", "is", "already", "gone" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/sandbox_network.go#L99-L118
train
cri-o/cri-o
server/image_status.go
getUserFromImage
func getUserFromImage(user string) (*int64, string) { // return both empty if user is not specified in the image. if user == "" { return nil, "" } // split instances where the id may contain user:group user = strings.Split(user, ":")[0] // user could be either uid or user name. Try to interpret as numeric uid. uid, err := strconv.ParseInt(user, 10, 64) if err != nil { // If user is non numeric, assume it's user name. return nil, user } // If user is a numeric uid. return &uid, "" }
go
func getUserFromImage(user string) (*int64, string) { // return both empty if user is not specified in the image. if user == "" { return nil, "" } // split instances where the id may contain user:group user = strings.Split(user, ":")[0] // user could be either uid or user name. Try to interpret as numeric uid. uid, err := strconv.ParseInt(user, 10, 64) if err != nil { // If user is non numeric, assume it's user name. return nil, user } // If user is a numeric uid. return &uid, "" }
[ "func", "getUserFromImage", "(", "user", "string", ")", "(", "*", "int64", ",", "string", ")", "{", "if", "user", "==", "\"\"", "{", "return", "nil", ",", "\"\"", "\n", "}", "\n", "user", "=", "strings", ".", "Split", "(", "user", ",", "\":\"", ")", "[", "0", "]", "\n", "uid", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "user", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "user", "\n", "}", "\n", "return", "&", "uid", ",", "\"\"", "\n", "}" ]
// getUserFromImage gets uid or user name of the image user. // If user is numeric, it will be treated as uid; or else, it is treated as user name.
[ "getUserFromImage", "gets", "uid", "or", "user", "name", "of", "the", "image", "user", ".", "If", "user", "is", "numeric", "it", "will", "be", "treated", "as", "uid", ";", "or", "else", "it", "is", "treated", "as", "user", "name", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/image_status.go#L94-L109
train
cri-o/cri-o
server/container_reopen_log.go
ReopenContainerLog
func (s *Server) ReopenContainerLog(ctx context.Context, req *pb.ReopenContainerLogRequest) (resp *pb.ReopenContainerLogResponse, err error) { const operation = "container_reopen_log" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() logrus.Debugf("ReopenContainerLogRequest %+v", req) containerID := req.ContainerId c := s.GetContainer(containerID) if c == nil { return nil, fmt.Errorf("could not find container %q", containerID) } if err := s.ContainerServer.Runtime().UpdateContainerStatus(c); err != nil { return nil, err } cState := c.State() if !(cState.Status == oci.ContainerStateRunning || cState.Status == oci.ContainerStateCreated) { return nil, fmt.Errorf("container is not created or running") } err = s.ContainerServer.Runtime().ReopenContainerLog(c) if err == nil { resp = &pb.ReopenContainerLogResponse{} } logrus.Debugf("ReopenContainerLogResponse %s: %+v", containerID, resp) return resp, err }
go
func (s *Server) ReopenContainerLog(ctx context.Context, req *pb.ReopenContainerLogRequest) (resp *pb.ReopenContainerLogResponse, err error) { const operation = "container_reopen_log" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() logrus.Debugf("ReopenContainerLogRequest %+v", req) containerID := req.ContainerId c := s.GetContainer(containerID) if c == nil { return nil, fmt.Errorf("could not find container %q", containerID) } if err := s.ContainerServer.Runtime().UpdateContainerStatus(c); err != nil { return nil, err } cState := c.State() if !(cState.Status == oci.ContainerStateRunning || cState.Status == oci.ContainerStateCreated) { return nil, fmt.Errorf("container is not created or running") } err = s.ContainerServer.Runtime().ReopenContainerLog(c) if err == nil { resp = &pb.ReopenContainerLogResponse{} } logrus.Debugf("ReopenContainerLogResponse %s: %+v", containerID, resp) return resp, err }
[ "func", "(", "s", "*", "Server", ")", "ReopenContainerLog", "(", "ctx", "context", ".", "Context", ",", "req", "*", "pb", ".", "ReopenContainerLogRequest", ")", "(", "resp", "*", "pb", ".", "ReopenContainerLogResponse", ",", "err", "error", ")", "{", "const", "operation", "=", "\"container_reopen_log\"", "\n", "defer", "func", "(", ")", "{", "recordOperation", "(", "operation", ",", "time", ".", "Now", "(", ")", ")", "\n", "recordError", "(", "operation", ",", "err", ")", "\n", "}", "(", ")", "\n", "logrus", ".", "Debugf", "(", "\"ReopenContainerLogRequest %+v\"", ",", "req", ")", "\n", "containerID", ":=", "req", ".", "ContainerId", "\n", "c", ":=", "s", ".", "GetContainer", "(", "containerID", ")", "\n", "if", "c", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"could not find container %q\"", ",", "containerID", ")", "\n", "}", "\n", "if", "err", ":=", "s", ".", "ContainerServer", ".", "Runtime", "(", ")", ".", "UpdateContainerStatus", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "cState", ":=", "c", ".", "State", "(", ")", "\n", "if", "!", "(", "cState", ".", "Status", "==", "oci", ".", "ContainerStateRunning", "||", "cState", ".", "Status", "==", "oci", ".", "ContainerStateCreated", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"container is not created or running\"", ")", "\n", "}", "\n", "err", "=", "s", ".", "ContainerServer", ".", "Runtime", "(", ")", ".", "ReopenContainerLog", "(", "c", ")", "\n", "if", "err", "==", "nil", "{", "resp", "=", "&", "pb", ".", "ReopenContainerLogResponse", "{", "}", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"ReopenContainerLogResponse %s: %+v\"", ",", "containerID", ",", "resp", ")", "\n", "return", "resp", ",", "err", "\n", "}" ]
// ReopenContainerLog reopens the containers log file
[ "ReopenContainerLog", "reopens", "the", "containers", "log", "file" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_reopen_log.go#L14-L45
train
cri-o/cri-o
server/sandbox_list.go
filterSandbox
func filterSandbox(p *pb.PodSandbox, filter *pb.PodSandboxFilter) bool { if filter != nil { if filter.State != nil { if p.State != filter.State.State { return false } } if filter.LabelSelector != nil { sel := fields.SelectorFromSet(filter.LabelSelector) if !sel.Matches(fields.Set(p.Labels)) { return false } } } return true }
go
func filterSandbox(p *pb.PodSandbox, filter *pb.PodSandboxFilter) bool { if filter != nil { if filter.State != nil { if p.State != filter.State.State { return false } } if filter.LabelSelector != nil { sel := fields.SelectorFromSet(filter.LabelSelector) if !sel.Matches(fields.Set(p.Labels)) { return false } } } return true }
[ "func", "filterSandbox", "(", "p", "*", "pb", ".", "PodSandbox", ",", "filter", "*", "pb", ".", "PodSandboxFilter", ")", "bool", "{", "if", "filter", "!=", "nil", "{", "if", "filter", ".", "State", "!=", "nil", "{", "if", "p", ".", "State", "!=", "filter", ".", "State", ".", "State", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "filter", ".", "LabelSelector", "!=", "nil", "{", "sel", ":=", "fields", ".", "SelectorFromSet", "(", "filter", ".", "LabelSelector", ")", "\n", "if", "!", "sel", ".", "Matches", "(", "fields", ".", "Set", "(", "p", ".", "Labels", ")", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// filterSandbox returns whether passed container matches filtering criteria
[ "filterSandbox", "returns", "whether", "passed", "container", "matches", "filtering", "criteria" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/sandbox_list.go#L15-L30
train
cri-o/cri-o
server/sandbox_list.go
ListPodSandbox
func (s *Server) ListPodSandbox(ctx context.Context, req *pb.ListPodSandboxRequest) (resp *pb.ListPodSandboxResponse, err error) { const operation = "list_pod_sandbox" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() logrus.Debugf("ListPodSandboxRequest %+v", req) var pods []*pb.PodSandbox var podList []*sandbox.Sandbox podList = append(podList, s.ContainerServer.ListSandboxes()...) filter := req.Filter // Filter by pod id first. if filter != nil { if filter.Id != "" { id, err := s.PodIDIndex().Get(filter.Id) if err != nil { // Not finding an ID in a filtered list should not be considered // and error; it might have been deleted when stop was done. // Log and return an empty struct. logrus.Warnf("unable to find pod %s with filter", filter.Id) return &pb.ListPodSandboxResponse{}, nil } sb := s.getSandbox(id) if sb == nil { podList = []*sandbox.Sandbox{} } else { podList = []*sandbox.Sandbox{sb} } } } for _, sb := range podList { // Skip sandboxes that aren't created yet if !sb.Created() { continue } podInfraContainer := sb.InfraContainer() if podInfraContainer == nil { // this can't really happen, but if it does because of a bug // it's better not to panic continue } cState := podInfraContainer.StateNoLock() rStatus := pb.PodSandboxState_SANDBOX_NOTREADY if cState.Status == oci.ContainerStateRunning { rStatus = pb.PodSandboxState_SANDBOX_READY } pod := &pb.PodSandbox{ Id: sb.ID(), CreatedAt: podInfraContainer.CreatedAt().UnixNano(), State: rStatus, Labels: sb.Labels(), Annotations: sb.Annotations(), Metadata: sb.Metadata(), } // Filter by other criteria such as state and labels. if filterSandbox(pod, req.Filter) { pods = append(pods, pod) } } resp = &pb.ListPodSandboxResponse{ Items: pods, } logrus.Debugf("ListPodSandboxResponse %+v", resp) return resp, nil }
go
func (s *Server) ListPodSandbox(ctx context.Context, req *pb.ListPodSandboxRequest) (resp *pb.ListPodSandboxResponse, err error) { const operation = "list_pod_sandbox" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() logrus.Debugf("ListPodSandboxRequest %+v", req) var pods []*pb.PodSandbox var podList []*sandbox.Sandbox podList = append(podList, s.ContainerServer.ListSandboxes()...) filter := req.Filter // Filter by pod id first. if filter != nil { if filter.Id != "" { id, err := s.PodIDIndex().Get(filter.Id) if err != nil { // Not finding an ID in a filtered list should not be considered // and error; it might have been deleted when stop was done. // Log and return an empty struct. logrus.Warnf("unable to find pod %s with filter", filter.Id) return &pb.ListPodSandboxResponse{}, nil } sb := s.getSandbox(id) if sb == nil { podList = []*sandbox.Sandbox{} } else { podList = []*sandbox.Sandbox{sb} } } } for _, sb := range podList { // Skip sandboxes that aren't created yet if !sb.Created() { continue } podInfraContainer := sb.InfraContainer() if podInfraContainer == nil { // this can't really happen, but if it does because of a bug // it's better not to panic continue } cState := podInfraContainer.StateNoLock() rStatus := pb.PodSandboxState_SANDBOX_NOTREADY if cState.Status == oci.ContainerStateRunning { rStatus = pb.PodSandboxState_SANDBOX_READY } pod := &pb.PodSandbox{ Id: sb.ID(), CreatedAt: podInfraContainer.CreatedAt().UnixNano(), State: rStatus, Labels: sb.Labels(), Annotations: sb.Annotations(), Metadata: sb.Metadata(), } // Filter by other criteria such as state and labels. if filterSandbox(pod, req.Filter) { pods = append(pods, pod) } } resp = &pb.ListPodSandboxResponse{ Items: pods, } logrus.Debugf("ListPodSandboxResponse %+v", resp) return resp, nil }
[ "func", "(", "s", "*", "Server", ")", "ListPodSandbox", "(", "ctx", "context", ".", "Context", ",", "req", "*", "pb", ".", "ListPodSandboxRequest", ")", "(", "resp", "*", "pb", ".", "ListPodSandboxResponse", ",", "err", "error", ")", "{", "const", "operation", "=", "\"list_pod_sandbox\"", "\n", "defer", "func", "(", ")", "{", "recordOperation", "(", "operation", ",", "time", ".", "Now", "(", ")", ")", "\n", "recordError", "(", "operation", ",", "err", ")", "\n", "}", "(", ")", "\n", "logrus", ".", "Debugf", "(", "\"ListPodSandboxRequest %+v\"", ",", "req", ")", "\n", "var", "pods", "[", "]", "*", "pb", ".", "PodSandbox", "\n", "var", "podList", "[", "]", "*", "sandbox", ".", "Sandbox", "\n", "podList", "=", "append", "(", "podList", ",", "s", ".", "ContainerServer", ".", "ListSandboxes", "(", ")", "...", ")", "\n", "filter", ":=", "req", ".", "Filter", "\n", "if", "filter", "!=", "nil", "{", "if", "filter", ".", "Id", "!=", "\"\"", "{", "id", ",", "err", ":=", "s", ".", "PodIDIndex", "(", ")", ".", "Get", "(", "filter", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warnf", "(", "\"unable to find pod %s with filter\"", ",", "filter", ".", "Id", ")", "\n", "return", "&", "pb", ".", "ListPodSandboxResponse", "{", "}", ",", "nil", "\n", "}", "\n", "sb", ":=", "s", ".", "getSandbox", "(", "id", ")", "\n", "if", "sb", "==", "nil", "{", "podList", "=", "[", "]", "*", "sandbox", ".", "Sandbox", "{", "}", "\n", "}", "else", "{", "podList", "=", "[", "]", "*", "sandbox", ".", "Sandbox", "{", "sb", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "_", ",", "sb", ":=", "range", "podList", "{", "if", "!", "sb", ".", "Created", "(", ")", "{", "continue", "\n", "}", "\n", "podInfraContainer", ":=", "sb", ".", "InfraContainer", "(", ")", "\n", "if", "podInfraContainer", "==", "nil", "{", "continue", "\n", "}", "\n", "cState", ":=", "podInfraContainer", ".", "StateNoLock", "(", ")", "\n", "rStatus", ":=", "pb", ".", "PodSandboxState_SANDBOX_NOTREADY", "\n", "if", "cState", ".", "Status", "==", "oci", ".", "ContainerStateRunning", "{", "rStatus", "=", "pb", ".", "PodSandboxState_SANDBOX_READY", "\n", "}", "\n", "pod", ":=", "&", "pb", ".", "PodSandbox", "{", "Id", ":", "sb", ".", "ID", "(", ")", ",", "CreatedAt", ":", "podInfraContainer", ".", "CreatedAt", "(", ")", ".", "UnixNano", "(", ")", ",", "State", ":", "rStatus", ",", "Labels", ":", "sb", ".", "Labels", "(", ")", ",", "Annotations", ":", "sb", ".", "Annotations", "(", ")", ",", "Metadata", ":", "sb", ".", "Metadata", "(", ")", ",", "}", "\n", "if", "filterSandbox", "(", "pod", ",", "req", ".", "Filter", ")", "{", "pods", "=", "append", "(", "pods", ",", "pod", ")", "\n", "}", "\n", "}", "\n", "resp", "=", "&", "pb", ".", "ListPodSandboxResponse", "{", "Items", ":", "pods", ",", "}", "\n", "logrus", ".", "Debugf", "(", "\"ListPodSandboxResponse %+v\"", ",", "resp", ")", "\n", "return", "resp", ",", "nil", "\n", "}" ]
// ListPodSandbox returns a list of SandBoxes.
[ "ListPodSandbox", "returns", "a", "list", "of", "SandBoxes", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/sandbox_list.go#L33-L103
train
cri-o/cri-o
server/container_remove.go
RemoveContainer
func (s *Server) RemoveContainer(ctx context.Context, req *pb.RemoveContainerRequest) (resp *pb.RemoveContainerResponse, err error) { const operation = "remove_container" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() logrus.Debugf("RemoveContainerRequest: %+v", req) // save container description to print c, err := s.GetContainerFromShortID(req.ContainerId) if err != nil { return nil, err } _, err = s.ContainerServer.Remove(ctx, req.ContainerId, true) if err != nil { return nil, err } logrus.Infof("Removed container %s", c.Description()) resp = &pb.RemoveContainerResponse{} logrus.Debugf("RemoveContainerResponse: %+v", resp) return resp, nil }
go
func (s *Server) RemoveContainer(ctx context.Context, req *pb.RemoveContainerRequest) (resp *pb.RemoveContainerResponse, err error) { const operation = "remove_container" defer func() { recordOperation(operation, time.Now()) recordError(operation, err) }() logrus.Debugf("RemoveContainerRequest: %+v", req) // save container description to print c, err := s.GetContainerFromShortID(req.ContainerId) if err != nil { return nil, err } _, err = s.ContainerServer.Remove(ctx, req.ContainerId, true) if err != nil { return nil, err } logrus.Infof("Removed container %s", c.Description()) resp = &pb.RemoveContainerResponse{} logrus.Debugf("RemoveContainerResponse: %+v", resp) return resp, nil }
[ "func", "(", "s", "*", "Server", ")", "RemoveContainer", "(", "ctx", "context", ".", "Context", ",", "req", "*", "pb", ".", "RemoveContainerRequest", ")", "(", "resp", "*", "pb", ".", "RemoveContainerResponse", ",", "err", "error", ")", "{", "const", "operation", "=", "\"remove_container\"", "\n", "defer", "func", "(", ")", "{", "recordOperation", "(", "operation", ",", "time", ".", "Now", "(", ")", ")", "\n", "recordError", "(", "operation", ",", "err", ")", "\n", "}", "(", ")", "\n", "logrus", ".", "Debugf", "(", "\"RemoveContainerRequest: %+v\"", ",", "req", ")", "\n", "c", ",", "err", ":=", "s", ".", "GetContainerFromShortID", "(", "req", ".", "ContainerId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "_", ",", "err", "=", "s", ".", "ContainerServer", ".", "Remove", "(", "ctx", ",", "req", ".", "ContainerId", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "logrus", ".", "Infof", "(", "\"Removed container %s\"", ",", "c", ".", "Description", "(", ")", ")", "\n", "resp", "=", "&", "pb", ".", "RemoveContainerResponse", "{", "}", "\n", "logrus", ".", "Debugf", "(", "\"RemoveContainerResponse: %+v\"", ",", "resp", ")", "\n", "return", "resp", ",", "nil", "\n", "}" ]
// RemoveContainer removes the container. If the container is running, the container // should be force removed.
[ "RemoveContainer", "removes", "the", "container", ".", "If", "the", "container", "is", "running", "the", "container", "should", "be", "force", "removed", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/container_remove.go#L13-L36
train
cri-o/cri-o
utils/ioutil/read_closer.go
Close
func (w *wrapReadCloser) Close() error { w.reader.Close() w.writer.Close() return nil }
go
func (w *wrapReadCloser) Close() error { w.reader.Close() w.writer.Close() return nil }
[ "func", "(", "w", "*", "wrapReadCloser", ")", "Close", "(", ")", "error", "{", "w", ".", "reader", ".", "Close", "(", ")", "\n", "w", ".", "writer", ".", "Close", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Close closes read closer.
[ "Close", "closes", "read", "closer", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/ioutil/read_closer.go#L53-L57
train
cri-o/cri-o
server/config.go
Validate
func (c *Config) Validate(onExecution bool) error { switch c.ImageVolumes { case lib.ImageVolumesMkdir: case lib.ImageVolumesIgnore: case lib.ImageVolumesBind: default: return fmt.Errorf("unrecognized image volume type specified") } if err := c.Config.Validate(onExecution); err != nil { return errors.Wrapf(err, "library config validation") } if c.UIDMappings != "" && c.ManageNetworkNSLifecycle { return fmt.Errorf("cannot use UIDMappings with ManageNetworkNSLifecycle") } if c.GIDMappings != "" && c.ManageNetworkNSLifecycle { return fmt.Errorf("cannot use GIDMappings with ManageNetworkNSLifecycle") } if c.LogSizeMax >= 0 && c.LogSizeMax < oci.BufSize { return fmt.Errorf("log size max should be negative or >= %d", oci.BufSize) } return nil }
go
func (c *Config) Validate(onExecution bool) error { switch c.ImageVolumes { case lib.ImageVolumesMkdir: case lib.ImageVolumesIgnore: case lib.ImageVolumesBind: default: return fmt.Errorf("unrecognized image volume type specified") } if err := c.Config.Validate(onExecution); err != nil { return errors.Wrapf(err, "library config validation") } if c.UIDMappings != "" && c.ManageNetworkNSLifecycle { return fmt.Errorf("cannot use UIDMappings with ManageNetworkNSLifecycle") } if c.GIDMappings != "" && c.ManageNetworkNSLifecycle { return fmt.Errorf("cannot use GIDMappings with ManageNetworkNSLifecycle") } if c.LogSizeMax >= 0 && c.LogSizeMax < oci.BufSize { return fmt.Errorf("log size max should be negative or >= %d", oci.BufSize) } return nil }
[ "func", "(", "c", "*", "Config", ")", "Validate", "(", "onExecution", "bool", ")", "error", "{", "switch", "c", ".", "ImageVolumes", "{", "case", "lib", ".", "ImageVolumesMkdir", ":", "case", "lib", ".", "ImageVolumesIgnore", ":", "case", "lib", ".", "ImageVolumesBind", ":", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"unrecognized image volume type specified\"", ")", "\n", "}", "\n", "if", "err", ":=", "c", ".", "Config", ".", "Validate", "(", "onExecution", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"library config validation\"", ")", "\n", "}", "\n", "if", "c", ".", "UIDMappings", "!=", "\"\"", "&&", "c", ".", "ManageNetworkNSLifecycle", "{", "return", "fmt", ".", "Errorf", "(", "\"cannot use UIDMappings with ManageNetworkNSLifecycle\"", ")", "\n", "}", "\n", "if", "c", ".", "GIDMappings", "!=", "\"\"", "&&", "c", ".", "ManageNetworkNSLifecycle", "{", "return", "fmt", ".", "Errorf", "(", "\"cannot use GIDMappings with ManageNetworkNSLifecycle\"", ")", "\n", "}", "\n", "if", "c", ".", "LogSizeMax", ">=", "0", "&&", "c", ".", "LogSizeMax", "<", "oci", ".", "BufSize", "{", "return", "fmt", ".", "Errorf", "(", "\"log size max should be negative or >= %d\"", ",", "oci", ".", "BufSize", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate is the main entry point for configuration validation // The parameter `onExecution` specifies if the validation should include // execution checks. It returns an `error` on validation failure, otherwise // `nil`.
[ "Validate", "is", "the", "main", "entry", "point", "for", "configuration", "validation", "The", "parameter", "onExecution", "specifies", "if", "the", "validation", "should", "include", "execution", "checks", ".", "It", "returns", "an", "error", "on", "validation", "failure", "otherwise", "nil", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/server/config.go#L167-L192
train
cri-o/cri-o
oci/runtime_oci.go
newRuntimeOCI
func newRuntimeOCI(r *Runtime, handler *RuntimeHandler) RuntimeImpl { return &runtimeOCI{ Runtime: r, path: handler.RuntimePath, root: handler.RuntimeRoot, } }
go
func newRuntimeOCI(r *Runtime, handler *RuntimeHandler) RuntimeImpl { return &runtimeOCI{ Runtime: r, path: handler.RuntimePath, root: handler.RuntimeRoot, } }
[ "func", "newRuntimeOCI", "(", "r", "*", "Runtime", ",", "handler", "*", "RuntimeHandler", ")", "RuntimeImpl", "{", "return", "&", "runtimeOCI", "{", "Runtime", ":", "r", ",", "path", ":", "handler", ".", "RuntimePath", ",", "root", ":", "handler", ".", "RuntimeRoot", ",", "}", "\n", "}" ]
// newRuntimeOCI creates a new runtimeOCI instance
[ "newRuntimeOCI", "creates", "a", "new", "runtimeOCI", "instance" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/runtime_oci.go#L49-L55
train
cri-o/cri-o
lib/sandbox/history.go
Less
func (history *History) Less(i, j int) bool { sandboxes := *history // FIXME: state access should be serialized return sandboxes[j].createdAt.Before(sandboxes[i].createdAt) }
go
func (history *History) Less(i, j int) bool { sandboxes := *history // FIXME: state access should be serialized return sandboxes[j].createdAt.Before(sandboxes[i].createdAt) }
[ "func", "(", "history", "*", "History", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "sandboxes", ":=", "*", "history", "\n", "return", "sandboxes", "[", "j", "]", ".", "createdAt", ".", "Before", "(", "sandboxes", "[", "i", "]", ".", "createdAt", ")", "\n", "}" ]
// Less compares two sandboxes and returns true if the second one // was created before the first one.
[ "Less", "compares", "two", "sandboxes", "and", "returns", "true", "if", "the", "second", "one", "was", "created", "before", "the", "first", "one", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/history.go#L16-L20
train
cri-o/cri-o
lib/sandbox/history.go
Swap
func (history *History) Swap(i, j int) { sandboxes := *history sandboxes[i], sandboxes[j] = sandboxes[j], sandboxes[i] }
go
func (history *History) Swap(i, j int) { sandboxes := *history sandboxes[i], sandboxes[j] = sandboxes[j], sandboxes[i] }
[ "func", "(", "history", "*", "History", ")", "Swap", "(", "i", ",", "j", "int", ")", "{", "sandboxes", ":=", "*", "history", "\n", "sandboxes", "[", "i", "]", ",", "sandboxes", "[", "j", "]", "=", "sandboxes", "[", "j", "]", ",", "sandboxes", "[", "i", "]", "\n", "}" ]
// Swap switches sandboxes i and j positions in the history.
[ "Swap", "switches", "sandboxes", "i", "and", "j", "positions", "in", "the", "history", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/lib/sandbox/history.go#L23-L26
train
cri-o/cri-o
utils/io/exec_io.go
NewExecIO
func NewExecIO(id, root string, tty, stdin bool) (*ExecIO, error) { fifos, err := newFifos(root, id, tty, stdin) if err != nil { return nil, err } stdio, closer, err := newStdioPipes(fifos) if err != nil { return nil, err } return &ExecIO{ id: id, fifos: fifos, stdioPipes: stdio, closer: closer, }, nil }
go
func NewExecIO(id, root string, tty, stdin bool) (*ExecIO, error) { fifos, err := newFifos(root, id, tty, stdin) if err != nil { return nil, err } stdio, closer, err := newStdioPipes(fifos) if err != nil { return nil, err } return &ExecIO{ id: id, fifos: fifos, stdioPipes: stdio, closer: closer, }, nil }
[ "func", "NewExecIO", "(", "id", ",", "root", "string", ",", "tty", ",", "stdin", "bool", ")", "(", "*", "ExecIO", ",", "error", ")", "{", "fifos", ",", "err", ":=", "newFifos", "(", "root", ",", "id", ",", "tty", ",", "stdin", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "stdio", ",", "closer", ",", "err", ":=", "newStdioPipes", "(", "fifos", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "ExecIO", "{", "id", ":", "id", ",", "fifos", ":", "fifos", ",", "stdioPipes", ":", "stdio", ",", "closer", ":", "closer", ",", "}", ",", "nil", "\n", "}" ]
// NewExecIO creates exec io.
[ "NewExecIO", "creates", "exec", "io", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/io/exec_io.go#L40-L55
train
cri-o/cri-o
utils/io/exec_io.go
Attach
func (e *ExecIO) Attach(opts AttachOptions) <-chan struct{} { var wg sync.WaitGroup var stdinStreamRC io.ReadCloser if e.stdin != nil && opts.Stdin != nil { stdinStreamRC = cioutil.NewWrapReadCloser(opts.Stdin) wg.Add(1) go func() { if _, err := io.Copy(e.stdin, stdinStreamRC); err != nil { logrus.WithError(err).Errorf("Failed to redirect stdin for container exec %q", e.id) } logrus.Infof("Container exec %q stdin closed", e.id) if opts.StdinOnce && !opts.Tty { e.stdin.Close() if err := opts.CloseStdin(); err != nil { logrus.WithError(err).Errorf("Failed to close stdin for container exec %q", e.id) } } else { if e.stdout != nil { e.stdout.Close() } if e.stderr != nil { e.stderr.Close() } } wg.Done() }() } attachOutput := func(t StreamType, stream io.WriteCloser, out io.ReadCloser) { if _, err := io.Copy(stream, out); err != nil { logrus.WithError(err).Errorf("Failed to pipe %q for container exec %q", t, e.id) } out.Close() stream.Close() if stdinStreamRC != nil { stdinStreamRC.Close() } e.closer.wg.Done() wg.Done() logrus.Infof("Finish piping %q of container exec %q", t, e.id) } if opts.Stdout != nil { wg.Add(1) // Closer should wait for this routine to be over. e.closer.wg.Add(1) go attachOutput(Stdout, opts.Stdout, e.stdout) } if !opts.Tty && opts.Stderr != nil { wg.Add(1) // Closer should wait for this routine to be over. e.closer.wg.Add(1) go attachOutput(Stderr, opts.Stderr, e.stderr) } done := make(chan struct{}) go func() { wg.Wait() close(done) }() return done }
go
func (e *ExecIO) Attach(opts AttachOptions) <-chan struct{} { var wg sync.WaitGroup var stdinStreamRC io.ReadCloser if e.stdin != nil && opts.Stdin != nil { stdinStreamRC = cioutil.NewWrapReadCloser(opts.Stdin) wg.Add(1) go func() { if _, err := io.Copy(e.stdin, stdinStreamRC); err != nil { logrus.WithError(err).Errorf("Failed to redirect stdin for container exec %q", e.id) } logrus.Infof("Container exec %q stdin closed", e.id) if opts.StdinOnce && !opts.Tty { e.stdin.Close() if err := opts.CloseStdin(); err != nil { logrus.WithError(err).Errorf("Failed to close stdin for container exec %q", e.id) } } else { if e.stdout != nil { e.stdout.Close() } if e.stderr != nil { e.stderr.Close() } } wg.Done() }() } attachOutput := func(t StreamType, stream io.WriteCloser, out io.ReadCloser) { if _, err := io.Copy(stream, out); err != nil { logrus.WithError(err).Errorf("Failed to pipe %q for container exec %q", t, e.id) } out.Close() stream.Close() if stdinStreamRC != nil { stdinStreamRC.Close() } e.closer.wg.Done() wg.Done() logrus.Infof("Finish piping %q of container exec %q", t, e.id) } if opts.Stdout != nil { wg.Add(1) // Closer should wait for this routine to be over. e.closer.wg.Add(1) go attachOutput(Stdout, opts.Stdout, e.stdout) } if !opts.Tty && opts.Stderr != nil { wg.Add(1) // Closer should wait for this routine to be over. e.closer.wg.Add(1) go attachOutput(Stderr, opts.Stderr, e.stderr) } done := make(chan struct{}) go func() { wg.Wait() close(done) }() return done }
[ "func", "(", "e", "*", "ExecIO", ")", "Attach", "(", "opts", "AttachOptions", ")", "<-", "chan", "struct", "{", "}", "{", "var", "wg", "sync", ".", "WaitGroup", "\n", "var", "stdinStreamRC", "io", ".", "ReadCloser", "\n", "if", "e", ".", "stdin", "!=", "nil", "&&", "opts", ".", "Stdin", "!=", "nil", "{", "stdinStreamRC", "=", "cioutil", ".", "NewWrapReadCloser", "(", "opts", ".", "Stdin", ")", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "e", ".", "stdin", ",", "stdinStreamRC", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"Failed to redirect stdin for container exec %q\"", ",", "e", ".", "id", ")", "\n", "}", "\n", "logrus", ".", "Infof", "(", "\"Container exec %q stdin closed\"", ",", "e", ".", "id", ")", "\n", "if", "opts", ".", "StdinOnce", "&&", "!", "opts", ".", "Tty", "{", "e", ".", "stdin", ".", "Close", "(", ")", "\n", "if", "err", ":=", "opts", ".", "CloseStdin", "(", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"Failed to close stdin for container exec %q\"", ",", "e", ".", "id", ")", "\n", "}", "\n", "}", "else", "{", "if", "e", ".", "stdout", "!=", "nil", "{", "e", ".", "stdout", ".", "Close", "(", ")", "\n", "}", "\n", "if", "e", ".", "stderr", "!=", "nil", "{", "e", ".", "stderr", ".", "Close", "(", ")", "\n", "}", "\n", "}", "\n", "wg", ".", "Done", "(", ")", "\n", "}", "(", ")", "\n", "}", "\n", "attachOutput", ":=", "func", "(", "t", "StreamType", ",", "stream", "io", ".", "WriteCloser", ",", "out", "io", ".", "ReadCloser", ")", "{", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "stream", ",", "out", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "\"Failed to pipe %q for container exec %q\"", ",", "t", ",", "e", ".", "id", ")", "\n", "}", "\n", "out", ".", "Close", "(", ")", "\n", "stream", ".", "Close", "(", ")", "\n", "if", "stdinStreamRC", "!=", "nil", "{", "stdinStreamRC", ".", "Close", "(", ")", "\n", "}", "\n", "e", ".", "closer", ".", "wg", ".", "Done", "(", ")", "\n", "wg", ".", "Done", "(", ")", "\n", "logrus", ".", "Infof", "(", "\"Finish piping %q of container exec %q\"", ",", "t", ",", "e", ".", "id", ")", "\n", "}", "\n", "if", "opts", ".", "Stdout", "!=", "nil", "{", "wg", ".", "Add", "(", "1", ")", "\n", "e", ".", "closer", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "attachOutput", "(", "Stdout", ",", "opts", ".", "Stdout", ",", "e", ".", "stdout", ")", "\n", "}", "\n", "if", "!", "opts", ".", "Tty", "&&", "opts", ".", "Stderr", "!=", "nil", "{", "wg", ".", "Add", "(", "1", ")", "\n", "e", ".", "closer", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "attachOutput", "(", "Stderr", ",", "opts", ".", "Stderr", ",", "e", ".", "stderr", ")", "\n", "}", "\n", "done", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "wg", ".", "Wait", "(", ")", "\n", "close", "(", "done", ")", "\n", "}", "(", ")", "\n", "return", "done", "\n", "}" ]
// Attach attaches exec stdio. The logic is similar with container io attach.
[ "Attach", "attaches", "exec", "stdio", ".", "The", "logic", "is", "similar", "with", "container", "io", "attach", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/io/exec_io.go#L63-L125
train
cri-o/cri-o
oci/stats.go
getContainerNetIO
func getContainerNetIO(stats *libcontainer.Stats) (received uint64, transmitted uint64) { for _, iface := range stats.Interfaces { received += iface.RxBytes transmitted += iface.TxBytes } return }
go
func getContainerNetIO(stats *libcontainer.Stats) (received uint64, transmitted uint64) { for _, iface := range stats.Interfaces { received += iface.RxBytes transmitted += iface.TxBytes } return }
[ "func", "getContainerNetIO", "(", "stats", "*", "libcontainer", ".", "Stats", ")", "(", "received", "uint64", ",", "transmitted", "uint64", ")", "{", "for", "_", ",", "iface", ":=", "range", "stats", ".", "Interfaces", "{", "received", "+=", "iface", ".", "RxBytes", "\n", "transmitted", "+=", "iface", ".", "TxBytes", "\n", "}", "\n", "return", "\n", "}" ]
// Returns the total number of bytes transmitted and received for the given container stats
[ "Returns", "the", "total", "number", "of", "bytes", "transmitted", "and", "received", "for", "the", "given", "container", "stats" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/stats.go#L27-L33
train
cri-o/cri-o
oci/stats.go
getMemLimit
func getMemLimit(cgroupLimit uint64) uint64 { si := &syscall.Sysinfo_t{} err := syscall.Sysinfo(si) if err != nil { return cgroupLimit } physicalLimit := si.Totalram if cgroupLimit > physicalLimit { return physicalLimit } return cgroupLimit }
go
func getMemLimit(cgroupLimit uint64) uint64 { si := &syscall.Sysinfo_t{} err := syscall.Sysinfo(si) if err != nil { return cgroupLimit } physicalLimit := si.Totalram if cgroupLimit > physicalLimit { return physicalLimit } return cgroupLimit }
[ "func", "getMemLimit", "(", "cgroupLimit", "uint64", ")", "uint64", "{", "si", ":=", "&", "syscall", ".", "Sysinfo_t", "{", "}", "\n", "err", ":=", "syscall", ".", "Sysinfo", "(", "si", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cgroupLimit", "\n", "}", "\n", "physicalLimit", ":=", "si", ".", "Totalram", "\n", "if", "cgroupLimit", ">", "physicalLimit", "{", "return", "physicalLimit", "\n", "}", "\n", "return", "cgroupLimit", "\n", "}" ]
// getMemory limit returns the memory limit for a given cgroup // If the configured memory limit is larger than the total memory on the sys, the // physical system memory size is returned
[ "getMemory", "limit", "returns", "the", "memory", "limit", "for", "a", "given", "cgroup", "If", "the", "configured", "memory", "limit", "is", "larger", "than", "the", "total", "memory", "on", "the", "sys", "the", "physical", "system", "memory", "size", "is", "returned" ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/oci/stats.go#L50-L62
train
cri-o/cri-o
utils/io/container_io.go
streamKey
func streamKey(id, name string, stream StreamType) string { return strings.Join([]string{id, name, string(stream)}, "-") }
go
func streamKey(id, name string, stream StreamType) string { return strings.Join([]string{id, name, string(stream)}, "-") }
[ "func", "streamKey", "(", "id", ",", "name", "string", ",", "stream", "StreamType", ")", "string", "{", "return", "strings", ".", "Join", "(", "[", "]", "string", "{", "id", ",", "name", ",", "string", "(", "stream", ")", "}", ",", "\"-\"", ")", "\n", "}" ]
// streamKey generates a key for the stream.
[ "streamKey", "generates", "a", "key", "for", "the", "stream", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/io/container_io.go#L33-L35
train
cri-o/cri-o
utils/io/container_io.go
WithFIFOs
func WithFIFOs(fifos *cio.FIFOSet) ContainerIOOpts { return func(c *ContainerIO) error { c.fifos = fifos return nil } }
go
func WithFIFOs(fifos *cio.FIFOSet) ContainerIOOpts { return func(c *ContainerIO) error { c.fifos = fifos return nil } }
[ "func", "WithFIFOs", "(", "fifos", "*", "cio", ".", "FIFOSet", ")", "ContainerIOOpts", "{", "return", "func", "(", "c", "*", "ContainerIO", ")", "error", "{", "c", ".", "fifos", "=", "fifos", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithFIFOs specifies existing fifos for the container io.
[ "WithFIFOs", "specifies", "existing", "fifos", "for", "the", "container", "io", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/io/container_io.go#L56-L61
train
cri-o/cri-o
utils/io/container_io.go
WithNewFIFOs
func WithNewFIFOs(root string, tty, stdin bool) ContainerIOOpts { return func(c *ContainerIO) error { fifos, err := newFifos(root, c.id, tty, stdin) if err != nil { return err } return WithFIFOs(fifos)(c) } }
go
func WithNewFIFOs(root string, tty, stdin bool) ContainerIOOpts { return func(c *ContainerIO) error { fifos, err := newFifos(root, c.id, tty, stdin) if err != nil { return err } return WithFIFOs(fifos)(c) } }
[ "func", "WithNewFIFOs", "(", "root", "string", ",", "tty", ",", "stdin", "bool", ")", "ContainerIOOpts", "{", "return", "func", "(", "c", "*", "ContainerIO", ")", "error", "{", "fifos", ",", "err", ":=", "newFifos", "(", "root", ",", "c", ".", "id", ",", "tty", ",", "stdin", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "WithFIFOs", "(", "fifos", ")", "(", "c", ")", "\n", "}", "\n", "}" ]
// WithNewFIFOs creates new fifos for the container io.
[ "WithNewFIFOs", "creates", "new", "fifos", "for", "the", "container", "io", "." ]
0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5
https://github.com/cri-o/cri-o/blob/0eac7be02d0a9d12b8b4bd1f2f0919c386ed61f5/utils/io/container_io.go#L64-L72
train