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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
remind101/empire | internal/migrate/migrate.go | NewMigrator | func NewMigrator(db *sql.DB) *Migrator {
return &Migrator{
db: db,
Locker: new(sync.Mutex),
}
} | go | func NewMigrator(db *sql.DB) *Migrator {
return &Migrator{
db: db,
Locker: new(sync.Mutex),
}
} | [
"func",
"NewMigrator",
"(",
"db",
"*",
"sql",
".",
"DB",
")",
"*",
"Migrator",
"{",
"return",
"&",
"Migrator",
"{",
"db",
":",
"db",
",",
"Locker",
":",
"new",
"(",
"sync",
".",
"Mutex",
")",
",",
"}",
"\n",
"}"
] | // NewMigrator returns a new Migrator instance that will use the sql.DB to
// perform the migrations. | [
"NewMigrator",
"returns",
"a",
"new",
"Migrator",
"instance",
"that",
"will",
"use",
"the",
"sql",
".",
"DB",
"to",
"perform",
"the",
"migrations",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/migrate/migrate.go#L122-L127 | train |
remind101/empire | internal/migrate/migrate.go | NewPostgresMigrator | func NewPostgresMigrator(db *sql.DB) *Migrator {
m := NewMigrator(db)
m.Locker = newPostgresLocker(db)
return m
} | go | func NewPostgresMigrator(db *sql.DB) *Migrator {
m := NewMigrator(db)
m.Locker = newPostgresLocker(db)
return m
} | [
"func",
"NewPostgresMigrator",
"(",
"db",
"*",
"sql",
".",
"DB",
")",
"*",
"Migrator",
"{",
"m",
":=",
"NewMigrator",
"(",
"db",
")",
"\n",
"m",
".",
"Locker",
"=",
"newPostgresLocker",
"(",
"db",
")",
"\n",
"return",
"m",
"\n",
"}"
] | // NewPostgresMigrator returns a new Migrator instance that uses the underlying
// sql.DB connection to a postgres database to perform migrations. It will use
// Postgres's advisory locks to ensure that only 1 migration is run at a time. | [
"NewPostgresMigrator",
"returns",
"a",
"new",
"Migrator",
"instance",
"that",
"uses",
"the",
"underlying",
"sql",
".",
"DB",
"connection",
"to",
"a",
"postgres",
"database",
"to",
"perform",
"migrations",
".",
"It",
"will",
"use",
"Postgres",
"s",
"advisory",
... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/migrate/migrate.go#L132-L136 | train |
remind101/empire | internal/migrate/migrate.go | Exec | func (m *Migrator) Exec(dir MigrationDirection, migrations ...Migration) error {
m.Lock()
defer m.Unlock()
_, err := m.db.Exec(fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (version integer primary key not null)", m.table()))
if err != nil {
return err
}
var tx *sql.Tx
if m.TransactionMode == SingleTransaction {
tx, err = m.db.Begin()
if err != nil {
return err
}
}
for _, migration := range sortMigrations(dir, migrations) {
if m.TransactionMode == IndividualTransactions {
tx, err = m.db.Begin()
if err != nil {
return err
}
}
if err := m.runMigration(tx, dir, migration); err != nil {
tx.Rollback()
return err
}
if m.TransactionMode == IndividualTransactions {
if err := tx.Commit(); err != nil {
return err
}
}
}
if m.TransactionMode == SingleTransaction {
if err := tx.Commit(); err != nil {
return err
}
}
return nil
} | go | func (m *Migrator) Exec(dir MigrationDirection, migrations ...Migration) error {
m.Lock()
defer m.Unlock()
_, err := m.db.Exec(fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s (version integer primary key not null)", m.table()))
if err != nil {
return err
}
var tx *sql.Tx
if m.TransactionMode == SingleTransaction {
tx, err = m.db.Begin()
if err != nil {
return err
}
}
for _, migration := range sortMigrations(dir, migrations) {
if m.TransactionMode == IndividualTransactions {
tx, err = m.db.Begin()
if err != nil {
return err
}
}
if err := m.runMigration(tx, dir, migration); err != nil {
tx.Rollback()
return err
}
if m.TransactionMode == IndividualTransactions {
if err := tx.Commit(); err != nil {
return err
}
}
}
if m.TransactionMode == SingleTransaction {
if err := tx.Commit(); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"m",
"*",
"Migrator",
")",
"Exec",
"(",
"dir",
"MigrationDirection",
",",
"migrations",
"...",
"Migration",
")",
"error",
"{",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"Unlock",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"m",
... | // Exec runs the migrations in the given direction. | [
"Exec",
"runs",
"the",
"migrations",
"in",
"the",
"given",
"direction",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/migrate/migrate.go#L139-L183 | train |
remind101/empire | internal/migrate/migrate.go | runMigration | func (m *Migrator) runMigration(tx *sql.Tx, dir MigrationDirection, migration Migration) error {
shouldMigrate, err := m.shouldMigrate(tx, migration.ID, dir)
if err != nil {
return err
}
if !shouldMigrate {
return nil
}
var migrate func(tx *sql.Tx) error
switch dir {
case Up:
migrate = migration.Up
default:
migrate = migration.Down
}
if err := migrate(tx); err != nil {
return &MigrationError{Migration: migration, Err: err}
}
var query string
switch dir {
case Up:
// Yes. This is a sql injection vulnerability. This gets around
// the different bindings for sqlite3/postgres.
//
// If you're running migrations from user input, you're doing
// something wrong.
query = fmt.Sprintf("INSERT INTO %s (version) VALUES (%d)", m.table(), migration.ID)
default:
query = fmt.Sprintf("DELETE FROM %s WHERE version = %d", m.table(), migration.ID)
}
_, err = tx.Exec(query)
return err
} | go | func (m *Migrator) runMigration(tx *sql.Tx, dir MigrationDirection, migration Migration) error {
shouldMigrate, err := m.shouldMigrate(tx, migration.ID, dir)
if err != nil {
return err
}
if !shouldMigrate {
return nil
}
var migrate func(tx *sql.Tx) error
switch dir {
case Up:
migrate = migration.Up
default:
migrate = migration.Down
}
if err := migrate(tx); err != nil {
return &MigrationError{Migration: migration, Err: err}
}
var query string
switch dir {
case Up:
// Yes. This is a sql injection vulnerability. This gets around
// the different bindings for sqlite3/postgres.
//
// If you're running migrations from user input, you're doing
// something wrong.
query = fmt.Sprintf("INSERT INTO %s (version) VALUES (%d)", m.table(), migration.ID)
default:
query = fmt.Sprintf("DELETE FROM %s WHERE version = %d", m.table(), migration.ID)
}
_, err = tx.Exec(query)
return err
} | [
"func",
"(",
"m",
"*",
"Migrator",
")",
"runMigration",
"(",
"tx",
"*",
"sql",
".",
"Tx",
",",
"dir",
"MigrationDirection",
",",
"migration",
"Migration",
")",
"error",
"{",
"shouldMigrate",
",",
"err",
":=",
"m",
".",
"shouldMigrate",
"(",
"tx",
",",
... | // runMigration runs the given Migration in the given direction using the given
// transaction. This function does not commit or rollback the transaction,
// that's the responsibility of the consumer dependending on whether an error
// gets returned. | [
"runMigration",
"runs",
"the",
"given",
"Migration",
"in",
"the",
"given",
"direction",
"using",
"the",
"given",
"transaction",
".",
"This",
"function",
"does",
"not",
"commit",
"or",
"rollback",
"the",
"transaction",
"that",
"s",
"the",
"responsibility",
"of",
... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/migrate/migrate.go#L189-L226 | train |
remind101/empire | internal/migrate/migrate.go | Exec | func Exec(db *sql.DB, dir MigrationDirection, migrations ...Migration) error {
return NewMigrator(db).Exec(dir, migrations...)
} | go | func Exec(db *sql.DB, dir MigrationDirection, migrations ...Migration) error {
return NewMigrator(db).Exec(dir, migrations...)
} | [
"func",
"Exec",
"(",
"db",
"*",
"sql",
".",
"DB",
",",
"dir",
"MigrationDirection",
",",
"migrations",
"...",
"Migration",
")",
"error",
"{",
"return",
"NewMigrator",
"(",
"db",
")",
".",
"Exec",
"(",
"dir",
",",
"migrations",
"...",
")",
"\n",
"}"
] | // Exec is a convenience method that runs the migrations against the default
// table. | [
"Exec",
"is",
"a",
"convenience",
"method",
"that",
"runs",
"the",
"migrations",
"against",
"the",
"default",
"table",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/migrate/migrate.go#L257-L259 | train |
remind101/empire | internal/migrate/migrate.go | sortMigrations | func sortMigrations(dir MigrationDirection, migrations []Migration) []Migration {
var m ByID
for _, migration := range migrations {
m = append(m, migration)
}
switch dir {
case Up:
sort.Sort(ByID(m))
default:
sort.Sort(sort.Reverse(ByID(m)))
}
return m
} | go | func sortMigrations(dir MigrationDirection, migrations []Migration) []Migration {
var m ByID
for _, migration := range migrations {
m = append(m, migration)
}
switch dir {
case Up:
sort.Sort(ByID(m))
default:
sort.Sort(sort.Reverse(ByID(m)))
}
return m
} | [
"func",
"sortMigrations",
"(",
"dir",
"MigrationDirection",
",",
"migrations",
"[",
"]",
"Migration",
")",
"[",
"]",
"Migration",
"{",
"var",
"m",
"ByID",
"\n",
"for",
"_",
",",
"migration",
":=",
"range",
"migrations",
"{",
"m",
"=",
"append",
"(",
"m",... | // sortMigrations sorts the migrations by id.
//
// When the direction is "Up", the migrations will be sorted by ID ascending.
// When the direction is "Down", the migrations will be sorted by ID descending. | [
"sortMigrations",
"sorts",
"the",
"migrations",
"by",
"id",
".",
"When",
"the",
"direction",
"is",
"Up",
"the",
"migrations",
"will",
"be",
"sorted",
"by",
"ID",
"ascending",
".",
"When",
"the",
"direction",
"is",
"Down",
"the",
"migrations",
"will",
"be",
... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/migrate/migrate.go#L279-L293 | train |
remind101/empire | server/cloudformation/cloudformation.go | NewCustomResourceProvisioner | func NewCustomResourceProvisioner(empire *empire.Empire, config client.ConfigProvider) *CustomResourceProvisioner {
db := empire.DB.DB.DB()
p := &CustomResourceProvisioner{
SQSDispatcher: newSQSDispatcher(config),
Provisioners: make(map[string]customresources.Provisioner),
sendResponse: customresources.SendResponse,
}
p.add("Custom::InstancePort", newInstancePortsProvisioner(&InstancePortsResource{
ports: newDBPortAllocator(db),
}))
ecs := newECSClient(config)
p.add("Custom::ECSService", newECSServiceProvisioner(&ECSServiceResource{
ecs: ecs,
}))
store := &dbEnvironmentStore{db}
p.add("Custom::ECSEnvironment", newECSEnvironmentProvisioner(&ECSEnvironmentResource{
environmentStore: store,
}))
p.add("Custom::ECSTaskDefinition", newECSTaskDefinitionProvisioner(&ECSTaskDefinitionResource{
ecs: ecs,
environmentStore: store,
}))
p.add("Custom::EmpireApp", &EmpireAppResource{
empire: empire,
})
p.add("Custom::EmpireAppEnvironment", &EmpireAppEnvironmentResource{
empire: empire,
})
return p
} | go | func NewCustomResourceProvisioner(empire *empire.Empire, config client.ConfigProvider) *CustomResourceProvisioner {
db := empire.DB.DB.DB()
p := &CustomResourceProvisioner{
SQSDispatcher: newSQSDispatcher(config),
Provisioners: make(map[string]customresources.Provisioner),
sendResponse: customresources.SendResponse,
}
p.add("Custom::InstancePort", newInstancePortsProvisioner(&InstancePortsResource{
ports: newDBPortAllocator(db),
}))
ecs := newECSClient(config)
p.add("Custom::ECSService", newECSServiceProvisioner(&ECSServiceResource{
ecs: ecs,
}))
store := &dbEnvironmentStore{db}
p.add("Custom::ECSEnvironment", newECSEnvironmentProvisioner(&ECSEnvironmentResource{
environmentStore: store,
}))
p.add("Custom::ECSTaskDefinition", newECSTaskDefinitionProvisioner(&ECSTaskDefinitionResource{
ecs: ecs,
environmentStore: store,
}))
p.add("Custom::EmpireApp", &EmpireAppResource{
empire: empire,
})
p.add("Custom::EmpireAppEnvironment", &EmpireAppEnvironmentResource{
empire: empire,
})
return p
} | [
"func",
"NewCustomResourceProvisioner",
"(",
"empire",
"*",
"empire",
".",
"Empire",
",",
"config",
"client",
".",
"ConfigProvider",
")",
"*",
"CustomResourceProvisioner",
"{",
"db",
":=",
"empire",
".",
"DB",
".",
"DB",
".",
"DB",
"(",
")",
"\n",
"p",
":=... | // NewCustomResourceProvisioner returns a new CustomResourceProvisioner with an
// sqs client configured from config. | [
"NewCustomResourceProvisioner",
"returns",
"a",
"new",
"CustomResourceProvisioner",
"with",
"an",
"sqs",
"client",
"configured",
"from",
"config",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/cloudformation/cloudformation.go#L50-L84 | train |
remind101/empire | server/cloudformation/cloudformation.go | add | func (c *CustomResourceProvisioner) add(resourceName string, p customresources.Provisioner) {
// Wrap the provisioner with timeouts.
p = customresources.WithTimeout(p, ProvisioningTimeout, ProvisioningGraceTimeout)
c.Provisioners[resourceName] = withMetrics(p)
} | go | func (c *CustomResourceProvisioner) add(resourceName string, p customresources.Provisioner) {
// Wrap the provisioner with timeouts.
p = customresources.WithTimeout(p, ProvisioningTimeout, ProvisioningGraceTimeout)
c.Provisioners[resourceName] = withMetrics(p)
} | [
"func",
"(",
"c",
"*",
"CustomResourceProvisioner",
")",
"add",
"(",
"resourceName",
"string",
",",
"p",
"customresources",
".",
"Provisioner",
")",
"{",
"p",
"=",
"customresources",
".",
"WithTimeout",
"(",
"p",
",",
"ProvisioningTimeout",
",",
"ProvisioningGra... | // add adds a custom resource provisioner. | [
"add",
"adds",
"a",
"custom",
"resource",
"provisioner",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/cloudformation/cloudformation.go#L87-L91 | train |
remind101/empire | server/cloudformation/cloudformation.go | Handle | func (c *CustomResourceProvisioner) Handle(ctx context.Context, message *sqs.Message) error {
var m Message
err := json.Unmarshal([]byte(*message.Body), &m)
if err != nil {
return fmt.Errorf("error unmarshalling sqs message body: %v", err)
}
var req customresources.Request
err = json.Unmarshal([]byte(m.Message), &req)
if err != nil {
return fmt.Errorf("error unmarshalling to cloudformation request: %v", err)
}
logger.Info(ctx, "cloudformation.provision.request",
"request_id", req.RequestId,
"stack_id", req.StackId,
"request_type", req.RequestType,
"resource_type", req.ResourceType,
"logical_resource_id", req.LogicalResourceId,
"physical_resource_id", req.PhysicalResourceId,
)
resp := customresources.NewResponseFromRequest(req)
// CloudFormation is weird. PhysicalResourceId is required when creating
// a resource, but if the creation fails, how would we have a physical
// resource id? In cases where a Create request fails, we set the
// physical resource id to `failed/Create`. When a delete request comes
// in to delete that resource, we just send back a SUCCESS response so
// CloudFormation is happy.
if req.RequestType == customresources.Delete && req.PhysicalResourceId == fmt.Sprintf("failed/%s", customresources.Create) {
resp.PhysicalResourceId = req.PhysicalResourceId
} else {
resp.PhysicalResourceId, resp.Data, err = c.provision(ctx, m, req)
}
// Allow provisioners to just return "" to indicate that the physical
// resource id did not change.
if resp.PhysicalResourceId == "" && req.PhysicalResourceId != "" {
resp.PhysicalResourceId = req.PhysicalResourceId
}
switch err {
case nil:
resp.Status = customresources.StatusSuccess
logger.Info(ctx, "cloudformation.provision.success",
"request_id", req.RequestId,
"stack_id", req.StackId,
"physical_resource_id", resp.PhysicalResourceId,
)
default:
// A physical resource id is required, so if a Create request
// fails, and there's no physical resource id, CloudFormation
// will only say `Invalid PhysicalResourceId` in the status
// Reason instead of the actual error that caused the Create to
// fail.
if req.RequestType == customresources.Create && resp.PhysicalResourceId == "" {
resp.PhysicalResourceId = fmt.Sprintf("failed/%s", req.RequestType)
}
resp.Status = customresources.StatusFailed
resp.Reason = err.Error()
logger.Error(ctx, "cloudformation.provision.error",
"request_id", req.RequestId,
"stack_id", req.StackId,
"err", err.Error(),
)
}
return c.sendResponse(req, resp)
} | go | func (c *CustomResourceProvisioner) Handle(ctx context.Context, message *sqs.Message) error {
var m Message
err := json.Unmarshal([]byte(*message.Body), &m)
if err != nil {
return fmt.Errorf("error unmarshalling sqs message body: %v", err)
}
var req customresources.Request
err = json.Unmarshal([]byte(m.Message), &req)
if err != nil {
return fmt.Errorf("error unmarshalling to cloudformation request: %v", err)
}
logger.Info(ctx, "cloudformation.provision.request",
"request_id", req.RequestId,
"stack_id", req.StackId,
"request_type", req.RequestType,
"resource_type", req.ResourceType,
"logical_resource_id", req.LogicalResourceId,
"physical_resource_id", req.PhysicalResourceId,
)
resp := customresources.NewResponseFromRequest(req)
// CloudFormation is weird. PhysicalResourceId is required when creating
// a resource, but if the creation fails, how would we have a physical
// resource id? In cases where a Create request fails, we set the
// physical resource id to `failed/Create`. When a delete request comes
// in to delete that resource, we just send back a SUCCESS response so
// CloudFormation is happy.
if req.RequestType == customresources.Delete && req.PhysicalResourceId == fmt.Sprintf("failed/%s", customresources.Create) {
resp.PhysicalResourceId = req.PhysicalResourceId
} else {
resp.PhysicalResourceId, resp.Data, err = c.provision(ctx, m, req)
}
// Allow provisioners to just return "" to indicate that the physical
// resource id did not change.
if resp.PhysicalResourceId == "" && req.PhysicalResourceId != "" {
resp.PhysicalResourceId = req.PhysicalResourceId
}
switch err {
case nil:
resp.Status = customresources.StatusSuccess
logger.Info(ctx, "cloudformation.provision.success",
"request_id", req.RequestId,
"stack_id", req.StackId,
"physical_resource_id", resp.PhysicalResourceId,
)
default:
// A physical resource id is required, so if a Create request
// fails, and there's no physical resource id, CloudFormation
// will only say `Invalid PhysicalResourceId` in the status
// Reason instead of the actual error that caused the Create to
// fail.
if req.RequestType == customresources.Create && resp.PhysicalResourceId == "" {
resp.PhysicalResourceId = fmt.Sprintf("failed/%s", req.RequestType)
}
resp.Status = customresources.StatusFailed
resp.Reason = err.Error()
logger.Error(ctx, "cloudformation.provision.error",
"request_id", req.RequestId,
"stack_id", req.StackId,
"err", err.Error(),
)
}
return c.sendResponse(req, resp)
} | [
"func",
"(",
"c",
"*",
"CustomResourceProvisioner",
")",
"Handle",
"(",
"ctx",
"context",
".",
"Context",
",",
"message",
"*",
"sqs",
".",
"Message",
")",
"error",
"{",
"var",
"m",
"Message",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
... | // Handle handles a single sqs.Message to perform the provisioning. | [
"Handle",
"handles",
"a",
"single",
"sqs",
".",
"Message",
"to",
"perform",
"the",
"provisioning",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/cloudformation/cloudformation.go#L98-L168 | train |
remind101/empire | server/cloudformation/cloudformation.go | requiresReplacement | func requiresReplacement(n, o properties) (bool, error) {
a, err := n.ReplacementHash()
if err != nil {
return false, err
}
b, err := o.ReplacementHash()
if err != nil {
return false, err
}
return a != b, nil
} | go | func requiresReplacement(n, o properties) (bool, error) {
a, err := n.ReplacementHash()
if err != nil {
return false, err
}
b, err := o.ReplacementHash()
if err != nil {
return false, err
}
return a != b, nil
} | [
"func",
"requiresReplacement",
"(",
"n",
",",
"o",
"properties",
")",
"(",
"bool",
",",
"error",
")",
"{",
"a",
",",
"err",
":=",
"n",
".",
"ReplacementHash",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
... | // requiresReplacement returns true if the new properties require a replacement
// of the old properties. | [
"requiresReplacement",
"returns",
"true",
"if",
"the",
"new",
"properties",
"require",
"a",
"replacement",
"of",
"the",
"old",
"properties",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/cloudformation/cloudformation.go#L244-L256 | train |
remind101/empire | tasks.go | taskFromInstance | func taskFromInstance(i *twelvefactor.Task) *Task {
version := i.Process.Env["EMPIRE_RELEASE"]
if version == "" {
version = "v0"
}
return &Task{
Name: fmt.Sprintf("%s.%s.%s", version, i.Process.Type, i.ID),
Type: string(i.Process.Type),
Host: Host{ID: i.Host.ID},
Command: Command(i.Process.Command),
Constraints: Constraints{
CPUShare: constraints.CPUShare(i.Process.CPUShares),
Memory: constraints.Memory(i.Process.Memory),
Nproc: constraints.Nproc(i.Process.Nproc),
},
State: i.State,
UpdatedAt: i.UpdatedAt,
}
} | go | func taskFromInstance(i *twelvefactor.Task) *Task {
version := i.Process.Env["EMPIRE_RELEASE"]
if version == "" {
version = "v0"
}
return &Task{
Name: fmt.Sprintf("%s.%s.%s", version, i.Process.Type, i.ID),
Type: string(i.Process.Type),
Host: Host{ID: i.Host.ID},
Command: Command(i.Process.Command),
Constraints: Constraints{
CPUShare: constraints.CPUShare(i.Process.CPUShares),
Memory: constraints.Memory(i.Process.Memory),
Nproc: constraints.Nproc(i.Process.Nproc),
},
State: i.State,
UpdatedAt: i.UpdatedAt,
}
} | [
"func",
"taskFromInstance",
"(",
"i",
"*",
"twelvefactor",
".",
"Task",
")",
"*",
"Task",
"{",
"version",
":=",
"i",
".",
"Process",
".",
"Env",
"[",
"\"EMPIRE_RELEASE\"",
"]",
"\n",
"if",
"version",
"==",
"\"\"",
"{",
"version",
"=",
"\"v0\"",
"\n",
"... | // taskFromInstance converts a scheduler.Instance into a Task.
// It pulls some of its data from empire specific environment variables if they have been set.
// Once ECS supports this data natively, we can stop doing this. | [
"taskFromInstance",
"converts",
"a",
"scheduler",
".",
"Instance",
"into",
"a",
"Task",
".",
"It",
"pulls",
"some",
"of",
"its",
"data",
"from",
"empire",
"specific",
"environment",
"variables",
"if",
"they",
"have",
"been",
"set",
".",
"Once",
"ECS",
"suppo... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/tasks.go#L67-L86 | train |
remind101/empire | logs/logs.go | RecordToCloudWatch | func RecordToCloudWatch(group string, config client.ConfigProvider) empire.RunRecorder {
c := cloudwatchlogs.New(config)
g := cloudwatch.NewGroup(group, c)
return func() (io.Writer, error) {
stream := uuid.New()
w, err := g.Create(stream)
if err != nil {
return nil, err
}
url := fmt.Sprintf("https://console.aws.amazon.com/cloudwatch/home?region=%s#logEvent:group=%s;stream=%s", *c.Config.Region, group, stream)
return &writerWithURL{w, url}, nil
}
} | go | func RecordToCloudWatch(group string, config client.ConfigProvider) empire.RunRecorder {
c := cloudwatchlogs.New(config)
g := cloudwatch.NewGroup(group, c)
return func() (io.Writer, error) {
stream := uuid.New()
w, err := g.Create(stream)
if err != nil {
return nil, err
}
url := fmt.Sprintf("https://console.aws.amazon.com/cloudwatch/home?region=%s#logEvent:group=%s;stream=%s", *c.Config.Region, group, stream)
return &writerWithURL{w, url}, nil
}
} | [
"func",
"RecordToCloudWatch",
"(",
"group",
"string",
",",
"config",
"client",
".",
"ConfigProvider",
")",
"empire",
".",
"RunRecorder",
"{",
"c",
":=",
"cloudwatchlogs",
".",
"New",
"(",
"config",
")",
"\n",
"g",
":=",
"cloudwatch",
".",
"NewGroup",
"(",
... | // RecordToCloudWatch returns a RunRecorder that writes the log record to
// CloudWatch Logs. | [
"RecordToCloudWatch",
"returns",
"a",
"RunRecorder",
"that",
"writes",
"the",
"log",
"record",
"to",
"CloudWatch",
"Logs",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/logs/logs.go#L45-L58 | train |
remind101/empire | logs/logs.go | RecordTo | func RecordTo(w io.Writer) empire.RunRecorder {
return func() (io.Writer, error) {
return w, nil
}
} | go | func RecordTo(w io.Writer) empire.RunRecorder {
return func() (io.Writer, error) {
return w, nil
}
} | [
"func",
"RecordTo",
"(",
"w",
"io",
".",
"Writer",
")",
"empire",
".",
"RunRecorder",
"{",
"return",
"func",
"(",
")",
"(",
"io",
".",
"Writer",
",",
"error",
")",
"{",
"return",
"w",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // RecordTo returns a RunRecorder that writes the log record to the io.Writer | [
"RecordTo",
"returns",
"a",
"RunRecorder",
"that",
"writes",
"the",
"log",
"record",
"to",
"the",
"io",
".",
"Writer"
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/logs/logs.go#L72-L76 | train |
remind101/empire | pkg/pg/lock/lock.go | NewAdvisoryLock | func NewAdvisoryLock(db *sql.DB, key uint32) (*AdvisoryLock, error) {
tx, err := db.Begin()
if err != nil {
return nil, err
}
return &AdvisoryLock{
tx: tx,
key: key,
}, nil
} | go | func NewAdvisoryLock(db *sql.DB, key uint32) (*AdvisoryLock, error) {
tx, err := db.Begin()
if err != nil {
return nil, err
}
return &AdvisoryLock{
tx: tx,
key: key,
}, nil
} | [
"func",
"NewAdvisoryLock",
"(",
"db",
"*",
"sql",
".",
"DB",
",",
"key",
"uint32",
")",
"(",
"*",
"AdvisoryLock",
",",
"error",
")",
"{",
"tx",
",",
"err",
":=",
"db",
".",
"Begin",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
... | // NewAdvisoryLock opens a new transaction and returns the AdvisoryLock. | [
"NewAdvisoryLock",
"opens",
"a",
"new",
"transaction",
"and",
"returns",
"the",
"AdvisoryLock",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/pg/lock/lock.go#L43-L53 | train |
remind101/empire | pkg/pg/lock/lock.go | Lock | func (l *AdvisoryLock) Lock() error {
l.mu.Lock()
defer l.mu.Unlock()
if l.commited {
panic("lock called on commited lock")
}
if l.LockTimeout != 0 {
_, err := l.tx.Exec(fmt.Sprintf("SET LOCAL lock_timeout = %d", int(l.LockTimeout.Seconds()*1000)))
if err != nil {
return fmt.Errorf("error setting lock timeout: %v", err)
}
}
_, err := l.tx.Exec(fmt.Sprintf("SELECT pg_advisory_lock($1) /* %s */", l.Context), l.key)
if err != nil {
// If there's an error trying to obtain the lock, probably the
// safest thing to do is commit the transaction and make this
// lock invalid.
l.commit()
if err, ok := err.(*pq.Error); ok {
switch err.Code.Name() {
case "query_canceled":
return Canceled
case "lock_not_available":
return ErrLockTimeout
}
}
return fmt.Errorf("error obtaining lock: %v", err)
}
l.c += 1
return nil
} | go | func (l *AdvisoryLock) Lock() error {
l.mu.Lock()
defer l.mu.Unlock()
if l.commited {
panic("lock called on commited lock")
}
if l.LockTimeout != 0 {
_, err := l.tx.Exec(fmt.Sprintf("SET LOCAL lock_timeout = %d", int(l.LockTimeout.Seconds()*1000)))
if err != nil {
return fmt.Errorf("error setting lock timeout: %v", err)
}
}
_, err := l.tx.Exec(fmt.Sprintf("SELECT pg_advisory_lock($1) /* %s */", l.Context), l.key)
if err != nil {
// If there's an error trying to obtain the lock, probably the
// safest thing to do is commit the transaction and make this
// lock invalid.
l.commit()
if err, ok := err.(*pq.Error); ok {
switch err.Code.Name() {
case "query_canceled":
return Canceled
case "lock_not_available":
return ErrLockTimeout
}
}
return fmt.Errorf("error obtaining lock: %v", err)
}
l.c += 1
return nil
} | [
"func",
"(",
"l",
"*",
"AdvisoryLock",
")",
"Lock",
"(",
")",
"error",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"l",
".",
"commited",
"{",
"panic",
"(",
"\"lock called on comm... | // Lock obtains the advisory lock. | [
"Lock",
"obtains",
"the",
"advisory",
"lock",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/pg/lock/lock.go#L74-L111 | train |
remind101/empire | pkg/pg/lock/lock.go | Unlock | func (l *AdvisoryLock) Unlock() error {
l.mu.Lock()
defer l.mu.Unlock()
if l.commited {
panic("unlock called on commited lock")
}
if l.c == 0 {
panic("unlock of unlocked advisory lock")
}
_, err := l.tx.Exec(fmt.Sprintf("SELECT pg_advisory_unlock($1) /* %s */", l.Context), l.key)
if err != nil {
return err
}
l.c -= 1
if l.c == 0 {
if err := l.commit(); err != nil {
return err
}
}
return err
} | go | func (l *AdvisoryLock) Unlock() error {
l.mu.Lock()
defer l.mu.Unlock()
if l.commited {
panic("unlock called on commited lock")
}
if l.c == 0 {
panic("unlock of unlocked advisory lock")
}
_, err := l.tx.Exec(fmt.Sprintf("SELECT pg_advisory_unlock($1) /* %s */", l.Context), l.key)
if err != nil {
return err
}
l.c -= 1
if l.c == 0 {
if err := l.commit(); err != nil {
return err
}
}
return err
} | [
"func",
"(",
"l",
"*",
"AdvisoryLock",
")",
"Unlock",
"(",
")",
"error",
"{",
"l",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"l",
".",
"commited",
"{",
"panic",
"(",
"\"unlock called on ... | // Unlock releases the advisory lock. | [
"Unlock",
"releases",
"the",
"advisory",
"lock",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/pg/lock/lock.go#L114-L140 | train |
remind101/empire | cmd/emp/suggest.go | suggest | func suggest(s string) (a []string) {
var g Suggestions
for _, c := range commands {
if d := editDistance(s, c.Name()); d < 4 {
if c.Runnable() {
g = append(g, Suggestion{c.Name(), d})
} else {
g = append(g, Suggestion{strconv.Quote("help " + c.Name()), d})
}
}
}
sort.Sort(g)
for i, s := range g {
a = append(a, s.s)
if i >= 4 {
break
}
}
return a
} | go | func suggest(s string) (a []string) {
var g Suggestions
for _, c := range commands {
if d := editDistance(s, c.Name()); d < 4 {
if c.Runnable() {
g = append(g, Suggestion{c.Name(), d})
} else {
g = append(g, Suggestion{strconv.Quote("help " + c.Name()), d})
}
}
}
sort.Sort(g)
for i, s := range g {
a = append(a, s.s)
if i >= 4 {
break
}
}
return a
} | [
"func",
"suggest",
"(",
"s",
"string",
")",
"(",
"a",
"[",
"]",
"string",
")",
"{",
"var",
"g",
"Suggestions",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"commands",
"{",
"if",
"d",
":=",
"editDistance",
"(",
"s",
",",
"c",
".",
"Name",
"(",
")... | // suggest returns command names that are similar to s. | [
"suggest",
"returns",
"command",
"names",
"that",
"are",
"similar",
"to",
"s",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/cmd/emp/suggest.go#L20-L39 | train |
remind101/empire | server/auth/saml/saml.go | SessionFromAssertion | func SessionFromAssertion(assertion *saml.Assertion) *auth.Session {
login := assertion.Subject.NameID.Value
user := &empire.User{
Name: login,
}
session := auth.NewSession(user)
session.ExpiresAt = &assertion.AuthnStatement.SessionNotOnOrAfter
return session
} | go | func SessionFromAssertion(assertion *saml.Assertion) *auth.Session {
login := assertion.Subject.NameID.Value
user := &empire.User{
Name: login,
}
session := auth.NewSession(user)
session.ExpiresAt = &assertion.AuthnStatement.SessionNotOnOrAfter
return session
} | [
"func",
"SessionFromAssertion",
"(",
"assertion",
"*",
"saml",
".",
"Assertion",
")",
"*",
"auth",
".",
"Session",
"{",
"login",
":=",
"assertion",
".",
"Subject",
".",
"NameID",
".",
"Value",
"\n",
"user",
":=",
"&",
"empire",
".",
"User",
"{",
"Name",
... | // SessionFromAssertion returns a new auth.Session generated from the SAML
// assertion. | [
"SessionFromAssertion",
"returns",
"a",
"new",
"auth",
".",
"Session",
"generated",
"from",
"the",
"SAML",
"assertion",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/auth/saml/saml.go#L11-L20 | train |
remind101/empire | processes.go | MustParseCommand | func MustParseCommand(command string) Command {
c, err := ParseCommand(command)
if err != nil {
panic(err)
}
return c
} | go | func MustParseCommand(command string) Command {
c, err := ParseCommand(command)
if err != nil {
panic(err)
}
return c
} | [
"func",
"MustParseCommand",
"(",
"command",
"string",
")",
"Command",
"{",
"c",
",",
"err",
":=",
"ParseCommand",
"(",
"command",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"c",
"\n",
"}"
] | // MustParseCommand parses the string into a Command, panicing if there's an
// error. This method should only be used in tests for convenience. | [
"MustParseCommand",
"parses",
"the",
"string",
"into",
"a",
"Command",
"panicing",
"if",
"there",
"s",
"an",
"error",
".",
"This",
"method",
"should",
"only",
"be",
"used",
"in",
"tests",
"for",
"convenience",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/processes.go#L32-L38 | train |
remind101/empire | processes.go | IsValid | func (p *Process) IsValid() error {
// Ensure that processes marked as NoService can't be scaled up.
if p.NoService {
if p.Quantity != 0 {
return errors.New("non-service processes cannot be scaled up")
}
}
return nil
} | go | func (p *Process) IsValid() error {
// Ensure that processes marked as NoService can't be scaled up.
if p.NoService {
if p.Quantity != 0 {
return errors.New("non-service processes cannot be scaled up")
}
}
return nil
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"IsValid",
"(",
")",
"error",
"{",
"if",
"p",
".",
"NoService",
"{",
"if",
"p",
".",
"Quantity",
"!=",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"non-service processes cannot be scaled up\"",
")",
"\n",
"}",
... | // IsValid returns nil if the Process is valid. | [
"IsValid",
"returns",
"nil",
"if",
"the",
"Process",
"is",
"valid",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/processes.go#L112-L121 | train |
remind101/empire | processes.go | Constraints | func (p *Process) Constraints() Constraints {
return Constraints{
Memory: p.Memory,
CPUShare: p.CPUShare,
Nproc: p.Nproc,
}
} | go | func (p *Process) Constraints() Constraints {
return Constraints{
Memory: p.Memory,
CPUShare: p.CPUShare,
Nproc: p.Nproc,
}
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"Constraints",
"(",
")",
"Constraints",
"{",
"return",
"Constraints",
"{",
"Memory",
":",
"p",
".",
"Memory",
",",
"CPUShare",
":",
"p",
".",
"CPUShare",
",",
"Nproc",
":",
"p",
".",
"Nproc",
",",
"}",
"\n",
"... | // Constraints returns a constraints.Constraints from this Process definition. | [
"Constraints",
"returns",
"a",
"constraints",
".",
"Constraints",
"from",
"this",
"Process",
"definition",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/processes.go#L124-L130 | train |
remind101/empire | processes.go | IsValid | func (f Formation) IsValid() error {
for n, p := range f {
if err := p.IsValid(); err != nil {
return fmt.Errorf("process %s is not valid: %v", n, err)
}
}
return nil
} | go | func (f Formation) IsValid() error {
for n, p := range f {
if err := p.IsValid(); err != nil {
return fmt.Errorf("process %s is not valid: %v", n, err)
}
}
return nil
} | [
"func",
"(",
"f",
"Formation",
")",
"IsValid",
"(",
")",
"error",
"{",
"for",
"n",
",",
"p",
":=",
"range",
"f",
"{",
"if",
"err",
":=",
"p",
".",
"IsValid",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"proces... | // IsValid returns nil if all of the Processes are valid. | [
"IsValid",
"returns",
"nil",
"if",
"all",
"of",
"the",
"Processes",
"are",
"valid",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/processes.go#L144-L152 | train |
remind101/empire | processes.go | Merge | func (f Formation) Merge(other Formation) Formation {
new := make(Formation)
for name, p := range f {
if existing, found := other[name]; found {
// If the existing Formation already had a process
// configuration for this process type, copy over the
// instance count.
p.Quantity = existing.Quantity
p.SetConstraints(existing.Constraints())
} else {
p.Quantity = DefaultQuantities[name]
p.SetConstraints(DefaultConstraints)
}
new[name] = p
}
return new
} | go | func (f Formation) Merge(other Formation) Formation {
new := make(Formation)
for name, p := range f {
if existing, found := other[name]; found {
// If the existing Formation already had a process
// configuration for this process type, copy over the
// instance count.
p.Quantity = existing.Quantity
p.SetConstraints(existing.Constraints())
} else {
p.Quantity = DefaultQuantities[name]
p.SetConstraints(DefaultConstraints)
}
new[name] = p
}
return new
} | [
"func",
"(",
"f",
"Formation",
")",
"Merge",
"(",
"other",
"Formation",
")",
"Formation",
"{",
"new",
":=",
"make",
"(",
"Formation",
")",
"\n",
"for",
"name",
",",
"p",
":=",
"range",
"f",
"{",
"if",
"existing",
",",
"found",
":=",
"other",
"[",
"... | // Merge merges in the existing quantity and constraints from the old Formation
// into this Formation. | [
"Merge",
"merges",
"in",
"the",
"existing",
"quantity",
"and",
"constraints",
"from",
"the",
"old",
"Formation",
"into",
"this",
"Formation",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/processes.go#L186-L205 | train |
remind101/empire | empire.go | New | func New(db *DB) *Empire {
e := &Empire{
LogsStreamer: logsDisabled,
EventStream: NullEventStream,
DB: db,
db: db.DB,
}
e.apps = &appsService{Empire: e}
e.configs = &configsService{Empire: e}
e.deployer = &deployerService{Empire: e}
e.domains = &domainsService{Empire: e}
e.slugs = &slugsService{Empire: e}
e.tasks = &tasksService{Empire: e}
e.runner = &runnerService{Empire: e}
e.releases = &releasesService{Empire: e}
e.certs = &certsService{Empire: e}
return e
} | go | func New(db *DB) *Empire {
e := &Empire{
LogsStreamer: logsDisabled,
EventStream: NullEventStream,
DB: db,
db: db.DB,
}
e.apps = &appsService{Empire: e}
e.configs = &configsService{Empire: e}
e.deployer = &deployerService{Empire: e}
e.domains = &domainsService{Empire: e}
e.slugs = &slugsService{Empire: e}
e.tasks = &tasksService{Empire: e}
e.runner = &runnerService{Empire: e}
e.releases = &releasesService{Empire: e}
e.certs = &certsService{Empire: e}
return e
} | [
"func",
"New",
"(",
"db",
"*",
"DB",
")",
"*",
"Empire",
"{",
"e",
":=",
"&",
"Empire",
"{",
"LogsStreamer",
":",
"logsDisabled",
",",
"EventStream",
":",
"NullEventStream",
",",
"DB",
":",
"db",
",",
"db",
":",
"db",
".",
"DB",
",",
"}",
"\n",
"... | // New returns a new Empire instance. | [
"New",
"returns",
"a",
"new",
"Empire",
"instance",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L113-L132 | train |
remind101/empire | empire.go | AppsFind | func (e *Empire) AppsFind(q AppsQuery) (*App, error) {
return appsFind(e.db, q)
} | go | func (e *Empire) AppsFind(q AppsQuery) (*App, error) {
return appsFind(e.db, q)
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"AppsFind",
"(",
"q",
"AppsQuery",
")",
"(",
"*",
"App",
",",
"error",
")",
"{",
"return",
"appsFind",
"(",
"e",
".",
"db",
",",
"q",
")",
"\n",
"}"
] | // AppsFind finds the first app matching the query. | [
"AppsFind",
"finds",
"the",
"first",
"app",
"matching",
"the",
"query",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L135-L137 | train |
remind101/empire | empire.go | Apps | func (e *Empire) Apps(q AppsQuery) ([]*App, error) {
return apps(e.db, q)
} | go | func (e *Empire) Apps(q AppsQuery) ([]*App, error) {
return apps(e.db, q)
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"Apps",
"(",
"q",
"AppsQuery",
")",
"(",
"[",
"]",
"*",
"App",
",",
"error",
")",
"{",
"return",
"apps",
"(",
"e",
".",
"db",
",",
"q",
")",
"\n",
"}"
] | // Apps returns all Apps. | [
"Apps",
"returns",
"all",
"Apps",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L140-L142 | train |
remind101/empire | empire.go | Create | func (e *Empire) Create(ctx context.Context, opts CreateOpts) (*App, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
a, err := appsCreate(e.db, &App{Name: opts.Name})
if err != nil {
return a, err
}
return a, e.PublishEvent(opts.Event())
} | go | func (e *Empire) Create(ctx context.Context, opts CreateOpts) (*App, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
a, err := appsCreate(e.db, &App{Name: opts.Name})
if err != nil {
return a, err
}
return a, e.PublishEvent(opts.Event())
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"Create",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"CreateOpts",
")",
"(",
"*",
"App",
",",
"error",
")",
"{",
"if",
"err",
":=",
"opts",
".",
"Validate",
"(",
"e",
")",
";",
"err",
"!=",
"nil",
... | // Create creates a new app. | [
"Create",
"creates",
"a",
"new",
"app",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L176-L187 | train |
remind101/empire | empire.go | Destroy | func (e *Empire) Destroy(ctx context.Context, opts DestroyOpts) error {
if err := opts.Validate(e); err != nil {
return err
}
tx := e.db.Begin()
if err := e.apps.Destroy(ctx, tx, opts.App); err != nil {
tx.Rollback()
return err
}
if err := tx.Commit().Error; err != nil {
return err
}
return e.PublishEvent(opts.Event())
} | go | func (e *Empire) Destroy(ctx context.Context, opts DestroyOpts) error {
if err := opts.Validate(e); err != nil {
return err
}
tx := e.db.Begin()
if err := e.apps.Destroy(ctx, tx, opts.App); err != nil {
tx.Rollback()
return err
}
if err := tx.Commit().Error; err != nil {
return err
}
return e.PublishEvent(opts.Event())
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"Destroy",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"DestroyOpts",
")",
"error",
"{",
"if",
"err",
":=",
"opts",
".",
"Validate",
"(",
"e",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
... | // Destroy destroys an app. | [
"Destroy",
"destroys",
"an",
"app",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L214-L231 | train |
remind101/empire | empire.go | Config | func (e *Empire) Config(app *App) (*Config, error) {
tx := e.db.Begin()
c, err := e.configs.Config(tx, app)
if err != nil {
tx.Rollback()
return c, err
}
if err := tx.Commit().Error; err != nil {
return c, err
}
return c, nil
} | go | func (e *Empire) Config(app *App) (*Config, error) {
tx := e.db.Begin()
c, err := e.configs.Config(tx, app)
if err != nil {
tx.Rollback()
return c, err
}
if err := tx.Commit().Error; err != nil {
return c, err
}
return c, nil
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"Config",
"(",
"app",
"*",
"App",
")",
"(",
"*",
"Config",
",",
"error",
")",
"{",
"tx",
":=",
"e",
".",
"db",
".",
"Begin",
"(",
")",
"\n",
"c",
",",
"err",
":=",
"e",
".",
"configs",
".",
"Config",
"(... | // Config returns the current Config for a given app. | [
"Config",
"returns",
"the",
"current",
"Config",
"for",
"a",
"given",
"app",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L234-L248 | train |
remind101/empire | empire.go | SetMaintenanceMode | func (e *Empire) SetMaintenanceMode(ctx context.Context, opts SetMaintenanceModeOpts) error {
if err := opts.Validate(e); err != nil {
return err
}
tx := e.db.Begin()
app := opts.App
app.Maintenance = opts.Maintenance
if err := appsUpdate(tx, app); err != nil {
tx.Rollback()
return err
}
if err := e.releases.ReleaseApp(ctx, tx, app, nil); err != nil {
tx.Rollback()
if err == ErrNoReleases {
return nil
}
return err
}
if err := tx.Commit().Error; err != nil {
return err
}
return e.PublishEvent(opts.Event())
} | go | func (e *Empire) SetMaintenanceMode(ctx context.Context, opts SetMaintenanceModeOpts) error {
if err := opts.Validate(e); err != nil {
return err
}
tx := e.db.Begin()
app := opts.App
app.Maintenance = opts.Maintenance
if err := appsUpdate(tx, app); err != nil {
tx.Rollback()
return err
}
if err := e.releases.ReleaseApp(ctx, tx, app, nil); err != nil {
tx.Rollback()
if err == ErrNoReleases {
return nil
}
return err
}
if err := tx.Commit().Error; err != nil {
return err
}
return e.PublishEvent(opts.Event())
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"SetMaintenanceMode",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"SetMaintenanceModeOpts",
")",
"error",
"{",
"if",
"err",
":=",
"opts",
".",
"Validate",
"(",
"e",
")",
";",
"err",
"!=",
"nil",
"{",
"retur... | // SetMaintenanceMode enables or disables "maintenance mode" on the app. When an
// app is in maintenance mode, all processes will be scaled down to 0. When
// taken out of maintenance mode, all processes will be scaled up back to their
// existing values. | [
"SetMaintenanceMode",
"enables",
"or",
"disables",
"maintenance",
"mode",
"on",
"the",
"app",
".",
"When",
"an",
"app",
"is",
"in",
"maintenance",
"mode",
"all",
"processes",
"will",
"be",
"scaled",
"down",
"to",
"0",
".",
"When",
"taken",
"out",
"of",
"ma... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L281-L311 | train |
remind101/empire | empire.go | Set | func (e *Empire) Set(ctx context.Context, opts SetOpts) (*Config, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
tx := e.db.Begin()
c, err := e.configs.Set(ctx, tx, opts)
if err != nil {
tx.Rollback()
return c, err
}
if err := tx.Commit().Error; err != nil {
return c, err
}
return c, e.PublishEvent(opts.Event())
} | go | func (e *Empire) Set(ctx context.Context, opts SetOpts) (*Config, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
tx := e.db.Begin()
c, err := e.configs.Set(ctx, tx, opts)
if err != nil {
tx.Rollback()
return c, err
}
if err := tx.Commit().Error; err != nil {
return c, err
}
return c, e.PublishEvent(opts.Event())
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"Set",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"SetOpts",
")",
"(",
"*",
"Config",
",",
"error",
")",
"{",
"if",
"err",
":=",
"opts",
".",
"Validate",
"(",
"e",
")",
";",
"err",
"!=",
"nil",
"{"... | // Set applies the new config vars to the apps current Config, returning the new
// Config. If the app has a running release, a new release will be created and
// run. | [
"Set",
"applies",
"the",
"new",
"config",
"vars",
"to",
"the",
"apps",
"current",
"Config",
"returning",
"the",
"new",
"Config",
".",
"If",
"the",
"app",
"has",
"a",
"running",
"release",
"a",
"new",
"release",
"will",
"be",
"created",
"and",
"run",
"."
... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L350-L368 | train |
remind101/empire | empire.go | DomainsFind | func (e *Empire) DomainsFind(q DomainsQuery) (*Domain, error) {
return domainsFind(e.db, q)
} | go | func (e *Empire) DomainsFind(q DomainsQuery) (*Domain, error) {
return domainsFind(e.db, q)
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"DomainsFind",
"(",
"q",
"DomainsQuery",
")",
"(",
"*",
"Domain",
",",
"error",
")",
"{",
"return",
"domainsFind",
"(",
"e",
".",
"db",
",",
"q",
")",
"\n",
"}"
] | // DomainsFind returns the first domain matching the query. | [
"DomainsFind",
"returns",
"the",
"first",
"domain",
"matching",
"the",
"query",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L371-L373 | train |
remind101/empire | empire.go | Domains | func (e *Empire) Domains(q DomainsQuery) ([]*Domain, error) {
return domains(e.db, q)
} | go | func (e *Empire) Domains(q DomainsQuery) ([]*Domain, error) {
return domains(e.db, q)
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"Domains",
"(",
"q",
"DomainsQuery",
")",
"(",
"[",
"]",
"*",
"Domain",
",",
"error",
")",
"{",
"return",
"domains",
"(",
"e",
".",
"db",
",",
"q",
")",
"\n",
"}"
] | // Domains returns all domains matching the query. | [
"Domains",
"returns",
"all",
"domains",
"matching",
"the",
"query",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L376-L378 | train |
remind101/empire | empire.go | DomainsCreate | func (e *Empire) DomainsCreate(ctx context.Context, domain *Domain) (*Domain, error) {
tx := e.db.Begin()
d, err := e.domains.DomainsCreate(ctx, tx, domain)
if err != nil {
tx.Rollback()
return d, err
}
if err := tx.Commit().Error; err != nil {
return d, err
}
return d, nil
} | go | func (e *Empire) DomainsCreate(ctx context.Context, domain *Domain) (*Domain, error) {
tx := e.db.Begin()
d, err := e.domains.DomainsCreate(ctx, tx, domain)
if err != nil {
tx.Rollback()
return d, err
}
if err := tx.Commit().Error; err != nil {
return d, err
}
return d, nil
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"DomainsCreate",
"(",
"ctx",
"context",
".",
"Context",
",",
"domain",
"*",
"Domain",
")",
"(",
"*",
"Domain",
",",
"error",
")",
"{",
"tx",
":=",
"e",
".",
"db",
".",
"Begin",
"(",
")",
"\n",
"d",
",",
"er... | // DomainsCreate adds a new Domain for an App. | [
"DomainsCreate",
"adds",
"a",
"new",
"Domain",
"for",
"an",
"App",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L381-L395 | train |
remind101/empire | empire.go | Tasks | func (e *Empire) Tasks(ctx context.Context, app *App) ([]*Task, error) {
return e.tasks.Tasks(ctx, app)
} | go | func (e *Empire) Tasks(ctx context.Context, app *App) ([]*Task, error) {
return e.tasks.Tasks(ctx, app)
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"Tasks",
"(",
"ctx",
"context",
".",
"Context",
",",
"app",
"*",
"App",
")",
"(",
"[",
"]",
"*",
"Task",
",",
"error",
")",
"{",
"return",
"e",
".",
"tasks",
".",
"Tasks",
"(",
"ctx",
",",
"app",
")",
"\n... | // Tasks returns the Tasks for the given app. | [
"Tasks",
"returns",
"the",
"Tasks",
"for",
"the",
"given",
"app",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L414-L416 | train |
remind101/empire | empire.go | Restart | func (e *Empire) Restart(ctx context.Context, opts RestartOpts) error {
if err := opts.Validate(e); err != nil {
return err
}
if err := e.apps.Restart(ctx, e.db, opts); err != nil {
return err
}
return e.PublishEvent(opts.Event())
} | go | func (e *Empire) Restart(ctx context.Context, opts RestartOpts) error {
if err := opts.Validate(e); err != nil {
return err
}
if err := e.apps.Restart(ctx, e.db, opts); err != nil {
return err
}
return e.PublishEvent(opts.Event())
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"Restart",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"RestartOpts",
")",
"error",
"{",
"if",
"err",
":=",
"opts",
".",
"Validate",
"(",
"e",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
... | // Restart restarts processes matching the given prefix for the given Release.
// If the prefix is empty, it will match all processes for the release. | [
"Restart",
"restarts",
"processes",
"matching",
"the",
"given",
"prefix",
"for",
"the",
"given",
"Release",
".",
"If",
"the",
"prefix",
"is",
"empty",
"it",
"will",
"match",
"all",
"processes",
"for",
"the",
"release",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L450-L461 | train |
remind101/empire | empire.go | Run | func (e *Empire) Run(ctx context.Context, opts RunOpts) error {
event := opts.Event()
if err := opts.Validate(e); err != nil {
return err
}
if e.RunRecorder != nil && (opts.Stdout != nil || opts.Stderr != nil) {
w, err := e.RunRecorder()
if err != nil {
return err
}
// Add the log url to the event, if there is one.
if w, ok := w.(interface {
URL() string
}); ok {
event.URL = w.URL()
}
msg := fmt.Sprintf("Running `%s` on %s as %s", opts.Command, opts.App.Name, opts.User.Name)
msg = appendCommitMessage(msg, opts.Message)
io.WriteString(w, fmt.Sprintf("%s\n", msg))
// Write output to both the original output as well as the
// record.
if opts.Stdout != nil {
opts.Stdout = io.MultiWriter(w, opts.Stdout)
}
if opts.Stderr != nil {
opts.Stderr = io.MultiWriter(w, opts.Stderr)
}
}
if err := e.PublishEvent(event); err != nil {
return err
}
if err := e.runner.Run(ctx, opts); err != nil {
return err
}
event.Finish()
return e.PublishEvent(event)
} | go | func (e *Empire) Run(ctx context.Context, opts RunOpts) error {
event := opts.Event()
if err := opts.Validate(e); err != nil {
return err
}
if e.RunRecorder != nil && (opts.Stdout != nil || opts.Stderr != nil) {
w, err := e.RunRecorder()
if err != nil {
return err
}
// Add the log url to the event, if there is one.
if w, ok := w.(interface {
URL() string
}); ok {
event.URL = w.URL()
}
msg := fmt.Sprintf("Running `%s` on %s as %s", opts.Command, opts.App.Name, opts.User.Name)
msg = appendCommitMessage(msg, opts.Message)
io.WriteString(w, fmt.Sprintf("%s\n", msg))
// Write output to both the original output as well as the
// record.
if opts.Stdout != nil {
opts.Stdout = io.MultiWriter(w, opts.Stdout)
}
if opts.Stderr != nil {
opts.Stderr = io.MultiWriter(w, opts.Stderr)
}
}
if err := e.PublishEvent(event); err != nil {
return err
}
if err := e.runner.Run(ctx, opts); err != nil {
return err
}
event.Finish()
return e.PublishEvent(event)
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"RunOpts",
")",
"error",
"{",
"event",
":=",
"opts",
".",
"Event",
"(",
")",
"\n",
"if",
"err",
":=",
"opts",
".",
"Validate",
"(",
"e",
")",
";",
... | // Run runs a one-off process for a given App and command. | [
"Run",
"runs",
"a",
"one",
"-",
"off",
"process",
"for",
"a",
"given",
"App",
"and",
"command",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L510-L554 | train |
remind101/empire | empire.go | Releases | func (e *Empire) Releases(q ReleasesQuery) ([]*Release, error) {
return releases(e.db, q)
} | go | func (e *Empire) Releases(q ReleasesQuery) ([]*Release, error) {
return releases(e.db, q)
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"Releases",
"(",
"q",
"ReleasesQuery",
")",
"(",
"[",
"]",
"*",
"Release",
",",
"error",
")",
"{",
"return",
"releases",
"(",
"e",
".",
"db",
",",
"q",
")",
"\n",
"}"
] | // Releases returns all Releases for a given App. | [
"Releases",
"returns",
"all",
"Releases",
"for",
"a",
"given",
"App",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L557-L559 | train |
remind101/empire | empire.go | ReleasesFind | func (e *Empire) ReleasesFind(q ReleasesQuery) (*Release, error) {
return releasesFind(e.db, q)
} | go | func (e *Empire) ReleasesFind(q ReleasesQuery) (*Release, error) {
return releasesFind(e.db, q)
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"ReleasesFind",
"(",
"q",
"ReleasesQuery",
")",
"(",
"*",
"Release",
",",
"error",
")",
"{",
"return",
"releasesFind",
"(",
"e",
".",
"db",
",",
"q",
")",
"\n",
"}"
] | // ReleasesFind returns the first releases for a given App. | [
"ReleasesFind",
"returns",
"the",
"first",
"releases",
"for",
"a",
"given",
"App",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L562-L564 | train |
remind101/empire | empire.go | Rollback | func (e *Empire) Rollback(ctx context.Context, opts RollbackOpts) (*Release, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
tx := e.db.Begin()
r, err := e.releases.Rollback(ctx, tx, opts)
if err != nil {
tx.Rollback()
return r, err
}
if err := tx.Commit().Error; err != nil {
return r, err
}
return r, e.PublishEvent(opts.Event())
} | go | func (e *Empire) Rollback(ctx context.Context, opts RollbackOpts) (*Release, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
tx := e.db.Begin()
r, err := e.releases.Rollback(ctx, tx, opts)
if err != nil {
tx.Rollback()
return r, err
}
if err := tx.Commit().Error; err != nil {
return r, err
}
return r, e.PublishEvent(opts.Event())
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"Rollback",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"RollbackOpts",
")",
"(",
"*",
"Release",
",",
"error",
")",
"{",
"if",
"err",
":=",
"opts",
".",
"Validate",
"(",
"e",
")",
";",
"err",
"!=",
"... | // Rollback rolls an app back to a specific release version. Returns a
// new release. | [
"Rollback",
"rolls",
"an",
"app",
"back",
"to",
"a",
"specific",
"release",
"version",
".",
"Returns",
"a",
"new",
"release",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L597-L615 | train |
remind101/empire | empire.go | Deploy | func (e *Empire) Deploy(ctx context.Context, opts DeployOpts) (*Release, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
r, err := e.deployer.Deploy(ctx, opts)
if err != nil {
return r, err
}
event := opts.Event()
event.Release = r.Version
event.Environment = e.Environment
// Deals with new app creation on first deploy
if event.App == "" && r.App != nil {
event.App = r.App.Name
event.app = r.App
}
return r, e.PublishEvent(event)
} | go | func (e *Empire) Deploy(ctx context.Context, opts DeployOpts) (*Release, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
r, err := e.deployer.Deploy(ctx, opts)
if err != nil {
return r, err
}
event := opts.Event()
event.Release = r.Version
event.Environment = e.Environment
// Deals with new app creation on first deploy
if event.App == "" && r.App != nil {
event.App = r.App.Name
event.app = r.App
}
return r, e.PublishEvent(event)
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"Deploy",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"DeployOpts",
")",
"(",
"*",
"Release",
",",
"error",
")",
"{",
"if",
"err",
":=",
"opts",
".",
"Validate",
"(",
"e",
")",
";",
"err",
"!=",
"nil"... | // Deploy deploys an image and streams the output to w. | [
"Deploy",
"deploys",
"an",
"image",
"and",
"streams",
"the",
"output",
"to",
"w",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L662-L682 | train |
remind101/empire | empire.go | Scale | func (e *Empire) Scale(ctx context.Context, opts ScaleOpts) ([]*Process, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
tx := e.db.Begin()
ps, err := e.apps.Scale(ctx, tx, opts)
if err != nil {
tx.Rollback()
return ps, err
}
return ps, tx.Commit().Error
} | go | func (e *Empire) Scale(ctx context.Context, opts ScaleOpts) ([]*Process, error) {
if err := opts.Validate(e); err != nil {
return nil, err
}
tx := e.db.Begin()
ps, err := e.apps.Scale(ctx, tx, opts)
if err != nil {
tx.Rollback()
return ps, err
}
return ps, tx.Commit().Error
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"Scale",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"ScaleOpts",
")",
"(",
"[",
"]",
"*",
"Process",
",",
"error",
")",
"{",
"if",
"err",
":=",
"opts",
".",
"Validate",
"(",
"e",
")",
";",
"err",
"... | // Scale scales an apps processes. | [
"Scale",
"scales",
"an",
"apps",
"processes",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L737-L751 | train |
remind101/empire | empire.go | ListScale | func (e *Empire) ListScale(ctx context.Context, app *App) (Formation, error) {
return currentFormation(e.db, app)
} | go | func (e *Empire) ListScale(ctx context.Context, app *App) (Formation, error) {
return currentFormation(e.db, app)
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"ListScale",
"(",
"ctx",
"context",
".",
"Context",
",",
"app",
"*",
"App",
")",
"(",
"Formation",
",",
"error",
")",
"{",
"return",
"currentFormation",
"(",
"e",
".",
"db",
",",
"app",
")",
"\n",
"}"
] | // ListScale lists the current scale settings for a given App | [
"ListScale",
"lists",
"the",
"current",
"scale",
"settings",
"for",
"a",
"given",
"App"
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L754-L756 | train |
remind101/empire | empire.go | StreamLogs | func (e *Empire) StreamLogs(app *App, w io.Writer, duration time.Duration) error {
if err := e.LogsStreamer.StreamLogs(app, w, duration); err != nil {
return fmt.Errorf("error streaming logs: %v", err)
}
return nil
} | go | func (e *Empire) StreamLogs(app *App, w io.Writer, duration time.Duration) error {
if err := e.LogsStreamer.StreamLogs(app, w, duration); err != nil {
return fmt.Errorf("error streaming logs: %v", err)
}
return nil
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"StreamLogs",
"(",
"app",
"*",
"App",
",",
"w",
"io",
".",
"Writer",
",",
"duration",
"time",
".",
"Duration",
")",
"error",
"{",
"if",
"err",
":=",
"e",
".",
"LogsStreamer",
".",
"StreamLogs",
"(",
"app",
",",... | // Streamlogs streams logs from an app. | [
"Streamlogs",
"streams",
"logs",
"from",
"an",
"app",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L759-L765 | train |
remind101/empire | empire.go | CertsAttach | func (e *Empire) CertsAttach(ctx context.Context, opts CertsAttachOpts) error {
tx := e.db.Begin()
if err := e.certs.CertsAttach(ctx, tx, opts); err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
} | go | func (e *Empire) CertsAttach(ctx context.Context, opts CertsAttachOpts) error {
tx := e.db.Begin()
if err := e.certs.CertsAttach(ctx, tx, opts); err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
} | [
"func",
"(",
"e",
"*",
"Empire",
")",
"CertsAttach",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"CertsAttachOpts",
")",
"error",
"{",
"tx",
":=",
"e",
".",
"db",
".",
"Begin",
"(",
")",
"\n",
"if",
"err",
":=",
"e",
".",
"certs",
".",
"C... | // CertsAttach attaches an SSL certificate to the app. | [
"CertsAttach",
"attaches",
"an",
"SSL",
"certificate",
"to",
"the",
"app",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/empire.go#L779-L788 | train |
remind101/empire | scheduler/cloudformation/clients.go | ecsWithCaching | func ecsWithCaching(ecs *ECS) *cachingECSClient {
return &cachingECSClient{
ecsClient: ecs,
taskDefinitions: cache.New(defaultExpiration, defaultPurge),
}
} | go | func ecsWithCaching(ecs *ECS) *cachingECSClient {
return &cachingECSClient{
ecsClient: ecs,
taskDefinitions: cache.New(defaultExpiration, defaultPurge),
}
} | [
"func",
"ecsWithCaching",
"(",
"ecs",
"*",
"ECS",
")",
"*",
"cachingECSClient",
"{",
"return",
"&",
"cachingECSClient",
"{",
"ecsClient",
":",
"ecs",
",",
"taskDefinitions",
":",
"cache",
".",
"New",
"(",
"defaultExpiration",
",",
"defaultPurge",
")",
",",
"... | // ecsWithCaching wraps an ecs.ECS client with caching. | [
"ecsWithCaching",
"wraps",
"an",
"ecs",
".",
"ECS",
"client",
"with",
"caching",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/clients.go#L34-L39 | train |
remind101/empire | scheduler/cloudformation/clients.go | DescribeTaskDefinition | func (c *cachingECSClient) DescribeTaskDefinition(input *ecs.DescribeTaskDefinitionInput) (*ecs.DescribeTaskDefinitionOutput, error) {
if _, err := arn.Parse(*input.TaskDefinition); err != nil {
return c.ecsClient.DescribeTaskDefinition(input)
}
if v, ok := c.taskDefinitions.Get(*input.TaskDefinition); ok {
return &ecs.DescribeTaskDefinitionOutput{
TaskDefinition: v.(*ecs.TaskDefinition),
}, nil
}
resp, err := c.ecsClient.DescribeTaskDefinition(input)
if err != nil {
return resp, err
}
c.taskDefinitions.Set(*resp.TaskDefinition.TaskDefinitionArn, resp.TaskDefinition, 0)
return resp, err
} | go | func (c *cachingECSClient) DescribeTaskDefinition(input *ecs.DescribeTaskDefinitionInput) (*ecs.DescribeTaskDefinitionOutput, error) {
if _, err := arn.Parse(*input.TaskDefinition); err != nil {
return c.ecsClient.DescribeTaskDefinition(input)
}
if v, ok := c.taskDefinitions.Get(*input.TaskDefinition); ok {
return &ecs.DescribeTaskDefinitionOutput{
TaskDefinition: v.(*ecs.TaskDefinition),
}, nil
}
resp, err := c.ecsClient.DescribeTaskDefinition(input)
if err != nil {
return resp, err
}
c.taskDefinitions.Set(*resp.TaskDefinition.TaskDefinitionArn, resp.TaskDefinition, 0)
return resp, err
} | [
"func",
"(",
"c",
"*",
"cachingECSClient",
")",
"DescribeTaskDefinition",
"(",
"input",
"*",
"ecs",
".",
"DescribeTaskDefinitionInput",
")",
"(",
"*",
"ecs",
".",
"DescribeTaskDefinitionOutput",
",",
"error",
")",
"{",
"if",
"_",
",",
"err",
":=",
"arn",
"."... | // DescribeTaskDefinition will use the task definition from cache if provided
// with a task definition ARN. | [
"DescribeTaskDefinition",
"will",
"use",
"the",
"task",
"definition",
"from",
"cache",
"if",
"provided",
"with",
"a",
"task",
"definition",
"ARN",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/clients.go#L43-L62 | train |
remind101/empire | scheduler/cloudformation/clients.go | WaitUntilTasksNotPending | func (c *ECS) WaitUntilTasksNotPending(input *ecs.DescribeTasksInput) error {
waiterCfg := awswaiter.Config{
Operation: "DescribeTasks",
Delay: 6,
MaxAttempts: 100,
Acceptors: []awswaiter.WaitAcceptor{
{
State: "failure",
Matcher: "pathAny",
Argument: "failures[].reason",
Expected: "MISSING",
},
{
State: "success",
Matcher: "pathAll",
Argument: "tasks[].lastStatus",
Expected: "RUNNING",
},
{
State: "success",
Matcher: "pathAll",
Argument: "tasks[].lastStatus",
Expected: "STOPPED",
},
},
}
w := awswaiter.Waiter{
Client: c.ECS,
Input: input,
Config: waiterCfg,
}
return w.Wait()
} | go | func (c *ECS) WaitUntilTasksNotPending(input *ecs.DescribeTasksInput) error {
waiterCfg := awswaiter.Config{
Operation: "DescribeTasks",
Delay: 6,
MaxAttempts: 100,
Acceptors: []awswaiter.WaitAcceptor{
{
State: "failure",
Matcher: "pathAny",
Argument: "failures[].reason",
Expected: "MISSING",
},
{
State: "success",
Matcher: "pathAll",
Argument: "tasks[].lastStatus",
Expected: "RUNNING",
},
{
State: "success",
Matcher: "pathAll",
Argument: "tasks[].lastStatus",
Expected: "STOPPED",
},
},
}
w := awswaiter.Waiter{
Client: c.ECS,
Input: input,
Config: waiterCfg,
}
return w.Wait()
} | [
"func",
"(",
"c",
"*",
"ECS",
")",
"WaitUntilTasksNotPending",
"(",
"input",
"*",
"ecs",
".",
"DescribeTasksInput",
")",
"error",
"{",
"waiterCfg",
":=",
"awswaiter",
".",
"Config",
"{",
"Operation",
":",
"\"DescribeTasks\"",
",",
"Delay",
":",
"6",
",",
"... | // WaitUntilTasksNotPending waits until all the given tasks are either RUNNING
// or STOPPED. | [
"WaitUntilTasksNotPending",
"waits",
"until",
"all",
"the",
"given",
"tasks",
"are",
"either",
"RUNNING",
"or",
"STOPPED",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/clients.go#L71-L104 | train |
remind101/empire | pkg/heroku/oauth_token.go | OAuthTokenCreate | func (c *Client) OAuthTokenCreate(grant OAuthTokenCreateGrant, client OAuthTokenCreateClient, refreshToken OAuthTokenCreateRefreshToken) (*OAuthToken, error) {
params := struct {
Grant OAuthTokenCreateGrant `json:"grant"`
Client OAuthTokenCreateClient `json:"client"`
RefreshToken OAuthTokenCreateRefreshToken `json:"refresh_token"`
}{
Grant: grant,
Client: client,
RefreshToken: refreshToken,
}
var oauthTokenRes OAuthToken
return &oauthTokenRes, c.Post(&oauthTokenRes, "/oauth/tokens", params)
} | go | func (c *Client) OAuthTokenCreate(grant OAuthTokenCreateGrant, client OAuthTokenCreateClient, refreshToken OAuthTokenCreateRefreshToken) (*OAuthToken, error) {
params := struct {
Grant OAuthTokenCreateGrant `json:"grant"`
Client OAuthTokenCreateClient `json:"client"`
RefreshToken OAuthTokenCreateRefreshToken `json:"refresh_token"`
}{
Grant: grant,
Client: client,
RefreshToken: refreshToken,
}
var oauthTokenRes OAuthToken
return &oauthTokenRes, c.Post(&oauthTokenRes, "/oauth/tokens", params)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OAuthTokenCreate",
"(",
"grant",
"OAuthTokenCreateGrant",
",",
"client",
"OAuthTokenCreateClient",
",",
"refreshToken",
"OAuthTokenCreateRefreshToken",
")",
"(",
"*",
"OAuthToken",
",",
"error",
")",
"{",
"params",
":=",
"str... | // Create a new OAuth token.
//
// grant is the grant used on the underlying authorization. client is the OAuth
// client secret used to obtain token. refreshToken is the refresh token for
// this authorization. | [
"Create",
"a",
"new",
"OAuth",
"token",
".",
"grant",
"is",
"the",
"grant",
"used",
"on",
"the",
"underlying",
"authorization",
".",
"client",
"is",
"the",
"OAuth",
"client",
"secret",
"used",
"to",
"obtain",
"token",
".",
"refreshToken",
"is",
"the",
"ref... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/oauth_token.go#L70-L82 | train |
remind101/empire | pkg/heroku/app_feature.go | AppFeatureInfo | func (c *Client) AppFeatureInfo(appIdentity string, appFeatureIdentity string) (*AppFeature, error) {
var appFeature AppFeature
return &appFeature, c.Get(&appFeature, "/apps/"+appIdentity+"/features/"+appFeatureIdentity)
} | go | func (c *Client) AppFeatureInfo(appIdentity string, appFeatureIdentity string) (*AppFeature, error) {
var appFeature AppFeature
return &appFeature, c.Get(&appFeature, "/apps/"+appIdentity+"/features/"+appFeatureIdentity)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AppFeatureInfo",
"(",
"appIdentity",
"string",
",",
"appFeatureIdentity",
"string",
")",
"(",
"*",
"AppFeature",
",",
"error",
")",
"{",
"var",
"appFeature",
"AppFeature",
"\n",
"return",
"&",
"appFeature",
",",
"c",
... | // Info for an existing app feature.
//
// appIdentity is the unique identifier of the AppFeature's App.
// appFeatureIdentity is the unique identifier of the AppFeature. | [
"Info",
"for",
"an",
"existing",
"app",
"feature",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"AppFeature",
"s",
"App",
".",
"appFeatureIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"AppFeature",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/app_feature.go#L43-L46 | train |
remind101/empire | pkg/heroku/app_feature.go | AppFeatureList | func (c *Client) AppFeatureList(appIdentity string, lr *ListRange) ([]AppFeature, error) {
req, err := c.NewRequest("GET", "/apps/"+appIdentity+"/features", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var appFeaturesRes []AppFeature
return appFeaturesRes, c.DoReq(req, &appFeaturesRes)
} | go | func (c *Client) AppFeatureList(appIdentity string, lr *ListRange) ([]AppFeature, error) {
req, err := c.NewRequest("GET", "/apps/"+appIdentity+"/features", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var appFeaturesRes []AppFeature
return appFeaturesRes, c.DoReq(req, &appFeaturesRes)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AppFeatureList",
"(",
"appIdentity",
"string",
",",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"AppFeature",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"GET\"",
",",
"\"/app... | // List existing app features.
//
// appIdentity is the unique identifier of the AppFeature's App. lr is an
// optional ListRange that sets the Range options for the paginated list of
// results. | [
"List",
"existing",
"app",
"features",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"AppFeature",
"s",
"App",
".",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"for",
"the",
"paginated",
"list... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/app_feature.go#L53-L65 | train |
remind101/empire | pkg/heroku/app_feature.go | AppFeatureUpdate | func (c *Client) AppFeatureUpdate(appIdentity string, appFeatureIdentity string, enabled bool) (*AppFeature, error) {
params := struct {
Enabled bool `json:"enabled"`
}{
Enabled: enabled,
}
var appFeatureRes AppFeature
return &appFeatureRes, c.Patch(&appFeatureRes, "/apps/"+appIdentity+"/features/"+appFeatureIdentity, params)
} | go | func (c *Client) AppFeatureUpdate(appIdentity string, appFeatureIdentity string, enabled bool) (*AppFeature, error) {
params := struct {
Enabled bool `json:"enabled"`
}{
Enabled: enabled,
}
var appFeatureRes AppFeature
return &appFeatureRes, c.Patch(&appFeatureRes, "/apps/"+appIdentity+"/features/"+appFeatureIdentity, params)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AppFeatureUpdate",
"(",
"appIdentity",
"string",
",",
"appFeatureIdentity",
"string",
",",
"enabled",
"bool",
")",
"(",
"*",
"AppFeature",
",",
"error",
")",
"{",
"params",
":=",
"struct",
"{",
"Enabled",
"bool",
"`js... | // Update an existing app feature.
//
// appIdentity is the unique identifier of the AppFeature's App.
// appFeatureIdentity is the unique identifier of the AppFeature. enabled is the
// whether or not app feature has been enabled. | [
"Update",
"an",
"existing",
"app",
"feature",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"AppFeature",
"s",
"App",
".",
"appFeatureIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"AppFeature",
".",
"enabled",
"is",
"the"... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/app_feature.go#L72-L80 | train |
remind101/empire | server/middleware/request.go | WithRequest | func WithRequest(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = httpx.WithRequest(ctx, r)
// Add the request to the context.
reporter.AddRequest(ctx, r)
// Add the request id
reporter.AddContext(ctx, "request_id", httpx.RequestID(ctx))
h.ServeHTTP(w, r.WithContext(ctx))
})
} | go | func WithRequest(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = httpx.WithRequest(ctx, r)
// Add the request to the context.
reporter.AddRequest(ctx, r)
// Add the request id
reporter.AddContext(ctx, "request_id", httpx.RequestID(ctx))
h.ServeHTTP(w, r.WithContext(ctx))
})
} | [
"func",
"WithRequest",
"(",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"ctx",
":=",
"r",
... | // WithRequest adds information about the http.Request to reported errors. | [
"WithRequest",
"adds",
"information",
"about",
"the",
"http",
".",
"Request",
"to",
"reported",
"errors",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/middleware/request.go#L11-L25 | train |
remind101/empire | pkg/troposphere/troposphere.go | NewTemplate | func NewTemplate() *Template {
return &Template{
Conditions: make(map[string]interface{}),
Outputs: make(map[string]Output),
Parameters: make(map[string]Parameter),
Resources: make(map[string]Resource),
}
} | go | func NewTemplate() *Template {
return &Template{
Conditions: make(map[string]interface{}),
Outputs: make(map[string]Output),
Parameters: make(map[string]Parameter),
Resources: make(map[string]Resource),
}
} | [
"func",
"NewTemplate",
"(",
")",
"*",
"Template",
"{",
"return",
"&",
"Template",
"{",
"Conditions",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
",",
"Outputs",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"Output",
")",
... | // NewTemplate returns an initialized Template. | [
"NewTemplate",
"returns",
"an",
"initialized",
"Template",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/troposphere/troposphere.go#L16-L23 | train |
remind101/empire | pkg/troposphere/troposphere.go | AddResource | func (t *Template) AddResource(resource NamedResource) {
if _, ok := t.Resources[resource.Name]; ok {
panic(fmt.Sprintf("%s is already defined in the template", resource.Name))
}
t.Resources[resource.Name] = resource.Resource
} | go | func (t *Template) AddResource(resource NamedResource) {
if _, ok := t.Resources[resource.Name]; ok {
panic(fmt.Sprintf("%s is already defined in the template", resource.Name))
}
t.Resources[resource.Name] = resource.Resource
} | [
"func",
"(",
"t",
"*",
"Template",
")",
"AddResource",
"(",
"resource",
"NamedResource",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"t",
".",
"Resources",
"[",
"resource",
".",
"Name",
"]",
";",
"ok",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s... | // AddResource adds a named resource to the template. | [
"AddResource",
"adds",
"a",
"named",
"resource",
"to",
"the",
"template",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/troposphere/troposphere.go#L26-L31 | train |
remind101/empire | pkg/arn/arn.go | Parse | func Parse(arn string) (*ARN, error) {
p := strings.SplitN(arn, delimiter, 6)
// Ensure that we have all the components that make up an ARN.
if len(p) < 6 {
return nil, ErrInvalidARN
}
a := &ARN{
ARN: p[0],
AWS: p[1],
Service: p[2],
Region: p[3],
Account: p[4],
Resource: p[5],
}
// ARN's always start with "arn:aws" (hopefully).
if a.ARN != "arn" || a.AWS != "aws" {
return nil, ErrInvalidARN
}
return a, nil
} | go | func Parse(arn string) (*ARN, error) {
p := strings.SplitN(arn, delimiter, 6)
// Ensure that we have all the components that make up an ARN.
if len(p) < 6 {
return nil, ErrInvalidARN
}
a := &ARN{
ARN: p[0],
AWS: p[1],
Service: p[2],
Region: p[3],
Account: p[4],
Resource: p[5],
}
// ARN's always start with "arn:aws" (hopefully).
if a.ARN != "arn" || a.AWS != "aws" {
return nil, ErrInvalidARN
}
return a, nil
} | [
"func",
"Parse",
"(",
"arn",
"string",
")",
"(",
"*",
"ARN",
",",
"error",
")",
"{",
"p",
":=",
"strings",
".",
"SplitN",
"(",
"arn",
",",
"delimiter",
",",
"6",
")",
"\n",
"if",
"len",
"(",
"p",
")",
"<",
"6",
"{",
"return",
"nil",
",",
"Err... | // Parse parses an Amazon Resource Name from a String into an ARN. | [
"Parse",
"parses",
"an",
"Amazon",
"Resource",
"Name",
"from",
"a",
"String",
"into",
"an",
"ARN",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/arn/arn.go#L30-L53 | train |
remind101/empire | pkg/arn/arn.go | String | func (a *ARN) String() string {
return strings.Join(
[]string{a.ARN, a.AWS, a.Service, a.Region, a.Account, a.Resource},
delimiter,
)
} | go | func (a *ARN) String() string {
return strings.Join(
[]string{a.ARN, a.AWS, a.Service, a.Region, a.Account, a.Resource},
delimiter,
)
} | [
"func",
"(",
"a",
"*",
"ARN",
")",
"String",
"(",
")",
"string",
"{",
"return",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"a",
".",
"ARN",
",",
"a",
".",
"AWS",
",",
"a",
".",
"Service",
",",
"a",
".",
"Region",
",",
"a",
".",
"... | // String returns the string representation of an Amazon Resource Name. | [
"String",
"returns",
"the",
"string",
"representation",
"of",
"an",
"Amazon",
"Resource",
"Name",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/arn/arn.go#L56-L61 | train |
remind101/empire | pkg/arn/arn.go | SplitResource | func SplitResource(r string) (resource, id string, err error) {
p := strings.Split(r, "/")
if len(p) != 2 {
err = ErrInvalidResource
return
}
resource = p[0]
id = p[1]
return
} | go | func SplitResource(r string) (resource, id string, err error) {
p := strings.Split(r, "/")
if len(p) != 2 {
err = ErrInvalidResource
return
}
resource = p[0]
id = p[1]
return
} | [
"func",
"SplitResource",
"(",
"r",
"string",
")",
"(",
"resource",
",",
"id",
"string",
",",
"err",
"error",
")",
"{",
"p",
":=",
"strings",
".",
"Split",
"(",
"r",
",",
"\"/\"",
")",
"\n",
"if",
"len",
"(",
"p",
")",
"!=",
"2",
"{",
"err",
"="... | // SplitResource splits the Resource section of an ARN into its type and id
// components. | [
"SplitResource",
"splits",
"the",
"Resource",
"section",
"of",
"an",
"ARN",
"into",
"its",
"type",
"and",
"id",
"components",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/arn/arn.go#L65-L77 | train |
remind101/empire | pkg/arn/arn.go | ResourceID | func ResourceID(arn string) (string, error) {
a, err := Parse(arn)
if err != nil {
return "", err
}
_, id, err := SplitResource(a.Resource)
return id, err
} | go | func ResourceID(arn string) (string, error) {
a, err := Parse(arn)
if err != nil {
return "", err
}
_, id, err := SplitResource(a.Resource)
return id, err
} | [
"func",
"ResourceID",
"(",
"arn",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"a",
",",
"err",
":=",
"Parse",
"(",
"arn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"_",
",",
"id",
",",
... | // ResourceID takes an ARN string and returns the resource ID from it. | [
"ResourceID",
"takes",
"an",
"ARN",
"string",
"and",
"returns",
"the",
"resource",
"ID",
"from",
"it",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/arn/arn.go#L80-L88 | train |
remind101/empire | server/middleware/middleware.go | LogRequests | func LogRequests(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logger.Info(ctx, "request.start",
"method", r.Method,
"path", r.URL.Path,
"user_agent", r.Header.Get("User-Agent"),
"remote_ip", realip.RealIP(r),
)
h.ServeHTTP(w, r)
logger.Info(ctx, "request.complete")
})
} | go | func LogRequests(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
logger.Info(ctx, "request.start",
"method", r.Method,
"path", r.URL.Path,
"user_agent", r.Header.Get("User-Agent"),
"remote_ip", realip.RealIP(r),
)
h.ServeHTTP(w, r)
logger.Info(ctx, "request.complete")
})
} | [
"func",
"LogRequests",
"(",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"ctx",
":=",
"r",
... | // LogRequests logs the requests to the embedded logger. | [
"LogRequests",
"logs",
"the",
"requests",
"to",
"the",
"embedded",
"logger",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/middleware/middleware.go#L32-L46 | train |
remind101/empire | server/middleware/middleware.go | PrefixRequestID | func PrefixRequestID(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if l, ok := logger.FromContext(ctx); ok {
if l, ok := l.(log15.Logger); ok {
ctx = logger.WithLogger(ctx, l.New("request_id", httpx.RequestID(ctx)))
}
}
h.ServeHTTP(w, r.WithContext(ctx))
})
} | go | func PrefixRequestID(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if l, ok := logger.FromContext(ctx); ok {
if l, ok := l.(log15.Logger); ok {
ctx = logger.WithLogger(ctx, l.New("request_id", httpx.RequestID(ctx)))
}
}
h.ServeHTTP(w, r.WithContext(ctx))
})
} | [
"func",
"PrefixRequestID",
"(",
"h",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"ctx",
":=",
"... | // PrefixRequestID adds the request as a prefix to the log15.Logger. | [
"PrefixRequestID",
"adds",
"the",
"request",
"as",
"a",
"prefix",
"to",
"the",
"log15",
".",
"Logger",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/middleware/middleware.go#L49-L61 | train |
remind101/empire | stats/dogstatsd.go | NewDogstatsd | func NewDogstatsd(addr string) (*Dogstatsd, error) {
c, err := statsd.New(addr)
if err != nil {
return nil, err
}
return &Dogstatsd{
Client: c,
}, nil
} | go | func NewDogstatsd(addr string) (*Dogstatsd, error) {
c, err := statsd.New(addr)
if err != nil {
return nil, err
}
return &Dogstatsd{
Client: c,
}, nil
} | [
"func",
"NewDogstatsd",
"(",
"addr",
"string",
")",
"(",
"*",
"Dogstatsd",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"statsd",
".",
"New",
"(",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
... | // NewDogstatsd returns a new Dogstatsd instance that sends statsd metrics to addr. | [
"NewDogstatsd",
"returns",
"a",
"new",
"Dogstatsd",
"instance",
"that",
"sends",
"statsd",
"metrics",
"to",
"addr",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/stats/dogstatsd.go#L16-L25 | train |
remind101/empire | pkg/heroku/collaborator.go | CollaboratorCreate | func (c *Client) CollaboratorCreate(appIdentity string, user string, options *CollaboratorCreateOpts) (*Collaborator, error) {
params := struct {
User string `json:"user"`
Silent *bool `json:"silent,omitempty"`
}{
User: user,
}
if options != nil {
params.Silent = options.Silent
}
var collaboratorRes Collaborator
return &collaboratorRes, c.Post(&collaboratorRes, "/apps/"+appIdentity+"/collaborators", params)
} | go | func (c *Client) CollaboratorCreate(appIdentity string, user string, options *CollaboratorCreateOpts) (*Collaborator, error) {
params := struct {
User string `json:"user"`
Silent *bool `json:"silent,omitempty"`
}{
User: user,
}
if options != nil {
params.Silent = options.Silent
}
var collaboratorRes Collaborator
return &collaboratorRes, c.Post(&collaboratorRes, "/apps/"+appIdentity+"/collaborators", params)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"CollaboratorCreate",
"(",
"appIdentity",
"string",
",",
"user",
"string",
",",
"options",
"*",
"CollaboratorCreateOpts",
")",
"(",
"*",
"Collaborator",
",",
"error",
")",
"{",
"params",
":=",
"struct",
"{",
"User",
"s... | // Create a new collaborator.
//
// appIdentity is the unique identifier of the Collaborator's App. user is the
// unique email address of account or unique identifier of an account. options
// is the struct of optional parameters for this action. | [
"Create",
"a",
"new",
"collaborator",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Collaborator",
"s",
"App",
".",
"user",
"is",
"the",
"unique",
"email",
"address",
"of",
"account",
"or",
"unique",
"identifier",
"of",
"an",
"accoun... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/collaborator.go#L35-L47 | train |
remind101/empire | pkg/heroku/collaborator.go | CollaboratorDelete | func (c *Client) CollaboratorDelete(appIdentity string, collaboratorIdentity string) error {
return c.Delete("/apps/" + appIdentity + "/collaborators/" + collaboratorIdentity)
} | go | func (c *Client) CollaboratorDelete(appIdentity string, collaboratorIdentity string) error {
return c.Delete("/apps/" + appIdentity + "/collaborators/" + collaboratorIdentity)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"CollaboratorDelete",
"(",
"appIdentity",
"string",
",",
"collaboratorIdentity",
"string",
")",
"error",
"{",
"return",
"c",
".",
"Delete",
"(",
"\"/apps/\"",
"+",
"appIdentity",
"+",
"\"/collaborators/\"",
"+",
"collaborato... | // Delete an existing collaborator.
//
// appIdentity is the unique identifier of the Collaborator's App.
// collaboratorIdentity is the unique identifier of the Collaborator. | [
"Delete",
"an",
"existing",
"collaborator",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Collaborator",
"s",
"App",
".",
"collaboratorIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Collaborator",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/collaborator.go#L59-L61 | train |
remind101/empire | pkg/heroku/collaborator.go | CollaboratorInfo | func (c *Client) CollaboratorInfo(appIdentity string, collaboratorIdentity string) (*Collaborator, error) {
var collaborator Collaborator
return &collaborator, c.Get(&collaborator, "/apps/"+appIdentity+"/collaborators/"+collaboratorIdentity)
} | go | func (c *Client) CollaboratorInfo(appIdentity string, collaboratorIdentity string) (*Collaborator, error) {
var collaborator Collaborator
return &collaborator, c.Get(&collaborator, "/apps/"+appIdentity+"/collaborators/"+collaboratorIdentity)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"CollaboratorInfo",
"(",
"appIdentity",
"string",
",",
"collaboratorIdentity",
"string",
")",
"(",
"*",
"Collaborator",
",",
"error",
")",
"{",
"var",
"collaborator",
"Collaborator",
"\n",
"return",
"&",
"collaborator",
",... | // Info for existing collaborator.
//
// appIdentity is the unique identifier of the Collaborator's App.
// collaboratorIdentity is the unique identifier of the Collaborator. | [
"Info",
"for",
"existing",
"collaborator",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Collaborator",
"s",
"App",
".",
"collaboratorIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Collaborator",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/collaborator.go#L67-L70 | train |
remind101/empire | pkg/heroku/collaborator.go | CollaboratorList | func (c *Client) CollaboratorList(appIdentity string, lr *ListRange) ([]Collaborator, error) {
req, err := c.NewRequest("GET", "/apps/"+appIdentity+"/collaborators", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var collaboratorsRes []Collaborator
return collaboratorsRes, c.DoReq(req, &collaboratorsRes)
} | go | func (c *Client) CollaboratorList(appIdentity string, lr *ListRange) ([]Collaborator, error) {
req, err := c.NewRequest("GET", "/apps/"+appIdentity+"/collaborators", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var collaboratorsRes []Collaborator
return collaboratorsRes, c.DoReq(req, &collaboratorsRes)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"CollaboratorList",
"(",
"appIdentity",
"string",
",",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"Collaborator",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"GET\"",
",",
"\"... | // List existing collaborators.
//
// appIdentity is the unique identifier of the Collaborator's App. lr is an
// optional ListRange that sets the Range options for the paginated list of
// results. | [
"List",
"existing",
"collaborators",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Collaborator",
"s",
"App",
".",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"for",
"the",
"paginated",
"list",... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/collaborator.go#L77-L89 | train |
remind101/empire | pkg/heroku/slug.go | SlugInfo | func (c *Client) SlugInfo(appIdentity string, slugIdentity string) (*Slug, error) {
var slug Slug
return &slug, c.Get(&slug, "/apps/"+appIdentity+"/slugs/"+slugIdentity)
} | go | func (c *Client) SlugInfo(appIdentity string, slugIdentity string) (*Slug, error) {
var slug Slug
return &slug, c.Get(&slug, "/apps/"+appIdentity+"/slugs/"+slugIdentity)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SlugInfo",
"(",
"appIdentity",
"string",
",",
"slugIdentity",
"string",
")",
"(",
"*",
"Slug",
",",
"error",
")",
"{",
"var",
"slug",
"Slug",
"\n",
"return",
"&",
"slug",
",",
"c",
".",
"Get",
"(",
"&",
"slug"... | // Info for existing slug.
//
// appIdentity is the unique identifier of the Slug's App. slugIdentity is the
// unique identifier of the Slug. | [
"Info",
"for",
"existing",
"slug",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Slug",
"s",
"App",
".",
"slugIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Slug",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/slug.go#L46-L49 | train |
remind101/empire | pkg/heroku/slug.go | SlugCreate | func (c *Client) SlugCreate(appIdentity string, processTypes map[string]string, options *SlugCreateOpts) (*Slug, error) {
params := struct {
ProcessTypes map[string]string `json:"process_types"`
BuildpackProvidedDescription *string `json:"buildpack_provided_description,omitempty"`
Commit *string `json:"commit,omitempty"`
}{
ProcessTypes: processTypes,
}
if options != nil {
params.BuildpackProvidedDescription = options.BuildpackProvidedDescription
params.Commit = options.Commit
}
var slugRes Slug
return &slugRes, c.Post(&slugRes, "/apps/"+appIdentity+"/slugs", params)
} | go | func (c *Client) SlugCreate(appIdentity string, processTypes map[string]string, options *SlugCreateOpts) (*Slug, error) {
params := struct {
ProcessTypes map[string]string `json:"process_types"`
BuildpackProvidedDescription *string `json:"buildpack_provided_description,omitempty"`
Commit *string `json:"commit,omitempty"`
}{
ProcessTypes: processTypes,
}
if options != nil {
params.BuildpackProvidedDescription = options.BuildpackProvidedDescription
params.Commit = options.Commit
}
var slugRes Slug
return &slugRes, c.Post(&slugRes, "/apps/"+appIdentity+"/slugs", params)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SlugCreate",
"(",
"appIdentity",
"string",
",",
"processTypes",
"map",
"[",
"string",
"]",
"string",
",",
"options",
"*",
"SlugCreateOpts",
")",
"(",
"*",
"Slug",
",",
"error",
")",
"{",
"params",
":=",
"struct",
... | // Create a new slug. For more information please refer to Deploying Slugs using
// the Platform API.
//
// appIdentity is the unique identifier of the Slug's App. processTypes is the
// hash mapping process type names to their respective command. options is the
// struct of optional parameters for this action. | [
"Create",
"a",
"new",
"slug",
".",
"For",
"more",
"information",
"please",
"refer",
"to",
"Deploying",
"Slugs",
"using",
"the",
"Platform",
"API",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Slug",
"s",
"App",
".",
"processTypes",
... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/slug.go#L57-L71 | train |
remind101/empire | pkg/dockerutil/client.go | NewDockerClient | func NewDockerClient(host, certPath string) (*docker.Client, error) {
if certPath != "" {
cert := certPath + "/cert.pem"
key := certPath + "/key.pem"
ca := certPath + "/ca.pem"
return docker.NewTLSClient(host, cert, key, ca)
}
return docker.NewClient(host)
} | go | func NewDockerClient(host, certPath string) (*docker.Client, error) {
if certPath != "" {
cert := certPath + "/cert.pem"
key := certPath + "/key.pem"
ca := certPath + "/ca.pem"
return docker.NewTLSClient(host, cert, key, ca)
}
return docker.NewClient(host)
} | [
"func",
"NewDockerClient",
"(",
"host",
",",
"certPath",
"string",
")",
"(",
"*",
"docker",
".",
"Client",
",",
"error",
")",
"{",
"if",
"certPath",
"!=",
"\"\"",
"{",
"cert",
":=",
"certPath",
"+",
"\"/cert.pem\"",
"\n",
"key",
":=",
"certPath",
"+",
... | // NewDockerClient returns a new docker.Client using the given host and certificate path. | [
"NewDockerClient",
"returns",
"a",
"new",
"docker",
".",
"Client",
"using",
"the",
"given",
"host",
"and",
"certificate",
"path",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/dockerutil/client.go#L17-L26 | train |
remind101/empire | pkg/dockerutil/client.go | NewClient | func NewClient(authProvider dockerauth.AuthProvider, host, certPath string) (*Client, error) {
c, err := NewDockerClient(host, certPath)
if err != nil {
return nil, err
}
return newClient(authProvider, c)
} | go | func NewClient(authProvider dockerauth.AuthProvider, host, certPath string) (*Client, error) {
c, err := NewDockerClient(host, certPath)
if err != nil {
return nil, err
}
return newClient(authProvider, c)
} | [
"func",
"NewClient",
"(",
"authProvider",
"dockerauth",
".",
"AuthProvider",
",",
"host",
",",
"certPath",
"string",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"NewDockerClient",
"(",
"host",
",",
"certPath",
")",
"\n",
"if",... | // NewClient returns a new Client instance. | [
"NewClient",
"returns",
"a",
"new",
"Client",
"instance",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/dockerutil/client.go#L40-L46 | train |
remind101/empire | pkg/dockerutil/client.go | PullImage | func (c *Client) PullImage(ctx context.Context, opts docker.PullImageOptions) error {
// This is to workaround an issue in the Docker API, where it doesn't
// respect the registry param. We have to put the registry in the
// repository field.
if opts.Registry != "" {
opts.Repository = fmt.Sprintf("%s/%s", opts.Registry, opts.Repository)
}
authConf, err := authConfiguration(c.AuthProvider, opts.Registry)
if err != nil {
return err
}
return c.Client.PullImage(opts, authConf)
} | go | func (c *Client) PullImage(ctx context.Context, opts docker.PullImageOptions) error {
// This is to workaround an issue in the Docker API, where it doesn't
// respect the registry param. We have to put the registry in the
// repository field.
if opts.Registry != "" {
opts.Repository = fmt.Sprintf("%s/%s", opts.Registry, opts.Repository)
}
authConf, err := authConfiguration(c.AuthProvider, opts.Registry)
if err != nil {
return err
}
return c.Client.PullImage(opts, authConf)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"PullImage",
"(",
"ctx",
"context",
".",
"Context",
",",
"opts",
"docker",
".",
"PullImageOptions",
")",
"error",
"{",
"if",
"opts",
".",
"Registry",
"!=",
"\"\"",
"{",
"opts",
".",
"Repository",
"=",
"fmt",
".",
... | // PullImage wraps the docker clients PullImage to handle authentication. | [
"PullImage",
"wraps",
"the",
"docker",
"clients",
"PullImage",
"to",
"handle",
"authentication",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/dockerutil/client.go#L71-L85 | train |
remind101/empire | pkg/heroku/addon_service.go | AddonServiceInfo | func (c *Client) AddonServiceInfo(addonServiceIdentity string) (*AddonService, error) {
var addonService AddonService
return &addonService, c.Get(&addonService, "/addon-services/"+addonServiceIdentity)
} | go | func (c *Client) AddonServiceInfo(addonServiceIdentity string) (*AddonService, error) {
var addonService AddonService
return &addonService, c.Get(&addonService, "/addon-services/"+addonServiceIdentity)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AddonServiceInfo",
"(",
"addonServiceIdentity",
"string",
")",
"(",
"*",
"AddonService",
",",
"error",
")",
"{",
"var",
"addonService",
"AddonService",
"\n",
"return",
"&",
"addonService",
",",
"c",
".",
"Get",
"(",
"... | // Info for existing addon-service.
//
// addonServiceIdentity is the unique identifier of the AddonService. | [
"Info",
"for",
"existing",
"addon",
"-",
"service",
".",
"addonServiceIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"AddonService",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/addon_service.go#L29-L32 | train |
remind101/empire | pkg/heroku/addon_service.go | AddonServiceList | func (c *Client) AddonServiceList(lr *ListRange) ([]AddonService, error) {
req, err := c.NewRequest("GET", "/addon-services", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var addonServicesRes []AddonService
return addonServicesRes, c.DoReq(req, &addonServicesRes)
} | go | func (c *Client) AddonServiceList(lr *ListRange) ([]AddonService, error) {
req, err := c.NewRequest("GET", "/addon-services", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var addonServicesRes []AddonService
return addonServicesRes, c.DoReq(req, &addonServicesRes)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"AddonServiceList",
"(",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"AddonService",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"GET\"",
",",
"\"/addon-services\"",
",",
"nil",
... | // List existing addon-services.
//
// lr is an optional ListRange that sets the Range options for the paginated
// list of results. | [
"List",
"existing",
"addon",
"-",
"services",
".",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"for",
"the",
"paginated",
"list",
"of",
"results",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/addon_service.go#L38-L50 | train |
remind101/empire | procfile/procfile.go | ParsePort | func ParsePort(s string) (p Port, err error) {
if strings.Contains(s, ":") {
return portFromHostContainer(s)
}
var port int
port, err = toPort(s)
if err != nil {
return
}
p.Host = port
p.Container = port
return
} | go | func ParsePort(s string) (p Port, err error) {
if strings.Contains(s, ":") {
return portFromHostContainer(s)
}
var port int
port, err = toPort(s)
if err != nil {
return
}
p.Host = port
p.Container = port
return
} | [
"func",
"ParsePort",
"(",
"s",
"string",
")",
"(",
"p",
"Port",
",",
"err",
"error",
")",
"{",
"if",
"strings",
".",
"Contains",
"(",
"s",
",",
"\":\"",
")",
"{",
"return",
"portFromHostContainer",
"(",
"s",
")",
"\n",
"}",
"\n",
"var",
"port",
"in... | // ParsePort parses a string into a Port. | [
"ParsePort",
"parses",
"a",
"string",
"into",
"a",
"Port",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/procfile/procfile.go#L51-L64 | train |
remind101/empire | procfile/procfile.go | Parse | func Parse(r io.Reader) (Procfile, error) {
raw, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
return ParseProcfile(raw)
} | go | func Parse(r io.Reader) (Procfile, error) {
raw, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
return ParseProcfile(raw)
} | [
"func",
"Parse",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"Procfile",
",",
"error",
")",
"{",
"raw",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
... | // Parse parses the Procfile by reading from r. | [
"Parse",
"parses",
"the",
"Procfile",
"by",
"reading",
"from",
"r",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/procfile/procfile.go#L139-L146 | train |
remind101/empire | procfile/procfile.go | ParseProcfile | func ParseProcfile(b []byte) (Procfile, error) {
p, err := parseStandardProcfile(b)
if err != nil {
p, err = parseExtendedProcfile(b)
}
return p, err
} | go | func ParseProcfile(b []byte) (Procfile, error) {
p, err := parseStandardProcfile(b)
if err != nil {
p, err = parseExtendedProcfile(b)
}
return p, err
} | [
"func",
"ParseProcfile",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"Procfile",
",",
"error",
")",
"{",
"p",
",",
"err",
":=",
"parseStandardProcfile",
"(",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"p",
",",
"err",
"=",
"parseExtendedProcfile",
"(",... | // ParseProcfile takes a byte slice representing a YAML Procfile and parses it
// into a Procfile. | [
"ParseProcfile",
"takes",
"a",
"byte",
"slice",
"representing",
"a",
"YAML",
"Procfile",
"and",
"parses",
"it",
"into",
"a",
"Procfile",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/procfile/procfile.go#L150-L156 | train |
remind101/empire | pkg/heroku/oauth_client.go | OAuthClientCreate | func (c *Client) OAuthClientCreate(name string, redirectUri string) (*OAuthClient, error) {
params := struct {
Name string `json:"name"`
RedirectUri string `json:"redirect_uri"`
}{
Name: name,
RedirectUri: redirectUri,
}
var oauthClientRes OAuthClient
return &oauthClientRes, c.Post(&oauthClientRes, "/oauth/clients", params)
} | go | func (c *Client) OAuthClientCreate(name string, redirectUri string) (*OAuthClient, error) {
params := struct {
Name string `json:"name"`
RedirectUri string `json:"redirect_uri"`
}{
Name: name,
RedirectUri: redirectUri,
}
var oauthClientRes OAuthClient
return &oauthClientRes, c.Post(&oauthClientRes, "/oauth/clients", params)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OAuthClientCreate",
"(",
"name",
"string",
",",
"redirectUri",
"string",
")",
"(",
"*",
"OAuthClient",
",",
"error",
")",
"{",
"params",
":=",
"struct",
"{",
"Name",
"string",
"`json:\"name\"`",
"\n",
"RedirectUri",
"... | // Create a new OAuth client.
//
// name is the OAuth client name. redirectUri is the endpoint for redirection
// after authorization with OAuth client. | [
"Create",
"a",
"new",
"OAuth",
"client",
".",
"name",
"is",
"the",
"OAuth",
"client",
"name",
".",
"redirectUri",
"is",
"the",
"endpoint",
"for",
"redirection",
"after",
"authorization",
"with",
"OAuth",
"client",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/oauth_client.go#L41-L51 | train |
remind101/empire | pkg/heroku/oauth_client.go | OAuthClientInfo | func (c *Client) OAuthClientInfo(oauthClientIdentity string) (*OAuthClient, error) {
var oauthClient OAuthClient
return &oauthClient, c.Get(&oauthClient, "/oauth/clients/"+oauthClientIdentity)
} | go | func (c *Client) OAuthClientInfo(oauthClientIdentity string) (*OAuthClient, error) {
var oauthClient OAuthClient
return &oauthClient, c.Get(&oauthClient, "/oauth/clients/"+oauthClientIdentity)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OAuthClientInfo",
"(",
"oauthClientIdentity",
"string",
")",
"(",
"*",
"OAuthClient",
",",
"error",
")",
"{",
"var",
"oauthClient",
"OAuthClient",
"\n",
"return",
"&",
"oauthClient",
",",
"c",
".",
"Get",
"(",
"&",
... | // Info for an OAuth client
//
// oauthClientIdentity is the unique identifier of the OAuthClient. | [
"Info",
"for",
"an",
"OAuth",
"client",
"oauthClientIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OAuthClient",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/oauth_client.go#L63-L66 | train |
remind101/empire | pkg/heroku/oauth_client.go | OAuthClientList | func (c *Client) OAuthClientList(lr *ListRange) ([]OAuthClient, error) {
req, err := c.NewRequest("GET", "/oauth/clients", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var oauthClientsRes []OAuthClient
return oauthClientsRes, c.DoReq(req, &oauthClientsRes)
} | go | func (c *Client) OAuthClientList(lr *ListRange) ([]OAuthClient, error) {
req, err := c.NewRequest("GET", "/oauth/clients", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var oauthClientsRes []OAuthClient
return oauthClientsRes, c.DoReq(req, &oauthClientsRes)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OAuthClientList",
"(",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"OAuthClient",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"GET\"",
",",
"\"/oauth/clients\"",
",",
"nil",
"... | // List OAuth clients
//
// lr is an optional ListRange that sets the Range options for the paginated
// list of results. | [
"List",
"OAuth",
"clients",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"for",
"the",
"paginated",
"list",
"of",
"results",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/oauth_client.go#L72-L84 | train |
remind101/empire | pkg/heroku/oauth_client.go | OAuthClientUpdate | func (c *Client) OAuthClientUpdate(oauthClientIdentity string, options *OAuthClientUpdateOpts) (*OAuthClient, error) {
var oauthClientRes OAuthClient
return &oauthClientRes, c.Patch(&oauthClientRes, "/oauth/clients/"+oauthClientIdentity, options)
} | go | func (c *Client) OAuthClientUpdate(oauthClientIdentity string, options *OAuthClientUpdateOpts) (*OAuthClient, error) {
var oauthClientRes OAuthClient
return &oauthClientRes, c.Patch(&oauthClientRes, "/oauth/clients/"+oauthClientIdentity, options)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OAuthClientUpdate",
"(",
"oauthClientIdentity",
"string",
",",
"options",
"*",
"OAuthClientUpdateOpts",
")",
"(",
"*",
"OAuthClient",
",",
"error",
")",
"{",
"var",
"oauthClientRes",
"OAuthClient",
"\n",
"return",
"&",
"o... | // Update OAuth client
//
// oauthClientIdentity is the unique identifier of the OAuthClient. options is
// the struct of optional parameters for this action. | [
"Update",
"OAuth",
"client",
"oauthClientIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OAuthClient",
".",
"options",
"is",
"the",
"struct",
"of",
"optional",
"parameters",
"for",
"this",
"action",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/oauth_client.go#L90-L93 | train |
remind101/empire | pkg/heroku/log_session.go | LogSessionCreate | func (c *Client) LogSessionCreate(appIdentity string, options *LogSessionCreateOpts) (*LogSession, error) {
var logSessionRes LogSession
return &logSessionRes, c.Post(&logSessionRes, "/apps/"+appIdentity+"/log-sessions", options)
} | go | func (c *Client) LogSessionCreate(appIdentity string, options *LogSessionCreateOpts) (*LogSession, error) {
var logSessionRes LogSession
return &logSessionRes, c.Post(&logSessionRes, "/apps/"+appIdentity+"/log-sessions", options)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"LogSessionCreate",
"(",
"appIdentity",
"string",
",",
"options",
"*",
"LogSessionCreateOpts",
")",
"(",
"*",
"LogSession",
",",
"error",
")",
"{",
"var",
"logSessionRes",
"LogSession",
"\n",
"return",
"&",
"logSessionRes"... | // Create a new log session.
//
// appIdentity is the unique identifier of the LogSession's App. options is the
// struct of optional parameters for this action. | [
"Create",
"a",
"new",
"log",
"session",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"LogSession",
"s",
"App",
".",
"options",
"is",
"the",
"struct",
"of",
"optional",
"parameters",
"for",
"this",
"action",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/log_session.go#L30-L33 | train |
remind101/empire | server/server.go | newDeployer | func newDeployer(e *empire.Empire, options Options) github.Deployer {
ed := github.NewEmpireDeployer(e)
ed.ImageBuilder = options.GitHub.Deployments.ImageBuilder
var d github.Deployer = ed
// Enables the Tugboat integration, which will send logs to a Tugboat
// instance.
if url := options.GitHub.Deployments.TugboatURL; url != "" {
d = github.NotifyTugboat(d, url)
}
// Perform the deployment within a go routine so we don't timeout
// githubs webhook requests.
d = github.DeployAsync(d)
return d
} | go | func newDeployer(e *empire.Empire, options Options) github.Deployer {
ed := github.NewEmpireDeployer(e)
ed.ImageBuilder = options.GitHub.Deployments.ImageBuilder
var d github.Deployer = ed
// Enables the Tugboat integration, which will send logs to a Tugboat
// instance.
if url := options.GitHub.Deployments.TugboatURL; url != "" {
d = github.NotifyTugboat(d, url)
}
// Perform the deployment within a go routine so we don't timeout
// githubs webhook requests.
d = github.DeployAsync(d)
return d
} | [
"func",
"newDeployer",
"(",
"e",
"*",
"empire",
".",
"Empire",
",",
"options",
"Options",
")",
"github",
".",
"Deployer",
"{",
"ed",
":=",
"github",
".",
"NewEmpireDeployer",
"(",
"e",
")",
"\n",
"ed",
".",
"ImageBuilder",
"=",
"options",
".",
"GitHub",
... | // newDeployer generates a new github.Deployer implementation for the given
// options. | [
"newDeployer",
"generates",
"a",
"new",
"github",
".",
"Deployer",
"implementation",
"for",
"the",
"given",
"options",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/server.go#L132-L149 | train |
remind101/empire | pkg/heroku/organization_member.go | OrganizationMemberCreateOrUpdate | func (c *Client) OrganizationMemberCreateOrUpdate(organizationIdentity string, email string, role string) (*OrganizationMember, error) {
params := struct {
Email string `json:"email"`
Role string `json:"role"`
}{
Email: email,
Role: role,
}
var organizationMemberRes OrganizationMember
return &organizationMemberRes, c.Put(&organizationMemberRes, "/organizations/"+organizationIdentity+"/members", params)
} | go | func (c *Client) OrganizationMemberCreateOrUpdate(organizationIdentity string, email string, role string) (*OrganizationMember, error) {
params := struct {
Email string `json:"email"`
Role string `json:"role"`
}{
Email: email,
Role: role,
}
var organizationMemberRes OrganizationMember
return &organizationMemberRes, c.Put(&organizationMemberRes, "/organizations/"+organizationIdentity+"/members", params)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationMemberCreateOrUpdate",
"(",
"organizationIdentity",
"string",
",",
"email",
"string",
",",
"role",
"string",
")",
"(",
"*",
"OrganizationMember",
",",
"error",
")",
"{",
"params",
":=",
"struct",
"{",
"Email",... | // Create a new organization member, or update their role.
//
// organizationIdentity is the unique identifier of the OrganizationMember's
// Organization. email is the email address of the organization member. role is
// the role in the organization. | [
"Create",
"a",
"new",
"organization",
"member",
"or",
"update",
"their",
"role",
".",
"organizationIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OrganizationMember",
"s",
"Organization",
".",
"email",
"is",
"the",
"email",
"address",
"of",
"the",... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_member.go#L31-L41 | train |
remind101/empire | pkg/heroku/organization_member.go | OrganizationMemberDelete | func (c *Client) OrganizationMemberDelete(organizationIdentity string, organizationMemberIdentity string) error {
return c.Delete("/organizations/" + organizationIdentity + "/members/" + organizationIdentity)
} | go | func (c *Client) OrganizationMemberDelete(organizationIdentity string, organizationMemberIdentity string) error {
return c.Delete("/organizations/" + organizationIdentity + "/members/" + organizationIdentity)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationMemberDelete",
"(",
"organizationIdentity",
"string",
",",
"organizationMemberIdentity",
"string",
")",
"error",
"{",
"return",
"c",
".",
"Delete",
"(",
"\"/organizations/\"",
"+",
"organizationIdentity",
"+",
"\"/m... | // Remove a member from the organization.
//
// organizationIdentity is the unique identifier of the OrganizationMember's
// Organization. organizationMemberIdentity is the unique identifier of the
// OrganizationMember. | [
"Remove",
"a",
"member",
"from",
"the",
"organization",
".",
"organizationIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OrganizationMember",
"s",
"Organization",
".",
"organizationMemberIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Or... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_member.go#L48-L50 | train |
remind101/empire | pkg/heroku/organization_member.go | OrganizationMemberList | func (c *Client) OrganizationMemberList(organizationIdentity string, lr *ListRange) ([]OrganizationMember, error) {
req, err := c.NewRequest("GET", "/organizations/"+organizationIdentity+"/members", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var organizationMembersRes []OrganizationMember
return organizationMembersRes, c.DoReq(req, &organizationMembersRes)
} | go | func (c *Client) OrganizationMemberList(organizationIdentity string, lr *ListRange) ([]OrganizationMember, error) {
req, err := c.NewRequest("GET", "/organizations/"+organizationIdentity+"/members", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var organizationMembersRes []OrganizationMember
return organizationMembersRes, c.DoReq(req, &organizationMembersRes)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationMemberList",
"(",
"organizationIdentity",
"string",
",",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"OrganizationMember",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\... | // List members of the organization.
//
// organizationIdentity is the unique identifier of the OrganizationMember's
// Organization. lr is an optional ListRange that sets the Range options for the
// paginated list of results. | [
"List",
"members",
"of",
"the",
"organization",
".",
"organizationIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OrganizationMember",
"s",
"Organization",
".",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_member.go#L57-L69 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | NewScheduler | func NewScheduler(db *sql.DB, config client.ConfigProvider) *Scheduler {
return &Scheduler{
cloudformation: cloudformation.New(config),
ecs: ecsWithCaching(&ECS{ecs.New(config)}),
s3: s3.New(config),
ec2: ec2.New(config),
db: db,
after: time.After,
}
} | go | func NewScheduler(db *sql.DB, config client.ConfigProvider) *Scheduler {
return &Scheduler{
cloudformation: cloudformation.New(config),
ecs: ecsWithCaching(&ECS{ecs.New(config)}),
s3: s3.New(config),
ec2: ec2.New(config),
db: db,
after: time.After,
}
} | [
"func",
"NewScheduler",
"(",
"db",
"*",
"sql",
".",
"DB",
",",
"config",
"client",
".",
"ConfigProvider",
")",
"*",
"Scheduler",
"{",
"return",
"&",
"Scheduler",
"{",
"cloudformation",
":",
"cloudformation",
".",
"New",
"(",
"config",
")",
",",
"ecs",
":... | // NewScheduler returns a new Scheduler instance. | [
"NewScheduler",
"returns",
"a",
"new",
"Scheduler",
"instance",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L190-L199 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | createTemplate | func (s *Scheduler) createTemplate(ctx context.Context, app *twelvefactor.Manifest, stackTags []*cloudformation.Tag) (*cloudformationTemplate, error) {
data := &TemplateData{
Manifest: app,
StackTags: stackTags,
}
buf := new(bytes.Buffer)
if err := s.Template.Execute(buf, data); err != nil {
return nil, err
}
key := fmt.Sprintf("%s/%s/%x", app.Name, app.AppID, sha1.Sum(buf.Bytes()))
url := fmt.Sprintf("https://%s.s3.amazonaws.com/%s", s.Bucket, key)
if _, err := s.s3.PutObject(&s3.PutObjectInput{
Bucket: aws.String(s.Bucket),
Key: aws.String(fmt.Sprintf("/%s", key)),
Body: bytes.NewReader(buf.Bytes()),
ContentType: aws.String("application/json"),
}); err != nil {
return nil, fmt.Errorf("error uploading stack template to s3: %v", err)
}
t := &cloudformationTemplate{
URL: aws.String(url),
Size: buf.Len(),
}
resp, err := s.cloudformation.ValidateTemplate(&cloudformation.ValidateTemplateInput{
TemplateURL: aws.String(url),
})
if err != nil {
return t, &templateValidationError{template: t, err: err}
}
t.Parameters = resp.Parameters
return t, nil
} | go | func (s *Scheduler) createTemplate(ctx context.Context, app *twelvefactor.Manifest, stackTags []*cloudformation.Tag) (*cloudformationTemplate, error) {
data := &TemplateData{
Manifest: app,
StackTags: stackTags,
}
buf := new(bytes.Buffer)
if err := s.Template.Execute(buf, data); err != nil {
return nil, err
}
key := fmt.Sprintf("%s/%s/%x", app.Name, app.AppID, sha1.Sum(buf.Bytes()))
url := fmt.Sprintf("https://%s.s3.amazonaws.com/%s", s.Bucket, key)
if _, err := s.s3.PutObject(&s3.PutObjectInput{
Bucket: aws.String(s.Bucket),
Key: aws.String(fmt.Sprintf("/%s", key)),
Body: bytes.NewReader(buf.Bytes()),
ContentType: aws.String("application/json"),
}); err != nil {
return nil, fmt.Errorf("error uploading stack template to s3: %v", err)
}
t := &cloudformationTemplate{
URL: aws.String(url),
Size: buf.Len(),
}
resp, err := s.cloudformation.ValidateTemplate(&cloudformation.ValidateTemplateInput{
TemplateURL: aws.String(url),
})
if err != nil {
return t, &templateValidationError{template: t, err: err}
}
t.Parameters = resp.Parameters
return t, nil
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"createTemplate",
"(",
"ctx",
"context",
".",
"Context",
",",
"app",
"*",
"twelvefactor",
".",
"Manifest",
",",
"stackTags",
"[",
"]",
"*",
"cloudformation",
".",
"Tag",
")",
"(",
"*",
"cloudformationTemplate",
",",... | // createTemplate takes a scheduler.App, and returns a validated cloudformation
// template. | [
"createTemplate",
"takes",
"a",
"scheduler",
".",
"App",
"and",
"returns",
"a",
"validated",
"cloudformation",
"template",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L426-L464 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | createStack | func (s *Scheduler) createStack(ctx context.Context, input *createStackInput, output chan stackOperationOutput, ss twelvefactor.StatusStream) error {
waiter := s.waitFor(ctx, createStack, ss)
submitted := make(chan error)
fn := func() error {
_, err := s.cloudformation.CreateStack(&cloudformation.CreateStackInput{
StackName: input.StackName,
TemplateURL: input.Template.URL,
Tags: input.Tags,
Parameters: input.Parameters,
})
submitted <- err
return err
}
go func() {
stack, err := s.performStackOperation(ctx, *input.StackName, fn, waiter, ss)
output <- stackOperationOutput{stack, err}
}()
return <-submitted
} | go | func (s *Scheduler) createStack(ctx context.Context, input *createStackInput, output chan stackOperationOutput, ss twelvefactor.StatusStream) error {
waiter := s.waitFor(ctx, createStack, ss)
submitted := make(chan error)
fn := func() error {
_, err := s.cloudformation.CreateStack(&cloudformation.CreateStackInput{
StackName: input.StackName,
TemplateURL: input.Template.URL,
Tags: input.Tags,
Parameters: input.Parameters,
})
submitted <- err
return err
}
go func() {
stack, err := s.performStackOperation(ctx, *input.StackName, fn, waiter, ss)
output <- stackOperationOutput{stack, err}
}()
return <-submitted
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"createStack",
"(",
"ctx",
"context",
".",
"Context",
",",
"input",
"*",
"createStackInput",
",",
"output",
"chan",
"stackOperationOutput",
",",
"ss",
"twelvefactor",
".",
"StatusStream",
")",
"error",
"{",
"waiter",
... | // createStack creates a new CloudFormation stack with the given input. This
// function returns as soon as the stack creation has been submitted. It does
// not wait for the stack creation to complete. | [
"createStack",
"creates",
"a",
"new",
"CloudFormation",
"stack",
"with",
"the",
"given",
"input",
".",
"This",
"function",
"returns",
"as",
"soon",
"as",
"the",
"stack",
"creation",
"has",
"been",
"submitted",
".",
"It",
"does",
"not",
"wait",
"for",
"the",
... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L484-L504 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | updateStack | func (s *Scheduler) updateStack(ctx context.Context, input *updateStackInput, output chan stackOperationOutput, ss twelvefactor.StatusStream) error {
waiter := s.waitFor(ctx, updateStack, ss)
locked := make(chan struct{})
submitted := make(chan error, 1)
fn := func() error {
close(locked)
err := s.executeStackUpdate(input)
if err == nil {
publish(ctx, ss, "Stack update submitted")
}
submitted <- err
return err
}
go func() {
stack, err := s.performStackOperation(ctx, *input.StackName, fn, waiter, ss)
output <- stackOperationOutput{stack, err}
}()
var err error
select {
case <-s.after(lockWait):
publish(ctx, ss, "Waiting for existing stack operation to complete")
// FIXME: At this point, we don't want to affect UX by waiting
// around, so we return. But, if the stack update times out, or
// there's an error, that information is essentially silenced.
return nil
case <-locked:
// if a lock is obtained within the time frame, we might as well
// just wait for the update to get submitted.
err = <-submitted
}
return err
} | go | func (s *Scheduler) updateStack(ctx context.Context, input *updateStackInput, output chan stackOperationOutput, ss twelvefactor.StatusStream) error {
waiter := s.waitFor(ctx, updateStack, ss)
locked := make(chan struct{})
submitted := make(chan error, 1)
fn := func() error {
close(locked)
err := s.executeStackUpdate(input)
if err == nil {
publish(ctx, ss, "Stack update submitted")
}
submitted <- err
return err
}
go func() {
stack, err := s.performStackOperation(ctx, *input.StackName, fn, waiter, ss)
output <- stackOperationOutput{stack, err}
}()
var err error
select {
case <-s.after(lockWait):
publish(ctx, ss, "Waiting for existing stack operation to complete")
// FIXME: At this point, we don't want to affect UX by waiting
// around, so we return. But, if the stack update times out, or
// there's an error, that information is essentially silenced.
return nil
case <-locked:
// if a lock is obtained within the time frame, we might as well
// just wait for the update to get submitted.
err = <-submitted
}
return err
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"updateStack",
"(",
"ctx",
"context",
".",
"Context",
",",
"input",
"*",
"updateStackInput",
",",
"output",
"chan",
"stackOperationOutput",
",",
"ss",
"twelvefactor",
".",
"StatusStream",
")",
"error",
"{",
"waiter",
... | // updateStack updates an existing CloudFormation stack with the given input.
// If there are no other active updates, this function returns as soon as the
// stack update has been submitted. If there are other updates, the function
// returns after `lockTimeout` and the update continues in the background. | [
"updateStack",
"updates",
"an",
"existing",
"CloudFormation",
"stack",
"with",
"the",
"given",
"input",
".",
"If",
"there",
"are",
"no",
"other",
"active",
"updates",
"this",
"function",
"returns",
"as",
"soon",
"as",
"the",
"stack",
"update",
"has",
"been",
... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L518-L553 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | waitUntilStackOperationComplete | func (s *Scheduler) waitUntilStackOperationComplete(lock *pglock.AdvisoryLock, wait func() error) error {
errCh := make(chan error)
go func() { errCh <- wait() }()
var err error
select {
case <-s.after(stackOperationTimeout):
err = errors.New("timed out waiting for stack operation to complete")
case err = <-errCh:
}
return err
} | go | func (s *Scheduler) waitUntilStackOperationComplete(lock *pglock.AdvisoryLock, wait func() error) error {
errCh := make(chan error)
go func() { errCh <- wait() }()
var err error
select {
case <-s.after(stackOperationTimeout):
err = errors.New("timed out waiting for stack operation to complete")
case err = <-errCh:
}
return err
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"waitUntilStackOperationComplete",
"(",
"lock",
"*",
"pglock",
".",
"AdvisoryLock",
",",
"wait",
"func",
"(",
")",
"error",
")",
"error",
"{",
"errCh",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"go",
"func",
... | // waitUntilStackOperationComplete waits until wait returns, or it times out. | [
"waitUntilStackOperationComplete",
"waits",
"until",
"wait",
"returns",
"or",
"it",
"times",
"out",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L615-L627 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | executeStackUpdate | func (s *Scheduler) executeStackUpdate(input *updateStackInput) error {
stack, err := s.stack(input.StackName)
if err != nil {
return err
}
i := &cloudformation.UpdateStackInput{
StackName: input.StackName,
Parameters: updateParameters(input.Parameters, stack, input.Template),
Tags: input.Tags,
}
if input.Template != nil {
i.TemplateURL = input.Template.URL
} else {
i.UsePreviousTemplate = aws.Bool(true)
}
_, err = s.cloudformation.UpdateStack(i)
if err != nil {
if err, ok := err.(awserr.Error); ok {
if err.Code() == "ValidationError" && err.Message() == "No updates are to be performed." {
return nil
}
}
return fmt.Errorf("error updating stack: %v", err)
}
return nil
} | go | func (s *Scheduler) executeStackUpdate(input *updateStackInput) error {
stack, err := s.stack(input.StackName)
if err != nil {
return err
}
i := &cloudformation.UpdateStackInput{
StackName: input.StackName,
Parameters: updateParameters(input.Parameters, stack, input.Template),
Tags: input.Tags,
}
if input.Template != nil {
i.TemplateURL = input.Template.URL
} else {
i.UsePreviousTemplate = aws.Bool(true)
}
_, err = s.cloudformation.UpdateStack(i)
if err != nil {
if err, ok := err.(awserr.Error); ok {
if err.Code() == "ValidationError" && err.Message() == "No updates are to be performed." {
return nil
}
}
return fmt.Errorf("error updating stack: %v", err)
}
return nil
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"executeStackUpdate",
"(",
"input",
"*",
"updateStackInput",
")",
"error",
"{",
"stack",
",",
"err",
":=",
"s",
".",
"stack",
"(",
"input",
".",
"StackName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // executeStackUpdate performs a stack update. | [
"executeStackUpdate",
"performs",
"a",
"stack",
"update",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L630-L659 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | stack | func (s *Scheduler) stack(stackName *string) (*cloudformation.Stack, error) {
resp, err := s.cloudformation.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: stackName,
})
if err != nil {
return nil, err
}
return resp.Stacks[0], nil
} | go | func (s *Scheduler) stack(stackName *string) (*cloudformation.Stack, error) {
resp, err := s.cloudformation.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: stackName,
})
if err != nil {
return nil, err
}
return resp.Stacks[0], nil
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"stack",
"(",
"stackName",
"*",
"string",
")",
"(",
"*",
"cloudformation",
".",
"Stack",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"s",
".",
"cloudformation",
".",
"DescribeStacks",
"(",
"&",
"cloudforma... | // stack returns the cloudformation.Stack for the given stack name. | [
"stack",
"returns",
"the",
"cloudformation",
".",
"Stack",
"for",
"the",
"given",
"stack",
"name",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L662-L670 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | Remove | func (s *Scheduler) Remove(ctx context.Context, appID string) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
err = s.remove(ctx, tx, appID)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
} | go | func (s *Scheduler) Remove(ctx context.Context, appID string) error {
tx, err := s.db.Begin()
if err != nil {
return err
}
err = s.remove(ctx, tx, appID)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Remove",
"(",
"ctx",
"context",
".",
"Context",
",",
"appID",
"string",
")",
"error",
"{",
"tx",
",",
"err",
":=",
"s",
".",
"db",
".",
"Begin",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // Remove removes the CloudFormation stack for the given app. | [
"Remove",
"removes",
"the",
"CloudFormation",
"stack",
"for",
"the",
"given",
"app",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L673-L686 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | remove | func (s *Scheduler) remove(_ context.Context, tx *sql.Tx, appID string) error {
stackName, err := s.stackName(appID)
// if there's no stack entry in the db for this app, nothing to remove
if err == errNoStack {
return nil
}
if err != nil {
return err
}
_, err = tx.Exec(`DELETE FROM stacks WHERE app_id = $1`, appID)
if err != nil {
return err
}
_, err = s.cloudformation.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: aws.String(stackName),
})
if err, ok := err.(awserr.Error); ok && err.Message() == fmt.Sprintf("Stack with id %s does not exist", stackName) {
return nil
}
if _, err := s.cloudformation.DeleteStack(&cloudformation.DeleteStackInput{
StackName: aws.String(stackName),
}); err != nil {
return fmt.Errorf("error deleting stack: %v", err)
}
return nil
} | go | func (s *Scheduler) remove(_ context.Context, tx *sql.Tx, appID string) error {
stackName, err := s.stackName(appID)
// if there's no stack entry in the db for this app, nothing to remove
if err == errNoStack {
return nil
}
if err != nil {
return err
}
_, err = tx.Exec(`DELETE FROM stacks WHERE app_id = $1`, appID)
if err != nil {
return err
}
_, err = s.cloudformation.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: aws.String(stackName),
})
if err, ok := err.(awserr.Error); ok && err.Message() == fmt.Sprintf("Stack with id %s does not exist", stackName) {
return nil
}
if _, err := s.cloudformation.DeleteStack(&cloudformation.DeleteStackInput{
StackName: aws.String(stackName),
}); err != nil {
return fmt.Errorf("error deleting stack: %v", err)
}
return nil
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"remove",
"(",
"_",
"context",
".",
"Context",
",",
"tx",
"*",
"sql",
".",
"Tx",
",",
"appID",
"string",
")",
"error",
"{",
"stackName",
",",
"err",
":=",
"s",
".",
"stackName",
"(",
"appID",
")",
"\n",
"i... | // Remove removes the CloudFormation stack for the given app, if it exists. | [
"Remove",
"removes",
"the",
"CloudFormation",
"stack",
"for",
"the",
"given",
"app",
"if",
"it",
"exists",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L689-L719 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | tasks | func (s *Scheduler) tasks(app string) ([]*ecs.Task, error) {
services, err := s.Services(app)
if err != nil {
return nil, err
}
var arns []*string
// Find all of the tasks started by the ECS services.
for process, serviceArn := range services {
id, err := arn.ResourceID(serviceArn)
if err != nil {
return nil, err
}
var taskArns []*string
if err := s.ecs.ListTasksPages(&ecs.ListTasksInput{
Cluster: aws.String(s.Cluster),
ServiceName: aws.String(id),
}, func(resp *ecs.ListTasksOutput, lastPage bool) bool {
taskArns = append(taskArns, resp.TaskArns...)
return true
}); err != nil {
return nil, fmt.Errorf("error listing tasks for %s: %v", process, err)
}
if len(taskArns) == 0 {
continue
}
arns = append(arns, taskArns...)
}
// Find all of the tasks started by Run.
if err := s.ecs.ListTasksPages(&ecs.ListTasksInput{
Cluster: aws.String(s.Cluster),
StartedBy: aws.String(app),
}, func(resp *ecs.ListTasksOutput, lastPage bool) bool {
arns = append(arns, resp.TaskArns...)
return true
}); err != nil {
return nil, fmt.Errorf("error listing tasks started by %s: %v", app, err)
}
var tasks []*ecs.Task
for _, chunk := range chunkStrings(arns, MaxDescribeTasks) {
resp, err := s.ecs.DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String(s.Cluster),
Tasks: chunk,
})
if err != nil {
return nil, fmt.Errorf("error describing %d tasks: %v", len(chunk), err)
}
tasks = append(tasks, resp.Tasks...)
}
return tasks, nil
} | go | func (s *Scheduler) tasks(app string) ([]*ecs.Task, error) {
services, err := s.Services(app)
if err != nil {
return nil, err
}
var arns []*string
// Find all of the tasks started by the ECS services.
for process, serviceArn := range services {
id, err := arn.ResourceID(serviceArn)
if err != nil {
return nil, err
}
var taskArns []*string
if err := s.ecs.ListTasksPages(&ecs.ListTasksInput{
Cluster: aws.String(s.Cluster),
ServiceName: aws.String(id),
}, func(resp *ecs.ListTasksOutput, lastPage bool) bool {
taskArns = append(taskArns, resp.TaskArns...)
return true
}); err != nil {
return nil, fmt.Errorf("error listing tasks for %s: %v", process, err)
}
if len(taskArns) == 0 {
continue
}
arns = append(arns, taskArns...)
}
// Find all of the tasks started by Run.
if err := s.ecs.ListTasksPages(&ecs.ListTasksInput{
Cluster: aws.String(s.Cluster),
StartedBy: aws.String(app),
}, func(resp *ecs.ListTasksOutput, lastPage bool) bool {
arns = append(arns, resp.TaskArns...)
return true
}); err != nil {
return nil, fmt.Errorf("error listing tasks started by %s: %v", app, err)
}
var tasks []*ecs.Task
for _, chunk := range chunkStrings(arns, MaxDescribeTasks) {
resp, err := s.ecs.DescribeTasks(&ecs.DescribeTasksInput{
Cluster: aws.String(s.Cluster),
Tasks: chunk,
})
if err != nil {
return nil, fmt.Errorf("error describing %d tasks: %v", len(chunk), err)
}
tasks = append(tasks, resp.Tasks...)
}
return tasks, nil
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"tasks",
"(",
"app",
"string",
")",
"(",
"[",
"]",
"*",
"ecs",
".",
"Task",
",",
"error",
")",
"{",
"services",
",",
"err",
":=",
"s",
".",
"Services",
"(",
"app",
")",
"\n",
"if",
"err",
"!=",
"nil",
... | // tasks returns all of the ECS tasks for this app. | [
"tasks",
"returns",
"all",
"of",
"the",
"ECS",
"tasks",
"for",
"this",
"app",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L829-L887 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | Stop | func (s *Scheduler) Stop(ctx context.Context, taskID string) error {
_, err := s.ecs.StopTask(&ecs.StopTaskInput{
Cluster: aws.String(s.Cluster),
Task: aws.String(taskID),
})
return err
} | go | func (s *Scheduler) Stop(ctx context.Context, taskID string) error {
_, err := s.ecs.StopTask(&ecs.StopTaskInput{
Cluster: aws.String(s.Cluster),
Task: aws.String(taskID),
})
return err
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Stop",
"(",
"ctx",
"context",
".",
"Context",
",",
"taskID",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"s",
".",
"ecs",
".",
"StopTask",
"(",
"&",
"ecs",
".",
"StopTaskInput",
"{",
"Cluster",
":",... | // Stop stops the given ECS task. | [
"Stop",
"stops",
"the",
"given",
"ECS",
"task",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L916-L922 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | Run | func (m *Scheduler) Run(ctx context.Context, app *twelvefactor.Manifest) error {
for _, process := range app.Processes {
var attached bool
if process.Stdout != nil || process.Stderr != nil {
attached = true
}
t, ok := m.Template.(interface {
ContainerDefinition(*twelvefactor.Manifest, *twelvefactor.Process) *ecs.ContainerDefinition
})
if !ok {
return errors.New("provided template can't generate a container definition for this process")
}
containerDefinition := t.ContainerDefinition(app, process)
if attached {
if containerDefinition.DockerLabels == nil {
containerDefinition.DockerLabels = make(map[string]*string)
}
// NOTE: Currently, this depends on a patched version of the
// Amazon ECS Container Agent, since the official agent doesn't
// provide a method to pass these down to the `CreateContainer`
// call.
containerDefinition.DockerLabels["docker.config.Tty"] = aws.String("true")
containerDefinition.DockerLabels["docker.config.OpenStdin"] = aws.String("true")
}
resp, err := m.ecs.RegisterTaskDefinition(&ecs.RegisterTaskDefinitionInput{
Family: aws.String(fmt.Sprintf("%s--%s", app.AppID, process.Type)),
TaskRoleArn: taskRoleArn(app),
ContainerDefinitions: []*ecs.ContainerDefinition{
containerDefinition,
},
})
if err != nil {
return fmt.Errorf("error registering TaskDefinition: %v", err)
}
input := &ecs.RunTaskInput{
TaskDefinition: resp.TaskDefinition.TaskDefinitionArn,
Cluster: aws.String(m.Cluster),
Count: aws.Int64(1),
StartedBy: aws.String(app.AppID),
}
if v := process.ECS; v != nil {
input.PlacementConstraints = v.PlacementConstraints
input.PlacementStrategy = v.PlacementStrategy
}
runResp, err := m.ecs.RunTask(input)
if err != nil {
return fmt.Errorf("error calling RunTask: %v", err)
}
for _, f := range runResp.Failures {
return fmt.Errorf("error running task %s: %s", aws.StringValue(f.Arn), aws.StringValue(f.Reason))
}
task := runResp.Tasks[0]
if attached {
// Ensure that we atleast try to stop the task, after we detach
// from the process. This ensures that we don't have zombie
// one-off processes lying around.
defer m.ecs.StopTask(&ecs.StopTaskInput{
Cluster: task.ClusterArn,
Task: task.TaskArn,
})
if err := m.attach(ctx, task, process.Stdin, process.Stdout, process.Stderr); err != nil {
return err
}
}
}
return nil
} | go | func (m *Scheduler) Run(ctx context.Context, app *twelvefactor.Manifest) error {
for _, process := range app.Processes {
var attached bool
if process.Stdout != nil || process.Stderr != nil {
attached = true
}
t, ok := m.Template.(interface {
ContainerDefinition(*twelvefactor.Manifest, *twelvefactor.Process) *ecs.ContainerDefinition
})
if !ok {
return errors.New("provided template can't generate a container definition for this process")
}
containerDefinition := t.ContainerDefinition(app, process)
if attached {
if containerDefinition.DockerLabels == nil {
containerDefinition.DockerLabels = make(map[string]*string)
}
// NOTE: Currently, this depends on a patched version of the
// Amazon ECS Container Agent, since the official agent doesn't
// provide a method to pass these down to the `CreateContainer`
// call.
containerDefinition.DockerLabels["docker.config.Tty"] = aws.String("true")
containerDefinition.DockerLabels["docker.config.OpenStdin"] = aws.String("true")
}
resp, err := m.ecs.RegisterTaskDefinition(&ecs.RegisterTaskDefinitionInput{
Family: aws.String(fmt.Sprintf("%s--%s", app.AppID, process.Type)),
TaskRoleArn: taskRoleArn(app),
ContainerDefinitions: []*ecs.ContainerDefinition{
containerDefinition,
},
})
if err != nil {
return fmt.Errorf("error registering TaskDefinition: %v", err)
}
input := &ecs.RunTaskInput{
TaskDefinition: resp.TaskDefinition.TaskDefinitionArn,
Cluster: aws.String(m.Cluster),
Count: aws.Int64(1),
StartedBy: aws.String(app.AppID),
}
if v := process.ECS; v != nil {
input.PlacementConstraints = v.PlacementConstraints
input.PlacementStrategy = v.PlacementStrategy
}
runResp, err := m.ecs.RunTask(input)
if err != nil {
return fmt.Errorf("error calling RunTask: %v", err)
}
for _, f := range runResp.Failures {
return fmt.Errorf("error running task %s: %s", aws.StringValue(f.Arn), aws.StringValue(f.Reason))
}
task := runResp.Tasks[0]
if attached {
// Ensure that we atleast try to stop the task, after we detach
// from the process. This ensures that we don't have zombie
// one-off processes lying around.
defer m.ecs.StopTask(&ecs.StopTaskInput{
Cluster: task.ClusterArn,
Task: task.TaskArn,
})
if err := m.attach(ctx, task, process.Stdin, process.Stdout, process.Stderr); err != nil {
return err
}
}
}
return nil
} | [
"func",
"(",
"m",
"*",
"Scheduler",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"app",
"*",
"twelvefactor",
".",
"Manifest",
")",
"error",
"{",
"for",
"_",
",",
"process",
":=",
"range",
"app",
".",
"Processes",
"{",
"var",
"attached",
"b... | // Run registers a TaskDefinition for the process, and calls RunTask. | [
"Run",
"registers",
"a",
"TaskDefinition",
"for",
"the",
"process",
"and",
"calls",
"RunTask",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L925-L1002 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | attach | func (m *Scheduler) attach(ctx context.Context, task *ecs.Task, stdin io.Reader, stdout, stderr io.Writer) error {
if a, _ := arn.Parse(aws.StringValue(task.TaskArn)); a != nil {
fmt.Fprintf(stderr, "Attaching to %s...\r\n", a.Resource)
}
descContainerInstanceResp, err := m.ecs.DescribeContainerInstances(&ecs.DescribeContainerInstancesInput{
Cluster: task.ClusterArn,
ContainerInstances: []*string{task.ContainerInstanceArn},
})
if err != nil {
return fmt.Errorf("error describing container instance (%s): %v", aws.StringValue(task.ContainerInstanceArn), err)
}
containerInstance := descContainerInstanceResp.ContainerInstances[0]
descInstanceResp, err := m.ec2.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: []*string{containerInstance.Ec2InstanceId},
})
if err != nil {
return fmt.Errorf("error describing ec2 instance (%s): %v", aws.StringValue(containerInstance.Ec2InstanceId), err)
}
ec2Instance := descInstanceResp.Reservations[0].Instances[0]
// Wait for the task to start running. It will stay in the
// PENDING state while the container is being pulled.
if err := m.ecs.WaitUntilTasksNotPending(&ecs.DescribeTasksInput{
Cluster: task.ClusterArn,
Tasks: []*string{task.TaskArn},
}); err != nil {
return fmt.Errorf("error waiting for %s to transition from PENDING state: %s", aws.StringValue(task.TaskArn), err)
}
// Open a new connection to the Docker daemon on the EC2
// instance where the task is running.
d, err := m.NewDockerClient(ec2Instance)
if err != nil {
return fmt.Errorf("error connecting to docker daemon on %s: %v", aws.StringValue(ec2Instance.InstanceId), err)
}
// Find the container id for the ECS task.
containers, err := d.ListContainers(docker.ListContainersOptions{
All: true,
Filters: map[string][]string{
"label": []string{
fmt.Sprintf("com.amazonaws.ecs.task-arn=%s", aws.StringValue(task.TaskArn)),
//fmt.Sprintf("com.amazonaws.ecs.container-name", p)
},
},
})
if err != nil {
return fmt.Errorf("error listing containers for task: %v", err)
}
if len(containers) != 1 {
return fmt.Errorf("unable to find container for %s running on %s", aws.StringValue(task.TaskArn), aws.StringValue(ec2Instance.InstanceId))
}
containerID := containers[0].ID
if err := d.AttachToContainer(docker.AttachToContainerOptions{
Container: containerID,
InputStream: stdin,
OutputStream: stdout,
ErrorStream: stderr,
Logs: true,
Stream: true,
Stdin: true,
Stdout: true,
Stderr: true,
RawTerminal: true,
}); err != nil {
return fmt.Errorf("error attaching to container (%s): %v", containerID, err)
}
return nil
} | go | func (m *Scheduler) attach(ctx context.Context, task *ecs.Task, stdin io.Reader, stdout, stderr io.Writer) error {
if a, _ := arn.Parse(aws.StringValue(task.TaskArn)); a != nil {
fmt.Fprintf(stderr, "Attaching to %s...\r\n", a.Resource)
}
descContainerInstanceResp, err := m.ecs.DescribeContainerInstances(&ecs.DescribeContainerInstancesInput{
Cluster: task.ClusterArn,
ContainerInstances: []*string{task.ContainerInstanceArn},
})
if err != nil {
return fmt.Errorf("error describing container instance (%s): %v", aws.StringValue(task.ContainerInstanceArn), err)
}
containerInstance := descContainerInstanceResp.ContainerInstances[0]
descInstanceResp, err := m.ec2.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: []*string{containerInstance.Ec2InstanceId},
})
if err != nil {
return fmt.Errorf("error describing ec2 instance (%s): %v", aws.StringValue(containerInstance.Ec2InstanceId), err)
}
ec2Instance := descInstanceResp.Reservations[0].Instances[0]
// Wait for the task to start running. It will stay in the
// PENDING state while the container is being pulled.
if err := m.ecs.WaitUntilTasksNotPending(&ecs.DescribeTasksInput{
Cluster: task.ClusterArn,
Tasks: []*string{task.TaskArn},
}); err != nil {
return fmt.Errorf("error waiting for %s to transition from PENDING state: %s", aws.StringValue(task.TaskArn), err)
}
// Open a new connection to the Docker daemon on the EC2
// instance where the task is running.
d, err := m.NewDockerClient(ec2Instance)
if err != nil {
return fmt.Errorf("error connecting to docker daemon on %s: %v", aws.StringValue(ec2Instance.InstanceId), err)
}
// Find the container id for the ECS task.
containers, err := d.ListContainers(docker.ListContainersOptions{
All: true,
Filters: map[string][]string{
"label": []string{
fmt.Sprintf("com.amazonaws.ecs.task-arn=%s", aws.StringValue(task.TaskArn)),
//fmt.Sprintf("com.amazonaws.ecs.container-name", p)
},
},
})
if err != nil {
return fmt.Errorf("error listing containers for task: %v", err)
}
if len(containers) != 1 {
return fmt.Errorf("unable to find container for %s running on %s", aws.StringValue(task.TaskArn), aws.StringValue(ec2Instance.InstanceId))
}
containerID := containers[0].ID
if err := d.AttachToContainer(docker.AttachToContainerOptions{
Container: containerID,
InputStream: stdin,
OutputStream: stdout,
ErrorStream: stderr,
Logs: true,
Stream: true,
Stdin: true,
Stdout: true,
Stderr: true,
RawTerminal: true,
}); err != nil {
return fmt.Errorf("error attaching to container (%s): %v", containerID, err)
}
return nil
} | [
"func",
"(",
"m",
"*",
"Scheduler",
")",
"attach",
"(",
"ctx",
"context",
".",
"Context",
",",
"task",
"*",
"ecs",
".",
"Task",
",",
"stdin",
"io",
".",
"Reader",
",",
"stdout",
",",
"stderr",
"io",
".",
"Writer",
")",
"error",
"{",
"if",
"a",
",... | // attach attaches to the given ECS task. | [
"attach",
"attaches",
"to",
"the",
"given",
"ECS",
"task",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L1005-L1080 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | stackName | func (s *Scheduler) stackName(appID string) (string, error) {
var stackName string
err := s.db.QueryRow(`SELECT stack_name FROM stacks WHERE app_id = $1`, appID).Scan(&stackName)
if err == sql.ErrNoRows {
return "", errNoStack
}
return stackName, err
} | go | func (s *Scheduler) stackName(appID string) (string, error) {
var stackName string
err := s.db.QueryRow(`SELECT stack_name FROM stacks WHERE app_id = $1`, appID).Scan(&stackName)
if err == sql.ErrNoRows {
return "", errNoStack
}
return stackName, err
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"stackName",
"(",
"appID",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"stackName",
"string",
"\n",
"err",
":=",
"s",
".",
"db",
".",
"QueryRow",
"(",
"`SELECT stack_name FROM stacks WHERE app_id = $1... | // stackName returns the name of the CloudFormation stack for the app id. | [
"stackName",
"returns",
"the",
"name",
"of",
"the",
"CloudFormation",
"stack",
"for",
"the",
"app",
"id",
"."
] | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L1083-L1090 | train |
remind101/empire | scheduler/cloudformation/cloudformation.go | waitFor | func (s *Scheduler) waitFor(ctx context.Context, op stackOperation, ss twelvefactor.StatusStream) func(*cloudformation.DescribeStacksInput) error {
waiter := waiters[op]
wait := waiter.wait(s.cloudformation)
return func(input *cloudformation.DescribeStacksInput) error {
tags := []string{
fmt.Sprintf("stack:%s", *input.StackName),
}
publish(ctx, ss, waiter.startMessage)
start := time.Now()
err := wait(input)
stats.Timing(ctx, fmt.Sprintf("scheduler.cloudformation.%s", op), time.Since(start), 1.0, tags)
if err == nil {
publish(ctx, ss, waiter.successMessage)
}
return err
}
} | go | func (s *Scheduler) waitFor(ctx context.Context, op stackOperation, ss twelvefactor.StatusStream) func(*cloudformation.DescribeStacksInput) error {
waiter := waiters[op]
wait := waiter.wait(s.cloudformation)
return func(input *cloudformation.DescribeStacksInput) error {
tags := []string{
fmt.Sprintf("stack:%s", *input.StackName),
}
publish(ctx, ss, waiter.startMessage)
start := time.Now()
err := wait(input)
stats.Timing(ctx, fmt.Sprintf("scheduler.cloudformation.%s", op), time.Since(start), 1.0, tags)
if err == nil {
publish(ctx, ss, waiter.successMessage)
}
return err
}
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"waitFor",
"(",
"ctx",
"context",
".",
"Context",
",",
"op",
"stackOperation",
",",
"ss",
"twelvefactor",
".",
"StatusStream",
")",
"func",
"(",
"*",
"cloudformation",
".",
"DescribeStacksInput",
")",
"error",
"{",
... | // waitFor returns a wait function that will wait for the given stack operation
// to complete, and sends status messages to the status stream, and also records
// metrics for how long the operation took. | [
"waitFor",
"returns",
"a",
"wait",
"function",
"that",
"will",
"wait",
"for",
"the",
"given",
"stack",
"operation",
"to",
"complete",
"and",
"sends",
"status",
"messages",
"to",
"the",
"status",
"stream",
"and",
"also",
"records",
"metrics",
"for",
"how",
"l... | 3daba389f6b07b5d219246bfc7d901fcec664161 | https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/cloudformation.go#L1128-L1145 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.