id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
19,500
coreos/ignition
internal/resource/url.go
decompressCopyHashAndVerify
func (f *Fetcher) decompressCopyHashAndVerify(dest io.Writer, src io.Reader, opts FetchOptions) error { decompressor, err := f.uncompress(src, opts) if err != nil { return err } defer decompressor.Close() if opts.Hash != nil { opts.Hash.Reset() dest = io.MultiWriter(dest, opts.Hash) } _, err = io.Copy(dest, decompressor) if err != nil { return err } if opts.Hash != nil { calculatedSum := opts.Hash.Sum(nil) if !bytes.Equal(calculatedSum, opts.ExpectedSum) { return util.ErrHashMismatch{ Calculated: hex.EncodeToString(calculatedSum), Expected: hex.EncodeToString(opts.ExpectedSum), } } f.Logger.Debug("file matches expected sum of: %s", hex.EncodeToString(opts.ExpectedSum)) } return nil }
go
func (f *Fetcher) decompressCopyHashAndVerify(dest io.Writer, src io.Reader, opts FetchOptions) error { decompressor, err := f.uncompress(src, opts) if err != nil { return err } defer decompressor.Close() if opts.Hash != nil { opts.Hash.Reset() dest = io.MultiWriter(dest, opts.Hash) } _, err = io.Copy(dest, decompressor) if err != nil { return err } if opts.Hash != nil { calculatedSum := opts.Hash.Sum(nil) if !bytes.Equal(calculatedSum, opts.ExpectedSum) { return util.ErrHashMismatch{ Calculated: hex.EncodeToString(calculatedSum), Expected: hex.EncodeToString(opts.ExpectedSum), } } f.Logger.Debug("file matches expected sum of: %s", hex.EncodeToString(opts.ExpectedSum)) } return nil }
[ "func", "(", "f", "*", "Fetcher", ")", "decompressCopyHashAndVerify", "(", "dest", "io", ".", "Writer", ",", "src", "io", ".", "Reader", ",", "opts", "FetchOptions", ")", "error", "{", "decompressor", ",", "err", ":=", "f", ".", "uncompress", "(", "src",...
// decompressCopyHashAndVerify will decompress src if necessary, copy src into // dest until src returns an io.EOF while also calculating a hash if one is set, // and will return an error if there's any problems with any of this or if the // hash doesn't match the expected hash in the opts.
[ "decompressCopyHashAndVerify", "will", "decompress", "src", "if", "necessary", "copy", "src", "into", "dest", "until", "src", "returns", "an", "io", ".", "EOF", "while", "also", "calculating", "a", "hash", "if", "one", "is", "set", "and", "will", "return", "...
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/resource/url.go#L378-L403
19,501
coreos/ignition
internal/resource/http.go
RewriteCAsWithDataUrls
func (f *Fetcher) RewriteCAsWithDataUrls(cas []types.CaReference) error { for i, ca := range cas { blob, err := f.getCABlob(ca) if err != nil { return err } cas[i].Source = dataurl.EncodeBytes(blob) } return nil }
go
func (f *Fetcher) RewriteCAsWithDataUrls(cas []types.CaReference) error { for i, ca := range cas { blob, err := f.getCABlob(ca) if err != nil { return err } cas[i].Source = dataurl.EncodeBytes(blob) } return nil }
[ "func", "(", "f", "*", "Fetcher", ")", "RewriteCAsWithDataUrls", "(", "cas", "[", "]", "types", ".", "CaReference", ")", "error", "{", "for", "i", ",", "ca", ":=", "range", "cas", "{", "blob", ",", "err", ":=", "f", ".", "getCABlob", "(", "ca", ")"...
// RewriteCAsWithDataUrls will modify the passed in slice of CA references to // contain the actual CA file via a dataurl in their source field.
[ "RewriteCAsWithDataUrls", "will", "modify", "the", "passed", "in", "slice", "of", "CA", "references", "to", "contain", "the", "actual", "CA", "file", "via", "a", "dataurl", "in", "their", "source", "field", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/resource/http.go#L174-L184
19,502
coreos/ignition
internal/resource/http.go
defaultHTTPClient
func defaultHTTPClient() (*http.Client, error) { urand, err := earlyrand.UrandomReader() if err != nil { return nil, err } tlsConfig := tls.Config{ Rand: urand, } transport := http.Transport{ ResponseHeaderTimeout: time.Duration(defaultHttpResponseHeaderTimeout) * time.Second, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, Resolver: &net.Resolver{ PreferGo: true, }, }).Dial, TLSClientConfig: &tlsConfig, TLSHandshakeTimeout: 10 * time.Second, } client := http.Client{ Transport: &transport, } return &client, nil }
go
func defaultHTTPClient() (*http.Client, error) { urand, err := earlyrand.UrandomReader() if err != nil { return nil, err } tlsConfig := tls.Config{ Rand: urand, } transport := http.Transport{ ResponseHeaderTimeout: time.Duration(defaultHttpResponseHeaderTimeout) * time.Second, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, Resolver: &net.Resolver{ PreferGo: true, }, }).Dial, TLSClientConfig: &tlsConfig, TLSHandshakeTimeout: 10 * time.Second, } client := http.Client{ Transport: &transport, } return &client, nil }
[ "func", "defaultHTTPClient", "(", ")", "(", "*", "http", ".", "Client", ",", "error", ")", "{", "urand", ",", "err", ":=", "earlyrand", ".", "UrandomReader", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n...
// DefaultHTTPClient builds the default `http.client` for Ignition.
[ "DefaultHTTPClient", "builds", "the", "default", "http", ".", "client", "for", "Ignition", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/resource/http.go#L187-L212
19,503
coreos/ignition
internal/resource/http.go
newHttpClient
func (f *Fetcher) newHttpClient() error { defaultClient, err := defaultHTTPClient() if err != nil { return err } f.client = &HttpClient{ client: defaultClient, logger: f.Logger, timeout: time.Duration(defaultHttpTotalTimeout) * time.Second, transport: defaultClient.Transport.(*http.Transport), cas: make(map[types.CaReference][]byte), } return nil }
go
func (f *Fetcher) newHttpClient() error { defaultClient, err := defaultHTTPClient() if err != nil { return err } f.client = &HttpClient{ client: defaultClient, logger: f.Logger, timeout: time.Duration(defaultHttpTotalTimeout) * time.Second, transport: defaultClient.Transport.(*http.Transport), cas: make(map[types.CaReference][]byte), } return nil }
[ "func", "(", "f", "*", "Fetcher", ")", "newHttpClient", "(", ")", "error", "{", "defaultClient", ",", "err", ":=", "defaultHTTPClient", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "f", ".", "client", "=", "&", ...
// newHttpClient populates the fetcher with the default HTTP client.
[ "newHttpClient", "populates", "the", "fetcher", "with", "the", "default", "HTTP", "client", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/resource/http.go#L215-L229
19,504
coreos/ignition
internal/registry/registry.go
Create
func Create(name string) *Registry { return &Registry{name: name, registrants: map[string]Registrant{}} }
go
func Create(name string) *Registry { return &Registry{name: name, registrants: map[string]Registrant{}} }
[ "func", "Create", "(", "name", "string", ")", "*", "Registry", "{", "return", "&", "Registry", "{", "name", ":", "name", ",", "registrants", ":", "map", "[", "string", "]", "Registrant", "{", "}", "}", "\n", "}" ]
// Create creates a new registry
[ "Create", "creates", "a", "new", "registry" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/registry/registry.go#L33-L35
19,505
coreos/ignition
internal/registry/registry.go
Register
func (r *Registry) Register(registrant Registrant) { if _, ok := r.registrants[registrant.Name()]; ok { panic(fmt.Sprintf("%s: registrant %q already registered", r.name, registrant.Name())) } r.registrants[registrant.Name()] = registrant }
go
func (r *Registry) Register(registrant Registrant) { if _, ok := r.registrants[registrant.Name()]; ok { panic(fmt.Sprintf("%s: registrant %q already registered", r.name, registrant.Name())) } r.registrants[registrant.Name()] = registrant }
[ "func", "(", "r", "*", "Registry", ")", "Register", "(", "registrant", "Registrant", ")", "{", "if", "_", ",", "ok", ":=", "r", ".", "registrants", "[", "registrant", ".", "Name", "(", ")", "]", ";", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", ...
// Register registers a new registrant to a registry
[ "Register", "registers", "a", "new", "registrant", "to", "a", "registry" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/registry/registry.go#L38-L43
19,506
coreos/ignition
internal/registry/registry.go
Names
func (r *Registry) Names() []string { keys := []string{} for key := range r.registrants { keys = append(keys, key) } sort.Strings(keys) return keys }
go
func (r *Registry) Names() []string { keys := []string{} for key := range r.registrants { keys = append(keys, key) } sort.Strings(keys) return keys }
[ "func", "(", "r", "*", "Registry", ")", "Names", "(", ")", "[", "]", "string", "{", "keys", ":=", "[", "]", "string", "{", "}", "\n", "for", "key", ":=", "range", "r", ".", "registrants", "{", "keys", "=", "append", "(", "keys", ",", "key", ")"...
// Names returns the sorted registrant names
[ "Names", "returns", "the", "sorted", "registrant", "names" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/registry/registry.go#L51-L58
19,507
coreos/ignition
internal/sgdisk/sgdisk.go
Begin
func Begin(logger *log.Logger, dev string) *Operation { return &Operation{logger: logger, dev: dev} }
go
func Begin(logger *log.Logger, dev string) *Operation { return &Operation{logger: logger, dev: dev} }
[ "func", "Begin", "(", "logger", "*", "log", ".", "Logger", ",", "dev", "string", ")", "*", "Operation", "{", "return", "&", "Operation", "{", "logger", ":", "logger", ",", "dev", ":", "dev", "}", "\n", "}" ]
// Begin begins an sgdisk operation
[ "Begin", "begins", "an", "sgdisk", "operation" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/sgdisk/sgdisk.go#L37-L39
19,508
coreos/ignition
internal/sgdisk/sgdisk.go
CreatePartition
func (op *Operation) CreatePartition(p types.Partition) { op.parts = append(op.parts, p) }
go
func (op *Operation) CreatePartition(p types.Partition) { op.parts = append(op.parts, p) }
[ "func", "(", "op", "*", "Operation", ")", "CreatePartition", "(", "p", "types", ".", "Partition", ")", "{", "op", ".", "parts", "=", "append", "(", "op", ".", "parts", ",", "p", ")", "\n", "}" ]
// CreatePartition adds the supplied partition to the list of partitions to be created as part of an operation.
[ "CreatePartition", "adds", "the", "supplied", "partition", "to", "the", "list", "of", "partitions", "to", "be", "created", "as", "part", "of", "an", "operation", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/sgdisk/sgdisk.go#L42-L44
19,509
coreos/ignition
internal/sgdisk/sgdisk.go
Commit
func (op *Operation) Commit() error { opts := op.buildOptions() if len(opts) == 0 { return nil } op.logger.Info("running sgdisk with options: %v", opts) cmd := exec.Command(distro.SgdiskCmd(), opts...) if _, err := op.logger.LogCmd(cmd, "deleting %d partitions and creating %d partitions on %q", len(op.deletions), len(op.parts), op.dev); err != nil { return fmt.Errorf("create partitions failed: %v", err) } return nil }
go
func (op *Operation) Commit() error { opts := op.buildOptions() if len(opts) == 0 { return nil } op.logger.Info("running sgdisk with options: %v", opts) cmd := exec.Command(distro.SgdiskCmd(), opts...) if _, err := op.logger.LogCmd(cmd, "deleting %d partitions and creating %d partitions on %q", len(op.deletions), len(op.parts), op.dev); err != nil { return fmt.Errorf("create partitions failed: %v", err) } return nil }
[ "func", "(", "op", "*", "Operation", ")", "Commit", "(", ")", "error", "{", "opts", ":=", "op", ".", "buildOptions", "(", ")", "\n", "if", "len", "(", "opts", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "op", ".", "logger", ".", "Inf...
// Commit commits an partitioning operation.
[ "Commit", "commits", "an", "partitioning", "operation", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/sgdisk/sgdisk.go#L101-L113
19,510
coreos/ignition
internal/exec/engine.go
Run
func (e Engine) Run(stageName string) error { if e.Fetcher == nil || e.Logger == nil { fmt.Fprintf(os.Stderr, "engine incorrectly configured\n") return errors.ErrEngineConfiguration } baseConfig := types.Config{ Ignition: types.Ignition{Version: types.MaxVersion.String()}, } systemBaseConfig, r, err := system.FetchBaseConfig(e.Logger) e.logReport(r) if err != nil && err != providers.ErrNoProvider { e.Logger.Crit("failed to acquire system base config: %v", err) return err } cfg, err := e.acquireConfig() if err == errors.ErrEmpty { e.Logger.Info("%v: ignoring user-provided config", err) } else if err != nil { e.Logger.Crit("failed to acquire config: %v", err) return err } e.Logger.PushPrefix(stageName) defer e.Logger.PopPrefix() fullConfig := latest.Merge(baseConfig, latest.Merge(systemBaseConfig, cfg)) if err = stages.Get(stageName).Create(e.Logger, e.Root, *e.Fetcher).Run(fullConfig); err != nil { // e.Logger could be nil fmt.Fprintf(os.Stderr, "%s failed", stageName) tmp, jsonerr := json.MarshalIndent(fullConfig, "", " ") if jsonerr != nil { // Nothing else to do with this error fmt.Fprintf(os.Stderr, "Could not marshal full config: %v", err) } else { fmt.Fprintf(os.Stderr, "Full config:\n%s", string(tmp)) } return err } e.Logger.Info("%s passed", stageName) return nil }
go
func (e Engine) Run(stageName string) error { if e.Fetcher == nil || e.Logger == nil { fmt.Fprintf(os.Stderr, "engine incorrectly configured\n") return errors.ErrEngineConfiguration } baseConfig := types.Config{ Ignition: types.Ignition{Version: types.MaxVersion.String()}, } systemBaseConfig, r, err := system.FetchBaseConfig(e.Logger) e.logReport(r) if err != nil && err != providers.ErrNoProvider { e.Logger.Crit("failed to acquire system base config: %v", err) return err } cfg, err := e.acquireConfig() if err == errors.ErrEmpty { e.Logger.Info("%v: ignoring user-provided config", err) } else if err != nil { e.Logger.Crit("failed to acquire config: %v", err) return err } e.Logger.PushPrefix(stageName) defer e.Logger.PopPrefix() fullConfig := latest.Merge(baseConfig, latest.Merge(systemBaseConfig, cfg)) if err = stages.Get(stageName).Create(e.Logger, e.Root, *e.Fetcher).Run(fullConfig); err != nil { // e.Logger could be nil fmt.Fprintf(os.Stderr, "%s failed", stageName) tmp, jsonerr := json.MarshalIndent(fullConfig, "", " ") if jsonerr != nil { // Nothing else to do with this error fmt.Fprintf(os.Stderr, "Could not marshal full config: %v", err) } else { fmt.Fprintf(os.Stderr, "Full config:\n%s", string(tmp)) } return err } e.Logger.Info("%s passed", stageName) return nil }
[ "func", "(", "e", "Engine", ")", "Run", "(", "stageName", "string", ")", "error", "{", "if", "e", ".", "Fetcher", "==", "nil", "||", "e", ".", "Logger", "==", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ...
// Run executes the stage of the given name. It returns true if the stage // successfully ran and false if there were any errors.
[ "Run", "executes", "the", "stage", "of", "the", "given", "name", ".", "It", "returns", "true", "if", "the", "stage", "successfully", "ran", "and", "false", "if", "there", "were", "any", "errors", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/engine.go#L60-L102
19,511
coreos/ignition
internal/exec/engine.go
acquireConfig
func (e *Engine) acquireConfig() (cfg types.Config, err error) { // First try read the config @ e.ConfigCache. b, err := ioutil.ReadFile(e.ConfigCache) if err == nil { if err = json.Unmarshal(b, &cfg); err != nil { e.Logger.Crit("failed to parse cached config: %v", err) } // Create an http client and fetcher with the timeouts from the cached // config err = e.Fetcher.UpdateHttpTimeoutsAndCAs(cfg.Ignition.Timeouts, cfg.Ignition.Security.TLS.CertificateAuthorities, cfg.Ignition.Proxy) if err != nil { e.Logger.Crit("failed to update timeouts and CAs for fetcher: %v", err) return } return } // Create a new http client and fetcher with the timeouts set via the flags, // since we don't have a config with timeout values we can use timeout := int(e.FetchTimeout.Seconds()) emptyProxy := types.Proxy{} err = e.Fetcher.UpdateHttpTimeoutsAndCAs(types.Timeouts{HTTPTotal: &timeout}, nil, emptyProxy) if err != nil { e.Logger.Crit("failed to update timeouts and CAs for fetcher: %v", err) return } // (Re)Fetch the config if the cache is unreadable. cfg, err = e.fetchProviderConfig() if err != nil { e.Logger.Warning("failed to fetch config: %s", err) return } // Update the http client to use the timeouts and CAs from the newly fetched // config err = e.Fetcher.UpdateHttpTimeoutsAndCAs(cfg.Ignition.Timeouts, cfg.Ignition.Security.TLS.CertificateAuthorities, cfg.Ignition.Proxy) if err != nil { e.Logger.Crit("failed to update timeouts and CAs for fetcher: %v", err) return } err = e.Fetcher.RewriteCAsWithDataUrls(cfg.Ignition.Security.TLS.CertificateAuthorities) if err != nil { e.Logger.Crit("error handling CAs: %v", err) return } rpt := validate.ValidateWithoutSource(reflect.ValueOf(cfg)) e.logReport(rpt) if rpt.IsFatal() { err = errors.ErrInvalid e.Logger.Crit("merging configs resulted in an invalid config") return } // Populate the config cache. b, err = json.Marshal(cfg) if err != nil { e.Logger.Crit("failed to marshal cached config: %v", err) return } if err = ioutil.WriteFile(e.ConfigCache, b, 0640); err != nil { e.Logger.Crit("failed to write cached config: %v", err) return } return }
go
func (e *Engine) acquireConfig() (cfg types.Config, err error) { // First try read the config @ e.ConfigCache. b, err := ioutil.ReadFile(e.ConfigCache) if err == nil { if err = json.Unmarshal(b, &cfg); err != nil { e.Logger.Crit("failed to parse cached config: %v", err) } // Create an http client and fetcher with the timeouts from the cached // config err = e.Fetcher.UpdateHttpTimeoutsAndCAs(cfg.Ignition.Timeouts, cfg.Ignition.Security.TLS.CertificateAuthorities, cfg.Ignition.Proxy) if err != nil { e.Logger.Crit("failed to update timeouts and CAs for fetcher: %v", err) return } return } // Create a new http client and fetcher with the timeouts set via the flags, // since we don't have a config with timeout values we can use timeout := int(e.FetchTimeout.Seconds()) emptyProxy := types.Proxy{} err = e.Fetcher.UpdateHttpTimeoutsAndCAs(types.Timeouts{HTTPTotal: &timeout}, nil, emptyProxy) if err != nil { e.Logger.Crit("failed to update timeouts and CAs for fetcher: %v", err) return } // (Re)Fetch the config if the cache is unreadable. cfg, err = e.fetchProviderConfig() if err != nil { e.Logger.Warning("failed to fetch config: %s", err) return } // Update the http client to use the timeouts and CAs from the newly fetched // config err = e.Fetcher.UpdateHttpTimeoutsAndCAs(cfg.Ignition.Timeouts, cfg.Ignition.Security.TLS.CertificateAuthorities, cfg.Ignition.Proxy) if err != nil { e.Logger.Crit("failed to update timeouts and CAs for fetcher: %v", err) return } err = e.Fetcher.RewriteCAsWithDataUrls(cfg.Ignition.Security.TLS.CertificateAuthorities) if err != nil { e.Logger.Crit("error handling CAs: %v", err) return } rpt := validate.ValidateWithoutSource(reflect.ValueOf(cfg)) e.logReport(rpt) if rpt.IsFatal() { err = errors.ErrInvalid e.Logger.Crit("merging configs resulted in an invalid config") return } // Populate the config cache. b, err = json.Marshal(cfg) if err != nil { e.Logger.Crit("failed to marshal cached config: %v", err) return } if err = ioutil.WriteFile(e.ConfigCache, b, 0640); err != nil { e.Logger.Crit("failed to write cached config: %v", err) return } return }
[ "func", "(", "e", "*", "Engine", ")", "acquireConfig", "(", ")", "(", "cfg", "types", ".", "Config", ",", "err", "error", ")", "{", "// First try read the config @ e.ConfigCache.", "b", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "e", ".", "ConfigCac...
// acquireConfig returns the configuration, first checking a local cache // before attempting to fetch it from the provider.
[ "acquireConfig", "returns", "the", "configuration", "first", "checking", "a", "local", "cache", "before", "attempting", "to", "fetch", "it", "from", "the", "provider", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/engine.go#L106-L175
19,512
coreos/ignition
internal/exec/engine.go
renderConfig
func (e *Engine) renderConfig(cfg types.Config) (types.Config, error) { if cfgRef := cfg.Ignition.Config.Replace; cfgRef.Source != nil { newCfg, err := e.fetchReferencedConfig(cfgRef) if err != nil { return types.Config{}, err } // Replace the HTTP client in the fetcher to be configured with the // timeouts of the new config err = e.Fetcher.UpdateHttpTimeoutsAndCAs(newCfg.Ignition.Timeouts, newCfg.Ignition.Security.TLS.CertificateAuthorities, newCfg.Ignition.Proxy) if err != nil { return types.Config{}, err } return e.renderConfig(newCfg) } appendedCfg := cfg for _, cfgRef := range cfg.Ignition.Config.Merge { newCfg, err := e.fetchReferencedConfig(cfgRef) if err != nil { return types.Config{}, err } // Merge the old config with the new config before the new config has // been rendered, so we can use the new config's timeouts and CAs when // fetching more configs. cfgForFetcherSettings := latest.Merge(appendedCfg, newCfg) err = e.Fetcher.UpdateHttpTimeoutsAndCAs(cfgForFetcherSettings.Ignition.Timeouts, cfgForFetcherSettings.Ignition.Security.TLS.CertificateAuthorities, cfgForFetcherSettings.Ignition.Proxy) if err != nil { return types.Config{}, err } newCfg, err = e.renderConfig(newCfg) if err != nil { return types.Config{}, err } appendedCfg = latest.Merge(appendedCfg, newCfg) } return appendedCfg, nil }
go
func (e *Engine) renderConfig(cfg types.Config) (types.Config, error) { if cfgRef := cfg.Ignition.Config.Replace; cfgRef.Source != nil { newCfg, err := e.fetchReferencedConfig(cfgRef) if err != nil { return types.Config{}, err } // Replace the HTTP client in the fetcher to be configured with the // timeouts of the new config err = e.Fetcher.UpdateHttpTimeoutsAndCAs(newCfg.Ignition.Timeouts, newCfg.Ignition.Security.TLS.CertificateAuthorities, newCfg.Ignition.Proxy) if err != nil { return types.Config{}, err } return e.renderConfig(newCfg) } appendedCfg := cfg for _, cfgRef := range cfg.Ignition.Config.Merge { newCfg, err := e.fetchReferencedConfig(cfgRef) if err != nil { return types.Config{}, err } // Merge the old config with the new config before the new config has // been rendered, so we can use the new config's timeouts and CAs when // fetching more configs. cfgForFetcherSettings := latest.Merge(appendedCfg, newCfg) err = e.Fetcher.UpdateHttpTimeoutsAndCAs(cfgForFetcherSettings.Ignition.Timeouts, cfgForFetcherSettings.Ignition.Security.TLS.CertificateAuthorities, cfgForFetcherSettings.Ignition.Proxy) if err != nil { return types.Config{}, err } newCfg, err = e.renderConfig(newCfg) if err != nil { return types.Config{}, err } appendedCfg = latest.Merge(appendedCfg, newCfg) } return appendedCfg, nil }
[ "func", "(", "e", "*", "Engine", ")", "renderConfig", "(", "cfg", "types", ".", "Config", ")", "(", "types", ".", "Config", ",", "error", ")", "{", "if", "cfgRef", ":=", "cfg", ".", "Ignition", ".", "Config", ".", "Replace", ";", "cfgRef", ".", "So...
// renderConfig evaluates "ignition.config.replace" and "ignition.config.append" // in the given config and returns the result. If "ignition.config.replace" is // set, the referenced and evaluted config will be returned. Otherwise, if // "ignition.config.append" is set, each of the referenced configs will be // evaluated and appended to the provided config. If neither option is set, the // provided config will be returned unmodified. An updated fetcher will be // returned with any new timeouts set.
[ "renderConfig", "evaluates", "ignition", ".", "config", ".", "replace", "and", "ignition", ".", "config", ".", "append", "in", "the", "given", "config", "and", "returns", "the", "result", ".", "If", "ignition", ".", "config", ".", "replace", "is", "set", "...
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/engine.go#L224-L265
19,513
coreos/ignition
internal/exec/engine.go
fetchReferencedConfig
func (e *Engine) fetchReferencedConfig(cfgRef types.ConfigReference) (types.Config, error) { u, err := url.Parse(*cfgRef.Source) if err != nil { return types.Config{}, err } rawCfg, err := e.Fetcher.FetchToBuffer(*u, resource.FetchOptions{ Headers: resource.ConfigHeaders, }) if err != nil { return types.Config{}, err } hash := sha512.Sum512(rawCfg) if u.Scheme != "data" { e.Logger.Debug("fetched referenced config at %s with SHA512: %s", *cfgRef.Source, hex.EncodeToString(hash[:])) } else { // data url's might contain secrets e.Logger.Debug("fetched referenced config from data url with SHA512: %s", hex.EncodeToString(hash[:])) } if err := util.AssertValid(cfgRef.Verification, rawCfg); err != nil { return types.Config{}, err } cfg, r, err := config.Parse(rawCfg) e.logReport(r) if err != nil { return types.Config{}, err } return cfg, nil }
go
func (e *Engine) fetchReferencedConfig(cfgRef types.ConfigReference) (types.Config, error) { u, err := url.Parse(*cfgRef.Source) if err != nil { return types.Config{}, err } rawCfg, err := e.Fetcher.FetchToBuffer(*u, resource.FetchOptions{ Headers: resource.ConfigHeaders, }) if err != nil { return types.Config{}, err } hash := sha512.Sum512(rawCfg) if u.Scheme != "data" { e.Logger.Debug("fetched referenced config at %s with SHA512: %s", *cfgRef.Source, hex.EncodeToString(hash[:])) } else { // data url's might contain secrets e.Logger.Debug("fetched referenced config from data url with SHA512: %s", hex.EncodeToString(hash[:])) } if err := util.AssertValid(cfgRef.Verification, rawCfg); err != nil { return types.Config{}, err } cfg, r, err := config.Parse(rawCfg) e.logReport(r) if err != nil { return types.Config{}, err } return cfg, nil }
[ "func", "(", "e", "*", "Engine", ")", "fetchReferencedConfig", "(", "cfgRef", "types", ".", "ConfigReference", ")", "(", "types", ".", "Config", ",", "error", ")", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "*", "cfgRef", ".", "Source", ")...
// fetchReferencedConfig fetches and parses the requested config. // cfgRef.Source must not ve nil
[ "fetchReferencedConfig", "fetches", "and", "parses", "the", "requested", "config", ".", "cfgRef", ".", "Source", "must", "not", "ve", "nil" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/engine.go#L269-L300
19,514
coreos/ignition
internal/exec/util/passwd.go
EnsureUser
func (u Util) EnsureUser(c types.PasswdUser) error { exists, err := u.CheckIfUserExists(c) if err != nil { return err } args := []string{"--root", u.DestDir} var cmd string if exists { cmd = distro.UsermodCmd() if c.HomeDir != nil && *c.HomeDir != "" { args = append(args, "--home", *c.HomeDir, "--move-home") } } else { cmd = distro.UseraddCmd() if c.HomeDir != nil && *c.HomeDir != "" { args = append(args, "--home-dir", *c.HomeDir) } if c.NoCreateHome != nil && *c.NoCreateHome { args = append(args, "--no-create-home") } else { args = append(args, "--create-home") } if c.NoUserGroup != nil && *c.NoUserGroup { args = append(args, "--no-user-group") } if c.System != nil && *c.System { args = append(args, "--system") } if c.NoLogInit != nil && *c.NoLogInit { args = append(args, "--no-log-init") } } if c.PasswordHash != nil { if *c.PasswordHash != "" { args = append(args, "--password", *c.PasswordHash) } else { args = append(args, "--password", "*") } } else if !exists { // Set the user's password to "*" if they don't exist yet and one wasn't // set to disable password logins args = append(args, "--password", "*") } if c.UID != nil { args = append(args, "--uid", strconv.FormatUint(uint64(*c.UID), 10)) } if c.Gecos != nil && *c.Gecos != "" { args = append(args, "--comment", *c.Gecos) } if c.PrimaryGroup != nil && *c.PrimaryGroup != "" { args = append(args, "--gid", *c.PrimaryGroup) } if len(c.Groups) > 0 { args = append(args, "--groups", strings.Join(translateV2_1PasswdUserGroupSliceToStringSlice(c.Groups), ",")) } if c.Shell != nil && *c.Shell != "" { args = append(args, "--shell", *c.Shell) } args = append(args, c.Name) _, err = u.LogCmd(exec.Command(cmd, args...), "creating or modifying user %q", c.Name) return err }
go
func (u Util) EnsureUser(c types.PasswdUser) error { exists, err := u.CheckIfUserExists(c) if err != nil { return err } args := []string{"--root", u.DestDir} var cmd string if exists { cmd = distro.UsermodCmd() if c.HomeDir != nil && *c.HomeDir != "" { args = append(args, "--home", *c.HomeDir, "--move-home") } } else { cmd = distro.UseraddCmd() if c.HomeDir != nil && *c.HomeDir != "" { args = append(args, "--home-dir", *c.HomeDir) } if c.NoCreateHome != nil && *c.NoCreateHome { args = append(args, "--no-create-home") } else { args = append(args, "--create-home") } if c.NoUserGroup != nil && *c.NoUserGroup { args = append(args, "--no-user-group") } if c.System != nil && *c.System { args = append(args, "--system") } if c.NoLogInit != nil && *c.NoLogInit { args = append(args, "--no-log-init") } } if c.PasswordHash != nil { if *c.PasswordHash != "" { args = append(args, "--password", *c.PasswordHash) } else { args = append(args, "--password", "*") } } else if !exists { // Set the user's password to "*" if they don't exist yet and one wasn't // set to disable password logins args = append(args, "--password", "*") } if c.UID != nil { args = append(args, "--uid", strconv.FormatUint(uint64(*c.UID), 10)) } if c.Gecos != nil && *c.Gecos != "" { args = append(args, "--comment", *c.Gecos) } if c.PrimaryGroup != nil && *c.PrimaryGroup != "" { args = append(args, "--gid", *c.PrimaryGroup) } if len(c.Groups) > 0 { args = append(args, "--groups", strings.Join(translateV2_1PasswdUserGroupSliceToStringSlice(c.Groups), ",")) } if c.Shell != nil && *c.Shell != "" { args = append(args, "--shell", *c.Shell) } args = append(args, c.Name) _, err = u.LogCmd(exec.Command(cmd, args...), "creating or modifying user %q", c.Name) return err }
[ "func", "(", "u", "Util", ")", "EnsureUser", "(", "c", "types", ".", "PasswdUser", ")", "error", "{", "exists", ",", "err", ":=", "u", ".", "CheckIfUserExists", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", ...
// EnsureUser ensures that the user exists as described. If the user does not // yet exist, they will be created, otherwise the existing user will be // modified.
[ "EnsureUser", "ensures", "that", "the", "user", "exists", "as", "described", ".", "If", "the", "user", "does", "not", "yet", "exist", "they", "will", "be", "created", "otherwise", "the", "existing", "user", "will", "be", "modified", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/passwd.go#L35-L113
19,515
coreos/ignition
internal/exec/util/passwd.go
CheckIfUserExists
func (u Util) CheckIfUserExists(c types.PasswdUser) (bool, error) { code := -1 cmd := exec.Command(distro.ChrootCmd(), u.DestDir, distro.IdCmd(), c.Name) stdout, err := cmd.CombinedOutput() if err != nil { if exitErr, ok := err.(*exec.ExitError); ok { code = exitErr.Sys().(syscall.WaitStatus).ExitStatus() } if code == 1 { u.Info("checking if user \"%s\" exists: %s", c.Name, fmt.Errorf("[Attention] %v: Cmd: %s Stdout: %s", err, log.QuotedCmd(cmd), stdout)) return false, nil } u.Logger.Info("error encountered (%T): %v", err, err) return false, err } return true, nil }
go
func (u Util) CheckIfUserExists(c types.PasswdUser) (bool, error) { code := -1 cmd := exec.Command(distro.ChrootCmd(), u.DestDir, distro.IdCmd(), c.Name) stdout, err := cmd.CombinedOutput() if err != nil { if exitErr, ok := err.(*exec.ExitError); ok { code = exitErr.Sys().(syscall.WaitStatus).ExitStatus() } if code == 1 { u.Info("checking if user \"%s\" exists: %s", c.Name, fmt.Errorf("[Attention] %v: Cmd: %s Stdout: %s", err, log.QuotedCmd(cmd), stdout)) return false, nil } u.Logger.Info("error encountered (%T): %v", err, err) return false, err } return true, nil }
[ "func", "(", "u", "Util", ")", "CheckIfUserExists", "(", "c", "types", ".", "PasswdUser", ")", "(", "bool", ",", "error", ")", "{", "code", ":=", "-", "1", "\n", "cmd", ":=", "exec", ".", "Command", "(", "distro", ".", "ChrootCmd", "(", ")", ",", ...
// CheckIfUserExists will return Info log when user is empty
[ "CheckIfUserExists", "will", "return", "Info", "log", "when", "user", "is", "empty" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/passwd.go#L116-L132
19,516
coreos/ignition
internal/exec/util/passwd.go
writeAuthKeysFile
func writeAuthKeysFile(u *user.User, fp string, keys []byte) error { if err := as_user.MkdirAll(u, filepath.Dir(fp), 0700); err != nil { return err } f, err := as_user.OpenFile(u, fp, syscall.O_WRONLY|syscall.O_CREAT|syscall.O_TRUNC, 0600) if err != nil { return err } if _, err = f.Write(keys); err != nil { return err } if err := f.Close(); err != nil { return err } return nil }
go
func writeAuthKeysFile(u *user.User, fp string, keys []byte) error { if err := as_user.MkdirAll(u, filepath.Dir(fp), 0700); err != nil { return err } f, err := as_user.OpenFile(u, fp, syscall.O_WRONLY|syscall.O_CREAT|syscall.O_TRUNC, 0600) if err != nil { return err } if _, err = f.Write(keys); err != nil { return err } if err := f.Close(); err != nil { return err } return nil }
[ "func", "writeAuthKeysFile", "(", "u", "*", "user", ".", "User", ",", "fp", "string", ",", "keys", "[", "]", "byte", ")", "error", "{", "if", "err", ":=", "as_user", ".", "MkdirAll", "(", "u", ",", "filepath", ".", "Dir", "(", "fp", ")", ",", "07...
// writeAuthKeysFile writes the content in keys to the path fp for the user, // creating any directories in fp as needed.
[ "writeAuthKeysFile", "writes", "the", "content", "in", "keys", "to", "the", "path", "fp", "for", "the", "user", "creating", "any", "directories", "in", "fp", "as", "needed", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/passwd.go#L145-L161
19,517
coreos/ignition
internal/exec/util/passwd.go
AuthorizeSSHKeys
func (u Util) AuthorizeSSHKeys(c types.PasswdUser) error { if len(c.SSHAuthorizedKeys) == 0 { return nil } return u.LogOp(func() error { usr, err := u.userLookup(c.Name) if err != nil { return fmt.Errorf("unable to lookup user %q", c.Name) } // TODO(vc): introduce key names to config? // TODO(vc): validate c.SSHAuthorizedKeys well-formedness. ks := strings.Join(translateV2_1SSHAuthorizedKeySliceToStringSlice(c.SSHAuthorizedKeys), "\n") // XXX(vc): for now ensure the addition is always // newline-terminated. A future version of akd will handle this // for us in addition to validating the ssh keys for // well-formedness. if !strings.HasSuffix(ks, "\n") { ks = ks + "\n" } if distro.WriteAuthorizedKeysFragment() { writeAuthKeysFile(usr, filepath.Join(usr.HomeDir, ".ssh", "authorized_keys.d", "ignition"), []byte(ks)) } else { writeAuthKeysFile(usr, filepath.Join(usr.HomeDir, ".ssh", "authorized_keys"), []byte(ks)) } return nil }, "adding ssh keys to user %q", c.Name) }
go
func (u Util) AuthorizeSSHKeys(c types.PasswdUser) error { if len(c.SSHAuthorizedKeys) == 0 { return nil } return u.LogOp(func() error { usr, err := u.userLookup(c.Name) if err != nil { return fmt.Errorf("unable to lookup user %q", c.Name) } // TODO(vc): introduce key names to config? // TODO(vc): validate c.SSHAuthorizedKeys well-formedness. ks := strings.Join(translateV2_1SSHAuthorizedKeySliceToStringSlice(c.SSHAuthorizedKeys), "\n") // XXX(vc): for now ensure the addition is always // newline-terminated. A future version of akd will handle this // for us in addition to validating the ssh keys for // well-formedness. if !strings.HasSuffix(ks, "\n") { ks = ks + "\n" } if distro.WriteAuthorizedKeysFragment() { writeAuthKeysFile(usr, filepath.Join(usr.HomeDir, ".ssh", "authorized_keys.d", "ignition"), []byte(ks)) } else { writeAuthKeysFile(usr, filepath.Join(usr.HomeDir, ".ssh", "authorized_keys"), []byte(ks)) } return nil }, "adding ssh keys to user %q", c.Name) }
[ "func", "(", "u", "Util", ")", "AuthorizeSSHKeys", "(", "c", "types", ".", "PasswdUser", ")", "error", "{", "if", "len", "(", "c", ".", "SSHAuthorizedKeys", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "return", "u", ".", "LogOp", "(", ...
// AuthorizeSSHKeys adds the provided SSH public keys to the user's authorized keys.
[ "AuthorizeSSHKeys", "adds", "the", "provided", "SSH", "public", "keys", "to", "the", "user", "s", "authorized", "keys", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/passwd.go#L164-L194
19,518
coreos/ignition
internal/exec/util/passwd.go
SetPasswordHash
func (u Util) SetPasswordHash(c types.PasswdUser) error { if c.PasswordHash == nil { return nil } pwhash := *c.PasswordHash if *c.PasswordHash == "" { pwhash = "*" } args := []string{ "--root", u.DestDir, "--password", pwhash, } args = append(args, c.Name) _, err := u.LogCmd(exec.Command(distro.UsermodCmd(), args...), "setting password for %q", c.Name) return err }
go
func (u Util) SetPasswordHash(c types.PasswdUser) error { if c.PasswordHash == nil { return nil } pwhash := *c.PasswordHash if *c.PasswordHash == "" { pwhash = "*" } args := []string{ "--root", u.DestDir, "--password", pwhash, } args = append(args, c.Name) _, err := u.LogCmd(exec.Command(distro.UsermodCmd(), args...), "setting password for %q", c.Name) return err }
[ "func", "(", "u", "Util", ")", "SetPasswordHash", "(", "c", "types", ".", "PasswdUser", ")", "error", "{", "if", "c", ".", "PasswordHash", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "pwhash", ":=", "*", "c", ".", "PasswordHash", "\n", "if"...
// SetPasswordHash sets the password hash of the specified user.
[ "SetPasswordHash", "sets", "the", "password", "hash", "of", "the", "specified", "user", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/passwd.go#L206-L226
19,519
coreos/ignition
internal/exec/util/passwd.go
CreateGroup
func (u Util) CreateGroup(g types.PasswdGroup) error { args := []string{"--root", u.DestDir} if g.Gid != nil { args = append(args, "--gid", strconv.FormatUint(uint64(*g.Gid), 10)) } if g.PasswordHash != nil && *g.PasswordHash != "" { args = append(args, "--password", *g.PasswordHash) } else { args = append(args, "--password", "*") } if g.System != nil && *g.System { args = append(args, "--system") } args = append(args, g.Name) _, err := u.LogCmd(exec.Command(distro.GroupaddCmd(), args...), "adding group %q", g.Name) return err }
go
func (u Util) CreateGroup(g types.PasswdGroup) error { args := []string{"--root", u.DestDir} if g.Gid != nil { args = append(args, "--gid", strconv.FormatUint(uint64(*g.Gid), 10)) } if g.PasswordHash != nil && *g.PasswordHash != "" { args = append(args, "--password", *g.PasswordHash) } else { args = append(args, "--password", "*") } if g.System != nil && *g.System { args = append(args, "--system") } args = append(args, g.Name) _, err := u.LogCmd(exec.Command(distro.GroupaddCmd(), args...), "adding group %q", g.Name) return err }
[ "func", "(", "u", "Util", ")", "CreateGroup", "(", "g", "types", ".", "PasswdGroup", ")", "error", "{", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "u", ".", "DestDir", "}", "\n\n", "if", "g", ".", "Gid", "!=", "nil", "{", "args", "...
// CreateGroup creates the group as described.
[ "CreateGroup", "creates", "the", "group", "as", "described", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/passwd.go#L229-L252
19,520
coreos/ignition
config/translate/translate.go
couldBeValidTranslator
func couldBeValidTranslator(t reflect.Type) bool { if t.Kind() != reflect.Func { return false } if t.NumIn() != 1 || t.NumOut() != 1 { return false } if util.IsInvalidInConfig(t.In(0).Kind()) || util.IsInvalidInConfig(t.Out(0).Kind()) { return false } return true }
go
func couldBeValidTranslator(t reflect.Type) bool { if t.Kind() != reflect.Func { return false } if t.NumIn() != 1 || t.NumOut() != 1 { return false } if util.IsInvalidInConfig(t.In(0).Kind()) || util.IsInvalidInConfig(t.Out(0).Kind()) { return false } return true }
[ "func", "couldBeValidTranslator", "(", "t", "reflect", ".", "Type", ")", "bool", "{", "if", "t", ".", "Kind", "(", ")", "!=", "reflect", ".", "Func", "{", "return", "false", "\n", "}", "\n", "if", "t", ".", "NumIn", "(", ")", "!=", "1", "||", "t"...
// checks that t could reasonably be the type of a translator function
[ "checks", "that", "t", "could", "reasonably", "be", "the", "type", "of", "a", "translator", "function" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/translate/translate.go#L78-L89
19,521
coreos/ignition
config/translate/translate.go
hasTranslator
func (t translator) hasTranslator(tFrom, tTo reflect.Type) bool { return t.getTranslator(tFrom, tTo).IsValid() }
go
func (t translator) hasTranslator(tFrom, tTo reflect.Type) bool { return t.getTranslator(tFrom, tTo).IsValid() }
[ "func", "(", "t", "translator", ")", "hasTranslator", "(", "tFrom", ",", "tTo", "reflect", ".", "Type", ")", "bool", "{", "return", "t", ".", "getTranslator", "(", "tFrom", ",", "tTo", ")", ".", "IsValid", "(", ")", "\n", "}" ]
// helper to return if a custom translator was defined
[ "helper", "to", "return", "if", "a", "custom", "translator", "was", "defined" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/translate/translate.go#L125-L127
19,522
coreos/ignition
config/util/parsingErrors.go
HandleParseErrors
func HandleParseErrors(rawConfig []byte, to interface{}) (report.Report, error) { err := json.Unmarshal(rawConfig, to) if err == nil { return report.Report{}, nil } // Handle json syntax and type errors first, since they are fatal but have offset info if serr, ok := err.(*json.SyntaxError); ok { line, col, highlight := util.Highlight(rawConfig, serr.Offset) return report.Report{ Entries: []report.Entry{{ Kind: report.EntryError, Message: serr.Error(), Line: line, Column: col, Highlight: highlight, }}, }, errors.ErrInvalid } if terr, ok := err.(*json.UnmarshalTypeError); ok { line, col, highlight := util.Highlight(rawConfig, terr.Offset) return report.Report{ Entries: []report.Entry{{ Kind: report.EntryError, Message: terr.Error(), Line: line, Column: col, Highlight: highlight, }}, }, errors.ErrInvalid } return report.ReportFromError(err, report.EntryError), errors.ErrInvalid }
go
func HandleParseErrors(rawConfig []byte, to interface{}) (report.Report, error) { err := json.Unmarshal(rawConfig, to) if err == nil { return report.Report{}, nil } // Handle json syntax and type errors first, since they are fatal but have offset info if serr, ok := err.(*json.SyntaxError); ok { line, col, highlight := util.Highlight(rawConfig, serr.Offset) return report.Report{ Entries: []report.Entry{{ Kind: report.EntryError, Message: serr.Error(), Line: line, Column: col, Highlight: highlight, }}, }, errors.ErrInvalid } if terr, ok := err.(*json.UnmarshalTypeError); ok { line, col, highlight := util.Highlight(rawConfig, terr.Offset) return report.Report{ Entries: []report.Entry{{ Kind: report.EntryError, Message: terr.Error(), Line: line, Column: col, Highlight: highlight, }}, }, errors.ErrInvalid } return report.ReportFromError(err, report.EntryError), errors.ErrInvalid }
[ "func", "HandleParseErrors", "(", "rawConfig", "[", "]", "byte", ",", "to", "interface", "{", "}", ")", "(", "report", ".", "Report", ",", "error", ")", "{", "err", ":=", "json", ".", "Unmarshal", "(", "rawConfig", ",", "to", ")", "\n", "if", "err", ...
// HandleParseErrors will attempt to unmarshal an invalid rawConfig into "to". // If it fails to unmarsh it will generate a report.Report from the errors.
[ "HandleParseErrors", "will", "attempt", "to", "unmarshal", "an", "invalid", "rawConfig", "into", "to", ".", "If", "it", "fails", "to", "unmarsh", "it", "will", "generate", "a", "report", ".", "Report", "from", "the", "errors", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/util/parsingErrors.go#L27-L63
19,523
coreos/ignition
config/shared/validations/unit.go
ValidateInstallSection
func ValidateInstallSection(name string, enabled bool, contentsEmpty bool, contentSections []*unit.UnitOption) report.Report { if !enabled { // install sections don't matter for not-enabled units return report.Report{} } if contentsEmpty { // install sections don't matter if it has no contents, e.g. it's being masked or just has dropins or such return report.Report{} } if contentSections == nil { // Should only happen if the unit could not be parsed, at which point an // error is probably already in the report so we don't need to double-up on // errors + warnings. return report.Report{} } for _, section := range contentSections { if section.Section == "Install" { return report.Report{} } } return report.Report{ Entries: []report.Entry{{ Message: errors.NewNoInstallSectionError(name).Error(), Kind: report.EntryWarning, }}, } }
go
func ValidateInstallSection(name string, enabled bool, contentsEmpty bool, contentSections []*unit.UnitOption) report.Report { if !enabled { // install sections don't matter for not-enabled units return report.Report{} } if contentsEmpty { // install sections don't matter if it has no contents, e.g. it's being masked or just has dropins or such return report.Report{} } if contentSections == nil { // Should only happen if the unit could not be parsed, at which point an // error is probably already in the report so we don't need to double-up on // errors + warnings. return report.Report{} } for _, section := range contentSections { if section.Section == "Install" { return report.Report{} } } return report.Report{ Entries: []report.Entry{{ Message: errors.NewNoInstallSectionError(name).Error(), Kind: report.EntryWarning, }}, } }
[ "func", "ValidateInstallSection", "(", "name", "string", ",", "enabled", "bool", ",", "contentsEmpty", "bool", ",", "contentSections", "[", "]", "*", "unit", ".", "UnitOption", ")", "report", ".", "Report", "{", "if", "!", "enabled", "{", "// install sections ...
// ValidateInstallSection is a helper to validate a given unit
[ "ValidateInstallSection", "is", "a", "helper", "to", "validate", "a", "given", "unit" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/shared/validations/unit.go#L26-L54
19,524
coreos/ignition
config/validate/astjson/node.go
posFromOffset
func posFromOffset(offset int, source []byte) (int, int, string) { if source == nil { return 0, 0, "" } return util.Highlight(source, int64(offset)) }
go
func posFromOffset(offset int, source []byte) (int, int, string) { if source == nil { return 0, 0, "" } return util.Highlight(source, int64(offset)) }
[ "func", "posFromOffset", "(", "offset", "int", ",", "source", "[", "]", "byte", ")", "(", "int", ",", "int", ",", "string", ")", "{", "if", "source", "==", "nil", "{", "return", "0", ",", "0", ",", "\"", "\"", "\n", "}", "\n", "return", "util", ...
// wrapper for errorutil that handles missing sources sanely and resets the reader afterwards
[ "wrapper", "for", "errorutil", "that", "handles", "missing", "sources", "sanely", "and", "resets", "the", "reader", "afterwards" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/validate/astjson/node.go#L64-L69
19,525
coreos/ignition
internal/log/log.go
New
func New(logToStdout bool) Logger { logger := Logger{} if !logToStdout { var err error logger.ops, err = syslog.New(syslog.LOG_DEBUG, "ignition") if err != nil { logger.ops = Stdout{} logger.Err("unable to open syslog: %v", err) } return logger } logger.ops = Stdout{} return logger }
go
func New(logToStdout bool) Logger { logger := Logger{} if !logToStdout { var err error logger.ops, err = syslog.New(syslog.LOG_DEBUG, "ignition") if err != nil { logger.ops = Stdout{} logger.Err("unable to open syslog: %v", err) } return logger } logger.ops = Stdout{} return logger }
[ "func", "New", "(", "logToStdout", "bool", ")", "Logger", "{", "logger", ":=", "Logger", "{", "}", "\n", "if", "!", "logToStdout", "{", "var", "err", "error", "\n", "logger", ".", "ops", ",", "err", "=", "syslog", ".", "New", "(", "syslog", ".", "L...
// New creates a new logger. // If logToStdout is true, syslog is tried first. If syslog fails or logToStdout // is false Stdout is used.
[ "New", "creates", "a", "new", "logger", ".", "If", "logToStdout", "is", "true", "syslog", "is", "tried", "first", ".", "If", "syslog", "fails", "or", "logToStdout", "is", "false", "Stdout", "is", "used", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/log/log.go#L48-L61
19,526
coreos/ignition
internal/log/log.go
Crit
func (l Logger) Crit(format string, a ...interface{}) error { return l.log(l.ops.Crit, format, a...) }
go
func (l Logger) Crit(format string, a ...interface{}) error { return l.log(l.ops.Crit, format, a...) }
[ "func", "(", "l", "Logger", ")", "Crit", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "error", "{", "return", "l", ".", "log", "(", "l", ".", "ops", ".", "Crit", ",", "format", ",", "a", "...", ")", "\n", "}" ]
// Crit logs a message at critical priority.
[ "Crit", "logs", "a", "message", "at", "critical", "priority", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/log/log.go#L79-L81
19,527
coreos/ignition
internal/log/log.go
PushPrefix
func (l *Logger) PushPrefix(format string, a ...interface{}) { l.prefixStack = append(l.prefixStack, fmt.Sprintf(format, a...)) }
go
func (l *Logger) PushPrefix(format string, a ...interface{}) { l.prefixStack = append(l.prefixStack, fmt.Sprintf(format, a...)) }
[ "func", "(", "l", "*", "Logger", ")", "PushPrefix", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "{", "l", ".", "prefixStack", "=", "append", "(", "l", ".", "prefixStack", ",", "fmt", ".", "Sprintf", "(", "format", ",", "a"...
// PushPrefix pushes the supplied message onto the Logger's prefix stack. // The prefix stack is concatenated in FIFO order and prefixed to the start of every message logged via Logger.
[ "PushPrefix", "pushes", "the", "supplied", "message", "onto", "the", "Logger", "s", "prefix", "stack", ".", "The", "prefix", "stack", "is", "concatenated", "in", "FIFO", "order", "and", "prefixed", "to", "the", "start", "of", "every", "message", "logged", "v...
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/log/log.go#L110-L112
19,528
coreos/ignition
internal/log/log.go
PopPrefix
func (l *Logger) PopPrefix() { if len(l.prefixStack) == 0 { l.Debug("popped from empty stack") return } l.prefixStack = l.prefixStack[:len(l.prefixStack)-1] }
go
func (l *Logger) PopPrefix() { if len(l.prefixStack) == 0 { l.Debug("popped from empty stack") return } l.prefixStack = l.prefixStack[:len(l.prefixStack)-1] }
[ "func", "(", "l", "*", "Logger", ")", "PopPrefix", "(", ")", "{", "if", "len", "(", "l", ".", "prefixStack", ")", "==", "0", "{", "l", ".", "Debug", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "l", ".", "prefixStack", "=", "l", "."...
// PopPrefix pops the top entry from the Logger's prefix stack. // The prefix stack is concatenated in FIFO order and prefixed to the start of every message logged via Logger.
[ "PopPrefix", "pops", "the", "top", "entry", "from", "the", "Logger", "s", "prefix", "stack", ".", "The", "prefix", "stack", "is", "concatenated", "in", "FIFO", "order", "and", "prefixed", "to", "the", "start", "of", "every", "message", "logged", "via", "Lo...
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/log/log.go#L116-L122
19,529
coreos/ignition
internal/log/log.go
QuotedCmd
func QuotedCmd(cmd *exec.Cmd) string { if len(cmd.Args) == 0 { return fmt.Sprintf("%q", cmd.Path) } var q []string for _, s := range cmd.Args { q = append(q, fmt.Sprintf("%q", s)) } return strings.Join(q, ` `) }
go
func QuotedCmd(cmd *exec.Cmd) string { if len(cmd.Args) == 0 { return fmt.Sprintf("%q", cmd.Path) } var q []string for _, s := range cmd.Args { q = append(q, fmt.Sprintf("%q", s)) } return strings.Join(q, ` `) }
[ "func", "QuotedCmd", "(", "cmd", "*", "exec", ".", "Cmd", ")", "string", "{", "if", "len", "(", "cmd", ".", "Args", ")", "==", "0", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cmd", ".", "Path", ")", "\n", "}", "\n\n", "var", ...
// QuotedCmd returns a concatenated, quoted form of cmd's cmdline
[ "QuotedCmd", "returns", "a", "concatenated", "quoted", "form", "of", "cmd", "s", "cmdline" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/log/log.go#L125-L136
19,530
coreos/ignition
internal/log/log.go
log
func (l Logger) log(logFunc func(string) error, format string, a ...interface{}) error { return logFunc(l.sprintf(format, a...)) }
go
func (l Logger) log(logFunc func(string) error, format string, a ...interface{}) error { return logFunc(l.sprintf(format, a...)) }
[ "func", "(", "l", "Logger", ")", "log", "(", "logFunc", "func", "(", "string", ")", "error", ",", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "error", "{", "return", "logFunc", "(", "l", ".", "sprintf", "(", "format", ",", "a",...
// log logs a formatted message using the supplied logFunc.
[ "log", "logs", "a", "formatted", "message", "using", "the", "supplied", "logFunc", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/log/log.go#L193-L195
19,531
coreos/ignition
internal/log/log.go
sprintf
func (l Logger) sprintf(format string, a ...interface{}) string { m := []string{} for _, pfx := range l.prefixStack { m = append(m, fmt.Sprintf("%s:", pfx)) } m = append(m, fmt.Sprintf(format, a...)) return strings.Join(m, " ") }
go
func (l Logger) sprintf(format string, a ...interface{}) string { m := []string{} for _, pfx := range l.prefixStack { m = append(m, fmt.Sprintf("%s:", pfx)) } m = append(m, fmt.Sprintf(format, a...)) return strings.Join(m, " ") }
[ "func", "(", "l", "Logger", ")", "sprintf", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "string", "{", "m", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "pfx", ":=", "range", "l", ".", "prefixStack", "{", ...
// sprintf returns the current prefix stack, if any, concatenated with the supplied format string and args in expanded form.
[ "sprintf", "returns", "the", "current", "prefix", "stack", "if", "any", "concatenated", "with", "the", "supplied", "format", "string", "and", "args", "in", "expanded", "form", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/log/log.go#L198-L205
19,532
coreos/ignition
internal/exec/stages/disks/filesystems.go
createFilesystems
func (s stage) createFilesystems(config types.Config) error { fss := config.Storage.Filesystems s.Logger.Info("fss: %v", fss) if len(fss) == 0 { return nil } s.Logger.PushPrefix("createFilesystems") defer s.Logger.PopPrefix() devs := []string{} for _, fs := range fss { devs = append(devs, string(fs.Device)) } if err := s.waitOnDevicesAndCreateAliases(devs, "filesystems"); err != nil { return err } // Create filesystems concurrently up to GOMAXPROCS concurrency := runtime.GOMAXPROCS(-1) work := make(chan types.Filesystem, len(fss)) results := make(chan error) for i := 0; i < concurrency; i++ { go func() { for fs := range work { results <- s.createFilesystem(fs) } }() } for _, fs := range fss { work <- fs } close(work) // Return combined errors var errs []string for range fss { if err := <-results; err != nil { errs = append(errs, err.Error()) } } if len(errs) > 0 { return errors.New(strings.Join(errs, "\n")) } return nil }
go
func (s stage) createFilesystems(config types.Config) error { fss := config.Storage.Filesystems s.Logger.Info("fss: %v", fss) if len(fss) == 0 { return nil } s.Logger.PushPrefix("createFilesystems") defer s.Logger.PopPrefix() devs := []string{} for _, fs := range fss { devs = append(devs, string(fs.Device)) } if err := s.waitOnDevicesAndCreateAliases(devs, "filesystems"); err != nil { return err } // Create filesystems concurrently up to GOMAXPROCS concurrency := runtime.GOMAXPROCS(-1) work := make(chan types.Filesystem, len(fss)) results := make(chan error) for i := 0; i < concurrency; i++ { go func() { for fs := range work { results <- s.createFilesystem(fs) } }() } for _, fs := range fss { work <- fs } close(work) // Return combined errors var errs []string for range fss { if err := <-results; err != nil { errs = append(errs, err.Error()) } } if len(errs) > 0 { return errors.New(strings.Join(errs, "\n")) } return nil }
[ "func", "(", "s", "stage", ")", "createFilesystems", "(", "config", "types", ".", "Config", ")", "error", "{", "fss", ":=", "config", ".", "Storage", ".", "Filesystems", "\n", "s", ".", "Logger", ".", "Info", "(", "\"", "\"", ",", "fss", ")", "\n\n",...
// createFilesystems creates the filesystems described in config.Storage.Filesystems.
[ "createFilesystems", "creates", "the", "filesystems", "described", "in", "config", ".", "Storage", ".", "Filesystems", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/filesystems.go#L38-L89
19,533
coreos/ignition
internal/exec/stages/disks/filesystems.go
canonicalizeFilesystemUUID
func canonicalizeFilesystemUUID(format, uuid string) string { uuid = strings.ToLower(uuid) if format == "vfat" { // FAT uses a 32-bit volume ID instead of a UUID. blkid // (and the rest of the world) formats it as A1B2-C3D4, but // mkfs.fat doesn't permit the dash, so strip it. Older // versions of Ignition would fail if the config included // the dash, so we need to support omitting it. if len(uuid) >= 5 && uuid[4] == '-' { uuid = uuid[0:4] + uuid[5:] } } return uuid }
go
func canonicalizeFilesystemUUID(format, uuid string) string { uuid = strings.ToLower(uuid) if format == "vfat" { // FAT uses a 32-bit volume ID instead of a UUID. blkid // (and the rest of the world) formats it as A1B2-C3D4, but // mkfs.fat doesn't permit the dash, so strip it. Older // versions of Ignition would fail if the config included // the dash, so we need to support omitting it. if len(uuid) >= 5 && uuid[4] == '-' { uuid = uuid[0:4] + uuid[5:] } } return uuid }
[ "func", "canonicalizeFilesystemUUID", "(", "format", ",", "uuid", "string", ")", "string", "{", "uuid", "=", "strings", ".", "ToLower", "(", "uuid", ")", "\n", "if", "format", "==", "\"", "\"", "{", "// FAT uses a 32-bit volume ID instead of a UUID. blkid", "// (a...
// canonicalizeFilesystemUUID does the minimum amount of canonicalization // required to make two valid equivalent UUIDs compare equal, but doesn't // attempt to fully validate the UUID.
[ "canonicalizeFilesystemUUID", "does", "the", "minimum", "amount", "of", "canonicalization", "required", "to", "make", "two", "valid", "equivalent", "UUIDs", "compare", "equal", "but", "doesn", "t", "attempt", "to", "fully", "validate", "the", "UUID", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/filesystems.go#L224-L237
19,534
coreos/ignition
internal/util/tools/docs/docs.go
isDeprecatedConfig
func isDeprecatedConfig(r report.Report) bool { if len(r.Entries) != 1 { return false } if r.Entries[0].Kind == report.EntryDeprecated && r.Entries[0].Message == errors.ErrDeprecated.Error() { return true } return false }
go
func isDeprecatedConfig(r report.Report) bool { if len(r.Entries) != 1 { return false } if r.Entries[0].Kind == report.EntryDeprecated && r.Entries[0].Message == errors.ErrDeprecated.Error() { return true } return false }
[ "func", "isDeprecatedConfig", "(", "r", "report", ".", "Report", ")", "bool", "{", "if", "len", "(", "r", ".", "Entries", ")", "!=", "1", "{", "return", "false", "\n", "}", "\n", "if", "r", ".", "Entries", "[", "0", "]", ".", "Kind", "==", "repor...
// isDeprecatedConfig returns if a report is from a deprecated config format.
[ "isDeprecatedConfig", "returns", "if", "a", "report", "is", "from", "a", "deprecated", "config", "format", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/util/tools/docs/docs.go#L82-L90
19,535
coreos/ignition
internal/exec/stages/disks/partitions.go
createPartitions
func (s stage) createPartitions(config types.Config) error { if len(config.Storage.Disks) == 0 { return nil } s.Logger.PushPrefix("createPartitions") defer s.Logger.PopPrefix() devs := []string{} for _, disk := range config.Storage.Disks { devs = append(devs, string(disk.Device)) } if err := s.waitOnDevicesAndCreateAliases(devs, "disks"); err != nil { return err } for _, dev := range config.Storage.Disks { devAlias := util.DeviceAlias(string(dev.Device)) err := s.Logger.LogOp(func() error { return s.partitionDisk(dev, devAlias) }, "partitioning %q", devAlias) if err != nil { return err } } return nil }
go
func (s stage) createPartitions(config types.Config) error { if len(config.Storage.Disks) == 0 { return nil } s.Logger.PushPrefix("createPartitions") defer s.Logger.PopPrefix() devs := []string{} for _, disk := range config.Storage.Disks { devs = append(devs, string(disk.Device)) } if err := s.waitOnDevicesAndCreateAliases(devs, "disks"); err != nil { return err } for _, dev := range config.Storage.Disks { devAlias := util.DeviceAlias(string(dev.Device)) err := s.Logger.LogOp(func() error { return s.partitionDisk(dev, devAlias) }, "partitioning %q", devAlias) if err != nil { return err } } return nil }
[ "func", "(", "s", "stage", ")", "createPartitions", "(", "config", "types", ".", "Config", ")", "error", "{", "if", "len", "(", "config", ".", "Storage", ".", "Disks", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "s", ".", "Logger", ".", ...
// createPartitions creates the partitions described in config.Storage.Disks.
[ "createPartitions", "creates", "the", "partitions", "described", "in", "config", ".", "Storage", ".", "Disks", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/partitions.go#L39-L67
19,536
coreos/ignition
internal/exec/stages/disks/partitions.go
partitionShouldBeInspected
func partitionShouldBeInspected(part types.Partition) bool { if part.Number == 0 { return false } return (part.StartMiB != nil && *part.StartMiB == 0) || (part.SizeMiB != nil && *part.SizeMiB == 0) }
go
func partitionShouldBeInspected(part types.Partition) bool { if part.Number == 0 { return false } return (part.StartMiB != nil && *part.StartMiB == 0) || (part.SizeMiB != nil && *part.SizeMiB == 0) }
[ "func", "partitionShouldBeInspected", "(", "part", "types", ".", "Partition", ")", "bool", "{", "if", "part", ".", "Number", "==", "0", "{", "return", "false", "\n", "}", "\n", "return", "(", "part", ".", "StartMiB", "!=", "nil", "&&", "*", "part", "."...
// partitionShouldBeInspected returns if the partition has zeroes that need to be resolved to sectors.
[ "partitionShouldBeInspected", "returns", "if", "the", "partition", "has", "zeroes", "that", "need", "to", "be", "resolved", "to", "sectors", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/partitions.go#L96-L102
19,537
coreos/ignition
internal/exec/stages/disks/partitions.go
parseLine
func parseLine(r *regexp.Regexp, line string) (int, error) { matches := r.FindStringSubmatch(line) switch len(matches) { case 0: return -1, nil case 2: return strconv.Atoi(matches[1]) default: return 0, ErrBadSgdiskOutput } }
go
func parseLine(r *regexp.Regexp, line string) (int, error) { matches := r.FindStringSubmatch(line) switch len(matches) { case 0: return -1, nil case 2: return strconv.Atoi(matches[1]) default: return 0, ErrBadSgdiskOutput } }
[ "func", "parseLine", "(", "r", "*", "regexp", ".", "Regexp", ",", "line", "string", ")", "(", "int", ",", "error", ")", "{", "matches", ":=", "r", ".", "FindStringSubmatch", "(", "line", ")", "\n", "switch", "len", "(", "matches", ")", "{", "case", ...
// parseLine takes a regexp that captures an int and a string to match on. On success it returns // the captured int and nil. If the regexp does not match it returns -1 and nil. If it encountered // an error it returns 0 and the error.
[ "parseLine", "takes", "a", "regexp", "that", "captures", "an", "int", "and", "a", "string", "to", "match", "on", ".", "On", "success", "it", "returns", "the", "captured", "int", "and", "nil", ".", "If", "the", "regexp", "does", "not", "match", "it", "r...
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/partitions.go#L180-L190
19,538
coreos/ignition
internal/exec/stages/disks/partitions.go
getPartitionMap
func (s stage) getPartitionMap(device string) (util.DiskInfo, error) { info := util.DiskInfo{} err := s.Logger.LogOp( func() error { var err error info, err = util.DumpDisk(device) return err }, "reading partition table of %q", device) if err != nil { return util.DiskInfo{}, err } return info, nil }
go
func (s stage) getPartitionMap(device string) (util.DiskInfo, error) { info := util.DiskInfo{} err := s.Logger.LogOp( func() error { var err error info, err = util.DumpDisk(device) return err }, "reading partition table of %q", device) if err != nil { return util.DiskInfo{}, err } return info, nil }
[ "func", "(", "s", "stage", ")", "getPartitionMap", "(", "device", "string", ")", "(", "util", ".", "DiskInfo", ",", "error", ")", "{", "info", ":=", "util", ".", "DiskInfo", "{", "}", "\n", "err", ":=", "s", ".", "Logger", ".", "LogOp", "(", "func"...
// getPartitionMap returns a map of partitions on device, indexed by partition number
[ "getPartitionMap", "returns", "a", "map", "of", "partitions", "on", "device", "indexed", "by", "partition", "number" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/partitions.go#L266-L278
19,539
coreos/ignition
internal/exec/stages/disks/partitions.go
Less
func (p PartitionList) Less(i, j int) bool { return p[i].Number != 0 && p[j].Number == 0 }
go
func (p PartitionList) Less(i, j int) bool { return p[i].Number != 0 && p[j].Number == 0 }
[ "func", "(", "p", "PartitionList", ")", "Less", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "p", "[", "i", "]", ".", "Number", "!=", "0", "&&", "p", "[", "j", "]", ".", "Number", "==", "0", "\n", "}" ]
// We only care about partitions with number 0 being considered the "largest" elements // so they are processed last.
[ "We", "only", "care", "about", "partitions", "with", "number", "0", "being", "considered", "the", "largest", "elements", "so", "they", "are", "processed", "last", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/partitions.go#L290-L292
19,540
coreos/ignition
internal/exec/stages/disks/partitions.go
partitionDisk
func (s stage) partitionDisk(dev types.Disk, devAlias string) error { if dev.WipeTable != nil && *dev.WipeTable { op := sgdisk.Begin(s.Logger, devAlias) s.Logger.Info("wiping partition table requested on %q", devAlias) op.WipeTable(true) op.Commit() } // Ensure all partitions with number 0 are last sort.Stable(PartitionList(dev.Partitions)) op := sgdisk.Begin(s.Logger, devAlias) diskInfo, err := s.getPartitionMap(devAlias) if err != nil { return err } // get a list of parititions that have size and start 0 replaced with the real sizes // that would be used if all specified partitions were to be created anew. // Also change all of the start/size values into sectors. resolvedPartitions, err := s.getRealStartAndSize(dev, devAlias, diskInfo) if err != nil { return err } for _, part := range resolvedPartitions { shouldExist := partitionShouldExist(part) info, exists := diskInfo.GetPartition(part.Number) var matchErr error if exists { matchErr = partitionMatches(info, part) } matches := exists && matchErr == nil wipeEntry := part.WipePartitionEntry != nil && *part.WipePartitionEntry // This is a translation of the matrix in the operator notes. switch { case !exists && !shouldExist: s.Logger.Info("partition %d specified as nonexistant and no partition was found. Success.", part.Number) case !exists && shouldExist: op.CreatePartition(part) case exists && !shouldExist && !wipeEntry: return fmt.Errorf("partition %d exists but is specified as nonexistant and wipePartitionEntry is false", part.Number) case exists && !shouldExist && wipeEntry: op.DeletePartition(part.Number) case exists && shouldExist && matches: s.Logger.Info("partition %d found with correct specifications", part.Number) case exists && shouldExist && !wipeEntry && !matches: return fmt.Errorf("Partition %d didn't match: %v", part.Number, matchErr) case exists && shouldExist && wipeEntry && !matches: s.Logger.Info("partition %d did not meet specifications, wiping partition entry and recreating", part.Number) op.DeletePartition(part.Number) op.CreatePartition(part) default: // unfortunatey, golang doesn't check that all cases are handled exhaustively return fmt.Errorf("Unreachable code reached when processing partition %d. golang--", part.Number) } } if err := op.Commit(); err != nil { return fmt.Errorf("commit failure: %v", err) } return nil }
go
func (s stage) partitionDisk(dev types.Disk, devAlias string) error { if dev.WipeTable != nil && *dev.WipeTable { op := sgdisk.Begin(s.Logger, devAlias) s.Logger.Info("wiping partition table requested on %q", devAlias) op.WipeTable(true) op.Commit() } // Ensure all partitions with number 0 are last sort.Stable(PartitionList(dev.Partitions)) op := sgdisk.Begin(s.Logger, devAlias) diskInfo, err := s.getPartitionMap(devAlias) if err != nil { return err } // get a list of parititions that have size and start 0 replaced with the real sizes // that would be used if all specified partitions were to be created anew. // Also change all of the start/size values into sectors. resolvedPartitions, err := s.getRealStartAndSize(dev, devAlias, diskInfo) if err != nil { return err } for _, part := range resolvedPartitions { shouldExist := partitionShouldExist(part) info, exists := diskInfo.GetPartition(part.Number) var matchErr error if exists { matchErr = partitionMatches(info, part) } matches := exists && matchErr == nil wipeEntry := part.WipePartitionEntry != nil && *part.WipePartitionEntry // This is a translation of the matrix in the operator notes. switch { case !exists && !shouldExist: s.Logger.Info("partition %d specified as nonexistant and no partition was found. Success.", part.Number) case !exists && shouldExist: op.CreatePartition(part) case exists && !shouldExist && !wipeEntry: return fmt.Errorf("partition %d exists but is specified as nonexistant and wipePartitionEntry is false", part.Number) case exists && !shouldExist && wipeEntry: op.DeletePartition(part.Number) case exists && shouldExist && matches: s.Logger.Info("partition %d found with correct specifications", part.Number) case exists && shouldExist && !wipeEntry && !matches: return fmt.Errorf("Partition %d didn't match: %v", part.Number, matchErr) case exists && shouldExist && wipeEntry && !matches: s.Logger.Info("partition %d did not meet specifications, wiping partition entry and recreating", part.Number) op.DeletePartition(part.Number) op.CreatePartition(part) default: // unfortunatey, golang doesn't check that all cases are handled exhaustively return fmt.Errorf("Unreachable code reached when processing partition %d. golang--", part.Number) } } if err := op.Commit(); err != nil { return fmt.Errorf("commit failure: %v", err) } return nil }
[ "func", "(", "s", "stage", ")", "partitionDisk", "(", "dev", "types", ".", "Disk", ",", "devAlias", "string", ")", "error", "{", "if", "dev", ".", "WipeTable", "!=", "nil", "&&", "*", "dev", ".", "WipeTable", "{", "op", ":=", "sgdisk", ".", "Begin", ...
// partitionDisk partitions devAlias according to the spec given by dev
[ "partitionDisk", "partitions", "devAlias", "according", "to", "the", "spec", "given", "by", "dev" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/partitions.go#L299-L363
19,541
coreos/ignition
config/validate/validate.go
ValidateConfig
func ValidateConfig(rawConfig []byte, config interface{}) report.Report { // Unmarshal again to a json.Node to get offset information for building a report var ast json.Node var r report.Report configValue := reflect.ValueOf(config) if err := json.Unmarshal(rawConfig, &ast); err != nil { r.Add(report.Entry{ Kind: report.EntryWarning, Message: "Ignition could not unmarshal your config for reporting line numbers. This should never happen. Please file a bug.", }) r.Merge(ValidateWithoutSource(configValue)) } else { r.Merge(Validate(configValue, astjson.FromJsonRoot(ast), rawConfig, true)) } return r }
go
func ValidateConfig(rawConfig []byte, config interface{}) report.Report { // Unmarshal again to a json.Node to get offset information for building a report var ast json.Node var r report.Report configValue := reflect.ValueOf(config) if err := json.Unmarshal(rawConfig, &ast); err != nil { r.Add(report.Entry{ Kind: report.EntryWarning, Message: "Ignition could not unmarshal your config for reporting line numbers. This should never happen. Please file a bug.", }) r.Merge(ValidateWithoutSource(configValue)) } else { r.Merge(Validate(configValue, astjson.FromJsonRoot(ast), rawConfig, true)) } return r }
[ "func", "ValidateConfig", "(", "rawConfig", "[", "]", "byte", ",", "config", "interface", "{", "}", ")", "report", ".", "Report", "{", "// Unmarshal again to a json.Node to get offset information for building a report", "var", "ast", "json", ".", "Node", "\n", "var", ...
// ValidateConfig validates a raw config object into a given config version
[ "ValidateConfig", "validates", "a", "raw", "config", "object", "into", "a", "given", "config", "version" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/validate/validate.go#L34-L49
19,542
coreos/ignition
config/validate/validate.go
Validate
func Validate(vObj reflect.Value, ast astnode.AstNode, source []byte, checkUnusedKeys bool) (r report.Report) { if !vObj.IsValid() { return } line, col, highlight := 0, 0, "" if ast != nil { line, col, highlight = ast.ValueLineCol(source) } // See if we A) can call Validate on vObj, and B) should call Validate. Validate should NOT be called // when vObj is nil, as it will panic or when vObj is a pointer to a value with Validate implemented with a // value receiver. This is to prevent Validate being called twice, as otherwise it would be called on the // pointer version (due to go's automatic deferencing) and once when the pointer is deferenced below. The only // time Validate should be called on a pointer is when the function is implemented with a pointer reciever. if obj, ok := vObj.Interface().(validator); ok && ((vObj.Kind() != reflect.Ptr) || (!vObj.IsNil() && !vObj.Elem().Type().Implements(reflect.TypeOf((*validator)(nil)).Elem()))) { sub_r := obj.Validate() sub_r.AddPosition(line, col, highlight) r.Merge(sub_r) // Dont recurse on invalid inner nodes, it mostly leads to bogus messages if sub_r.IsFatal() { return } } switch vObj.Kind() { case reflect.Ptr: sub_report := Validate(vObj.Elem(), ast, source, checkUnusedKeys) sub_report.AddPosition(line, col, "") r.Merge(sub_report) case reflect.Struct: sub_report := validateStruct(vObj, ast, source, checkUnusedKeys) sub_report.AddPosition(line, col, "") r.Merge(sub_report) case reflect.Slice: for i := 0; i < vObj.Len(); i++ { sub_node := ast if ast != nil { if n, ok := ast.SliceChild(i); ok { sub_node = n } } sub_report := Validate(vObj.Index(i), sub_node, source, checkUnusedKeys) sub_report.AddPosition(line, col, "") r.Merge(sub_report) } } return }
go
func Validate(vObj reflect.Value, ast astnode.AstNode, source []byte, checkUnusedKeys bool) (r report.Report) { if !vObj.IsValid() { return } line, col, highlight := 0, 0, "" if ast != nil { line, col, highlight = ast.ValueLineCol(source) } // See if we A) can call Validate on vObj, and B) should call Validate. Validate should NOT be called // when vObj is nil, as it will panic or when vObj is a pointer to a value with Validate implemented with a // value receiver. This is to prevent Validate being called twice, as otherwise it would be called on the // pointer version (due to go's automatic deferencing) and once when the pointer is deferenced below. The only // time Validate should be called on a pointer is when the function is implemented with a pointer reciever. if obj, ok := vObj.Interface().(validator); ok && ((vObj.Kind() != reflect.Ptr) || (!vObj.IsNil() && !vObj.Elem().Type().Implements(reflect.TypeOf((*validator)(nil)).Elem()))) { sub_r := obj.Validate() sub_r.AddPosition(line, col, highlight) r.Merge(sub_r) // Dont recurse on invalid inner nodes, it mostly leads to bogus messages if sub_r.IsFatal() { return } } switch vObj.Kind() { case reflect.Ptr: sub_report := Validate(vObj.Elem(), ast, source, checkUnusedKeys) sub_report.AddPosition(line, col, "") r.Merge(sub_report) case reflect.Struct: sub_report := validateStruct(vObj, ast, source, checkUnusedKeys) sub_report.AddPosition(line, col, "") r.Merge(sub_report) case reflect.Slice: for i := 0; i < vObj.Len(); i++ { sub_node := ast if ast != nil { if n, ok := ast.SliceChild(i); ok { sub_node = n } } sub_report := Validate(vObj.Index(i), sub_node, source, checkUnusedKeys) sub_report.AddPosition(line, col, "") r.Merge(sub_report) } } return }
[ "func", "Validate", "(", "vObj", "reflect", ".", "Value", ",", "ast", "astnode", ".", "AstNode", ",", "source", "[", "]", "byte", ",", "checkUnusedKeys", "bool", ")", "(", "r", "report", ".", "Report", ")", "{", "if", "!", "vObj", ".", "IsValid", "("...
// Validate walks down a struct tree calling Validate on every node that implements it, building // A report of all the errors, warnings, info, and deprecations it encounters. If checkUnusedKeys // is true, Validate will generate warnings for unused keys in the ast, otherwise it will not.
[ "Validate", "walks", "down", "a", "struct", "tree", "calling", "Validate", "on", "every", "node", "that", "implements", "it", "building", "A", "report", "of", "all", "the", "errors", "warnings", "info", "and", "deprecations", "it", "encounters", ".", "If", "...
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/validate/validate.go#L54-L105
19,543
coreos/ignition
config/validate/validate.go
similar
func similar(str string, candidates []string) string { for _, candidate := range candidates { if strings.EqualFold(str, candidate) { return candidate } } return "" }
go
func similar(str string, candidates []string) string { for _, candidate := range candidates { if strings.EqualFold(str, candidate) { return candidate } } return "" }
[ "func", "similar", "(", "str", "string", ",", "candidates", "[", "]", "string", ")", "string", "{", "for", "_", ",", "candidate", ":=", "range", "candidates", "{", "if", "strings", ".", "EqualFold", "(", "str", ",", "candidate", ")", "{", "return", "ca...
// similar returns a string in candidates that is similar to str. Currently it just does case // insensitive comparison, but it should be updated to use levenstein distances to catch typos
[ "similar", "returns", "a", "string", "in", "candidates", "that", "is", "similar", "to", "str", ".", "Currently", "it", "just", "does", "case", "insensitive", "comparison", "but", "it", "should", "be", "updated", "to", "use", "levenstein", "distances", "to", ...
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/validate/validate.go#L292-L299
19,544
coreos/ignition
internal/exec/stages/files/passwd.go
createPasswd
func (s *stage) createPasswd(config types.Config) error { if err := s.createGroups(config); err != nil { return fmt.Errorf("failed to create groups: %v", err) } if err := s.createUsers(config); err != nil { return fmt.Errorf("failed to create users: %v", err) } // to be safe, just blanket mark all passwd-related files rather than // trying to make it more granular based on which executables we ran if len(config.Passwd.Groups) != 0 || len(config.Passwd.Users) != 0 { s.relabel( "/etc/passwd*", "/etc/group*", "/etc/shadow*", "/etc/gshadow*", "/etc/subuid*", "/etc/subgid*", "/etc/.pwd.lock", "/home", "/root", // for OSTree-based systems (newer restorecon doesn't follow symlinks) "/var/home", "/var/roothome", ) } return nil }
go
func (s *stage) createPasswd(config types.Config) error { if err := s.createGroups(config); err != nil { return fmt.Errorf("failed to create groups: %v", err) } if err := s.createUsers(config); err != nil { return fmt.Errorf("failed to create users: %v", err) } // to be safe, just blanket mark all passwd-related files rather than // trying to make it more granular based on which executables we ran if len(config.Passwd.Groups) != 0 || len(config.Passwd.Users) != 0 { s.relabel( "/etc/passwd*", "/etc/group*", "/etc/shadow*", "/etc/gshadow*", "/etc/subuid*", "/etc/subgid*", "/etc/.pwd.lock", "/home", "/root", // for OSTree-based systems (newer restorecon doesn't follow symlinks) "/var/home", "/var/roothome", ) } return nil }
[ "func", "(", "s", "*", "stage", ")", "createPasswd", "(", "config", "types", ".", "Config", ")", "error", "{", "if", "err", ":=", "s", ".", "createGroups", "(", "config", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"",...
// createPasswd creates the users and groups as described in config.Passwd.
[ "createPasswd", "creates", "the", "users", "and", "groups", "as", "described", "in", "config", ".", "Passwd", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/files/passwd.go#L24-L53
19,545
coreos/ignition
internal/exec/stages/files/passwd.go
createUsers
func (s stage) createUsers(config types.Config) error { if len(config.Passwd.Users) == 0 { return nil } s.Logger.PushPrefix("createUsers") defer s.Logger.PopPrefix() for _, u := range config.Passwd.Users { if err := s.EnsureUser(u); err != nil { return fmt.Errorf("failed to create user %q: %v", u.Name, err) } if err := s.SetPasswordHash(u); err != nil { return fmt.Errorf("failed to set password for %q: %v", u.Name, err) } if err := s.AuthorizeSSHKeys(u); err != nil { return fmt.Errorf("failed to add keys to user %q: %v", u.Name, err) } } return nil }
go
func (s stage) createUsers(config types.Config) error { if len(config.Passwd.Users) == 0 { return nil } s.Logger.PushPrefix("createUsers") defer s.Logger.PopPrefix() for _, u := range config.Passwd.Users { if err := s.EnsureUser(u); err != nil { return fmt.Errorf("failed to create user %q: %v", u.Name, err) } if err := s.SetPasswordHash(u); err != nil { return fmt.Errorf("failed to set password for %q: %v", u.Name, err) } if err := s.AuthorizeSSHKeys(u); err != nil { return fmt.Errorf("failed to add keys to user %q: %v", u.Name, err) } } return nil }
[ "func", "(", "s", "stage", ")", "createUsers", "(", "config", "types", ".", "Config", ")", "error", "{", "if", "len", "(", "config", ".", "Passwd", ".", "Users", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "s", ".", "Logger", ".", "Pus...
// createUsers creates the users as described in config.Passwd.Users.
[ "createUsers", "creates", "the", "users", "as", "described", "in", "config", ".", "Passwd", ".", "Users", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/files/passwd.go#L56-L81
19,546
coreos/ignition
internal/exec/stages/files/passwd.go
createGroups
func (s stage) createGroups(config types.Config) error { if len(config.Passwd.Groups) == 0 { return nil } s.Logger.PushPrefix("createGroups") defer s.Logger.PopPrefix() for _, g := range config.Passwd.Groups { if err := s.CreateGroup(g); err != nil { return fmt.Errorf("failed to create group %q: %v", g.Name, err) } } return nil }
go
func (s stage) createGroups(config types.Config) error { if len(config.Passwd.Groups) == 0 { return nil } s.Logger.PushPrefix("createGroups") defer s.Logger.PopPrefix() for _, g := range config.Passwd.Groups { if err := s.CreateGroup(g); err != nil { return fmt.Errorf("failed to create group %q: %v", g.Name, err) } } return nil }
[ "func", "(", "s", "stage", ")", "createGroups", "(", "config", "types", ".", "Config", ")", "error", "{", "if", "len", "(", "config", ".", "Passwd", ".", "Groups", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "s", ".", "Logger", ".", "P...
// createGroups creates the users as described in config.Passwd.Groups.
[ "createGroups", "creates", "the", "users", "as", "described", "in", "config", ".", "Passwd", ".", "Groups", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/files/passwd.go#L84-L99
19,547
coreos/ignition
internal/exec/util/user_group_lookup.go
userLookup
func (u Util) userLookup(name string) (*user.User, error) { res := &C.lookup_res_t{} if ret, err := C.user_lookup(C.CString(u.DestDir), C.CString(name), res); ret < 0 { return nil, fmt.Errorf("lookup failed: %v", err) } if res.name == nil { return nil, fmt.Errorf("user %q not found", name) } homedir, err := u.JoinPath(C.GoString(res.home)) if err != nil { return nil, err } usr := &user.User{ Name: C.GoString(res.name), Uid: fmt.Sprintf("%d", int(res.uid)), Gid: fmt.Sprintf("%d", int(res.gid)), HomeDir: homedir, } C.user_lookup_res_free(res) return usr, nil }
go
func (u Util) userLookup(name string) (*user.User, error) { res := &C.lookup_res_t{} if ret, err := C.user_lookup(C.CString(u.DestDir), C.CString(name), res); ret < 0 { return nil, fmt.Errorf("lookup failed: %v", err) } if res.name == nil { return nil, fmt.Errorf("user %q not found", name) } homedir, err := u.JoinPath(C.GoString(res.home)) if err != nil { return nil, err } usr := &user.User{ Name: C.GoString(res.name), Uid: fmt.Sprintf("%d", int(res.uid)), Gid: fmt.Sprintf("%d", int(res.gid)), HomeDir: homedir, } C.user_lookup_res_free(res) return usr, nil }
[ "func", "(", "u", "Util", ")", "userLookup", "(", "name", "string", ")", "(", "*", "user", ".", "User", ",", "error", ")", "{", "res", ":=", "&", "C", ".", "lookup_res_t", "{", "}", "\n\n", "if", "ret", ",", "err", ":=", "C", ".", "user_lookup", ...
// userLookup looks up the user in u.DestDir.
[ "userLookup", "looks", "up", "the", "user", "in", "u", ".", "DestDir", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/user_group_lookup.go#L31-L58
19,548
coreos/ignition
internal/exec/util/user_group_lookup.go
groupLookup
func (u Util) groupLookup(name string) (*user.Group, error) { res := &C.lookup_res_t{} if ret, err := C.group_lookup(C.CString(u.DestDir), C.CString(name), res); ret < 0 { return nil, fmt.Errorf("lookup failed: %v", err) } if res.name == nil { return nil, fmt.Errorf("user %q not found", name) } grp := &user.Group{ Name: C.GoString(res.name), Gid: fmt.Sprintf("%d", int(res.gid)), } C.group_lookup_res_free(res) return grp, nil }
go
func (u Util) groupLookup(name string) (*user.Group, error) { res := &C.lookup_res_t{} if ret, err := C.group_lookup(C.CString(u.DestDir), C.CString(name), res); ret < 0 { return nil, fmt.Errorf("lookup failed: %v", err) } if res.name == nil { return nil, fmt.Errorf("user %q not found", name) } grp := &user.Group{ Name: C.GoString(res.name), Gid: fmt.Sprintf("%d", int(res.gid)), } C.group_lookup_res_free(res) return grp, nil }
[ "func", "(", "u", "Util", ")", "groupLookup", "(", "name", "string", ")", "(", "*", "user", ".", "Group", ",", "error", ")", "{", "res", ":=", "&", "C", ".", "lookup_res_t", "{", "}", "\n\n", "if", "ret", ",", "err", ":=", "C", ".", "group_lookup...
// groupLookup looks up the group in u.DestDir.
[ "groupLookup", "looks", "up", "the", "group", "in", "u", ".", "DestDir", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/user_group_lookup.go#L61-L81
19,549
coreos/ignition
internal/exec/stages/files/files.go
relabel
func (s *stage) relabel(paths ...string) { if s.toRelabel != nil { s.toRelabel = append(s.toRelabel, paths...) } }
go
func (s *stage) relabel(paths ...string) { if s.toRelabel != nil { s.toRelabel = append(s.toRelabel, paths...) } }
[ "func", "(", "s", "*", "stage", ")", "relabel", "(", "paths", "...", "string", ")", "{", "if", "s", ".", "toRelabel", "!=", "nil", "{", "s", ".", "toRelabel", "=", "append", "(", "s", ".", "toRelabel", ",", "paths", "...", ")", "\n", "}", "\n", ...
// relabel adds one or more paths to the list of paths that need relabeling.
[ "relabel", "adds", "one", "or", "more", "paths", "to", "the", "list", "of", "paths", "that", "need", "relabeling", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/files/files.go#L125-L129
19,550
coreos/ignition
internal/exec/stages/files/files.go
addRelabelUnit
func (s *stage) addRelabelUnit(config types.Config) error { if s.toRelabel == nil || len(s.toRelabel) == 0 { return nil } contents := `[Unit] Description=Relabel files created by Ignition DefaultDependencies=no After=local-fs.target Before=sysinit.target systemd-sysctl.service ConditionSecurity=selinux ConditionPathExists=/etc/selinux/ignition.relabel OnFailure=emergency.target OnFailureJobMode=replace-irreversibly [Service] Type=oneshot ExecStart=` + distro.RestoreconCmd() + ` -0vRif /etc/selinux/ignition.relabel ExecStart=/usr/bin/rm /etc/selinux/ignition.relabel RemainAfterExit=yes` // create the unit file itself unit := types.Unit{ Name: "ignition-relabel.service", Contents: &contents, } if err := s.writeSystemdUnit(unit, true); err != nil { return err } if err := s.EnableRuntimeUnit(unit, "sysinit.target"); err != nil { return err } // and now create the list of files to relabel etcRelabelPath, err := s.JoinPath("etc/selinux/ignition.relabel") if err != nil { return err } f, err := os.Create(etcRelabelPath) if err != nil { return err } defer f.Close() // yes, apparently the final \0 is needed _, err = f.WriteString(strings.Join(s.toRelabel, "\000") + "\000") return err }
go
func (s *stage) addRelabelUnit(config types.Config) error { if s.toRelabel == nil || len(s.toRelabel) == 0 { return nil } contents := `[Unit] Description=Relabel files created by Ignition DefaultDependencies=no After=local-fs.target Before=sysinit.target systemd-sysctl.service ConditionSecurity=selinux ConditionPathExists=/etc/selinux/ignition.relabel OnFailure=emergency.target OnFailureJobMode=replace-irreversibly [Service] Type=oneshot ExecStart=` + distro.RestoreconCmd() + ` -0vRif /etc/selinux/ignition.relabel ExecStart=/usr/bin/rm /etc/selinux/ignition.relabel RemainAfterExit=yes` // create the unit file itself unit := types.Unit{ Name: "ignition-relabel.service", Contents: &contents, } if err := s.writeSystemdUnit(unit, true); err != nil { return err } if err := s.EnableRuntimeUnit(unit, "sysinit.target"); err != nil { return err } // and now create the list of files to relabel etcRelabelPath, err := s.JoinPath("etc/selinux/ignition.relabel") if err != nil { return err } f, err := os.Create(etcRelabelPath) if err != nil { return err } defer f.Close() // yes, apparently the final \0 is needed _, err = f.WriteString(strings.Join(s.toRelabel, "\000") + "\000") return err }
[ "func", "(", "s", "*", "stage", ")", "addRelabelUnit", "(", "config", "types", ".", "Config", ")", "error", "{", "if", "s", ".", "toRelabel", "==", "nil", "||", "len", "(", "s", ".", "toRelabel", ")", "==", "0", "{", "return", "nil", "\n", "}", "...
// addRelabelUnit creates and enables a runtime systemd unit to run restorecon // if there are files that need to be relabeled.
[ "addRelabelUnit", "creates", "and", "enables", "a", "runtime", "systemd", "unit", "to", "run", "restorecon", "if", "there", "are", "files", "that", "need", "to", "be", "relabeled", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/files/files.go#L133-L181
19,551
coreos/ignition
config/v3_1_experimental/types/disk.go
partitionNumbersCollide
func (n Disk) partitionNumbersCollide() bool { m := map[int][]Partition{} for _, p := range n.Partitions { if p.Number != 0 { // a number of 0 means next available number, multiple devices can specify this m[p.Number] = append(m[p.Number], p) } } for _, n := range m { if len(n) > 1 { // TODO(vc): return information describing the collision for logging return true } } return false }
go
func (n Disk) partitionNumbersCollide() bool { m := map[int][]Partition{} for _, p := range n.Partitions { if p.Number != 0 { // a number of 0 means next available number, multiple devices can specify this m[p.Number] = append(m[p.Number], p) } } for _, n := range m { if len(n) > 1 { // TODO(vc): return information describing the collision for logging return true } } return false }
[ "func", "(", "n", "Disk", ")", "partitionNumbersCollide", "(", ")", "bool", "{", "m", ":=", "map", "[", "int", "]", "[", "]", "Partition", "{", "}", "\n", "for", "_", ",", "p", ":=", "range", "n", ".", "Partitions", "{", "if", "p", ".", "Number",...
// partitionNumbersCollide returns true if partition numbers in n.Partitions are not unique.
[ "partitionNumbersCollide", "returns", "true", "if", "partition", "numbers", "in", "n", ".", "Partitions", "are", "not", "unique", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/v3_1_experimental/types/disk.go#L56-L71
19,552
coreos/ignition
config/v3_1_experimental/types/disk.go
end
func (p Partition) end() int { if *p.SizeMiB == 0 { // a size of 0 means "fill available", just return the start as the end for those. return *p.StartMiB } return *p.StartMiB + *p.SizeMiB - 1 }
go
func (p Partition) end() int { if *p.SizeMiB == 0 { // a size of 0 means "fill available", just return the start as the end for those. return *p.StartMiB } return *p.StartMiB + *p.SizeMiB - 1 }
[ "func", "(", "p", "Partition", ")", "end", "(", ")", "int", "{", "if", "*", "p", ".", "SizeMiB", "==", "0", "{", "// a size of 0 means \"fill available\", just return the start as the end for those.", "return", "*", "p", ".", "StartMiB", "\n", "}", "\n", "return...
// end returns the last sector of a partition. Only used by partitionsOverlap. Requires non-nil Start and Size.
[ "end", "returns", "the", "last", "sector", "of", "a", "partition", ".", "Only", "used", "by", "partitionsOverlap", ".", "Requires", "non", "-", "nil", "Start", "and", "Size", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/v3_1_experimental/types/disk.go#L88-L94
19,553
coreos/ignition
config/v3_1_experimental/types/disk.go
partitionsOverlap
func (n Disk) partitionsOverlap() bool { for _, p := range n.Partitions { // Starts of 0 are placed by sgdisk into the "largest available block" at that time. // We aren't going to check those for overlap since we don't have the disk geometry. if p.StartMiB == nil || p.SizeMiB == nil || *p.StartMiB == 0 { continue } for _, o := range n.Partitions { if o.StartMiB == nil || o.SizeMiB == nil || p == o || *o.StartMiB == 0 { continue } // is p.StartMiB within o? if *p.StartMiB >= *o.StartMiB && *p.StartMiB <= o.end() { return true } // is p.end() within o? if p.end() >= *o.StartMiB && p.end() <= o.end() { return true } // do p.StartMiB and p.end() straddle o? if *p.StartMiB < *o.StartMiB && p.end() > o.end() { return true } } } return false }
go
func (n Disk) partitionsOverlap() bool { for _, p := range n.Partitions { // Starts of 0 are placed by sgdisk into the "largest available block" at that time. // We aren't going to check those for overlap since we don't have the disk geometry. if p.StartMiB == nil || p.SizeMiB == nil || *p.StartMiB == 0 { continue } for _, o := range n.Partitions { if o.StartMiB == nil || o.SizeMiB == nil || p == o || *o.StartMiB == 0 { continue } // is p.StartMiB within o? if *p.StartMiB >= *o.StartMiB && *p.StartMiB <= o.end() { return true } // is p.end() within o? if p.end() >= *o.StartMiB && p.end() <= o.end() { return true } // do p.StartMiB and p.end() straddle o? if *p.StartMiB < *o.StartMiB && p.end() > o.end() { return true } } } return false }
[ "func", "(", "n", "Disk", ")", "partitionsOverlap", "(", ")", "bool", "{", "for", "_", ",", "p", ":=", "range", "n", ".", "Partitions", "{", "// Starts of 0 are placed by sgdisk into the \"largest available block\" at that time.", "// We aren't going to check those for over...
// partitionsOverlap returns true if any explicitly dimensioned partitions overlap
[ "partitionsOverlap", "returns", "true", "if", "any", "explicitly", "dimensioned", "partitions", "overlap" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/v3_1_experimental/types/disk.go#L97-L127
19,554
coreos/ignition
internal/exec/util/file.go
newHashedReader
func newHashedReader(reader io.ReadCloser, hasher hash.Hash) io.ReadCloser { return struct { io.Reader io.Closer }{ Reader: io.TeeReader(reader, hasher), Closer: reader, } }
go
func newHashedReader(reader io.ReadCloser, hasher hash.Hash) io.ReadCloser { return struct { io.Reader io.Closer }{ Reader: io.TeeReader(reader, hasher), Closer: reader, } }
[ "func", "newHashedReader", "(", "reader", "io", ".", "ReadCloser", ",", "hasher", "hash", ".", "Hash", ")", "io", ".", "ReadCloser", "{", "return", "struct", "{", "io", ".", "Reader", "\n", "io", ".", "Closer", "\n", "}", "{", "Reader", ":", "io", "....
// newHashedReader returns a new ReadCloser that also writes to the provided hash.
[ "newHashedReader", "returns", "a", "new", "ReadCloser", "that", "also", "writes", "to", "the", "provided", "hash", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/file.go#L49-L57
19,555
coreos/ignition
internal/exec/util/file.go
PerformFetch
func (u Util) PerformFetch(f FetchOp) error { path := f.Node.Path if err := MkdirForFile(path); err != nil { return err } // Create a temporary file in the same directory to ensure it's on the same filesystem tmp, err := ioutil.TempFile(filepath.Dir(path), "tmp") if err != nil { return err } defer tmp.Close() // ioutil.TempFile defaults to 0600 if err := tmp.Chmod(DefaultFilePermissions); err != nil { return err } // sometimes the following line will fail (the file might be renamed), // but that's ok (we wanted to keep the file in that case). defer os.Remove(tmp.Name()) err = u.Fetcher.Fetch(f.Url, tmp, f.FetchOptions) if err != nil { u.Crit("Error fetching file %q: %v", path, err) return err } if f.Append { // Make sure that we're appending to a file finfo, err := os.Lstat(path) switch { case os.IsNotExist(err): // No problem, we'll create it. break case err != nil: return err default: if !finfo.Mode().IsRegular() { return fmt.Errorf("can only append to files: %q", path) } } // Open with the default permissions, we'll chown/chmod it later targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, DefaultFilePermissions) if err != nil { return err } defer targetFile.Close() if _, err = tmp.Seek(0, os.SEEK_SET); err != nil { return err } if _, err = io.Copy(targetFile, tmp); err != nil { return err } } else { if err = os.Rename(tmp.Name(), path); err != nil { return err } } return nil }
go
func (u Util) PerformFetch(f FetchOp) error { path := f.Node.Path if err := MkdirForFile(path); err != nil { return err } // Create a temporary file in the same directory to ensure it's on the same filesystem tmp, err := ioutil.TempFile(filepath.Dir(path), "tmp") if err != nil { return err } defer tmp.Close() // ioutil.TempFile defaults to 0600 if err := tmp.Chmod(DefaultFilePermissions); err != nil { return err } // sometimes the following line will fail (the file might be renamed), // but that's ok (we wanted to keep the file in that case). defer os.Remove(tmp.Name()) err = u.Fetcher.Fetch(f.Url, tmp, f.FetchOptions) if err != nil { u.Crit("Error fetching file %q: %v", path, err) return err } if f.Append { // Make sure that we're appending to a file finfo, err := os.Lstat(path) switch { case os.IsNotExist(err): // No problem, we'll create it. break case err != nil: return err default: if !finfo.Mode().IsRegular() { return fmt.Errorf("can only append to files: %q", path) } } // Open with the default permissions, we'll chown/chmod it later targetFile, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, DefaultFilePermissions) if err != nil { return err } defer targetFile.Close() if _, err = tmp.Seek(0, os.SEEK_SET); err != nil { return err } if _, err = io.Copy(targetFile, tmp); err != nil { return err } } else { if err = os.Rename(tmp.Name(), path); err != nil { return err } } return nil }
[ "func", "(", "u", "Util", ")", "PerformFetch", "(", "f", "FetchOp", ")", "error", "{", "path", ":=", "f", ".", "Node", ".", "Path", "\n\n", "if", "err", ":=", "MkdirForFile", "(", "path", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", ...
// PerformFetch performs a fetch operation generated by PrepareFetch, retrieving // the file and writing it to disk. Any encountered errors are returned.
[ "PerformFetch", "performs", "a", "fetch", "operation", "generated", "by", "PrepareFetch", "retrieving", "the", "file", "and", "writing", "it", "to", "disk", ".", "Any", "encountered", "errors", "are", "returned", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/file.go#L173-L237
19,556
coreos/ignition
internal/exec/util/file.go
MkdirForFile
func MkdirForFile(path string) error { return os.MkdirAll(filepath.Dir(path), DefaultDirectoryPermissions) }
go
func MkdirForFile(path string) error { return os.MkdirAll(filepath.Dir(path), DefaultDirectoryPermissions) }
[ "func", "MkdirForFile", "(", "path", "string", ")", "error", "{", "return", "os", ".", "MkdirAll", "(", "filepath", ".", "Dir", "(", "path", ")", ",", "DefaultDirectoryPermissions", ")", "\n", "}" ]
// MkdirForFile helper creates the directory components of path.
[ "MkdirForFile", "helper", "creates", "the", "directory", "components", "of", "path", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/file.go#L240-L242
19,557
coreos/ignition
internal/exec/util/file.go
getFileOwnerAndMode
func getFileOwnerAndMode(path string) (int, int, os.FileMode) { finfo, err := os.Stat(path) if err != nil { return 0, 0, 0 } return int(finfo.Sys().(*syscall.Stat_t).Uid), int(finfo.Sys().(*syscall.Stat_t).Gid), finfo.Mode() }
go
func getFileOwnerAndMode(path string) (int, int, os.FileMode) { finfo, err := os.Stat(path) if err != nil { return 0, 0, 0 } return int(finfo.Sys().(*syscall.Stat_t).Uid), int(finfo.Sys().(*syscall.Stat_t).Gid), finfo.Mode() }
[ "func", "getFileOwnerAndMode", "(", "path", "string", ")", "(", "int", ",", "int", ",", "os", ".", "FileMode", ")", "{", "finfo", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0",...
// getFileOwner will return the uid and gid for the file at a given path. If the // file doesn't exist, or some other error is encountered when running stat on // the path, 0, 0, and 0 will be returned.
[ "getFileOwner", "will", "return", "the", "uid", "and", "gid", "for", "the", "file", "at", "a", "given", "path", ".", "If", "the", "file", "doesn", "t", "exist", "or", "some", "other", "error", "is", "encountered", "when", "running", "stat", "on", "the", ...
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/file.go#L247-L253
19,558
coreos/ignition
internal/exec/util/file.go
ResolveNodeUidAndGid
func (u Util) ResolveNodeUidAndGid(n types.Node, defaultUid, defaultGid int) (int, int, error) { var err error uid, gid := defaultUid, defaultGid if n.User.ID != nil { uid = *n.User.ID } else if n.User.Name != nil && *n.User.Name != "" { uid, err = u.getUserID(*n.User.Name) if err != nil { return 0, 0, err } } if n.Group.ID != nil { gid = *n.Group.ID } else if n.Group.Name != nil && *n.Group.Name != "" { gid, err = u.getGroupID(*n.Group.Name) if err != nil { return 0, 0, err } } return uid, gid, nil }
go
func (u Util) ResolveNodeUidAndGid(n types.Node, defaultUid, defaultGid int) (int, int, error) { var err error uid, gid := defaultUid, defaultGid if n.User.ID != nil { uid = *n.User.ID } else if n.User.Name != nil && *n.User.Name != "" { uid, err = u.getUserID(*n.User.Name) if err != nil { return 0, 0, err } } if n.Group.ID != nil { gid = *n.Group.ID } else if n.Group.Name != nil && *n.Group.Name != "" { gid, err = u.getGroupID(*n.Group.Name) if err != nil { return 0, 0, err } } return uid, gid, nil }
[ "func", "(", "u", "Util", ")", "ResolveNodeUidAndGid", "(", "n", "types", ".", "Node", ",", "defaultUid", ",", "defaultGid", "int", ")", "(", "int", ",", "int", ",", "error", ")", "{", "var", "err", "error", "\n", "uid", ",", "gid", ":=", "defaultUid...
// ResolveNodeUidAndGid attempts to convert a types.Node into a concrete uid and // gid. If the node has the User.ID field set, that's used for the uid. If the // node has the User.Name field set, a username -> uid lookup is performed. If // neither are set, it returns the passed in defaultUid. The logic is identical // for gids with equivalent fields.
[ "ResolveNodeUidAndGid", "attempts", "to", "convert", "a", "types", ".", "Node", "into", "a", "concrete", "uid", "and", "gid", ".", "If", "the", "node", "has", "the", "User", ".", "ID", "field", "set", "that", "s", "used", "for", "the", "uid", ".", "If"...
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/file.go#L260-L282
19,559
coreos/ignition
internal/exec/stages/files/units.go
createUnits
func (s *stage) createUnits(config types.Config) error { enabledOneUnit := false for _, unit := range config.Systemd.Units { if err := s.writeSystemdUnit(unit, false); err != nil { return err } if unit.Enabled != nil { if *unit.Enabled { if err := s.Logger.LogOp( func() error { return s.EnableUnit(unit) }, "enabling unit %q", unit.Name, ); err != nil { return err } } else { if err := s.Logger.LogOp( func() error { return s.DisableUnit(unit) }, "disabling unit %q", unit.Name, ); err != nil { return err } } enabledOneUnit = true } if unit.Mask != nil && *unit.Mask { if err := s.Logger.LogOp( func() error { return s.MaskUnit(unit) }, "masking unit %q", unit.Name, ); err != nil { return err } } } // and relabel the preset file itself if we enabled/disabled something if enabledOneUnit { s.relabel(util.PresetPath) } return nil }
go
func (s *stage) createUnits(config types.Config) error { enabledOneUnit := false for _, unit := range config.Systemd.Units { if err := s.writeSystemdUnit(unit, false); err != nil { return err } if unit.Enabled != nil { if *unit.Enabled { if err := s.Logger.LogOp( func() error { return s.EnableUnit(unit) }, "enabling unit %q", unit.Name, ); err != nil { return err } } else { if err := s.Logger.LogOp( func() error { return s.DisableUnit(unit) }, "disabling unit %q", unit.Name, ); err != nil { return err } } enabledOneUnit = true } if unit.Mask != nil && *unit.Mask { if err := s.Logger.LogOp( func() error { return s.MaskUnit(unit) }, "masking unit %q", unit.Name, ); err != nil { return err } } } // and relabel the preset file itself if we enabled/disabled something if enabledOneUnit { s.relabel(util.PresetPath) } return nil }
[ "func", "(", "s", "*", "stage", ")", "createUnits", "(", "config", "types", ".", "Config", ")", "error", "{", "enabledOneUnit", ":=", "false", "\n", "for", "_", ",", "unit", ":=", "range", "config", ".", "Systemd", ".", "Units", "{", "if", "err", ":=...
// createUnits creates the units listed under systemd.units.
[ "createUnits", "creates", "the", "units", "listed", "under", "systemd", ".", "units", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/files/units.go#L28-L66
19,560
coreos/ignition
internal/exec/stages/files/units.go
writeSystemdUnit
func (s *stage) writeSystemdUnit(unit types.Unit, runtime bool) error { // use a different DestDir if it's runtime so it affects our /run (but not // if we're running locally through blackbox tests) u := s.Util if runtime && !distro.BlackboxTesting() { u.DestDir = "/" } return s.Logger.LogOp(func() error { relabeledDropinDir := false for _, dropin := range unit.Dropins { if dropin.Contents == nil || *dropin.Contents == "" { continue } f, err := u.FileFromSystemdUnitDropin(unit, dropin, runtime) if err != nil { s.Logger.Crit("error converting systemd dropin: %v", err) return err } relabelPath := f.Node.Path if !runtime { // trim off prefix since this needs to be relative to the sysroot if !strings.HasPrefix(f.Node.Path, s.DestDir) { panic(fmt.Sprintf("Dropin path %s isn't under prefix %s", f.Node.Path, s.DestDir)) } relabelPath = f.Node.Path[len(s.DestDir):] } if err := s.Logger.LogOp( func() error { return u.PerformFetch(f) }, "writing systemd drop-in %q at %q", dropin.Name, f.Node.Path, ); err != nil { return err } if !relabeledDropinDir { s.relabel(filepath.Dir(relabelPath)) relabeledDropinDir = true } } if unit.Contents == nil || *unit.Contents == "" { return nil } f, err := u.FileFromSystemdUnit(unit, runtime) if err != nil { s.Logger.Crit("error converting unit: %v", err) return err } relabelPath := f.Node.Path if !runtime { // trim off prefix since this needs to be relative to the sysroot if !strings.HasPrefix(f.Node.Path, s.DestDir) { panic(fmt.Sprintf("Unit path %s isn't under prefix %s", f.Node.Path, s.DestDir)) } relabelPath = f.Node.Path[len(s.DestDir):] } if err := s.Logger.LogOp( func() error { return u.PerformFetch(f) }, "writing unit %q at %q", unit.Name, f.Node.Path, ); err != nil { return err } s.relabel(relabelPath) return nil }, "processing unit %q", unit.Name) }
go
func (s *stage) writeSystemdUnit(unit types.Unit, runtime bool) error { // use a different DestDir if it's runtime so it affects our /run (but not // if we're running locally through blackbox tests) u := s.Util if runtime && !distro.BlackboxTesting() { u.DestDir = "/" } return s.Logger.LogOp(func() error { relabeledDropinDir := false for _, dropin := range unit.Dropins { if dropin.Contents == nil || *dropin.Contents == "" { continue } f, err := u.FileFromSystemdUnitDropin(unit, dropin, runtime) if err != nil { s.Logger.Crit("error converting systemd dropin: %v", err) return err } relabelPath := f.Node.Path if !runtime { // trim off prefix since this needs to be relative to the sysroot if !strings.HasPrefix(f.Node.Path, s.DestDir) { panic(fmt.Sprintf("Dropin path %s isn't under prefix %s", f.Node.Path, s.DestDir)) } relabelPath = f.Node.Path[len(s.DestDir):] } if err := s.Logger.LogOp( func() error { return u.PerformFetch(f) }, "writing systemd drop-in %q at %q", dropin.Name, f.Node.Path, ); err != nil { return err } if !relabeledDropinDir { s.relabel(filepath.Dir(relabelPath)) relabeledDropinDir = true } } if unit.Contents == nil || *unit.Contents == "" { return nil } f, err := u.FileFromSystemdUnit(unit, runtime) if err != nil { s.Logger.Crit("error converting unit: %v", err) return err } relabelPath := f.Node.Path if !runtime { // trim off prefix since this needs to be relative to the sysroot if !strings.HasPrefix(f.Node.Path, s.DestDir) { panic(fmt.Sprintf("Unit path %s isn't under prefix %s", f.Node.Path, s.DestDir)) } relabelPath = f.Node.Path[len(s.DestDir):] } if err := s.Logger.LogOp( func() error { return u.PerformFetch(f) }, "writing unit %q at %q", unit.Name, f.Node.Path, ); err != nil { return err } s.relabel(relabelPath) return nil }, "processing unit %q", unit.Name) }
[ "func", "(", "s", "*", "stage", ")", "writeSystemdUnit", "(", "unit", "types", ".", "Unit", ",", "runtime", "bool", ")", "error", "{", "// use a different DestDir if it's runtime so it affects our /run (but not", "// if we're running locally through blackbox tests)", "u", "...
// writeSystemdUnit creates the specified unit and any dropins for that unit. // If the contents of the unit or are empty, the unit is not created. The same // applies to the unit's dropins.
[ "writeSystemdUnit", "creates", "the", "specified", "unit", "and", "any", "dropins", "for", "that", "unit", ".", "If", "the", "contents", "of", "the", "unit", "or", "are", "empty", "the", "unit", "is", "not", "created", ".", "The", "same", "applies", "to", ...
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/files/units.go#L71-L137
19,561
coreos/ignition
internal/exec/util/blkid.go
cResultToErr
func cResultToErr(res C.result_t, device string) error { switch res { case C.RESULT_OK: return nil case C.RESULT_OPEN_FAILED: return fmt.Errorf("failed to open %q", device) case C.RESULT_PROBE_FAILED: return fmt.Errorf("failed to probe %q", device) case C.RESULT_LOOKUP_FAILED: return fmt.Errorf("failed to lookup attribute on %q", device) case C.RESULT_NO_PARTITION_TABLE: return fmt.Errorf("no partition table found on %q", device) case C.RESULT_BAD_INDEX: return fmt.Errorf("bad partition index specified for device %q", device) case C.RESULT_GET_PARTLIST_FAILED: return fmt.Errorf("failed to get list of partitions on %q", device) case C.RESULT_DISK_HAS_NO_TYPE: return fmt.Errorf("%q has no type string, despite having a partition table", device) case C.RESULT_DISK_NOT_GPT: return fmt.Errorf("%q is not a gpt disk", device) case C.RESULT_BAD_PARAMS: return fmt.Errorf("internal error. bad params passed while handling %q", device) case C.RESULT_OVERFLOW: return fmt.Errorf("internal error. libblkid returned impossibly large value when handling %q", device) case C.RESULT_NO_TOPO: return fmt.Errorf("failed to get topology information for %q", device) case C.RESULT_NO_SECTOR_SIZE: return fmt.Errorf("failed to get logical sector size for %q", device) case C.RESULT_BAD_SECTOR_SIZE: return fmt.Errorf("logical sector size for %q was not a multiple of 512", device) default: return fmt.Errorf("Unknown error while handling %q. err code: %d", device, res) } }
go
func cResultToErr(res C.result_t, device string) error { switch res { case C.RESULT_OK: return nil case C.RESULT_OPEN_FAILED: return fmt.Errorf("failed to open %q", device) case C.RESULT_PROBE_FAILED: return fmt.Errorf("failed to probe %q", device) case C.RESULT_LOOKUP_FAILED: return fmt.Errorf("failed to lookup attribute on %q", device) case C.RESULT_NO_PARTITION_TABLE: return fmt.Errorf("no partition table found on %q", device) case C.RESULT_BAD_INDEX: return fmt.Errorf("bad partition index specified for device %q", device) case C.RESULT_GET_PARTLIST_FAILED: return fmt.Errorf("failed to get list of partitions on %q", device) case C.RESULT_DISK_HAS_NO_TYPE: return fmt.Errorf("%q has no type string, despite having a partition table", device) case C.RESULT_DISK_NOT_GPT: return fmt.Errorf("%q is not a gpt disk", device) case C.RESULT_BAD_PARAMS: return fmt.Errorf("internal error. bad params passed while handling %q", device) case C.RESULT_OVERFLOW: return fmt.Errorf("internal error. libblkid returned impossibly large value when handling %q", device) case C.RESULT_NO_TOPO: return fmt.Errorf("failed to get topology information for %q", device) case C.RESULT_NO_SECTOR_SIZE: return fmt.Errorf("failed to get logical sector size for %q", device) case C.RESULT_BAD_SECTOR_SIZE: return fmt.Errorf("logical sector size for %q was not a multiple of 512", device) default: return fmt.Errorf("Unknown error while handling %q. err code: %d", device, res) } }
[ "func", "cResultToErr", "(", "res", "C", ".", "result_t", ",", "device", "string", ")", "error", "{", "switch", "res", "{", "case", "C", ".", "RESULT_OK", ":", "return", "nil", "\n", "case", "C", ".", "RESULT_OPEN_FAILED", ":", "return", "fmt", ".", "E...
// cResultToErr takes a result_t from the blkid c code and a device it was operating on // and returns a golang error describing the result code.
[ "cResultToErr", "takes", "a", "result_t", "from", "the", "blkid", "c", "code", "and", "a", "device", "it", "was", "operating", "on", "and", "returns", "a", "golang", "error", "describing", "the", "result", "code", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/blkid.go#L80-L113
19,562
coreos/ignition
internal/providers/packet/packet.go
PostStatus
func PostStatus(stageName string, f resource.Fetcher, errMsg error) error { f.Logger.Info("POST message to Packet Timeline") // fetch JSON from https://metadata.packet.net/metadata data, err := f.FetchToBuffer(metadataUrl, resource.FetchOptions{ Headers: nil, }) if err != nil { return err } if data == nil { return ErrValidFetchEmptyData } metadata := struct { PhoneHomeURL string `json:"phone_home_url"` }{} err = json.Unmarshal(data, &metadata) if err != nil { return err } phonehomeURL := metadata.PhoneHomeURL // to get phonehome IPv4 phonehomeURL = strings.TrimSuffix(phonehomeURL, "/phone-home") // POST Message to phonehome IP postMessageURL := phonehomeURL + "/events" return postMessage(stageName, errMsg, postMessageURL) }
go
func PostStatus(stageName string, f resource.Fetcher, errMsg error) error { f.Logger.Info("POST message to Packet Timeline") // fetch JSON from https://metadata.packet.net/metadata data, err := f.FetchToBuffer(metadataUrl, resource.FetchOptions{ Headers: nil, }) if err != nil { return err } if data == nil { return ErrValidFetchEmptyData } metadata := struct { PhoneHomeURL string `json:"phone_home_url"` }{} err = json.Unmarshal(data, &metadata) if err != nil { return err } phonehomeURL := metadata.PhoneHomeURL // to get phonehome IPv4 phonehomeURL = strings.TrimSuffix(phonehomeURL, "/phone-home") // POST Message to phonehome IP postMessageURL := phonehomeURL + "/events" return postMessage(stageName, errMsg, postMessageURL) }
[ "func", "PostStatus", "(", "stageName", "string", ",", "f", "resource", ".", "Fetcher", ",", "errMsg", "error", ")", "error", "{", "f", ".", "Logger", ".", "Info", "(", "\"", "\"", ")", "\n", "// fetch JSON from https://metadata.packet.net/metadata", "data", "...
// PostStatus posts a message that will show on the Packet Instance Timeline
[ "PostStatus", "posts", "a", "message", "that", "will", "show", "on", "the", "Packet", "Instance", "Timeline" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/providers/packet/packet.go#L70-L96
19,563
coreos/ignition
internal/providers/packet/packet.go
postMessage
func postMessage(stageName string, e error, url string) error { stageName = "[" + stageName + "]" type mStruct struct { State string `json:"state"` Message string `json:"message"` } m := mStruct{} if e != nil { m = mStruct{ State: "failed", Message: stageName + " Ignition error: " + e.Error(), } } else { m = mStruct{ State: "running", Message: stageName + " Ignition status: finished successfully", } } messageJSON, err := json.Marshal(m) if err != nil { return err } postReq, err := http.NewRequest("POST", url, bytes.NewBuffer(messageJSON)) if err != nil { return err } postReq.Header.Set("Content-Type", "application/json") client := &http.Client{} respPost, err := client.Do(postReq) if err != nil { return err } defer respPost.Body.Close() return err }
go
func postMessage(stageName string, e error, url string) error { stageName = "[" + stageName + "]" type mStruct struct { State string `json:"state"` Message string `json:"message"` } m := mStruct{} if e != nil { m = mStruct{ State: "failed", Message: stageName + " Ignition error: " + e.Error(), } } else { m = mStruct{ State: "running", Message: stageName + " Ignition status: finished successfully", } } messageJSON, err := json.Marshal(m) if err != nil { return err } postReq, err := http.NewRequest("POST", url, bytes.NewBuffer(messageJSON)) if err != nil { return err } postReq.Header.Set("Content-Type", "application/json") client := &http.Client{} respPost, err := client.Do(postReq) if err != nil { return err } defer respPost.Body.Close() return err }
[ "func", "postMessage", "(", "stageName", "string", ",", "e", "error", ",", "url", "string", ")", "error", "{", "stageName", "=", "\"", "\"", "+", "stageName", "+", "\"", "\"", "\n\n", "type", "mStruct", "struct", "{", "State", "string", "`json:\"state\"`",...
// postMessage makes a post request with the supplied message to the url
[ "postMessage", "makes", "a", "post", "request", "with", "the", "supplied", "message", "to", "the", "url" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/providers/packet/packet.go#L99-L135
19,564
coreos/ignition
internal/exec/stages/disks/disks.go
waitOnDevices
func (s stage) waitOnDevices(devs []string, ctxt string) error { if err := s.LogOp( func() error { return systemd.WaitOnDevices(devs, ctxt) }, "waiting for devices %v", devs, ); err != nil { return fmt.Errorf("failed to wait on %s devs: %v", ctxt, err) } return nil }
go
func (s stage) waitOnDevices(devs []string, ctxt string) error { if err := s.LogOp( func() error { return systemd.WaitOnDevices(devs, ctxt) }, "waiting for devices %v", devs, ); err != nil { return fmt.Errorf("failed to wait on %s devs: %v", ctxt, err) } return nil }
[ "func", "(", "s", "stage", ")", "waitOnDevices", "(", "devs", "[", "]", "string", ",", "ctxt", "string", ")", "error", "{", "if", "err", ":=", "s", ".", "LogOp", "(", "func", "(", ")", "error", "{", "return", "systemd", ".", "WaitOnDevices", "(", "...
// waitOnDevices waits for the devices enumerated in devs as a logged operation // using ctxt for the logging and systemd unit identity.
[ "waitOnDevices", "waits", "for", "the", "devices", "enumerated", "in", "devs", "as", "a", "logged", "operation", "using", "ctxt", "for", "the", "logging", "and", "systemd", "unit", "identity", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/disks.go#L126-L135
19,565
coreos/ignition
internal/exec/stages/disks/disks.go
createDeviceAliases
func (s stage) createDeviceAliases(devs []string) error { for _, dev := range devs { target, err := util.CreateDeviceAlias(dev) if err != nil { return fmt.Errorf("failed to create device alias for %q: %v", dev, err) } s.Logger.Info("created device alias for %q: %q -> %q", dev, util.DeviceAlias(dev), target) } return nil }
go
func (s stage) createDeviceAliases(devs []string) error { for _, dev := range devs { target, err := util.CreateDeviceAlias(dev) if err != nil { return fmt.Errorf("failed to create device alias for %q: %v", dev, err) } s.Logger.Info("created device alias for %q: %q -> %q", dev, util.DeviceAlias(dev), target) } return nil }
[ "func", "(", "s", "stage", ")", "createDeviceAliases", "(", "devs", "[", "]", "string", ")", "error", "{", "for", "_", ",", "dev", ":=", "range", "devs", "{", "target", ",", "err", ":=", "util", ".", "CreateDeviceAlias", "(", "dev", ")", "\n", "if", ...
// createDeviceAliases creates device aliases for every device in devs.
[ "createDeviceAliases", "creates", "device", "aliases", "for", "every", "device", "in", "devs", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/disks.go#L138-L148
19,566
coreos/ignition
internal/exec/stages/disks/disks.go
waitOnDevicesAndCreateAliases
func (s stage) waitOnDevicesAndCreateAliases(devs []string, ctxt string) error { if err := s.waitOnDevices(devs, ctxt); err != nil { return err } if err := s.createDeviceAliases(devs); err != nil { return err } return nil }
go
func (s stage) waitOnDevicesAndCreateAliases(devs []string, ctxt string) error { if err := s.waitOnDevices(devs, ctxt); err != nil { return err } if err := s.createDeviceAliases(devs); err != nil { return err } return nil }
[ "func", "(", "s", "stage", ")", "waitOnDevicesAndCreateAliases", "(", "devs", "[", "]", "string", ",", "ctxt", "string", ")", "error", "{", "if", "err", ":=", "s", ".", "waitOnDevices", "(", "devs", ",", "ctxt", ")", ";", "err", "!=", "nil", "{", "re...
// waitOnDevicesAndCreateAliases simply wraps waitOnDevices and createDeviceAliases.
[ "waitOnDevicesAndCreateAliases", "simply", "wraps", "waitOnDevices", "and", "createDeviceAliases", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/disks/disks.go#L151-L161
19,567
coreos/ignition
config/v3_1_experimental/config.go
Parse
func Parse(rawConfig []byte) (types.Config, report.Report, error) { if isEmpty(rawConfig) { return types.Config{}, report.Report{}, errors.ErrEmpty } var config types.Config if rpt, err := util.HandleParseErrors(rawConfig, &config); err != nil { return types.Config{}, rpt, err } version, err := semver.NewVersion(config.Ignition.Version) if err != nil || *version != types.MaxVersion { return types.Config{}, report.Report{}, errors.ErrUnknownVersion } rpt := validate.ValidateConfig(rawConfig, config) if rpt.IsFatal() { return types.Config{}, rpt, errors.ErrInvalid } return config, rpt, nil }
go
func Parse(rawConfig []byte) (types.Config, report.Report, error) { if isEmpty(rawConfig) { return types.Config{}, report.Report{}, errors.ErrEmpty } var config types.Config if rpt, err := util.HandleParseErrors(rawConfig, &config); err != nil { return types.Config{}, rpt, err } version, err := semver.NewVersion(config.Ignition.Version) if err != nil || *version != types.MaxVersion { return types.Config{}, report.Report{}, errors.ErrUnknownVersion } rpt := validate.ValidateConfig(rawConfig, config) if rpt.IsFatal() { return types.Config{}, rpt, errors.ErrInvalid } return config, rpt, nil }
[ "func", "Parse", "(", "rawConfig", "[", "]", "byte", ")", "(", "types", ".", "Config", ",", "report", ".", "Report", ",", "error", ")", "{", "if", "isEmpty", "(", "rawConfig", ")", "{", "return", "types", ".", "Config", "{", "}", ",", "report", "."...
// Parse parses the raw config into a types.Config struct and generates a report of any // errors, warnings, info, and deprecations it encountered
[ "Parse", "parses", "the", "raw", "config", "into", "a", "types", ".", "Config", "struct", "and", "generates", "a", "report", "of", "any", "errors", "warnings", "info", "and", "deprecations", "it", "encountered" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/v3_1_experimental/config.go#L41-L63
19,568
coreos/ignition
config/validate/report/report.go
addFromError
func (r *Report) addFromError(err error, severity entryKind) { if err == nil { return } r.Add(Entry{ Kind: severity, Message: err.Error(), }) }
go
func (r *Report) addFromError(err error, severity entryKind) { if err == nil { return } r.Add(Entry{ Kind: severity, Message: err.Error(), }) }
[ "func", "(", "r", "*", "Report", ")", "addFromError", "(", "err", "error", ",", "severity", "entryKind", ")", "{", "if", "err", "==", "nil", "{", "return", "\n", "}", "\n", "r", ".", "Add", "(", "Entry", "{", "Kind", ":", "severity", ",", "Message"...
// Helpers to cut verbosity
[ "Helpers", "to", "cut", "verbosity" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/validate/report/report.go#L47-L55
19,569
coreos/ignition
config/validate/report/report.go
IsFatal
func (r Report) IsFatal() bool { for _, entry := range r.Entries { if entry.Kind == EntryError { return true } } return false }
go
func (r Report) IsFatal() bool { for _, entry := range r.Entries { if entry.Kind == EntryError { return true } } return false }
[ "func", "(", "r", "Report", ")", "IsFatal", "(", ")", "bool", "{", "for", "_", ",", "entry", ":=", "range", "r", ".", "Entries", "{", "if", "entry", ".", "Kind", "==", "EntryError", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "fa...
// IsFatal returns if there were any errors that make the config invalid
[ "IsFatal", "returns", "if", "there", "were", "any", "errors", "that", "make", "the", "config", "invalid" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/validate/report/report.go#L132-L139
19,570
coreos/ignition
config/validate/report/report.go
IsDeprecated
func (r Report) IsDeprecated() bool { for _, entry := range r.Entries { if entry.Kind == EntryDeprecated { return true } } return false }
go
func (r Report) IsDeprecated() bool { for _, entry := range r.Entries { if entry.Kind == EntryDeprecated { return true } } return false }
[ "func", "(", "r", "Report", ")", "IsDeprecated", "(", ")", "bool", "{", "for", "_", ",", "entry", ":=", "range", "r", ".", "Entries", "{", "if", "entry", ".", "Kind", "==", "EntryDeprecated", "{", "return", "true", "\n", "}", "\n", "}", "\n", "retu...
// IsDeprecated returns if the report has deprecations
[ "IsDeprecated", "returns", "if", "the", "report", "has", "deprecations" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/config/validate/report/report.go#L142-L149
19,571
coreos/ignition
internal/exec/stages/mount/mount.go
checkForNonDirectories
func checkForNonDirectories(path string) error { p := "/" for _, component := range util.SplitPath(path) { p = filepath.Join(p, component) st, err := os.Lstat(p) if err != nil && os.IsNotExist(err) { return nil // nonexistent is ok } else if err != nil { return err } if !st.Mode().IsDir() { return fmt.Errorf("Mount path %q contains non-directory component %q", path, p) } } return nil }
go
func checkForNonDirectories(path string) error { p := "/" for _, component := range util.SplitPath(path) { p = filepath.Join(p, component) st, err := os.Lstat(p) if err != nil && os.IsNotExist(err) { return nil // nonexistent is ok } else if err != nil { return err } if !st.Mode().IsDir() { return fmt.Errorf("Mount path %q contains non-directory component %q", path, p) } } return nil }
[ "func", "checkForNonDirectories", "(", "path", "string", ")", "error", "{", "p", ":=", "\"", "\"", "\n", "for", "_", ",", "component", ":=", "range", "util", ".", "SplitPath", "(", "path", ")", "{", "p", "=", "filepath", ".", "Join", "(", "p", ",", ...
// checkForNonDirectories returns an error if any element of path is not a directory
[ "checkForNonDirectories", "returns", "an", "error", "if", "any", "element", "of", "path", "is", "not", "a", "directory" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/stages/mount/mount.go#L83-L98
19,572
coreos/ignition
internal/exec/util/device_alias.go
DeviceAlias
func DeviceAlias(path string) string { return filepath.Join(deviceAliasDir, filepath.Clean(path)) }
go
func DeviceAlias(path string) string { return filepath.Join(deviceAliasDir, filepath.Clean(path)) }
[ "func", "DeviceAlias", "(", "path", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "deviceAliasDir", ",", "filepath", ".", "Clean", "(", "path", ")", ")", "\n", "}" ]
// DeviceAlias returns the aliased form of the supplied path. // Note device paths in ignition are always absolute.
[ "DeviceAlias", "returns", "the", "aliased", "form", "of", "the", "supplied", "path", ".", "Note", "device", "paths", "in", "ignition", "are", "always", "absolute", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/device_alias.go#L33-L35
19,573
coreos/ignition
internal/exec/util/device_alias.go
evalSymlinks
func evalSymlinks(path string) (res string, err error) { for i := 0; i < retrySymlinkCount; i++ { res, err = filepath.EvalSymlinks(path) if err == nil { return res, nil } else if os.IsNotExist(err) { time.Sleep(retrySymlinkDelay) } else { return "", err } } return "", fmt.Errorf("Failed to evaluate symlink after %v: %v", retrySymlinkTimeout, err) }
go
func evalSymlinks(path string) (res string, err error) { for i := 0; i < retrySymlinkCount; i++ { res, err = filepath.EvalSymlinks(path) if err == nil { return res, nil } else if os.IsNotExist(err) { time.Sleep(retrySymlinkDelay) } else { return "", err } } return "", fmt.Errorf("Failed to evaluate symlink after %v: %v", retrySymlinkTimeout, err) }
[ "func", "evalSymlinks", "(", "path", "string", ")", "(", "res", "string", ",", "err", "error", ")", "{", "for", "i", ":=", "0", ";", "i", "<", "retrySymlinkCount", ";", "i", "++", "{", "res", ",", "err", "=", "filepath", ".", "EvalSymlinks", "(", "...
// evalSymlinks wraps filepath.EvalSymlinks, retrying if it fails
[ "evalSymlinks", "wraps", "filepath", ".", "EvalSymlinks", "retrying", "if", "it", "fails" ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/device_alias.go#L38-L51
19,574
coreos/ignition
internal/exec/util/device_alias.go
CreateDeviceAlias
func CreateDeviceAlias(path string) (string, error) { target, err := evalSymlinks(path) if err != nil { return "", err } alias := DeviceAlias(path) if err := os.Remove(alias); err != nil { if !os.IsNotExist(err) { return "", err } if err = os.MkdirAll(filepath.Dir(alias), 0750); err != nil { return "", err } } if err = os.Symlink(target, alias); err != nil { return "", err } return target, nil }
go
func CreateDeviceAlias(path string) (string, error) { target, err := evalSymlinks(path) if err != nil { return "", err } alias := DeviceAlias(path) if err := os.Remove(alias); err != nil { if !os.IsNotExist(err) { return "", err } if err = os.MkdirAll(filepath.Dir(alias), 0750); err != nil { return "", err } } if err = os.Symlink(target, alias); err != nil { return "", err } return target, nil }
[ "func", "CreateDeviceAlias", "(", "path", "string", ")", "(", "string", ",", "error", ")", "{", "target", ",", "err", ":=", "evalSymlinks", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", ...
// CreateDeviceAlias creates a device alias for the supplied path. // On success the canonicalized path used as the alias target is returned.
[ "CreateDeviceAlias", "creates", "a", "device", "alias", "for", "the", "supplied", "path", ".", "On", "success", "the", "canonicalized", "path", "used", "as", "the", "alias", "target", "is", "returned", "." ]
1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9
https://github.com/coreos/ignition/blob/1eeb201e9e6045383cba2e37ad53b3f49ca7b5a9/internal/exec/util/device_alias.go#L55-L78
19,575
decred/dcrdata
exchanges/websocket.go
Read
func (client *socketClient) Read() (msg []byte, err error) { _, msg, err = client.conn.ReadMessage() return }
go
func (client *socketClient) Read() (msg []byte, err error) { _, msg, err = client.conn.ReadMessage() return }
[ "func", "(", "client", "*", "socketClient", ")", "Read", "(", ")", "(", "msg", "[", "]", "byte", ",", "err", "error", ")", "{", "_", ",", "msg", ",", "err", "=", "client", ".", "conn", ".", "ReadMessage", "(", ")", "\n", "return", "\n", "}" ]
// Read is a wrapper for gorilla's ReadMessage that satisfies websocketFeed.Read.
[ "Read", "is", "a", "wrapper", "for", "gorilla", "s", "ReadMessage", "that", "satisfies", "websocketFeed", ".", "Read", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/websocket.go#L50-L53
19,576
decred/dcrdata
exchanges/websocket.go
Write
func (client *socketClient) Write(msg interface{}) error { client.writeMtx.Lock() defer client.writeMtx.Unlock() bytes, err := json.Marshal(msg) if err != nil { return err } return client.conn.WriteMessage(websocket.TextMessage, bytes) }
go
func (client *socketClient) Write(msg interface{}) error { client.writeMtx.Lock() defer client.writeMtx.Unlock() bytes, err := json.Marshal(msg) if err != nil { return err } return client.conn.WriteMessage(websocket.TextMessage, bytes) }
[ "func", "(", "client", "*", "socketClient", ")", "Write", "(", "msg", "interface", "{", "}", ")", "error", "{", "client", ".", "writeMtx", ".", "Lock", "(", ")", "\n", "defer", "client", ".", "writeMtx", ".", "Unlock", "(", ")", "\n", "bytes", ",", ...
// Write is a wrapper for gorilla WriteMessage. Satisfies websocketFeed.Write. // JSON marshaling is performed before sending. Writes are sequenced with a // mutex lock for per-connection multi-threaded use.
[ "Write", "is", "a", "wrapper", "for", "gorilla", "WriteMessage", ".", "Satisfies", "websocketFeed", ".", "Write", ".", "JSON", "marshaling", "is", "performed", "before", "sending", ".", "Writes", "are", "sequenced", "with", "a", "mutex", "lock", "for", "per", ...
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/websocket.go#L58-L66
19,577
decred/dcrdata
exchanges/websocket.go
newSocketConnection
func newSocketConnection(cfg *socketConfig) (websocketFeed, error) { dialer := &websocket.Dialer{ Proxy: http.ProxyFromEnvironment, // Same as DefaultDialer. HandshakeTimeout: 10 * time.Second, // DefaultDialer is 45 seconds. } conn, _, err := dialer.Dial(cfg.address, nil) if err != nil { return nil, err } return &socketClient{ conn: conn, done: make(chan struct{}), }, nil }
go
func newSocketConnection(cfg *socketConfig) (websocketFeed, error) { dialer := &websocket.Dialer{ Proxy: http.ProxyFromEnvironment, // Same as DefaultDialer. HandshakeTimeout: 10 * time.Second, // DefaultDialer is 45 seconds. } conn, _, err := dialer.Dial(cfg.address, nil) if err != nil { return nil, err } return &socketClient{ conn: conn, done: make(chan struct{}), }, nil }
[ "func", "newSocketConnection", "(", "cfg", "*", "socketConfig", ")", "(", "websocketFeed", ",", "error", ")", "{", "dialer", ":=", "&", "websocket", ".", "Dialer", "{", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "// Same as DefaultDialer.", "Handsha...
// Constructor for a socketClient, but returned as a websocketFeed.
[ "Constructor", "for", "a", "socketClient", "but", "returned", "as", "a", "websocketFeed", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/exchanges/websocket.go#L80-L94
19,578
decred/dcrdata
cmd/rebuilddb2/log.go
InitLogger
func InitLogger() error { logFilePath, _ := filepath.Abs(logFile) var err error logFILE, err = os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664) if err != nil { return fmt.Errorf("Error opening log file: %v", err) } logrus.SetOutput(io.MultiWriter(logFILE, os.Stdout)) logrus.SetLevel(logrus.DebugLevel) logrus.SetFormatter(&prefix_fmt.TextFormatter{ ForceColors: true, ForceFormatting: true, FullTimestamp: true, }) //logrus.SetOutput(ansicolor.NewAnsiColorWriter(os.Stdout)) //logrus.SetOutput(colorable.NewColorableStdout()) log = logrus.New() log.Level = logrus.DebugLevel log.Formatter = &prefix_fmt.TextFormatter{ ForceColors: true, ForceFormatting: true, FullTimestamp: true, TimestampFormat: "02 Jan 06 15:04:05.00 -0700", } //log.Out = colorable.NewColorableStdout() //log.Out = colorable.NewNonColorable(io.MultiWriter(logFILE, os.Stdout)) log.Out = ansicolor.NewAnsiColorWriter(io.MultiWriter(logFILE, os.Stdout)) log.Debug("rebuilddb logger started.") return nil }
go
func InitLogger() error { logFilePath, _ := filepath.Abs(logFile) var err error logFILE, err = os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664) if err != nil { return fmt.Errorf("Error opening log file: %v", err) } logrus.SetOutput(io.MultiWriter(logFILE, os.Stdout)) logrus.SetLevel(logrus.DebugLevel) logrus.SetFormatter(&prefix_fmt.TextFormatter{ ForceColors: true, ForceFormatting: true, FullTimestamp: true, }) //logrus.SetOutput(ansicolor.NewAnsiColorWriter(os.Stdout)) //logrus.SetOutput(colorable.NewColorableStdout()) log = logrus.New() log.Level = logrus.DebugLevel log.Formatter = &prefix_fmt.TextFormatter{ ForceColors: true, ForceFormatting: true, FullTimestamp: true, TimestampFormat: "02 Jan 06 15:04:05.00 -0700", } //log.Out = colorable.NewColorableStdout() //log.Out = colorable.NewNonColorable(io.MultiWriter(logFILE, os.Stdout)) log.Out = ansicolor.NewAnsiColorWriter(io.MultiWriter(logFILE, os.Stdout)) log.Debug("rebuilddb logger started.") return nil }
[ "func", "InitLogger", "(", ")", "error", "{", "logFilePath", ",", "_", ":=", "filepath", ".", "Abs", "(", "logFile", ")", "\n", "var", "err", "error", "\n", "logFILE", ",", "err", "=", "os", ".", "OpenFile", "(", "logFilePath", ",", "os", ".", "O_RDW...
// InitLogger starts the logger
[ "InitLogger", "starts", "the", "logger" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/cmd/rebuilddb2/log.go#L23-L58
19,579
decred/dcrdata
db/dcrpg/tables.go
DropTables
func DropTables(db *sql.DB) { for tableName := range createTableStatements { log.Infof("DROPPING the \"%s\" table.", tableName) if err := dropTable(db, tableName); err != nil { log.Errorf(`DROP TABLE "%s" failed.`, tableName) } } _, err := db.Exec(`DROP TYPE IF EXISTS vin;`) if err != nil { log.Errorf("DROP TYPE vin failed.") } }
go
func DropTables(db *sql.DB) { for tableName := range createTableStatements { log.Infof("DROPPING the \"%s\" table.", tableName) if err := dropTable(db, tableName); err != nil { log.Errorf(`DROP TABLE "%s" failed.`, tableName) } } _, err := db.Exec(`DROP TYPE IF EXISTS vin;`) if err != nil { log.Errorf("DROP TYPE vin failed.") } }
[ "func", "DropTables", "(", "db", "*", "sql", ".", "DB", ")", "{", "for", "tableName", ":=", "range", "createTableStatements", "{", "log", ".", "Infof", "(", "\"", "\\\"", "\\\"", "\"", ",", "tableName", ")", "\n", "if", "err", ":=", "dropTable", "(", ...
// DropTables drops all of the tables internally recognized tables.
[ "DropTables", "drops", "all", "of", "the", "tables", "internally", "recognized", "tables", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L67-L79
19,580
decred/dcrdata
db/dcrpg/tables.go
AnalyzeAllTables
func AnalyzeAllTables(db *sql.DB, statisticsTarget int) error { dbTx, err := db.Begin() if err != nil { return fmt.Errorf("failed to begin transactions: %v", err) } _, err = dbTx.Exec(fmt.Sprintf("SET LOCAL default_statistics_target TO %d;", statisticsTarget)) if err != nil { _ = dbTx.Rollback() return fmt.Errorf("failed to set default_statistics_target: %v", err) } _, err = dbTx.Exec(`ANALYZE;`) if err != nil { _ = dbTx.Rollback() return fmt.Errorf("failed to ANALYZE all tables: %v", err) } return dbTx.Commit() }
go
func AnalyzeAllTables(db *sql.DB, statisticsTarget int) error { dbTx, err := db.Begin() if err != nil { return fmt.Errorf("failed to begin transactions: %v", err) } _, err = dbTx.Exec(fmt.Sprintf("SET LOCAL default_statistics_target TO %d;", statisticsTarget)) if err != nil { _ = dbTx.Rollback() return fmt.Errorf("failed to set default_statistics_target: %v", err) } _, err = dbTx.Exec(`ANALYZE;`) if err != nil { _ = dbTx.Rollback() return fmt.Errorf("failed to ANALYZE all tables: %v", err) } return dbTx.Commit() }
[ "func", "AnalyzeAllTables", "(", "db", "*", "sql", ".", "DB", ",", "statisticsTarget", "int", ")", "error", "{", "dbTx", ",", "err", ":=", "db", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"",...
// AnalyzeAllTables performs an ANALYZE on all tables after setting // default_statistics_target for the transaction.
[ "AnalyzeAllTables", "performs", "an", "ANALYZE", "on", "all", "tables", "after", "setting", "default_statistics_target", "for", "the", "transaction", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L89-L108
19,581
decred/dcrdata
db/dcrpg/tables.go
CreateTables
func CreateTables(db *sql.DB) error { // Create all of the data tables. for tableName, createCommand := range createTableStatements { err := createTable(db, tableName, createCommand) if err != nil { return err } } return ClearTestingTable(db) }
go
func CreateTables(db *sql.DB) error { // Create all of the data tables. for tableName, createCommand := range createTableStatements { err := createTable(db, tableName, createCommand) if err != nil { return err } } return ClearTestingTable(db) }
[ "func", "CreateTables", "(", "db", "*", "sql", ".", "DB", ")", "error", "{", "// Create all of the data tables.", "for", "tableName", ",", "createCommand", ":=", "range", "createTableStatements", "{", "err", ":=", "createTable", "(", "db", ",", "tableName", ",",...
// CreateTables creates all tables required by dcrdata if they do not already // exist.
[ "CreateTables", "creates", "all", "tables", "required", "by", "dcrdata", "if", "they", "do", "not", "already", "exist", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L180-L190
19,582
decred/dcrdata
db/dcrpg/tables.go
CreateTable
func CreateTable(db *sql.DB, tableName string) error { createCommand, tableNameFound := createTableStatements[tableName] if !tableNameFound { return fmt.Errorf("table name %s unknown", tableName) } return createTable(db, tableName, createCommand) }
go
func CreateTable(db *sql.DB, tableName string) error { createCommand, tableNameFound := createTableStatements[tableName] if !tableNameFound { return fmt.Errorf("table name %s unknown", tableName) } return createTable(db, tableName, createCommand) }
[ "func", "CreateTable", "(", "db", "*", "sql", ".", "DB", ",", "tableName", "string", ")", "error", "{", "createCommand", ",", "tableNameFound", ":=", "createTableStatements", "[", "tableName", "]", "\n", "if", "!", "tableNameFound", "{", "return", "fmt", "."...
// CreateTable creates one of the known tables by name.
[ "CreateTable", "creates", "one", "of", "the", "known", "tables", "by", "name", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L193-L200
19,583
decred/dcrdata
db/dcrpg/tables.go
createTable
func createTable(db *sql.DB, tableName, stmt string) error { exists, err := TableExists(db, tableName) if err != nil { return err } if !exists { log.Infof(`Creating the "%s" table.`, tableName) _, err = db.Exec(stmt) if err != nil { return err } } else { log.Tracef(`Table "%s" exists.`, tableName) } return err }
go
func createTable(db *sql.DB, tableName, stmt string) error { exists, err := TableExists(db, tableName) if err != nil { return err } if !exists { log.Infof(`Creating the "%s" table.`, tableName) _, err = db.Exec(stmt) if err != nil { return err } } else { log.Tracef(`Table "%s" exists.`, tableName) } return err }
[ "func", "createTable", "(", "db", "*", "sql", ".", "DB", ",", "tableName", ",", "stmt", "string", ")", "error", "{", "exists", ",", "err", ":=", "TableExists", "(", "db", ",", "tableName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", ...
// createTable creates a table with the given name using the provided SQL // statement, if it does not already exist.
[ "createTable", "creates", "a", "table", "with", "the", "given", "name", "using", "the", "provided", "SQL", "statement", "if", "it", "does", "not", "already", "exist", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L204-L221
19,584
decred/dcrdata
db/dcrpg/tables.go
CheckColumnDataType
func CheckColumnDataType(db *sql.DB, table, column string) (dataType string, err error) { err = db.QueryRow(`SELECT data_type FROM information_schema.columns WHERE table_name=$1 AND column_name=$2`, table, column).Scan(&dataType) return }
go
func CheckColumnDataType(db *sql.DB, table, column string) (dataType string, err error) { err = db.QueryRow(`SELECT data_type FROM information_schema.columns WHERE table_name=$1 AND column_name=$2`, table, column).Scan(&dataType) return }
[ "func", "CheckColumnDataType", "(", "db", "*", "sql", ".", "DB", ",", "table", ",", "column", "string", ")", "(", "dataType", "string", ",", "err", "error", ")", "{", "err", "=", "db", ".", "QueryRow", "(", "`SELECT data_type\n\t\tFROM information_schema.colum...
// CheckColumnDataType gets the data type of specified table column .
[ "CheckColumnDataType", "gets", "the", "data", "type", "of", "specified", "table", "column", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L224-L230
19,585
decred/dcrdata
db/dcrpg/tables.go
DeleteDuplicates
func (pgb *ChainDB) DeleteDuplicates(barLoad chan *dbtypes.ProgressBarLoad) error { allDuplicates := []dropDuplicatesInfo{ // Remove duplicate vins {TableName: "vins", DropDupsFunc: pgb.DeleteDuplicateVins}, // Remove duplicate vouts {TableName: "vouts", DropDupsFunc: pgb.DeleteDuplicateVouts}, // Remove duplicate transactions {TableName: "transactions", DropDupsFunc: pgb.DeleteDuplicateTxns}, // Remove duplicate agendas {TableName: "agendas", DropDupsFunc: pgb.DeleteDuplicateAgendas}, // Remove duplicate agenda_votes {TableName: "agenda_votes", DropDupsFunc: pgb.DeleteDuplicateAgendaVotes}, } var err error for _, val := range allDuplicates { msg := fmt.Sprintf("Finding and removing duplicate %s entries...", val.TableName) if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.InitialDBLoad, Subtitle: msg} } log.Info(msg) var numRemoved int64 if numRemoved, err = val.DropDupsFunc(); err != nil { return fmt.Errorf("delete %s duplicate failed: %v", val.TableName, err) } msg = fmt.Sprintf("Removed %d duplicate %s entries.", numRemoved, val.TableName) if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.InitialDBLoad, Subtitle: msg} } log.Info(msg) } // Signal task is done if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.InitialDBLoad, Subtitle: " "} } return nil }
go
func (pgb *ChainDB) DeleteDuplicates(barLoad chan *dbtypes.ProgressBarLoad) error { allDuplicates := []dropDuplicatesInfo{ // Remove duplicate vins {TableName: "vins", DropDupsFunc: pgb.DeleteDuplicateVins}, // Remove duplicate vouts {TableName: "vouts", DropDupsFunc: pgb.DeleteDuplicateVouts}, // Remove duplicate transactions {TableName: "transactions", DropDupsFunc: pgb.DeleteDuplicateTxns}, // Remove duplicate agendas {TableName: "agendas", DropDupsFunc: pgb.DeleteDuplicateAgendas}, // Remove duplicate agenda_votes {TableName: "agenda_votes", DropDupsFunc: pgb.DeleteDuplicateAgendaVotes}, } var err error for _, val := range allDuplicates { msg := fmt.Sprintf("Finding and removing duplicate %s entries...", val.TableName) if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.InitialDBLoad, Subtitle: msg} } log.Info(msg) var numRemoved int64 if numRemoved, err = val.DropDupsFunc(); err != nil { return fmt.Errorf("delete %s duplicate failed: %v", val.TableName, err) } msg = fmt.Sprintf("Removed %d duplicate %s entries.", numRemoved, val.TableName) if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.InitialDBLoad, Subtitle: msg} } log.Info(msg) } // Signal task is done if barLoad != nil { barLoad <- &dbtypes.ProgressBarLoad{BarID: dbtypes.InitialDBLoad, Subtitle: " "} } return nil }
[ "func", "(", "pgb", "*", "ChainDB", ")", "DeleteDuplicates", "(", "barLoad", "chan", "*", "dbtypes", ".", "ProgressBarLoad", ")", "error", "{", "allDuplicates", ":=", "[", "]", "dropDuplicatesInfo", "{", "// Remove duplicate vins", "{", "TableName", ":", "\"", ...
// DeleteDuplicates attempts to delete "duplicate" rows in tables where unique // indexes are to be created.
[ "DeleteDuplicates", "attempts", "to", "delete", "duplicate", "rows", "in", "tables", "where", "unique", "indexes", "are", "to", "be", "created", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dcrpg/tables.go#L234-L276
19,586
decred/dcrdata
api/apirouter.go
stackedMux
func stackedMux(useRealIP bool) *chi.Mux { mux := chi.NewRouter() if useRealIP { mux.Use(middleware.RealIP) } mux.Use(middleware.Logger) mux.Use(middleware.Recoverer) corsMW := cors.Default() mux.Use(corsMW.Handler) return mux }
go
func stackedMux(useRealIP bool) *chi.Mux { mux := chi.NewRouter() if useRealIP { mux.Use(middleware.RealIP) } mux.Use(middleware.Logger) mux.Use(middleware.Recoverer) corsMW := cors.Default() mux.Use(corsMW.Handler) return mux }
[ "func", "stackedMux", "(", "useRealIP", "bool", ")", "*", "chi", ".", "Mux", "{", "mux", ":=", "chi", ".", "NewRouter", "(", ")", "\n", "if", "useRealIP", "{", "mux", ".", "Use", "(", "middleware", ".", "RealIP", ")", "\n", "}", "\n", "mux", ".", ...
// Stacks some middleware common to both file and api router.
[ "Stacks", "some", "middleware", "common", "to", "both", "file", "and", "api", "router", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apirouter.go#L289-L299
19,587
decred/dcrdata
api/apiroutes.go
NewContext
func NewContext(cfg *AppContextConfig) *appContext { conns, _ := cfg.Client.GetConnectionCount() nodeHeight, _ := cfg.Client.GetBlockCount() // auxDataSource is an interface that could have a value of pointer type. if cfg.DBSource == nil || reflect.ValueOf(cfg.DBSource).IsNil() { log.Errorf("NewContext: a DataSourceAux is required.") return nil } return &appContext{ nodeClient: cfg.Client, Params: cfg.Params, BlockData: cfg.DataSource, AuxDataSource: cfg.DBSource, xcBot: cfg.XcBot, AgendaDB: cfg.AgendasDBInstance, Status: apitypes.NewStatus(uint32(nodeHeight), conns, APIVersion, appver.Version(), cfg.Params.Name), JSONIndent: cfg.JsonIndent, maxCSVAddrs: cfg.MaxAddrs, charts: cfg.Charts, } }
go
func NewContext(cfg *AppContextConfig) *appContext { conns, _ := cfg.Client.GetConnectionCount() nodeHeight, _ := cfg.Client.GetBlockCount() // auxDataSource is an interface that could have a value of pointer type. if cfg.DBSource == nil || reflect.ValueOf(cfg.DBSource).IsNil() { log.Errorf("NewContext: a DataSourceAux is required.") return nil } return &appContext{ nodeClient: cfg.Client, Params: cfg.Params, BlockData: cfg.DataSource, AuxDataSource: cfg.DBSource, xcBot: cfg.XcBot, AgendaDB: cfg.AgendasDBInstance, Status: apitypes.NewStatus(uint32(nodeHeight), conns, APIVersion, appver.Version(), cfg.Params.Name), JSONIndent: cfg.JsonIndent, maxCSVAddrs: cfg.MaxAddrs, charts: cfg.Charts, } }
[ "func", "NewContext", "(", "cfg", "*", "AppContextConfig", ")", "*", "appContext", "{", "conns", ",", "_", ":=", "cfg", ".", "Client", ".", "GetConnectionCount", "(", ")", "\n", "nodeHeight", ",", "_", ":=", "cfg", ".", "Client", ".", "GetBlockCount", "(...
// NewContext constructs a new appContext from the RPC client, primary and // auxiliary data sources, and JSON indentation string.
[ "NewContext", "constructs", "a", "new", "appContext", "from", "the", "RPC", "client", "primary", "and", "auxiliary", "data", "sources", "and", "JSON", "indentation", "string", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L150-L172
19,588
decred/dcrdata
api/apiroutes.go
StatusNtfnHandler
func (c *appContext) StatusNtfnHandler(ctx context.Context, wg *sync.WaitGroup) { defer wg.Done() out: for { keepon: select { case height, ok := <-notify.NtfnChans.UpdateStatusNodeHeight: if !ok { log.Warnf("Block connected channel closed.") break out } nodeConnections, err := c.nodeClient.GetConnectionCount() if err == nil { c.Status.SetHeightAndConnections(height, nodeConnections) } else { c.Status.SetHeight(height) c.Status.SetReady(false) log.Warn("Failed to get connection count: ", err) break keepon } case height, ok := <-notify.NtfnChans.UpdateStatusDBHeight: if !ok { log.Warnf("Block connected channel closed.") break out } if c.BlockData == nil { panic("BlockData DataSourceLite is nil") } summary := c.BlockData.GetBestBlockSummary() if summary == nil { log.Errorf("BlockData summary is nil for height %d.", height) break keepon } c.Status.DBUpdate(height, summary.Time.S.UNIX()) bdHeight, err := c.BlockData.GetHeight() // Catch certain pathological conditions. switch { case err != nil: log.Errorf("GetHeight failed: %v", err) case (height != uint32(bdHeight)) || (height != summary.Height): log.Errorf("New DB height (%d) and stored block data (%d, %d) are not consistent.", height, bdHeight, summary.Height) case bdHeight < 0: log.Warnf("DB empty (height = %d)", bdHeight) default: // If DB height agrees with node height, then we're ready. break keepon } c.Status.SetReady(false) case <-ctx.Done(): log.Debugf("Got quit signal. Exiting block connected handler for STATUS monitor.") break out } } }
go
func (c *appContext) StatusNtfnHandler(ctx context.Context, wg *sync.WaitGroup) { defer wg.Done() out: for { keepon: select { case height, ok := <-notify.NtfnChans.UpdateStatusNodeHeight: if !ok { log.Warnf("Block connected channel closed.") break out } nodeConnections, err := c.nodeClient.GetConnectionCount() if err == nil { c.Status.SetHeightAndConnections(height, nodeConnections) } else { c.Status.SetHeight(height) c.Status.SetReady(false) log.Warn("Failed to get connection count: ", err) break keepon } case height, ok := <-notify.NtfnChans.UpdateStatusDBHeight: if !ok { log.Warnf("Block connected channel closed.") break out } if c.BlockData == nil { panic("BlockData DataSourceLite is nil") } summary := c.BlockData.GetBestBlockSummary() if summary == nil { log.Errorf("BlockData summary is nil for height %d.", height) break keepon } c.Status.DBUpdate(height, summary.Time.S.UNIX()) bdHeight, err := c.BlockData.GetHeight() // Catch certain pathological conditions. switch { case err != nil: log.Errorf("GetHeight failed: %v", err) case (height != uint32(bdHeight)) || (height != summary.Height): log.Errorf("New DB height (%d) and stored block data (%d, %d) are not consistent.", height, bdHeight, summary.Height) case bdHeight < 0: log.Warnf("DB empty (height = %d)", bdHeight) default: // If DB height agrees with node height, then we're ready. break keepon } c.Status.SetReady(false) case <-ctx.Done(): log.Debugf("Got quit signal. Exiting block connected handler for STATUS monitor.") break out } } }
[ "func", "(", "c", "*", "appContext", ")", "StatusNtfnHandler", "(", "ctx", "context", ".", "Context", ",", "wg", "*", "sync", ".", "WaitGroup", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "out", ":", "for", "{", "keepon", ":", "select", "...
// StatusNtfnHandler keeps the appContext's Status up-to-date with changes in // node and DB status.
[ "StatusNtfnHandler", "keeps", "the", "appContext", "s", "Status", "up", "-", "to", "-", "date", "with", "changes", "in", "node", "and", "DB", "status", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L176-L238
19,589
decred/dcrdata
api/apiroutes.go
root
func (c *appContext) root(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "dcrdata api running") }
go
func (c *appContext) root(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "dcrdata api running") }
[ "func", "(", "c", "*", "appContext", ")", "root", "(", "w", "http", ".", "ResponseWriter", ",", "_", "*", "http", ".", "Request", ")", "{", "fmt", ".", "Fprint", "(", "w", ",", "\"", "\"", ")", "\n", "}" ]
// root is a http.Handler intended for the API root path. This essentially // provides a heartbeat, and no information about the application status.
[ "root", "is", "a", "http", ".", "Handler", "intended", "for", "the", "API", "root", "path", ".", "This", "essentially", "provides", "a", "heartbeat", "and", "no", "information", "about", "the", "application", "status", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L242-L244
19,590
decred/dcrdata
api/apiroutes.go
writeJSONBytes
func writeJSONBytes(w http.ResponseWriter, data []byte) { w.Header().Set("Content-Type", "application/json; charset=utf-8") _, err := w.Write(data) if err != nil { apiLog.Warnf("ResponseWriter.Write error: %v", err) } }
go
func writeJSONBytes(w http.ResponseWriter, data []byte) { w.Header().Set("Content-Type", "application/json; charset=utf-8") _, err := w.Write(data) if err != nil { apiLog.Warnf("ResponseWriter.Write error: %v", err) } }
[ "func", "writeJSONBytes", "(", "w", "http", ".", "ResponseWriter", ",", "data", "[", "]", "byte", ")", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "_", ",", "err", ":=", "w", ".", "Write", "(", ...
// writeJSONBytes prepares the headers for pre-encoded JSON and writes the JSON // bytes.
[ "writeJSONBytes", "prepares", "the", "headers", "for", "pre", "-", "encoded", "JSON", "and", "writes", "the", "JSON", "bytes", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L263-L269
19,591
decred/dcrdata
api/apiroutes.go
writeCSV
func writeCSV(w http.ResponseWriter, rows [][]string, filename string, useCRLF bool) { w.Header().Set("Content-Disposition", fmt.Sprintf("attachment;filename=%s", filename)) w.Header().Set("Content-Type", "text/csv") // To set the Content-Length response header, it is necessary to write the // CSV data into a buffer rather than streaming the response directly to the // http.ResponseWriter. buffer := new(bytes.Buffer) writer := csv.NewWriter(buffer) writer.UseCRLF = useCRLF err := writer.WriteAll(rows) if err != nil { log.Errorf("Failed to write address rows to buffer: %v", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } bytesToSend := int64(buffer.Len()) w.Header().Set("Content-Length", strconv.FormatInt(bytesToSend, 10)) bytesWritten, err := buffer.WriteTo(w) if err != nil { log.Errorf("Failed to transfer address rows from buffer. "+ "%d bytes written. %v", bytesWritten, err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } // Warn if the number of bytes sent differs from buffer length. if bytesWritten != bytesToSend { log.Warnf("Failed to send the entire file. Sent %d of %d bytes.", bytesWritten, bytesToSend) } }
go
func writeCSV(w http.ResponseWriter, rows [][]string, filename string, useCRLF bool) { w.Header().Set("Content-Disposition", fmt.Sprintf("attachment;filename=%s", filename)) w.Header().Set("Content-Type", "text/csv") // To set the Content-Length response header, it is necessary to write the // CSV data into a buffer rather than streaming the response directly to the // http.ResponseWriter. buffer := new(bytes.Buffer) writer := csv.NewWriter(buffer) writer.UseCRLF = useCRLF err := writer.WriteAll(rows) if err != nil { log.Errorf("Failed to write address rows to buffer: %v", err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } bytesToSend := int64(buffer.Len()) w.Header().Set("Content-Length", strconv.FormatInt(bytesToSend, 10)) bytesWritten, err := buffer.WriteTo(w) if err != nil { log.Errorf("Failed to transfer address rows from buffer. "+ "%d bytes written. %v", bytesWritten, err) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } // Warn if the number of bytes sent differs from buffer length. if bytesWritten != bytesToSend { log.Warnf("Failed to send the entire file. Sent %d of %d bytes.", bytesWritten, bytesToSend) } }
[ "func", "writeCSV", "(", "w", "http", ".", "ResponseWriter", ",", "rows", "[", "]", "[", "]", "string", ",", "filename", "string", ",", "useCRLF", "bool", ")", "{", "w", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Spri...
// Measures length, sets common headers, formats, and sends CSV data.
[ "Measures", "length", "sets", "common", "headers", "formats", "and", "sends", "CSV", "data", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L272-L308
19,592
decred/dcrdata
api/apiroutes.go
setTrimmedTxSpends
func (c *appContext) setTrimmedTxSpends(tx *apitypes.TrimmedTx) error { return c.setOutputSpends(tx.TxID, tx.Vout) }
go
func (c *appContext) setTrimmedTxSpends(tx *apitypes.TrimmedTx) error { return c.setOutputSpends(tx.TxID, tx.Vout) }
[ "func", "(", "c", "*", "appContext", ")", "setTrimmedTxSpends", "(", "tx", "*", "apitypes", ".", "TrimmedTx", ")", "error", "{", "return", "c", ".", "setOutputSpends", "(", "tx", ".", "TxID", ",", "tx", ".", "Vout", ")", "\n", "}" ]
// setTrimmedTxSpends is like setTxSpends except that it operates on a TrimmedTx // instead of a Tx.
[ "setTrimmedTxSpends", "is", "like", "setTxSpends", "except", "that", "it", "operates", "on", "a", "TrimmedTx", "instead", "of", "a", "Tx", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L603-L605
19,593
decred/dcrdata
api/apiroutes.go
getBlockStakeInfoExtendedByHash
func (c *appContext) getBlockStakeInfoExtendedByHash(w http.ResponseWriter, r *http.Request) { hash, err := c.getBlockHashCtx(r) if err != nil { http.Error(w, http.StatusText(422), 422) return } stakeinfo := c.BlockData.GetStakeInfoExtendedByHash(hash) if stakeinfo == nil { apiLog.Errorf("Unable to get block fee info for %s", hash) http.Error(w, http.StatusText(422), 422) return } writeJSON(w, stakeinfo, c.getIndentQuery(r)) }
go
func (c *appContext) getBlockStakeInfoExtendedByHash(w http.ResponseWriter, r *http.Request) { hash, err := c.getBlockHashCtx(r) if err != nil { http.Error(w, http.StatusText(422), 422) return } stakeinfo := c.BlockData.GetStakeInfoExtendedByHash(hash) if stakeinfo == nil { apiLog.Errorf("Unable to get block fee info for %s", hash) http.Error(w, http.StatusText(422), 422) return } writeJSON(w, stakeinfo, c.getIndentQuery(r)) }
[ "func", "(", "c", "*", "appContext", ")", "getBlockStakeInfoExtendedByHash", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "hash", ",", "err", ":=", "c", ".", "getBlockHashCtx", "(", "r", ")", "\n", "if", "er...
// getBlockStakeInfoExtendedByHash retrieves the apitype.StakeInfoExtended // for the given blockhash
[ "getBlockStakeInfoExtendedByHash", "retrieves", "the", "apitype", ".", "StakeInfoExtended", "for", "the", "given", "blockhash" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L894-L909
19,594
decred/dcrdata
api/apiroutes.go
getBlockStakeInfoExtendedByHeight
func (c *appContext) getBlockStakeInfoExtendedByHeight(w http.ResponseWriter, r *http.Request) { idx, err := c.getBlockHeightCtx(r) if err != nil { http.Error(w, http.StatusText(422), 422) return } stakeinfo := c.BlockData.GetStakeInfoExtendedByHeight(int(idx)) if stakeinfo == nil { apiLog.Errorf("Unable to get block fee info for height %d", idx) http.Error(w, http.StatusText(422), 422) return } writeJSON(w, stakeinfo, c.getIndentQuery(r)) }
go
func (c *appContext) getBlockStakeInfoExtendedByHeight(w http.ResponseWriter, r *http.Request) { idx, err := c.getBlockHeightCtx(r) if err != nil { http.Error(w, http.StatusText(422), 422) return } stakeinfo := c.BlockData.GetStakeInfoExtendedByHeight(int(idx)) if stakeinfo == nil { apiLog.Errorf("Unable to get block fee info for height %d", idx) http.Error(w, http.StatusText(422), 422) return } writeJSON(w, stakeinfo, c.getIndentQuery(r)) }
[ "func", "(", "c", "*", "appContext", ")", "getBlockStakeInfoExtendedByHeight", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "idx", ",", "err", ":=", "c", ".", "getBlockHeightCtx", "(", "r", ")", "\n", "if", ...
// getBlockStakeInfoExtendedByHeight retrieves the apitype.StakeInfoExtended // for the given blockheight on mainchain
[ "getBlockStakeInfoExtendedByHeight", "retrieves", "the", "apitype", ".", "StakeInfoExtended", "for", "the", "given", "blockheight", "on", "mainchain" ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L913-L927
19,595
decred/dcrdata
api/apiroutes.go
getPowerlessTickets
func (c *appContext) getPowerlessTickets(w http.ResponseWriter, r *http.Request) { tickets, err := c.AuxDataSource.PowerlessTickets() if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } writeJSON(w, tickets, c.getIndentQuery(r)) }
go
func (c *appContext) getPowerlessTickets(w http.ResponseWriter, r *http.Request) { tickets, err := c.AuxDataSource.PowerlessTickets() if err != nil { http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } writeJSON(w, tickets, c.getIndentQuery(r)) }
[ "func", "(", "c", "*", "appContext", ")", "getPowerlessTickets", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "tickets", ",", "err", ":=", "c", ".", "AuxDataSource", ".", "PowerlessTickets", "(", ")", "\n", ...
// Encodes apitypes.PowerlessTickets, which is missed or expired tickets sorted // by revocation status.
[ "Encodes", "apitypes", ".", "PowerlessTickets", "which", "is", "missed", "or", "expired", "tickets", "sorted", "by", "revocation", "status", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L942-L949
19,596
decred/dcrdata
api/apiroutes.go
getAgendasData
func (c *appContext) getAgendasData(w http.ResponseWriter, _ *http.Request) { agendas, err := c.AgendaDB.AllAgendas() if err != nil { apiLog.Errorf("agendadb AllAgendas error: %v", err) http.Error(w, "agendadb.AllAgendas failed.", http.StatusServiceUnavailable) return } voteMilestones, err := c.AuxDataSource.AllAgendas() if err != nil { apiLog.Errorf("AllAgendas timeout error: %v", err) http.Error(w, "Database timeout.", http.StatusServiceUnavailable) } data := make([]apitypes.AgendasInfo, 0, len(agendas)) for index := range agendas { val := agendas[index] agendaMilestone := voteMilestones[val.ID] agendaMilestone.StartTime = time.Unix(int64(val.StartTime), 0).UTC() agendaMilestone.ExpireTime = time.Unix(int64(val.ExpireTime), 0).UTC() data = append(data, apitypes.AgendasInfo{ Name: val.ID, Description: val.Description, VoteVersion: val.VoteVersion, MileStone: &agendaMilestone, Mask: val.Mask, }) } writeJSON(w, data, "") }
go
func (c *appContext) getAgendasData(w http.ResponseWriter, _ *http.Request) { agendas, err := c.AgendaDB.AllAgendas() if err != nil { apiLog.Errorf("agendadb AllAgendas error: %v", err) http.Error(w, "agendadb.AllAgendas failed.", http.StatusServiceUnavailable) return } voteMilestones, err := c.AuxDataSource.AllAgendas() if err != nil { apiLog.Errorf("AllAgendas timeout error: %v", err) http.Error(w, "Database timeout.", http.StatusServiceUnavailable) } data := make([]apitypes.AgendasInfo, 0, len(agendas)) for index := range agendas { val := agendas[index] agendaMilestone := voteMilestones[val.ID] agendaMilestone.StartTime = time.Unix(int64(val.StartTime), 0).UTC() agendaMilestone.ExpireTime = time.Unix(int64(val.ExpireTime), 0).UTC() data = append(data, apitypes.AgendasInfo{ Name: val.ID, Description: val.Description, VoteVersion: val.VoteVersion, MileStone: &agendaMilestone, Mask: val.Mask, }) } writeJSON(w, data, "") }
[ "func", "(", "c", "*", "appContext", ")", "getAgendasData", "(", "w", "http", ".", "ResponseWriter", ",", "_", "*", "http", ".", "Request", ")", "{", "agendas", ",", "err", ":=", "c", ".", "AgendaDB", ".", "AllAgendas", "(", ")", "\n", "if", "err", ...
// getAgendasData returns high level agendas details that includes Name, // Description, Vote Version, VotingDone height, Activated, HardForked, // StartTime and ExpireTime.
[ "getAgendasData", "returns", "high", "level", "agendas", "details", "that", "includes", "Name", "Description", "Vote", "Version", "VotingDone", "height", "Activated", "HardForked", "StartTime", "and", "ExpireTime", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/api/apiroutes.go#L1757-L1787
19,597
decred/dcrdata
db/dbtypes/types.go
IsTimeout
func IsTimeout(msg string) bool { // Contains is used instead of HasPrefix since error messages are often // supplemented with additional information. return strings.Contains(msg, TimeoutPrefix) || strings.Contains(msg, CtxDeadlineExceeded) }
go
func IsTimeout(msg string) bool { // Contains is used instead of HasPrefix since error messages are often // supplemented with additional information. return strings.Contains(msg, TimeoutPrefix) || strings.Contains(msg, CtxDeadlineExceeded) }
[ "func", "IsTimeout", "(", "msg", "string", ")", "bool", "{", "// Contains is used instead of HasPrefix since error messages are often", "// supplemented with additional information.", "return", "strings", ".", "Contains", "(", "msg", ",", "TimeoutPrefix", ")", "||", "strings"...
// IsTimeout checks if the message is prefixed with the expected DB timeout // message prefix.
[ "IsTimeout", "checks", "if", "the", "message", "is", "prefixed", "with", "the", "expected", "DB", "timeout", "message", "prefix", "." ]
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L32-L37
19,598
decred/dcrdata
db/dbtypes/types.go
Value
func (t TimeDef) Value() (driver.Value, error) { return t.T.UTC(), nil }
go
func (t TimeDef) Value() (driver.Value, error) { return t.T.UTC(), nil }
[ "func", "(", "t", "TimeDef", ")", "Value", "(", ")", "(", "driver", ".", "Value", ",", "error", ")", "{", "return", "t", ".", "T", ".", "UTC", "(", ")", ",", "nil", "\n", "}" ]
// Value implements the sql.Valuer interface. It ensures that the Time Values // are for the UTC time zone. Times will only survive a round trip to and from // the DB tables if they are stored from a time.Time with Location set to UTC.
[ "Value", "implements", "the", "sql", ".", "Valuer", "interface", ".", "It", "ensures", "that", "the", "Time", "Values", "are", "for", "the", "UTC", "time", "zone", ".", "Times", "will", "only", "survive", "a", "round", "trip", "to", "and", "from", "the",...
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L130-L132
19,599
decred/dcrdata
db/dbtypes/types.go
Value
func (t TimeDefLocal) Value() (driver.Value, error) { return t.T.Local(), nil }
go
func (t TimeDefLocal) Value() (driver.Value, error) { return t.T.Local(), nil }
[ "func", "(", "t", "TimeDefLocal", ")", "Value", "(", ")", "(", "driver", ".", "Value", ",", "error", ")", "{", "return", "t", ".", "T", ".", "Local", "(", ")", ",", "nil", "\n", "}" ]
// Value implements the sql.Valuer interface. It ensures that the Time Values // are for the Local time zone. It is unlikely to be desirable to store values // this way. Only storing a time.Time in UTC allows round trip fidelity.
[ "Value", "implements", "the", "sql", ".", "Valuer", "interface", ".", "It", "ensures", "that", "the", "Time", "Values", "are", "for", "the", "Local", "time", "zone", ".", "It", "is", "unlikely", "to", "be", "desirable", "to", "store", "values", "this", "...
02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6
https://github.com/decred/dcrdata/blob/02d6f8e648f7e2c5cf78ea92fb17b1d4aa4a99f6/db/dbtypes/types.go#L143-L145