repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
jpillora/overseer
fetcher/fetcher_s3.go
Fetch
func (s *S3) Fetch() (io.Reader, error) { //delay fetches after first if s.delay { time.Sleep(s.Interval) } s.delay = true //status check using HEAD head, err := s.client.HeadObject(&s3.HeadObjectInput{Bucket: &s.Bucket, Key: &s.Key}) if err != nil { return nil, fmt.Errorf("HEAD request failed (%s)", err) } if s.lastETag == *head.ETag { return nil, nil //skip, file match } s.lastETag = *head.ETag //binary fetch using GET get, err := s.client.GetObject(&s3.GetObjectInput{Bucket: &s.Bucket, Key: &s.Key}) if err != nil { return nil, fmt.Errorf("GET request failed (%s)", err) } //extract gz files if strings.HasSuffix(s.Key, ".gz") && aws.StringValue(get.ContentEncoding) != "gzip" { return gzip.NewReader(get.Body) } //success! return get.Body, nil }
go
func (s *S3) Fetch() (io.Reader, error) { //delay fetches after first if s.delay { time.Sleep(s.Interval) } s.delay = true //status check using HEAD head, err := s.client.HeadObject(&s3.HeadObjectInput{Bucket: &s.Bucket, Key: &s.Key}) if err != nil { return nil, fmt.Errorf("HEAD request failed (%s)", err) } if s.lastETag == *head.ETag { return nil, nil //skip, file match } s.lastETag = *head.ETag //binary fetch using GET get, err := s.client.GetObject(&s3.GetObjectInput{Bucket: &s.Bucket, Key: &s.Key}) if err != nil { return nil, fmt.Errorf("GET request failed (%s)", err) } //extract gz files if strings.HasSuffix(s.Key, ".gz") && aws.StringValue(get.ContentEncoding) != "gzip" { return gzip.NewReader(get.Body) } //success! return get.Body, nil }
[ "func", "(", "s", "*", "S3", ")", "Fetch", "(", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "if", "s", ".", "delay", "{", "time", ".", "Sleep", "(", "s", ".", "Interval", ")", "\n", "}", "\n", "s", ".", "delay", "=", "true", "\n", "head", ",", "err", ":=", "s", ".", "client", ".", "HeadObject", "(", "&", "s3", ".", "HeadObjectInput", "{", "Bucket", ":", "&", "s", ".", "Bucket", ",", "Key", ":", "&", "s", ".", "Key", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"HEAD request failed (%s)\"", ",", "err", ")", "\n", "}", "\n", "if", "s", ".", "lastETag", "==", "*", "head", ".", "ETag", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "s", ".", "lastETag", "=", "*", "head", ".", "ETag", "\n", "get", ",", "err", ":=", "s", ".", "client", ".", "GetObject", "(", "&", "s3", ".", "GetObjectInput", "{", "Bucket", ":", "&", "s", ".", "Bucket", ",", "Key", ":", "&", "s", ".", "Key", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"GET request failed (%s)\"", ",", "err", ")", "\n", "}", "\n", "if", "strings", ".", "HasSuffix", "(", "s", ".", "Key", ",", "\".gz\"", ")", "&&", "aws", ".", "StringValue", "(", "get", ".", "ContentEncoding", ")", "!=", "\"gzip\"", "{", "return", "gzip", ".", "NewReader", "(", "get", ".", "Body", ")", "\n", "}", "\n", "return", "get", ".", "Body", ",", "nil", "\n", "}" ]
// Fetch the binary from S3
[ "Fetch", "the", "binary", "from", "S3" ]
ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/fetcher/fetcher_s3.go#L63-L89
test
jpillora/overseer
overseer.go
sanityCheck
func sanityCheck() bool { //sanity check if token := os.Getenv(envBinCheck); token != "" { fmt.Fprint(os.Stdout, token) return true } //legacy sanity check using old env var if token := os.Getenv(envBinCheckLegacy); token != "" { fmt.Fprint(os.Stdout, token) return true } return false }
go
func sanityCheck() bool { //sanity check if token := os.Getenv(envBinCheck); token != "" { fmt.Fprint(os.Stdout, token) return true } //legacy sanity check using old env var if token := os.Getenv(envBinCheckLegacy); token != "" { fmt.Fprint(os.Stdout, token) return true } return false }
[ "func", "sanityCheck", "(", ")", "bool", "{", "if", "token", ":=", "os", ".", "Getenv", "(", "envBinCheck", ")", ";", "token", "!=", "\"\"", "{", "fmt", ".", "Fprint", "(", "os", ".", "Stdout", ",", "token", ")", "\n", "return", "true", "\n", "}", "\n", "if", "token", ":=", "os", ".", "Getenv", "(", "envBinCheckLegacy", ")", ";", "token", "!=", "\"\"", "{", "fmt", ".", "Fprint", "(", "os", ".", "Stdout", ",", "token", ")", "\n", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
//sanityCheck returns true if a check was performed
[ "sanityCheck", "returns", "true", "if", "a", "check", "was", "performed" ]
ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/overseer.go#L113-L125
test
jpillora/overseer
graceful.go
release
func (l *overseerListener) release(timeout time.Duration) { //stop accepting connections - release fd l.closeError = l.Listener.Close() //start timer, close by force if deadline not met waited := make(chan bool) go func() { l.wg.Wait() waited <- true }() go func() { select { case <-time.After(timeout): close(l.closeByForce) case <-waited: //no need to force close } }() }
go
func (l *overseerListener) release(timeout time.Duration) { //stop accepting connections - release fd l.closeError = l.Listener.Close() //start timer, close by force if deadline not met waited := make(chan bool) go func() { l.wg.Wait() waited <- true }() go func() { select { case <-time.After(timeout): close(l.closeByForce) case <-waited: //no need to force close } }() }
[ "func", "(", "l", "*", "overseerListener", ")", "release", "(", "timeout", "time", ".", "Duration", ")", "{", "l", ".", "closeError", "=", "l", ".", "Listener", ".", "Close", "(", ")", "\n", "waited", ":=", "make", "(", "chan", "bool", ")", "\n", "go", "func", "(", ")", "{", "l", ".", "wg", ".", "Wait", "(", ")", "\n", "waited", "<-", "true", "\n", "}", "(", ")", "\n", "go", "func", "(", ")", "{", "select", "{", "case", "<-", "time", ".", "After", "(", "timeout", ")", ":", "close", "(", "l", ".", "closeByForce", ")", "\n", "case", "<-", "waited", ":", "}", "\n", "}", "(", ")", "\n", "}" ]
//non-blocking trigger close
[ "non", "-", "blocking", "trigger", "close" ]
ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/graceful.go#L55-L72
test
jpillora/overseer
proc_master.go
fetchLoop
func (mp *master) fetchLoop() { min := mp.Config.MinFetchInterval time.Sleep(min) for { t0 := time.Now() mp.fetch() //duration fetch of fetch diff := time.Now().Sub(t0) if diff < min { delay := min - diff //ensures at least MinFetchInterval delay. //should be throttled by the fetcher! time.Sleep(delay) } } }
go
func (mp *master) fetchLoop() { min := mp.Config.MinFetchInterval time.Sleep(min) for { t0 := time.Now() mp.fetch() //duration fetch of fetch diff := time.Now().Sub(t0) if diff < min { delay := min - diff //ensures at least MinFetchInterval delay. //should be throttled by the fetcher! time.Sleep(delay) } } }
[ "func", "(", "mp", "*", "master", ")", "fetchLoop", "(", ")", "{", "min", ":=", "mp", ".", "Config", ".", "MinFetchInterval", "\n", "time", ".", "Sleep", "(", "min", ")", "\n", "for", "{", "t0", ":=", "time", ".", "Now", "(", ")", "\n", "mp", ".", "fetch", "(", ")", "\n", "diff", ":=", "time", ".", "Now", "(", ")", ".", "Sub", "(", "t0", ")", "\n", "if", "diff", "<", "min", "{", "delay", ":=", "min", "-", "diff", "\n", "time", ".", "Sleep", "(", "delay", ")", "\n", "}", "\n", "}", "\n", "}" ]
//fetchLoop is run in a goroutine
[ "fetchLoop", "is", "run", "in", "a", "goroutine" ]
ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/proc_master.go#L181-L196
test
jpillora/overseer
proc_master.go
forkLoop
func (mp *master) forkLoop() error { //loop, restart command for { if err := mp.fork(); err != nil { return err } } }
go
func (mp *master) forkLoop() error { //loop, restart command for { if err := mp.fork(); err != nil { return err } } }
[ "func", "(", "mp", "*", "master", ")", "forkLoop", "(", ")", "error", "{", "for", "{", "if", "err", ":=", "mp", ".", "fork", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
//not a real fork
[ "not", "a", "real", "fork" ]
ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/proc_master.go#L336-L343
test
jpillora/overseer
fetcher/fetcher_file.go
Init
func (f *File) Init() error { if f.Path == "" { return fmt.Errorf("Path required") } if f.Interval < 1*time.Second { f.Interval = 1 * time.Second } if err := f.updateHash(); err != nil { return err } return nil }
go
func (f *File) Init() error { if f.Path == "" { return fmt.Errorf("Path required") } if f.Interval < 1*time.Second { f.Interval = 1 * time.Second } if err := f.updateHash(); err != nil { return err } return nil }
[ "func", "(", "f", "*", "File", ")", "Init", "(", ")", "error", "{", "if", "f", ".", "Path", "==", "\"\"", "{", "return", "fmt", ".", "Errorf", "(", "\"Path required\"", ")", "\n", "}", "\n", "if", "f", ".", "Interval", "<", "1", "*", "time", ".", "Second", "{", "f", ".", "Interval", "=", "1", "*", "time", ".", "Second", "\n", "}", "\n", "if", "err", ":=", "f", ".", "updateHash", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Init sets the Path and Interval options
[ "Init", "sets", "the", "Path", "and", "Interval", "options" ]
ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/fetcher/fetcher_file.go#L24-L35
test
jpillora/overseer
fetcher/fetcher_file.go
Fetch
func (f *File) Fetch() (io.Reader, error) { //only delay after first fetch if f.delay { time.Sleep(f.Interval) } f.delay = true lastHash := f.hash if err := f.updateHash(); err != nil { return nil, err } // no change if lastHash == f.hash { return nil, nil } // changed! file, err := os.Open(f.Path) if err != nil { return nil, err } //check every 1/4s for 5s to //ensure its not mid-copy const rate = 250 * time.Millisecond const total = int(5 * time.Second / rate) attempt := 1 for { if attempt == total { file.Close() return nil, errors.New("file is currently being changed") } attempt++ //sleep time.Sleep(rate) //check hash! if err := f.updateHash(); err != nil { file.Close() return nil, err } //check until no longer changing if lastHash == f.hash { break } lastHash = f.hash } return file, nil }
go
func (f *File) Fetch() (io.Reader, error) { //only delay after first fetch if f.delay { time.Sleep(f.Interval) } f.delay = true lastHash := f.hash if err := f.updateHash(); err != nil { return nil, err } // no change if lastHash == f.hash { return nil, nil } // changed! file, err := os.Open(f.Path) if err != nil { return nil, err } //check every 1/4s for 5s to //ensure its not mid-copy const rate = 250 * time.Millisecond const total = int(5 * time.Second / rate) attempt := 1 for { if attempt == total { file.Close() return nil, errors.New("file is currently being changed") } attempt++ //sleep time.Sleep(rate) //check hash! if err := f.updateHash(); err != nil { file.Close() return nil, err } //check until no longer changing if lastHash == f.hash { break } lastHash = f.hash } return file, nil }
[ "func", "(", "f", "*", "File", ")", "Fetch", "(", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "if", "f", ".", "delay", "{", "time", ".", "Sleep", "(", "f", ".", "Interval", ")", "\n", "}", "\n", "f", ".", "delay", "=", "true", "\n", "lastHash", ":=", "f", ".", "hash", "\n", "if", "err", ":=", "f", ".", "updateHash", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "lastHash", "==", "f", ".", "hash", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "file", ",", "err", ":=", "os", ".", "Open", "(", "f", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "const", "rate", "=", "250", "*", "time", ".", "Millisecond", "\n", "const", "total", "=", "int", "(", "5", "*", "time", ".", "Second", "/", "rate", ")", "\n", "attempt", ":=", "1", "\n", "for", "{", "if", "attempt", "==", "total", "{", "file", ".", "Close", "(", ")", "\n", "return", "nil", ",", "errors", ".", "New", "(", "\"file is currently being changed\"", ")", "\n", "}", "\n", "attempt", "++", "\n", "time", ".", "Sleep", "(", "rate", ")", "\n", "if", "err", ":=", "f", ".", "updateHash", "(", ")", ";", "err", "!=", "nil", "{", "file", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "lastHash", "==", "f", ".", "hash", "{", "break", "\n", "}", "\n", "lastHash", "=", "f", ".", "hash", "\n", "}", "\n", "return", "file", ",", "nil", "\n", "}" ]
// Fetch file from the specified Path
[ "Fetch", "file", "from", "the", "specified", "Path" ]
ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/fetcher/fetcher_file.go#L38-L82
test
jpillora/overseer
fetcher/fetcher_http.go
Fetch
func (h *HTTP) Fetch() (io.Reader, error) { //delay fetches after first if h.delay { time.Sleep(h.Interval) } h.delay = true //status check using HEAD resp, err := http.Head(h.URL) if err != nil { return nil, fmt.Errorf("HEAD request failed (%s)", err) } resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("HEAD request failed (status code %d)", resp.StatusCode) } //if all headers match, skip update matches, total := 0, 0 for _, header := range h.CheckHeaders { if curr := resp.Header.Get(header); curr != "" { if last, ok := h.lasts[header]; ok && last == curr { matches++ } h.lasts[header] = curr total++ } } if matches == total { return nil, nil //skip, file match } //binary fetch using GET resp, err = http.Get(h.URL) if err != nil { return nil, fmt.Errorf("GET request failed (%s)", err) } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("GET request failed (status code %d)", resp.StatusCode) } //extract gz files if strings.HasSuffix(h.URL, ".gz") && resp.Header.Get("Content-Encoding") != "gzip" { return gzip.NewReader(resp.Body) } //success! return resp.Body, nil }
go
func (h *HTTP) Fetch() (io.Reader, error) { //delay fetches after first if h.delay { time.Sleep(h.Interval) } h.delay = true //status check using HEAD resp, err := http.Head(h.URL) if err != nil { return nil, fmt.Errorf("HEAD request failed (%s)", err) } resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("HEAD request failed (status code %d)", resp.StatusCode) } //if all headers match, skip update matches, total := 0, 0 for _, header := range h.CheckHeaders { if curr := resp.Header.Get(header); curr != "" { if last, ok := h.lasts[header]; ok && last == curr { matches++ } h.lasts[header] = curr total++ } } if matches == total { return nil, nil //skip, file match } //binary fetch using GET resp, err = http.Get(h.URL) if err != nil { return nil, fmt.Errorf("GET request failed (%s)", err) } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("GET request failed (status code %d)", resp.StatusCode) } //extract gz files if strings.HasSuffix(h.URL, ".gz") && resp.Header.Get("Content-Encoding") != "gzip" { return gzip.NewReader(resp.Body) } //success! return resp.Body, nil }
[ "func", "(", "h", "*", "HTTP", ")", "Fetch", "(", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "if", "h", ".", "delay", "{", "time", ".", "Sleep", "(", "h", ".", "Interval", ")", "\n", "}", "\n", "h", ".", "delay", "=", "true", "\n", "resp", ",", "err", ":=", "http", ".", "Head", "(", "h", ".", "URL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"HEAD request failed (%s)\"", ",", "err", ")", "\n", "}", "\n", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"HEAD request failed (status code %d)\"", ",", "resp", ".", "StatusCode", ")", "\n", "}", "\n", "matches", ",", "total", ":=", "0", ",", "0", "\n", "for", "_", ",", "header", ":=", "range", "h", ".", "CheckHeaders", "{", "if", "curr", ":=", "resp", ".", "Header", ".", "Get", "(", "header", ")", ";", "curr", "!=", "\"\"", "{", "if", "last", ",", "ok", ":=", "h", ".", "lasts", "[", "header", "]", ";", "ok", "&&", "last", "==", "curr", "{", "matches", "++", "\n", "}", "\n", "h", ".", "lasts", "[", "header", "]", "=", "curr", "\n", "total", "++", "\n", "}", "\n", "}", "\n", "if", "matches", "==", "total", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "resp", ",", "err", "=", "http", ".", "Get", "(", "h", ".", "URL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"GET request failed (%s)\"", ",", "err", ")", "\n", "}", "\n", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"GET request failed (status code %d)\"", ",", "resp", ".", "StatusCode", ")", "\n", "}", "\n", "if", "strings", ".", "HasSuffix", "(", "h", ".", "URL", ",", "\".gz\"", ")", "&&", "resp", ".", "Header", ".", "Get", "(", "\"Content-Encoding\"", ")", "!=", "\"gzip\"", "{", "return", "gzip", ".", "NewReader", "(", "resp", ".", "Body", ")", "\n", "}", "\n", "return", "resp", ".", "Body", ",", "nil", "\n", "}" ]
// Fetch the binary from the provided URL
[ "Fetch", "the", "binary", "from", "the", "provided", "URL" ]
ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a
https://github.com/jpillora/overseer/blob/ce9055846616cf7e1ab91bb8a0bcbb1d7fa3d11a/fetcher/fetcher_http.go#L45-L88
test
bsm/sarama-cluster
config.go
NewConfig
func NewConfig() *Config { c := &Config{ Config: *sarama.NewConfig(), } c.Group.PartitionStrategy = StrategyRange c.Group.Offsets.Retry.Max = 3 c.Group.Offsets.Synchronization.DwellTime = c.Consumer.MaxProcessingTime c.Group.Session.Timeout = 30 * time.Second c.Group.Heartbeat.Interval = 3 * time.Second c.Config.Version = minVersion return c }
go
func NewConfig() *Config { c := &Config{ Config: *sarama.NewConfig(), } c.Group.PartitionStrategy = StrategyRange c.Group.Offsets.Retry.Max = 3 c.Group.Offsets.Synchronization.DwellTime = c.Consumer.MaxProcessingTime c.Group.Session.Timeout = 30 * time.Second c.Group.Heartbeat.Interval = 3 * time.Second c.Config.Version = minVersion return c }
[ "func", "NewConfig", "(", ")", "*", "Config", "{", "c", ":=", "&", "Config", "{", "Config", ":", "*", "sarama", ".", "NewConfig", "(", ")", ",", "}", "\n", "c", ".", "Group", ".", "PartitionStrategy", "=", "StrategyRange", "\n", "c", ".", "Group", ".", "Offsets", ".", "Retry", ".", "Max", "=", "3", "\n", "c", ".", "Group", ".", "Offsets", ".", "Synchronization", ".", "DwellTime", "=", "c", ".", "Consumer", ".", "MaxProcessingTime", "\n", "c", ".", "Group", ".", "Session", ".", "Timeout", "=", "30", "*", "time", ".", "Second", "\n", "c", ".", "Group", ".", "Heartbeat", ".", "Interval", "=", "3", "*", "time", ".", "Second", "\n", "c", ".", "Config", ".", "Version", "=", "minVersion", "\n", "return", "c", "\n", "}" ]
// NewConfig returns a new configuration instance with sane defaults.
[ "NewConfig", "returns", "a", "new", "configuration", "instance", "with", "sane", "defaults", "." ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/config.go#L87-L98
test
bsm/sarama-cluster
config.go
Validate
func (c *Config) Validate() error { if c.Group.Heartbeat.Interval%time.Millisecond != 0 { sarama.Logger.Println("Group.Heartbeat.Interval only supports millisecond precision; nanoseconds will be truncated.") } if c.Group.Session.Timeout%time.Millisecond != 0 { sarama.Logger.Println("Group.Session.Timeout only supports millisecond precision; nanoseconds will be truncated.") } if c.Group.PartitionStrategy != StrategyRange && c.Group.PartitionStrategy != StrategyRoundRobin { sarama.Logger.Println("Group.PartitionStrategy is not supported; range will be assumed.") } if !c.Version.IsAtLeast(minVersion) { sarama.Logger.Println("Version is not supported; 0.9. will be assumed.") c.Version = minVersion } if err := c.Config.Validate(); err != nil { return err } // validate the Group values switch { case c.Group.Offsets.Retry.Max < 0: return sarama.ConfigurationError("Group.Offsets.Retry.Max must be >= 0") case c.Group.Offsets.Synchronization.DwellTime <= 0: return sarama.ConfigurationError("Group.Offsets.Synchronization.DwellTime must be > 0") case c.Group.Offsets.Synchronization.DwellTime > 10*time.Minute: return sarama.ConfigurationError("Group.Offsets.Synchronization.DwellTime must be <= 10m") case c.Group.Heartbeat.Interval <= 0: return sarama.ConfigurationError("Group.Heartbeat.Interval must be > 0") case c.Group.Session.Timeout <= 0: return sarama.ConfigurationError("Group.Session.Timeout must be > 0") case !c.Metadata.Full && c.Group.Topics.Whitelist != nil: return sarama.ConfigurationError("Metadata.Full must be enabled when Group.Topics.Whitelist is used") case !c.Metadata.Full && c.Group.Topics.Blacklist != nil: return sarama.ConfigurationError("Metadata.Full must be enabled when Group.Topics.Blacklist is used") } // ensure offset is correct switch c.Consumer.Offsets.Initial { case sarama.OffsetOldest, sarama.OffsetNewest: default: return sarama.ConfigurationError("Consumer.Offsets.Initial must be either OffsetOldest or OffsetNewest") } return nil }
go
func (c *Config) Validate() error { if c.Group.Heartbeat.Interval%time.Millisecond != 0 { sarama.Logger.Println("Group.Heartbeat.Interval only supports millisecond precision; nanoseconds will be truncated.") } if c.Group.Session.Timeout%time.Millisecond != 0 { sarama.Logger.Println("Group.Session.Timeout only supports millisecond precision; nanoseconds will be truncated.") } if c.Group.PartitionStrategy != StrategyRange && c.Group.PartitionStrategy != StrategyRoundRobin { sarama.Logger.Println("Group.PartitionStrategy is not supported; range will be assumed.") } if !c.Version.IsAtLeast(minVersion) { sarama.Logger.Println("Version is not supported; 0.9. will be assumed.") c.Version = minVersion } if err := c.Config.Validate(); err != nil { return err } // validate the Group values switch { case c.Group.Offsets.Retry.Max < 0: return sarama.ConfigurationError("Group.Offsets.Retry.Max must be >= 0") case c.Group.Offsets.Synchronization.DwellTime <= 0: return sarama.ConfigurationError("Group.Offsets.Synchronization.DwellTime must be > 0") case c.Group.Offsets.Synchronization.DwellTime > 10*time.Minute: return sarama.ConfigurationError("Group.Offsets.Synchronization.DwellTime must be <= 10m") case c.Group.Heartbeat.Interval <= 0: return sarama.ConfigurationError("Group.Heartbeat.Interval must be > 0") case c.Group.Session.Timeout <= 0: return sarama.ConfigurationError("Group.Session.Timeout must be > 0") case !c.Metadata.Full && c.Group.Topics.Whitelist != nil: return sarama.ConfigurationError("Metadata.Full must be enabled when Group.Topics.Whitelist is used") case !c.Metadata.Full && c.Group.Topics.Blacklist != nil: return sarama.ConfigurationError("Metadata.Full must be enabled when Group.Topics.Blacklist is used") } // ensure offset is correct switch c.Consumer.Offsets.Initial { case sarama.OffsetOldest, sarama.OffsetNewest: default: return sarama.ConfigurationError("Consumer.Offsets.Initial must be either OffsetOldest or OffsetNewest") } return nil }
[ "func", "(", "c", "*", "Config", ")", "Validate", "(", ")", "error", "{", "if", "c", ".", "Group", ".", "Heartbeat", ".", "Interval", "%", "time", ".", "Millisecond", "!=", "0", "{", "sarama", ".", "Logger", ".", "Println", "(", "\"Group.Heartbeat.Interval only supports millisecond precision; nanoseconds will be truncated.\"", ")", "\n", "}", "\n", "if", "c", ".", "Group", ".", "Session", ".", "Timeout", "%", "time", ".", "Millisecond", "!=", "0", "{", "sarama", ".", "Logger", ".", "Println", "(", "\"Group.Session.Timeout only supports millisecond precision; nanoseconds will be truncated.\"", ")", "\n", "}", "\n", "if", "c", ".", "Group", ".", "PartitionStrategy", "!=", "StrategyRange", "&&", "c", ".", "Group", ".", "PartitionStrategy", "!=", "StrategyRoundRobin", "{", "sarama", ".", "Logger", ".", "Println", "(", "\"Group.PartitionStrategy is not supported; range will be assumed.\"", ")", "\n", "}", "\n", "if", "!", "c", ".", "Version", ".", "IsAtLeast", "(", "minVersion", ")", "{", "sarama", ".", "Logger", ".", "Println", "(", "\"Version is not supported; 0.9. will be assumed.\"", ")", "\n", "c", ".", "Version", "=", "minVersion", "\n", "}", "\n", "if", "err", ":=", "c", ".", "Config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "switch", "{", "case", "c", ".", "Group", ".", "Offsets", ".", "Retry", ".", "Max", "<", "0", ":", "return", "sarama", ".", "ConfigurationError", "(", "\"Group.Offsets.Retry.Max must be >= 0\"", ")", "\n", "case", "c", ".", "Group", ".", "Offsets", ".", "Synchronization", ".", "DwellTime", "<=", "0", ":", "return", "sarama", ".", "ConfigurationError", "(", "\"Group.Offsets.Synchronization.DwellTime must be > 0\"", ")", "\n", "case", "c", ".", "Group", ".", "Offsets", ".", "Synchronization", ".", "DwellTime", ">", "10", "*", "time", ".", "Minute", ":", "return", "sarama", ".", "ConfigurationError", "(", "\"Group.Offsets.Synchronization.DwellTime must be <= 10m\"", ")", "\n", "case", "c", ".", "Group", ".", "Heartbeat", ".", "Interval", "<=", "0", ":", "return", "sarama", ".", "ConfigurationError", "(", "\"Group.Heartbeat.Interval must be > 0\"", ")", "\n", "case", "c", ".", "Group", ".", "Session", ".", "Timeout", "<=", "0", ":", "return", "sarama", ".", "ConfigurationError", "(", "\"Group.Session.Timeout must be > 0\"", ")", "\n", "case", "!", "c", ".", "Metadata", ".", "Full", "&&", "c", ".", "Group", ".", "Topics", ".", "Whitelist", "!=", "nil", ":", "return", "sarama", ".", "ConfigurationError", "(", "\"Metadata.Full must be enabled when Group.Topics.Whitelist is used\"", ")", "\n", "case", "!", "c", ".", "Metadata", ".", "Full", "&&", "c", ".", "Group", ".", "Topics", ".", "Blacklist", "!=", "nil", ":", "return", "sarama", ".", "ConfigurationError", "(", "\"Metadata.Full must be enabled when Group.Topics.Blacklist is used\"", ")", "\n", "}", "\n", "switch", "c", ".", "Consumer", ".", "Offsets", ".", "Initial", "{", "case", "sarama", ".", "OffsetOldest", ",", "sarama", ".", "OffsetNewest", ":", "default", ":", "return", "sarama", ".", "ConfigurationError", "(", "\"Consumer.Offsets.Initial must be either OffsetOldest or OffsetNewest\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate checks a Config instance. It will return a // sarama.ConfigurationError if the specified values don't make sense.
[ "Validate", "checks", "a", "Config", "instance", ".", "It", "will", "return", "a", "sarama", ".", "ConfigurationError", "if", "the", "specified", "values", "don", "t", "make", "sense", "." ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/config.go#L102-L146
test
bsm/sarama-cluster
client.go
NewClient
func NewClient(addrs []string, config *Config) (*Client, error) { if config == nil { config = NewConfig() } if err := config.Validate(); err != nil { return nil, err } client, err := sarama.NewClient(addrs, &config.Config) if err != nil { return nil, err } return &Client{Client: client, config: *config}, nil }
go
func NewClient(addrs []string, config *Config) (*Client, error) { if config == nil { config = NewConfig() } if err := config.Validate(); err != nil { return nil, err } client, err := sarama.NewClient(addrs, &config.Config) if err != nil { return nil, err } return &Client{Client: client, config: *config}, nil }
[ "func", "NewClient", "(", "addrs", "[", "]", "string", ",", "config", "*", "Config", ")", "(", "*", "Client", ",", "error", ")", "{", "if", "config", "==", "nil", "{", "config", "=", "NewConfig", "(", ")", "\n", "}", "\n", "if", "err", ":=", "config", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "client", ",", "err", ":=", "sarama", ".", "NewClient", "(", "addrs", ",", "&", "config", ".", "Config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Client", "{", "Client", ":", "client", ",", "config", ":", "*", "config", "}", ",", "nil", "\n", "}" ]
// NewClient creates a new client instance
[ "NewClient", "creates", "a", "new", "client", "instance" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/client.go#L21-L36
test
bsm/sarama-cluster
partitions.go
AsyncClose
func (c *partitionConsumer) AsyncClose() { c.closeOnce.Do(func() { c.closeErr = c.PartitionConsumer.Close() close(c.dying) }) }
go
func (c *partitionConsumer) AsyncClose() { c.closeOnce.Do(func() { c.closeErr = c.PartitionConsumer.Close() close(c.dying) }) }
[ "func", "(", "c", "*", "partitionConsumer", ")", "AsyncClose", "(", ")", "{", "c", ".", "closeOnce", ".", "Do", "(", "func", "(", ")", "{", "c", ".", "closeErr", "=", "c", ".", "PartitionConsumer", ".", "Close", "(", ")", "\n", "close", "(", "c", ".", "dying", ")", "\n", "}", ")", "\n", "}" ]
// AsyncClose implements PartitionConsumer
[ "AsyncClose", "implements", "PartitionConsumer" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/partitions.go#L87-L92
test
bsm/sarama-cluster
partitions.go
Close
func (c *partitionConsumer) Close() error { c.AsyncClose() <-c.dead return c.closeErr }
go
func (c *partitionConsumer) Close() error { c.AsyncClose() <-c.dead return c.closeErr }
[ "func", "(", "c", "*", "partitionConsumer", ")", "Close", "(", ")", "error", "{", "c", ".", "AsyncClose", "(", ")", "\n", "<-", "c", ".", "dead", "\n", "return", "c", ".", "closeErr", "\n", "}" ]
// Close implements PartitionConsumer
[ "Close", "implements", "PartitionConsumer" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/partitions.go#L95-L99
test
bsm/sarama-cluster
partitions.go
MarkOffset
func (c *partitionConsumer) MarkOffset(offset int64, metadata string) { c.mu.Lock() if next := offset + 1; next > c.state.Info.Offset { c.state.Info.Offset = next c.state.Info.Metadata = metadata c.state.Dirty = true } c.mu.Unlock() }
go
func (c *partitionConsumer) MarkOffset(offset int64, metadata string) { c.mu.Lock() if next := offset + 1; next > c.state.Info.Offset { c.state.Info.Offset = next c.state.Info.Metadata = metadata c.state.Dirty = true } c.mu.Unlock() }
[ "func", "(", "c", "*", "partitionConsumer", ")", "MarkOffset", "(", "offset", "int64", ",", "metadata", "string", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "next", ":=", "offset", "+", "1", ";", "next", ">", "c", ".", "state", ".", "Info", ".", "Offset", "{", "c", ".", "state", ".", "Info", ".", "Offset", "=", "next", "\n", "c", ".", "state", ".", "Info", ".", "Metadata", "=", "metadata", "\n", "c", ".", "state", ".", "Dirty", "=", "true", "\n", "}", "\n", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// MarkOffset implements PartitionConsumer
[ "MarkOffset", "implements", "PartitionConsumer" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/partitions.go#L161-L169
test
bsm/sarama-cluster
consumer.go
NewConsumer
func NewConsumer(addrs []string, groupID string, topics []string, config *Config) (*Consumer, error) { client, err := NewClient(addrs, config) if err != nil { return nil, err } consumer, err := NewConsumerFromClient(client, groupID, topics) if err != nil { return nil, err } consumer.ownClient = true return consumer, nil }
go
func NewConsumer(addrs []string, groupID string, topics []string, config *Config) (*Consumer, error) { client, err := NewClient(addrs, config) if err != nil { return nil, err } consumer, err := NewConsumerFromClient(client, groupID, topics) if err != nil { return nil, err } consumer.ownClient = true return consumer, nil }
[ "func", "NewConsumer", "(", "addrs", "[", "]", "string", ",", "groupID", "string", ",", "topics", "[", "]", "string", ",", "config", "*", "Config", ")", "(", "*", "Consumer", ",", "error", ")", "{", "client", ",", "err", ":=", "NewClient", "(", "addrs", ",", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "consumer", ",", "err", ":=", "NewConsumerFromClient", "(", "client", ",", "groupID", ",", "topics", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "consumer", ".", "ownClient", "=", "true", "\n", "return", "consumer", ",", "nil", "\n", "}" ]
// NewConsumer initializes a new consumer
[ "NewConsumer", "initializes", "a", "new", "consumer" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L43-L55
test
bsm/sarama-cluster
consumer.go
MarkOffsets
func (c *Consumer) MarkOffsets(s *OffsetStash) { s.mu.Lock() defer s.mu.Unlock() for tp, info := range s.offsets { if sub := c.subs.Fetch(tp.Topic, tp.Partition); sub != nil { sub.MarkOffset(info.Offset, info.Metadata) } delete(s.offsets, tp) } }
go
func (c *Consumer) MarkOffsets(s *OffsetStash) { s.mu.Lock() defer s.mu.Unlock() for tp, info := range s.offsets { if sub := c.subs.Fetch(tp.Topic, tp.Partition); sub != nil { sub.MarkOffset(info.Offset, info.Metadata) } delete(s.offsets, tp) } }
[ "func", "(", "c", "*", "Consumer", ")", "MarkOffsets", "(", "s", "*", "OffsetStash", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "for", "tp", ",", "info", ":=", "range", "s", ".", "offsets", "{", "if", "sub", ":=", "c", ".", "subs", ".", "Fetch", "(", "tp", ".", "Topic", ",", "tp", ".", "Partition", ")", ";", "sub", "!=", "nil", "{", "sub", ".", "MarkOffset", "(", "info", ".", "Offset", ",", "info", ".", "Metadata", ")", "\n", "}", "\n", "delete", "(", "s", ".", "offsets", ",", "tp", ")", "\n", "}", "\n", "}" ]
// MarkOffsets marks stashed offsets as processed. // See MarkOffset for additional explanation.
[ "MarkOffsets", "marks", "stashed", "offsets", "as", "processed", ".", "See", "MarkOffset", "for", "additional", "explanation", "." ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L158-L168
test
bsm/sarama-cluster
consumer.go
ResetOffset
func (c *Consumer) ResetOffset(msg *sarama.ConsumerMessage, metadata string) { if sub := c.subs.Fetch(msg.Topic, msg.Partition); sub != nil { sub.ResetOffset(msg.Offset, metadata) } }
go
func (c *Consumer) ResetOffset(msg *sarama.ConsumerMessage, metadata string) { if sub := c.subs.Fetch(msg.Topic, msg.Partition); sub != nil { sub.ResetOffset(msg.Offset, metadata) } }
[ "func", "(", "c", "*", "Consumer", ")", "ResetOffset", "(", "msg", "*", "sarama", ".", "ConsumerMessage", ",", "metadata", "string", ")", "{", "if", "sub", ":=", "c", ".", "subs", ".", "Fetch", "(", "msg", ".", "Topic", ",", "msg", ".", "Partition", ")", ";", "sub", "!=", "nil", "{", "sub", ".", "ResetOffset", "(", "msg", ".", "Offset", ",", "metadata", ")", "\n", "}", "\n", "}" ]
// ResetOffset marks the provided message as processed, alongside a metadata string // that represents the state of the partition consumer at that point in time. The // metadata string can be used by another consumer to restore that state, so it // can resume consumption. // // Difference between ResetOffset and MarkOffset is that it allows to rewind to an earlier offset
[ "ResetOffset", "marks", "the", "provided", "message", "as", "processed", "alongside", "a", "metadata", "string", "that", "represents", "the", "state", "of", "the", "partition", "consumer", "at", "that", "point", "in", "time", ".", "The", "metadata", "string", "can", "be", "used", "by", "another", "consumer", "to", "restore", "that", "state", "so", "it", "can", "resume", "consumption", ".", "Difference", "between", "ResetOffset", "and", "MarkOffset", "is", "that", "it", "allows", "to", "rewind", "to", "an", "earlier", "offset" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L176-L180
test
bsm/sarama-cluster
consumer.go
Close
func (c *Consumer) Close() (err error) { c.closeOnce.Do(func() { close(c.dying) <-c.dead if e := c.release(); e != nil { err = e } if e := c.consumer.Close(); e != nil { err = e } close(c.messages) close(c.errors) if e := c.leaveGroup(); e != nil { err = e } close(c.partitions) close(c.notifications) // drain for range c.messages { } for range c.errors { } for p := range c.partitions { _ = p.Close() } for range c.notifications { } c.client.release() if c.ownClient { if e := c.client.Close(); e != nil { err = e } } }) return }
go
func (c *Consumer) Close() (err error) { c.closeOnce.Do(func() { close(c.dying) <-c.dead if e := c.release(); e != nil { err = e } if e := c.consumer.Close(); e != nil { err = e } close(c.messages) close(c.errors) if e := c.leaveGroup(); e != nil { err = e } close(c.partitions) close(c.notifications) // drain for range c.messages { } for range c.errors { } for p := range c.partitions { _ = p.Close() } for range c.notifications { } c.client.release() if c.ownClient { if e := c.client.Close(); e != nil { err = e } } }) return }
[ "func", "(", "c", "*", "Consumer", ")", "Close", "(", ")", "(", "err", "error", ")", "{", "c", ".", "closeOnce", ".", "Do", "(", "func", "(", ")", "{", "close", "(", "c", ".", "dying", ")", "\n", "<-", "c", ".", "dead", "\n", "if", "e", ":=", "c", ".", "release", "(", ")", ";", "e", "!=", "nil", "{", "err", "=", "e", "\n", "}", "\n", "if", "e", ":=", "c", ".", "consumer", ".", "Close", "(", ")", ";", "e", "!=", "nil", "{", "err", "=", "e", "\n", "}", "\n", "close", "(", "c", ".", "messages", ")", "\n", "close", "(", "c", ".", "errors", ")", "\n", "if", "e", ":=", "c", ".", "leaveGroup", "(", ")", ";", "e", "!=", "nil", "{", "err", "=", "e", "\n", "}", "\n", "close", "(", "c", ".", "partitions", ")", "\n", "close", "(", "c", ".", "notifications", ")", "\n", "for", "range", "c", ".", "messages", "{", "}", "\n", "for", "range", "c", ".", "errors", "{", "}", "\n", "for", "p", ":=", "range", "c", ".", "partitions", "{", "_", "=", "p", ".", "Close", "(", ")", "\n", "}", "\n", "for", "range", "c", ".", "notifications", "{", "}", "\n", "c", ".", "client", ".", "release", "(", ")", "\n", "if", "c", ".", "ownClient", "{", "if", "e", ":=", "c", ".", "client", ".", "Close", "(", ")", ";", "e", "!=", "nil", "{", "err", "=", "e", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "return", "\n", "}" ]
// Close safely closes the consumer and releases all resources
[ "Close", "safely", "closes", "the", "consumer", "and", "releases", "all", "resources" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L272-L311
test
bsm/sarama-cluster
consumer.go
hbLoop
func (c *Consumer) hbLoop(stopped <-chan none) { ticker := time.NewTicker(c.client.config.Group.Heartbeat.Interval) defer ticker.Stop() for { select { case <-ticker.C: switch err := c.heartbeat(); err { case nil, sarama.ErrNoError: case sarama.ErrNotCoordinatorForConsumer, sarama.ErrRebalanceInProgress: return default: c.handleError(&Error{Ctx: "heartbeat", error: err}) return } case <-stopped: return case <-c.dying: return } } }
go
func (c *Consumer) hbLoop(stopped <-chan none) { ticker := time.NewTicker(c.client.config.Group.Heartbeat.Interval) defer ticker.Stop() for { select { case <-ticker.C: switch err := c.heartbeat(); err { case nil, sarama.ErrNoError: case sarama.ErrNotCoordinatorForConsumer, sarama.ErrRebalanceInProgress: return default: c.handleError(&Error{Ctx: "heartbeat", error: err}) return } case <-stopped: return case <-c.dying: return } } }
[ "func", "(", "c", "*", "Consumer", ")", "hbLoop", "(", "stopped", "<-", "chan", "none", ")", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "c", ".", "client", ".", "config", ".", "Group", ".", "Heartbeat", ".", "Interval", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "ticker", ".", "C", ":", "switch", "err", ":=", "c", ".", "heartbeat", "(", ")", ";", "err", "{", "case", "nil", ",", "sarama", ".", "ErrNoError", ":", "case", "sarama", ".", "ErrNotCoordinatorForConsumer", ",", "sarama", ".", "ErrRebalanceInProgress", ":", "return", "\n", "default", ":", "c", ".", "handleError", "(", "&", "Error", "{", "Ctx", ":", "\"heartbeat\"", ",", "error", ":", "err", "}", ")", "\n", "return", "\n", "}", "\n", "case", "<-", "stopped", ":", "return", "\n", "case", "<-", "c", ".", "dying", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// heartbeat loop, triggered by the mainLoop
[ "heartbeat", "loop", "triggered", "by", "the", "mainLoop" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L398-L419
test
bsm/sarama-cluster
consumer.go
twLoop
func (c *Consumer) twLoop(stopped <-chan none) { ticker := time.NewTicker(c.client.config.Metadata.RefreshFrequency / 2) defer ticker.Stop() for { select { case <-ticker.C: topics, err := c.client.Topics() if err != nil { c.handleError(&Error{Ctx: "topics", error: err}) return } for _, topic := range topics { if !c.isKnownCoreTopic(topic) && !c.isKnownExtraTopic(topic) && c.isPotentialExtraTopic(topic) { return } } case <-stopped: return case <-c.dying: return } } }
go
func (c *Consumer) twLoop(stopped <-chan none) { ticker := time.NewTicker(c.client.config.Metadata.RefreshFrequency / 2) defer ticker.Stop() for { select { case <-ticker.C: topics, err := c.client.Topics() if err != nil { c.handleError(&Error{Ctx: "topics", error: err}) return } for _, topic := range topics { if !c.isKnownCoreTopic(topic) && !c.isKnownExtraTopic(topic) && c.isPotentialExtraTopic(topic) { return } } case <-stopped: return case <-c.dying: return } } }
[ "func", "(", "c", "*", "Consumer", ")", "twLoop", "(", "stopped", "<-", "chan", "none", ")", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "c", ".", "client", ".", "config", ".", "Metadata", ".", "RefreshFrequency", "/", "2", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "ticker", ".", "C", ":", "topics", ",", "err", ":=", "c", ".", "client", ".", "Topics", "(", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "handleError", "(", "&", "Error", "{", "Ctx", ":", "\"topics\"", ",", "error", ":", "err", "}", ")", "\n", "return", "\n", "}", "\n", "for", "_", ",", "topic", ":=", "range", "topics", "{", "if", "!", "c", ".", "isKnownCoreTopic", "(", "topic", ")", "&&", "!", "c", ".", "isKnownExtraTopic", "(", "topic", ")", "&&", "c", ".", "isPotentialExtraTopic", "(", "topic", ")", "{", "return", "\n", "}", "\n", "}", "\n", "case", "<-", "stopped", ":", "return", "\n", "case", "<-", "c", ".", "dying", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// topic watcher loop, triggered by the mainLoop
[ "topic", "watcher", "loop", "triggered", "by", "the", "mainLoop" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L422-L448
test
bsm/sarama-cluster
consumer.go
cmLoop
func (c *Consumer) cmLoop(stopped <-chan none) { ticker := time.NewTicker(c.client.config.Consumer.Offsets.CommitInterval) defer ticker.Stop() for { select { case <-ticker.C: if err := c.commitOffsetsWithRetry(c.client.config.Group.Offsets.Retry.Max); err != nil { c.handleError(&Error{Ctx: "commit", error: err}) return } case <-stopped: return case <-c.dying: return } } }
go
func (c *Consumer) cmLoop(stopped <-chan none) { ticker := time.NewTicker(c.client.config.Consumer.Offsets.CommitInterval) defer ticker.Stop() for { select { case <-ticker.C: if err := c.commitOffsetsWithRetry(c.client.config.Group.Offsets.Retry.Max); err != nil { c.handleError(&Error{Ctx: "commit", error: err}) return } case <-stopped: return case <-c.dying: return } } }
[ "func", "(", "c", "*", "Consumer", ")", "cmLoop", "(", "stopped", "<-", "chan", "none", ")", "{", "ticker", ":=", "time", ".", "NewTicker", "(", "c", ".", "client", ".", "config", ".", "Consumer", ".", "Offsets", ".", "CommitInterval", ")", "\n", "defer", "ticker", ".", "Stop", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "ticker", ".", "C", ":", "if", "err", ":=", "c", ".", "commitOffsetsWithRetry", "(", "c", ".", "client", ".", "config", ".", "Group", ".", "Offsets", ".", "Retry", ".", "Max", ")", ";", "err", "!=", "nil", "{", "c", ".", "handleError", "(", "&", "Error", "{", "Ctx", ":", "\"commit\"", ",", "error", ":", "err", "}", ")", "\n", "return", "\n", "}", "\n", "case", "<-", "stopped", ":", "return", "\n", "case", "<-", "c", ".", "dying", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// commit loop, triggered by the mainLoop
[ "commit", "loop", "triggered", "by", "the", "mainLoop" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L451-L468
test
bsm/sarama-cluster
consumer.go
fetchOffsets
func (c *Consumer) fetchOffsets(subs map[string][]int32) (map[string]map[int32]offsetInfo, error) { offsets := make(map[string]map[int32]offsetInfo, len(subs)) req := &sarama.OffsetFetchRequest{ Version: 1, ConsumerGroup: c.groupID, } for topic, partitions := range subs { offsets[topic] = make(map[int32]offsetInfo, len(partitions)) for _, partition := range partitions { offsets[topic][partition] = offsetInfo{Offset: -1} req.AddPartition(topic, partition) } } broker, err := c.client.Coordinator(c.groupID) if err != nil { c.closeCoordinator(broker, err) return nil, err } resp, err := broker.FetchOffset(req) if err != nil { c.closeCoordinator(broker, err) return nil, err } for topic, partitions := range subs { for _, partition := range partitions { block := resp.GetBlock(topic, partition) if block == nil { return nil, sarama.ErrIncompleteResponse } if block.Err == sarama.ErrNoError { offsets[topic][partition] = offsetInfo{Offset: block.Offset, Metadata: block.Metadata} } else { return nil, block.Err } } } return offsets, nil }
go
func (c *Consumer) fetchOffsets(subs map[string][]int32) (map[string]map[int32]offsetInfo, error) { offsets := make(map[string]map[int32]offsetInfo, len(subs)) req := &sarama.OffsetFetchRequest{ Version: 1, ConsumerGroup: c.groupID, } for topic, partitions := range subs { offsets[topic] = make(map[int32]offsetInfo, len(partitions)) for _, partition := range partitions { offsets[topic][partition] = offsetInfo{Offset: -1} req.AddPartition(topic, partition) } } broker, err := c.client.Coordinator(c.groupID) if err != nil { c.closeCoordinator(broker, err) return nil, err } resp, err := broker.FetchOffset(req) if err != nil { c.closeCoordinator(broker, err) return nil, err } for topic, partitions := range subs { for _, partition := range partitions { block := resp.GetBlock(topic, partition) if block == nil { return nil, sarama.ErrIncompleteResponse } if block.Err == sarama.ErrNoError { offsets[topic][partition] = offsetInfo{Offset: block.Offset, Metadata: block.Metadata} } else { return nil, block.Err } } } return offsets, nil }
[ "func", "(", "c", "*", "Consumer", ")", "fetchOffsets", "(", "subs", "map", "[", "string", "]", "[", "]", "int32", ")", "(", "map", "[", "string", "]", "map", "[", "int32", "]", "offsetInfo", ",", "error", ")", "{", "offsets", ":=", "make", "(", "map", "[", "string", "]", "map", "[", "int32", "]", "offsetInfo", ",", "len", "(", "subs", ")", ")", "\n", "req", ":=", "&", "sarama", ".", "OffsetFetchRequest", "{", "Version", ":", "1", ",", "ConsumerGroup", ":", "c", ".", "groupID", ",", "}", "\n", "for", "topic", ",", "partitions", ":=", "range", "subs", "{", "offsets", "[", "topic", "]", "=", "make", "(", "map", "[", "int32", "]", "offsetInfo", ",", "len", "(", "partitions", ")", ")", "\n", "for", "_", ",", "partition", ":=", "range", "partitions", "{", "offsets", "[", "topic", "]", "[", "partition", "]", "=", "offsetInfo", "{", "Offset", ":", "-", "1", "}", "\n", "req", ".", "AddPartition", "(", "topic", ",", "partition", ")", "\n", "}", "\n", "}", "\n", "broker", ",", "err", ":=", "c", ".", "client", ".", "Coordinator", "(", "c", ".", "groupID", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "closeCoordinator", "(", "broker", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "resp", ",", "err", ":=", "broker", ".", "FetchOffset", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "closeCoordinator", "(", "broker", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "for", "topic", ",", "partitions", ":=", "range", "subs", "{", "for", "_", ",", "partition", ":=", "range", "partitions", "{", "block", ":=", "resp", ".", "GetBlock", "(", "topic", ",", "partition", ")", "\n", "if", "block", "==", "nil", "{", "return", "nil", ",", "sarama", ".", "ErrIncompleteResponse", "\n", "}", "\n", "if", "block", ".", "Err", "==", "sarama", ".", "ErrNoError", "{", "offsets", "[", "topic", "]", "[", "partition", "]", "=", "offsetInfo", "{", "Offset", ":", "block", ".", "Offset", ",", "Metadata", ":", "block", ".", "Metadata", "}", "\n", "}", "else", "{", "return", "nil", ",", "block", ".", "Err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "offsets", ",", "nil", "\n", "}" ]
// Fetches latest committed offsets for all subscriptions
[ "Fetches", "latest", "committed", "offsets", "for", "all", "subscriptions" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/consumer.go#L748-L790
test
bsm/sarama-cluster
offsets.go
MarkOffset
func (s *OffsetStash) MarkOffset(msg *sarama.ConsumerMessage, metadata string) { s.MarkPartitionOffset(msg.Topic, msg.Partition, msg.Offset, metadata) }
go
func (s *OffsetStash) MarkOffset(msg *sarama.ConsumerMessage, metadata string) { s.MarkPartitionOffset(msg.Topic, msg.Partition, msg.Offset, metadata) }
[ "func", "(", "s", "*", "OffsetStash", ")", "MarkOffset", "(", "msg", "*", "sarama", ".", "ConsumerMessage", ",", "metadata", "string", ")", "{", "s", ".", "MarkPartitionOffset", "(", "msg", ".", "Topic", ",", "msg", ".", "Partition", ",", "msg", ".", "Offset", ",", "metadata", ")", "\n", "}" ]
// MarkOffset stashes the provided message offset
[ "MarkOffset", "stashes", "the", "provided", "message", "offset" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/offsets.go#L22-L24
test
bsm/sarama-cluster
offsets.go
ResetOffset
func (s *OffsetStash) ResetOffset(msg *sarama.ConsumerMessage, metadata string) { s.ResetPartitionOffset(msg.Topic, msg.Partition, msg.Offset, metadata) }
go
func (s *OffsetStash) ResetOffset(msg *sarama.ConsumerMessage, metadata string) { s.ResetPartitionOffset(msg.Topic, msg.Partition, msg.Offset, metadata) }
[ "func", "(", "s", "*", "OffsetStash", ")", "ResetOffset", "(", "msg", "*", "sarama", ".", "ConsumerMessage", ",", "metadata", "string", ")", "{", "s", ".", "ResetPartitionOffset", "(", "msg", ".", "Topic", ",", "msg", ".", "Partition", ",", "msg", ".", "Offset", ",", "metadata", ")", "\n", "}" ]
// ResetOffset stashes the provided message offset // See ResetPartitionOffset for explanation
[ "ResetOffset", "stashes", "the", "provided", "message", "offset", "See", "ResetPartitionOffset", "for", "explanation" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/offsets.go#L55-L57
test
bsm/sarama-cluster
offsets.go
Offsets
func (s *OffsetStash) Offsets() map[string]int64 { s.mu.Lock() defer s.mu.Unlock() res := make(map[string]int64, len(s.offsets)) for tp, info := range s.offsets { res[tp.String()] = info.Offset } return res }
go
func (s *OffsetStash) Offsets() map[string]int64 { s.mu.Lock() defer s.mu.Unlock() res := make(map[string]int64, len(s.offsets)) for tp, info := range s.offsets { res[tp.String()] = info.Offset } return res }
[ "func", "(", "s", "*", "OffsetStash", ")", "Offsets", "(", ")", "map", "[", "string", "]", "int64", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "res", ":=", "make", "(", "map", "[", "string", "]", "int64", ",", "len", "(", "s", ".", "offsets", ")", ")", "\n", "for", "tp", ",", "info", ":=", "range", "s", ".", "offsets", "{", "res", "[", "tp", ".", "String", "(", ")", "]", "=", "info", ".", "Offset", "\n", "}", "\n", "return", "res", "\n", "}" ]
// Offsets returns the latest stashed offsets by topic-partition
[ "Offsets", "returns", "the", "latest", "stashed", "offsets", "by", "topic", "-", "partition" ]
d5779253526cc8a3129a0e5d7cc429f4b4473ab4
https://github.com/bsm/sarama-cluster/blob/d5779253526cc8a3129a0e5d7cc429f4b4473ab4/offsets.go#L60-L69
test
kubicorn/kubicorn
cloud/google/compute/resources/instancegroup.go
Actual
func (r *InstanceGroup) Actual(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("instanceGroup.Actual") if r.CachedActual != nil { logger.Debug("Using cached instance [actual]") return immutable, r.CachedActual, nil } newResource := &InstanceGroup{ Shared: Shared{ Name: r.Name, CloudID: r.ServerPool.Identifier, }, } project, err := Sdk.Service.Projects.Get(immutable.ProviderConfig().CloudId).Do() if err != nil && project != nil { instances, err := Sdk.Service.Instances.List(immutable.ProviderConfig().CloudId, immutable.ProviderConfig().Location).Do() if err != nil { return nil, nil, err } count := len(instances.Items) if count > 0 { newResource.Count = count instance := instances.Items[0] newResource.Name = instance.Name newResource.CloudID = string(instance.Id) newResource.Size = instance.Kind newResource.Image = r.Image newResource.Location = instance.Zone } } newResource.BootstrapScripts = r.ServerPool.BootstrapScripts newResource.SSHFingerprint = immutable.ProviderConfig().SSH.PublicKeyFingerprint newResource.Name = r.Name r.CachedActual = newResource return immutable, newResource, nil }
go
func (r *InstanceGroup) Actual(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("instanceGroup.Actual") if r.CachedActual != nil { logger.Debug("Using cached instance [actual]") return immutable, r.CachedActual, nil } newResource := &InstanceGroup{ Shared: Shared{ Name: r.Name, CloudID: r.ServerPool.Identifier, }, } project, err := Sdk.Service.Projects.Get(immutable.ProviderConfig().CloudId).Do() if err != nil && project != nil { instances, err := Sdk.Service.Instances.List(immutable.ProviderConfig().CloudId, immutable.ProviderConfig().Location).Do() if err != nil { return nil, nil, err } count := len(instances.Items) if count > 0 { newResource.Count = count instance := instances.Items[0] newResource.Name = instance.Name newResource.CloudID = string(instance.Id) newResource.Size = instance.Kind newResource.Image = r.Image newResource.Location = instance.Zone } } newResource.BootstrapScripts = r.ServerPool.BootstrapScripts newResource.SSHFingerprint = immutable.ProviderConfig().SSH.PublicKeyFingerprint newResource.Name = r.Name r.CachedActual = newResource return immutable, newResource, nil }
[ "func", "(", "r", "*", "InstanceGroup", ")", "Actual", "(", "immutable", "*", "cluster", ".", "Cluster", ")", "(", "*", "cluster", ".", "Cluster", ",", "cloud", ".", "Resource", ",", "error", ")", "{", "logger", ".", "Debug", "(", "\"instanceGroup.Actual\"", ")", "\n", "if", "r", ".", "CachedActual", "!=", "nil", "{", "logger", ".", "Debug", "(", "\"Using cached instance [actual]\"", ")", "\n", "return", "immutable", ",", "r", ".", "CachedActual", ",", "nil", "\n", "}", "\n", "newResource", ":=", "&", "InstanceGroup", "{", "Shared", ":", "Shared", "{", "Name", ":", "r", ".", "Name", ",", "CloudID", ":", "r", ".", "ServerPool", ".", "Identifier", ",", "}", ",", "}", "\n", "project", ",", "err", ":=", "Sdk", ".", "Service", ".", "Projects", ".", "Get", "(", "immutable", ".", "ProviderConfig", "(", ")", ".", "CloudId", ")", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "project", "!=", "nil", "{", "instances", ",", "err", ":=", "Sdk", ".", "Service", ".", "Instances", ".", "List", "(", "immutable", ".", "ProviderConfig", "(", ")", ".", "CloudId", ",", "immutable", ".", "ProviderConfig", "(", ")", ".", "Location", ")", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "count", ":=", "len", "(", "instances", ".", "Items", ")", "\n", "if", "count", ">", "0", "{", "newResource", ".", "Count", "=", "count", "\n", "instance", ":=", "instances", ".", "Items", "[", "0", "]", "\n", "newResource", ".", "Name", "=", "instance", ".", "Name", "\n", "newResource", ".", "CloudID", "=", "string", "(", "instance", ".", "Id", ")", "\n", "newResource", ".", "Size", "=", "instance", ".", "Kind", "\n", "newResource", ".", "Image", "=", "r", ".", "Image", "\n", "newResource", ".", "Location", "=", "instance", ".", "Zone", "\n", "}", "\n", "}", "\n", "newResource", ".", "BootstrapScripts", "=", "r", ".", "ServerPool", ".", "BootstrapScripts", "\n", "newResource", ".", "SSHFingerprint", "=", "immutable", ".", "ProviderConfig", "(", ")", ".", "SSH", ".", "PublicKeyFingerprint", "\n", "newResource", ".", "Name", "=", "r", ".", "Name", "\n", "r", ".", "CachedActual", "=", "newResource", "\n", "return", "immutable", ",", "newResource", ",", "nil", "\n", "}" ]
// Actual is used to build a cluster based on instances on the cloud provider.
[ "Actual", "is", "used", "to", "build", "a", "cluster", "based", "on", "instances", "on", "the", "cloud", "provider", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/google/compute/resources/instancegroup.go#L57-L95
test
kubicorn/kubicorn
cloud/google/compute/resources/instancegroup.go
Expected
func (r *InstanceGroup) Expected(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("instanceGroup.Expected") if r.CachedExpected != nil { logger.Debug("Using instance subnet [expected]") return immutable, r.CachedExpected, nil } expected := &InstanceGroup{ Shared: Shared{ Name: r.Name, CloudID: r.ServerPool.Identifier, }, Size: r.ServerPool.Size, Location: immutable.ProviderConfig().Location, Image: r.ServerPool.Image, Count: r.ServerPool.MaxCount, SSHFingerprint: immutable.ProviderConfig().SSH.PublicKeyFingerprint, BootstrapScripts: r.ServerPool.BootstrapScripts, } r.CachedExpected = expected return immutable, expected, nil }
go
func (r *InstanceGroup) Expected(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("instanceGroup.Expected") if r.CachedExpected != nil { logger.Debug("Using instance subnet [expected]") return immutable, r.CachedExpected, nil } expected := &InstanceGroup{ Shared: Shared{ Name: r.Name, CloudID: r.ServerPool.Identifier, }, Size: r.ServerPool.Size, Location: immutable.ProviderConfig().Location, Image: r.ServerPool.Image, Count: r.ServerPool.MaxCount, SSHFingerprint: immutable.ProviderConfig().SSH.PublicKeyFingerprint, BootstrapScripts: r.ServerPool.BootstrapScripts, } r.CachedExpected = expected return immutable, expected, nil }
[ "func", "(", "r", "*", "InstanceGroup", ")", "Expected", "(", "immutable", "*", "cluster", ".", "Cluster", ")", "(", "*", "cluster", ".", "Cluster", ",", "cloud", ".", "Resource", ",", "error", ")", "{", "logger", ".", "Debug", "(", "\"instanceGroup.Expected\"", ")", "\n", "if", "r", ".", "CachedExpected", "!=", "nil", "{", "logger", ".", "Debug", "(", "\"Using instance subnet [expected]\"", ")", "\n", "return", "immutable", ",", "r", ".", "CachedExpected", ",", "nil", "\n", "}", "\n", "expected", ":=", "&", "InstanceGroup", "{", "Shared", ":", "Shared", "{", "Name", ":", "r", ".", "Name", ",", "CloudID", ":", "r", ".", "ServerPool", ".", "Identifier", ",", "}", ",", "Size", ":", "r", ".", "ServerPool", ".", "Size", ",", "Location", ":", "immutable", ".", "ProviderConfig", "(", ")", ".", "Location", ",", "Image", ":", "r", ".", "ServerPool", ".", "Image", ",", "Count", ":", "r", ".", "ServerPool", ".", "MaxCount", ",", "SSHFingerprint", ":", "immutable", ".", "ProviderConfig", "(", ")", ".", "SSH", ".", "PublicKeyFingerprint", ",", "BootstrapScripts", ":", "r", ".", "ServerPool", ".", "BootstrapScripts", ",", "}", "\n", "r", ".", "CachedExpected", "=", "expected", "\n", "return", "immutable", ",", "expected", ",", "nil", "\n", "}" ]
// Expected is used to build a cluster expected to be on the cloud provider.
[ "Expected", "is", "used", "to", "build", "a", "cluster", "expected", "to", "be", "on", "the", "cloud", "provider", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/google/compute/resources/instancegroup.go#L98-L118
test
kubicorn/kubicorn
cloud/google/compute/resources/instancegroup.go
Delete
func (r *InstanceGroup) Delete(actual cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("instanceGroup.Delete") deleteResource := actual.(*InstanceGroup) if deleteResource.Name == "" { return nil, nil, fmt.Errorf("Unable to delete instance resource without Name [%s]", deleteResource.Name) } logger.Success("Deleting InstanceGroup manager [%s]", r.ServerPool.Name) _, err := Sdk.Service.InstanceGroupManagers.Get(immutable.ProviderConfig().CloudId, immutable.ProviderConfig().Location, strings.ToLower(r.ServerPool.Name)).Do() if err == nil { _, err := Sdk.Service.InstanceGroupManagers.Delete(immutable.ProviderConfig().CloudId, immutable.ProviderConfig().Location, strings.ToLower(r.ServerPool.Name)).Do() if err != nil { return nil, nil, err } } _, err = Sdk.Service.InstanceTemplates.Get(immutable.ProviderConfig().CloudId, strings.ToLower(r.ServerPool.Name)).Do() if err == nil { err := r.retryDeleteInstanceTemplate(immutable) if err != nil { return nil, nil, err } } // Kubernetes API providerConfig := immutable.ProviderConfig() providerConfig.KubernetesAPI.Endpoint = "" immutable.SetProviderConfig(providerConfig) renderedCluster, err := r.immutableRender(actual, immutable) if err != nil { return nil, nil, err } return renderedCluster, actual, nil }
go
func (r *InstanceGroup) Delete(actual cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("instanceGroup.Delete") deleteResource := actual.(*InstanceGroup) if deleteResource.Name == "" { return nil, nil, fmt.Errorf("Unable to delete instance resource without Name [%s]", deleteResource.Name) } logger.Success("Deleting InstanceGroup manager [%s]", r.ServerPool.Name) _, err := Sdk.Service.InstanceGroupManagers.Get(immutable.ProviderConfig().CloudId, immutable.ProviderConfig().Location, strings.ToLower(r.ServerPool.Name)).Do() if err == nil { _, err := Sdk.Service.InstanceGroupManagers.Delete(immutable.ProviderConfig().CloudId, immutable.ProviderConfig().Location, strings.ToLower(r.ServerPool.Name)).Do() if err != nil { return nil, nil, err } } _, err = Sdk.Service.InstanceTemplates.Get(immutable.ProviderConfig().CloudId, strings.ToLower(r.ServerPool.Name)).Do() if err == nil { err := r.retryDeleteInstanceTemplate(immutable) if err != nil { return nil, nil, err } } // Kubernetes API providerConfig := immutable.ProviderConfig() providerConfig.KubernetesAPI.Endpoint = "" immutable.SetProviderConfig(providerConfig) renderedCluster, err := r.immutableRender(actual, immutable) if err != nil { return nil, nil, err } return renderedCluster, actual, nil }
[ "func", "(", "r", "*", "InstanceGroup", ")", "Delete", "(", "actual", "cloud", ".", "Resource", ",", "immutable", "*", "cluster", ".", "Cluster", ")", "(", "*", "cluster", ".", "Cluster", ",", "cloud", ".", "Resource", ",", "error", ")", "{", "logger", ".", "Debug", "(", "\"instanceGroup.Delete\"", ")", "\n", "deleteResource", ":=", "actual", ".", "(", "*", "InstanceGroup", ")", "\n", "if", "deleteResource", ".", "Name", "==", "\"\"", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"Unable to delete instance resource without Name [%s]\"", ",", "deleteResource", ".", "Name", ")", "\n", "}", "\n", "logger", ".", "Success", "(", "\"Deleting InstanceGroup manager [%s]\"", ",", "r", ".", "ServerPool", ".", "Name", ")", "\n", "_", ",", "err", ":=", "Sdk", ".", "Service", ".", "InstanceGroupManagers", ".", "Get", "(", "immutable", ".", "ProviderConfig", "(", ")", ".", "CloudId", ",", "immutable", ".", "ProviderConfig", "(", ")", ".", "Location", ",", "strings", ".", "ToLower", "(", "r", ".", "ServerPool", ".", "Name", ")", ")", ".", "Do", "(", ")", "\n", "if", "err", "==", "nil", "{", "_", ",", "err", ":=", "Sdk", ".", "Service", ".", "InstanceGroupManagers", ".", "Delete", "(", "immutable", ".", "ProviderConfig", "(", ")", ".", "CloudId", ",", "immutable", ".", "ProviderConfig", "(", ")", ".", "Location", ",", "strings", ".", "ToLower", "(", "r", ".", "ServerPool", ".", "Name", ")", ")", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "_", ",", "err", "=", "Sdk", ".", "Service", ".", "InstanceTemplates", ".", "Get", "(", "immutable", ".", "ProviderConfig", "(", ")", ".", "CloudId", ",", "strings", ".", "ToLower", "(", "r", ".", "ServerPool", ".", "Name", ")", ")", ".", "Do", "(", ")", "\n", "if", "err", "==", "nil", "{", "err", ":=", "r", ".", "retryDeleteInstanceTemplate", "(", "immutable", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "providerConfig", ":=", "immutable", ".", "ProviderConfig", "(", ")", "\n", "providerConfig", ".", "KubernetesAPI", ".", "Endpoint", "=", "\"\"", "\n", "immutable", ".", "SetProviderConfig", "(", "providerConfig", ")", "\n", "renderedCluster", ",", "err", ":=", "r", ".", "immutableRender", "(", "actual", ",", "immutable", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "renderedCluster", ",", "actual", ",", "nil", "\n", "}" ]
// Delete is used to delete the instances on the cloud provider
[ "Delete", "is", "used", "to", "delete", "the", "instances", "on", "the", "cloud", "provider" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/google/compute/resources/instancegroup.go#L338-L371
test
kubicorn/kubicorn
pkg/reconciler.go
GetReconciler
func GetReconciler(known *cluster.Cluster, runtimeParameters *RuntimeParameters) (reconciler cloud.Reconciler, err error) { switch known.ProviderConfig().Cloud { case cluster.CloudGoogle: sdk, err := googleSDK.NewSdk() if err != nil { return nil, err } gr.Sdk = sdk return cloud.NewAtomicReconciler(known, compute.NewGoogleComputeModel(known)), nil case cluster.CloudDigitalOcean: sdk, err := godoSdk.NewSdk() if err != nil { return nil, err } dr.Sdk = sdk return cloud.NewAtomicReconciler(known, droplet.NewDigitalOceanDropletModel(known)), nil case cluster.CloudAmazon: awsProfile := "" if runtimeParameters != nil { awsProfile = runtimeParameters.AwsProfile } sdk, err := awsSdkGo.NewSdk(known.ProviderConfig().Location, awsProfile) if err != nil { return nil, err } ar.Sdk = sdk return cloud.NewAtomicReconciler(known, awspub.NewAmazonPublicModel(known)), nil case cluster.CloudAzure: sdk, err := azureSDK.NewSdk() if err != nil { return nil, err } azr.Sdk = sdk return cloud.NewAtomicReconciler(known, azpub.NewAzurePublicModel(known)), nil case cluster.CloudOVH: sdk, err := openstackSdk.NewSdk(known.ProviderConfig().Location) if err != nil { return nil, err } osr.Sdk = sdk return cloud.NewAtomicReconciler(known, osovh.NewOvhPublicModel(known)), nil case cluster.CloudPacket: sdk, err := packetSDK.NewSdk() if err != nil { return nil, err } packetr.Sdk = sdk return cloud.NewAtomicReconciler(known, packetpub.NewPacketPublicModel(known)), nil case cluster.CloudECS: sdk, err := openstackSdk.NewSdk(known.ProviderConfig().Location) if err != nil { return nil, err } osr.Sdk = sdk return cloud.NewAtomicReconciler(known, osecs.NewEcsPublicModel(known)), nil default: return nil, fmt.Errorf("Invalid cloud type: %s", known.ProviderConfig().Cloud) } }
go
func GetReconciler(known *cluster.Cluster, runtimeParameters *RuntimeParameters) (reconciler cloud.Reconciler, err error) { switch known.ProviderConfig().Cloud { case cluster.CloudGoogle: sdk, err := googleSDK.NewSdk() if err != nil { return nil, err } gr.Sdk = sdk return cloud.NewAtomicReconciler(known, compute.NewGoogleComputeModel(known)), nil case cluster.CloudDigitalOcean: sdk, err := godoSdk.NewSdk() if err != nil { return nil, err } dr.Sdk = sdk return cloud.NewAtomicReconciler(known, droplet.NewDigitalOceanDropletModel(known)), nil case cluster.CloudAmazon: awsProfile := "" if runtimeParameters != nil { awsProfile = runtimeParameters.AwsProfile } sdk, err := awsSdkGo.NewSdk(known.ProviderConfig().Location, awsProfile) if err != nil { return nil, err } ar.Sdk = sdk return cloud.NewAtomicReconciler(known, awspub.NewAmazonPublicModel(known)), nil case cluster.CloudAzure: sdk, err := azureSDK.NewSdk() if err != nil { return nil, err } azr.Sdk = sdk return cloud.NewAtomicReconciler(known, azpub.NewAzurePublicModel(known)), nil case cluster.CloudOVH: sdk, err := openstackSdk.NewSdk(known.ProviderConfig().Location) if err != nil { return nil, err } osr.Sdk = sdk return cloud.NewAtomicReconciler(known, osovh.NewOvhPublicModel(known)), nil case cluster.CloudPacket: sdk, err := packetSDK.NewSdk() if err != nil { return nil, err } packetr.Sdk = sdk return cloud.NewAtomicReconciler(known, packetpub.NewPacketPublicModel(known)), nil case cluster.CloudECS: sdk, err := openstackSdk.NewSdk(known.ProviderConfig().Location) if err != nil { return nil, err } osr.Sdk = sdk return cloud.NewAtomicReconciler(known, osecs.NewEcsPublicModel(known)), nil default: return nil, fmt.Errorf("Invalid cloud type: %s", known.ProviderConfig().Cloud) } }
[ "func", "GetReconciler", "(", "known", "*", "cluster", ".", "Cluster", ",", "runtimeParameters", "*", "RuntimeParameters", ")", "(", "reconciler", "cloud", ".", "Reconciler", ",", "err", "error", ")", "{", "switch", "known", ".", "ProviderConfig", "(", ")", ".", "Cloud", "{", "case", "cluster", ".", "CloudGoogle", ":", "sdk", ",", "err", ":=", "googleSDK", ".", "NewSdk", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "gr", ".", "Sdk", "=", "sdk", "\n", "return", "cloud", ".", "NewAtomicReconciler", "(", "known", ",", "compute", ".", "NewGoogleComputeModel", "(", "known", ")", ")", ",", "nil", "\n", "case", "cluster", ".", "CloudDigitalOcean", ":", "sdk", ",", "err", ":=", "godoSdk", ".", "NewSdk", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "dr", ".", "Sdk", "=", "sdk", "\n", "return", "cloud", ".", "NewAtomicReconciler", "(", "known", ",", "droplet", ".", "NewDigitalOceanDropletModel", "(", "known", ")", ")", ",", "nil", "\n", "case", "cluster", ".", "CloudAmazon", ":", "awsProfile", ":=", "\"\"", "\n", "if", "runtimeParameters", "!=", "nil", "{", "awsProfile", "=", "runtimeParameters", ".", "AwsProfile", "\n", "}", "\n", "sdk", ",", "err", ":=", "awsSdkGo", ".", "NewSdk", "(", "known", ".", "ProviderConfig", "(", ")", ".", "Location", ",", "awsProfile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ar", ".", "Sdk", "=", "sdk", "\n", "return", "cloud", ".", "NewAtomicReconciler", "(", "known", ",", "awspub", ".", "NewAmazonPublicModel", "(", "known", ")", ")", ",", "nil", "\n", "case", "cluster", ".", "CloudAzure", ":", "sdk", ",", "err", ":=", "azureSDK", ".", "NewSdk", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "azr", ".", "Sdk", "=", "sdk", "\n", "return", "cloud", ".", "NewAtomicReconciler", "(", "known", ",", "azpub", ".", "NewAzurePublicModel", "(", "known", ")", ")", ",", "nil", "\n", "case", "cluster", ".", "CloudOVH", ":", "sdk", ",", "err", ":=", "openstackSdk", ".", "NewSdk", "(", "known", ".", "ProviderConfig", "(", ")", ".", "Location", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "osr", ".", "Sdk", "=", "sdk", "\n", "return", "cloud", ".", "NewAtomicReconciler", "(", "known", ",", "osovh", ".", "NewOvhPublicModel", "(", "known", ")", ")", ",", "nil", "\n", "case", "cluster", ".", "CloudPacket", ":", "sdk", ",", "err", ":=", "packetSDK", ".", "NewSdk", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "packetr", ".", "Sdk", "=", "sdk", "\n", "return", "cloud", ".", "NewAtomicReconciler", "(", "known", ",", "packetpub", ".", "NewPacketPublicModel", "(", "known", ")", ")", ",", "nil", "\n", "case", "cluster", ".", "CloudECS", ":", "sdk", ",", "err", ":=", "openstackSdk", ".", "NewSdk", "(", "known", ".", "ProviderConfig", "(", ")", ".", "Location", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "osr", ".", "Sdk", "=", "sdk", "\n", "return", "cloud", ".", "NewAtomicReconciler", "(", "known", ",", "osecs", ".", "NewEcsPublicModel", "(", "known", ")", ")", ",", "nil", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"Invalid cloud type: %s\"", ",", "known", ".", "ProviderConfig", "(", ")", ".", "Cloud", ")", "\n", "}", "\n", "}" ]
// GetReconciler gets the correct Reconciler for the cloud provider currenty used.
[ "GetReconciler", "gets", "the", "correct", "Reconciler", "for", "the", "cloud", "provider", "currenty", "used", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/reconciler.go#L51-L109
test
kubicorn/kubicorn
pkg/version/version.go
GetVersion
func GetVersion() *Version { return &Version{ Version: KubicornVersion, GitCommit: GitSha, BuildDate: time.Now().UTC().String(), GoVersion: runtime.Version(), GOOS: runtime.GOOS, GOArch: runtime.GOARCH, } }
go
func GetVersion() *Version { return &Version{ Version: KubicornVersion, GitCommit: GitSha, BuildDate: time.Now().UTC().String(), GoVersion: runtime.Version(), GOOS: runtime.GOOS, GOArch: runtime.GOARCH, } }
[ "func", "GetVersion", "(", ")", "*", "Version", "{", "return", "&", "Version", "{", "Version", ":", "KubicornVersion", ",", "GitCommit", ":", "GitSha", ",", "BuildDate", ":", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "String", "(", ")", ",", "GoVersion", ":", "runtime", ".", "Version", "(", ")", ",", "GOOS", ":", "runtime", ".", "GOOS", ",", "GOArch", ":", "runtime", ".", "GOARCH", ",", "}", "\n", "}" ]
// GetVersion returns Kubicorn version.
[ "GetVersion", "returns", "Kubicorn", "version", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/version/version.go#L48-L57
test
kubicorn/kubicorn
pkg/version/version.go
GetVersionJSON
func GetVersionJSON() string { verBytes, err := json.Marshal(GetVersion()) if err != nil { logger.Critical("Unable to marshal version struct: %v", err) } return string(verBytes) }
go
func GetVersionJSON() string { verBytes, err := json.Marshal(GetVersion()) if err != nil { logger.Critical("Unable to marshal version struct: %v", err) } return string(verBytes) }
[ "func", "GetVersionJSON", "(", ")", "string", "{", "verBytes", ",", "err", ":=", "json", ".", "Marshal", "(", "GetVersion", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "\"Unable to marshal version struct: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "string", "(", "verBytes", ")", "\n", "}" ]
// GetVersionJSON returns Kubicorn version in JSON format.
[ "GetVersionJSON", "returns", "Kubicorn", "version", "in", "JSON", "format", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/version/version.go#L60-L66
test
kubicorn/kubicorn
cloud/azure/public/resources/resourcegroup.go
Actual
func (r *ResourceGroup) Actual(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("resourcegroup.Actual") newResource := &ResourceGroup{ Shared: Shared{ Name: r.Name, Tags: r.Tags, Identifier: immutable.ProviderConfig().GroupIdentifier, }, Location: r.Location, } if r.Identifier != "" { group, err := Sdk.ResourceGroup.Get(immutable.Name) if err != nil { return nil, nil, err } newResource.Location = *group.Location newResource.Name = *group.Name newResource.Identifier = *group.ID } newCluster := r.immutableRender(newResource, immutable) return newCluster, newResource, nil }
go
func (r *ResourceGroup) Actual(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("resourcegroup.Actual") newResource := &ResourceGroup{ Shared: Shared{ Name: r.Name, Tags: r.Tags, Identifier: immutable.ProviderConfig().GroupIdentifier, }, Location: r.Location, } if r.Identifier != "" { group, err := Sdk.ResourceGroup.Get(immutable.Name) if err != nil { return nil, nil, err } newResource.Location = *group.Location newResource.Name = *group.Name newResource.Identifier = *group.ID } newCluster := r.immutableRender(newResource, immutable) return newCluster, newResource, nil }
[ "func", "(", "r", "*", "ResourceGroup", ")", "Actual", "(", "immutable", "*", "cluster", ".", "Cluster", ")", "(", "*", "cluster", ".", "Cluster", ",", "cloud", ".", "Resource", ",", "error", ")", "{", "logger", ".", "Debug", "(", "\"resourcegroup.Actual\"", ")", "\n", "newResource", ":=", "&", "ResourceGroup", "{", "Shared", ":", "Shared", "{", "Name", ":", "r", ".", "Name", ",", "Tags", ":", "r", ".", "Tags", ",", "Identifier", ":", "immutable", ".", "ProviderConfig", "(", ")", ".", "GroupIdentifier", ",", "}", ",", "Location", ":", "r", ".", "Location", ",", "}", "\n", "if", "r", ".", "Identifier", "!=", "\"\"", "{", "group", ",", "err", ":=", "Sdk", ".", "ResourceGroup", ".", "Get", "(", "immutable", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "newResource", ".", "Location", "=", "*", "group", ".", "Location", "\n", "newResource", ".", "Name", "=", "*", "group", ".", "Name", "\n", "newResource", ".", "Identifier", "=", "*", "group", ".", "ID", "\n", "}", "\n", "newCluster", ":=", "r", ".", "immutableRender", "(", "newResource", ",", "immutable", ")", "\n", "return", "newCluster", ",", "newResource", ",", "nil", "\n", "}" ]
// Actual returns the actual resource group in Azure if it exists.
[ "Actual", "returns", "the", "actual", "resource", "group", "in", "Azure", "if", "it", "exists", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/azure/public/resources/resourcegroup.go#L35-L58
test
kubicorn/kubicorn
cloud/azure/public/resources/resourcegroup.go
Expected
func (r *ResourceGroup) Expected(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("resourcegroup.Expected") newResource := &ResourceGroup{ Shared: Shared{ Name: immutable.Name, Tags: r.Tags, Identifier: immutable.ProviderConfig().GroupIdentifier, }, Location: immutable.ProviderConfig().Location, } newCluster := r.immutableRender(newResource, immutable) return newCluster, newResource, nil }
go
func (r *ResourceGroup) Expected(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("resourcegroup.Expected") newResource := &ResourceGroup{ Shared: Shared{ Name: immutable.Name, Tags: r.Tags, Identifier: immutable.ProviderConfig().GroupIdentifier, }, Location: immutable.ProviderConfig().Location, } newCluster := r.immutableRender(newResource, immutable) return newCluster, newResource, nil }
[ "func", "(", "r", "*", "ResourceGroup", ")", "Expected", "(", "immutable", "*", "cluster", ".", "Cluster", ")", "(", "*", "cluster", ".", "Cluster", ",", "cloud", ".", "Resource", ",", "error", ")", "{", "logger", ".", "Debug", "(", "\"resourcegroup.Expected\"", ")", "\n", "newResource", ":=", "&", "ResourceGroup", "{", "Shared", ":", "Shared", "{", "Name", ":", "immutable", ".", "Name", ",", "Tags", ":", "r", ".", "Tags", ",", "Identifier", ":", "immutable", ".", "ProviderConfig", "(", ")", ".", "GroupIdentifier", ",", "}", ",", "Location", ":", "immutable", ".", "ProviderConfig", "(", ")", ".", "Location", ",", "}", "\n", "newCluster", ":=", "r", ".", "immutableRender", "(", "newResource", ",", "immutable", ")", "\n", "return", "newCluster", ",", "newResource", ",", "nil", "\n", "}" ]
// Expected will return the expected resource group as it would be defined in Azure
[ "Expected", "will", "return", "the", "expected", "resource", "group", "as", "it", "would", "be", "defined", "in", "Azure" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/azure/public/resources/resourcegroup.go#L61-L73
test
kubicorn/kubicorn
cmd/create.go
CreateCmd
func CreateCmd() *cobra.Command { var co = &cli.CreateOptions{} var createCmd = &cobra.Command{ Use: "create [NAME] [-p|--profile PROFILENAME] [-c|--cloudid CLOUDID]", Short: "Create a Kubicorn API model from a profile", Long: `Use this command to create a Kubicorn API model in a defined state store. This command will create a cluster API model as a YAML manifest in a state store. Once the API model has been created, a user can optionally change the model to their liking. After a model is defined and configured properly, the user can then apply the model.`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: co.Name = viper.GetString(keyKubicornName) if co.Name == "" { co.Name = namer.RandomName() } case 1: co.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := RunCreate(co); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := createCmd.Flags() bindCommonStateStoreFlags(&co.StateStoreOptions, fs) bindCommonAwsFlags(&co.AwsOptions, fs) fs.StringVarP(&co.Profile, keyProfile, "p", viper.GetString(keyProfile), descProfile) fs.StringVarP(&co.CloudID, keyCloudID, "c", viper.GetString(keyCloudID), descCloudID) fs.StringVar(&co.KubeConfigLocalFile, keyKubeConfigLocalFile, viper.GetString(keyKubeConfigLocalFile), descKubeConfigLocalFile) fs.StringArrayVarP(&co.Set, keySet, "C", viper.GetStringSlice(keySet), descSet) fs.StringArrayVarP(&co.MasterSet, keyMasterSet, "M", viper.GetStringSlice(keyMasterSet), descMasterSet) fs.StringArrayVarP(&co.NodeSet, keyNodeSet, "N", viper.GetStringSlice(keyNodeSet), descNodeSet) fs.StringVarP(&co.GitRemote, keyGitConfig, "g", viper.GetString(keyGitConfig), descGitConfig) fs.StringArrayVar(&co.AwsOptions.PolicyAttachments, keyPolicyAttachments, co.AwsOptions.PolicyAttachments, descPolicyAttachments) flagApplyAnnotations(createCmd, "profile", "__kubicorn_parse_profiles") flagApplyAnnotations(createCmd, "cloudid", "__kubicorn_parse_cloudid") createCmd.SetUsageTemplate(cli.UsageTemplate) return createCmd }
go
func CreateCmd() *cobra.Command { var co = &cli.CreateOptions{} var createCmd = &cobra.Command{ Use: "create [NAME] [-p|--profile PROFILENAME] [-c|--cloudid CLOUDID]", Short: "Create a Kubicorn API model from a profile", Long: `Use this command to create a Kubicorn API model in a defined state store. This command will create a cluster API model as a YAML manifest in a state store. Once the API model has been created, a user can optionally change the model to their liking. After a model is defined and configured properly, the user can then apply the model.`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: co.Name = viper.GetString(keyKubicornName) if co.Name == "" { co.Name = namer.RandomName() } case 1: co.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := RunCreate(co); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := createCmd.Flags() bindCommonStateStoreFlags(&co.StateStoreOptions, fs) bindCommonAwsFlags(&co.AwsOptions, fs) fs.StringVarP(&co.Profile, keyProfile, "p", viper.GetString(keyProfile), descProfile) fs.StringVarP(&co.CloudID, keyCloudID, "c", viper.GetString(keyCloudID), descCloudID) fs.StringVar(&co.KubeConfigLocalFile, keyKubeConfigLocalFile, viper.GetString(keyKubeConfigLocalFile), descKubeConfigLocalFile) fs.StringArrayVarP(&co.Set, keySet, "C", viper.GetStringSlice(keySet), descSet) fs.StringArrayVarP(&co.MasterSet, keyMasterSet, "M", viper.GetStringSlice(keyMasterSet), descMasterSet) fs.StringArrayVarP(&co.NodeSet, keyNodeSet, "N", viper.GetStringSlice(keyNodeSet), descNodeSet) fs.StringVarP(&co.GitRemote, keyGitConfig, "g", viper.GetString(keyGitConfig), descGitConfig) fs.StringArrayVar(&co.AwsOptions.PolicyAttachments, keyPolicyAttachments, co.AwsOptions.PolicyAttachments, descPolicyAttachments) flagApplyAnnotations(createCmd, "profile", "__kubicorn_parse_profiles") flagApplyAnnotations(createCmd, "cloudid", "__kubicorn_parse_cloudid") createCmd.SetUsageTemplate(cli.UsageTemplate) return createCmd }
[ "func", "CreateCmd", "(", ")", "*", "cobra", ".", "Command", "{", "var", "co", "=", "&", "cli", ".", "CreateOptions", "{", "}", "\n", "var", "createCmd", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"create [NAME] [-p|--profile PROFILENAME] [-c|--cloudid CLOUDID]\"", ",", "Short", ":", "\"Create a Kubicorn API model from a profile\"", ",", "Long", ":", "`Use this command to create a Kubicorn API model in a defined state store.\tThis command will create a cluster API model as a YAML manifest in a state store.\tOnce the API model has been created, a user can optionally change the model to their liking.\tAfter a model is defined and configured properly, the user can then apply the model.`", ",", "Run", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "switch", "len", "(", "args", ")", "{", "case", "0", ":", "co", ".", "Name", "=", "viper", ".", "GetString", "(", "keyKubicornName", ")", "\n", "if", "co", ".", "Name", "==", "\"\"", "{", "co", ".", "Name", "=", "namer", ".", "RandomName", "(", ")", "\n", "}", "\n", "case", "1", ":", "co", ".", "Name", "=", "args", "[", "0", "]", "\n", "default", ":", "logger", ".", "Critical", "(", "\"Too many arguments.\"", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "if", "err", ":=", "RunCreate", "(", "co", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "err", ".", "Error", "(", ")", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}", ",", "}", "\n", "fs", ":=", "createCmd", ".", "Flags", "(", ")", "\n", "bindCommonStateStoreFlags", "(", "&", "co", ".", "StateStoreOptions", ",", "fs", ")", "\n", "bindCommonAwsFlags", "(", "&", "co", ".", "AwsOptions", ",", "fs", ")", "\n", "fs", ".", "StringVarP", "(", "&", "co", ".", "Profile", ",", "keyProfile", ",", "\"p\"", ",", "viper", ".", "GetString", "(", "keyProfile", ")", ",", "descProfile", ")", "\n", "fs", ".", "StringVarP", "(", "&", "co", ".", "CloudID", ",", "keyCloudID", ",", "\"c\"", ",", "viper", ".", "GetString", "(", "keyCloudID", ")", ",", "descCloudID", ")", "\n", "fs", ".", "StringVar", "(", "&", "co", ".", "KubeConfigLocalFile", ",", "keyKubeConfigLocalFile", ",", "viper", ".", "GetString", "(", "keyKubeConfigLocalFile", ")", ",", "descKubeConfigLocalFile", ")", "\n", "fs", ".", "StringArrayVarP", "(", "&", "co", ".", "Set", ",", "keySet", ",", "\"C\"", ",", "viper", ".", "GetStringSlice", "(", "keySet", ")", ",", "descSet", ")", "\n", "fs", ".", "StringArrayVarP", "(", "&", "co", ".", "MasterSet", ",", "keyMasterSet", ",", "\"M\"", ",", "viper", ".", "GetStringSlice", "(", "keyMasterSet", ")", ",", "descMasterSet", ")", "\n", "fs", ".", "StringArrayVarP", "(", "&", "co", ".", "NodeSet", ",", "keyNodeSet", ",", "\"N\"", ",", "viper", ".", "GetStringSlice", "(", "keyNodeSet", ")", ",", "descNodeSet", ")", "\n", "fs", ".", "StringVarP", "(", "&", "co", ".", "GitRemote", ",", "keyGitConfig", ",", "\"g\"", ",", "viper", ".", "GetString", "(", "keyGitConfig", ")", ",", "descGitConfig", ")", "\n", "fs", ".", "StringArrayVar", "(", "&", "co", ".", "AwsOptions", ".", "PolicyAttachments", ",", "keyPolicyAttachments", ",", "co", ".", "AwsOptions", ".", "PolicyAttachments", ",", "descPolicyAttachments", ")", "\n", "flagApplyAnnotations", "(", "createCmd", ",", "\"profile\"", ",", "\"__kubicorn_parse_profiles\"", ")", "\n", "flagApplyAnnotations", "(", "createCmd", ",", "\"cloudid\"", ",", "\"__kubicorn_parse_cloudid\"", ")", "\n", "createCmd", ".", "SetUsageTemplate", "(", "cli", ".", "UsageTemplate", ")", "\n", "return", "createCmd", "\n", "}" ]
// CreateCmd represents create command
[ "CreateCmd", "represents", "create", "command" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/create.go#L35-L87
test
kubicorn/kubicorn
profiles/azure/ubuntu.go
NewUbuntuCluster
func NewUbuntuCluster(name string) *cluster.Cluster { controlPlaneProviderConfig := &cluster.ControlPlaneProviderConfig{ Cloud: cluster.CloudAzure, Location: "eastus", SSH: &cluster.SSH{ PublicKeyPath: "~/.ssh/id_rsa.pub", User: "root", }, KubernetesAPI: &cluster.KubernetesAPI{ Port: "443", }, Values: &cluster.Values{ ItemMap: map[string]string{ "INJECTEDTOKEN": kubeadm.GetRandomToken(), }, }, } machineSetsProviderConfigs := []*cluster.MachineProviderConfig{ { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeMaster, Name: fmt.Sprintf("%s-master", name), MaxCount: 1, Image: "UbuntuServer", Size: "Standard_DS3_v2 ", BootstrapScripts: []string{}, Firewalls: []*cluster.Firewall{ { Name: fmt.Sprintf("%s-master", name), IngressRules: []*cluster.IngressRule{ { IngressToPort: "22", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressToPort: "443", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressToPort: "1194", IngressSource: "0.0.0.0/0", IngressProtocol: "udp", }, }, EgressRules: []*cluster.EgressRule{ { EgressToPort: "all", // By default all egress from VM EgressDestination: "0.0.0.0/0", EgressProtocol: "tcp", }, { EgressToPort: "all", // By default all egress from VM EgressDestination: "0.0.0.0/0", EgressProtocol: "udp", }, }, }, }, }, }, { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeNode, Name: fmt.Sprintf("%s-node", name), MaxCount: 1, Image: "UbuntuServer", Size: "Standard_DS3_v2 ", BootstrapScripts: []string{}, Firewalls: []*cluster.Firewall{ { Name: fmt.Sprintf("%s-node", name), IngressRules: []*cluster.IngressRule{ { IngressToPort: "22", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressToPort: "1194", IngressSource: "0.0.0.0/0", IngressProtocol: "udp", }, }, EgressRules: []*cluster.EgressRule{ { EgressToPort: "all", // By default all egress from VM EgressDestination: "0.0.0.0/0", EgressProtocol: "tcp", }, { EgressToPort: "all", // By default all egress from VM EgressDestination: "0.0.0.0/0", EgressProtocol: "udp", }, }, }, }, }, }, } c := cluster.NewCluster(name) c.SetProviderConfig(controlPlaneProviderConfig) c.NewMachineSetsFromProviderConfigs(machineSetsProviderConfigs) return c }
go
func NewUbuntuCluster(name string) *cluster.Cluster { controlPlaneProviderConfig := &cluster.ControlPlaneProviderConfig{ Cloud: cluster.CloudAzure, Location: "eastus", SSH: &cluster.SSH{ PublicKeyPath: "~/.ssh/id_rsa.pub", User: "root", }, KubernetesAPI: &cluster.KubernetesAPI{ Port: "443", }, Values: &cluster.Values{ ItemMap: map[string]string{ "INJECTEDTOKEN": kubeadm.GetRandomToken(), }, }, } machineSetsProviderConfigs := []*cluster.MachineProviderConfig{ { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeMaster, Name: fmt.Sprintf("%s-master", name), MaxCount: 1, Image: "UbuntuServer", Size: "Standard_DS3_v2 ", BootstrapScripts: []string{}, Firewalls: []*cluster.Firewall{ { Name: fmt.Sprintf("%s-master", name), IngressRules: []*cluster.IngressRule{ { IngressToPort: "22", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressToPort: "443", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressToPort: "1194", IngressSource: "0.0.0.0/0", IngressProtocol: "udp", }, }, EgressRules: []*cluster.EgressRule{ { EgressToPort: "all", // By default all egress from VM EgressDestination: "0.0.0.0/0", EgressProtocol: "tcp", }, { EgressToPort: "all", // By default all egress from VM EgressDestination: "0.0.0.0/0", EgressProtocol: "udp", }, }, }, }, }, }, { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeNode, Name: fmt.Sprintf("%s-node", name), MaxCount: 1, Image: "UbuntuServer", Size: "Standard_DS3_v2 ", BootstrapScripts: []string{}, Firewalls: []*cluster.Firewall{ { Name: fmt.Sprintf("%s-node", name), IngressRules: []*cluster.IngressRule{ { IngressToPort: "22", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressToPort: "1194", IngressSource: "0.0.0.0/0", IngressProtocol: "udp", }, }, EgressRules: []*cluster.EgressRule{ { EgressToPort: "all", // By default all egress from VM EgressDestination: "0.0.0.0/0", EgressProtocol: "tcp", }, { EgressToPort: "all", // By default all egress from VM EgressDestination: "0.0.0.0/0", EgressProtocol: "udp", }, }, }, }, }, }, } c := cluster.NewCluster(name) c.SetProviderConfig(controlPlaneProviderConfig) c.NewMachineSetsFromProviderConfigs(machineSetsProviderConfigs) return c }
[ "func", "NewUbuntuCluster", "(", "name", "string", ")", "*", "cluster", ".", "Cluster", "{", "controlPlaneProviderConfig", ":=", "&", "cluster", ".", "ControlPlaneProviderConfig", "{", "Cloud", ":", "cluster", ".", "CloudAzure", ",", "Location", ":", "\"eastus\"", ",", "SSH", ":", "&", "cluster", ".", "SSH", "{", "PublicKeyPath", ":", "\"~/.ssh/id_rsa.pub\"", ",", "User", ":", "\"root\"", ",", "}", ",", "KubernetesAPI", ":", "&", "cluster", ".", "KubernetesAPI", "{", "Port", ":", "\"443\"", ",", "}", ",", "Values", ":", "&", "cluster", ".", "Values", "{", "ItemMap", ":", "map", "[", "string", "]", "string", "{", "\"INJECTEDTOKEN\"", ":", "kubeadm", ".", "GetRandomToken", "(", ")", ",", "}", ",", "}", ",", "}", "\n", "machineSetsProviderConfigs", ":=", "[", "]", "*", "cluster", ".", "MachineProviderConfig", "{", "{", "ServerPool", ":", "&", "cluster", ".", "ServerPool", "{", "Type", ":", "cluster", ".", "ServerPoolTypeMaster", ",", "Name", ":", "fmt", ".", "Sprintf", "(", "\"%s-master\"", ",", "name", ")", ",", "MaxCount", ":", "1", ",", "Image", ":", "\"UbuntuServer\"", ",", "Size", ":", "\"Standard_DS3_v2 \"", ",", "BootstrapScripts", ":", "[", "]", "string", "{", "}", ",", "Firewalls", ":", "[", "]", "*", "cluster", ".", "Firewall", "{", "{", "Name", ":", "fmt", ".", "Sprintf", "(", "\"%s-master\"", ",", "name", ")", ",", "IngressRules", ":", "[", "]", "*", "cluster", ".", "IngressRule", "{", "{", "IngressToPort", ":", "\"22\"", ",", "IngressSource", ":", "\"0.0.0.0/0\"", ",", "IngressProtocol", ":", "\"tcp\"", ",", "}", ",", "{", "IngressToPort", ":", "\"443\"", ",", "IngressSource", ":", "\"0.0.0.0/0\"", ",", "IngressProtocol", ":", "\"tcp\"", ",", "}", ",", "{", "IngressToPort", ":", "\"1194\"", ",", "IngressSource", ":", "\"0.0.0.0/0\"", ",", "IngressProtocol", ":", "\"udp\"", ",", "}", ",", "}", ",", "EgressRules", ":", "[", "]", "*", "cluster", ".", "EgressRule", "{", "{", "EgressToPort", ":", "\"all\"", ",", "EgressDestination", ":", "\"0.0.0.0/0\"", ",", "EgressProtocol", ":", "\"tcp\"", ",", "}", ",", "{", "EgressToPort", ":", "\"all\"", ",", "EgressDestination", ":", "\"0.0.0.0/0\"", ",", "EgressProtocol", ":", "\"udp\"", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "{", "ServerPool", ":", "&", "cluster", ".", "ServerPool", "{", "Type", ":", "cluster", ".", "ServerPoolTypeNode", ",", "Name", ":", "fmt", ".", "Sprintf", "(", "\"%s-node\"", ",", "name", ")", ",", "MaxCount", ":", "1", ",", "Image", ":", "\"UbuntuServer\"", ",", "Size", ":", "\"Standard_DS3_v2 \"", ",", "BootstrapScripts", ":", "[", "]", "string", "{", "}", ",", "Firewalls", ":", "[", "]", "*", "cluster", ".", "Firewall", "{", "{", "Name", ":", "fmt", ".", "Sprintf", "(", "\"%s-node\"", ",", "name", ")", ",", "IngressRules", ":", "[", "]", "*", "cluster", ".", "IngressRule", "{", "{", "IngressToPort", ":", "\"22\"", ",", "IngressSource", ":", "\"0.0.0.0/0\"", ",", "IngressProtocol", ":", "\"tcp\"", ",", "}", ",", "{", "IngressToPort", ":", "\"1194\"", ",", "IngressSource", ":", "\"0.0.0.0/0\"", ",", "IngressProtocol", ":", "\"udp\"", ",", "}", ",", "}", ",", "EgressRules", ":", "[", "]", "*", "cluster", ".", "EgressRule", "{", "{", "EgressToPort", ":", "\"all\"", ",", "EgressDestination", ":", "\"0.0.0.0/0\"", ",", "EgressProtocol", ":", "\"tcp\"", ",", "}", ",", "{", "EgressToPort", ":", "\"all\"", ",", "EgressDestination", ":", "\"0.0.0.0/0\"", ",", "EgressProtocol", ":", "\"udp\"", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", "\n", "c", ":=", "cluster", ".", "NewCluster", "(", "name", ")", "\n", "c", ".", "SetProviderConfig", "(", "controlPlaneProviderConfig", ")", "\n", "c", ".", "NewMachineSetsFromProviderConfigs", "(", "machineSetsProviderConfigs", ")", "\n", "return", "c", "\n", "}" ]
// NewUbuntuCluster creates a basic Azure cluster profile, to bootstrap Kubernetes.
[ "NewUbuntuCluster", "creates", "a", "basic", "Azure", "cluster", "profile", "to", "bootstrap", "Kubernetes", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/profiles/azure/ubuntu.go#L25-L132
test
kubicorn/kubicorn
apis/cluster/cluster.go
ProviderConfig
func (c *Cluster) ProviderConfig() *ControlPlaneProviderConfig { //providerConfig providerConfig raw := c.ClusterAPI.Spec.ProviderConfig providerConfig := &ControlPlaneProviderConfig{} err := json.Unmarshal([]byte(raw), providerConfig) if err != nil { logger.Critical("Unable to unmarshal provider config: %v", err) } return providerConfig }
go
func (c *Cluster) ProviderConfig() *ControlPlaneProviderConfig { //providerConfig providerConfig raw := c.ClusterAPI.Spec.ProviderConfig providerConfig := &ControlPlaneProviderConfig{} err := json.Unmarshal([]byte(raw), providerConfig) if err != nil { logger.Critical("Unable to unmarshal provider config: %v", err) } return providerConfig }
[ "func", "(", "c", "*", "Cluster", ")", "ProviderConfig", "(", ")", "*", "ControlPlaneProviderConfig", "{", "raw", ":=", "c", ".", "ClusterAPI", ".", "Spec", ".", "ProviderConfig", "\n", "providerConfig", ":=", "&", "ControlPlaneProviderConfig", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "raw", ")", ",", "providerConfig", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "\"Unable to unmarshal provider config: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "providerConfig", "\n", "}" ]
// ProviderConfig is a convenience method that will attempt // to return a ControlPlaneProviderConfig for a cluster. // This is useful for managing the legacy API in a clean way. // This will ignore errors from json.Unmarshal and will simply // return an empty config.
[ "ProviderConfig", "is", "a", "convenience", "method", "that", "will", "attempt", "to", "return", "a", "ControlPlaneProviderConfig", "for", "a", "cluster", ".", "This", "is", "useful", "for", "managing", "the", "legacy", "API", "in", "a", "clean", "way", ".", "This", "will", "ignore", "errors", "from", "json", ".", "Unmarshal", "and", "will", "simply", "return", "an", "empty", "config", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/apis/cluster/cluster.go#L76-L85
test
kubicorn/kubicorn
apis/cluster/cluster.go
SetProviderConfig
func (c *Cluster) SetProviderConfig(config *ControlPlaneProviderConfig) error { bytes, err := json.Marshal(config) if err != nil { logger.Critical("Unable to marshal provider config: %v", err) return err } str := string(bytes) c.ClusterAPI.Spec.ProviderConfig = str return nil }
go
func (c *Cluster) SetProviderConfig(config *ControlPlaneProviderConfig) error { bytes, err := json.Marshal(config) if err != nil { logger.Critical("Unable to marshal provider config: %v", err) return err } str := string(bytes) c.ClusterAPI.Spec.ProviderConfig = str return nil }
[ "func", "(", "c", "*", "Cluster", ")", "SetProviderConfig", "(", "config", "*", "ControlPlaneProviderConfig", ")", "error", "{", "bytes", ",", "err", ":=", "json", ".", "Marshal", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "\"Unable to marshal provider config: %v\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "str", ":=", "string", "(", "bytes", ")", "\n", "c", ".", "ClusterAPI", ".", "Spec", ".", "ProviderConfig", "=", "str", "\n", "return", "nil", "\n", "}" ]
// SetProviderConfig is a convenience method that will attempt // to set a provider config on a particular cluster. Just like // it's counterpart ProviderConfig this makes working with the legacy API much easier.
[ "SetProviderConfig", "is", "a", "convenience", "method", "that", "will", "attempt", "to", "set", "a", "provider", "config", "on", "a", "particular", "cluster", ".", "Just", "like", "it", "s", "counterpart", "ProviderConfig", "this", "makes", "working", "with", "the", "legacy", "API", "much", "easier", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/apis/cluster/cluster.go#L90-L99
test
kubicorn/kubicorn
apis/cluster/cluster.go
MachineProviderConfigs
func (c *Cluster) MachineProviderConfigs() []*MachineProviderConfig { var providerConfigs []*MachineProviderConfig for _, machineSet := range c.MachineSets { raw := machineSet.Spec.Template.Spec.ProviderConfig providerConfig := &MachineProviderConfig{} err := json.Unmarshal([]byte(raw), providerConfig) if err != nil { logger.Critical("Unable to unmarshal provider config: %v", err) } providerConfigs = append(providerConfigs, providerConfig) } return providerConfigs }
go
func (c *Cluster) MachineProviderConfigs() []*MachineProviderConfig { var providerConfigs []*MachineProviderConfig for _, machineSet := range c.MachineSets { raw := machineSet.Spec.Template.Spec.ProviderConfig providerConfig := &MachineProviderConfig{} err := json.Unmarshal([]byte(raw), providerConfig) if err != nil { logger.Critical("Unable to unmarshal provider config: %v", err) } providerConfigs = append(providerConfigs, providerConfig) } return providerConfigs }
[ "func", "(", "c", "*", "Cluster", ")", "MachineProviderConfigs", "(", ")", "[", "]", "*", "MachineProviderConfig", "{", "var", "providerConfigs", "[", "]", "*", "MachineProviderConfig", "\n", "for", "_", ",", "machineSet", ":=", "range", "c", ".", "MachineSets", "{", "raw", ":=", "machineSet", ".", "Spec", ".", "Template", ".", "Spec", ".", "ProviderConfig", "\n", "providerConfig", ":=", "&", "MachineProviderConfig", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "raw", ")", ",", "providerConfig", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "\"Unable to unmarshal provider config: %v\"", ",", "err", ")", "\n", "}", "\n", "providerConfigs", "=", "append", "(", "providerConfigs", ",", "providerConfig", ")", "\n", "}", "\n", "return", "providerConfigs", "\n", "}" ]
// MachineProviderConfigs will return all MachineProviderConfigs for a cluster
[ "MachineProviderConfigs", "will", "return", "all", "MachineProviderConfigs", "for", "a", "cluster" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/apis/cluster/cluster.go#L102-L114
test
kubicorn/kubicorn
apis/cluster/cluster.go
SetMachineProviderConfigs
func (c *Cluster) SetMachineProviderConfigs(providerConfigs []*MachineProviderConfig) { for _, providerConfig := range providerConfigs { name := providerConfig.ServerPool.Name found := false for _, machineSet := range c.MachineSets { if machineSet.Name == name { //logger.Debug("Matched machine set to provider config: %s", name) bytes, err := json.Marshal(providerConfig) if err != nil { logger.Critical("unable to marshal machine provider config: %v") continue } str := string(bytes) machineSet.Spec.Template.Spec.ProviderConfig = str found = true } } // TODO // @kris-nova // Right now if we have a machine provider config and we can't match it // we log a warning and move on. We might want to change this to create // the machineSet moving forward.. if !found { logger.Warning("Unable to match provider config to machine set: %s", name) } } }
go
func (c *Cluster) SetMachineProviderConfigs(providerConfigs []*MachineProviderConfig) { for _, providerConfig := range providerConfigs { name := providerConfig.ServerPool.Name found := false for _, machineSet := range c.MachineSets { if machineSet.Name == name { //logger.Debug("Matched machine set to provider config: %s", name) bytes, err := json.Marshal(providerConfig) if err != nil { logger.Critical("unable to marshal machine provider config: %v") continue } str := string(bytes) machineSet.Spec.Template.Spec.ProviderConfig = str found = true } } // TODO // @kris-nova // Right now if we have a machine provider config and we can't match it // we log a warning and move on. We might want to change this to create // the machineSet moving forward.. if !found { logger.Warning("Unable to match provider config to machine set: %s", name) } } }
[ "func", "(", "c", "*", "Cluster", ")", "SetMachineProviderConfigs", "(", "providerConfigs", "[", "]", "*", "MachineProviderConfig", ")", "{", "for", "_", ",", "providerConfig", ":=", "range", "providerConfigs", "{", "name", ":=", "providerConfig", ".", "ServerPool", ".", "Name", "\n", "found", ":=", "false", "\n", "for", "_", ",", "machineSet", ":=", "range", "c", ".", "MachineSets", "{", "if", "machineSet", ".", "Name", "==", "name", "{", "bytes", ",", "err", ":=", "json", ".", "Marshal", "(", "providerConfig", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "\"unable to marshal machine provider config: %v\"", ")", "\n", "continue", "\n", "}", "\n", "str", ":=", "string", "(", "bytes", ")", "\n", "machineSet", ".", "Spec", ".", "Template", ".", "Spec", ".", "ProviderConfig", "=", "str", "\n", "found", "=", "true", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "logger", ".", "Warning", "(", "\"Unable to match provider config to machine set: %s\"", ",", "name", ")", "\n", "}", "\n", "}", "\n", "}" ]
// SetMachineProviderConfig will attempt to match a provider config to a machine set // on the "Name" field. If a match cannot be made we warn and move on.
[ "SetMachineProviderConfig", "will", "attempt", "to", "match", "a", "provider", "config", "to", "a", "machine", "set", "on", "the", "Name", "field", ".", "If", "a", "match", "cannot", "be", "made", "we", "warn", "and", "move", "on", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/apis/cluster/cluster.go#L118-L147
test
kubicorn/kubicorn
apis/cluster/cluster.go
NewCluster
func NewCluster(name string) *Cluster { return &Cluster{ Name: name, ClusterAPI: &clusterv1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, Spec: clusterv1.ClusterSpec{}, }, ControlPlane: &clusterv1.MachineSet{}, } }
go
func NewCluster(name string) *Cluster { return &Cluster{ Name: name, ClusterAPI: &clusterv1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: name, }, Spec: clusterv1.ClusterSpec{}, }, ControlPlane: &clusterv1.MachineSet{}, } }
[ "func", "NewCluster", "(", "name", "string", ")", "*", "Cluster", "{", "return", "&", "Cluster", "{", "Name", ":", "name", ",", "ClusterAPI", ":", "&", "clusterv1", ".", "Cluster", "{", "ObjectMeta", ":", "metav1", ".", "ObjectMeta", "{", "Name", ":", "name", ",", "}", ",", "Spec", ":", "clusterv1", ".", "ClusterSpec", "{", "}", ",", "}", ",", "ControlPlane", ":", "&", "clusterv1", ".", "MachineSet", "{", "}", ",", "}", "\n", "}" ]
// NewCluster will initialize a new Cluster
[ "NewCluster", "will", "initialize", "a", "new", "Cluster" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/apis/cluster/cluster.go#L254-L265
test
kubicorn/kubicorn
cmd/deploycontroller.go
DeployControllerCmd
func DeployControllerCmd() *cobra.Command { var dco = &cli.DeployControllerOptions{} var deployControllerCmd = &cobra.Command{ Use: "deploycontroller <NAME>", Short: "Deploy a controller for a given cluster", Long: `Use this command to deploy a controller for a given cluster. As long as a controller is defined, this will create the deployment and the namespace.`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: dco.Name = viper.GetString(keyKubicornName) case 1: dco.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runDeployController(dco); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := deployControllerCmd.Flags() bindCommonStateStoreFlags(&dco.StateStoreOptions, fs) bindCommonAwsFlags(&dco.AwsOptions, fs) fs.StringVar(&dco.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) return deployControllerCmd }
go
func DeployControllerCmd() *cobra.Command { var dco = &cli.DeployControllerOptions{} var deployControllerCmd = &cobra.Command{ Use: "deploycontroller <NAME>", Short: "Deploy a controller for a given cluster", Long: `Use this command to deploy a controller for a given cluster. As long as a controller is defined, this will create the deployment and the namespace.`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: dco.Name = viper.GetString(keyKubicornName) case 1: dco.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runDeployController(dco); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := deployControllerCmd.Flags() bindCommonStateStoreFlags(&dco.StateStoreOptions, fs) bindCommonAwsFlags(&dco.AwsOptions, fs) fs.StringVar(&dco.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) return deployControllerCmd }
[ "func", "DeployControllerCmd", "(", ")", "*", "cobra", ".", "Command", "{", "var", "dco", "=", "&", "cli", ".", "DeployControllerOptions", "{", "}", "\n", "var", "deployControllerCmd", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"deploycontroller <NAME>\"", ",", "Short", ":", "\"Deploy a controller for a given cluster\"", ",", "Long", ":", "`Use this command to deploy a controller for a given cluster.As long as a controller is defined, this will create the deployment and the namespace.`", ",", "Run", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "switch", "len", "(", "args", ")", "{", "case", "0", ":", "dco", ".", "Name", "=", "viper", ".", "GetString", "(", "keyKubicornName", ")", "\n", "case", "1", ":", "dco", ".", "Name", "=", "args", "[", "0", "]", "\n", "default", ":", "logger", ".", "Critical", "(", "\"Too many arguments.\"", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "if", "err", ":=", "runDeployController", "(", "dco", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "err", ".", "Error", "(", ")", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}", ",", "}", "\n", "fs", ":=", "deployControllerCmd", ".", "Flags", "(", ")", "\n", "bindCommonStateStoreFlags", "(", "&", "dco", ".", "StateStoreOptions", ",", "fs", ")", "\n", "bindCommonAwsFlags", "(", "&", "dco", ".", "AwsOptions", ",", "fs", ")", "\n", "fs", ".", "StringVar", "(", "&", "dco", ".", "GitRemote", ",", "keyGitConfig", ",", "viper", ".", "GetString", "(", "keyGitConfig", ")", ",", "descGitConfig", ")", "\n", "return", "deployControllerCmd", "\n", "}" ]
// DeployControllerCmd represents the apply command
[ "DeployControllerCmd", "represents", "the", "apply", "command" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/deploycontroller.go#L31-L66
test
kubicorn/kubicorn
pkg/retry/retry.go
NewRetrier
func NewRetrier(retries, sleepSeconds int, retryable Retryable) *Retrier { return &Retrier{ retries: retries, sleepSeconds: sleepSeconds, retryable: retryable, } }
go
func NewRetrier(retries, sleepSeconds int, retryable Retryable) *Retrier { return &Retrier{ retries: retries, sleepSeconds: sleepSeconds, retryable: retryable, } }
[ "func", "NewRetrier", "(", "retries", ",", "sleepSeconds", "int", ",", "retryable", "Retryable", ")", "*", "Retrier", "{", "return", "&", "Retrier", "{", "retries", ":", "retries", ",", "sleepSeconds", ":", "sleepSeconds", ",", "retryable", ":", "retryable", ",", "}", "\n", "}" ]
// NewRetrier creates a new Retrier using given properties.
[ "NewRetrier", "creates", "a", "new", "Retrier", "using", "given", "properties", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/retry/retry.go#L40-L46
test
kubicorn/kubicorn
pkg/retry/retry.go
RunRetry
func (r *Retrier) RunRetry() error { // Start signal handler. sigHandler := signals.NewSignalHandler(10) go sigHandler.Register() finish := make(chan bool, 1) go func() { select { case <-finish: return case <-time.After(10 * time.Second): return default: for { if sigHandler.GetState() != 0 { logger.Critical("detected signal. retry failed.") os.Exit(1) } } } }() for i := 0; i < r.retries; i++ { err := r.retryable.Try() if err != nil { logger.Info("Retryable error: %v", err) time.Sleep(time.Duration(r.sleepSeconds) * time.Second) continue } finish <- true return nil } finish <- true return fmt.Errorf("unable to succeed at retry after %d attempts at %d seconds", r.retries, r.sleepSeconds) }
go
func (r *Retrier) RunRetry() error { // Start signal handler. sigHandler := signals.NewSignalHandler(10) go sigHandler.Register() finish := make(chan bool, 1) go func() { select { case <-finish: return case <-time.After(10 * time.Second): return default: for { if sigHandler.GetState() != 0 { logger.Critical("detected signal. retry failed.") os.Exit(1) } } } }() for i := 0; i < r.retries; i++ { err := r.retryable.Try() if err != nil { logger.Info("Retryable error: %v", err) time.Sleep(time.Duration(r.sleepSeconds) * time.Second) continue } finish <- true return nil } finish <- true return fmt.Errorf("unable to succeed at retry after %d attempts at %d seconds", r.retries, r.sleepSeconds) }
[ "func", "(", "r", "*", "Retrier", ")", "RunRetry", "(", ")", "error", "{", "sigHandler", ":=", "signals", ".", "NewSignalHandler", "(", "10", ")", "\n", "go", "sigHandler", ".", "Register", "(", ")", "\n", "finish", ":=", "make", "(", "chan", "bool", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "select", "{", "case", "<-", "finish", ":", "return", "\n", "case", "<-", "time", ".", "After", "(", "10", "*", "time", ".", "Second", ")", ":", "return", "\n", "default", ":", "for", "{", "if", "sigHandler", ".", "GetState", "(", ")", "!=", "0", "{", "logger", ".", "Critical", "(", "\"detected signal. retry failed.\"", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "r", ".", "retries", ";", "i", "++", "{", "err", ":=", "r", ".", "retryable", ".", "Try", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Info", "(", "\"Retryable error: %v\"", ",", "err", ")", "\n", "time", ".", "Sleep", "(", "time", ".", "Duration", "(", "r", ".", "sleepSeconds", ")", "*", "time", ".", "Second", ")", "\n", "continue", "\n", "}", "\n", "finish", "<-", "true", "\n", "return", "nil", "\n", "}", "\n", "finish", "<-", "true", "\n", "return", "fmt", ".", "Errorf", "(", "\"unable to succeed at retry after %d attempts at %d seconds\"", ",", "r", ".", "retries", ",", "r", ".", "sleepSeconds", ")", "\n", "}" ]
// RunRetry runs a retryable function.
[ "RunRetry", "runs", "a", "retryable", "function", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/retry/retry.go#L49-L84
test
kubicorn/kubicorn
pkg/rand/cryptorand.go
MustGenerateRandomBytes
func MustGenerateRandomBytes(length int) []byte { res, err := GenerateRandomBytes(length) if err != nil { panic("Could not generate random bytes") } return res }
go
func MustGenerateRandomBytes(length int) []byte { res, err := GenerateRandomBytes(length) if err != nil { panic("Could not generate random bytes") } return res }
[ "func", "MustGenerateRandomBytes", "(", "length", "int", ")", "[", "]", "byte", "{", "res", ",", "err", ":=", "GenerateRandomBytes", "(", "length", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"Could not generate random bytes\"", ")", "\n", "}", "\n", "return", "res", "\n", "}" ]
// MustGenerateRandomBytes generates random bytes or panics if it can't
[ "MustGenerateRandomBytes", "generates", "random", "bytes", "or", "panics", "if", "it", "can", "t" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/rand/cryptorand.go#L23-L31
test
kubicorn/kubicorn
cmd/explain.go
ExplainCmd
func ExplainCmd() *cobra.Command { var exo = &cli.ExplainOptions{} var cmd = &cobra.Command{ Use: "explain", Short: "Explain cluster", Long: `Output expected and actual state of the given cluster`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: exo.Name = viper.GetString(keyKubicornName) case 1: exo.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runExplain(exo); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := cmd.Flags() bindCommonStateStoreFlags(&exo.StateStoreOptions, fs) bindCommonAwsFlags(&exo.AwsOptions, fs) fs.StringVarP(&exo.Output, keyOutput, "o", viper.GetString(keyOutput), descOutput) fs.StringVar(&exo.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) return cmd }
go
func ExplainCmd() *cobra.Command { var exo = &cli.ExplainOptions{} var cmd = &cobra.Command{ Use: "explain", Short: "Explain cluster", Long: `Output expected and actual state of the given cluster`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: exo.Name = viper.GetString(keyKubicornName) case 1: exo.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runExplain(exo); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := cmd.Flags() bindCommonStateStoreFlags(&exo.StateStoreOptions, fs) bindCommonAwsFlags(&exo.AwsOptions, fs) fs.StringVarP(&exo.Output, keyOutput, "o", viper.GetString(keyOutput), descOutput) fs.StringVar(&exo.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) return cmd }
[ "func", "ExplainCmd", "(", ")", "*", "cobra", ".", "Command", "{", "var", "exo", "=", "&", "cli", ".", "ExplainOptions", "{", "}", "\n", "var", "cmd", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"explain\"", ",", "Short", ":", "\"Explain cluster\"", ",", "Long", ":", "`Output expected and actual state of the given cluster`", ",", "Run", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "switch", "len", "(", "args", ")", "{", "case", "0", ":", "exo", ".", "Name", "=", "viper", ".", "GetString", "(", "keyKubicornName", ")", "\n", "case", "1", ":", "exo", ".", "Name", "=", "args", "[", "0", "]", "\n", "default", ":", "logger", ".", "Critical", "(", "\"Too many arguments.\"", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "if", "err", ":=", "runExplain", "(", "exo", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "err", ".", "Error", "(", ")", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}", ",", "}", "\n", "fs", ":=", "cmd", ".", "Flags", "(", ")", "\n", "bindCommonStateStoreFlags", "(", "&", "exo", ".", "StateStoreOptions", ",", "fs", ")", "\n", "bindCommonAwsFlags", "(", "&", "exo", ".", "AwsOptions", ",", "fs", ")", "\n", "fs", ".", "StringVarP", "(", "&", "exo", ".", "Output", ",", "keyOutput", ",", "\"o\"", ",", "viper", ".", "GetString", "(", "keyOutput", ")", ",", "descOutput", ")", "\n", "fs", ".", "StringVar", "(", "&", "exo", ".", "GitRemote", ",", "keyGitConfig", ",", "viper", ".", "GetString", "(", "keyGitConfig", ")", ",", "descGitConfig", ")", "\n", "return", "cmd", "\n", "}" ]
// ExplainCmd represents the explain command
[ "ExplainCmd", "represents", "the", "explain", "command" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/explain.go#L39-L73
test
kubicorn/kubicorn
pkg/uuid/uuid.go
TimeOrderedUUID
func TimeOrderedUUID() string { unixTime := uint32(time.Now().UTC().Unix()) return fmt.Sprintf("%08x-%04x-%04x-%04x-%04x%08x", unixTime, rand.MustGenerateRandomBytes(2), rand.MustGenerateRandomBytes(2), rand.MustGenerateRandomBytes(2), rand.MustGenerateRandomBytes(2), rand.MustGenerateRandomBytes(4)) }
go
func TimeOrderedUUID() string { unixTime := uint32(time.Now().UTC().Unix()) return fmt.Sprintf("%08x-%04x-%04x-%04x-%04x%08x", unixTime, rand.MustGenerateRandomBytes(2), rand.MustGenerateRandomBytes(2), rand.MustGenerateRandomBytes(2), rand.MustGenerateRandomBytes(2), rand.MustGenerateRandomBytes(4)) }
[ "func", "TimeOrderedUUID", "(", ")", "string", "{", "unixTime", ":=", "uint32", "(", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ".", "Unix", "(", ")", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%08x-%04x-%04x-%04x-%04x%08x\"", ",", "unixTime", ",", "rand", ".", "MustGenerateRandomBytes", "(", "2", ")", ",", "rand", ".", "MustGenerateRandomBytes", "(", "2", ")", ",", "rand", ".", "MustGenerateRandomBytes", "(", "2", ")", ",", "rand", ".", "MustGenerateRandomBytes", "(", "2", ")", ",", "rand", ".", "MustGenerateRandomBytes", "(", "4", ")", ")", "\n", "}" ]
// TimeOrderedUUID generates a time ordered UUID. Top 32b are timestamp bottom 96b are random.
[ "TimeOrderedUUID", "generates", "a", "time", "ordered", "UUID", ".", "Top", "32b", "are", "timestamp", "bottom", "96b", "are", "random", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/uuid/uuid.go#L25-L34
test
kubicorn/kubicorn
cmd/getconfig.go
GetConfigCmd
func GetConfigCmd() *cobra.Command { var cro = &cli.GetConfigOptions{} var getConfigCmd = &cobra.Command{ Use: "getconfig <NAME>", Short: "Manage Kubernetes configuration", Long: `Use this command to pull a kubeconfig file from a cluster so you can use kubectl. This command will attempt to find a cluster, and append a local kubeconfig file with a kubeconfig `, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: cro.Name = viper.GetString(keyKubicornName) case 1: cro.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runGetConfig(cro); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := getConfigCmd.Flags() bindCommonStateStoreFlags(&cro.StateStoreOptions, fs) bindCommonAwsFlags(&cro.AwsOptions, fs) fs.StringVar(&cro.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) return getConfigCmd }
go
func GetConfigCmd() *cobra.Command { var cro = &cli.GetConfigOptions{} var getConfigCmd = &cobra.Command{ Use: "getconfig <NAME>", Short: "Manage Kubernetes configuration", Long: `Use this command to pull a kubeconfig file from a cluster so you can use kubectl. This command will attempt to find a cluster, and append a local kubeconfig file with a kubeconfig `, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: cro.Name = viper.GetString(keyKubicornName) case 1: cro.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runGetConfig(cro); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := getConfigCmd.Flags() bindCommonStateStoreFlags(&cro.StateStoreOptions, fs) bindCommonAwsFlags(&cro.AwsOptions, fs) fs.StringVar(&cro.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) return getConfigCmd }
[ "func", "GetConfigCmd", "(", ")", "*", "cobra", ".", "Command", "{", "var", "cro", "=", "&", "cli", ".", "GetConfigOptions", "{", "}", "\n", "var", "getConfigCmd", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"getconfig <NAME>\"", ",", "Short", ":", "\"Manage Kubernetes configuration\"", ",", "Long", ":", "`Use this command to pull a kubeconfig file from a cluster so you can use kubectl.\t\tThis command will attempt to find a cluster, and append a local kubeconfig file with a kubeconfig `", ",", "Run", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "switch", "len", "(", "args", ")", "{", "case", "0", ":", "cro", ".", "Name", "=", "viper", ".", "GetString", "(", "keyKubicornName", ")", "\n", "case", "1", ":", "cro", ".", "Name", "=", "args", "[", "0", "]", "\n", "default", ":", "logger", ".", "Critical", "(", "\"Too many arguments.\"", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "if", "err", ":=", "runGetConfig", "(", "cro", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "err", ".", "Error", "(", ")", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}", ",", "}", "\n", "fs", ":=", "getConfigCmd", ".", "Flags", "(", ")", "\n", "bindCommonStateStoreFlags", "(", "&", "cro", ".", "StateStoreOptions", ",", "fs", ")", "\n", "bindCommonAwsFlags", "(", "&", "cro", ".", "AwsOptions", ",", "fs", ")", "\n", "fs", ".", "StringVar", "(", "&", "cro", ".", "GitRemote", ",", "keyGitConfig", ",", "viper", ".", "GetString", "(", "keyGitConfig", ")", ",", "descGitConfig", ")", "\n", "return", "getConfigCmd", "\n", "}" ]
// GetConfigCmd represents the apply command
[ "GetConfigCmd", "represents", "the", "apply", "command" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/getconfig.go#L31-L66
test
kubicorn/kubicorn
pkg/task/task.go
RunAnnotated
func RunAnnotated(task Task, description string, symbol string, options ...interface{}) error { doneCh := make(chan bool) errCh := make(chan error) l := logger.Log t := DefaultTicker for _, o := range options { if value, ok := o.(logger.Logger); ok { l = value } else if value, ok := o.(*time.Ticker); ok { t = value } } go func() { errCh <- task() }() l(description) logActivity(symbol, l, t, doneCh) err := <-errCh doneCh <- true return err }
go
func RunAnnotated(task Task, description string, symbol string, options ...interface{}) error { doneCh := make(chan bool) errCh := make(chan error) l := logger.Log t := DefaultTicker for _, o := range options { if value, ok := o.(logger.Logger); ok { l = value } else if value, ok := o.(*time.Ticker); ok { t = value } } go func() { errCh <- task() }() l(description) logActivity(symbol, l, t, doneCh) err := <-errCh doneCh <- true return err }
[ "func", "RunAnnotated", "(", "task", "Task", ",", "description", "string", ",", "symbol", "string", ",", "options", "...", "interface", "{", "}", ")", "error", "{", "doneCh", ":=", "make", "(", "chan", "bool", ")", "\n", "errCh", ":=", "make", "(", "chan", "error", ")", "\n", "l", ":=", "logger", ".", "Log", "\n", "t", ":=", "DefaultTicker", "\n", "for", "_", ",", "o", ":=", "range", "options", "{", "if", "value", ",", "ok", ":=", "o", ".", "(", "logger", ".", "Logger", ")", ";", "ok", "{", "l", "=", "value", "\n", "}", "else", "if", "value", ",", "ok", ":=", "o", ".", "(", "*", "time", ".", "Ticker", ")", ";", "ok", "{", "t", "=", "value", "\n", "}", "\n", "}", "\n", "go", "func", "(", ")", "{", "errCh", "<-", "task", "(", ")", "\n", "}", "(", ")", "\n", "l", "(", "description", ")", "\n", "logActivity", "(", "symbol", ",", "l", ",", "t", ",", "doneCh", ")", "\n", "err", ":=", "<-", "errCh", "\n", "doneCh", "<-", "true", "\n", "return", "err", "\n", "}" ]
// RunAnnotated annotates a task with a description and a sequence of symbols indicating task activity until it terminates
[ "RunAnnotated", "annotates", "a", "task", "with", "a", "description", "and", "a", "sequence", "of", "symbols", "indicating", "task", "activity", "until", "it", "terminates" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/task/task.go#L30-L56
test
kubicorn/kubicorn
cmd/list.go
ListCmd
func ListCmd() *cobra.Command { var lo = &cli.ListOptions{} var cmd = &cobra.Command{ Use: "list", Short: "List available states", Long: `List the states available in the _state directory`, Run: func(cmd *cobra.Command, args []string) { if err := runList(lo); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := cmd.Flags() bindCommonStateStoreFlags(&lo.StateStoreOptions, fs) bindCommonAwsFlags(&lo.AwsOptions, fs) fs.BoolVarP(&noHeaders, keyNoHeaders, "n", viper.GetBool(keyNoHeaders), desNoHeaders) return cmd }
go
func ListCmd() *cobra.Command { var lo = &cli.ListOptions{} var cmd = &cobra.Command{ Use: "list", Short: "List available states", Long: `List the states available in the _state directory`, Run: func(cmd *cobra.Command, args []string) { if err := runList(lo); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := cmd.Flags() bindCommonStateStoreFlags(&lo.StateStoreOptions, fs) bindCommonAwsFlags(&lo.AwsOptions, fs) fs.BoolVarP(&noHeaders, keyNoHeaders, "n", viper.GetBool(keyNoHeaders), desNoHeaders) return cmd }
[ "func", "ListCmd", "(", ")", "*", "cobra", ".", "Command", "{", "var", "lo", "=", "&", "cli", ".", "ListOptions", "{", "}", "\n", "var", "cmd", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"list\"", ",", "Short", ":", "\"List available states\"", ",", "Long", ":", "`List the states available in the _state directory`", ",", "Run", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "err", ":=", "runList", "(", "lo", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "err", ".", "Error", "(", ")", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}", ",", "}", "\n", "fs", ":=", "cmd", ".", "Flags", "(", ")", "\n", "bindCommonStateStoreFlags", "(", "&", "lo", ".", "StateStoreOptions", ",", "fs", ")", "\n", "bindCommonAwsFlags", "(", "&", "lo", ".", "AwsOptions", ",", "fs", ")", "\n", "fs", ".", "BoolVarP", "(", "&", "noHeaders", ",", "keyNoHeaders", ",", "\"n\"", ",", "viper", ".", "GetBool", "(", "keyNoHeaders", ")", ",", "desNoHeaders", ")", "\n", "return", "cmd", "\n", "}" ]
// ListCmd represents the list command
[ "ListCmd", "represents", "the", "list", "command" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/list.go#L36-L58
test
kubicorn/kubicorn
profiles/packet/ubuntu_16_04.go
NewUbuntuCluster
func NewUbuntuCluster(name string) *cluster.Cluster { controlPlaneProviderConfig := &cluster.ControlPlaneProviderConfig{ Cloud: cluster.CloudPacket, Project: &cluster.Project{ Name: fmt.Sprintf("kubicorn-%s", name), }, Location: "ewr1", SSH: &cluster.SSH{ PublicKeyPath: "~/.ssh/id_rsa.pub", User: "root", }, KubernetesAPI: &cluster.KubernetesAPI{ Port: "443", }, Values: &cluster.Values{ ItemMap: map[string]string{ "INJECTEDTOKEN": kubeadm.GetRandomToken(), }, }, } machineSetsProviderConfigs := []*cluster.MachineProviderConfig{ { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeMaster, Name: fmt.Sprintf("%s.master", name), MaxCount: 1, MinCount: 1, Image: "ubuntu_16_04", Size: "baremetal_1", BootstrapScripts: []string{ "bootstrap/packet_k8s_ubuntu_16.04_master.sh", }, }, }, { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeNode, Name: fmt.Sprintf("%s.node", name), MaxCount: 1, MinCount: 1, Image: "ubuntu_16_04", Size: "baremetal_2", BootstrapScripts: []string{ "bootstrap/packet_k8s_ubuntu_16.04_node.sh", }, }, }, } c := cluster.NewCluster(name) c.SetProviderConfig(controlPlaneProviderConfig) c.NewMachineSetsFromProviderConfigs(machineSetsProviderConfigs) return c }
go
func NewUbuntuCluster(name string) *cluster.Cluster { controlPlaneProviderConfig := &cluster.ControlPlaneProviderConfig{ Cloud: cluster.CloudPacket, Project: &cluster.Project{ Name: fmt.Sprintf("kubicorn-%s", name), }, Location: "ewr1", SSH: &cluster.SSH{ PublicKeyPath: "~/.ssh/id_rsa.pub", User: "root", }, KubernetesAPI: &cluster.KubernetesAPI{ Port: "443", }, Values: &cluster.Values{ ItemMap: map[string]string{ "INJECTEDTOKEN": kubeadm.GetRandomToken(), }, }, } machineSetsProviderConfigs := []*cluster.MachineProviderConfig{ { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeMaster, Name: fmt.Sprintf("%s.master", name), MaxCount: 1, MinCount: 1, Image: "ubuntu_16_04", Size: "baremetal_1", BootstrapScripts: []string{ "bootstrap/packet_k8s_ubuntu_16.04_master.sh", }, }, }, { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeNode, Name: fmt.Sprintf("%s.node", name), MaxCount: 1, MinCount: 1, Image: "ubuntu_16_04", Size: "baremetal_2", BootstrapScripts: []string{ "bootstrap/packet_k8s_ubuntu_16.04_node.sh", }, }, }, } c := cluster.NewCluster(name) c.SetProviderConfig(controlPlaneProviderConfig) c.NewMachineSetsFromProviderConfigs(machineSetsProviderConfigs) return c }
[ "func", "NewUbuntuCluster", "(", "name", "string", ")", "*", "cluster", ".", "Cluster", "{", "controlPlaneProviderConfig", ":=", "&", "cluster", ".", "ControlPlaneProviderConfig", "{", "Cloud", ":", "cluster", ".", "CloudPacket", ",", "Project", ":", "&", "cluster", ".", "Project", "{", "Name", ":", "fmt", ".", "Sprintf", "(", "\"kubicorn-%s\"", ",", "name", ")", ",", "}", ",", "Location", ":", "\"ewr1\"", ",", "SSH", ":", "&", "cluster", ".", "SSH", "{", "PublicKeyPath", ":", "\"~/.ssh/id_rsa.pub\"", ",", "User", ":", "\"root\"", ",", "}", ",", "KubernetesAPI", ":", "&", "cluster", ".", "KubernetesAPI", "{", "Port", ":", "\"443\"", ",", "}", ",", "Values", ":", "&", "cluster", ".", "Values", "{", "ItemMap", ":", "map", "[", "string", "]", "string", "{", "\"INJECTEDTOKEN\"", ":", "kubeadm", ".", "GetRandomToken", "(", ")", ",", "}", ",", "}", ",", "}", "\n", "machineSetsProviderConfigs", ":=", "[", "]", "*", "cluster", ".", "MachineProviderConfig", "{", "{", "ServerPool", ":", "&", "cluster", ".", "ServerPool", "{", "Type", ":", "cluster", ".", "ServerPoolTypeMaster", ",", "Name", ":", "fmt", ".", "Sprintf", "(", "\"%s.master\"", ",", "name", ")", ",", "MaxCount", ":", "1", ",", "MinCount", ":", "1", ",", "Image", ":", "\"ubuntu_16_04\"", ",", "Size", ":", "\"baremetal_1\"", ",", "BootstrapScripts", ":", "[", "]", "string", "{", "\"bootstrap/packet_k8s_ubuntu_16.04_master.sh\"", ",", "}", ",", "}", ",", "}", ",", "{", "ServerPool", ":", "&", "cluster", ".", "ServerPool", "{", "Type", ":", "cluster", ".", "ServerPoolTypeNode", ",", "Name", ":", "fmt", ".", "Sprintf", "(", "\"%s.node\"", ",", "name", ")", ",", "MaxCount", ":", "1", ",", "MinCount", ":", "1", ",", "Image", ":", "\"ubuntu_16_04\"", ",", "Size", ":", "\"baremetal_2\"", ",", "BootstrapScripts", ":", "[", "]", "string", "{", "\"bootstrap/packet_k8s_ubuntu_16.04_node.sh\"", ",", "}", ",", "}", ",", "}", ",", "}", "\n", "c", ":=", "cluster", ".", "NewCluster", "(", "name", ")", "\n", "c", ".", "SetProviderConfig", "(", "controlPlaneProviderConfig", ")", "\n", "c", ".", "NewMachineSetsFromProviderConfigs", "(", "machineSetsProviderConfigs", ")", "\n", "return", "c", "\n", "}" ]
// NewUbuntuCluster creates a simple Ubuntu Amazon cluster
[ "NewUbuntuCluster", "creates", "a", "simple", "Ubuntu", "Amazon", "cluster" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/profiles/packet/ubuntu_16_04.go#L25-L78
test
kubicorn/kubicorn
cmd/edit.go
EditCmd
func EditCmd() *cobra.Command { var eo = &cli.EditOptions{} var editCmd = &cobra.Command{ Use: "edit <NAME>", Short: "Edit a cluster state", Long: `Use this command to edit a state.`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: eo.Name = viper.GetString(keyKubicornName) case 1: eo.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runEdit(eo); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := editCmd.Flags() bindCommonStateStoreFlags(&eo.StateStoreOptions, fs) bindCommonAwsFlags(&eo.AwsOptions, fs) fs.StringVarP(&eo.Editor, keyEditor, "e", viper.GetString(keyEditor), descEditor) fs.StringVar(&eo.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) return editCmd }
go
func EditCmd() *cobra.Command { var eo = &cli.EditOptions{} var editCmd = &cobra.Command{ Use: "edit <NAME>", Short: "Edit a cluster state", Long: `Use this command to edit a state.`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: eo.Name = viper.GetString(keyKubicornName) case 1: eo.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runEdit(eo); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := editCmd.Flags() bindCommonStateStoreFlags(&eo.StateStoreOptions, fs) bindCommonAwsFlags(&eo.AwsOptions, fs) fs.StringVarP(&eo.Editor, keyEditor, "e", viper.GetString(keyEditor), descEditor) fs.StringVar(&eo.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) return editCmd }
[ "func", "EditCmd", "(", ")", "*", "cobra", ".", "Command", "{", "var", "eo", "=", "&", "cli", ".", "EditOptions", "{", "}", "\n", "var", "editCmd", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"edit <NAME>\"", ",", "Short", ":", "\"Edit a cluster state\"", ",", "Long", ":", "`Use this command to edit a state.`", ",", "Run", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "switch", "len", "(", "args", ")", "{", "case", "0", ":", "eo", ".", "Name", "=", "viper", ".", "GetString", "(", "keyKubicornName", ")", "\n", "case", "1", ":", "eo", ".", "Name", "=", "args", "[", "0", "]", "\n", "default", ":", "logger", ".", "Critical", "(", "\"Too many arguments.\"", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "if", "err", ":=", "runEdit", "(", "eo", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "err", ".", "Error", "(", ")", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}", ",", "}", "\n", "fs", ":=", "editCmd", ".", "Flags", "(", ")", "\n", "bindCommonStateStoreFlags", "(", "&", "eo", ".", "StateStoreOptions", ",", "fs", ")", "\n", "bindCommonAwsFlags", "(", "&", "eo", ".", "AwsOptions", ",", "fs", ")", "\n", "fs", ".", "StringVarP", "(", "&", "eo", ".", "Editor", ",", "keyEditor", ",", "\"e\"", ",", "viper", ".", "GetString", "(", "keyEditor", ")", ",", "descEditor", ")", "\n", "fs", ".", "StringVar", "(", "&", "eo", ".", "GitRemote", ",", "keyGitConfig", ",", "viper", ".", "GetString", "(", "keyGitConfig", ")", ",", "descGitConfig", ")", "\n", "return", "editCmd", "\n", "}" ]
// EditCmd represents edit command
[ "EditCmd", "represents", "edit", "command" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/edit.go#L31-L65
test
kubicorn/kubicorn
pkg/agent/agent.go
RemoveKey
func (k *Keyring) RemoveKey(key ssh.PublicKey) error { return k.Agent.Remove(key) }
go
func (k *Keyring) RemoveKey(key ssh.PublicKey) error { return k.Agent.Remove(key) }
[ "func", "(", "k", "*", "Keyring", ")", "RemoveKey", "(", "key", "ssh", ".", "PublicKey", ")", "error", "{", "return", "k", ".", "Agent", ".", "Remove", "(", "key", ")", "\n", "}" ]
// RemoveKey removes an existing key from keyring
[ "RemoveKey", "removes", "an", "existing", "key", "from", "keyring" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/agent/agent.go#L117-L119
test
kubicorn/kubicorn
pkg/agent/agent.go
RemoveKeyUsingFile
func (k *Keyring) RemoveKeyUsingFile(pubkey string) error { p, err := ioutil.ReadFile(pubkey) if err != nil { return err } key, _, _, _, _ := ssh.ParseAuthorizedKey(p) if err != nil { return err } return k.RemoveKey(key) }
go
func (k *Keyring) RemoveKeyUsingFile(pubkey string) error { p, err := ioutil.ReadFile(pubkey) if err != nil { return err } key, _, _, _, _ := ssh.ParseAuthorizedKey(p) if err != nil { return err } return k.RemoveKey(key) }
[ "func", "(", "k", "*", "Keyring", ")", "RemoveKeyUsingFile", "(", "pubkey", "string", ")", "error", "{", "p", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "pubkey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "key", ",", "_", ",", "_", ",", "_", ",", "_", ":=", "ssh", ".", "ParseAuthorizedKey", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "k", ".", "RemoveKey", "(", "key", ")", "\n", "}" ]
// RemoveKeyUsingFile removes an existing key from keyring given a file
[ "RemoveKeyUsingFile", "removes", "an", "existing", "key", "from", "keyring", "given", "a", "file" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/agent/agent.go#L122-L134
test
kubicorn/kubicorn
cloud/digitalocean/droplet/resources/firewall.go
Actual
func (r *Firewall) Actual(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("firewall.Actual") newResource := defaultFirewallStruct() // Digital Firewalls.Get requires firewall ID, which we will not always have.thats why using List. firewalls, _, err := Sdk.Client.Firewalls.List(context.TODO(), &godo.ListOptions{}) if err != nil { return nil, nil, fmt.Errorf("failed to get firwalls info") } for _, firewall := range firewalls { if firewall.Name == r.Name { // In digitalOcean Firwall names are unique. // gotcha get all details from this firewall and populate actual. firewallBytes, err := json.Marshal(firewall) if err != nil { return nil, nil, fmt.Errorf("failed to marshal DO firewall details err: %v", err) } if err := json.Unmarshal(firewallBytes, newResource); err != nil { return nil, nil, fmt.Errorf("failed to unmarhal DO firewall details err: %v", err) } // hack: DO api doesn't take "0" as portRange, but returns "0" for port range in firewall.List. for i := 0; i < len(newResource.OutboundRules); i++ { if newResource.OutboundRules[i].PortRange == "0" { newResource.OutboundRules[i].PortRange = "all" } } for i := 0; i < len(newResource.InboundRules); i++ { if newResource.InboundRules[i].PortRange == "0" { newResource.InboundRules[i].PortRange = "all" } } } } newCluster := r.immutableRender(newResource, immutable) return newCluster, newResource, nil }
go
func (r *Firewall) Actual(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("firewall.Actual") newResource := defaultFirewallStruct() // Digital Firewalls.Get requires firewall ID, which we will not always have.thats why using List. firewalls, _, err := Sdk.Client.Firewalls.List(context.TODO(), &godo.ListOptions{}) if err != nil { return nil, nil, fmt.Errorf("failed to get firwalls info") } for _, firewall := range firewalls { if firewall.Name == r.Name { // In digitalOcean Firwall names are unique. // gotcha get all details from this firewall and populate actual. firewallBytes, err := json.Marshal(firewall) if err != nil { return nil, nil, fmt.Errorf("failed to marshal DO firewall details err: %v", err) } if err := json.Unmarshal(firewallBytes, newResource); err != nil { return nil, nil, fmt.Errorf("failed to unmarhal DO firewall details err: %v", err) } // hack: DO api doesn't take "0" as portRange, but returns "0" for port range in firewall.List. for i := 0; i < len(newResource.OutboundRules); i++ { if newResource.OutboundRules[i].PortRange == "0" { newResource.OutboundRules[i].PortRange = "all" } } for i := 0; i < len(newResource.InboundRules); i++ { if newResource.InboundRules[i].PortRange == "0" { newResource.InboundRules[i].PortRange = "all" } } } } newCluster := r.immutableRender(newResource, immutable) return newCluster, newResource, nil }
[ "func", "(", "r", "*", "Firewall", ")", "Actual", "(", "immutable", "*", "cluster", ".", "Cluster", ")", "(", "*", "cluster", ".", "Cluster", ",", "cloud", ".", "Resource", ",", "error", ")", "{", "logger", ".", "Debug", "(", "\"firewall.Actual\"", ")", "\n", "newResource", ":=", "defaultFirewallStruct", "(", ")", "\n", "firewalls", ",", "_", ",", "err", ":=", "Sdk", ".", "Client", ".", "Firewalls", ".", "List", "(", "context", ".", "TODO", "(", ")", ",", "&", "godo", ".", "ListOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"failed to get firwalls info\"", ")", "\n", "}", "\n", "for", "_", ",", "firewall", ":=", "range", "firewalls", "{", "if", "firewall", ".", "Name", "==", "r", ".", "Name", "{", "firewallBytes", ",", "err", ":=", "json", ".", "Marshal", "(", "firewall", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"failed to marshal DO firewall details err: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "firewallBytes", ",", "newResource", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"failed to unmarhal DO firewall details err: %v\"", ",", "err", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "newResource", ".", "OutboundRules", ")", ";", "i", "++", "{", "if", "newResource", ".", "OutboundRules", "[", "i", "]", ".", "PortRange", "==", "\"0\"", "{", "newResource", ".", "OutboundRules", "[", "i", "]", ".", "PortRange", "=", "\"all\"", "\n", "}", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "newResource", ".", "InboundRules", ")", ";", "i", "++", "{", "if", "newResource", ".", "InboundRules", "[", "i", "]", ".", "PortRange", "==", "\"0\"", "{", "newResource", ".", "InboundRules", "[", "i", "]", ".", "PortRange", "=", "\"all\"", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "newCluster", ":=", "r", ".", "immutableRender", "(", "newResource", ",", "immutable", ")", "\n", "return", "newCluster", ",", "newResource", ",", "nil", "\n", "}" ]
// Actual calls DO firewall Api and returns the actual state of firewall in the cloud.
[ "Actual", "calls", "DO", "firewall", "Api", "and", "returns", "the", "actual", "state", "of", "firewall", "in", "the", "cloud", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/digitalocean/droplet/resources/firewall.go#L82-L117
test
kubicorn/kubicorn
cloud/digitalocean/droplet/resources/firewall.go
Expected
func (r *Firewall) Expected(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("firewall.Expected") newResource := &Firewall{ Shared: Shared{ Name: r.Name, CloudID: r.ServerPool.Identifier, }, InboundRules: r.InboundRules, OutboundRules: r.OutboundRules, DropletIDs: r.DropletIDs, Tags: r.Tags, FirewallID: r.FirewallID, Status: r.Status, Created: r.Created, } //logger.Info("Expected firewall returned is %+v", immutable) newCluster := r.immutableRender(newResource, immutable) return newCluster, newResource, nil }
go
func (r *Firewall) Expected(immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("firewall.Expected") newResource := &Firewall{ Shared: Shared{ Name: r.Name, CloudID: r.ServerPool.Identifier, }, InboundRules: r.InboundRules, OutboundRules: r.OutboundRules, DropletIDs: r.DropletIDs, Tags: r.Tags, FirewallID: r.FirewallID, Status: r.Status, Created: r.Created, } //logger.Info("Expected firewall returned is %+v", immutable) newCluster := r.immutableRender(newResource, immutable) return newCluster, newResource, nil }
[ "func", "(", "r", "*", "Firewall", ")", "Expected", "(", "immutable", "*", "cluster", ".", "Cluster", ")", "(", "*", "cluster", ".", "Cluster", ",", "cloud", ".", "Resource", ",", "error", ")", "{", "logger", ".", "Debug", "(", "\"firewall.Expected\"", ")", "\n", "newResource", ":=", "&", "Firewall", "{", "Shared", ":", "Shared", "{", "Name", ":", "r", ".", "Name", ",", "CloudID", ":", "r", ".", "ServerPool", ".", "Identifier", ",", "}", ",", "InboundRules", ":", "r", ".", "InboundRules", ",", "OutboundRules", ":", "r", ".", "OutboundRules", ",", "DropletIDs", ":", "r", ".", "DropletIDs", ",", "Tags", ":", "r", ".", "Tags", ",", "FirewallID", ":", "r", ".", "FirewallID", ",", "Status", ":", "r", ".", "Status", ",", "Created", ":", "r", ".", "Created", ",", "}", "\n", "newCluster", ":=", "r", ".", "immutableRender", "(", "newResource", ",", "immutable", ")", "\n", "return", "newCluster", ",", "newResource", ",", "nil", "\n", "}" ]
// Expected returns the Firewall structure of what is Expected.
[ "Expected", "returns", "the", "Firewall", "structure", "of", "what", "is", "Expected", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/digitalocean/droplet/resources/firewall.go#L120-L140
test
kubicorn/kubicorn
cloud/digitalocean/droplet/resources/firewall.go
Apply
func (r *Firewall) Apply(actual, expected cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("firewall.Apply") expectedResource := expected.(*Firewall) actualResource := actual.(*Firewall) isEqual, err := compare.IsEqual(actualResource, expectedResource) if err != nil { return nil, nil, err } if isEqual { return immutable, expected, nil } firewallRequest := godo.FirewallRequest{ Name: expectedResource.Name, InboundRules: convertInRuleType(expectedResource.InboundRules), OutboundRules: convertOutRuleType(expectedResource.OutboundRules), DropletIDs: expectedResource.DropletIDs, Tags: expectedResource.Tags, } // Make sure Droplets are fully created before applying a firewall machineProviderConfigs := immutable.MachineProviderConfigs() for _, machineProviderConfig := range machineProviderConfigs { for i := 0; i <= TagsGetAttempts; i++ { active := true droplets, _, err := Sdk.Client.Droplets.ListByTag(context.TODO(), machineProviderConfig.ServerPool.Name, &godo.ListOptions{}) if err != nil { logger.Debug("Hanging for droplets to get created.. (%v)", err) time.Sleep(time.Duration(TagsGetTimeout) * time.Second) continue } if len(droplets) == 0 { continue } for _, d := range droplets { if d.Status != "active" { active = false break } } if !active { logger.Debug("Waiting for droplets to become active..") time.Sleep(time.Duration(TagsGetTimeout) * time.Second) continue } break } } firewall, _, err := Sdk.Client.Firewalls.Create(context.TODO(), &firewallRequest) if err != nil { return nil, nil, fmt.Errorf("failed to create the firewall err: %v", err) } logger.Success("Created Firewall [%s]", firewall.ID) newResource := &Firewall{ Shared: Shared{ CloudID: firewall.ID, Name: r.Name, Tags: r.Tags, }, DropletIDs: r.DropletIDs, FirewallID: firewall.ID, InboundRules: r.InboundRules, OutboundRules: r.OutboundRules, Created: r.Created, } newCluster := r.immutableRender(newResource, immutable) return newCluster, newResource, nil }
go
func (r *Firewall) Apply(actual, expected cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("firewall.Apply") expectedResource := expected.(*Firewall) actualResource := actual.(*Firewall) isEqual, err := compare.IsEqual(actualResource, expectedResource) if err != nil { return nil, nil, err } if isEqual { return immutable, expected, nil } firewallRequest := godo.FirewallRequest{ Name: expectedResource.Name, InboundRules: convertInRuleType(expectedResource.InboundRules), OutboundRules: convertOutRuleType(expectedResource.OutboundRules), DropletIDs: expectedResource.DropletIDs, Tags: expectedResource.Tags, } // Make sure Droplets are fully created before applying a firewall machineProviderConfigs := immutable.MachineProviderConfigs() for _, machineProviderConfig := range machineProviderConfigs { for i := 0; i <= TagsGetAttempts; i++ { active := true droplets, _, err := Sdk.Client.Droplets.ListByTag(context.TODO(), machineProviderConfig.ServerPool.Name, &godo.ListOptions{}) if err != nil { logger.Debug("Hanging for droplets to get created.. (%v)", err) time.Sleep(time.Duration(TagsGetTimeout) * time.Second) continue } if len(droplets) == 0 { continue } for _, d := range droplets { if d.Status != "active" { active = false break } } if !active { logger.Debug("Waiting for droplets to become active..") time.Sleep(time.Duration(TagsGetTimeout) * time.Second) continue } break } } firewall, _, err := Sdk.Client.Firewalls.Create(context.TODO(), &firewallRequest) if err != nil { return nil, nil, fmt.Errorf("failed to create the firewall err: %v", err) } logger.Success("Created Firewall [%s]", firewall.ID) newResource := &Firewall{ Shared: Shared{ CloudID: firewall.ID, Name: r.Name, Tags: r.Tags, }, DropletIDs: r.DropletIDs, FirewallID: firewall.ID, InboundRules: r.InboundRules, OutboundRules: r.OutboundRules, Created: r.Created, } newCluster := r.immutableRender(newResource, immutable) return newCluster, newResource, nil }
[ "func", "(", "r", "*", "Firewall", ")", "Apply", "(", "actual", ",", "expected", "cloud", ".", "Resource", ",", "immutable", "*", "cluster", ".", "Cluster", ")", "(", "*", "cluster", ".", "Cluster", ",", "cloud", ".", "Resource", ",", "error", ")", "{", "logger", ".", "Debug", "(", "\"firewall.Apply\"", ")", "\n", "expectedResource", ":=", "expected", ".", "(", "*", "Firewall", ")", "\n", "actualResource", ":=", "actual", ".", "(", "*", "Firewall", ")", "\n", "isEqual", ",", "err", ":=", "compare", ".", "IsEqual", "(", "actualResource", ",", "expectedResource", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "if", "isEqual", "{", "return", "immutable", ",", "expected", ",", "nil", "\n", "}", "\n", "firewallRequest", ":=", "godo", ".", "FirewallRequest", "{", "Name", ":", "expectedResource", ".", "Name", ",", "InboundRules", ":", "convertInRuleType", "(", "expectedResource", ".", "InboundRules", ")", ",", "OutboundRules", ":", "convertOutRuleType", "(", "expectedResource", ".", "OutboundRules", ")", ",", "DropletIDs", ":", "expectedResource", ".", "DropletIDs", ",", "Tags", ":", "expectedResource", ".", "Tags", ",", "}", "\n", "machineProviderConfigs", ":=", "immutable", ".", "MachineProviderConfigs", "(", ")", "\n", "for", "_", ",", "machineProviderConfig", ":=", "range", "machineProviderConfigs", "{", "for", "i", ":=", "0", ";", "i", "<=", "TagsGetAttempts", ";", "i", "++", "{", "active", ":=", "true", "\n", "droplets", ",", "_", ",", "err", ":=", "Sdk", ".", "Client", ".", "Droplets", ".", "ListByTag", "(", "context", ".", "TODO", "(", ")", ",", "machineProviderConfig", ".", "ServerPool", ".", "Name", ",", "&", "godo", ".", "ListOptions", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Debug", "(", "\"Hanging for droplets to get created.. (%v)\"", ",", "err", ")", "\n", "time", ".", "Sleep", "(", "time", ".", "Duration", "(", "TagsGetTimeout", ")", "*", "time", ".", "Second", ")", "\n", "continue", "\n", "}", "\n", "if", "len", "(", "droplets", ")", "==", "0", "{", "continue", "\n", "}", "\n", "for", "_", ",", "d", ":=", "range", "droplets", "{", "if", "d", ".", "Status", "!=", "\"active\"", "{", "active", "=", "false", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "active", "{", "logger", ".", "Debug", "(", "\"Waiting for droplets to become active..\"", ")", "\n", "time", ".", "Sleep", "(", "time", ".", "Duration", "(", "TagsGetTimeout", ")", "*", "time", ".", "Second", ")", "\n", "continue", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "firewall", ",", "_", ",", "err", ":=", "Sdk", ".", "Client", ".", "Firewalls", ".", "Create", "(", "context", ".", "TODO", "(", ")", ",", "&", "firewallRequest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"failed to create the firewall err: %v\"", ",", "err", ")", "\n", "}", "\n", "logger", ".", "Success", "(", "\"Created Firewall [%s]\"", ",", "firewall", ".", "ID", ")", "\n", "newResource", ":=", "&", "Firewall", "{", "Shared", ":", "Shared", "{", "CloudID", ":", "firewall", ".", "ID", ",", "Name", ":", "r", ".", "Name", ",", "Tags", ":", "r", ".", "Tags", ",", "}", ",", "DropletIDs", ":", "r", ".", "DropletIDs", ",", "FirewallID", ":", "firewall", ".", "ID", ",", "InboundRules", ":", "r", ".", "InboundRules", ",", "OutboundRules", ":", "r", ".", "OutboundRules", ",", "Created", ":", "r", ".", "Created", ",", "}", "\n", "newCluster", ":=", "r", ".", "immutableRender", "(", "newResource", ",", "immutable", ")", "\n", "return", "newCluster", ",", "newResource", ",", "nil", "\n", "}" ]
// Apply will compare the actual and expected firewall config, if needed it will create the firewall.
[ "Apply", "will", "compare", "the", "actual", "and", "expected", "firewall", "config", "if", "needed", "it", "will", "create", "the", "firewall", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/digitalocean/droplet/resources/firewall.go#L143-L213
test
kubicorn/kubicorn
cloud/digitalocean/droplet/resources/firewall.go
Delete
func (r *Firewall) Delete(actual cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("firewall.Delete") deleteResource, ok := actual.(*Firewall) if !ok { return nil, nil, fmt.Errorf("failed to type convert actual Firewall type ") } if deleteResource.Name == "" { return immutable, nil, nil return nil, nil, fmt.Errorf("Unable to delete firewall resource without Name [%s]", deleteResource.Name) } if _, err := Sdk.Client.Firewalls.Delete(context.TODO(), deleteResource.FirewallID); err != nil { return nil, nil, fmt.Errorf("failed to delete firewall [%s] err: %v", deleteResource.Name, err) } logger.Success("Deleted firewall [%s]", deleteResource.FirewallID) newResource := &Firewall{ Shared: Shared{ Name: r.Name, Tags: r.Tags, }, InboundRules: r.InboundRules, OutboundRules: r.OutboundRules, Created: r.Created, } newCluster := r.immutableRender(newResource, immutable) return newCluster, newResource, nil }
go
func (r *Firewall) Delete(actual cloud.Resource, immutable *cluster.Cluster) (*cluster.Cluster, cloud.Resource, error) { logger.Debug("firewall.Delete") deleteResource, ok := actual.(*Firewall) if !ok { return nil, nil, fmt.Errorf("failed to type convert actual Firewall type ") } if deleteResource.Name == "" { return immutable, nil, nil return nil, nil, fmt.Errorf("Unable to delete firewall resource without Name [%s]", deleteResource.Name) } if _, err := Sdk.Client.Firewalls.Delete(context.TODO(), deleteResource.FirewallID); err != nil { return nil, nil, fmt.Errorf("failed to delete firewall [%s] err: %v", deleteResource.Name, err) } logger.Success("Deleted firewall [%s]", deleteResource.FirewallID) newResource := &Firewall{ Shared: Shared{ Name: r.Name, Tags: r.Tags, }, InboundRules: r.InboundRules, OutboundRules: r.OutboundRules, Created: r.Created, } newCluster := r.immutableRender(newResource, immutable) return newCluster, newResource, nil }
[ "func", "(", "r", "*", "Firewall", ")", "Delete", "(", "actual", "cloud", ".", "Resource", ",", "immutable", "*", "cluster", ".", "Cluster", ")", "(", "*", "cluster", ".", "Cluster", ",", "cloud", ".", "Resource", ",", "error", ")", "{", "logger", ".", "Debug", "(", "\"firewall.Delete\"", ")", "\n", "deleteResource", ",", "ok", ":=", "actual", ".", "(", "*", "Firewall", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"failed to type convert actual Firewall type \"", ")", "\n", "}", "\n", "if", "deleteResource", ".", "Name", "==", "\"\"", "{", "return", "immutable", ",", "nil", ",", "nil", "\n", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"Unable to delete firewall resource without Name [%s]\"", ",", "deleteResource", ".", "Name", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "Sdk", ".", "Client", ".", "Firewalls", ".", "Delete", "(", "context", ".", "TODO", "(", ")", ",", "deleteResource", ".", "FirewallID", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"failed to delete firewall [%s] err: %v\"", ",", "deleteResource", ".", "Name", ",", "err", ")", "\n", "}", "\n", "logger", ".", "Success", "(", "\"Deleted firewall [%s]\"", ",", "deleteResource", ".", "FirewallID", ")", "\n", "newResource", ":=", "&", "Firewall", "{", "Shared", ":", "Shared", "{", "Name", ":", "r", ".", "Name", ",", "Tags", ":", "r", ".", "Tags", ",", "}", ",", "InboundRules", ":", "r", ".", "InboundRules", ",", "OutboundRules", ":", "r", ".", "OutboundRules", ",", "Created", ":", "r", ".", "Created", ",", "}", "\n", "newCluster", ":=", "r", ".", "immutableRender", "(", "newResource", ",", "immutable", ")", "\n", "return", "newCluster", ",", "newResource", ",", "nil", "\n", "}" ]
// Delete removes the firewall
[ "Delete", "removes", "the", "firewall" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cloud/digitalocean/droplet/resources/firewall.go#L304-L331
test
kubicorn/kubicorn
cmd/delete.go
DeleteCmd
func DeleteCmd() *cobra.Command { var do = &cli.DeleteOptions{} var deleteCmd = &cobra.Command{ Use: "delete <NAME>", Short: "Delete a Kubernetes cluster", Long: `Use this command to delete cloud resources. This command will attempt to build the resource graph based on an API model. Once the graph is built, the delete will attempt to delete the resources from the cloud. After the delete is complete, the state store will be left in tact and could potentially be applied later. To delete the resource AND the API model in the state store, use --purge.`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: do.Name = viper.GetString(keyKubicornName) case 1: do.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runDelete(do); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := deleteCmd.Flags() bindCommonStateStoreFlags(&do.StateStoreOptions, fs) bindCommonAwsFlags(&do.AwsOptions, fs) fs.StringVar(&do.AwsProfile, keyAwsProfile, viper.GetString(keyAwsProfile), descAwsProfile) fs.StringVar(&do.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) fs.BoolVarP(&do.Purge, keyPurge, "p", viper.GetBool(keyPurge), descPurge) return deleteCmd }
go
func DeleteCmd() *cobra.Command { var do = &cli.DeleteOptions{} var deleteCmd = &cobra.Command{ Use: "delete <NAME>", Short: "Delete a Kubernetes cluster", Long: `Use this command to delete cloud resources. This command will attempt to build the resource graph based on an API model. Once the graph is built, the delete will attempt to delete the resources from the cloud. After the delete is complete, the state store will be left in tact and could potentially be applied later. To delete the resource AND the API model in the state store, use --purge.`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: do.Name = viper.GetString(keyKubicornName) case 1: do.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runDelete(do); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := deleteCmd.Flags() bindCommonStateStoreFlags(&do.StateStoreOptions, fs) bindCommonAwsFlags(&do.AwsOptions, fs) fs.StringVar(&do.AwsProfile, keyAwsProfile, viper.GetString(keyAwsProfile), descAwsProfile) fs.StringVar(&do.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) fs.BoolVarP(&do.Purge, keyPurge, "p", viper.GetBool(keyPurge), descPurge) return deleteCmd }
[ "func", "DeleteCmd", "(", ")", "*", "cobra", ".", "Command", "{", "var", "do", "=", "&", "cli", ".", "DeleteOptions", "{", "}", "\n", "var", "deleteCmd", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"delete <NAME>\"", ",", "Short", ":", "\"Delete a Kubernetes cluster\"", ",", "Long", ":", "`Use this command to delete cloud resources.\t\tThis command will attempt to build the resource graph based on an API model.\tOnce the graph is built, the delete will attempt to delete the resources from the cloud.\tAfter the delete is complete, the state store will be left in tact and could potentially be applied later.\t\tTo delete the resource AND the API model in the state store, use --purge.`", ",", "Run", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "switch", "len", "(", "args", ")", "{", "case", "0", ":", "do", ".", "Name", "=", "viper", ".", "GetString", "(", "keyKubicornName", ")", "\n", "case", "1", ":", "do", ".", "Name", "=", "args", "[", "0", "]", "\n", "default", ":", "logger", ".", "Critical", "(", "\"Too many arguments.\"", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "if", "err", ":=", "runDelete", "(", "do", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "err", ".", "Error", "(", ")", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}", ",", "}", "\n", "fs", ":=", "deleteCmd", ".", "Flags", "(", ")", "\n", "bindCommonStateStoreFlags", "(", "&", "do", ".", "StateStoreOptions", ",", "fs", ")", "\n", "bindCommonAwsFlags", "(", "&", "do", ".", "AwsOptions", ",", "fs", ")", "\n", "fs", ".", "StringVar", "(", "&", "do", ".", "AwsProfile", ",", "keyAwsProfile", ",", "viper", ".", "GetString", "(", "keyAwsProfile", ")", ",", "descAwsProfile", ")", "\n", "fs", ".", "StringVar", "(", "&", "do", ".", "GitRemote", ",", "keyGitConfig", ",", "viper", ".", "GetString", "(", "keyGitConfig", ")", ",", "descGitConfig", ")", "\n", "fs", ".", "BoolVarP", "(", "&", "do", ".", "Purge", ",", "keyPurge", ",", "\"p\"", ",", "viper", ".", "GetBool", "(", "keyPurge", ")", ",", "descPurge", ")", "\n", "return", "deleteCmd", "\n", "}" ]
// DeleteCmd represents the delete command
[ "DeleteCmd", "represents", "the", "delete", "command" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/delete.go#L32-L73
test
kubicorn/kubicorn
pkg/cli/state_store.go
NewStateStore
func (options Options) NewStateStore() (state.ClusterStorer, error) { var stateStore state.ClusterStorer switch options.StateStore { case "fs": logger.Info("Selected [fs] state store") stateStore = fs.NewFileSystemStore(&fs.FileSystemStoreOptions{ BasePath: options.StateStorePath, ClusterName: options.Name, }) case "crd": logger.Info("Selected [crd] state store") stateStore = crd.NewCRDStore(&crd.CRDStoreOptions{ BasePath: options.StateStorePath, ClusterName: options.Name, }) case "git": logger.Info("Selected [git] state store") if options.GitRemote == "" { return nil, errors.New("empty GitRemote url. Must specify the link to the remote git repo") } user, _ := gg.Global("user.name") email, _ := gg.Email() stateStore = git.NewJSONGitStore(&git.JSONGitStoreOptions{ BasePath: options.StateStorePath, ClusterName: options.Name, CommitConfig: &git.JSONGitCommitConfig{ Name: user, Email: email, Remote: options.GitRemote, }, }) case "jsonfs": logger.Info("Selected [jsonfs] state store") stateStore = jsonfs.NewJSONFileSystemStore(&jsonfs.JSONFileSystemStoreOptions{ BasePath: options.StateStorePath, ClusterName: options.Name, }) case "s3": logger.Info("Selected [s3] state store") client, err := minio.New(options.BucketEndpointURL, options.S3AccessKey, options.S3SecretKey, options.BucketSSL) if err != nil { return nil, err } stateStore = s3.NewJSONFS3Store(&s3.JSONS3StoreOptions{ BasePath: options.StateStorePath, ClusterName: options.Name, Client: client, BucketOptions: &s3.S3BucketOptions{ EndpointURL: options.BucketEndpointURL, BucketName: options.BucketName, }, }) default: return nil, fmt.Errorf("state store [%s] has an invalid type [%s]", options.Name, options.StateStore) } return stateStore, nil }
go
func (options Options) NewStateStore() (state.ClusterStorer, error) { var stateStore state.ClusterStorer switch options.StateStore { case "fs": logger.Info("Selected [fs] state store") stateStore = fs.NewFileSystemStore(&fs.FileSystemStoreOptions{ BasePath: options.StateStorePath, ClusterName: options.Name, }) case "crd": logger.Info("Selected [crd] state store") stateStore = crd.NewCRDStore(&crd.CRDStoreOptions{ BasePath: options.StateStorePath, ClusterName: options.Name, }) case "git": logger.Info("Selected [git] state store") if options.GitRemote == "" { return nil, errors.New("empty GitRemote url. Must specify the link to the remote git repo") } user, _ := gg.Global("user.name") email, _ := gg.Email() stateStore = git.NewJSONGitStore(&git.JSONGitStoreOptions{ BasePath: options.StateStorePath, ClusterName: options.Name, CommitConfig: &git.JSONGitCommitConfig{ Name: user, Email: email, Remote: options.GitRemote, }, }) case "jsonfs": logger.Info("Selected [jsonfs] state store") stateStore = jsonfs.NewJSONFileSystemStore(&jsonfs.JSONFileSystemStoreOptions{ BasePath: options.StateStorePath, ClusterName: options.Name, }) case "s3": logger.Info("Selected [s3] state store") client, err := minio.New(options.BucketEndpointURL, options.S3AccessKey, options.S3SecretKey, options.BucketSSL) if err != nil { return nil, err } stateStore = s3.NewJSONFS3Store(&s3.JSONS3StoreOptions{ BasePath: options.StateStorePath, ClusterName: options.Name, Client: client, BucketOptions: &s3.S3BucketOptions{ EndpointURL: options.BucketEndpointURL, BucketName: options.BucketName, }, }) default: return nil, fmt.Errorf("state store [%s] has an invalid type [%s]", options.Name, options.StateStore) } return stateStore, nil }
[ "func", "(", "options", "Options", ")", "NewStateStore", "(", ")", "(", "state", ".", "ClusterStorer", ",", "error", ")", "{", "var", "stateStore", "state", ".", "ClusterStorer", "\n", "switch", "options", ".", "StateStore", "{", "case", "\"fs\"", ":", "logger", ".", "Info", "(", "\"Selected [fs] state store\"", ")", "\n", "stateStore", "=", "fs", ".", "NewFileSystemStore", "(", "&", "fs", ".", "FileSystemStoreOptions", "{", "BasePath", ":", "options", ".", "StateStorePath", ",", "ClusterName", ":", "options", ".", "Name", ",", "}", ")", "\n", "case", "\"crd\"", ":", "logger", ".", "Info", "(", "\"Selected [crd] state store\"", ")", "\n", "stateStore", "=", "crd", ".", "NewCRDStore", "(", "&", "crd", ".", "CRDStoreOptions", "{", "BasePath", ":", "options", ".", "StateStorePath", ",", "ClusterName", ":", "options", ".", "Name", ",", "}", ")", "\n", "case", "\"git\"", ":", "logger", ".", "Info", "(", "\"Selected [git] state store\"", ")", "\n", "if", "options", ".", "GitRemote", "==", "\"\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"empty GitRemote url. Must specify the link to the remote git repo\"", ")", "\n", "}", "\n", "user", ",", "_", ":=", "gg", ".", "Global", "(", "\"user.name\"", ")", "\n", "email", ",", "_", ":=", "gg", ".", "Email", "(", ")", "\n", "stateStore", "=", "git", ".", "NewJSONGitStore", "(", "&", "git", ".", "JSONGitStoreOptions", "{", "BasePath", ":", "options", ".", "StateStorePath", ",", "ClusterName", ":", "options", ".", "Name", ",", "CommitConfig", ":", "&", "git", ".", "JSONGitCommitConfig", "{", "Name", ":", "user", ",", "Email", ":", "email", ",", "Remote", ":", "options", ".", "GitRemote", ",", "}", ",", "}", ")", "\n", "case", "\"jsonfs\"", ":", "logger", ".", "Info", "(", "\"Selected [jsonfs] state store\"", ")", "\n", "stateStore", "=", "jsonfs", ".", "NewJSONFileSystemStore", "(", "&", "jsonfs", ".", "JSONFileSystemStoreOptions", "{", "BasePath", ":", "options", ".", "StateStorePath", ",", "ClusterName", ":", "options", ".", "Name", ",", "}", ")", "\n", "case", "\"s3\"", ":", "logger", ".", "Info", "(", "\"Selected [s3] state store\"", ")", "\n", "client", ",", "err", ":=", "minio", ".", "New", "(", "options", ".", "BucketEndpointURL", ",", "options", ".", "S3AccessKey", ",", "options", ".", "S3SecretKey", ",", "options", ".", "BucketSSL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "stateStore", "=", "s3", ".", "NewJSONFS3Store", "(", "&", "s3", ".", "JSONS3StoreOptions", "{", "BasePath", ":", "options", ".", "StateStorePath", ",", "ClusterName", ":", "options", ".", "Name", ",", "Client", ":", "client", ",", "BucketOptions", ":", "&", "s3", ".", "S3BucketOptions", "{", "EndpointURL", ":", "options", ".", "BucketEndpointURL", ",", "BucketName", ":", "options", ".", "BucketName", ",", "}", ",", "}", ")", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"state store [%s] has an invalid type [%s]\"", ",", "options", ".", "Name", ",", "options", ".", "StateStore", ")", "\n", "}", "\n", "return", "stateStore", ",", "nil", "\n", "}" ]
// NewStateStore returns clusterStorer object based on type.
[ "NewStateStore", "returns", "clusterStorer", "object", "based", "on", "type", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/cli/state_store.go#L33-L92
test
kubicorn/kubicorn
pkg/state/git/impl.go
Commit
func (git *JSONGitStore) Commit(c *cluster.Cluster) error { if c == nil { return fmt.Errorf("Nil cluster spec") } bytes, err := json.Marshal(c) if err != nil { return err } //writes latest changes to git repo. git.Write(state.ClusterJSONFile, bytes) //commits the changes r, err := g.NewFilesystemRepository(state.ClusterJSONFile) if err != nil { return err } // Add a new remote, with the default fetch refspec _, err = r.CreateRemote(&config.RemoteConfig{ Name: git.ClusterName, URL: git.options.CommitConfig.Remote, }) _, err = r.Commits() if err != nil { return err } return nil }
go
func (git *JSONGitStore) Commit(c *cluster.Cluster) error { if c == nil { return fmt.Errorf("Nil cluster spec") } bytes, err := json.Marshal(c) if err != nil { return err } //writes latest changes to git repo. git.Write(state.ClusterJSONFile, bytes) //commits the changes r, err := g.NewFilesystemRepository(state.ClusterJSONFile) if err != nil { return err } // Add a new remote, with the default fetch refspec _, err = r.CreateRemote(&config.RemoteConfig{ Name: git.ClusterName, URL: git.options.CommitConfig.Remote, }) _, err = r.Commits() if err != nil { return err } return nil }
[ "func", "(", "git", "*", "JSONGitStore", ")", "Commit", "(", "c", "*", "cluster", ".", "Cluster", ")", "error", "{", "if", "c", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"Nil cluster spec\"", ")", "\n", "}", "\n", "bytes", ",", "err", ":=", "json", ".", "Marshal", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "git", ".", "Write", "(", "state", ".", "ClusterJSONFile", ",", "bytes", ")", "\n", "r", ",", "err", ":=", "g", ".", "NewFilesystemRepository", "(", "state", ".", "ClusterJSONFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "r", ".", "CreateRemote", "(", "&", "config", ".", "RemoteConfig", "{", "Name", ":", "git", ".", "ClusterName", ",", "URL", ":", "git", ".", "options", ".", "CommitConfig", ".", "Remote", ",", "}", ")", "\n", "_", ",", "err", "=", "r", ".", "Commits", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
//Performs a git 'commit' and 'push' of the current cluster changes.
[ "Performs", "a", "git", "commit", "and", "push", "of", "the", "current", "cluster", "changes", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/state/git/impl.go#L122-L150
test
kubicorn/kubicorn
cmd/apply.go
ApplyCmd
func ApplyCmd() *cobra.Command { var ao = &cli.ApplyOptions{} var applyCmd = &cobra.Command{ Use: "apply <NAME>", Short: "Apply a cluster resource to a cloud", Long: `Use this command to apply an API model in a cloud. This command will attempt to find an API model in a defined state store, and then apply any changes needed directly to a cloud. The apply will run once, and ultimately time out if something goes wrong.`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: ao.Name = viper.GetString(keyKubicornName) case 1: ao.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runApply(ao); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := applyCmd.Flags() bindCommonStateStoreFlags(&ao.StateStoreOptions, fs) bindCommonAwsFlags(&ao.AwsOptions, fs) fs.StringArrayVarP(&ao.Set, keyKubicornSet, "e", viper.GetStringSlice(keyKubicornSet), descSet) fs.StringVar(&ao.AwsProfile, keyAwsProfile, viper.GetString(keyAwsProfile), descAwsProfile) fs.StringVar(&ao.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) return applyCmd }
go
func ApplyCmd() *cobra.Command { var ao = &cli.ApplyOptions{} var applyCmd = &cobra.Command{ Use: "apply <NAME>", Short: "Apply a cluster resource to a cloud", Long: `Use this command to apply an API model in a cloud. This command will attempt to find an API model in a defined state store, and then apply any changes needed directly to a cloud. The apply will run once, and ultimately time out if something goes wrong.`, Run: func(cmd *cobra.Command, args []string) { switch len(args) { case 0: ao.Name = viper.GetString(keyKubicornName) case 1: ao.Name = args[0] default: logger.Critical("Too many arguments.") os.Exit(1) } if err := runApply(ao); err != nil { logger.Critical(err.Error()) os.Exit(1) } }, } fs := applyCmd.Flags() bindCommonStateStoreFlags(&ao.StateStoreOptions, fs) bindCommonAwsFlags(&ao.AwsOptions, fs) fs.StringArrayVarP(&ao.Set, keyKubicornSet, "e", viper.GetStringSlice(keyKubicornSet), descSet) fs.StringVar(&ao.AwsProfile, keyAwsProfile, viper.GetString(keyAwsProfile), descAwsProfile) fs.StringVar(&ao.GitRemote, keyGitConfig, viper.GetString(keyGitConfig), descGitConfig) return applyCmd }
[ "func", "ApplyCmd", "(", ")", "*", "cobra", ".", "Command", "{", "var", "ao", "=", "&", "cli", ".", "ApplyOptions", "{", "}", "\n", "var", "applyCmd", "=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"apply <NAME>\"", ",", "Short", ":", "\"Apply a cluster resource to a cloud\"", ",", "Long", ":", "`Use this command to apply an API model in a cloud.\tThis command will attempt to find an API model in a defined state store, and then apply any changes needed directly to a cloud.\tThe apply will run once, and ultimately time out if something goes wrong.`", ",", "Run", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "switch", "len", "(", "args", ")", "{", "case", "0", ":", "ao", ".", "Name", "=", "viper", ".", "GetString", "(", "keyKubicornName", ")", "\n", "case", "1", ":", "ao", ".", "Name", "=", "args", "[", "0", "]", "\n", "default", ":", "logger", ".", "Critical", "(", "\"Too many arguments.\"", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "if", "err", ":=", "runApply", "(", "ao", ")", ";", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "err", ".", "Error", "(", ")", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}", ",", "}", "\n", "fs", ":=", "applyCmd", ".", "Flags", "(", ")", "\n", "bindCommonStateStoreFlags", "(", "&", "ao", ".", "StateStoreOptions", ",", "fs", ")", "\n", "bindCommonAwsFlags", "(", "&", "ao", ".", "AwsOptions", ",", "fs", ")", "\n", "fs", ".", "StringArrayVarP", "(", "&", "ao", ".", "Set", ",", "keyKubicornSet", ",", "\"e\"", ",", "viper", ".", "GetStringSlice", "(", "keyKubicornSet", ")", ",", "descSet", ")", "\n", "fs", ".", "StringVar", "(", "&", "ao", ".", "AwsProfile", ",", "keyAwsProfile", ",", "viper", ".", "GetString", "(", "keyAwsProfile", ")", ",", "descAwsProfile", ")", "\n", "fs", ".", "StringVar", "(", "&", "ao", ".", "GitRemote", ",", "keyGitConfig", ",", "viper", ".", "GetString", "(", "keyGitConfig", ")", ",", "descGitConfig", ")", "\n", "return", "applyCmd", "\n", "}" ]
// ApplyCmd represents the apply command
[ "ApplyCmd", "represents", "the", "apply", "command" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/apply.go#L39-L76
test
kubicorn/kubicorn
pkg/cli/utils.go
ExpandPath
func ExpandPath(path string) string { switch path { case ".": wd, err := os.Getwd() if err != nil { logger.Critical("Unable to get current working directory: %v", err) return "" } path = wd case "~": homeVar := os.Getenv("HOME") if homeVar == "" { homeUser, err := user.Current() if err != nil { logger.Critical("Unable to use user.Current() for user. Maybe a cross compile issue: %v", err) return "" } path = homeUser.HomeDir } } return path }
go
func ExpandPath(path string) string { switch path { case ".": wd, err := os.Getwd() if err != nil { logger.Critical("Unable to get current working directory: %v", err) return "" } path = wd case "~": homeVar := os.Getenv("HOME") if homeVar == "" { homeUser, err := user.Current() if err != nil { logger.Critical("Unable to use user.Current() for user. Maybe a cross compile issue: %v", err) return "" } path = homeUser.HomeDir } } return path }
[ "func", "ExpandPath", "(", "path", "string", ")", "string", "{", "switch", "path", "{", "case", "\".\"", ":", "wd", ",", "err", ":=", "os", ".", "Getwd", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "\"Unable to get current working directory: %v\"", ",", "err", ")", "\n", "return", "\"\"", "\n", "}", "\n", "path", "=", "wd", "\n", "case", "\"~\"", ":", "homeVar", ":=", "os", ".", "Getenv", "(", "\"HOME\"", ")", "\n", "if", "homeVar", "==", "\"\"", "{", "homeUser", ",", "err", ":=", "user", ".", "Current", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logger", ".", "Critical", "(", "\"Unable to use user.Current() for user. Maybe a cross compile issue: %v\"", ",", "err", ")", "\n", "return", "\"\"", "\n", "}", "\n", "path", "=", "homeUser", ".", "HomeDir", "\n", "}", "\n", "}", "\n", "return", "path", "\n", "}" ]
// ExpandPath returns working directory path
[ "ExpandPath", "returns", "working", "directory", "path" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/cli/utils.go#L25-L47
test
kubicorn/kubicorn
cmd/completion.go
CompletionCmd
func CompletionCmd() *cobra.Command { return &cobra.Command{ Use: "completion", Short: "Generate completion code for bash and zsh shells.", Long: `completion is used to output completion code for bash and zsh shells. Before using completion features, you have to source completion code from your .profile. This is done by adding following line to one of above files: source <(kubicorn completion SHELL) Valid arguments for SHELL are: "bash" and "zsh". Notes: 1) zsh completions requires zsh 5.2 or newer. 2) macOS users have to install bash-completion framework to utilize completion features. This can be done using homebrew: brew install bash-completion Once installed, you must load bash_completion by adding following line to your .profile or .bashrc/.zshrc: source $(brew --prefix)/etc/bash_completion`, RunE: func(cmd *cobra.Command, args []string) error { if logger.Fabulous { cmd.SetOutput(logger.FabulousWriter) } if viper.GetString(keyTrueColor) != "" { cmd.SetOutput(logger.FabulousWriter) } switch len(args) { case 0: return fmt.Errorf("shell argument is not specified") default: switch args[0] { case "bash": return runBashGeneration() case "zsh": return runZshGeneration() default: return fmt.Errorf("invalid shell argument") } } }, } }
go
func CompletionCmd() *cobra.Command { return &cobra.Command{ Use: "completion", Short: "Generate completion code for bash and zsh shells.", Long: `completion is used to output completion code for bash and zsh shells. Before using completion features, you have to source completion code from your .profile. This is done by adding following line to one of above files: source <(kubicorn completion SHELL) Valid arguments for SHELL are: "bash" and "zsh". Notes: 1) zsh completions requires zsh 5.2 or newer. 2) macOS users have to install bash-completion framework to utilize completion features. This can be done using homebrew: brew install bash-completion Once installed, you must load bash_completion by adding following line to your .profile or .bashrc/.zshrc: source $(brew --prefix)/etc/bash_completion`, RunE: func(cmd *cobra.Command, args []string) error { if logger.Fabulous { cmd.SetOutput(logger.FabulousWriter) } if viper.GetString(keyTrueColor) != "" { cmd.SetOutput(logger.FabulousWriter) } switch len(args) { case 0: return fmt.Errorf("shell argument is not specified") default: switch args[0] { case "bash": return runBashGeneration() case "zsh": return runZshGeneration() default: return fmt.Errorf("invalid shell argument") } } }, } }
[ "func", "CompletionCmd", "(", ")", "*", "cobra", ".", "Command", "{", "return", "&", "cobra", ".", "Command", "{", "Use", ":", "\"completion\"", ",", "Short", ":", "\"Generate completion code for bash and zsh shells.\"", ",", "Long", ":", "`completion is used to output completion code for bash and zsh shells.\t\tBefore using completion features, you have to source completion code\tfrom your .profile. This is done by adding following line to one of above files:\t\tsource <(kubicorn completion SHELL)\tValid arguments for SHELL are: \"bash\" and \"zsh\".\tNotes:\t1) zsh completions requires zsh 5.2 or newer.\t\t\t2) macOS users have to install bash-completion framework to utilize\tcompletion features. This can be done using homebrew:\t\tbrew install bash-completion\tOnce installed, you must load bash_completion by adding following\tline to your .profile or .bashrc/.zshrc:\t\tsource $(brew --prefix)/etc/bash_completion`", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "if", "logger", ".", "Fabulous", "{", "cmd", ".", "SetOutput", "(", "logger", ".", "FabulousWriter", ")", "\n", "}", "\n", "if", "viper", ".", "GetString", "(", "keyTrueColor", ")", "!=", "\"\"", "{", "cmd", ".", "SetOutput", "(", "logger", ".", "FabulousWriter", ")", "\n", "}", "\n", "switch", "len", "(", "args", ")", "{", "case", "0", ":", "return", "fmt", ".", "Errorf", "(", "\"shell argument is not specified\"", ")", "\n", "default", ":", "switch", "args", "[", "0", "]", "{", "case", "\"bash\"", ":", "return", "runBashGeneration", "(", ")", "\n", "case", "\"zsh\"", ":", "return", "runZshGeneration", "(", ")", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"invalid shell argument\"", ")", "\n", "}", "\n", "}", "\n", "}", ",", "}", "\n", "}" ]
// CompletionCmd represents the completion command
[ "CompletionCmd", "represents", "the", "completion", "command" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/completion.go#L44-L87
test
kubicorn/kubicorn
cmd/adopt.go
AdoptCmd
func AdoptCmd() *cobra.Command { return &cobra.Command{ Use: "adopt", Short: "Adopt a Kubernetes cluster into a Kubicorn state store", Long: `Use this command to audit and adopt a Kubernetes cluster into a Kubicorn state store. This command will query cloud resources and attempt to build a representation of the cluster in the Kubicorn API model. Once the cluster has been adopted, a user can manage and scale their Kubernetes cluster with Kubicorn.`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("adopt called") }, } }
go
func AdoptCmd() *cobra.Command { return &cobra.Command{ Use: "adopt", Short: "Adopt a Kubernetes cluster into a Kubicorn state store", Long: `Use this command to audit and adopt a Kubernetes cluster into a Kubicorn state store. This command will query cloud resources and attempt to build a representation of the cluster in the Kubicorn API model. Once the cluster has been adopted, a user can manage and scale their Kubernetes cluster with Kubicorn.`, Run: func(cmd *cobra.Command, args []string) { fmt.Println("adopt called") }, } }
[ "func", "AdoptCmd", "(", ")", "*", "cobra", ".", "Command", "{", "return", "&", "cobra", ".", "Command", "{", "Use", ":", "\"adopt\"", ",", "Short", ":", "\"Adopt a Kubernetes cluster into a Kubicorn state store\"", ",", "Long", ":", "`Use this command to audit and adopt a Kubernetes cluster into a Kubicorn state store.\t\tThis command will query cloud resources and attempt to build a representation of the cluster in the Kubicorn API model.\tOnce the cluster has been adopted, a user can manage and scale their Kubernetes cluster with Kubicorn.`", ",", "Run", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "fmt", ".", "Println", "(", "\"adopt called\"", ")", "\n", "}", ",", "}", "\n", "}" ]
// AdoptCmd represents the adopt command
[ "AdoptCmd", "represents", "the", "adopt", "command" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/adopt.go#L24-L36
test
kubicorn/kubicorn
pkg/cli/env.go
StrEnvDef
func StrEnvDef(env string, def string) string { val := os.Getenv(env) if val == "" { return def } return val }
go
func StrEnvDef(env string, def string) string { val := os.Getenv(env) if val == "" { return def } return val }
[ "func", "StrEnvDef", "(", "env", "string", ",", "def", "string", ")", "string", "{", "val", ":=", "os", ".", "Getenv", "(", "env", ")", "\n", "if", "val", "==", "\"\"", "{", "return", "def", "\n", "}", "\n", "return", "val", "\n", "}" ]
// StrEnvDef get environment variable, or some default def
[ "StrEnvDef", "get", "environment", "variable", "or", "some", "default", "def" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/cli/env.go#L23-L29
test
kubicorn/kubicorn
pkg/cli/env.go
IntEnvDef
func IntEnvDef(env string, def int) int { val := os.Getenv(env) if val == "" { return def } ival, err := strconv.Atoi(val) if err != nil { return def } return ival }
go
func IntEnvDef(env string, def int) int { val := os.Getenv(env) if val == "" { return def } ival, err := strconv.Atoi(val) if err != nil { return def } return ival }
[ "func", "IntEnvDef", "(", "env", "string", ",", "def", "int", ")", "int", "{", "val", ":=", "os", ".", "Getenv", "(", "env", ")", "\n", "if", "val", "==", "\"\"", "{", "return", "def", "\n", "}", "\n", "ival", ",", "err", ":=", "strconv", ".", "Atoi", "(", "val", ")", "\n", "if", "err", "!=", "nil", "{", "return", "def", "\n", "}", "\n", "return", "ival", "\n", "}" ]
// IntEnvDef get environment variable, or some default def
[ "IntEnvDef", "get", "environment", "variable", "or", "some", "default", "def" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/cli/env.go#L32-L42
test
kubicorn/kubicorn
pkg/cli/env.go
BoolEnvDef
func BoolEnvDef(env string, def bool) bool { val := os.Getenv(env) if val == "" { return def } b, err := strconv.ParseBool(val) if err != nil { return def } return b }
go
func BoolEnvDef(env string, def bool) bool { val := os.Getenv(env) if val == "" { return def } b, err := strconv.ParseBool(val) if err != nil { return def } return b }
[ "func", "BoolEnvDef", "(", "env", "string", ",", "def", "bool", ")", "bool", "{", "val", ":=", "os", ".", "Getenv", "(", "env", ")", "\n", "if", "val", "==", "\"\"", "{", "return", "def", "\n", "}", "\n", "b", ",", "err", ":=", "strconv", ".", "ParseBool", "(", "val", ")", "\n", "if", "err", "!=", "nil", "{", "return", "def", "\n", "}", "\n", "return", "b", "\n", "}" ]
// BoolEnvDef get environemnt variable and return bool.
[ "BoolEnvDef", "get", "environemnt", "variable", "and", "return", "bool", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/cli/env.go#L45-L55
test
kubicorn/kubicorn
pkg/parser/localresource.go
readFromFS
func readFromFS(sourcePath string) (string, error) { // If sourcePath starts with ~ we search for $HOME // and preppend it to the absolutePath overwriting the first character // TODO: Add Windows support if strings.HasPrefix(sourcePath, "~") { homeDir := os.Getenv("HOME") if homeDir == "" { return "", fmt.Errorf("Could not find $HOME") } sourcePath = filepath.Join(homeDir, sourcePath[1:]) } bytes, err := ioutil.ReadFile(sourcePath) if err != nil { return "", err } return string(bytes), nil }
go
func readFromFS(sourcePath string) (string, error) { // If sourcePath starts with ~ we search for $HOME // and preppend it to the absolutePath overwriting the first character // TODO: Add Windows support if strings.HasPrefix(sourcePath, "~") { homeDir := os.Getenv("HOME") if homeDir == "" { return "", fmt.Errorf("Could not find $HOME") } sourcePath = filepath.Join(homeDir, sourcePath[1:]) } bytes, err := ioutil.ReadFile(sourcePath) if err != nil { return "", err } return string(bytes), nil }
[ "func", "readFromFS", "(", "sourcePath", "string", ")", "(", "string", ",", "error", ")", "{", "if", "strings", ".", "HasPrefix", "(", "sourcePath", ",", "\"~\"", ")", "{", "homeDir", ":=", "os", ".", "Getenv", "(", "\"HOME\"", ")", "\n", "if", "homeDir", "==", "\"\"", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"Could not find $HOME\"", ")", "\n", "}", "\n", "sourcePath", "=", "filepath", ".", "Join", "(", "homeDir", ",", "sourcePath", "[", "1", ":", "]", ")", "\n", "}", "\n", "bytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "sourcePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "string", "(", "bytes", ")", ",", "nil", "\n", "}" ]
// readFromFS reads file from a local path and returns as string
[ "readFromFS", "reads", "file", "from", "a", "local", "path", "and", "returns", "as", "string" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/parser/localresource.go#L26-L44
test
kubicorn/kubicorn
cmd/version.go
VersionCmd
func VersionCmd() *cobra.Command { return &cobra.Command{ Use: "version", Short: "Verify Kubicorn version", Long: `Use this command to check the version of Kubicorn. This command will return the version of the Kubicorn binary.`, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("%s\n", version.GetVersionJSON()) }, } }
go
func VersionCmd() *cobra.Command { return &cobra.Command{ Use: "version", Short: "Verify Kubicorn version", Long: `Use this command to check the version of Kubicorn. This command will return the version of the Kubicorn binary.`, Run: func(cmd *cobra.Command, args []string) { fmt.Printf("%s\n", version.GetVersionJSON()) }, } }
[ "func", "VersionCmd", "(", ")", "*", "cobra", ".", "Command", "{", "return", "&", "cobra", ".", "Command", "{", "Use", ":", "\"version\"", ",", "Short", ":", "\"Verify Kubicorn version\"", ",", "Long", ":", "`Use this command to check the version of Kubicorn.\t\tThis command will return the version of the Kubicorn binary.`", ",", "Run", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "fmt", ".", "Printf", "(", "\"%s\\n\"", ",", "\\n", ")", "\n", "}", ",", "}", "\n", "}" ]
// VersionCmd represents the version command
[ "VersionCmd", "represents", "the", "version", "command" ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/cmd/version.go#L25-L36
test
kubicorn/kubicorn
pkg/signals/signals.go
NewSignalHandler
func NewSignalHandler(timeoutSeconds int) *Handler { signals := make(chan os.Signal) signal.Notify(signals, os.Interrupt, os.Kill) return &Handler{ timeoutSeconds: timeoutSeconds, signals: signals, signalReceived: 0, } }
go
func NewSignalHandler(timeoutSeconds int) *Handler { signals := make(chan os.Signal) signal.Notify(signals, os.Interrupt, os.Kill) return &Handler{ timeoutSeconds: timeoutSeconds, signals: signals, signalReceived: 0, } }
[ "func", "NewSignalHandler", "(", "timeoutSeconds", "int", ")", "*", "Handler", "{", "signals", ":=", "make", "(", "chan", "os", ".", "Signal", ")", "\n", "signal", ".", "Notify", "(", "signals", ",", "os", ".", "Interrupt", ",", "os", ".", "Kill", ")", "\n", "return", "&", "Handler", "{", "timeoutSeconds", ":", "timeoutSeconds", ",", "signals", ":", "signals", ",", "signalReceived", ":", "0", ",", "}", "\n", "}" ]
// NewSignalHandler creates a new Handler using given properties.
[ "NewSignalHandler", "creates", "a", "new", "Handler", "using", "given", "properties", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/signals/signals.go#L57-L65
test
kubicorn/kubicorn
pkg/signals/signals.go
Register
func (h *Handler) Register() { go func() { h.timer = time.NewTimer(time.Duration(h.timeoutSeconds) * time.Second) for { select { case s := <-h.signals: switch { case s == os.Interrupt: if h.signalReceived == 0 { h.signalReceived = 1 logger.Debug("SIGINT Received") continue } h.signalReceived = signalTerminate debug.PrintStack() os.Exit(130) break case s == syscall.SIGQUIT: h.signalReceived = signalAbort break case s == syscall.SIGTERM: h.signalReceived = signalTerminate os.Exit(3) break } case <-h.timer.C: os.Exit(4) break } } }() }
go
func (h *Handler) Register() { go func() { h.timer = time.NewTimer(time.Duration(h.timeoutSeconds) * time.Second) for { select { case s := <-h.signals: switch { case s == os.Interrupt: if h.signalReceived == 0 { h.signalReceived = 1 logger.Debug("SIGINT Received") continue } h.signalReceived = signalTerminate debug.PrintStack() os.Exit(130) break case s == syscall.SIGQUIT: h.signalReceived = signalAbort break case s == syscall.SIGTERM: h.signalReceived = signalTerminate os.Exit(3) break } case <-h.timer.C: os.Exit(4) break } } }() }
[ "func", "(", "h", "*", "Handler", ")", "Register", "(", ")", "{", "go", "func", "(", ")", "{", "h", ".", "timer", "=", "time", ".", "NewTimer", "(", "time", ".", "Duration", "(", "h", ".", "timeoutSeconds", ")", "*", "time", ".", "Second", ")", "\n", "for", "{", "select", "{", "case", "s", ":=", "<-", "h", ".", "signals", ":", "switch", "{", "case", "s", "==", "os", ".", "Interrupt", ":", "if", "h", ".", "signalReceived", "==", "0", "{", "h", ".", "signalReceived", "=", "1", "\n", "logger", ".", "Debug", "(", "\"SIGINT Received\"", ")", "\n", "continue", "\n", "}", "\n", "h", ".", "signalReceived", "=", "signalTerminate", "\n", "debug", ".", "PrintStack", "(", ")", "\n", "os", ".", "Exit", "(", "130", ")", "\n", "break", "\n", "case", "s", "==", "syscall", ".", "SIGQUIT", ":", "h", ".", "signalReceived", "=", "signalAbort", "\n", "break", "\n", "case", "s", "==", "syscall", ".", "SIGTERM", ":", "h", ".", "signalReceived", "=", "signalTerminate", "\n", "os", ".", "Exit", "(", "3", ")", "\n", "break", "\n", "}", "\n", "case", "<-", "h", ".", "timer", ".", "C", ":", "os", ".", "Exit", "(", "4", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// Register starts handling signals.
[ "Register", "starts", "handling", "signals", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/pkg/signals/signals.go#L79-L111
test
kubicorn/kubicorn
profiles/openstack/ecs/ubuntu_16_04.go
NewUbuntuCluster
func NewUbuntuCluster(name string) *cluster.Cluster { var ( masterName = fmt.Sprintf("%s-master", name) nodeName = fmt.Sprintf("%s-node", name) ) controlPlaneProviderConfig := &cluster.ControlPlaneProviderConfig{ Cloud: cluster.CloudECS, Location: "nl-ams1", SSH: &cluster.SSH{ PublicKeyPath: "~/.ssh/id_rsa.pub", User: "ubuntu", }, Values: &cluster.Values{ ItemMap: map[string]string{ "INJECTEDTOKEN": kubeadm.GetRandomToken(), }, }, KubernetesAPI: &cluster.KubernetesAPI{ Port: "443", }, Network: &cluster.Network{ Type: cluster.NetworkTypePublic, InternetGW: &cluster.InternetGW{ Name: "default", }, }, } machineSetsProviderConfigs := []*cluster.MachineProviderConfig{ { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeMaster, Name: masterName, MaxCount: 1, Image: "GNU/Linux Ubuntu Server 16.04 Xenial Xerus x64", Size: "e3standard.x3", BootstrapScripts: []string{ "bootstrap/ecs_k8s_ubuntu_16.04_master.sh", }, Subnets: []*cluster.Subnet{ { Name: "internal", CIDR: "192.168.200.0/24", }, }, Firewalls: []*cluster.Firewall{ { Name: masterName, IngressRules: []*cluster.IngressRule{ { IngressFromPort: "22", IngressToPort: "22", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressFromPort: "443", IngressToPort: "443", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressSource: "192.168.200.0/24", }, }, }, }, }, }, { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeNode, Name: nodeName, MaxCount: 2, Image: "GNU/Linux Ubuntu Server 16.04 Xenial Xerus x64", Size: "e3standard.x3", BootstrapScripts: []string{ "bootstrap/ecs_k8s_ubuntu_16.04_node.sh", }, Firewalls: []*cluster.Firewall{ { Name: nodeName, IngressRules: []*cluster.IngressRule{ { IngressFromPort: "22", IngressToPort: "22", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressSource: "192.168.200.0/24", }, }, }, }, }, }, } c := cluster.NewCluster(name) c.SetProviderConfig(controlPlaneProviderConfig) c.NewMachineSetsFromProviderConfigs(machineSetsProviderConfigs) return c }
go
func NewUbuntuCluster(name string) *cluster.Cluster { var ( masterName = fmt.Sprintf("%s-master", name) nodeName = fmt.Sprintf("%s-node", name) ) controlPlaneProviderConfig := &cluster.ControlPlaneProviderConfig{ Cloud: cluster.CloudECS, Location: "nl-ams1", SSH: &cluster.SSH{ PublicKeyPath: "~/.ssh/id_rsa.pub", User: "ubuntu", }, Values: &cluster.Values{ ItemMap: map[string]string{ "INJECTEDTOKEN": kubeadm.GetRandomToken(), }, }, KubernetesAPI: &cluster.KubernetesAPI{ Port: "443", }, Network: &cluster.Network{ Type: cluster.NetworkTypePublic, InternetGW: &cluster.InternetGW{ Name: "default", }, }, } machineSetsProviderConfigs := []*cluster.MachineProviderConfig{ { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeMaster, Name: masterName, MaxCount: 1, Image: "GNU/Linux Ubuntu Server 16.04 Xenial Xerus x64", Size: "e3standard.x3", BootstrapScripts: []string{ "bootstrap/ecs_k8s_ubuntu_16.04_master.sh", }, Subnets: []*cluster.Subnet{ { Name: "internal", CIDR: "192.168.200.0/24", }, }, Firewalls: []*cluster.Firewall{ { Name: masterName, IngressRules: []*cluster.IngressRule{ { IngressFromPort: "22", IngressToPort: "22", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressFromPort: "443", IngressToPort: "443", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressSource: "192.168.200.0/24", }, }, }, }, }, }, { ServerPool: &cluster.ServerPool{ Type: cluster.ServerPoolTypeNode, Name: nodeName, MaxCount: 2, Image: "GNU/Linux Ubuntu Server 16.04 Xenial Xerus x64", Size: "e3standard.x3", BootstrapScripts: []string{ "bootstrap/ecs_k8s_ubuntu_16.04_node.sh", }, Firewalls: []*cluster.Firewall{ { Name: nodeName, IngressRules: []*cluster.IngressRule{ { IngressFromPort: "22", IngressToPort: "22", IngressSource: "0.0.0.0/0", IngressProtocol: "tcp", }, { IngressSource: "192.168.200.0/24", }, }, }, }, }, }, } c := cluster.NewCluster(name) c.SetProviderConfig(controlPlaneProviderConfig) c.NewMachineSetsFromProviderConfigs(machineSetsProviderConfigs) return c }
[ "func", "NewUbuntuCluster", "(", "name", "string", ")", "*", "cluster", ".", "Cluster", "{", "var", "(", "masterName", "=", "fmt", ".", "Sprintf", "(", "\"%s-master\"", ",", "name", ")", "\n", "nodeName", "=", "fmt", ".", "Sprintf", "(", "\"%s-node\"", ",", "name", ")", "\n", ")", "\n", "controlPlaneProviderConfig", ":=", "&", "cluster", ".", "ControlPlaneProviderConfig", "{", "Cloud", ":", "cluster", ".", "CloudECS", ",", "Location", ":", "\"nl-ams1\"", ",", "SSH", ":", "&", "cluster", ".", "SSH", "{", "PublicKeyPath", ":", "\"~/.ssh/id_rsa.pub\"", ",", "User", ":", "\"ubuntu\"", ",", "}", ",", "Values", ":", "&", "cluster", ".", "Values", "{", "ItemMap", ":", "map", "[", "string", "]", "string", "{", "\"INJECTEDTOKEN\"", ":", "kubeadm", ".", "GetRandomToken", "(", ")", ",", "}", ",", "}", ",", "KubernetesAPI", ":", "&", "cluster", ".", "KubernetesAPI", "{", "Port", ":", "\"443\"", ",", "}", ",", "Network", ":", "&", "cluster", ".", "Network", "{", "Type", ":", "cluster", ".", "NetworkTypePublic", ",", "InternetGW", ":", "&", "cluster", ".", "InternetGW", "{", "Name", ":", "\"default\"", ",", "}", ",", "}", ",", "}", "\n", "machineSetsProviderConfigs", ":=", "[", "]", "*", "cluster", ".", "MachineProviderConfig", "{", "{", "ServerPool", ":", "&", "cluster", ".", "ServerPool", "{", "Type", ":", "cluster", ".", "ServerPoolTypeMaster", ",", "Name", ":", "masterName", ",", "MaxCount", ":", "1", ",", "Image", ":", "\"GNU/Linux Ubuntu Server 16.04 Xenial Xerus x64\"", ",", "Size", ":", "\"e3standard.x3\"", ",", "BootstrapScripts", ":", "[", "]", "string", "{", "\"bootstrap/ecs_k8s_ubuntu_16.04_master.sh\"", ",", "}", ",", "Subnets", ":", "[", "]", "*", "cluster", ".", "Subnet", "{", "{", "Name", ":", "\"internal\"", ",", "CIDR", ":", "\"192.168.200.0/24\"", ",", "}", ",", "}", ",", "Firewalls", ":", "[", "]", "*", "cluster", ".", "Firewall", "{", "{", "Name", ":", "masterName", ",", "IngressRules", ":", "[", "]", "*", "cluster", ".", "IngressRule", "{", "{", "IngressFromPort", ":", "\"22\"", ",", "IngressToPort", ":", "\"22\"", ",", "IngressSource", ":", "\"0.0.0.0/0\"", ",", "IngressProtocol", ":", "\"tcp\"", ",", "}", ",", "{", "IngressFromPort", ":", "\"443\"", ",", "IngressToPort", ":", "\"443\"", ",", "IngressSource", ":", "\"0.0.0.0/0\"", ",", "IngressProtocol", ":", "\"tcp\"", ",", "}", ",", "{", "IngressSource", ":", "\"192.168.200.0/24\"", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "{", "ServerPool", ":", "&", "cluster", ".", "ServerPool", "{", "Type", ":", "cluster", ".", "ServerPoolTypeNode", ",", "Name", ":", "nodeName", ",", "MaxCount", ":", "2", ",", "Image", ":", "\"GNU/Linux Ubuntu Server 16.04 Xenial Xerus x64\"", ",", "Size", ":", "\"e3standard.x3\"", ",", "BootstrapScripts", ":", "[", "]", "string", "{", "\"bootstrap/ecs_k8s_ubuntu_16.04_node.sh\"", ",", "}", ",", "Firewalls", ":", "[", "]", "*", "cluster", ".", "Firewall", "{", "{", "Name", ":", "nodeName", ",", "IngressRules", ":", "[", "]", "*", "cluster", ".", "IngressRule", "{", "{", "IngressFromPort", ":", "\"22\"", ",", "IngressToPort", ":", "\"22\"", ",", "IngressSource", ":", "\"0.0.0.0/0\"", ",", "IngressProtocol", ":", "\"tcp\"", ",", "}", ",", "{", "IngressSource", ":", "\"192.168.200.0/24\"", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", ",", "}", "\n", "c", ":=", "cluster", ".", "NewCluster", "(", "name", ")", "\n", "c", ".", "SetProviderConfig", "(", "controlPlaneProviderConfig", ")", "\n", "c", ".", "NewMachineSetsFromProviderConfigs", "(", "machineSetsProviderConfigs", ")", "\n", "return", "c", "\n", "}" ]
// NewUbuntuCluster creates a simple Ubuntu Openstack cluster.
[ "NewUbuntuCluster", "creates", "a", "simple", "Ubuntu", "Openstack", "cluster", "." ]
c4a4b80994b4333709c0f8164faabd801866b986
https://github.com/kubicorn/kubicorn/blob/c4a4b80994b4333709c0f8164faabd801866b986/profiles/openstack/ecs/ubuntu_16_04.go#L25-L126
test
jinzhu/now
now.go
BeginningOfHour
func (now *Now) BeginningOfHour() time.Time { y, m, d := now.Date() return time.Date(y, m, d, now.Time.Hour(), 0, 0, 0, now.Time.Location()) }
go
func (now *Now) BeginningOfHour() time.Time { y, m, d := now.Date() return time.Date(y, m, d, now.Time.Hour(), 0, 0, 0, now.Time.Location()) }
[ "func", "(", "now", "*", "Now", ")", "BeginningOfHour", "(", ")", "time", ".", "Time", "{", "y", ",", "m", ",", "d", ":=", "now", ".", "Date", "(", ")", "\n", "return", "time", ".", "Date", "(", "y", ",", "m", ",", "d", ",", "now", ".", "Time", ".", "Hour", "(", ")", ",", "0", ",", "0", ",", "0", ",", "now", ".", "Time", ".", "Location", "(", ")", ")", "\n", "}" ]
// BeginningOfHour beginning of hour
[ "BeginningOfHour", "beginning", "of", "hour" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L15-L18
test
jinzhu/now
now.go
BeginningOfDay
func (now *Now) BeginningOfDay() time.Time { y, m, d := now.Date() return time.Date(y, m, d, 0, 0, 0, 0, now.Time.Location()) }
go
func (now *Now) BeginningOfDay() time.Time { y, m, d := now.Date() return time.Date(y, m, d, 0, 0, 0, 0, now.Time.Location()) }
[ "func", "(", "now", "*", "Now", ")", "BeginningOfDay", "(", ")", "time", ".", "Time", "{", "y", ",", "m", ",", "d", ":=", "now", ".", "Date", "(", ")", "\n", "return", "time", ".", "Date", "(", "y", ",", "m", ",", "d", ",", "0", ",", "0", ",", "0", ",", "0", ",", "now", ".", "Time", ".", "Location", "(", ")", ")", "\n", "}" ]
// BeginningOfDay beginning of day
[ "BeginningOfDay", "beginning", "of", "day" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L21-L24
test
jinzhu/now
now.go
BeginningOfWeek
func (now *Now) BeginningOfWeek() time.Time { t := now.BeginningOfDay() weekday := int(t.Weekday()) if WeekStartDay != time.Sunday { weekStartDayInt := int(WeekStartDay) if weekday < weekStartDayInt { weekday = weekday + 7 - weekStartDayInt } else { weekday = weekday - weekStartDayInt } } return t.AddDate(0, 0, -weekday) }
go
func (now *Now) BeginningOfWeek() time.Time { t := now.BeginningOfDay() weekday := int(t.Weekday()) if WeekStartDay != time.Sunday { weekStartDayInt := int(WeekStartDay) if weekday < weekStartDayInt { weekday = weekday + 7 - weekStartDayInt } else { weekday = weekday - weekStartDayInt } } return t.AddDate(0, 0, -weekday) }
[ "func", "(", "now", "*", "Now", ")", "BeginningOfWeek", "(", ")", "time", ".", "Time", "{", "t", ":=", "now", ".", "BeginningOfDay", "(", ")", "\n", "weekday", ":=", "int", "(", "t", ".", "Weekday", "(", ")", ")", "\n", "if", "WeekStartDay", "!=", "time", ".", "Sunday", "{", "weekStartDayInt", ":=", "int", "(", "WeekStartDay", ")", "\n", "if", "weekday", "<", "weekStartDayInt", "{", "weekday", "=", "weekday", "+", "7", "-", "weekStartDayInt", "\n", "}", "else", "{", "weekday", "=", "weekday", "-", "weekStartDayInt", "\n", "}", "\n", "}", "\n", "return", "t", ".", "AddDate", "(", "0", ",", "0", ",", "-", "weekday", ")", "\n", "}" ]
// BeginningOfWeek beginning of week
[ "BeginningOfWeek", "beginning", "of", "week" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L27-L41
test
jinzhu/now
now.go
BeginningOfMonth
func (now *Now) BeginningOfMonth() time.Time { y, m, _ := now.Date() return time.Date(y, m, 1, 0, 0, 0, 0, now.Location()) }
go
func (now *Now) BeginningOfMonth() time.Time { y, m, _ := now.Date() return time.Date(y, m, 1, 0, 0, 0, 0, now.Location()) }
[ "func", "(", "now", "*", "Now", ")", "BeginningOfMonth", "(", ")", "time", ".", "Time", "{", "y", ",", "m", ",", "_", ":=", "now", ".", "Date", "(", ")", "\n", "return", "time", ".", "Date", "(", "y", ",", "m", ",", "1", ",", "0", ",", "0", ",", "0", ",", "0", ",", "now", ".", "Location", "(", ")", ")", "\n", "}" ]
// BeginningOfMonth beginning of month
[ "BeginningOfMonth", "beginning", "of", "month" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L44-L47
test
jinzhu/now
now.go
BeginningOfQuarter
func (now *Now) BeginningOfQuarter() time.Time { month := now.BeginningOfMonth() offset := (int(month.Month()) - 1) % 3 return month.AddDate(0, -offset, 0) }
go
func (now *Now) BeginningOfQuarter() time.Time { month := now.BeginningOfMonth() offset := (int(month.Month()) - 1) % 3 return month.AddDate(0, -offset, 0) }
[ "func", "(", "now", "*", "Now", ")", "BeginningOfQuarter", "(", ")", "time", ".", "Time", "{", "month", ":=", "now", ".", "BeginningOfMonth", "(", ")", "\n", "offset", ":=", "(", "int", "(", "month", ".", "Month", "(", ")", ")", "-", "1", ")", "%", "3", "\n", "return", "month", ".", "AddDate", "(", "0", ",", "-", "offset", ",", "0", ")", "\n", "}" ]
// BeginningOfQuarter beginning of quarter
[ "BeginningOfQuarter", "beginning", "of", "quarter" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L50-L54
test
jinzhu/now
now.go
BeginningOfYear
func (now *Now) BeginningOfYear() time.Time { y, _, _ := now.Date() return time.Date(y, time.January, 1, 0, 0, 0, 0, now.Location()) }
go
func (now *Now) BeginningOfYear() time.Time { y, _, _ := now.Date() return time.Date(y, time.January, 1, 0, 0, 0, 0, now.Location()) }
[ "func", "(", "now", "*", "Now", ")", "BeginningOfYear", "(", ")", "time", ".", "Time", "{", "y", ",", "_", ",", "_", ":=", "now", ".", "Date", "(", ")", "\n", "return", "time", ".", "Date", "(", "y", ",", "time", ".", "January", ",", "1", ",", "0", ",", "0", ",", "0", ",", "0", ",", "now", ".", "Location", "(", ")", ")", "\n", "}" ]
// BeginningOfYear BeginningOfYear beginning of year
[ "BeginningOfYear", "BeginningOfYear", "beginning", "of", "year" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L57-L60
test
jinzhu/now
now.go
EndOfMinute
func (now *Now) EndOfMinute() time.Time { return now.BeginningOfMinute().Add(time.Minute - time.Nanosecond) }
go
func (now *Now) EndOfMinute() time.Time { return now.BeginningOfMinute().Add(time.Minute - time.Nanosecond) }
[ "func", "(", "now", "*", "Now", ")", "EndOfMinute", "(", ")", "time", ".", "Time", "{", "return", "now", ".", "BeginningOfMinute", "(", ")", ".", "Add", "(", "time", ".", "Minute", "-", "time", ".", "Nanosecond", ")", "\n", "}" ]
// EndOfMinute end of minute
[ "EndOfMinute", "end", "of", "minute" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L63-L65
test
jinzhu/now
now.go
EndOfHour
func (now *Now) EndOfHour() time.Time { return now.BeginningOfHour().Add(time.Hour - time.Nanosecond) }
go
func (now *Now) EndOfHour() time.Time { return now.BeginningOfHour().Add(time.Hour - time.Nanosecond) }
[ "func", "(", "now", "*", "Now", ")", "EndOfHour", "(", ")", "time", ".", "Time", "{", "return", "now", ".", "BeginningOfHour", "(", ")", ".", "Add", "(", "time", ".", "Hour", "-", "time", ".", "Nanosecond", ")", "\n", "}" ]
// EndOfHour end of hour
[ "EndOfHour", "end", "of", "hour" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L68-L70
test
jinzhu/now
now.go
EndOfDay
func (now *Now) EndOfDay() time.Time { y, m, d := now.Date() return time.Date(y, m, d, 23, 59, 59, int(time.Second-time.Nanosecond), now.Location()) }
go
func (now *Now) EndOfDay() time.Time { y, m, d := now.Date() return time.Date(y, m, d, 23, 59, 59, int(time.Second-time.Nanosecond), now.Location()) }
[ "func", "(", "now", "*", "Now", ")", "EndOfDay", "(", ")", "time", ".", "Time", "{", "y", ",", "m", ",", "d", ":=", "now", ".", "Date", "(", ")", "\n", "return", "time", ".", "Date", "(", "y", ",", "m", ",", "d", ",", "23", ",", "59", ",", "59", ",", "int", "(", "time", ".", "Second", "-", "time", ".", "Nanosecond", ")", ",", "now", ".", "Location", "(", ")", ")", "\n", "}" ]
// EndOfDay end of day
[ "EndOfDay", "end", "of", "day" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L73-L76
test
jinzhu/now
now.go
EndOfWeek
func (now *Now) EndOfWeek() time.Time { return now.BeginningOfWeek().AddDate(0, 0, 7).Add(-time.Nanosecond) }
go
func (now *Now) EndOfWeek() time.Time { return now.BeginningOfWeek().AddDate(0, 0, 7).Add(-time.Nanosecond) }
[ "func", "(", "now", "*", "Now", ")", "EndOfWeek", "(", ")", "time", ".", "Time", "{", "return", "now", ".", "BeginningOfWeek", "(", ")", ".", "AddDate", "(", "0", ",", "0", ",", "7", ")", ".", "Add", "(", "-", "time", ".", "Nanosecond", ")", "\n", "}" ]
// EndOfWeek end of week
[ "EndOfWeek", "end", "of", "week" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L79-L81
test
jinzhu/now
now.go
EndOfMonth
func (now *Now) EndOfMonth() time.Time { return now.BeginningOfMonth().AddDate(0, 1, 0).Add(-time.Nanosecond) }
go
func (now *Now) EndOfMonth() time.Time { return now.BeginningOfMonth().AddDate(0, 1, 0).Add(-time.Nanosecond) }
[ "func", "(", "now", "*", "Now", ")", "EndOfMonth", "(", ")", "time", ".", "Time", "{", "return", "now", ".", "BeginningOfMonth", "(", ")", ".", "AddDate", "(", "0", ",", "1", ",", "0", ")", ".", "Add", "(", "-", "time", ".", "Nanosecond", ")", "\n", "}" ]
// EndOfMonth end of month
[ "EndOfMonth", "end", "of", "month" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L84-L86
test
jinzhu/now
now.go
EndOfQuarter
func (now *Now) EndOfQuarter() time.Time { return now.BeginningOfQuarter().AddDate(0, 3, 0).Add(-time.Nanosecond) }
go
func (now *Now) EndOfQuarter() time.Time { return now.BeginningOfQuarter().AddDate(0, 3, 0).Add(-time.Nanosecond) }
[ "func", "(", "now", "*", "Now", ")", "EndOfQuarter", "(", ")", "time", ".", "Time", "{", "return", "now", ".", "BeginningOfQuarter", "(", ")", ".", "AddDate", "(", "0", ",", "3", ",", "0", ")", ".", "Add", "(", "-", "time", ".", "Nanosecond", ")", "\n", "}" ]
// EndOfQuarter end of quarter
[ "EndOfQuarter", "end", "of", "quarter" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L89-L91
test
jinzhu/now
now.go
EndOfYear
func (now *Now) EndOfYear() time.Time { return now.BeginningOfYear().AddDate(1, 0, 0).Add(-time.Nanosecond) }
go
func (now *Now) EndOfYear() time.Time { return now.BeginningOfYear().AddDate(1, 0, 0).Add(-time.Nanosecond) }
[ "func", "(", "now", "*", "Now", ")", "EndOfYear", "(", ")", "time", ".", "Time", "{", "return", "now", ".", "BeginningOfYear", "(", ")", ".", "AddDate", "(", "1", ",", "0", ",", "0", ")", ".", "Add", "(", "-", "time", ".", "Nanosecond", ")", "\n", "}" ]
// EndOfYear end of year
[ "EndOfYear", "end", "of", "year" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L94-L96
test
jinzhu/now
now.go
MustParse
func (now *Now) MustParse(strs ...string) (t time.Time) { t, err := now.Parse(strs...) if err != nil { panic(err) } return t }
go
func (now *Now) MustParse(strs ...string) (t time.Time) { t, err := now.Parse(strs...) if err != nil { panic(err) } return t }
[ "func", "(", "now", "*", "Now", ")", "MustParse", "(", "strs", "...", "string", ")", "(", "t", "time", ".", "Time", ")", "{", "t", ",", "err", ":=", "now", ".", "Parse", "(", "strs", "...", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "t", "\n", "}" ]
// MustParse must parse string to time or it will panic
[ "MustParse", "must", "parse", "string", "to", "time", "or", "it", "will", "panic" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L190-L196
test
jinzhu/now
now.go
Between
func (now *Now) Between(begin, end string) bool { beginTime := now.MustParse(begin) endTime := now.MustParse(end) return now.After(beginTime) && now.Before(endTime) }
go
func (now *Now) Between(begin, end string) bool { beginTime := now.MustParse(begin) endTime := now.MustParse(end) return now.After(beginTime) && now.Before(endTime) }
[ "func", "(", "now", "*", "Now", ")", "Between", "(", "begin", ",", "end", "string", ")", "bool", "{", "beginTime", ":=", "now", ".", "MustParse", "(", "begin", ")", "\n", "endTime", ":=", "now", ".", "MustParse", "(", "end", ")", "\n", "return", "now", ".", "After", "(", "beginTime", ")", "&&", "now", ".", "Before", "(", "endTime", ")", "\n", "}" ]
// Between check time between the begin, end time or not
[ "Between", "check", "time", "between", "the", "begin", "end", "time", "or", "not" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/now.go#L199-L203
test
jinzhu/now
main.go
ParseInLocation
func ParseInLocation(loc *time.Location, strs ...string) (time.Time, error) { return New(time.Now().In(loc)).Parse(strs...) }
go
func ParseInLocation(loc *time.Location, strs ...string) (time.Time, error) { return New(time.Now().In(loc)).Parse(strs...) }
[ "func", "ParseInLocation", "(", "loc", "*", "time", ".", "Location", ",", "strs", "...", "string", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "return", "New", "(", "time", ".", "Now", "(", ")", ".", "In", "(", "loc", ")", ")", ".", "Parse", "(", "strs", "...", ")", "\n", "}" ]
// ParseInLocation parse string to time in location
[ "ParseInLocation", "parse", "string", "to", "time", "in", "location" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/main.go#L121-L123
test
jinzhu/now
main.go
MustParse
func MustParse(strs ...string) time.Time { return New(time.Now()).MustParse(strs...) }
go
func MustParse(strs ...string) time.Time { return New(time.Now()).MustParse(strs...) }
[ "func", "MustParse", "(", "strs", "...", "string", ")", "time", ".", "Time", "{", "return", "New", "(", "time", ".", "Now", "(", ")", ")", ".", "MustParse", "(", "strs", "...", ")", "\n", "}" ]
// MustParse must parse string to time or will panic
[ "MustParse", "must", "parse", "string", "to", "time", "or", "will", "panic" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/main.go#L126-L128
test
jinzhu/now
main.go
MustParseInLocation
func MustParseInLocation(loc *time.Location, strs ...string) time.Time { return New(time.Now().In(loc)).MustParse(strs...) }
go
func MustParseInLocation(loc *time.Location, strs ...string) time.Time { return New(time.Now().In(loc)).MustParse(strs...) }
[ "func", "MustParseInLocation", "(", "loc", "*", "time", ".", "Location", ",", "strs", "...", "string", ")", "time", ".", "Time", "{", "return", "New", "(", "time", ".", "Now", "(", ")", ".", "In", "(", "loc", ")", ")", ".", "MustParse", "(", "strs", "...", ")", "\n", "}" ]
// MustParseInLocation must parse string to time in location or will panic
[ "MustParseInLocation", "must", "parse", "string", "to", "time", "in", "location", "or", "will", "panic" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/main.go#L131-L133
test
jinzhu/now
main.go
Between
func Between(time1, time2 string) bool { return New(time.Now()).Between(time1, time2) }
go
func Between(time1, time2 string) bool { return New(time.Now()).Between(time1, time2) }
[ "func", "Between", "(", "time1", ",", "time2", "string", ")", "bool", "{", "return", "New", "(", "time", ".", "Now", "(", ")", ")", ".", "Between", "(", "time1", ",", "time2", ")", "\n", "}" ]
// Between check now between the begin, end time or not
[ "Between", "check", "now", "between", "the", "begin", "end", "time", "or", "not" ]
8ec929ed50c3ac25ce77ba4486e1f277c552c591
https://github.com/jinzhu/now/blob/8ec929ed50c3ac25ce77ba4486e1f277c552c591/main.go#L136-L138
test
op/go-logging
memory.go
NewChannelMemoryBackend
func NewChannelMemoryBackend(size int) *ChannelMemoryBackend { backend := &ChannelMemoryBackend{ maxSize: size, incoming: make(chan *Record, 1024), events: make(chan event), } backend.Start() return backend }
go
func NewChannelMemoryBackend(size int) *ChannelMemoryBackend { backend := &ChannelMemoryBackend{ maxSize: size, incoming: make(chan *Record, 1024), events: make(chan event), } backend.Start() return backend }
[ "func", "NewChannelMemoryBackend", "(", "size", "int", ")", "*", "ChannelMemoryBackend", "{", "backend", ":=", "&", "ChannelMemoryBackend", "{", "maxSize", ":", "size", ",", "incoming", ":", "make", "(", "chan", "*", "Record", ",", "1024", ")", ",", "events", ":", "make", "(", "chan", "event", ")", ",", "}", "\n", "backend", ".", "Start", "(", ")", "\n", "return", "backend", "\n", "}" ]
// NewChannelMemoryBackend creates a simple in-memory logging backend which // utilizes a go channel for communication. // // Start will automatically be called by this function.
[ "NewChannelMemoryBackend", "creates", "a", "simple", "in", "-", "memory", "logging", "backend", "which", "utilizes", "a", "go", "channel", "for", "communication", ".", "Start", "will", "automatically", "be", "called", "by", "this", "function", "." ]
970db520ece77730c7e4724c61121037378659d9
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/memory.go#L146-L154
test
op/go-logging
memory.go
Start
func (b *ChannelMemoryBackend) Start() { b.mu.Lock() defer b.mu.Unlock() // Launch the goroutine unless it's already running. if b.running != true { b.running = true b.stopWg.Add(1) go b.process() } }
go
func (b *ChannelMemoryBackend) Start() { b.mu.Lock() defer b.mu.Unlock() // Launch the goroutine unless it's already running. if b.running != true { b.running = true b.stopWg.Add(1) go b.process() } }
[ "func", "(", "b", "*", "ChannelMemoryBackend", ")", "Start", "(", ")", "{", "b", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "b", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "b", ".", "running", "!=", "true", "{", "b", ".", "running", "=", "true", "\n", "b", ".", "stopWg", ".", "Add", "(", "1", ")", "\n", "go", "b", ".", "process", "(", ")", "\n", "}", "\n", "}" ]
// Start launches the internal goroutine which starts processing data from the // input channel.
[ "Start", "launches", "the", "internal", "goroutine", "which", "starts", "processing", "data", "from", "the", "input", "channel", "." ]
970db520ece77730c7e4724c61121037378659d9
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/memory.go#L158-L168
test
op/go-logging
memory.go
Flush
func (b *ChannelMemoryBackend) Flush() { b.flushWg.Add(1) b.events <- eventFlush b.flushWg.Wait() }
go
func (b *ChannelMemoryBackend) Flush() { b.flushWg.Add(1) b.events <- eventFlush b.flushWg.Wait() }
[ "func", "(", "b", "*", "ChannelMemoryBackend", ")", "Flush", "(", ")", "{", "b", ".", "flushWg", ".", "Add", "(", "1", ")", "\n", "b", ".", "events", "<-", "eventFlush", "\n", "b", ".", "flushWg", ".", "Wait", "(", ")", "\n", "}" ]
// Flush waits until all records in the buffered channel have been processed.
[ "Flush", "waits", "until", "all", "records", "in", "the", "buffered", "channel", "have", "been", "processed", "." ]
970db520ece77730c7e4724c61121037378659d9
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/memory.go#L207-L211
test
op/go-logging
memory.go
Stop
func (b *ChannelMemoryBackend) Stop() { b.mu.Lock() if b.running == true { b.running = false b.events <- eventStop } b.mu.Unlock() b.stopWg.Wait() }
go
func (b *ChannelMemoryBackend) Stop() { b.mu.Lock() if b.running == true { b.running = false b.events <- eventStop } b.mu.Unlock() b.stopWg.Wait() }
[ "func", "(", "b", "*", "ChannelMemoryBackend", ")", "Stop", "(", ")", "{", "b", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "b", ".", "running", "==", "true", "{", "b", ".", "running", "=", "false", "\n", "b", ".", "events", "<-", "eventStop", "\n", "}", "\n", "b", ".", "mu", ".", "Unlock", "(", ")", "\n", "b", ".", "stopWg", ".", "Wait", "(", ")", "\n", "}" ]
// Stop signals the internal goroutine to exit and waits until it have.
[ "Stop", "signals", "the", "internal", "goroutine", "to", "exit", "and", "waits", "until", "it", "have", "." ]
970db520ece77730c7e4724c61121037378659d9
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/memory.go#L214-L222
test
op/go-logging
logger.go
Formatted
func (r *Record) Formatted(calldepth int) string { if r.formatted == "" { var buf bytes.Buffer r.formatter.Format(calldepth+1, r, &buf) r.formatted = buf.String() } return r.formatted }
go
func (r *Record) Formatted(calldepth int) string { if r.formatted == "" { var buf bytes.Buffer r.formatter.Format(calldepth+1, r, &buf) r.formatted = buf.String() } return r.formatted }
[ "func", "(", "r", "*", "Record", ")", "Formatted", "(", "calldepth", "int", ")", "string", "{", "if", "r", ".", "formatted", "==", "\"\"", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "r", ".", "formatter", ".", "Format", "(", "calldepth", "+", "1", ",", "r", ",", "&", "buf", ")", "\n", "r", ".", "formatted", "=", "buf", ".", "String", "(", ")", "\n", "}", "\n", "return", "r", ".", "formatted", "\n", "}" ]
// Formatted returns the formatted log record string.
[ "Formatted", "returns", "the", "formatted", "log", "record", "string", "." ]
970db520ece77730c7e4724c61121037378659d9
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/logger.go#L59-L66
test
op/go-logging
logger.go
Message
func (r *Record) Message() string { if r.message == nil { // Redact the arguments that implements the Redactor interface for i, arg := range r.Args { if redactor, ok := arg.(Redactor); ok == true { r.Args[i] = redactor.Redacted() } } var buf bytes.Buffer if r.fmt != nil { fmt.Fprintf(&buf, *r.fmt, r.Args...) } else { // use Fprintln to make sure we always get space between arguments fmt.Fprintln(&buf, r.Args...) buf.Truncate(buf.Len() - 1) // strip newline } msg := buf.String() r.message = &msg } return *r.message }
go
func (r *Record) Message() string { if r.message == nil { // Redact the arguments that implements the Redactor interface for i, arg := range r.Args { if redactor, ok := arg.(Redactor); ok == true { r.Args[i] = redactor.Redacted() } } var buf bytes.Buffer if r.fmt != nil { fmt.Fprintf(&buf, *r.fmt, r.Args...) } else { // use Fprintln to make sure we always get space between arguments fmt.Fprintln(&buf, r.Args...) buf.Truncate(buf.Len() - 1) // strip newline } msg := buf.String() r.message = &msg } return *r.message }
[ "func", "(", "r", "*", "Record", ")", "Message", "(", ")", "string", "{", "if", "r", ".", "message", "==", "nil", "{", "for", "i", ",", "arg", ":=", "range", "r", ".", "Args", "{", "if", "redactor", ",", "ok", ":=", "arg", ".", "(", "Redactor", ")", ";", "ok", "==", "true", "{", "r", ".", "Args", "[", "i", "]", "=", "redactor", ".", "Redacted", "(", ")", "\n", "}", "\n", "}", "\n", "var", "buf", "bytes", ".", "Buffer", "\n", "if", "r", ".", "fmt", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "*", "r", ".", "fmt", ",", "r", ".", "Args", "...", ")", "\n", "}", "else", "{", "fmt", ".", "Fprintln", "(", "&", "buf", ",", "r", ".", "Args", "...", ")", "\n", "buf", ".", "Truncate", "(", "buf", ".", "Len", "(", ")", "-", "1", ")", "\n", "}", "\n", "msg", ":=", "buf", ".", "String", "(", ")", "\n", "r", ".", "message", "=", "&", "msg", "\n", "}", "\n", "return", "*", "r", ".", "message", "\n", "}" ]
// Message returns the log record message.
[ "Message", "returns", "the", "log", "record", "message", "." ]
970db520ece77730c7e4724c61121037378659d9
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/logger.go#L69-L89
test
op/go-logging
logger.go
SetBackend
func (l *Logger) SetBackend(backend LeveledBackend) { l.backend = backend l.haveBackend = true }
go
func (l *Logger) SetBackend(backend LeveledBackend) { l.backend = backend l.haveBackend = true }
[ "func", "(", "l", "*", "Logger", ")", "SetBackend", "(", "backend", "LeveledBackend", ")", "{", "l", ".", "backend", "=", "backend", "\n", "l", ".", "haveBackend", "=", "true", "\n", "}" ]
// SetBackend overrides any previously defined backend for this logger.
[ "SetBackend", "overrides", "any", "previously", "defined", "backend", "for", "this", "logger", "." ]
970db520ece77730c7e4724c61121037378659d9
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/logger.go#L104-L107
test
op/go-logging
logger.go
MustGetLogger
func MustGetLogger(module string) *Logger { logger, err := GetLogger(module) if err != nil { panic("logger: " + module + ": " + err.Error()) } return logger }
go
func MustGetLogger(module string) *Logger { logger, err := GetLogger(module) if err != nil { panic("logger: " + module + ": " + err.Error()) } return logger }
[ "func", "MustGetLogger", "(", "module", "string", ")", "*", "Logger", "{", "logger", ",", "err", ":=", "GetLogger", "(", "module", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"logger: \"", "+", "module", "+", "\": \"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "logger", "\n", "}" ]
// MustGetLogger is like GetLogger but panics if the logger can't be created. // It simplifies safe initialization of a global logger for eg. a package.
[ "MustGetLogger", "is", "like", "GetLogger", "but", "panics", "if", "the", "logger", "can", "t", "be", "created", ".", "It", "simplifies", "safe", "initialization", "of", "a", "global", "logger", "for", "eg", ".", "a", "package", "." ]
970db520ece77730c7e4724c61121037378659d9
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/logger.go#L118-L124
test
op/go-logging
logger.go
Reset
func Reset() { // TODO make a global Init() method to be less magic? or make it such that // if there's no backends at all configured, we could use some tricks to // automatically setup backends based if we have a TTY or not. sequenceNo = 0 b := SetBackend(NewLogBackend(os.Stderr, "", log.LstdFlags)) b.SetLevel(DEBUG, "") SetFormatter(DefaultFormatter) timeNow = time.Now }
go
func Reset() { // TODO make a global Init() method to be less magic? or make it such that // if there's no backends at all configured, we could use some tricks to // automatically setup backends based if we have a TTY or not. sequenceNo = 0 b := SetBackend(NewLogBackend(os.Stderr, "", log.LstdFlags)) b.SetLevel(DEBUG, "") SetFormatter(DefaultFormatter) timeNow = time.Now }
[ "func", "Reset", "(", ")", "{", "sequenceNo", "=", "0", "\n", "b", ":=", "SetBackend", "(", "NewLogBackend", "(", "os", ".", "Stderr", ",", "\"\"", ",", "log", ".", "LstdFlags", ")", ")", "\n", "b", ".", "SetLevel", "(", "DEBUG", ",", "\"\"", ")", "\n", "SetFormatter", "(", "DefaultFormatter", ")", "\n", "timeNow", "=", "time", ".", "Now", "\n", "}" ]
// Reset restores the internal state of the logging library.
[ "Reset", "restores", "the", "internal", "state", "of", "the", "logging", "library", "." ]
970db520ece77730c7e4724c61121037378659d9
https://github.com/op/go-logging/blob/970db520ece77730c7e4724c61121037378659d9/logger.go#L127-L136
test