repository_name
stringlengths 5
54
| func_path_in_repository
stringlengths 4
155
| func_name
stringlengths 1
118
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 1
value | func_code_string
stringlengths 52
3.87M
| func_code_tokens
sequencelengths 21
188k
| func_documentation_string
stringlengths 4
26.3k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|
radovskyb/watcher | watcher.go | AddFilterHook | func (w *Watcher) AddFilterHook(f FilterFileHookFunc) {
w.mu.Lock()
w.ffh = append(w.ffh, f)
w.mu.Unlock()
} | go | func (w *Watcher) AddFilterHook(f FilterFileHookFunc) {
w.mu.Lock()
w.ffh = append(w.ffh, f)
w.mu.Unlock()
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"AddFilterHook",
"(",
"f",
"FilterFileHookFunc",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"w",
".",
"ffh",
"=",
"append",
"(",
"w",
".",
"ffh",
",",
"f",
")",
"\n",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // AddFilterHook | [
"AddFilterHook"
] | train | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L162-L166 |
radovskyb/watcher | watcher.go | IgnoreHiddenFiles | func (w *Watcher) IgnoreHiddenFiles(ignore bool) {
w.mu.Lock()
w.ignoreHidden = ignore
w.mu.Unlock()
} | go | func (w *Watcher) IgnoreHiddenFiles(ignore bool) {
w.mu.Lock()
w.ignoreHidden = ignore
w.mu.Unlock()
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"IgnoreHiddenFiles",
"(",
"ignore",
"bool",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"w",
".",
"ignoreHidden",
"=",
"ignore",
"\n",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // IgnoreHiddenFiles sets the watcher to ignore any file or directory
// that starts with a dot. | [
"IgnoreHiddenFiles",
"sets",
"the",
"watcher",
"to",
"ignore",
"any",
"file",
"or",
"directory",
"that",
"starts",
"with",
"a",
"dot",
"."
] | train | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L170-L174 |
radovskyb/watcher | watcher.go | FilterOps | func (w *Watcher) FilterOps(ops ...Op) {
w.mu.Lock()
w.ops = make(map[Op]struct{})
for _, op := range ops {
w.ops[op] = struct{}{}
}
w.mu.Unlock()
} | go | func (w *Watcher) FilterOps(ops ...Op) {
w.mu.Lock()
w.ops = make(map[Op]struct{})
for _, op := range ops {
w.ops[op] = struct{}{}
}
w.mu.Unlock()
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"FilterOps",
"(",
"ops",
"...",
"Op",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"w",
".",
"ops",
"=",
"make",
"(",
"map",
"[",
"Op",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"op",
":=",
"range",
"ops",
"{",
"w",
".",
"ops",
"[",
"op",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // FilterOps filters which event op types should be returned
// when an event occurs. | [
"FilterOps",
"filters",
"which",
"event",
"op",
"types",
"should",
"be",
"returned",
"when",
"an",
"event",
"occurs",
"."
] | train | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L178-L185 |
radovskyb/watcher | watcher.go | Add | func (w *Watcher) Add(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
// If name is on the ignored list or if hidden files are
// ignored and name is a hidden file or directory, simply return.
_, ignored := w.ignored[name]
isHidden, err := isHiddenFile(name)
if err != nil {
return err
}
if ignored || (w.ignoreHidden && isHidden) {
return nil
}
// Add the directory's contents to the files list.
fileList, err := w.list(name)
if err != nil {
return err
}
for k, v := range fileList {
w.files[k] = v
}
// Add the name to the names list.
w.names[name] = false
return nil
} | go | func (w *Watcher) Add(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
// If name is on the ignored list or if hidden files are
// ignored and name is a hidden file or directory, simply return.
_, ignored := w.ignored[name]
isHidden, err := isHiddenFile(name)
if err != nil {
return err
}
if ignored || (w.ignoreHidden && isHidden) {
return nil
}
// Add the directory's contents to the files list.
fileList, err := w.list(name)
if err != nil {
return err
}
for k, v := range fileList {
w.files[k] = v
}
// Add the name to the names list.
w.names[name] = false
return nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Add",
"(",
"name",
"string",
")",
"(",
"err",
"error",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"name",
",",
"err",
"=",
"filepath",
".",
"Abs",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// If name is on the ignored list or if hidden files are",
"// ignored and name is a hidden file or directory, simply return.",
"_",
",",
"ignored",
":=",
"w",
".",
"ignored",
"[",
"name",
"]",
"\n\n",
"isHidden",
",",
"err",
":=",
"isHiddenFile",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"ignored",
"||",
"(",
"w",
".",
"ignoreHidden",
"&&",
"isHidden",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Add the directory's contents to the files list.",
"fileList",
",",
"err",
":=",
"w",
".",
"list",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"fileList",
"{",
"w",
".",
"files",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"// Add the name to the names list.",
"w",
".",
"names",
"[",
"name",
"]",
"=",
"false",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Add adds either a single file or directory to the file list. | [
"Add",
"adds",
"either",
"a",
"single",
"file",
"or",
"directory",
"to",
"the",
"file",
"list",
"."
] | train | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L188-L223 |
radovskyb/watcher | watcher.go | AddRecursive | func (w *Watcher) AddRecursive(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
fileList, err := w.listRecursive(name)
if err != nil {
return err
}
for k, v := range fileList {
w.files[k] = v
}
// Add the name to the names list.
w.names[name] = true
return nil
} | go | func (w *Watcher) AddRecursive(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
fileList, err := w.listRecursive(name)
if err != nil {
return err
}
for k, v := range fileList {
w.files[k] = v
}
// Add the name to the names list.
w.names[name] = true
return nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"AddRecursive",
"(",
"name",
"string",
")",
"(",
"err",
"error",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"name",
",",
"err",
"=",
"filepath",
".",
"Abs",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"fileList",
",",
"err",
":=",
"w",
".",
"listRecursive",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"fileList",
"{",
"w",
".",
"files",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"// Add the name to the names list.",
"w",
".",
"names",
"[",
"name",
"]",
"=",
"true",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // AddRecursive adds either a single file or directory recursively to the file list. | [
"AddRecursive",
"adds",
"either",
"a",
"single",
"file",
"or",
"directory",
"recursively",
"to",
"the",
"file",
"list",
"."
] | train | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L279-L300 |
radovskyb/watcher | watcher.go | Remove | func (w *Watcher) Remove(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
// Remove the name from w's names list.
delete(w.names, name)
// If name is a single file, remove it and return.
info, found := w.files[name]
if !found {
return nil // Doesn't exist, just return.
}
if !info.IsDir() {
delete(w.files, name)
return nil
}
// Delete the actual directory from w.files
delete(w.files, name)
// If it's a directory, delete all of it's contents from w.files.
for path := range w.files {
if filepath.Dir(path) == name {
delete(w.files, path)
}
}
return nil
} | go | func (w *Watcher) Remove(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
// Remove the name from w's names list.
delete(w.names, name)
// If name is a single file, remove it and return.
info, found := w.files[name]
if !found {
return nil // Doesn't exist, just return.
}
if !info.IsDir() {
delete(w.files, name)
return nil
}
// Delete the actual directory from w.files
delete(w.files, name)
// If it's a directory, delete all of it's contents from w.files.
for path := range w.files {
if filepath.Dir(path) == name {
delete(w.files, path)
}
}
return nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Remove",
"(",
"name",
"string",
")",
"(",
"err",
"error",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"name",
",",
"err",
"=",
"filepath",
".",
"Abs",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Remove the name from w's names list.",
"delete",
"(",
"w",
".",
"names",
",",
"name",
")",
"\n\n",
"// If name is a single file, remove it and return.",
"info",
",",
"found",
":=",
"w",
".",
"files",
"[",
"name",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"nil",
"// Doesn't exist, just return.",
"\n",
"}",
"\n",
"if",
"!",
"info",
".",
"IsDir",
"(",
")",
"{",
"delete",
"(",
"w",
".",
"files",
",",
"name",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Delete the actual directory from w.files",
"delete",
"(",
"w",
".",
"files",
",",
"name",
")",
"\n\n",
"// If it's a directory, delete all of it's contents from w.files.",
"for",
"path",
":=",
"range",
"w",
".",
"files",
"{",
"if",
"filepath",
".",
"Dir",
"(",
"path",
")",
"==",
"name",
"{",
"delete",
"(",
"w",
".",
"files",
",",
"path",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Remove removes either a single file or directory from the file's list. | [
"Remove",
"removes",
"either",
"a",
"single",
"file",
"or",
"directory",
"from",
"the",
"file",
"s",
"list",
"."
] | train | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L342-L374 |
radovskyb/watcher | watcher.go | RemoveRecursive | func (w *Watcher) RemoveRecursive(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
// Remove the name from w's names list.
delete(w.names, name)
// If name is a single file, remove it and return.
info, found := w.files[name]
if !found {
return nil // Doesn't exist, just return.
}
if !info.IsDir() {
delete(w.files, name)
return nil
}
// If it's a directory, delete all of it's contents recursively
// from w.files.
for path := range w.files {
if strings.HasPrefix(path, name) {
delete(w.files, path)
}
}
return nil
} | go | func (w *Watcher) RemoveRecursive(name string) (err error) {
w.mu.Lock()
defer w.mu.Unlock()
name, err = filepath.Abs(name)
if err != nil {
return err
}
// Remove the name from w's names list.
delete(w.names, name)
// If name is a single file, remove it and return.
info, found := w.files[name]
if !found {
return nil // Doesn't exist, just return.
}
if !info.IsDir() {
delete(w.files, name)
return nil
}
// If it's a directory, delete all of it's contents recursively
// from w.files.
for path := range w.files {
if strings.HasPrefix(path, name) {
delete(w.files, path)
}
}
return nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"RemoveRecursive",
"(",
"name",
"string",
")",
"(",
"err",
"error",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"name",
",",
"err",
"=",
"filepath",
".",
"Abs",
"(",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Remove the name from w's names list.",
"delete",
"(",
"w",
".",
"names",
",",
"name",
")",
"\n\n",
"// If name is a single file, remove it and return.",
"info",
",",
"found",
":=",
"w",
".",
"files",
"[",
"name",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"nil",
"// Doesn't exist, just return.",
"\n",
"}",
"\n",
"if",
"!",
"info",
".",
"IsDir",
"(",
")",
"{",
"delete",
"(",
"w",
".",
"files",
",",
"name",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// If it's a directory, delete all of it's contents recursively",
"// from w.files.",
"for",
"path",
":=",
"range",
"w",
".",
"files",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"path",
",",
"name",
")",
"{",
"delete",
"(",
"w",
".",
"files",
",",
"path",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // RemoveRecursive removes either a single file or a directory recursively from
// the file's list. | [
"RemoveRecursive",
"removes",
"either",
"a",
"single",
"file",
"or",
"a",
"directory",
"recursively",
"from",
"the",
"file",
"s",
"list",
"."
] | train | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L378-L408 |
radovskyb/watcher | watcher.go | Ignore | func (w *Watcher) Ignore(paths ...string) (err error) {
for _, path := range paths {
path, err = filepath.Abs(path)
if err != nil {
return err
}
// Remove any of the paths that were already added.
if err := w.RemoveRecursive(path); err != nil {
return err
}
w.mu.Lock()
w.ignored[path] = struct{}{}
w.mu.Unlock()
}
return nil
} | go | func (w *Watcher) Ignore(paths ...string) (err error) {
for _, path := range paths {
path, err = filepath.Abs(path)
if err != nil {
return err
}
// Remove any of the paths that were already added.
if err := w.RemoveRecursive(path); err != nil {
return err
}
w.mu.Lock()
w.ignored[path] = struct{}{}
w.mu.Unlock()
}
return nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Ignore",
"(",
"paths",
"...",
"string",
")",
"(",
"err",
"error",
")",
"{",
"for",
"_",
",",
"path",
":=",
"range",
"paths",
"{",
"path",
",",
"err",
"=",
"filepath",
".",
"Abs",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// Remove any of the paths that were already added.",
"if",
"err",
":=",
"w",
".",
"RemoveRecursive",
"(",
"path",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"w",
".",
"ignored",
"[",
"path",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Ignore adds paths that should be ignored.
//
// For files that are already added, Ignore removes them. | [
"Ignore",
"adds",
"paths",
"that",
"should",
"be",
"ignored",
".",
"For",
"files",
"that",
"are",
"already",
"added",
"Ignore",
"removes",
"them",
"."
] | train | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L413-L428 |
radovskyb/watcher | watcher.go | WatchedFiles | func (w *Watcher) WatchedFiles() map[string]os.FileInfo {
w.mu.Lock()
defer w.mu.Unlock()
files := make(map[string]os.FileInfo)
for k, v := range w.files {
files[k] = v
}
return files
} | go | func (w *Watcher) WatchedFiles() map[string]os.FileInfo {
w.mu.Lock()
defer w.mu.Unlock()
files := make(map[string]os.FileInfo)
for k, v := range w.files {
files[k] = v
}
return files
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"WatchedFiles",
"(",
")",
"map",
"[",
"string",
"]",
"os",
".",
"FileInfo",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"files",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"os",
".",
"FileInfo",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"w",
".",
"files",
"{",
"files",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"return",
"files",
"\n",
"}"
] | // WatchedFiles returns a map of files added to a Watcher. | [
"WatchedFiles",
"returns",
"a",
"map",
"of",
"files",
"added",
"to",
"a",
"Watcher",
"."
] | train | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L431-L441 |
radovskyb/watcher | watcher.go | TriggerEvent | func (w *Watcher) TriggerEvent(eventType Op, file os.FileInfo) {
w.Wait()
if file == nil {
file = &fileInfo{name: "triggered event", modTime: time.Now()}
}
w.Event <- Event{Op: eventType, Path: "-", FileInfo: file}
} | go | func (w *Watcher) TriggerEvent(eventType Op, file os.FileInfo) {
w.Wait()
if file == nil {
file = &fileInfo{name: "triggered event", modTime: time.Now()}
}
w.Event <- Event{Op: eventType, Path: "-", FileInfo: file}
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"TriggerEvent",
"(",
"eventType",
"Op",
",",
"file",
"os",
".",
"FileInfo",
")",
"{",
"w",
".",
"Wait",
"(",
")",
"\n",
"if",
"file",
"==",
"nil",
"{",
"file",
"=",
"&",
"fileInfo",
"{",
"name",
":",
"\"",
"\"",
",",
"modTime",
":",
"time",
".",
"Now",
"(",
")",
"}",
"\n",
"}",
"\n",
"w",
".",
"Event",
"<-",
"Event",
"{",
"Op",
":",
"eventType",
",",
"Path",
":",
"\"",
"\"",
",",
"FileInfo",
":",
"file",
"}",
"\n",
"}"
] | // TriggerEvent is a method that can be used to trigger an event, separate to
// the file watching process. | [
"TriggerEvent",
"is",
"a",
"method",
"that",
"can",
"be",
"used",
"to",
"trigger",
"an",
"event",
"separate",
"to",
"the",
"file",
"watching",
"process",
"."
] | train | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L476-L482 |
radovskyb/watcher | watcher.go | Start | func (w *Watcher) Start(d time.Duration) error {
// Return an error if d is less than 1 nanosecond.
if d < time.Nanosecond {
return ErrDurationTooShort
}
// Make sure the Watcher is not already running.
w.mu.Lock()
if w.running {
w.mu.Unlock()
return ErrWatcherRunning
}
w.running = true
w.mu.Unlock()
// Unblock w.Wait().
w.wg.Done()
for {
// done lets the inner polling cycle loop know when the
// current cycle's method has finished executing.
done := make(chan struct{})
// Any events that are found are first piped to evt before
// being sent to the main Event channel.
evt := make(chan Event)
// Retrieve the file list for all watched file's and dirs.
fileList := w.retrieveFileList()
// cancel can be used to cancel the current event polling function.
cancel := make(chan struct{})
// Look for events.
go func() {
w.pollEvents(fileList, evt, cancel)
done <- struct{}{}
}()
// numEvents holds the number of events for the current cycle.
numEvents := 0
inner:
for {
select {
case <-w.close:
close(cancel)
close(w.Closed)
return nil
case event := <-evt:
if len(w.ops) > 0 { // Filter Ops.
_, found := w.ops[event.Op]
if !found {
continue
}
}
numEvents++
if w.maxEvents > 0 && numEvents > w.maxEvents {
close(cancel)
break inner
}
w.Event <- event
case <-done: // Current cycle is finished.
break inner
}
}
// Update the file's list.
w.mu.Lock()
w.files = fileList
w.mu.Unlock()
// Sleep and then continue to the next loop iteration.
time.Sleep(d)
}
} | go | func (w *Watcher) Start(d time.Duration) error {
// Return an error if d is less than 1 nanosecond.
if d < time.Nanosecond {
return ErrDurationTooShort
}
// Make sure the Watcher is not already running.
w.mu.Lock()
if w.running {
w.mu.Unlock()
return ErrWatcherRunning
}
w.running = true
w.mu.Unlock()
// Unblock w.Wait().
w.wg.Done()
for {
// done lets the inner polling cycle loop know when the
// current cycle's method has finished executing.
done := make(chan struct{})
// Any events that are found are first piped to evt before
// being sent to the main Event channel.
evt := make(chan Event)
// Retrieve the file list for all watched file's and dirs.
fileList := w.retrieveFileList()
// cancel can be used to cancel the current event polling function.
cancel := make(chan struct{})
// Look for events.
go func() {
w.pollEvents(fileList, evt, cancel)
done <- struct{}{}
}()
// numEvents holds the number of events for the current cycle.
numEvents := 0
inner:
for {
select {
case <-w.close:
close(cancel)
close(w.Closed)
return nil
case event := <-evt:
if len(w.ops) > 0 { // Filter Ops.
_, found := w.ops[event.Op]
if !found {
continue
}
}
numEvents++
if w.maxEvents > 0 && numEvents > w.maxEvents {
close(cancel)
break inner
}
w.Event <- event
case <-done: // Current cycle is finished.
break inner
}
}
// Update the file's list.
w.mu.Lock()
w.files = fileList
w.mu.Unlock()
// Sleep and then continue to the next loop iteration.
time.Sleep(d)
}
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Start",
"(",
"d",
"time",
".",
"Duration",
")",
"error",
"{",
"// Return an error if d is less than 1 nanosecond.",
"if",
"d",
"<",
"time",
".",
"Nanosecond",
"{",
"return",
"ErrDurationTooShort",
"\n",
"}",
"\n\n",
"// Make sure the Watcher is not already running.",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"w",
".",
"running",
"{",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"ErrWatcherRunning",
"\n",
"}",
"\n",
"w",
".",
"running",
"=",
"true",
"\n",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Unblock w.Wait().",
"w",
".",
"wg",
".",
"Done",
"(",
")",
"\n\n",
"for",
"{",
"// done lets the inner polling cycle loop know when the",
"// current cycle's method has finished executing.",
"done",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n\n",
"// Any events that are found are first piped to evt before",
"// being sent to the main Event channel.",
"evt",
":=",
"make",
"(",
"chan",
"Event",
")",
"\n\n",
"// Retrieve the file list for all watched file's and dirs.",
"fileList",
":=",
"w",
".",
"retrieveFileList",
"(",
")",
"\n\n",
"// cancel can be used to cancel the current event polling function.",
"cancel",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n\n",
"// Look for events.",
"go",
"func",
"(",
")",
"{",
"w",
".",
"pollEvents",
"(",
"fileList",
",",
"evt",
",",
"cancel",
")",
"\n",
"done",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// numEvents holds the number of events for the current cycle.",
"numEvents",
":=",
"0",
"\n\n",
"inner",
":",
"for",
"{",
"select",
"{",
"case",
"<-",
"w",
".",
"close",
":",
"close",
"(",
"cancel",
")",
"\n",
"close",
"(",
"w",
".",
"Closed",
")",
"\n",
"return",
"nil",
"\n",
"case",
"event",
":=",
"<-",
"evt",
":",
"if",
"len",
"(",
"w",
".",
"ops",
")",
">",
"0",
"{",
"// Filter Ops.",
"_",
",",
"found",
":=",
"w",
".",
"ops",
"[",
"event",
".",
"Op",
"]",
"\n",
"if",
"!",
"found",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"numEvents",
"++",
"\n",
"if",
"w",
".",
"maxEvents",
">",
"0",
"&&",
"numEvents",
">",
"w",
".",
"maxEvents",
"{",
"close",
"(",
"cancel",
")",
"\n",
"break",
"inner",
"\n",
"}",
"\n",
"w",
".",
"Event",
"<-",
"event",
"\n",
"case",
"<-",
"done",
":",
"// Current cycle is finished.",
"break",
"inner",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Update the file's list.",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"w",
".",
"files",
"=",
"fileList",
"\n",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Sleep and then continue to the next loop iteration.",
"time",
".",
"Sleep",
"(",
"d",
")",
"\n",
"}",
"\n",
"}"
] | // Start begins the polling cycle which repeats every specified
// duration until Close is called. | [
"Start",
"begins",
"the",
"polling",
"cycle",
"which",
"repeats",
"every",
"specified",
"duration",
"until",
"Close",
"is",
"called",
"."
] | train | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L534-L609 |
radovskyb/watcher | watcher.go | Close | func (w *Watcher) Close() {
w.mu.Lock()
if !w.running {
w.mu.Unlock()
return
}
w.running = false
w.files = make(map[string]os.FileInfo)
w.names = make(map[string]bool)
w.mu.Unlock()
// Send a close signal to the Start method.
w.close <- struct{}{}
} | go | func (w *Watcher) Close() {
w.mu.Lock()
if !w.running {
w.mu.Unlock()
return
}
w.running = false
w.files = make(map[string]os.FileInfo)
w.names = make(map[string]bool)
w.mu.Unlock()
// Send a close signal to the Start method.
w.close <- struct{}{}
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Close",
"(",
")",
"{",
"w",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"!",
"w",
".",
"running",
"{",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"running",
"=",
"false",
"\n",
"w",
".",
"files",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"os",
".",
"FileInfo",
")",
"\n",
"w",
".",
"names",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"w",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"// Send a close signal to the Start method.",
"w",
".",
"close",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}"
] | // Close stops a Watcher and unlocks its mutex, then sends a close signal. | [
"Close",
"stops",
"a",
"Watcher",
"and",
"unlocks",
"its",
"mutex",
"then",
"sends",
"a",
"close",
"signal",
"."
] | train | https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L701-L713 |
canthefason/go-watcher | common.go | NewParams | func NewParams() *Params {
return &Params{
Package: make([]string, 0),
Watcher: make(map[string]string),
}
} | go | func NewParams() *Params {
return &Params{
Package: make([]string, 0),
Watcher: make(map[string]string),
}
} | [
"func",
"NewParams",
"(",
")",
"*",
"Params",
"{",
"return",
"&",
"Params",
"{",
"Package",
":",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
",",
"Watcher",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
",",
"}",
"\n",
"}"
] | // NewParams creates a new Params instance | [
"NewParams",
"creates",
"a",
"new",
"Params",
"instance"
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L28-L33 |
canthefason/go-watcher | common.go | generateBinaryName | func (p *Params) generateBinaryName() string {
rand.Seed(time.Now().UnixNano())
randName := rand.Int31n(999999)
packageName := strings.Replace(p.packagePath(), "/", "-", -1)
return fmt.Sprintf("%s-%s-%d", generateBinaryPrefix(), packageName, randName)
} | go | func (p *Params) generateBinaryName() string {
rand.Seed(time.Now().UnixNano())
randName := rand.Int31n(999999)
packageName := strings.Replace(p.packagePath(), "/", "-", -1)
return fmt.Sprintf("%s-%s-%d", generateBinaryPrefix(), packageName, randName)
} | [
"func",
"(",
"p",
"*",
"Params",
")",
"generateBinaryName",
"(",
")",
"string",
"{",
"rand",
".",
"Seed",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n",
"randName",
":=",
"rand",
".",
"Int31n",
"(",
"999999",
")",
"\n",
"packageName",
":=",
"strings",
".",
"Replace",
"(",
"p",
".",
"packagePath",
"(",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"generateBinaryPrefix",
"(",
")",
",",
"packageName",
",",
"randName",
")",
"\n",
"}"
] | // generateBinaryName generates a new binary name for each rebuild, for preventing any sorts of conflicts | [
"generateBinaryName",
"generates",
"a",
"new",
"binary",
"name",
"for",
"each",
"rebuild",
"for",
"preventing",
"any",
"sorts",
"of",
"conflicts"
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L56-L62 |
canthefason/go-watcher | common.go | runCommand | func runCommand(name string, args ...string) (*exec.Cmd, error) {
cmd := exec.Command(name, args...)
stderr, err := cmd.StderrPipe()
if err != nil {
return cmd, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return cmd, err
}
if err := cmd.Start(); err != nil {
return cmd, err
}
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
return cmd, nil
} | go | func runCommand(name string, args ...string) (*exec.Cmd, error) {
cmd := exec.Command(name, args...)
stderr, err := cmd.StderrPipe()
if err != nil {
return cmd, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return cmd, err
}
if err := cmd.Start(); err != nil {
return cmd, err
}
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
return cmd, nil
} | [
"func",
"runCommand",
"(",
"name",
"string",
",",
"args",
"...",
"string",
")",
"(",
"*",
"exec",
".",
"Cmd",
",",
"error",
")",
"{",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"name",
",",
"args",
"...",
")",
"\n",
"stderr",
",",
"err",
":=",
"cmd",
".",
"StderrPipe",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"cmd",
",",
"err",
"\n",
"}",
"\n\n",
"stdout",
",",
"err",
":=",
"cmd",
".",
"StdoutPipe",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"cmd",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"cmd",
".",
"Start",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"cmd",
",",
"err",
"\n",
"}",
"\n\n",
"go",
"io",
".",
"Copy",
"(",
"os",
".",
"Stdout",
",",
"stdout",
")",
"\n",
"go",
"io",
".",
"Copy",
"(",
"os",
".",
"Stderr",
",",
"stderr",
")",
"\n\n",
"return",
"cmd",
",",
"nil",
"\n",
"}"
] | // runCommand runs the command with given name and arguments. It copies the
// logs to standard output | [
"runCommand",
"runs",
"the",
"command",
"with",
"given",
"name",
"and",
"arguments",
".",
"It",
"copies",
"the",
"logs",
"to",
"standard",
"output"
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L75-L95 |
canthefason/go-watcher | common.go | ParseArgs | func ParseArgs(args []string) *Params {
params := NewParams()
// remove the command argument
args = args[1:len(args)]
for i := 0; i < len(args); i++ {
arg := args[i]
arg = stripDash(arg)
if existIn(arg, watcherFlags) {
// used for fetching the value of the given parameter
if len(args) <= i+1 {
log.Fatalf("missing parameter value: %s", arg)
}
if strings.HasPrefix(args[i+1], "-") {
log.Fatalf("missing parameter value: %s", arg)
}
params.Watcher[arg] = args[i+1]
i++
continue
}
params.Package = append(params.Package, args[i])
}
params.cloneRunFlag()
return params
} | go | func ParseArgs(args []string) *Params {
params := NewParams()
// remove the command argument
args = args[1:len(args)]
for i := 0; i < len(args); i++ {
arg := args[i]
arg = stripDash(arg)
if existIn(arg, watcherFlags) {
// used for fetching the value of the given parameter
if len(args) <= i+1 {
log.Fatalf("missing parameter value: %s", arg)
}
if strings.HasPrefix(args[i+1], "-") {
log.Fatalf("missing parameter value: %s", arg)
}
params.Watcher[arg] = args[i+1]
i++
continue
}
params.Package = append(params.Package, args[i])
}
params.cloneRunFlag()
return params
} | [
"func",
"ParseArgs",
"(",
"args",
"[",
"]",
"string",
")",
"*",
"Params",
"{",
"params",
":=",
"NewParams",
"(",
")",
"\n\n",
"// remove the command argument",
"args",
"=",
"args",
"[",
"1",
":",
"len",
"(",
"args",
")",
"]",
"\n\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"args",
")",
";",
"i",
"++",
"{",
"arg",
":=",
"args",
"[",
"i",
"]",
"\n",
"arg",
"=",
"stripDash",
"(",
"arg",
")",
"\n\n",
"if",
"existIn",
"(",
"arg",
",",
"watcherFlags",
")",
"{",
"// used for fetching the value of the given parameter",
"if",
"len",
"(",
"args",
")",
"<=",
"i",
"+",
"1",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"arg",
")",
"\n",
"}",
"\n\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"args",
"[",
"i",
"+",
"1",
"]",
",",
"\"",
"\"",
")",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"arg",
")",
"\n",
"}",
"\n\n",
"params",
".",
"Watcher",
"[",
"arg",
"]",
"=",
"args",
"[",
"i",
"+",
"1",
"]",
"\n",
"i",
"++",
"\n",
"continue",
"\n",
"}",
"\n\n",
"params",
".",
"Package",
"=",
"append",
"(",
"params",
".",
"Package",
",",
"args",
"[",
"i",
"]",
")",
"\n",
"}",
"\n\n",
"params",
".",
"cloneRunFlag",
"(",
")",
"\n\n",
"return",
"params",
"\n",
"}"
] | // ParseArgs extracts the application parameters from args and returns
// Params instance with separated watcher and application parameters | [
"ParseArgs",
"extracts",
"the",
"application",
"parameters",
"from",
"args",
"and",
"returns",
"Params",
"instance",
"with",
"separated",
"watcher",
"and",
"application",
"parameters"
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L99-L131 |
canthefason/go-watcher | common.go | stripDash | func stripDash(arg string) string {
if len(arg) > 1 {
if arg[1] == '-' {
return arg[2:]
} else if arg[0] == '-' {
return arg[1:]
}
}
return arg
} | go | func stripDash(arg string) string {
if len(arg) > 1 {
if arg[1] == '-' {
return arg[2:]
} else if arg[0] == '-' {
return arg[1:]
}
}
return arg
} | [
"func",
"stripDash",
"(",
"arg",
"string",
")",
"string",
"{",
"if",
"len",
"(",
"arg",
")",
">",
"1",
"{",
"if",
"arg",
"[",
"1",
"]",
"==",
"'-'",
"{",
"return",
"arg",
"[",
"2",
":",
"]",
"\n",
"}",
"else",
"if",
"arg",
"[",
"0",
"]",
"==",
"'-'",
"{",
"return",
"arg",
"[",
"1",
":",
"]",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"arg",
"\n",
"}"
] | // stripDash removes the both single and double dash chars and returns
// the actual parameter name | [
"stripDash",
"removes",
"the",
"both",
"single",
"and",
"double",
"dash",
"chars",
"and",
"returns",
"the",
"actual",
"parameter",
"name"
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L135-L145 |
canthefason/go-watcher | build.go | NewBuilder | func NewBuilder(w *Watcher, r *Runner) *Builder {
return &Builder{watcher: w, runner: r}
} | go | func NewBuilder(w *Watcher, r *Runner) *Builder {
return &Builder{watcher: w, runner: r}
} | [
"func",
"NewBuilder",
"(",
"w",
"*",
"Watcher",
",",
"r",
"*",
"Runner",
")",
"*",
"Builder",
"{",
"return",
"&",
"Builder",
"{",
"watcher",
":",
"w",
",",
"runner",
":",
"r",
"}",
"\n",
"}"
] | // NewBuilder constructs the Builder instance | [
"NewBuilder",
"constructs",
"the",
"Builder",
"instance"
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/build.go#L20-L22 |
canthefason/go-watcher | build.go | Build | func (b *Builder) Build(p *Params) {
go b.registerSignalHandler()
go func() {
// used for triggering the first build
b.watcher.update <- struct{}{}
}()
for range b.watcher.Wait() {
fileName := p.generateBinaryName()
pkg := p.packagePath()
log.Println("build started")
color.Cyan("Building %s...\n", pkg)
// build package
cmd, err := runCommand("go", "build", "-i", "-o", fileName, pkg)
if err != nil {
log.Fatalf("Could not run 'go build' command: %s", err)
continue
}
if err := cmd.Wait(); err != nil {
if err := interpretError(err); err != nil {
color.Red("An error occurred while building: %s", err)
} else {
color.Red("A build error occurred. Please update your code...")
}
continue
}
log.Println("build completed")
// and start the new process
b.runner.restart(fileName)
}
} | go | func (b *Builder) Build(p *Params) {
go b.registerSignalHandler()
go func() {
// used for triggering the first build
b.watcher.update <- struct{}{}
}()
for range b.watcher.Wait() {
fileName := p.generateBinaryName()
pkg := p.packagePath()
log.Println("build started")
color.Cyan("Building %s...\n", pkg)
// build package
cmd, err := runCommand("go", "build", "-i", "-o", fileName, pkg)
if err != nil {
log.Fatalf("Could not run 'go build' command: %s", err)
continue
}
if err := cmd.Wait(); err != nil {
if err := interpretError(err); err != nil {
color.Red("An error occurred while building: %s", err)
} else {
color.Red("A build error occurred. Please update your code...")
}
continue
}
log.Println("build completed")
// and start the new process
b.runner.restart(fileName)
}
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"Build",
"(",
"p",
"*",
"Params",
")",
"{",
"go",
"b",
".",
"registerSignalHandler",
"(",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"// used for triggering the first build",
"b",
".",
"watcher",
".",
"update",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"for",
"range",
"b",
".",
"watcher",
".",
"Wait",
"(",
")",
"{",
"fileName",
":=",
"p",
".",
"generateBinaryName",
"(",
")",
"\n\n",
"pkg",
":=",
"p",
".",
"packagePath",
"(",
")",
"\n\n",
"log",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"color",
".",
"Cyan",
"(",
"\"",
"\\n",
"\"",
",",
"pkg",
")",
"\n\n",
"// build package",
"cmd",
",",
"err",
":=",
"runCommand",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fileName",
",",
"pkg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"cmd",
".",
"Wait",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
":=",
"interpretError",
"(",
"err",
")",
";",
"err",
"!=",
"nil",
"{",
"color",
".",
"Red",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"color",
".",
"Red",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"continue",
"\n",
"}",
"\n",
"log",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n\n",
"// and start the new process",
"b",
".",
"runner",
".",
"restart",
"(",
"fileName",
")",
"\n",
"}",
"\n",
"}"
] | // Build listens watch events from Watcher and sends messages to Runner
// when new changes are built. | [
"Build",
"listens",
"watch",
"events",
"from",
"Watcher",
"and",
"sends",
"messages",
"to",
"Runner",
"when",
"new",
"changes",
"are",
"built",
"."
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/build.go#L26-L62 |
canthefason/go-watcher | watch.go | MustRegisterWatcher | func MustRegisterWatcher(params *Params) *Watcher {
watchVendorStr := params.Get("watch-vendor")
var watchVendor bool
var err error
if watchVendorStr != "" {
watchVendor, err = strconv.ParseBool(watchVendorStr)
if err != nil {
log.Println("Wrong watch-vendor value: %s (default=false)", watchVendorStr)
}
}
w := &Watcher{
update: make(chan struct{}),
rootdir: params.Get("watch"),
watchVendor: watchVendor,
}
w.watcher, err = fsnotify.NewWatcher()
if err != nil {
log.Fatalf("Could not register watcher: %s", err)
}
// add folders that will be watched
w.watchFolders()
return w
} | go | func MustRegisterWatcher(params *Params) *Watcher {
watchVendorStr := params.Get("watch-vendor")
var watchVendor bool
var err error
if watchVendorStr != "" {
watchVendor, err = strconv.ParseBool(watchVendorStr)
if err != nil {
log.Println("Wrong watch-vendor value: %s (default=false)", watchVendorStr)
}
}
w := &Watcher{
update: make(chan struct{}),
rootdir: params.Get("watch"),
watchVendor: watchVendor,
}
w.watcher, err = fsnotify.NewWatcher()
if err != nil {
log.Fatalf("Could not register watcher: %s", err)
}
// add folders that will be watched
w.watchFolders()
return w
} | [
"func",
"MustRegisterWatcher",
"(",
"params",
"*",
"Params",
")",
"*",
"Watcher",
"{",
"watchVendorStr",
":=",
"params",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"var",
"watchVendor",
"bool",
"\n",
"var",
"err",
"error",
"\n",
"if",
"watchVendorStr",
"!=",
"\"",
"\"",
"{",
"watchVendor",
",",
"err",
"=",
"strconv",
".",
"ParseBool",
"(",
"watchVendorStr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"watchVendorStr",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"w",
":=",
"&",
"Watcher",
"{",
"update",
":",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
",",
"rootdir",
":",
"params",
".",
"Get",
"(",
"\"",
"\"",
")",
",",
"watchVendor",
":",
"watchVendor",
",",
"}",
"\n\n",
"w",
".",
"watcher",
",",
"err",
"=",
"fsnotify",
".",
"NewWatcher",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// add folders that will be watched",
"w",
".",
"watchFolders",
"(",
")",
"\n\n",
"return",
"w",
"\n",
"}"
] | // MustRegisterWatcher creates a new Watcher and starts listening to
// given folders | [
"MustRegisterWatcher",
"creates",
"a",
"new",
"Watcher",
"and",
"starts",
"listening",
"to",
"given",
"folders"
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L37-L63 |
canthefason/go-watcher | watch.go | Watch | func (w *Watcher) Watch() {
eventSent := false
for {
select {
case event := <-w.watcher.Events:
// discard chmod events
if event.Op&fsnotify.Chmod != fsnotify.Chmod {
// test files do not need a rebuild
if isTestFile(event.Name) {
continue
}
if !isWatchedFileType(event.Name) {
continue
}
if eventSent {
continue
}
eventSent = true
// prevent consequent builds
go func() {
w.update <- struct{}{}
time.Sleep(watchDelta)
eventSent = false
}()
}
case err := <-w.watcher.Errors:
if err != nil {
log.Fatalf("Watcher error: %s", err)
}
return
}
}
} | go | func (w *Watcher) Watch() {
eventSent := false
for {
select {
case event := <-w.watcher.Events:
// discard chmod events
if event.Op&fsnotify.Chmod != fsnotify.Chmod {
// test files do not need a rebuild
if isTestFile(event.Name) {
continue
}
if !isWatchedFileType(event.Name) {
continue
}
if eventSent {
continue
}
eventSent = true
// prevent consequent builds
go func() {
w.update <- struct{}{}
time.Sleep(watchDelta)
eventSent = false
}()
}
case err := <-w.watcher.Errors:
if err != nil {
log.Fatalf("Watcher error: %s", err)
}
return
}
}
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"Watch",
"(",
")",
"{",
"eventSent",
":=",
"false",
"\n\n",
"for",
"{",
"select",
"{",
"case",
"event",
":=",
"<-",
"w",
".",
"watcher",
".",
"Events",
":",
"// discard chmod events",
"if",
"event",
".",
"Op",
"&",
"fsnotify",
".",
"Chmod",
"!=",
"fsnotify",
".",
"Chmod",
"{",
"// test files do not need a rebuild",
"if",
"isTestFile",
"(",
"event",
".",
"Name",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"!",
"isWatchedFileType",
"(",
"event",
".",
"Name",
")",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"eventSent",
"{",
"continue",
"\n",
"}",
"\n",
"eventSent",
"=",
"true",
"\n",
"// prevent consequent builds",
"go",
"func",
"(",
")",
"{",
"w",
".",
"update",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"watchDelta",
")",
"\n",
"eventSent",
"=",
"false",
"\n",
"}",
"(",
")",
"\n\n",
"}",
"\n",
"case",
"err",
":=",
"<-",
"w",
".",
"watcher",
".",
"Errors",
":",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Watch listens file updates, and sends signal to
// update channel when .go and .tmpl files are updated | [
"Watch",
"listens",
"file",
"updates",
"and",
"sends",
"signal",
"to",
"update",
"channel",
"when",
".",
"go",
"and",
".",
"tmpl",
"files",
"are",
"updated"
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L67-L101 |
canthefason/go-watcher | watch.go | watchFolders | func (w *Watcher) watchFolders() {
wd, err := w.prepareRootDir()
if err != nil {
log.Fatalf("Could not get root working directory: %s", err)
}
filepath.Walk(wd, func(path string, info os.FileInfo, err error) error {
// skip files
if info == nil {
log.Fatalf("wrong watcher package: %s", path)
}
if !info.IsDir() {
return nil
}
if !w.watchVendor {
// skip vendor directory
vendor := fmt.Sprintf("%s/vendor", wd)
if strings.HasPrefix(path, vendor) {
return filepath.SkipDir
}
}
// skip hidden folders
if len(path) > 1 && strings.HasPrefix(filepath.Base(path), ".") {
return filepath.SkipDir
}
w.addFolder(path)
return err
})
} | go | func (w *Watcher) watchFolders() {
wd, err := w.prepareRootDir()
if err != nil {
log.Fatalf("Could not get root working directory: %s", err)
}
filepath.Walk(wd, func(path string, info os.FileInfo, err error) error {
// skip files
if info == nil {
log.Fatalf("wrong watcher package: %s", path)
}
if !info.IsDir() {
return nil
}
if !w.watchVendor {
// skip vendor directory
vendor := fmt.Sprintf("%s/vendor", wd)
if strings.HasPrefix(path, vendor) {
return filepath.SkipDir
}
}
// skip hidden folders
if len(path) > 1 && strings.HasPrefix(filepath.Base(path), ".") {
return filepath.SkipDir
}
w.addFolder(path)
return err
})
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"watchFolders",
"(",
")",
"{",
"wd",
",",
"err",
":=",
"w",
".",
"prepareRootDir",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"filepath",
".",
"Walk",
"(",
"wd",
",",
"func",
"(",
"path",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"// skip files",
"if",
"info",
"==",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"info",
".",
"IsDir",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"!",
"w",
".",
"watchVendor",
"{",
"// skip vendor directory",
"vendor",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"wd",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"path",
",",
"vendor",
")",
"{",
"return",
"filepath",
".",
"SkipDir",
"\n",
"}",
"\n",
"}",
"\n\n",
"// skip hidden folders",
"if",
"len",
"(",
"path",
")",
">",
"1",
"&&",
"strings",
".",
"HasPrefix",
"(",
"filepath",
".",
"Base",
"(",
"path",
")",
",",
"\"",
"\"",
")",
"{",
"return",
"filepath",
".",
"SkipDir",
"\n",
"}",
"\n\n",
"w",
".",
"addFolder",
"(",
"path",
")",
"\n\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"}"
] | // watchFolders recursively adds folders that will be watched against the changes,
// starting from the working directory | [
"watchFolders",
"recursively",
"adds",
"folders",
"that",
"will",
"be",
"watched",
"against",
"the",
"changes",
"starting",
"from",
"the",
"working",
"directory"
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L126-L160 |
canthefason/go-watcher | watch.go | addFolder | func (w *Watcher) addFolder(name string) {
if err := w.watcher.Add(name); err != nil {
log.Fatalf("Could not watch folder: %s", err)
}
} | go | func (w *Watcher) addFolder(name string) {
if err := w.watcher.Add(name); err != nil {
log.Fatalf("Could not watch folder: %s", err)
}
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"addFolder",
"(",
"name",
"string",
")",
"{",
"if",
"err",
":=",
"w",
".",
"watcher",
".",
"Add",
"(",
"name",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // addFolder adds given folder name to the watched folders, and starts
// watching it for further changes | [
"addFolder",
"adds",
"given",
"folder",
"name",
"to",
"the",
"watched",
"folders",
"and",
"starts",
"watching",
"it",
"for",
"further",
"changes"
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L164-L168 |
canthefason/go-watcher | watch.go | prepareRootDir | func (w *Watcher) prepareRootDir() (string, error) {
if w.rootdir == "" {
return os.Getwd()
}
path := os.Getenv("GOPATH")
if path == "" {
return "", ErrPathNotSet
}
root := fmt.Sprintf("%s/src/%s", path, w.rootdir)
return root, nil
} | go | func (w *Watcher) prepareRootDir() (string, error) {
if w.rootdir == "" {
return os.Getwd()
}
path := os.Getenv("GOPATH")
if path == "" {
return "", ErrPathNotSet
}
root := fmt.Sprintf("%s/src/%s", path, w.rootdir)
return root, nil
} | [
"func",
"(",
"w",
"*",
"Watcher",
")",
"prepareRootDir",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"w",
".",
"rootdir",
"==",
"\"",
"\"",
"{",
"return",
"os",
".",
"Getwd",
"(",
")",
"\n",
"}",
"\n\n",
"path",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"path",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"ErrPathNotSet",
"\n",
"}",
"\n\n",
"root",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"path",
",",
"w",
".",
"rootdir",
")",
"\n\n",
"return",
"root",
",",
"nil",
"\n",
"}"
] | // prepareRootDir prepares working directory depending on root directory | [
"prepareRootDir",
"prepares",
"working",
"directory",
"depending",
"on",
"root",
"directory"
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L171-L184 |
canthefason/go-watcher | run.go | Run | func (r *Runner) Run(p *Params) {
for fileName := range r.start {
color.Green("Running %s...\n", p.Get("run"))
cmd, err := runCommand(fileName, p.Package...)
if err != nil {
log.Printf("Could not run the go binary: %s \n", err)
r.kill(cmd)
continue
}
r.cmd = cmd
removeFile(fileName)
go func(cmd *exec.Cmd) {
if err := cmd.Wait(); err != nil {
log.Printf("process interrupted: %s \n", err)
r.kill(cmd)
}
}(r.cmd)
}
} | go | func (r *Runner) Run(p *Params) {
for fileName := range r.start {
color.Green("Running %s...\n", p.Get("run"))
cmd, err := runCommand(fileName, p.Package...)
if err != nil {
log.Printf("Could not run the go binary: %s \n", err)
r.kill(cmd)
continue
}
r.cmd = cmd
removeFile(fileName)
go func(cmd *exec.Cmd) {
if err := cmd.Wait(); err != nil {
log.Printf("process interrupted: %s \n", err)
r.kill(cmd)
}
}(r.cmd)
}
} | [
"func",
"(",
"r",
"*",
"Runner",
")",
"Run",
"(",
"p",
"*",
"Params",
")",
"{",
"for",
"fileName",
":=",
"range",
"r",
".",
"start",
"{",
"color",
".",
"Green",
"(",
"\"",
"\\n",
"\"",
",",
"p",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n\n",
"cmd",
",",
"err",
":=",
"runCommand",
"(",
"fileName",
",",
"p",
".",
"Package",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"r",
".",
"kill",
"(",
"cmd",
")",
"\n\n",
"continue",
"\n",
"}",
"\n\n",
"r",
".",
"cmd",
"=",
"cmd",
"\n",
"removeFile",
"(",
"fileName",
")",
"\n\n",
"go",
"func",
"(",
"cmd",
"*",
"exec",
".",
"Cmd",
")",
"{",
"if",
"err",
":=",
"cmd",
".",
"Wait",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"r",
".",
"kill",
"(",
"cmd",
")",
"\n",
"}",
"\n",
"}",
"(",
"r",
".",
"cmd",
")",
"\n",
"}",
"\n",
"}"
] | // Run initializes runner with given parameters. | [
"Run",
"initializes",
"runner",
"with",
"given",
"parameters",
"."
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/run.go#L31-L54 |
canthefason/go-watcher | run.go | restart | func (r *Runner) restart(fileName string) {
r.kill(r.cmd)
r.start <- fileName
} | go | func (r *Runner) restart(fileName string) {
r.kill(r.cmd)
r.start <- fileName
} | [
"func",
"(",
"r",
"*",
"Runner",
")",
"restart",
"(",
"fileName",
"string",
")",
"{",
"r",
".",
"kill",
"(",
"r",
".",
"cmd",
")",
"\n\n",
"r",
".",
"start",
"<-",
"fileName",
"\n",
"}"
] | // Restart kills the process, removes the old binary and
// restarts the new process | [
"Restart",
"kills",
"the",
"process",
"removes",
"the",
"old",
"binary",
"and",
"restarts",
"the",
"new",
"process"
] | train | https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/run.go#L58-L62 |
sony/sonyflake | sonyflake.go | NewSonyflake | func NewSonyflake(st Settings) *Sonyflake {
sf := new(Sonyflake)
sf.mutex = new(sync.Mutex)
sf.sequence = uint16(1<<BitLenSequence - 1)
if st.StartTime.After(time.Now()) {
return nil
}
if st.StartTime.IsZero() {
sf.startTime = toSonyflakeTime(time.Date(2014, 9, 1, 0, 0, 0, 0, time.UTC))
} else {
sf.startTime = toSonyflakeTime(st.StartTime)
}
var err error
if st.MachineID == nil {
sf.machineID, err = lower16BitPrivateIP()
} else {
sf.machineID, err = st.MachineID()
}
if err != nil || (st.CheckMachineID != nil && !st.CheckMachineID(sf.machineID)) {
return nil
}
return sf
} | go | func NewSonyflake(st Settings) *Sonyflake {
sf := new(Sonyflake)
sf.mutex = new(sync.Mutex)
sf.sequence = uint16(1<<BitLenSequence - 1)
if st.StartTime.After(time.Now()) {
return nil
}
if st.StartTime.IsZero() {
sf.startTime = toSonyflakeTime(time.Date(2014, 9, 1, 0, 0, 0, 0, time.UTC))
} else {
sf.startTime = toSonyflakeTime(st.StartTime)
}
var err error
if st.MachineID == nil {
sf.machineID, err = lower16BitPrivateIP()
} else {
sf.machineID, err = st.MachineID()
}
if err != nil || (st.CheckMachineID != nil && !st.CheckMachineID(sf.machineID)) {
return nil
}
return sf
} | [
"func",
"NewSonyflake",
"(",
"st",
"Settings",
")",
"*",
"Sonyflake",
"{",
"sf",
":=",
"new",
"(",
"Sonyflake",
")",
"\n",
"sf",
".",
"mutex",
"=",
"new",
"(",
"sync",
".",
"Mutex",
")",
"\n",
"sf",
".",
"sequence",
"=",
"uint16",
"(",
"1",
"<<",
"BitLenSequence",
"-",
"1",
")",
"\n\n",
"if",
"st",
".",
"StartTime",
".",
"After",
"(",
"time",
".",
"Now",
"(",
")",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"st",
".",
"StartTime",
".",
"IsZero",
"(",
")",
"{",
"sf",
".",
"startTime",
"=",
"toSonyflakeTime",
"(",
"time",
".",
"Date",
"(",
"2014",
",",
"9",
",",
"1",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"time",
".",
"UTC",
")",
")",
"\n",
"}",
"else",
"{",
"sf",
".",
"startTime",
"=",
"toSonyflakeTime",
"(",
"st",
".",
"StartTime",
")",
"\n",
"}",
"\n\n",
"var",
"err",
"error",
"\n",
"if",
"st",
".",
"MachineID",
"==",
"nil",
"{",
"sf",
".",
"machineID",
",",
"err",
"=",
"lower16BitPrivateIP",
"(",
")",
"\n",
"}",
"else",
"{",
"sf",
".",
"machineID",
",",
"err",
"=",
"st",
".",
"MachineID",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"(",
"st",
".",
"CheckMachineID",
"!=",
"nil",
"&&",
"!",
"st",
".",
"CheckMachineID",
"(",
"sf",
".",
"machineID",
")",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"sf",
"\n",
"}"
] | // NewSonyflake returns a new Sonyflake configured with the given Settings.
// NewSonyflake returns nil in the following cases:
// - Settings.StartTime is ahead of the current time.
// - Settings.MachineID returns an error.
// - Settings.CheckMachineID returns false. | [
"NewSonyflake",
"returns",
"a",
"new",
"Sonyflake",
"configured",
"with",
"the",
"given",
"Settings",
".",
"NewSonyflake",
"returns",
"nil",
"in",
"the",
"following",
"cases",
":",
"-",
"Settings",
".",
"StartTime",
"is",
"ahead",
"of",
"the",
"current",
"time",
".",
"-",
"Settings",
".",
"MachineID",
"returns",
"an",
"error",
".",
"-",
"Settings",
".",
"CheckMachineID",
"returns",
"false",
"."
] | train | https://github.com/sony/sonyflake/blob/6d5bd61810093eae37d7d605d0cbdd845969b5b2/sonyflake.go#L57-L82 |
sony/sonyflake | sonyflake.go | NextID | func (sf *Sonyflake) NextID() (uint64, error) {
const maskSequence = uint16(1<<BitLenSequence - 1)
sf.mutex.Lock()
defer sf.mutex.Unlock()
current := currentElapsedTime(sf.startTime)
if sf.elapsedTime < current {
sf.elapsedTime = current
sf.sequence = 0
} else { // sf.elapsedTime >= current
sf.sequence = (sf.sequence + 1) & maskSequence
if sf.sequence == 0 {
sf.elapsedTime++
overtime := sf.elapsedTime - current
time.Sleep(sleepTime((overtime)))
}
}
return sf.toID()
} | go | func (sf *Sonyflake) NextID() (uint64, error) {
const maskSequence = uint16(1<<BitLenSequence - 1)
sf.mutex.Lock()
defer sf.mutex.Unlock()
current := currentElapsedTime(sf.startTime)
if sf.elapsedTime < current {
sf.elapsedTime = current
sf.sequence = 0
} else { // sf.elapsedTime >= current
sf.sequence = (sf.sequence + 1) & maskSequence
if sf.sequence == 0 {
sf.elapsedTime++
overtime := sf.elapsedTime - current
time.Sleep(sleepTime((overtime)))
}
}
return sf.toID()
} | [
"func",
"(",
"sf",
"*",
"Sonyflake",
")",
"NextID",
"(",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"const",
"maskSequence",
"=",
"uint16",
"(",
"1",
"<<",
"BitLenSequence",
"-",
"1",
")",
"\n\n",
"sf",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"sf",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n\n",
"current",
":=",
"currentElapsedTime",
"(",
"sf",
".",
"startTime",
")",
"\n",
"if",
"sf",
".",
"elapsedTime",
"<",
"current",
"{",
"sf",
".",
"elapsedTime",
"=",
"current",
"\n",
"sf",
".",
"sequence",
"=",
"0",
"\n",
"}",
"else",
"{",
"// sf.elapsedTime >= current",
"sf",
".",
"sequence",
"=",
"(",
"sf",
".",
"sequence",
"+",
"1",
")",
"&",
"maskSequence",
"\n",
"if",
"sf",
".",
"sequence",
"==",
"0",
"{",
"sf",
".",
"elapsedTime",
"++",
"\n",
"overtime",
":=",
"sf",
".",
"elapsedTime",
"-",
"current",
"\n",
"time",
".",
"Sleep",
"(",
"sleepTime",
"(",
"(",
"overtime",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"sf",
".",
"toID",
"(",
")",
"\n",
"}"
] | // NextID generates a next unique ID.
// After the Sonyflake time overflows, NextID returns an error. | [
"NextID",
"generates",
"a",
"next",
"unique",
"ID",
".",
"After",
"the",
"Sonyflake",
"time",
"overflows",
"NextID",
"returns",
"an",
"error",
"."
] | train | https://github.com/sony/sonyflake/blob/6d5bd61810093eae37d7d605d0cbdd845969b5b2/sonyflake.go#L86-L106 |
sony/sonyflake | sonyflake.go | Decompose | func Decompose(id uint64) map[string]uint64 {
const maskSequence = uint64((1<<BitLenSequence - 1) << BitLenMachineID)
const maskMachineID = uint64(1<<BitLenMachineID - 1)
msb := id >> 63
time := id >> (BitLenSequence + BitLenMachineID)
sequence := id & maskSequence >> BitLenMachineID
machineID := id & maskMachineID
return map[string]uint64{
"id": id,
"msb": msb,
"time": time,
"sequence": sequence,
"machine-id": machineID,
}
} | go | func Decompose(id uint64) map[string]uint64 {
const maskSequence = uint64((1<<BitLenSequence - 1) << BitLenMachineID)
const maskMachineID = uint64(1<<BitLenMachineID - 1)
msb := id >> 63
time := id >> (BitLenSequence + BitLenMachineID)
sequence := id & maskSequence >> BitLenMachineID
machineID := id & maskMachineID
return map[string]uint64{
"id": id,
"msb": msb,
"time": time,
"sequence": sequence,
"machine-id": machineID,
}
} | [
"func",
"Decompose",
"(",
"id",
"uint64",
")",
"map",
"[",
"string",
"]",
"uint64",
"{",
"const",
"maskSequence",
"=",
"uint64",
"(",
"(",
"1",
"<<",
"BitLenSequence",
"-",
"1",
")",
"<<",
"BitLenMachineID",
")",
"\n",
"const",
"maskMachineID",
"=",
"uint64",
"(",
"1",
"<<",
"BitLenMachineID",
"-",
"1",
")",
"\n\n",
"msb",
":=",
"id",
">>",
"63",
"\n",
"time",
":=",
"id",
">>",
"(",
"BitLenSequence",
"+",
"BitLenMachineID",
")",
"\n",
"sequence",
":=",
"id",
"&",
"maskSequence",
">>",
"BitLenMachineID",
"\n",
"machineID",
":=",
"id",
"&",
"maskMachineID",
"\n",
"return",
"map",
"[",
"string",
"]",
"uint64",
"{",
"\"",
"\"",
":",
"id",
",",
"\"",
"\"",
":",
"msb",
",",
"\"",
"\"",
":",
"time",
",",
"\"",
"\"",
":",
"sequence",
",",
"\"",
"\"",
":",
"machineID",
",",
"}",
"\n",
"}"
] | // Decompose returns a set of Sonyflake ID parts. | [
"Decompose",
"returns",
"a",
"set",
"of",
"Sonyflake",
"ID",
"parts",
"."
] | train | https://github.com/sony/sonyflake/blob/6d5bd61810093eae37d7d605d0cbdd845969b5b2/sonyflake.go#L168-L183 |
sony/sonyflake | awsutil/awsutil.go | AmazonEC2MachineID | func AmazonEC2MachineID() (uint16, error) {
ip, err := amazonEC2PrivateIPv4()
if err != nil {
return 0, err
}
return uint16(ip[2])<<8 + uint16(ip[3]), nil
} | go | func AmazonEC2MachineID() (uint16, error) {
ip, err := amazonEC2PrivateIPv4()
if err != nil {
return 0, err
}
return uint16(ip[2])<<8 + uint16(ip[3]), nil
} | [
"func",
"AmazonEC2MachineID",
"(",
")",
"(",
"uint16",
",",
"error",
")",
"{",
"ip",
",",
"err",
":=",
"amazonEC2PrivateIPv4",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"uint16",
"(",
"ip",
"[",
"2",
"]",
")",
"<<",
"8",
"+",
"uint16",
"(",
"ip",
"[",
"3",
"]",
")",
",",
"nil",
"\n",
"}"
] | // AmazonEC2MachineID retrieves the private IP address of the Amazon EC2 instance
// and returns its lower 16 bits.
// It works correctly on Docker as well. | [
"AmazonEC2MachineID",
"retrieves",
"the",
"private",
"IP",
"address",
"of",
"the",
"Amazon",
"EC2",
"instance",
"and",
"returns",
"its",
"lower",
"16",
"bits",
".",
"It",
"works",
"correctly",
"on",
"Docker",
"as",
"well",
"."
] | train | https://github.com/sony/sonyflake/blob/6d5bd61810093eae37d7d605d0cbdd845969b5b2/awsutil/awsutil.go#L37-L44 |
sony/sonyflake | awsutil/awsutil.go | TimeDifference | func TimeDifference(server string) (time.Duration, error) {
output, err := exec.Command("/usr/sbin/ntpdate", "-q", server).CombinedOutput()
if err != nil {
return time.Duration(0), err
}
re, _ := regexp.Compile("offset (.*) sec")
submatched := re.FindSubmatch(output)
if len(submatched) != 2 {
return time.Duration(0), errors.New("invalid ntpdate output")
}
f, err := strconv.ParseFloat(string(submatched[1]), 64)
if err != nil {
return time.Duration(0), err
}
return time.Duration(f*1000) * time.Millisecond, nil
} | go | func TimeDifference(server string) (time.Duration, error) {
output, err := exec.Command("/usr/sbin/ntpdate", "-q", server).CombinedOutput()
if err != nil {
return time.Duration(0), err
}
re, _ := regexp.Compile("offset (.*) sec")
submatched := re.FindSubmatch(output)
if len(submatched) != 2 {
return time.Duration(0), errors.New("invalid ntpdate output")
}
f, err := strconv.ParseFloat(string(submatched[1]), 64)
if err != nil {
return time.Duration(0), err
}
return time.Duration(f*1000) * time.Millisecond, nil
} | [
"func",
"TimeDifference",
"(",
"server",
"string",
")",
"(",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"output",
",",
"err",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"server",
")",
".",
"CombinedOutput",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Duration",
"(",
"0",
")",
",",
"err",
"\n",
"}",
"\n\n",
"re",
",",
"_",
":=",
"regexp",
".",
"Compile",
"(",
"\"",
"\"",
")",
"\n",
"submatched",
":=",
"re",
".",
"FindSubmatch",
"(",
"output",
")",
"\n",
"if",
"len",
"(",
"submatched",
")",
"!=",
"2",
"{",
"return",
"time",
".",
"Duration",
"(",
"0",
")",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"f",
",",
"err",
":=",
"strconv",
".",
"ParseFloat",
"(",
"string",
"(",
"submatched",
"[",
"1",
"]",
")",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Duration",
"(",
"0",
")",
",",
"err",
"\n",
"}",
"\n",
"return",
"time",
".",
"Duration",
"(",
"f",
"*",
"1000",
")",
"*",
"time",
".",
"Millisecond",
",",
"nil",
"\n",
"}"
] | // TimeDifference returns the time difference between the localhost and the given NTP server. | [
"TimeDifference",
"returns",
"the",
"time",
"difference",
"between",
"the",
"localhost",
"and",
"the",
"given",
"NTP",
"server",
"."
] | train | https://github.com/sony/sonyflake/blob/6d5bd61810093eae37d7d605d0cbdd845969b5b2/awsutil/awsutil.go#L47-L64 |
terraform-providers/terraform-provider-openstack | openstack/dns_zone_v2.go | ToZoneCreateMap | func (opts ZoneCreateOpts) ToZoneCreateMap() (map[string]interface{}, error) {
b, err := BuildRequest(opts, "")
if err != nil {
return nil, err
}
if m, ok := b[""].(map[string]interface{}); ok {
if opts.TTL > 0 {
m["ttl"] = opts.TTL
}
return m, nil
}
return nil, fmt.Errorf("Expected map but got %T", b[""])
} | go | func (opts ZoneCreateOpts) ToZoneCreateMap() (map[string]interface{}, error) {
b, err := BuildRequest(opts, "")
if err != nil {
return nil, err
}
if m, ok := b[""].(map[string]interface{}); ok {
if opts.TTL > 0 {
m["ttl"] = opts.TTL
}
return m, nil
}
return nil, fmt.Errorf("Expected map but got %T", b[""])
} | [
"func",
"(",
"opts",
"ZoneCreateOpts",
")",
"ToZoneCreateMap",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"BuildRequest",
"(",
"opts",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"m",
",",
"ok",
":=",
"b",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"if",
"opts",
".",
"TTL",
">",
"0",
"{",
"m",
"[",
"\"",
"\"",
"]",
"=",
"opts",
".",
"TTL",
"\n",
"}",
"\n\n",
"return",
"m",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"b",
"[",
"\"",
"\"",
"]",
")",
"\n",
"}"
] | // ToZoneCreateMap casts a CreateOpts struct to a map.
// It overrides zones.ToZoneCreateMap to add the ValueSpecs field. | [
"ToZoneCreateMap",
"casts",
"a",
"CreateOpts",
"struct",
"to",
"a",
"map",
".",
"It",
"overrides",
"zones",
".",
"ToZoneCreateMap",
"to",
"add",
"the",
"ValueSpecs",
"field",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/dns_zone_v2.go#L21-L36 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_identity_role_v3.go | dataSourceIdentityRoleV3Read | func dataSourceIdentityRoleV3Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
identityClient, err := config.identityV3Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack identity client: %s", err)
}
listOpts := roles.ListOpts{
DomainID: d.Get("domain_id").(string),
Name: d.Get("name").(string),
}
log.Printf("[DEBUG] openstack_identity_role_v3 list options: %#v", listOpts)
var role roles.Role
allPages, err := roles.List(identityClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query openstack_identity_role_v3: %s", err)
}
allRoles, err := roles.ExtractRoles(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve openstack_identity_role_v3: %s", err)
}
if len(allRoles) < 1 {
return fmt.Errorf("Your openstack_identity_role_v3 query returned no results.")
}
if len(allRoles) > 1 {
return fmt.Errorf("Your openstack_identity_role_v3 query returned more than one result.")
}
role = allRoles[0]
return dataSourceIdentityRoleV3Attributes(d, config, &role)
} | go | func dataSourceIdentityRoleV3Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
identityClient, err := config.identityV3Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack identity client: %s", err)
}
listOpts := roles.ListOpts{
DomainID: d.Get("domain_id").(string),
Name: d.Get("name").(string),
}
log.Printf("[DEBUG] openstack_identity_role_v3 list options: %#v", listOpts)
var role roles.Role
allPages, err := roles.List(identityClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query openstack_identity_role_v3: %s", err)
}
allRoles, err := roles.ExtractRoles(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve openstack_identity_role_v3: %s", err)
}
if len(allRoles) < 1 {
return fmt.Errorf("Your openstack_identity_role_v3 query returned no results.")
}
if len(allRoles) > 1 {
return fmt.Errorf("Your openstack_identity_role_v3 query returned more than one result.")
}
role = allRoles[0]
return dataSourceIdentityRoleV3Attributes(d, config, &role)
} | [
"func",
"dataSourceIdentityRoleV3Read",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"meta",
"interface",
"{",
"}",
")",
"error",
"{",
"config",
":=",
"meta",
".",
"(",
"*",
"Config",
")",
"\n",
"identityClient",
",",
"err",
":=",
"config",
".",
"identityV3Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"listOpts",
":=",
"roles",
".",
"ListOpts",
"{",
"DomainID",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"Name",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"listOpts",
")",
"\n\n",
"var",
"role",
"roles",
".",
"Role",
"\n",
"allPages",
",",
"err",
":=",
"roles",
".",
"List",
"(",
"identityClient",
",",
"listOpts",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"allRoles",
",",
"err",
":=",
"roles",
".",
"ExtractRoles",
"(",
"allPages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allRoles",
")",
"<",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allRoles",
")",
">",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"role",
"=",
"allRoles",
"[",
"0",
"]",
"\n\n",
"return",
"dataSourceIdentityRoleV3Attributes",
"(",
"d",
",",
"config",
",",
"&",
"role",
")",
"\n",
"}"
] | // dataSourceIdentityRoleV3Read performs the role lookup. | [
"dataSourceIdentityRoleV3Read",
"performs",
"the",
"role",
"lookup",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_role_v3.go#L38-L74 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_identity_role_v3.go | dataSourceIdentityRoleV3Attributes | func dataSourceIdentityRoleV3Attributes(d *schema.ResourceData, config *Config, role *roles.Role) error {
log.Printf("[DEBUG] openstack_identity_role_v3 details: %#v", role)
d.SetId(role.ID)
d.Set("name", role.Name)
d.Set("domain_id", role.DomainID)
d.Set("region", GetRegion(d, config))
return nil
} | go | func dataSourceIdentityRoleV3Attributes(d *schema.ResourceData, config *Config, role *roles.Role) error {
log.Printf("[DEBUG] openstack_identity_role_v3 details: %#v", role)
d.SetId(role.ID)
d.Set("name", role.Name)
d.Set("domain_id", role.DomainID)
d.Set("region", GetRegion(d, config))
return nil
} | [
"func",
"dataSourceIdentityRoleV3Attributes",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"config",
"*",
"Config",
",",
"role",
"*",
"roles",
".",
"Role",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"role",
")",
"\n\n",
"d",
".",
"SetId",
"(",
"role",
".",
"ID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"role",
".",
"Name",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"role",
".",
"DomainID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // dataSourceIdentityRoleV3Attributes populates the fields of an Role resource. | [
"dataSourceIdentityRoleV3Attributes",
"populates",
"the",
"fields",
"of",
"an",
"Role",
"resource",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_role_v3.go#L77-L86 |
terraform-providers/terraform-provider-openstack | openstack/identity_role_assignment_v3.go | identityRoleAssignmentV3ID | func identityRoleAssignmentV3ID(domainID, projectID, groupID, userID, roleID string) string {
return fmt.Sprintf("%s/%s/%s/%s/%s", domainID, projectID, groupID, userID, roleID)
} | go | func identityRoleAssignmentV3ID(domainID, projectID, groupID, userID, roleID string) string {
return fmt.Sprintf("%s/%s/%s/%s/%s", domainID, projectID, groupID, userID, roleID)
} | [
"func",
"identityRoleAssignmentV3ID",
"(",
"domainID",
",",
"projectID",
",",
"groupID",
",",
"userID",
",",
"roleID",
"string",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"domainID",
",",
"projectID",
",",
"groupID",
",",
"userID",
",",
"roleID",
")",
"\n",
"}"
] | // Role assignments have no ID in OpenStack.
// Build an ID out of the IDs that make up the role assignment | [
"Role",
"assignments",
"have",
"no",
"ID",
"in",
"OpenStack",
".",
"Build",
"an",
"ID",
"out",
"of",
"the",
"IDs",
"that",
"make",
"up",
"the",
"role",
"assignment"
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/identity_role_assignment_v3.go#L14-L16 |
terraform-providers/terraform-provider-openstack | openstack/resource_openstack_networking_subnet_v2.go | resourceSubnetAllocationPoolsCreateV2 | func resourceSubnetAllocationPoolsCreateV2(d *schema.ResourceData) []subnets.AllocationPool {
// First check allocation_pool since that is the new argument.
rawAPs := d.Get("allocation_pool").(*schema.Set).List()
if len(rawAPs) == 0 {
// If no allocation_pool was specified, check allocation_pools
// which is the older legacy argument.
rawAPs = d.Get("allocation_pools").([]interface{})
}
aps := make([]subnets.AllocationPool, len(rawAPs))
for i, raw := range rawAPs {
rawMap := raw.(map[string]interface{})
aps[i] = subnets.AllocationPool{
Start: rawMap["start"].(string),
End: rawMap["end"].(string),
}
}
return aps
} | go | func resourceSubnetAllocationPoolsCreateV2(d *schema.ResourceData) []subnets.AllocationPool {
// First check allocation_pool since that is the new argument.
rawAPs := d.Get("allocation_pool").(*schema.Set).List()
if len(rawAPs) == 0 {
// If no allocation_pool was specified, check allocation_pools
// which is the older legacy argument.
rawAPs = d.Get("allocation_pools").([]interface{})
}
aps := make([]subnets.AllocationPool, len(rawAPs))
for i, raw := range rawAPs {
rawMap := raw.(map[string]interface{})
aps[i] = subnets.AllocationPool{
Start: rawMap["start"].(string),
End: rawMap["end"].(string),
}
}
return aps
} | [
"func",
"resourceSubnetAllocationPoolsCreateV2",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
")",
"[",
"]",
"subnets",
".",
"AllocationPool",
"{",
"// First check allocation_pool since that is the new argument.",
"rawAPs",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"*",
"schema",
".",
"Set",
")",
".",
"List",
"(",
")",
"\n\n",
"if",
"len",
"(",
"rawAPs",
")",
"==",
"0",
"{",
"// If no allocation_pool was specified, check allocation_pools",
"// which is the older legacy argument.",
"rawAPs",
"=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
"\n",
"}",
"\n\n",
"aps",
":=",
"make",
"(",
"[",
"]",
"subnets",
".",
"AllocationPool",
",",
"len",
"(",
"rawAPs",
")",
")",
"\n",
"for",
"i",
",",
"raw",
":=",
"range",
"rawAPs",
"{",
"rawMap",
":=",
"raw",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"aps",
"[",
"i",
"]",
"=",
"subnets",
".",
"AllocationPool",
"{",
"Start",
":",
"rawMap",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
",",
"End",
":",
"rawMap",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
",",
"}",
"\n",
"}",
"\n",
"return",
"aps",
"\n",
"}"
] | // resourceSubnetAllocationPoolsCreateV2 returns a slice of allocation pools
// when creating a subnet. It takes into account both the old allocation_pools
// argument as well as the new allocation_pool argument.
//
// This can be modified to only account for allocation_pool when
// allocation_pools is removed. | [
"resourceSubnetAllocationPoolsCreateV2",
"returns",
"a",
"slice",
"of",
"allocation",
"pools",
"when",
"creating",
"a",
"subnet",
".",
"It",
"takes",
"into",
"account",
"both",
"the",
"old",
"allocation_pools",
"argument",
"as",
"well",
"as",
"the",
"new",
"allocation_pool",
"argument",
".",
"This",
"can",
"be",
"modified",
"to",
"only",
"account",
"for",
"allocation_pool",
"when",
"allocation_pools",
"is",
"removed",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/resource_openstack_networking_subnet_v2.go#L474-L493 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_identity_project_v3.go | dataSourceIdentityProjectV3Read | func dataSourceIdentityProjectV3Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
identityClient, err := config.identityV3Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack identity client: %s", err)
}
enabled := d.Get("enabled").(bool)
isDomain := d.Get("is_domain").(bool)
listOpts := projects.ListOpts{
DomainID: d.Get("domain_id").(string),
Enabled: &enabled,
IsDomain: &isDomain,
Name: d.Get("name").(string),
ParentID: d.Get("parent_id").(string),
}
log.Printf("[DEBUG] openstack_identity_project_v3 list options: %#v", listOpts)
var project projects.Project
allPages, err := projects.List(identityClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query openstack_identity_project_v3: %s", err)
}
allProjects, err := projects.ExtractProjects(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve openstack_identity_project_v3: %s", err)
}
if len(allProjects) < 1 {
return fmt.Errorf("Your openstack_identity_project_v3 query returned no results. " +
"Please change your search criteria and try again.")
}
if len(allProjects) > 1 {
return fmt.Errorf("Your openstack_identity_project_v3 query returned more than one result.")
}
project = allProjects[0]
return dataSourceIdentityProjectV3Attributes(d, &project)
} | go | func dataSourceIdentityProjectV3Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
identityClient, err := config.identityV3Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack identity client: %s", err)
}
enabled := d.Get("enabled").(bool)
isDomain := d.Get("is_domain").(bool)
listOpts := projects.ListOpts{
DomainID: d.Get("domain_id").(string),
Enabled: &enabled,
IsDomain: &isDomain,
Name: d.Get("name").(string),
ParentID: d.Get("parent_id").(string),
}
log.Printf("[DEBUG] openstack_identity_project_v3 list options: %#v", listOpts)
var project projects.Project
allPages, err := projects.List(identityClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query openstack_identity_project_v3: %s", err)
}
allProjects, err := projects.ExtractProjects(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve openstack_identity_project_v3: %s", err)
}
if len(allProjects) < 1 {
return fmt.Errorf("Your openstack_identity_project_v3 query returned no results. " +
"Please change your search criteria and try again.")
}
if len(allProjects) > 1 {
return fmt.Errorf("Your openstack_identity_project_v3 query returned more than one result.")
}
project = allProjects[0]
return dataSourceIdentityProjectV3Attributes(d, &project)
} | [
"func",
"dataSourceIdentityProjectV3Read",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"meta",
"interface",
"{",
"}",
")",
"error",
"{",
"config",
":=",
"meta",
".",
"(",
"*",
"Config",
")",
"\n",
"identityClient",
",",
"err",
":=",
"config",
".",
"identityV3Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"enabled",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"bool",
")",
"\n",
"isDomain",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"bool",
")",
"\n",
"listOpts",
":=",
"projects",
".",
"ListOpts",
"{",
"DomainID",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"Enabled",
":",
"&",
"enabled",
",",
"IsDomain",
":",
"&",
"isDomain",
",",
"Name",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"ParentID",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"listOpts",
")",
"\n\n",
"var",
"project",
"projects",
".",
"Project",
"\n",
"allPages",
",",
"err",
":=",
"projects",
".",
"List",
"(",
"identityClient",
",",
"listOpts",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"allProjects",
",",
"err",
":=",
"projects",
".",
"ExtractProjects",
"(",
"allPages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allProjects",
")",
"<",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allProjects",
")",
">",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"project",
"=",
"allProjects",
"[",
"0",
"]",
"\n\n",
"return",
"dataSourceIdentityProjectV3Attributes",
"(",
"d",
",",
"&",
"project",
")",
"\n",
"}"
] | // dataSourceIdentityProjectV3Read performs the project lookup. | [
"dataSourceIdentityProjectV3Read",
"performs",
"the",
"project",
"lookup",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_project_v3.go#L60-L102 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_identity_project_v3.go | dataSourceIdentityProjectV3Attributes | func dataSourceIdentityProjectV3Attributes(d *schema.ResourceData, project *projects.Project) error {
log.Printf("[DEBUG] openstack_identity_project_v3 details: %#v", project)
d.SetId(project.ID)
d.Set("is_domain", project.IsDomain)
d.Set("description", project.Description)
d.Set("domain_id", project.DomainID)
d.Set("enabled", project.Enabled)
d.Set("name", project.Name)
d.Set("parent_id", project.ParentID)
return nil
} | go | func dataSourceIdentityProjectV3Attributes(d *schema.ResourceData, project *projects.Project) error {
log.Printf("[DEBUG] openstack_identity_project_v3 details: %#v", project)
d.SetId(project.ID)
d.Set("is_domain", project.IsDomain)
d.Set("description", project.Description)
d.Set("domain_id", project.DomainID)
d.Set("enabled", project.Enabled)
d.Set("name", project.Name)
d.Set("parent_id", project.ParentID)
return nil
} | [
"func",
"dataSourceIdentityProjectV3Attributes",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"project",
"*",
"projects",
".",
"Project",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"project",
")",
"\n\n",
"d",
".",
"SetId",
"(",
"project",
".",
"ID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"project",
".",
"IsDomain",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"project",
".",
"Description",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"project",
".",
"DomainID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"project",
".",
"Enabled",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"project",
".",
"Name",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"project",
".",
"ParentID",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // dataSourceIdentityProjectV3Attributes populates the fields of an Project resource. | [
"dataSourceIdentityProjectV3Attributes",
"populates",
"the",
"fields",
"of",
"an",
"Project",
"resource",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_project_v3.go#L105-L117 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_compute_flavor_v2.go | dataSourceComputeFlavorV2Read | func dataSourceComputeFlavorV2Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
computeClient, err := config.computeV2Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack compute client: %s", err)
}
var allFlavors []flavors.Flavor
if v := d.Get("flavor_id").(string); v != "" {
flavor, err := flavors.Get(computeClient, v).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
return fmt.Errorf("No Flavor found")
}
return fmt.Errorf("Unable to retrieve OpenStack %s flavor: %s", v, err)
}
allFlavors = append(allFlavors, *flavor)
} else {
listOpts := flavors.ListOpts{
MinDisk: d.Get("min_disk").(int),
MinRAM: d.Get("min_ram").(int),
AccessType: flavors.PublicAccess,
}
log.Printf("[DEBUG] openstack_compute_flavor_v2 ListOpts: %#v", listOpts)
allPages, err := flavors.ListDetail(computeClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query OpenStack flavors: %s", err)
}
allFlavors, err = flavors.ExtractFlavors(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve OpenStack flavors: %s", err)
}
}
// Loop through all flavors to find a more specific one.
if len(allFlavors) > 0 {
var filteredFlavors []flavors.Flavor
for _, flavor := range allFlavors {
if v := d.Get("name").(string); v != "" {
if flavor.Name != v {
continue
}
}
// d.GetOk is used because 0 might be a valid choice.
if v, ok := d.GetOk("ram"); ok {
if flavor.RAM != v.(int) {
continue
}
}
if v, ok := d.GetOk("vcpus"); ok {
if flavor.VCPUs != v.(int) {
continue
}
}
if v, ok := d.GetOk("disk"); ok {
if flavor.Disk != v.(int) {
continue
}
}
if v, ok := d.GetOk("swap"); ok {
if flavor.Swap != v.(int) {
continue
}
}
if v, ok := d.GetOk("rx_tx_factor"); ok {
if flavor.RxTxFactor != v.(float64) {
continue
}
}
filteredFlavors = append(filteredFlavors, flavor)
}
allFlavors = filteredFlavors
}
if len(allFlavors) < 1 {
return fmt.Errorf("Your query returned no results. " +
"Please change your search criteria and try again.")
}
if len(allFlavors) > 1 {
log.Printf("[DEBUG] Multiple results found: %#v", allFlavors)
return fmt.Errorf("Your query returned more than one result. " +
"Please try a more specific search criteria")
}
return dataSourceComputeFlavorV2Attributes(d, computeClient, &allFlavors[0])
} | go | func dataSourceComputeFlavorV2Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
computeClient, err := config.computeV2Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack compute client: %s", err)
}
var allFlavors []flavors.Flavor
if v := d.Get("flavor_id").(string); v != "" {
flavor, err := flavors.Get(computeClient, v).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
return fmt.Errorf("No Flavor found")
}
return fmt.Errorf("Unable to retrieve OpenStack %s flavor: %s", v, err)
}
allFlavors = append(allFlavors, *flavor)
} else {
listOpts := flavors.ListOpts{
MinDisk: d.Get("min_disk").(int),
MinRAM: d.Get("min_ram").(int),
AccessType: flavors.PublicAccess,
}
log.Printf("[DEBUG] openstack_compute_flavor_v2 ListOpts: %#v", listOpts)
allPages, err := flavors.ListDetail(computeClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query OpenStack flavors: %s", err)
}
allFlavors, err = flavors.ExtractFlavors(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve OpenStack flavors: %s", err)
}
}
// Loop through all flavors to find a more specific one.
if len(allFlavors) > 0 {
var filteredFlavors []flavors.Flavor
for _, flavor := range allFlavors {
if v := d.Get("name").(string); v != "" {
if flavor.Name != v {
continue
}
}
// d.GetOk is used because 0 might be a valid choice.
if v, ok := d.GetOk("ram"); ok {
if flavor.RAM != v.(int) {
continue
}
}
if v, ok := d.GetOk("vcpus"); ok {
if flavor.VCPUs != v.(int) {
continue
}
}
if v, ok := d.GetOk("disk"); ok {
if flavor.Disk != v.(int) {
continue
}
}
if v, ok := d.GetOk("swap"); ok {
if flavor.Swap != v.(int) {
continue
}
}
if v, ok := d.GetOk("rx_tx_factor"); ok {
if flavor.RxTxFactor != v.(float64) {
continue
}
}
filteredFlavors = append(filteredFlavors, flavor)
}
allFlavors = filteredFlavors
}
if len(allFlavors) < 1 {
return fmt.Errorf("Your query returned no results. " +
"Please change your search criteria and try again.")
}
if len(allFlavors) > 1 {
log.Printf("[DEBUG] Multiple results found: %#v", allFlavors)
return fmt.Errorf("Your query returned more than one result. " +
"Please try a more specific search criteria")
}
return dataSourceComputeFlavorV2Attributes(d, computeClient, &allFlavors[0])
} | [
"func",
"dataSourceComputeFlavorV2Read",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"meta",
"interface",
"{",
"}",
")",
"error",
"{",
"config",
":=",
"meta",
".",
"(",
"*",
"Config",
")",
"\n",
"computeClient",
",",
"err",
":=",
"config",
".",
"computeV2Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"allFlavors",
"[",
"]",
"flavors",
".",
"Flavor",
"\n",
"if",
"v",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
";",
"v",
"!=",
"\"",
"\"",
"{",
"flavor",
",",
"err",
":=",
"flavors",
".",
"Get",
"(",
"computeClient",
",",
"v",
")",
".",
"Extract",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"gophercloud",
".",
"ErrDefault404",
")",
";",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
",",
"err",
")",
"\n",
"}",
"\n\n",
"allFlavors",
"=",
"append",
"(",
"allFlavors",
",",
"*",
"flavor",
")",
"\n",
"}",
"else",
"{",
"listOpts",
":=",
"flavors",
".",
"ListOpts",
"{",
"MinDisk",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"int",
")",
",",
"MinRAM",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"int",
")",
",",
"AccessType",
":",
"flavors",
".",
"PublicAccess",
",",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"listOpts",
")",
"\n\n",
"allPages",
",",
"err",
":=",
"flavors",
".",
"ListDetail",
"(",
"computeClient",
",",
"listOpts",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"allFlavors",
",",
"err",
"=",
"flavors",
".",
"ExtractFlavors",
"(",
"allPages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Loop through all flavors to find a more specific one.",
"if",
"len",
"(",
"allFlavors",
")",
">",
"0",
"{",
"var",
"filteredFlavors",
"[",
"]",
"flavors",
".",
"Flavor",
"\n",
"for",
"_",
",",
"flavor",
":=",
"range",
"allFlavors",
"{",
"if",
"v",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
";",
"v",
"!=",
"\"",
"\"",
"{",
"if",
"flavor",
".",
"Name",
"!=",
"v",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"// d.GetOk is used because 0 might be a valid choice.",
"if",
"v",
",",
"ok",
":=",
"d",
".",
"GetOk",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"if",
"flavor",
".",
"RAM",
"!=",
"v",
".",
"(",
"int",
")",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"v",
",",
"ok",
":=",
"d",
".",
"GetOk",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"if",
"flavor",
".",
"VCPUs",
"!=",
"v",
".",
"(",
"int",
")",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"v",
",",
"ok",
":=",
"d",
".",
"GetOk",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"if",
"flavor",
".",
"Disk",
"!=",
"v",
".",
"(",
"int",
")",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"v",
",",
"ok",
":=",
"d",
".",
"GetOk",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"if",
"flavor",
".",
"Swap",
"!=",
"v",
".",
"(",
"int",
")",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"v",
",",
"ok",
":=",
"d",
".",
"GetOk",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"if",
"flavor",
".",
"RxTxFactor",
"!=",
"v",
".",
"(",
"float64",
")",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"filteredFlavors",
"=",
"append",
"(",
"filteredFlavors",
",",
"flavor",
")",
"\n",
"}",
"\n\n",
"allFlavors",
"=",
"filteredFlavors",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allFlavors",
")",
"<",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allFlavors",
")",
">",
"1",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"allFlavors",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"dataSourceComputeFlavorV2Attributes",
"(",
"d",
",",
"computeClient",
",",
"&",
"allFlavors",
"[",
"0",
"]",
")",
"\n",
"}"
] | // dataSourceComputeFlavorV2Read performs the flavor lookup. | [
"dataSourceComputeFlavorV2Read",
"performs",
"the",
"flavor",
"lookup",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_compute_flavor_v2.go#L98-L195 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_compute_flavor_v2.go | dataSourceComputeFlavorV2Attributes | func dataSourceComputeFlavorV2Attributes(
d *schema.ResourceData, computeClient *gophercloud.ServiceClient, flavor *flavors.Flavor) error {
log.Printf("[DEBUG] Retrieved openstack_compute_flavor_v2 %s: %#v", flavor.ID, flavor)
d.SetId(flavor.ID)
d.Set("name", flavor.Name)
d.Set("flavor_id", flavor.ID)
d.Set("disk", flavor.Disk)
d.Set("ram", flavor.RAM)
d.Set("rx_tx_factor", flavor.RxTxFactor)
d.Set("swap", flavor.Swap)
d.Set("vcpus", flavor.VCPUs)
d.Set("is_public", flavor.IsPublic)
es, err := flavors.ListExtraSpecs(computeClient, d.Id()).Extract()
if err != nil {
return err
}
if err := d.Set("extra_specs", es); err != nil {
log.Printf("[WARN] Unable to set extra_specs for openstack_compute_flavor_v2 %s: %s", d.Id(), err)
}
return nil
} | go | func dataSourceComputeFlavorV2Attributes(
d *schema.ResourceData, computeClient *gophercloud.ServiceClient, flavor *flavors.Flavor) error {
log.Printf("[DEBUG] Retrieved openstack_compute_flavor_v2 %s: %#v", flavor.ID, flavor)
d.SetId(flavor.ID)
d.Set("name", flavor.Name)
d.Set("flavor_id", flavor.ID)
d.Set("disk", flavor.Disk)
d.Set("ram", flavor.RAM)
d.Set("rx_tx_factor", flavor.RxTxFactor)
d.Set("swap", flavor.Swap)
d.Set("vcpus", flavor.VCPUs)
d.Set("is_public", flavor.IsPublic)
es, err := flavors.ListExtraSpecs(computeClient, d.Id()).Extract()
if err != nil {
return err
}
if err := d.Set("extra_specs", es); err != nil {
log.Printf("[WARN] Unable to set extra_specs for openstack_compute_flavor_v2 %s: %s", d.Id(), err)
}
return nil
} | [
"func",
"dataSourceComputeFlavorV2Attributes",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"computeClient",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"flavor",
"*",
"flavors",
".",
"Flavor",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"flavor",
".",
"ID",
",",
"flavor",
")",
"\n\n",
"d",
".",
"SetId",
"(",
"flavor",
".",
"ID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"flavor",
".",
"Name",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"flavor",
".",
"ID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"flavor",
".",
"Disk",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"flavor",
".",
"RAM",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"flavor",
".",
"RxTxFactor",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"flavor",
".",
"Swap",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"flavor",
".",
"VCPUs",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"flavor",
".",
"IsPublic",
")",
"\n\n",
"es",
",",
"err",
":=",
"flavors",
".",
"ListExtraSpecs",
"(",
"computeClient",
",",
"d",
".",
"Id",
"(",
")",
")",
".",
"Extract",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"es",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"d",
".",
"Id",
"(",
")",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // dataSourceComputeFlavorV2Attributes populates the fields of a Flavor resource. | [
"dataSourceComputeFlavorV2Attributes",
"populates",
"the",
"fields",
"of",
"a",
"Flavor",
"resource",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_compute_flavor_v2.go#L198-L223 |
terraform-providers/terraform-provider-openstack | openstack/resource_openstack_objectstorage_tempurl_v1.go | resourceObjectstorageTempurlV1Create | func resourceObjectstorageTempurlV1Create(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
objectStorageClient, err := config.objectStorageV1Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack compute client: %s", err)
}
method := objects.GET
switch d.Get("method") {
case "post":
method = objects.POST
// gophercloud doesn't have support for PUT yet,
// although it's a valid method for swift
//case "put":
// method = objects.PUT
}
turlOptions := objects.CreateTempURLOpts{
Method: method,
TTL: d.Get("ttl").(int),
Split: d.Get("split").(string),
}
containerName := d.Get("container").(string)
objectName := d.Get("object").(string)
log.Printf("[DEBUG] Create temporary url Options: %#v", turlOptions)
url, err := objects.CreateTempURL(objectStorageClient, containerName, objectName, turlOptions)
if err != nil {
return fmt.Errorf("Unable to generate a temporary url for the object %s in container %s: %s",
objectName, containerName, err)
}
log.Printf("[DEBUG] URL Generated: %s", url)
// Set the URL and Id fields.
hasher := md5.New()
hasher.Write([]byte(url))
d.SetId(hex.EncodeToString(hasher.Sum(nil)))
d.Set("url", url)
return nil
} | go | func resourceObjectstorageTempurlV1Create(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
objectStorageClient, err := config.objectStorageV1Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack compute client: %s", err)
}
method := objects.GET
switch d.Get("method") {
case "post":
method = objects.POST
// gophercloud doesn't have support for PUT yet,
// although it's a valid method for swift
//case "put":
// method = objects.PUT
}
turlOptions := objects.CreateTempURLOpts{
Method: method,
TTL: d.Get("ttl").(int),
Split: d.Get("split").(string),
}
containerName := d.Get("container").(string)
objectName := d.Get("object").(string)
log.Printf("[DEBUG] Create temporary url Options: %#v", turlOptions)
url, err := objects.CreateTempURL(objectStorageClient, containerName, objectName, turlOptions)
if err != nil {
return fmt.Errorf("Unable to generate a temporary url for the object %s in container %s: %s",
objectName, containerName, err)
}
log.Printf("[DEBUG] URL Generated: %s", url)
// Set the URL and Id fields.
hasher := md5.New()
hasher.Write([]byte(url))
d.SetId(hex.EncodeToString(hasher.Sum(nil)))
d.Set("url", url)
return nil
} | [
"func",
"resourceObjectstorageTempurlV1Create",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"meta",
"interface",
"{",
"}",
")",
"error",
"{",
"config",
":=",
"meta",
".",
"(",
"*",
"Config",
")",
"\n",
"objectStorageClient",
",",
"err",
":=",
"config",
".",
"objectStorageV1Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"method",
":=",
"objects",
".",
"GET",
"\n",
"switch",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
"{",
"case",
"\"",
"\"",
":",
"method",
"=",
"objects",
".",
"POST",
"\n",
"// gophercloud doesn't have support for PUT yet,",
"// although it's a valid method for swift",
"//case \"put\":",
"//\tmethod = objects.PUT",
"}",
"\n\n",
"turlOptions",
":=",
"objects",
".",
"CreateTempURLOpts",
"{",
"Method",
":",
"method",
",",
"TTL",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"int",
")",
",",
"Split",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"}",
"\n\n",
"containerName",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
"\n",
"objectName",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"turlOptions",
")",
"\n\n",
"url",
",",
"err",
":=",
"objects",
".",
"CreateTempURL",
"(",
"objectStorageClient",
",",
"containerName",
",",
"objectName",
",",
"turlOptions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"objectName",
",",
"containerName",
",",
"err",
")",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"url",
")",
"\n\n",
"// Set the URL and Id fields.",
"hasher",
":=",
"md5",
".",
"New",
"(",
")",
"\n",
"hasher",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"url",
")",
")",
"\n",
"d",
".",
"SetId",
"(",
"hex",
".",
"EncodeToString",
"(",
"hasher",
".",
"Sum",
"(",
"nil",
")",
")",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"url",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // resourceObjectstorageTempurlV1Create performs the image lookup. | [
"resourceObjectstorageTempurlV1Create",
"performs",
"the",
"image",
"lookup",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/resource_openstack_objectstorage_tempurl_v1.go#L85-L127 |
terraform-providers/terraform-provider-openstack | openstack/resource_openstack_objectstorage_tempurl_v1.go | resourceObjectstorageTempurlV1Read | func resourceObjectstorageTempurlV1Read(d *schema.ResourceData, meta interface{}) error {
turl := d.Get("url").(string)
u, err := url.Parse(turl)
if err != nil {
return fmt.Errorf("Failed to read the temporary url %s: %s", turl, err)
}
qp, err := url.ParseQuery(u.RawQuery)
if err != nil {
return fmt.Errorf("Failed to parse the temporary url %s query string: %s", turl, err)
}
tempURLExpires := qp.Get("temp_url_expires")
expiry, err := strconv.ParseInt(tempURLExpires, 10, 64)
if err != nil {
return fmt.Errorf(
"Failed to parse the temporary url %s expiration time %s: %s",
turl, tempURLExpires, err)
}
// Regenerate the URL if it has expired and if the user requested it to be.
regen := d.Get("regenerate").(bool)
now := time.Now().Unix()
if expiry < now && regen {
log.Printf("[DEBUG] temporary url %s expired, generating a new one", turl)
d.SetId("")
}
return nil
} | go | func resourceObjectstorageTempurlV1Read(d *schema.ResourceData, meta interface{}) error {
turl := d.Get("url").(string)
u, err := url.Parse(turl)
if err != nil {
return fmt.Errorf("Failed to read the temporary url %s: %s", turl, err)
}
qp, err := url.ParseQuery(u.RawQuery)
if err != nil {
return fmt.Errorf("Failed to parse the temporary url %s query string: %s", turl, err)
}
tempURLExpires := qp.Get("temp_url_expires")
expiry, err := strconv.ParseInt(tempURLExpires, 10, 64)
if err != nil {
return fmt.Errorf(
"Failed to parse the temporary url %s expiration time %s: %s",
turl, tempURLExpires, err)
}
// Regenerate the URL if it has expired and if the user requested it to be.
regen := d.Get("regenerate").(bool)
now := time.Now().Unix()
if expiry < now && regen {
log.Printf("[DEBUG] temporary url %s expired, generating a new one", turl)
d.SetId("")
}
return nil
} | [
"func",
"resourceObjectstorageTempurlV1Read",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"meta",
"interface",
"{",
"}",
")",
"error",
"{",
"turl",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
"\n",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"turl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"turl",
",",
"err",
")",
"\n",
"}",
"\n\n",
"qp",
",",
"err",
":=",
"url",
".",
"ParseQuery",
"(",
"u",
".",
"RawQuery",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"turl",
",",
"err",
")",
"\n",
"}",
"\n\n",
"tempURLExpires",
":=",
"qp",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"expiry",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"tempURLExpires",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"turl",
",",
"tempURLExpires",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Regenerate the URL if it has expired and if the user requested it to be.",
"regen",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"bool",
")",
"\n",
"now",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Unix",
"(",
")",
"\n",
"if",
"expiry",
"<",
"now",
"&&",
"regen",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"turl",
")",
"\n",
"d",
".",
"SetId",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // resourceObjectstorageTempurlV1Read performs the image lookup. | [
"resourceObjectstorageTempurlV1Read",
"performs",
"the",
"image",
"lookup",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/resource_openstack_objectstorage_tempurl_v1.go#L130-L159 |
terraform-providers/terraform-provider-openstack | openstack/provider.go | Provider | func Provider() terraform.ResourceProvider {
return &schema.Provider{
Schema: map[string]*schema.Schema{
"auth_url": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_AUTH_URL", ""),
Description: descriptions["auth_url"],
},
"region": {
Type: schema.TypeString,
Optional: true,
Description: descriptions["region"],
DefaultFunc: schema.EnvDefaultFunc("OS_REGION_NAME", ""),
},
"user_name": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_USERNAME", ""),
Description: descriptions["user_name"],
},
"user_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_USER_ID", ""),
Description: descriptions["user_name"],
},
"application_credential_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_APPLICATION_CREDENTIAL_ID", ""),
Description: descriptions["application_credential_id"],
},
"application_credential_name": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_APPLICATION_CREDENTIAL_NAME", ""),
Description: descriptions["application_credential_name"],
},
"application_credential_secret": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_APPLICATION_CREDENTIAL_SECRET", ""),
Description: descriptions["application_credential_secret"],
},
"tenant_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.MultiEnvDefaultFunc([]string{
"OS_TENANT_ID",
"OS_PROJECT_ID",
}, ""),
Description: descriptions["tenant_id"],
},
"tenant_name": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.MultiEnvDefaultFunc([]string{
"OS_TENANT_NAME",
"OS_PROJECT_NAME",
}, ""),
Description: descriptions["tenant_name"],
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("OS_PASSWORD", ""),
Description: descriptions["password"],
},
"token": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.MultiEnvDefaultFunc([]string{
"OS_TOKEN",
"OS_AUTH_TOKEN",
}, ""),
Description: descriptions["token"],
},
"user_domain_name": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_USER_DOMAIN_NAME", ""),
Description: descriptions["user_domain_name"],
},
"user_domain_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_USER_DOMAIN_ID", ""),
Description: descriptions["user_domain_id"],
},
"project_domain_name": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_PROJECT_DOMAIN_NAME", ""),
Description: descriptions["project_domain_name"],
},
"project_domain_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_PROJECT_DOMAIN_ID", ""),
Description: descriptions["project_domain_id"],
},
"domain_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_DOMAIN_ID", ""),
Description: descriptions["domain_id"],
},
"domain_name": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_DOMAIN_NAME", ""),
Description: descriptions["domain_name"],
},
"default_domain": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_DEFAULT_DOMAIN", "default"),
Description: descriptions["default_domain"],
},
"insecure": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_INSECURE", nil),
Description: descriptions["insecure"],
},
"endpoint_type": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_ENDPOINT_TYPE", ""),
},
"cacert_file": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_CACERT", ""),
Description: descriptions["cacert_file"],
},
"cert": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_CERT", ""),
Description: descriptions["cert"],
},
"key": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_KEY", ""),
Description: descriptions["key"],
},
"swauth": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_SWAUTH", false),
Description: descriptions["swauth"],
},
"use_octavia": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_USE_OCTAVIA", false),
Description: descriptions["use_octavia"],
},
"cloud": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_CLOUD", ""),
Description: descriptions["cloud"],
},
"max_retries": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
Description: descriptions["max_retries"],
},
"endpoint_overrides": {
Type: schema.TypeMap,
Optional: true,
Description: descriptions["endpoint_overrides"],
},
},
DataSourcesMap: map[string]*schema.Resource{
"openstack_blockstorage_availability_zones_v3": dataSourceBlockStorageAvailabilityZonesV3(),
"openstack_blockstorage_snapshot_v2": dataSourceBlockStorageSnapshotV2(),
"openstack_blockstorage_snapshot_v3": dataSourceBlockStorageSnapshotV3(),
"openstack_compute_availability_zones_v2": dataSourceComputeAvailabilityZonesV2(),
"openstack_compute_flavor_v2": dataSourceComputeFlavorV2(),
"openstack_compute_keypair_v2": dataSourceComputeKeypairV2(),
"openstack_containerinfra_clustertemplate_v1": dataSourceContainerInfraClusterTemplateV1(),
"openstack_containerinfra_cluster_v1": dataSourceContainerInfraCluster(),
"openstack_dns_zone_v2": dataSourceDNSZoneV2(),
"openstack_fw_policy_v1": dataSourceFWPolicyV1(),
"openstack_identity_role_v3": dataSourceIdentityRoleV3(),
"openstack_identity_project_v3": dataSourceIdentityProjectV3(),
"openstack_identity_user_v3": dataSourceIdentityUserV3(),
"openstack_identity_auth_scope_v3": dataSourceIdentityAuthScopeV3(),
"openstack_identity_endpoint_v3": dataSourceIdentityEndpointV3(),
"openstack_identity_group_v3": dataSourceIdentityGroupV3(),
"openstack_images_image_v2": dataSourceImagesImageV2(),
"openstack_networking_addressscope_v2": dataSourceNetworkingAddressScopeV2(),
"openstack_networking_network_v2": dataSourceNetworkingNetworkV2(),
"openstack_networking_subnet_v2": dataSourceNetworkingSubnetV2(),
"openstack_networking_secgroup_v2": dataSourceNetworkingSecGroupV2(),
"openstack_networking_subnetpool_v2": dataSourceNetworkingSubnetPoolV2(),
"openstack_networking_floatingip_v2": dataSourceNetworkingFloatingIPV2(),
"openstack_networking_router_v2": dataSourceNetworkingRouterV2(),
"openstack_networking_port_v2": dataSourceNetworkingPortV2(),
"openstack_networking_port_ids_v2": dataSourceNetworkingPortIDsV2(),
"openstack_networking_trunk_v2": dataSourceNetworkingTrunkV2(),
"openstack_sharedfilesystem_availability_zones_v2": dataSourceSharedFilesystemAvailabilityZonesV2(),
"openstack_sharedfilesystem_sharenetwork_v2": dataSourceSharedFilesystemShareNetworkV2(),
"openstack_sharedfilesystem_share_v2": dataSourceSharedFilesystemShareV2(),
"openstack_sharedfilesystem_snapshot_v2": dataSourceSharedFilesystemSnapshotV2(),
},
ResourcesMap: map[string]*schema.Resource{
"openstack_blockstorage_volume_v1": resourceBlockStorageVolumeV1(),
"openstack_blockstorage_volume_v2": resourceBlockStorageVolumeV2(),
"openstack_blockstorage_volume_v3": resourceBlockStorageVolumeV3(),
"openstack_blockstorage_volume_attach_v2": resourceBlockStorageVolumeAttachV2(),
"openstack_blockstorage_volume_attach_v3": resourceBlockStorageVolumeAttachV3(),
"openstack_compute_flavor_v2": resourceComputeFlavorV2(),
"openstack_compute_flavor_access_v2": resourceComputeFlavorAccessV2(),
"openstack_compute_instance_v2": resourceComputeInstanceV2(),
"openstack_compute_interface_attach_v2": resourceComputeInterfaceAttachV2(),
"openstack_compute_keypair_v2": resourceComputeKeypairV2(),
"openstack_compute_secgroup_v2": resourceComputeSecGroupV2(),
"openstack_compute_servergroup_v2": resourceComputeServerGroupV2(),
"openstack_compute_floatingip_v2": resourceComputeFloatingIPV2(),
"openstack_compute_floatingip_associate_v2": resourceComputeFloatingIPAssociateV2(),
"openstack_compute_volume_attach_v2": resourceComputeVolumeAttachV2(),
"openstack_containerinfra_clustertemplate_v1": resourceContainerInfraClusterTemplateV1(),
"openstack_containerinfra_cluster_v1": resourceContainerInfraClusterV1(),
"openstack_db_instance_v1": resourceDatabaseInstanceV1(),
"openstack_db_user_v1": resourceDatabaseUserV1(),
"openstack_db_configuration_v1": resourceDatabaseConfigurationV1(),
"openstack_db_database_v1": resourceDatabaseDatabaseV1(),
"openstack_dns_recordset_v2": resourceDNSRecordSetV2(),
"openstack_dns_zone_v2": resourceDNSZoneV2(),
"openstack_fw_firewall_v1": resourceFWFirewallV1(),
"openstack_fw_policy_v1": resourceFWPolicyV1(),
"openstack_fw_rule_v1": resourceFWRuleV1(),
"openstack_identity_project_v3": resourceIdentityProjectV3(),
"openstack_identity_role_v3": resourceIdentityRoleV3(),
"openstack_identity_role_assignment_v3": resourceIdentityRoleAssignmentV3(),
"openstack_identity_user_v3": resourceIdentityUserV3(),
"openstack_identity_application_credential_v3": resourceIdentityApplicationCredentialV3(),
"openstack_images_image_v2": resourceImagesImageV2(),
"openstack_lb_member_v1": resourceLBMemberV1(),
"openstack_lb_monitor_v1": resourceLBMonitorV1(),
"openstack_lb_pool_v1": resourceLBPoolV1(),
"openstack_lb_vip_v1": resourceLBVipV1(),
"openstack_lb_loadbalancer_v2": resourceLoadBalancerV2(),
"openstack_lb_listener_v2": resourceListenerV2(),
"openstack_lb_pool_v2": resourcePoolV2(),
"openstack_lb_member_v2": resourceMemberV2(),
"openstack_lb_monitor_v2": resourceMonitorV2(),
"openstack_lb_l7policy_v2": resourceL7PolicyV2(),
"openstack_lb_l7rule_v2": resourceL7RuleV2(),
"openstack_networking_floatingip_v2": resourceNetworkingFloatingIPV2(),
"openstack_networking_floatingip_associate_v2": resourceNetworkingFloatingIPAssociateV2(),
"openstack_networking_network_v2": resourceNetworkingNetworkV2(),
"openstack_networking_port_v2": resourceNetworkingPortV2(),
"openstack_networking_port_secgroup_associate_v2": resourceNetworkingPortSecGroupAssociateV2(),
"openstack_networking_router_v2": resourceNetworkingRouterV2(),
"openstack_networking_router_interface_v2": resourceNetworkingRouterInterfaceV2(),
"openstack_networking_router_route_v2": resourceNetworkingRouterRouteV2(),
"openstack_networking_secgroup_v2": resourceNetworkingSecGroupV2(),
"openstack_networking_secgroup_rule_v2": resourceNetworkingSecGroupRuleV2(),
"openstack_networking_subnet_v2": resourceNetworkingSubnetV2(),
"openstack_networking_subnet_route_v2": resourceNetworkingSubnetRouteV2(),
"openstack_networking_subnetpool_v2": resourceNetworkingSubnetPoolV2(),
"openstack_networking_addressscope_v2": resourceNetworkingAddressScopeV2(),
"openstack_networking_trunk_v2": resourceNetworkingTrunkV2(),
"openstack_objectstorage_container_v1": resourceObjectStorageContainerV1(),
"openstack_objectstorage_object_v1": resourceObjectStorageObjectV1(),
"openstack_objectstorage_tempurl_v1": resourceObjectstorageTempurlV1(),
"openstack_vpnaas_ipsec_policy_v2": resourceIPSecPolicyV2(),
"openstack_vpnaas_service_v2": resourceServiceV2(),
"openstack_vpnaas_ike_policy_v2": resourceIKEPolicyV2(),
"openstack_vpnaas_endpoint_group_v2": resourceEndpointGroupV2(),
"openstack_vpnaas_site_connection_v2": resourceSiteConnectionV2(),
"openstack_sharedfilesystem_securityservice_v2": resourceSharedFilesystemSecurityServiceV2(),
"openstack_sharedfilesystem_sharenetwork_v2": resourceSharedFilesystemShareNetworkV2(),
"openstack_sharedfilesystem_share_v2": resourceSharedFilesystemShareV2(),
"openstack_sharedfilesystem_share_access_v2": resourceSharedFilesystemShareAccessV2(),
},
ConfigureFunc: configureProvider,
}
} | go | func Provider() terraform.ResourceProvider {
return &schema.Provider{
Schema: map[string]*schema.Schema{
"auth_url": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_AUTH_URL", ""),
Description: descriptions["auth_url"],
},
"region": {
Type: schema.TypeString,
Optional: true,
Description: descriptions["region"],
DefaultFunc: schema.EnvDefaultFunc("OS_REGION_NAME", ""),
},
"user_name": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_USERNAME", ""),
Description: descriptions["user_name"],
},
"user_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_USER_ID", ""),
Description: descriptions["user_name"],
},
"application_credential_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_APPLICATION_CREDENTIAL_ID", ""),
Description: descriptions["application_credential_id"],
},
"application_credential_name": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_APPLICATION_CREDENTIAL_NAME", ""),
Description: descriptions["application_credential_name"],
},
"application_credential_secret": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_APPLICATION_CREDENTIAL_SECRET", ""),
Description: descriptions["application_credential_secret"],
},
"tenant_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.MultiEnvDefaultFunc([]string{
"OS_TENANT_ID",
"OS_PROJECT_ID",
}, ""),
Description: descriptions["tenant_id"],
},
"tenant_name": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.MultiEnvDefaultFunc([]string{
"OS_TENANT_NAME",
"OS_PROJECT_NAME",
}, ""),
Description: descriptions["tenant_name"],
},
"password": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("OS_PASSWORD", ""),
Description: descriptions["password"],
},
"token": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.MultiEnvDefaultFunc([]string{
"OS_TOKEN",
"OS_AUTH_TOKEN",
}, ""),
Description: descriptions["token"],
},
"user_domain_name": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_USER_DOMAIN_NAME", ""),
Description: descriptions["user_domain_name"],
},
"user_domain_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_USER_DOMAIN_ID", ""),
Description: descriptions["user_domain_id"],
},
"project_domain_name": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_PROJECT_DOMAIN_NAME", ""),
Description: descriptions["project_domain_name"],
},
"project_domain_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_PROJECT_DOMAIN_ID", ""),
Description: descriptions["project_domain_id"],
},
"domain_id": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_DOMAIN_ID", ""),
Description: descriptions["domain_id"],
},
"domain_name": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_DOMAIN_NAME", ""),
Description: descriptions["domain_name"],
},
"default_domain": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_DEFAULT_DOMAIN", "default"),
Description: descriptions["default_domain"],
},
"insecure": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_INSECURE", nil),
Description: descriptions["insecure"],
},
"endpoint_type": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_ENDPOINT_TYPE", ""),
},
"cacert_file": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_CACERT", ""),
Description: descriptions["cacert_file"],
},
"cert": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_CERT", ""),
Description: descriptions["cert"],
},
"key": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_KEY", ""),
Description: descriptions["key"],
},
"swauth": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_SWAUTH", false),
Description: descriptions["swauth"],
},
"use_octavia": {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_USE_OCTAVIA", false),
Description: descriptions["use_octavia"],
},
"cloud": {
Type: schema.TypeString,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("OS_CLOUD", ""),
Description: descriptions["cloud"],
},
"max_retries": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
Description: descriptions["max_retries"],
},
"endpoint_overrides": {
Type: schema.TypeMap,
Optional: true,
Description: descriptions["endpoint_overrides"],
},
},
DataSourcesMap: map[string]*schema.Resource{
"openstack_blockstorage_availability_zones_v3": dataSourceBlockStorageAvailabilityZonesV3(),
"openstack_blockstorage_snapshot_v2": dataSourceBlockStorageSnapshotV2(),
"openstack_blockstorage_snapshot_v3": dataSourceBlockStorageSnapshotV3(),
"openstack_compute_availability_zones_v2": dataSourceComputeAvailabilityZonesV2(),
"openstack_compute_flavor_v2": dataSourceComputeFlavorV2(),
"openstack_compute_keypair_v2": dataSourceComputeKeypairV2(),
"openstack_containerinfra_clustertemplate_v1": dataSourceContainerInfraClusterTemplateV1(),
"openstack_containerinfra_cluster_v1": dataSourceContainerInfraCluster(),
"openstack_dns_zone_v2": dataSourceDNSZoneV2(),
"openstack_fw_policy_v1": dataSourceFWPolicyV1(),
"openstack_identity_role_v3": dataSourceIdentityRoleV3(),
"openstack_identity_project_v3": dataSourceIdentityProjectV3(),
"openstack_identity_user_v3": dataSourceIdentityUserV3(),
"openstack_identity_auth_scope_v3": dataSourceIdentityAuthScopeV3(),
"openstack_identity_endpoint_v3": dataSourceIdentityEndpointV3(),
"openstack_identity_group_v3": dataSourceIdentityGroupV3(),
"openstack_images_image_v2": dataSourceImagesImageV2(),
"openstack_networking_addressscope_v2": dataSourceNetworkingAddressScopeV2(),
"openstack_networking_network_v2": dataSourceNetworkingNetworkV2(),
"openstack_networking_subnet_v2": dataSourceNetworkingSubnetV2(),
"openstack_networking_secgroup_v2": dataSourceNetworkingSecGroupV2(),
"openstack_networking_subnetpool_v2": dataSourceNetworkingSubnetPoolV2(),
"openstack_networking_floatingip_v2": dataSourceNetworkingFloatingIPV2(),
"openstack_networking_router_v2": dataSourceNetworkingRouterV2(),
"openstack_networking_port_v2": dataSourceNetworkingPortV2(),
"openstack_networking_port_ids_v2": dataSourceNetworkingPortIDsV2(),
"openstack_networking_trunk_v2": dataSourceNetworkingTrunkV2(),
"openstack_sharedfilesystem_availability_zones_v2": dataSourceSharedFilesystemAvailabilityZonesV2(),
"openstack_sharedfilesystem_sharenetwork_v2": dataSourceSharedFilesystemShareNetworkV2(),
"openstack_sharedfilesystem_share_v2": dataSourceSharedFilesystemShareV2(),
"openstack_sharedfilesystem_snapshot_v2": dataSourceSharedFilesystemSnapshotV2(),
},
ResourcesMap: map[string]*schema.Resource{
"openstack_blockstorage_volume_v1": resourceBlockStorageVolumeV1(),
"openstack_blockstorage_volume_v2": resourceBlockStorageVolumeV2(),
"openstack_blockstorage_volume_v3": resourceBlockStorageVolumeV3(),
"openstack_blockstorage_volume_attach_v2": resourceBlockStorageVolumeAttachV2(),
"openstack_blockstorage_volume_attach_v3": resourceBlockStorageVolumeAttachV3(),
"openstack_compute_flavor_v2": resourceComputeFlavorV2(),
"openstack_compute_flavor_access_v2": resourceComputeFlavorAccessV2(),
"openstack_compute_instance_v2": resourceComputeInstanceV2(),
"openstack_compute_interface_attach_v2": resourceComputeInterfaceAttachV2(),
"openstack_compute_keypair_v2": resourceComputeKeypairV2(),
"openstack_compute_secgroup_v2": resourceComputeSecGroupV2(),
"openstack_compute_servergroup_v2": resourceComputeServerGroupV2(),
"openstack_compute_floatingip_v2": resourceComputeFloatingIPV2(),
"openstack_compute_floatingip_associate_v2": resourceComputeFloatingIPAssociateV2(),
"openstack_compute_volume_attach_v2": resourceComputeVolumeAttachV2(),
"openstack_containerinfra_clustertemplate_v1": resourceContainerInfraClusterTemplateV1(),
"openstack_containerinfra_cluster_v1": resourceContainerInfraClusterV1(),
"openstack_db_instance_v1": resourceDatabaseInstanceV1(),
"openstack_db_user_v1": resourceDatabaseUserV1(),
"openstack_db_configuration_v1": resourceDatabaseConfigurationV1(),
"openstack_db_database_v1": resourceDatabaseDatabaseV1(),
"openstack_dns_recordset_v2": resourceDNSRecordSetV2(),
"openstack_dns_zone_v2": resourceDNSZoneV2(),
"openstack_fw_firewall_v1": resourceFWFirewallV1(),
"openstack_fw_policy_v1": resourceFWPolicyV1(),
"openstack_fw_rule_v1": resourceFWRuleV1(),
"openstack_identity_project_v3": resourceIdentityProjectV3(),
"openstack_identity_role_v3": resourceIdentityRoleV3(),
"openstack_identity_role_assignment_v3": resourceIdentityRoleAssignmentV3(),
"openstack_identity_user_v3": resourceIdentityUserV3(),
"openstack_identity_application_credential_v3": resourceIdentityApplicationCredentialV3(),
"openstack_images_image_v2": resourceImagesImageV2(),
"openstack_lb_member_v1": resourceLBMemberV1(),
"openstack_lb_monitor_v1": resourceLBMonitorV1(),
"openstack_lb_pool_v1": resourceLBPoolV1(),
"openstack_lb_vip_v1": resourceLBVipV1(),
"openstack_lb_loadbalancer_v2": resourceLoadBalancerV2(),
"openstack_lb_listener_v2": resourceListenerV2(),
"openstack_lb_pool_v2": resourcePoolV2(),
"openstack_lb_member_v2": resourceMemberV2(),
"openstack_lb_monitor_v2": resourceMonitorV2(),
"openstack_lb_l7policy_v2": resourceL7PolicyV2(),
"openstack_lb_l7rule_v2": resourceL7RuleV2(),
"openstack_networking_floatingip_v2": resourceNetworkingFloatingIPV2(),
"openstack_networking_floatingip_associate_v2": resourceNetworkingFloatingIPAssociateV2(),
"openstack_networking_network_v2": resourceNetworkingNetworkV2(),
"openstack_networking_port_v2": resourceNetworkingPortV2(),
"openstack_networking_port_secgroup_associate_v2": resourceNetworkingPortSecGroupAssociateV2(),
"openstack_networking_router_v2": resourceNetworkingRouterV2(),
"openstack_networking_router_interface_v2": resourceNetworkingRouterInterfaceV2(),
"openstack_networking_router_route_v2": resourceNetworkingRouterRouteV2(),
"openstack_networking_secgroup_v2": resourceNetworkingSecGroupV2(),
"openstack_networking_secgroup_rule_v2": resourceNetworkingSecGroupRuleV2(),
"openstack_networking_subnet_v2": resourceNetworkingSubnetV2(),
"openstack_networking_subnet_route_v2": resourceNetworkingSubnetRouteV2(),
"openstack_networking_subnetpool_v2": resourceNetworkingSubnetPoolV2(),
"openstack_networking_addressscope_v2": resourceNetworkingAddressScopeV2(),
"openstack_networking_trunk_v2": resourceNetworkingTrunkV2(),
"openstack_objectstorage_container_v1": resourceObjectStorageContainerV1(),
"openstack_objectstorage_object_v1": resourceObjectStorageObjectV1(),
"openstack_objectstorage_tempurl_v1": resourceObjectstorageTempurlV1(),
"openstack_vpnaas_ipsec_policy_v2": resourceIPSecPolicyV2(),
"openstack_vpnaas_service_v2": resourceServiceV2(),
"openstack_vpnaas_ike_policy_v2": resourceIKEPolicyV2(),
"openstack_vpnaas_endpoint_group_v2": resourceEndpointGroupV2(),
"openstack_vpnaas_site_connection_v2": resourceSiteConnectionV2(),
"openstack_sharedfilesystem_securityservice_v2": resourceSharedFilesystemSecurityServiceV2(),
"openstack_sharedfilesystem_sharenetwork_v2": resourceSharedFilesystemShareNetworkV2(),
"openstack_sharedfilesystem_share_v2": resourceSharedFilesystemShareV2(),
"openstack_sharedfilesystem_share_access_v2": resourceSharedFilesystemShareAccessV2(),
},
ConfigureFunc: configureProvider,
}
} | [
"func",
"Provider",
"(",
")",
"terraform",
".",
"ResourceProvider",
"{",
"return",
"&",
"schema",
".",
"Provider",
"{",
"Schema",
":",
"map",
"[",
"string",
"]",
"*",
"schema",
".",
"Schema",
"{",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"MultiEnvDefaultFunc",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"}",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"MultiEnvDefaultFunc",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"}",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"Sensitive",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"MultiEnvDefaultFunc",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"}",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeBool",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"nil",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeBool",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"false",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeBool",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"false",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeString",
",",
"Optional",
":",
"true",
",",
"DefaultFunc",
":",
"schema",
".",
"EnvDefaultFunc",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeInt",
",",
"Optional",
":",
"true",
",",
"Default",
":",
"0",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"\"",
"\"",
":",
"{",
"Type",
":",
"schema",
".",
"TypeMap",
",",
"Optional",
":",
"true",
",",
"Description",
":",
"descriptions",
"[",
"\"",
"\"",
"]",
",",
"}",
",",
"}",
",",
"DataSourcesMap",
":",
"map",
"[",
"string",
"]",
"*",
"schema",
".",
"Resource",
"{",
"\"",
"\"",
":",
"dataSourceBlockStorageAvailabilityZonesV3",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceBlockStorageSnapshotV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceBlockStorageSnapshotV3",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceComputeAvailabilityZonesV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceComputeFlavorV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceComputeKeypairV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceContainerInfraClusterTemplateV1",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceContainerInfraCluster",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceDNSZoneV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceFWPolicyV1",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceIdentityRoleV3",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceIdentityProjectV3",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceIdentityUserV3",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceIdentityAuthScopeV3",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceIdentityEndpointV3",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceIdentityGroupV3",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceImagesImageV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceNetworkingAddressScopeV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceNetworkingNetworkV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceNetworkingSubnetV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceNetworkingSecGroupV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceNetworkingSubnetPoolV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceNetworkingFloatingIPV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceNetworkingRouterV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceNetworkingPortV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceNetworkingPortIDsV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceNetworkingTrunkV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceSharedFilesystemAvailabilityZonesV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceSharedFilesystemShareNetworkV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceSharedFilesystemShareV2",
"(",
")",
",",
"\"",
"\"",
":",
"dataSourceSharedFilesystemSnapshotV2",
"(",
")",
",",
"}",
",",
"ResourcesMap",
":",
"map",
"[",
"string",
"]",
"*",
"schema",
".",
"Resource",
"{",
"\"",
"\"",
":",
"resourceBlockStorageVolumeV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceBlockStorageVolumeV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceBlockStorageVolumeV3",
"(",
")",
",",
"\"",
"\"",
":",
"resourceBlockStorageVolumeAttachV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceBlockStorageVolumeAttachV3",
"(",
")",
",",
"\"",
"\"",
":",
"resourceComputeFlavorV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceComputeFlavorAccessV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceComputeInstanceV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceComputeInterfaceAttachV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceComputeKeypairV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceComputeSecGroupV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceComputeServerGroupV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceComputeFloatingIPV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceComputeFloatingIPAssociateV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceComputeVolumeAttachV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceContainerInfraClusterTemplateV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceContainerInfraClusterV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceDatabaseInstanceV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceDatabaseUserV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceDatabaseConfigurationV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceDatabaseDatabaseV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceDNSRecordSetV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceDNSZoneV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceFWFirewallV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceFWPolicyV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceFWRuleV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceIdentityProjectV3",
"(",
")",
",",
"\"",
"\"",
":",
"resourceIdentityRoleV3",
"(",
")",
",",
"\"",
"\"",
":",
"resourceIdentityRoleAssignmentV3",
"(",
")",
",",
"\"",
"\"",
":",
"resourceIdentityUserV3",
"(",
")",
",",
"\"",
"\"",
":",
"resourceIdentityApplicationCredentialV3",
"(",
")",
",",
"\"",
"\"",
":",
"resourceImagesImageV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceLBMemberV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceLBMonitorV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceLBPoolV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceLBVipV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceLoadBalancerV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceListenerV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourcePoolV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceMemberV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceMonitorV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceL7PolicyV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceL7RuleV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingFloatingIPV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingFloatingIPAssociateV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingNetworkV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingPortV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingPortSecGroupAssociateV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingRouterV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingRouterInterfaceV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingRouterRouteV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingSecGroupV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingSecGroupRuleV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingSubnetV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingSubnetRouteV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingSubnetPoolV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingAddressScopeV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceNetworkingTrunkV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceObjectStorageContainerV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceObjectStorageObjectV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceObjectstorageTempurlV1",
"(",
")",
",",
"\"",
"\"",
":",
"resourceIPSecPolicyV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceServiceV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceIKEPolicyV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceEndpointGroupV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceSiteConnectionV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceSharedFilesystemSecurityServiceV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceSharedFilesystemShareNetworkV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceSharedFilesystemShareV2",
"(",
")",
",",
"\"",
"\"",
":",
"resourceSharedFilesystemShareAccessV2",
"(",
")",
",",
"}",
",",
"ConfigureFunc",
":",
"configureProvider",
",",
"}",
"\n",
"}"
] | // Provider returns a schema.Provider for OpenStack. | [
"Provider",
"returns",
"a",
"schema",
".",
"Provider",
"for",
"OpenStack",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/provider.go#L13-L330 |
terraform-providers/terraform-provider-openstack | openstack/util.go | BuildRequest | func BuildRequest(opts interface{}, parent string) (map[string]interface{}, error) {
b, err := gophercloud.BuildRequestBody(opts, "")
if err != nil {
return nil, err
}
b = AddValueSpecs(b)
return map[string]interface{}{parent: b}, nil
} | go | func BuildRequest(opts interface{}, parent string) (map[string]interface{}, error) {
b, err := gophercloud.BuildRequestBody(opts, "")
if err != nil {
return nil, err
}
b = AddValueSpecs(b)
return map[string]interface{}{parent: b}, nil
} | [
"func",
"BuildRequest",
"(",
"opts",
"interface",
"{",
"}",
",",
"parent",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"gophercloud",
".",
"BuildRequestBody",
"(",
"opts",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"b",
"=",
"AddValueSpecs",
"(",
"b",
")",
"\n\n",
"return",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"parent",
":",
"b",
"}",
",",
"nil",
"\n",
"}"
] | // BuildRequest takes an opts struct and builds a request body for
// Gophercloud to execute | [
"BuildRequest",
"takes",
"an",
"opts",
"struct",
"and",
"builds",
"a",
"request",
"body",
"for",
"Gophercloud",
"to",
"execute"
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L22-L31 |
terraform-providers/terraform-provider-openstack | openstack/util.go | CheckDeleted | func CheckDeleted(d *schema.ResourceData, err error, msg string) error {
if _, ok := err.(gophercloud.ErrDefault404); ok {
d.SetId("")
return nil
}
return fmt.Errorf("%s %s: %s", msg, d.Id(), err)
} | go | func CheckDeleted(d *schema.ResourceData, err error, msg string) error {
if _, ok := err.(gophercloud.ErrDefault404); ok {
d.SetId("")
return nil
}
return fmt.Errorf("%s %s: %s", msg, d.Id(), err)
} | [
"func",
"CheckDeleted",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"err",
"error",
",",
"msg",
"string",
")",
"error",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"gophercloud",
".",
"ErrDefault404",
")",
";",
"ok",
"{",
"d",
".",
"SetId",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"msg",
",",
"d",
".",
"Id",
"(",
")",
",",
"err",
")",
"\n",
"}"
] | // CheckDeleted checks the error to see if it's a 404 (Not Found) and, if so,
// sets the resource ID to the empty string instead of throwing an error. | [
"CheckDeleted",
"checks",
"the",
"error",
"to",
"see",
"if",
"it",
"s",
"a",
"404",
"(",
"Not",
"Found",
")",
"and",
"if",
"so",
"sets",
"the",
"resource",
"ID",
"to",
"the",
"empty",
"string",
"instead",
"of",
"throwing",
"an",
"error",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L35-L42 |
terraform-providers/terraform-provider-openstack | openstack/util.go | GetRegion | func GetRegion(d *schema.ResourceData, config *Config) string {
if v, ok := d.GetOk("region"); ok {
return v.(string)
}
return config.Region
} | go | func GetRegion(d *schema.ResourceData, config *Config) string {
if v, ok := d.GetOk("region"); ok {
return v.(string)
}
return config.Region
} | [
"func",
"GetRegion",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"config",
"*",
"Config",
")",
"string",
"{",
"if",
"v",
",",
"ok",
":=",
"d",
".",
"GetOk",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"return",
"v",
".",
"(",
"string",
")",
"\n",
"}",
"\n\n",
"return",
"config",
".",
"Region",
"\n",
"}"
] | // GetRegion returns the region that was specified in the resource. If a
// region was not set, the provider-level region is checked. The provider-level
// region can either be set by the region argument or by OS_REGION_NAME. | [
"GetRegion",
"returns",
"the",
"region",
"that",
"was",
"specified",
"in",
"the",
"resource",
".",
"If",
"a",
"region",
"was",
"not",
"set",
"the",
"provider",
"-",
"level",
"region",
"is",
"checked",
".",
"The",
"provider",
"-",
"level",
"region",
"can",
"either",
"be",
"set",
"by",
"the",
"region",
"argument",
"or",
"by",
"OS_REGION_NAME",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L47-L53 |
terraform-providers/terraform-provider-openstack | openstack/util.go | AddValueSpecs | func AddValueSpecs(body map[string]interface{}) map[string]interface{} {
if body["value_specs"] != nil {
for k, v := range body["value_specs"].(map[string]interface{}) {
body[k] = v
}
delete(body, "value_specs")
}
return body
} | go | func AddValueSpecs(body map[string]interface{}) map[string]interface{} {
if body["value_specs"] != nil {
for k, v := range body["value_specs"].(map[string]interface{}) {
body[k] = v
}
delete(body, "value_specs")
}
return body
} | [
"func",
"AddValueSpecs",
"(",
"body",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"if",
"body",
"[",
"\"",
"\"",
"]",
"!=",
"nil",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"body",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"{",
"body",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"delete",
"(",
"body",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"body",
"\n",
"}"
] | // AddValueSpecs expands the 'value_specs' object and removes 'value_specs'
// from the reqeust body. | [
"AddValueSpecs",
"expands",
"the",
"value_specs",
"object",
"and",
"removes",
"value_specs",
"from",
"the",
"reqeust",
"body",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L57-L66 |
terraform-providers/terraform-provider-openstack | openstack/util.go | MapValueSpecs | func MapValueSpecs(d *schema.ResourceData) map[string]string {
m := make(map[string]string)
for key, val := range d.Get("value_specs").(map[string]interface{}) {
m[key] = val.(string)
}
return m
} | go | func MapValueSpecs(d *schema.ResourceData) map[string]string {
m := make(map[string]string)
for key, val := range d.Get("value_specs").(map[string]interface{}) {
m[key] = val.(string)
}
return m
} | [
"func",
"MapValueSpecs",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"m",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"key",
",",
"val",
":=",
"range",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"{",
"m",
"[",
"key",
"]",
"=",
"val",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] | // MapValueSpecs converts ResourceData into a map | [
"MapValueSpecs",
"converts",
"ResourceData",
"into",
"a",
"map"
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L69-L75 |
terraform-providers/terraform-provider-openstack | openstack/util.go | RedactHeaders | func RedactHeaders(headers http.Header) (processedHeaders []string) {
for name, header := range headers {
for _, v := range header {
if com.IsSliceContainsStr(REDACT_HEADERS, name) {
processedHeaders = append(processedHeaders, fmt.Sprintf("%v: %v", name, "***"))
} else {
processedHeaders = append(processedHeaders, fmt.Sprintf("%v: %v", name, v))
}
}
}
return
} | go | func RedactHeaders(headers http.Header) (processedHeaders []string) {
for name, header := range headers {
for _, v := range header {
if com.IsSliceContainsStr(REDACT_HEADERS, name) {
processedHeaders = append(processedHeaders, fmt.Sprintf("%v: %v", name, "***"))
} else {
processedHeaders = append(processedHeaders, fmt.Sprintf("%v: %v", name, v))
}
}
}
return
} | [
"func",
"RedactHeaders",
"(",
"headers",
"http",
".",
"Header",
")",
"(",
"processedHeaders",
"[",
"]",
"string",
")",
"{",
"for",
"name",
",",
"header",
":=",
"range",
"headers",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"header",
"{",
"if",
"com",
".",
"IsSliceContainsStr",
"(",
"REDACT_HEADERS",
",",
"name",
")",
"{",
"processedHeaders",
"=",
"append",
"(",
"processedHeaders",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"else",
"{",
"processedHeaders",
"=",
"append",
"(",
"processedHeaders",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
",",
"v",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // RedactHeaders processes a headers object, returning a redacted list | [
"RedactHeaders",
"processes",
"a",
"headers",
"object",
"returning",
"a",
"redacted",
"list"
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L84-L95 |
terraform-providers/terraform-provider-openstack | openstack/util.go | FormatHeaders | func FormatHeaders(headers http.Header, seperator string) string {
redactedHeaders := RedactHeaders(headers)
sort.Strings(redactedHeaders)
return strings.Join(redactedHeaders, seperator)
} | go | func FormatHeaders(headers http.Header, seperator string) string {
redactedHeaders := RedactHeaders(headers)
sort.Strings(redactedHeaders)
return strings.Join(redactedHeaders, seperator)
} | [
"func",
"FormatHeaders",
"(",
"headers",
"http",
".",
"Header",
",",
"seperator",
"string",
")",
"string",
"{",
"redactedHeaders",
":=",
"RedactHeaders",
"(",
"headers",
")",
"\n",
"sort",
".",
"Strings",
"(",
"redactedHeaders",
")",
"\n\n",
"return",
"strings",
".",
"Join",
"(",
"redactedHeaders",
",",
"seperator",
")",
"\n",
"}"
] | // FormatHeaders processes a headers object plus a deliminator, returning a string | [
"FormatHeaders",
"processes",
"a",
"headers",
"object",
"plus",
"a",
"deliminator",
"returning",
"a",
"string"
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L98-L103 |
terraform-providers/terraform-provider-openstack | openstack/util.go | compatibleMicroversion | func compatibleMicroversion(direction, required, given string) (bool, error) {
if direction != "min" && direction != "max" {
return false, fmt.Errorf("Invalid microversion direction %s. Must be min or max", direction)
}
if required == "" || given == "" {
return false, nil
}
requiredParts := strings.Split(required, ".")
if len(requiredParts) != 2 {
return false, fmt.Errorf("Not a valid microversion: %s", required)
}
givenParts := strings.Split(given, ".")
if len(givenParts) != 2 {
return false, fmt.Errorf("Not a valid microversion: %s", given)
}
requiredMajor, requiredMinor := requiredParts[0], requiredParts[1]
givenMajor, givenMinor := givenParts[0], givenParts[1]
requiredMajorInt, err := strconv.Atoi(requiredMajor)
if err != nil {
return false, fmt.Errorf("Unable to parse microversion: %s", required)
}
requiredMinorInt, err := strconv.Atoi(requiredMinor)
if err != nil {
return false, fmt.Errorf("Unable to parse microversion: %s", required)
}
givenMajorInt, err := strconv.Atoi(givenMajor)
if err != nil {
return false, fmt.Errorf("Unable to parse microversion: %s", given)
}
givenMinorInt, err := strconv.Atoi(givenMinor)
if err != nil {
return false, fmt.Errorf("Unable to parse microversion: %s", given)
}
switch direction {
case "min":
if requiredMajorInt == givenMajorInt {
if requiredMinorInt <= givenMinorInt {
return true, nil
}
}
case "max":
if requiredMajorInt == givenMajorInt {
if requiredMinorInt >= givenMinorInt {
return true, nil
}
}
}
return false, nil
} | go | func compatibleMicroversion(direction, required, given string) (bool, error) {
if direction != "min" && direction != "max" {
return false, fmt.Errorf("Invalid microversion direction %s. Must be min or max", direction)
}
if required == "" || given == "" {
return false, nil
}
requiredParts := strings.Split(required, ".")
if len(requiredParts) != 2 {
return false, fmt.Errorf("Not a valid microversion: %s", required)
}
givenParts := strings.Split(given, ".")
if len(givenParts) != 2 {
return false, fmt.Errorf("Not a valid microversion: %s", given)
}
requiredMajor, requiredMinor := requiredParts[0], requiredParts[1]
givenMajor, givenMinor := givenParts[0], givenParts[1]
requiredMajorInt, err := strconv.Atoi(requiredMajor)
if err != nil {
return false, fmt.Errorf("Unable to parse microversion: %s", required)
}
requiredMinorInt, err := strconv.Atoi(requiredMinor)
if err != nil {
return false, fmt.Errorf("Unable to parse microversion: %s", required)
}
givenMajorInt, err := strconv.Atoi(givenMajor)
if err != nil {
return false, fmt.Errorf("Unable to parse microversion: %s", given)
}
givenMinorInt, err := strconv.Atoi(givenMinor)
if err != nil {
return false, fmt.Errorf("Unable to parse microversion: %s", given)
}
switch direction {
case "min":
if requiredMajorInt == givenMajorInt {
if requiredMinorInt <= givenMinorInt {
return true, nil
}
}
case "max":
if requiredMajorInt == givenMajorInt {
if requiredMinorInt >= givenMinorInt {
return true, nil
}
}
}
return false, nil
} | [
"func",
"compatibleMicroversion",
"(",
"direction",
",",
"required",
",",
"given",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"if",
"direction",
"!=",
"\"",
"\"",
"&&",
"direction",
"!=",
"\"",
"\"",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"direction",
")",
"\n",
"}",
"\n\n",
"if",
"required",
"==",
"\"",
"\"",
"||",
"given",
"==",
"\"",
"\"",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"requiredParts",
":=",
"strings",
".",
"Split",
"(",
"required",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"requiredParts",
")",
"!=",
"2",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"required",
")",
"\n",
"}",
"\n\n",
"givenParts",
":=",
"strings",
".",
"Split",
"(",
"given",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"givenParts",
")",
"!=",
"2",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"given",
")",
"\n",
"}",
"\n\n",
"requiredMajor",
",",
"requiredMinor",
":=",
"requiredParts",
"[",
"0",
"]",
",",
"requiredParts",
"[",
"1",
"]",
"\n",
"givenMajor",
",",
"givenMinor",
":=",
"givenParts",
"[",
"0",
"]",
",",
"givenParts",
"[",
"1",
"]",
"\n\n",
"requiredMajorInt",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"requiredMajor",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"required",
")",
"\n",
"}",
"\n\n",
"requiredMinorInt",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"requiredMinor",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"required",
")",
"\n",
"}",
"\n\n",
"givenMajorInt",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"givenMajor",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"given",
")",
"\n",
"}",
"\n\n",
"givenMinorInt",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"givenMinor",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"given",
")",
"\n",
"}",
"\n\n",
"switch",
"direction",
"{",
"case",
"\"",
"\"",
":",
"if",
"requiredMajorInt",
"==",
"givenMajorInt",
"{",
"if",
"requiredMinorInt",
"<=",
"givenMinorInt",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"requiredMajorInt",
"==",
"givenMajorInt",
"{",
"if",
"requiredMinorInt",
">=",
"givenMinorInt",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // compatibleMicroversion will determine if an obtained microversion is
// compatible with a given microversion. | [
"compatibleMicroversion",
"will",
"determine",
"if",
"an",
"obtained",
"microversion",
"is",
"compatible",
"with",
"a",
"given",
"microversion",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L278-L336 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_images_image_v2.go | dataSourceImagesImageV2Read | func dataSourceImagesImageV2Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
imageClient, err := config.imageV2Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack image client: %s", err)
}
visibility := resourceImagesImageV2VisibilityFromString(d.Get("visibility").(string))
member_status := resourceImagesImageV2MemberStatusFromString(d.Get("member_status").(string))
var tags []string
tag := d.Get("tag").(string)
if tag != "" {
tags = append(tags, tag)
}
listOpts := images.ListOpts{
Name: d.Get("name").(string),
Visibility: visibility,
Owner: d.Get("owner").(string),
Status: images.ImageStatusActive,
SizeMin: int64(d.Get("size_min").(int)),
SizeMax: int64(d.Get("size_max").(int)),
SortKey: d.Get("sort_key").(string),
SortDir: d.Get("sort_direction").(string),
Tags: tags,
MemberStatus: member_status,
}
log.Printf("[DEBUG] List Options: %#v", listOpts)
var image images.Image
allPages, err := images.List(imageClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query images: %s", err)
}
allImages, err := images.ExtractImages(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve images: %s", err)
}
properties := d.Get("properties").(map[string]interface{})
imageProperties := resourceImagesImageV2ExpandProperties(properties)
if len(allImages) > 1 && len(imageProperties) > 0 {
var filteredImages []images.Image
for _, image := range allImages {
if len(image.Properties) > 0 {
match := true
for searchKey, searchValue := range imageProperties {
imageValue, ok := image.Properties[searchKey]
if !ok {
match = false
break
}
if searchValue != imageValue {
match = false
break
}
}
if match {
filteredImages = append(filteredImages, image)
}
}
}
allImages = filteredImages
}
if len(allImages) < 1 {
return fmt.Errorf("Your query returned no results. " +
"Please change your search criteria and try again.")
}
if len(allImages) > 1 {
recent := d.Get("most_recent").(bool)
log.Printf("[DEBUG] Multiple results found and `most_recent` is set to: %t", recent)
if recent {
image = mostRecentImage(allImages)
} else {
log.Printf("[DEBUG] Multiple results found: %#v", allImages)
return fmt.Errorf("Your query returned more than one result. Please try a more " +
"specific search criteria, or set `most_recent` attribute to true.")
}
} else {
image = allImages[0]
}
log.Printf("[DEBUG] Single Image found: %s", image.ID)
return dataSourceImagesImageV2Attributes(d, &image)
} | go | func dataSourceImagesImageV2Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
imageClient, err := config.imageV2Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack image client: %s", err)
}
visibility := resourceImagesImageV2VisibilityFromString(d.Get("visibility").(string))
member_status := resourceImagesImageV2MemberStatusFromString(d.Get("member_status").(string))
var tags []string
tag := d.Get("tag").(string)
if tag != "" {
tags = append(tags, tag)
}
listOpts := images.ListOpts{
Name: d.Get("name").(string),
Visibility: visibility,
Owner: d.Get("owner").(string),
Status: images.ImageStatusActive,
SizeMin: int64(d.Get("size_min").(int)),
SizeMax: int64(d.Get("size_max").(int)),
SortKey: d.Get("sort_key").(string),
SortDir: d.Get("sort_direction").(string),
Tags: tags,
MemberStatus: member_status,
}
log.Printf("[DEBUG] List Options: %#v", listOpts)
var image images.Image
allPages, err := images.List(imageClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query images: %s", err)
}
allImages, err := images.ExtractImages(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve images: %s", err)
}
properties := d.Get("properties").(map[string]interface{})
imageProperties := resourceImagesImageV2ExpandProperties(properties)
if len(allImages) > 1 && len(imageProperties) > 0 {
var filteredImages []images.Image
for _, image := range allImages {
if len(image.Properties) > 0 {
match := true
for searchKey, searchValue := range imageProperties {
imageValue, ok := image.Properties[searchKey]
if !ok {
match = false
break
}
if searchValue != imageValue {
match = false
break
}
}
if match {
filteredImages = append(filteredImages, image)
}
}
}
allImages = filteredImages
}
if len(allImages) < 1 {
return fmt.Errorf("Your query returned no results. " +
"Please change your search criteria and try again.")
}
if len(allImages) > 1 {
recent := d.Get("most_recent").(bool)
log.Printf("[DEBUG] Multiple results found and `most_recent` is set to: %t", recent)
if recent {
image = mostRecentImage(allImages)
} else {
log.Printf("[DEBUG] Multiple results found: %#v", allImages)
return fmt.Errorf("Your query returned more than one result. Please try a more " +
"specific search criteria, or set `most_recent` attribute to true.")
}
} else {
image = allImages[0]
}
log.Printf("[DEBUG] Single Image found: %s", image.ID)
return dataSourceImagesImageV2Attributes(d, &image)
} | [
"func",
"dataSourceImagesImageV2Read",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"meta",
"interface",
"{",
"}",
")",
"error",
"{",
"config",
":=",
"meta",
".",
"(",
"*",
"Config",
")",
"\n",
"imageClient",
",",
"err",
":=",
"config",
".",
"imageV2Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"visibility",
":=",
"resourceImagesImageV2VisibilityFromString",
"(",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
")",
"\n",
"member_status",
":=",
"resourceImagesImageV2MemberStatusFromString",
"(",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
")",
"\n\n",
"var",
"tags",
"[",
"]",
"string",
"\n",
"tag",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
"\n",
"if",
"tag",
"!=",
"\"",
"\"",
"{",
"tags",
"=",
"append",
"(",
"tags",
",",
"tag",
")",
"\n",
"}",
"\n\n",
"listOpts",
":=",
"images",
".",
"ListOpts",
"{",
"Name",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"Visibility",
":",
"visibility",
",",
"Owner",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"Status",
":",
"images",
".",
"ImageStatusActive",
",",
"SizeMin",
":",
"int64",
"(",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"int",
")",
")",
",",
"SizeMax",
":",
"int64",
"(",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"int",
")",
")",
",",
"SortKey",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"SortDir",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"Tags",
":",
"tags",
",",
"MemberStatus",
":",
"member_status",
",",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"listOpts",
")",
"\n\n",
"var",
"image",
"images",
".",
"Image",
"\n",
"allPages",
",",
"err",
":=",
"images",
".",
"List",
"(",
"imageClient",
",",
"listOpts",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"allImages",
",",
"err",
":=",
"images",
".",
"ExtractImages",
"(",
"allPages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"properties",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"imageProperties",
":=",
"resourceImagesImageV2ExpandProperties",
"(",
"properties",
")",
"\n",
"if",
"len",
"(",
"allImages",
")",
">",
"1",
"&&",
"len",
"(",
"imageProperties",
")",
">",
"0",
"{",
"var",
"filteredImages",
"[",
"]",
"images",
".",
"Image",
"\n",
"for",
"_",
",",
"image",
":=",
"range",
"allImages",
"{",
"if",
"len",
"(",
"image",
".",
"Properties",
")",
">",
"0",
"{",
"match",
":=",
"true",
"\n",
"for",
"searchKey",
",",
"searchValue",
":=",
"range",
"imageProperties",
"{",
"imageValue",
",",
"ok",
":=",
"image",
".",
"Properties",
"[",
"searchKey",
"]",
"\n",
"if",
"!",
"ok",
"{",
"match",
"=",
"false",
"\n",
"break",
"\n",
"}",
"\n\n",
"if",
"searchValue",
"!=",
"imageValue",
"{",
"match",
"=",
"false",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"match",
"{",
"filteredImages",
"=",
"append",
"(",
"filteredImages",
",",
"image",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"allImages",
"=",
"filteredImages",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allImages",
")",
"<",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allImages",
")",
">",
"1",
"{",
"recent",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"bool",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"recent",
")",
"\n",
"if",
"recent",
"{",
"image",
"=",
"mostRecentImage",
"(",
"allImages",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"allImages",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"image",
"=",
"allImages",
"[",
"0",
"]",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"image",
".",
"ID",
")",
"\n",
"return",
"dataSourceImagesImageV2Attributes",
"(",
"d",
",",
"&",
"image",
")",
"\n",
"}"
] | // dataSourceImagesImageV2Read performs the image lookup. | [
"dataSourceImagesImageV2Read",
"performs",
"the",
"image",
"lookup",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_images_image_v2.go#L168-L259 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_images_image_v2.go | dataSourceImagesImageV2Attributes | func dataSourceImagesImageV2Attributes(d *schema.ResourceData, image *images.Image) error {
log.Printf("[DEBUG] openstack_images_image details: %#v", image)
d.SetId(image.ID)
d.Set("name", image.Name)
d.Set("tags", image.Tags)
d.Set("container_format", image.ContainerFormat)
d.Set("disk_format", image.DiskFormat)
d.Set("min_disk_gb", image.MinDiskGigabytes)
d.Set("min_ram_mb", image.MinRAMMegabytes)
d.Set("owner", image.Owner)
d.Set("protected", image.Protected)
d.Set("visibility", image.Visibility)
d.Set("checksum", image.Checksum)
d.Set("size_bytes", image.SizeBytes)
d.Set("metadata", image.Metadata)
d.Set("created_at", image.CreatedAt.Format(time.RFC3339))
d.Set("updated_at", image.UpdatedAt.Format(time.RFC3339))
d.Set("file", image.File)
d.Set("schema", image.Schema)
return nil
} | go | func dataSourceImagesImageV2Attributes(d *schema.ResourceData, image *images.Image) error {
log.Printf("[DEBUG] openstack_images_image details: %#v", image)
d.SetId(image.ID)
d.Set("name", image.Name)
d.Set("tags", image.Tags)
d.Set("container_format", image.ContainerFormat)
d.Set("disk_format", image.DiskFormat)
d.Set("min_disk_gb", image.MinDiskGigabytes)
d.Set("min_ram_mb", image.MinRAMMegabytes)
d.Set("owner", image.Owner)
d.Set("protected", image.Protected)
d.Set("visibility", image.Visibility)
d.Set("checksum", image.Checksum)
d.Set("size_bytes", image.SizeBytes)
d.Set("metadata", image.Metadata)
d.Set("created_at", image.CreatedAt.Format(time.RFC3339))
d.Set("updated_at", image.UpdatedAt.Format(time.RFC3339))
d.Set("file", image.File)
d.Set("schema", image.Schema)
return nil
} | [
"func",
"dataSourceImagesImageV2Attributes",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"image",
"*",
"images",
".",
"Image",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"image",
")",
"\n\n",
"d",
".",
"SetId",
"(",
"image",
".",
"ID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"Name",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"Tags",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"ContainerFormat",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"DiskFormat",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"MinDiskGigabytes",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"MinRAMMegabytes",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"Owner",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"Protected",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"Visibility",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"Checksum",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"SizeBytes",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"Metadata",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"CreatedAt",
".",
"Format",
"(",
"time",
".",
"RFC3339",
")",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"UpdatedAt",
".",
"Format",
"(",
"time",
".",
"RFC3339",
")",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"File",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"image",
".",
"Schema",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // dataSourceImagesImageV2Attributes populates the fields of an Image resource. | [
"dataSourceImagesImageV2Attributes",
"populates",
"the",
"fields",
"of",
"an",
"Image",
"resource",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_images_image_v2.go#L262-L284 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_images_image_v2.go | mostRecentImage | func mostRecentImage(images []images.Image) images.Image {
sortedImages := images
sort.Sort(imageSort(sortedImages))
return sortedImages[len(sortedImages)-1]
} | go | func mostRecentImage(images []images.Image) images.Image {
sortedImages := images
sort.Sort(imageSort(sortedImages))
return sortedImages[len(sortedImages)-1]
} | [
"func",
"mostRecentImage",
"(",
"images",
"[",
"]",
"images",
".",
"Image",
")",
"images",
".",
"Image",
"{",
"sortedImages",
":=",
"images",
"\n",
"sort",
".",
"Sort",
"(",
"imageSort",
"(",
"sortedImages",
")",
")",
"\n",
"return",
"sortedImages",
"[",
"len",
"(",
"sortedImages",
")",
"-",
"1",
"]",
"\n",
"}"
] | // Returns the most recent Image out of a slice of images. | [
"Returns",
"the",
"most",
"recent",
"Image",
"out",
"of",
"a",
"slice",
"of",
"images",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_images_image_v2.go#L297-L301 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_identity_group_v3.go | dataSourceIdentityGroupV3Read | func dataSourceIdentityGroupV3Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
identityClient, err := config.identityV3Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack identity client: %s", err)
}
listOpts := groups.ListOpts{
DomainID: d.Get("domain_id").(string),
Name: d.Get("name").(string),
}
log.Printf("[DEBUG] openstack_identity_group_v3 list options: %#v", listOpts)
var group groups.Group
allPages, err := groups.List(identityClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query openstack_identity_group_v3: %s", err)
}
allGroups, err := groups.ExtractGroups(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve openstack_identity_group_v3: %s", err)
}
if len(allGroups) < 1 {
return fmt.Errorf("Your openstack_identity_group_v3 query returned no results. " +
"Please change your search criteria and try again.")
}
if len(allGroups) > 1 {
return fmt.Errorf("Your openstack_identity_group_v3 query returned more than one result.")
}
group = allGroups[0]
return dataSourceIdentityGroupV3Attributes(d, config, &group)
} | go | func dataSourceIdentityGroupV3Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
identityClient, err := config.identityV3Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack identity client: %s", err)
}
listOpts := groups.ListOpts{
DomainID: d.Get("domain_id").(string),
Name: d.Get("name").(string),
}
log.Printf("[DEBUG] openstack_identity_group_v3 list options: %#v", listOpts)
var group groups.Group
allPages, err := groups.List(identityClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query openstack_identity_group_v3: %s", err)
}
allGroups, err := groups.ExtractGroups(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve openstack_identity_group_v3: %s", err)
}
if len(allGroups) < 1 {
return fmt.Errorf("Your openstack_identity_group_v3 query returned no results. " +
"Please change your search criteria and try again.")
}
if len(allGroups) > 1 {
return fmt.Errorf("Your openstack_identity_group_v3 query returned more than one result.")
}
group = allGroups[0]
return dataSourceIdentityGroupV3Attributes(d, config, &group)
} | [
"func",
"dataSourceIdentityGroupV3Read",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"meta",
"interface",
"{",
"}",
")",
"error",
"{",
"config",
":=",
"meta",
".",
"(",
"*",
"Config",
")",
"\n",
"identityClient",
",",
"err",
":=",
"config",
".",
"identityV3Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"listOpts",
":=",
"groups",
".",
"ListOpts",
"{",
"DomainID",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"Name",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"listOpts",
")",
"\n\n",
"var",
"group",
"groups",
".",
"Group",
"\n",
"allPages",
",",
"err",
":=",
"groups",
".",
"List",
"(",
"identityClient",
",",
"listOpts",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"allGroups",
",",
"err",
":=",
"groups",
".",
"ExtractGroups",
"(",
"allPages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allGroups",
")",
"<",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allGroups",
")",
">",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"group",
"=",
"allGroups",
"[",
"0",
"]",
"\n\n",
"return",
"dataSourceIdentityGroupV3Attributes",
"(",
"d",
",",
"config",
",",
"&",
"group",
")",
"\n",
"}"
] | // dataSourceIdentityGroupV3Read performs the group lookup. | [
"dataSourceIdentityGroupV3Read",
"performs",
"the",
"group",
"lookup",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_group_v3.go#L38-L75 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_identity_group_v3.go | dataSourceIdentityGroupV3Attributes | func dataSourceIdentityGroupV3Attributes(d *schema.ResourceData, config *Config, group *groups.Group) error {
log.Printf("[DEBUG] openstack_identity_group_v3 details: %#v", group)
d.SetId(group.ID)
d.Set("name", group.Name)
d.Set("domain_id", group.DomainID)
d.Set("region", GetRegion(d, config))
return nil
} | go | func dataSourceIdentityGroupV3Attributes(d *schema.ResourceData, config *Config, group *groups.Group) error {
log.Printf("[DEBUG] openstack_identity_group_v3 details: %#v", group)
d.SetId(group.ID)
d.Set("name", group.Name)
d.Set("domain_id", group.DomainID)
d.Set("region", GetRegion(d, config))
return nil
} | [
"func",
"dataSourceIdentityGroupV3Attributes",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"config",
"*",
"Config",
",",
"group",
"*",
"groups",
".",
"Group",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"group",
")",
"\n\n",
"d",
".",
"SetId",
"(",
"group",
".",
"ID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"group",
".",
"Name",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"group",
".",
"DomainID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // dataSourceIdentityRoleV3Attributes populates the fields of an Role resource. | [
"dataSourceIdentityRoleV3Attributes",
"populates",
"the",
"fields",
"of",
"an",
"Role",
"resource",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_group_v3.go#L78-L87 |
terraform-providers/terraform-provider-openstack | openstack/resource_openstack_sharedfilesystem_share_access_v2.go | waitForSFV2Access | func waitForSFV2Access(sfsClient *gophercloud.ServiceClient, shareID string, id string, target string, pending []string, timeout time.Duration) error {
log.Printf("[DEBUG] Waiting for access %s to become %s.", id, target)
stateConf := &resource.StateChangeConf{
Target: []string{target},
Pending: pending,
Refresh: resourceSFV2AccessRefreshFunc(sfsClient, shareID, id),
Timeout: timeout,
Delay: 1 * time.Second,
MinTimeout: 1 * time.Second,
}
_, err := stateConf.WaitForState()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
switch target {
case "denied":
return nil
default:
return fmt.Errorf("Error: access %s not found: %s", id, err)
}
}
return fmt.Errorf("Error waiting for access %s to become %s: %s", id, target, err)
}
return nil
} | go | func waitForSFV2Access(sfsClient *gophercloud.ServiceClient, shareID string, id string, target string, pending []string, timeout time.Duration) error {
log.Printf("[DEBUG] Waiting for access %s to become %s.", id, target)
stateConf := &resource.StateChangeConf{
Target: []string{target},
Pending: pending,
Refresh: resourceSFV2AccessRefreshFunc(sfsClient, shareID, id),
Timeout: timeout,
Delay: 1 * time.Second,
MinTimeout: 1 * time.Second,
}
_, err := stateConf.WaitForState()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
switch target {
case "denied":
return nil
default:
return fmt.Errorf("Error: access %s not found: %s", id, err)
}
}
return fmt.Errorf("Error waiting for access %s to become %s: %s", id, target, err)
}
return nil
} | [
"func",
"waitForSFV2Access",
"(",
"sfsClient",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"shareID",
"string",
",",
"id",
"string",
",",
"target",
"string",
",",
"pending",
"[",
"]",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"id",
",",
"target",
")",
"\n\n",
"stateConf",
":=",
"&",
"resource",
".",
"StateChangeConf",
"{",
"Target",
":",
"[",
"]",
"string",
"{",
"target",
"}",
",",
"Pending",
":",
"pending",
",",
"Refresh",
":",
"resourceSFV2AccessRefreshFunc",
"(",
"sfsClient",
",",
"shareID",
",",
"id",
")",
",",
"Timeout",
":",
"timeout",
",",
"Delay",
":",
"1",
"*",
"time",
".",
"Second",
",",
"MinTimeout",
":",
"1",
"*",
"time",
".",
"Second",
",",
"}",
"\n\n",
"_",
",",
"err",
":=",
"stateConf",
".",
"WaitForState",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"gophercloud",
".",
"ErrDefault404",
")",
";",
"ok",
"{",
"switch",
"target",
"{",
"case",
"\"",
"\"",
":",
"return",
"nil",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"id",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"id",
",",
"target",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Full list of the share access statuses: https://developer.openstack.org/api-ref/shared-file-system/?expanded=list-services-detail,list-access-rules-detail#list-access-rules | [
"Full",
"list",
"of",
"the",
"share",
"access",
"statuses",
":",
"https",
":",
"//",
"developer",
".",
"openstack",
".",
"org",
"/",
"api",
"-",
"ref",
"/",
"shared",
"-",
"file",
"-",
"system",
"/",
"?expanded",
"=",
"list",
"-",
"services",
"-",
"detail",
"list",
"-",
"access",
"-",
"rules",
"-",
"detail#list",
"-",
"access",
"-",
"rules"
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/resource_openstack_sharedfilesystem_share_access_v2.go#L280-L306 |
terraform-providers/terraform-provider-openstack | openstack/identity_user_v3.go | validatePasswordExpiresAtQuery | func validatePasswordExpiresAtQuery(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
values := strings.SplitN(value, ":", 2)
if len(values) != 2 {
err := fmt.Errorf("%s '%s' does not match expected format: {operator}:{timestamp}", k, value)
errors = append(errors, err)
}
operator, timestamp := values[0], values[1]
validOperators := map[string]bool{
"lt": true,
"lte": true,
"gt": true,
"gte": true,
"eq": true,
"neq": true,
}
if !validOperators[operator] {
err := fmt.Errorf("'%s' is not a valid operator for %s. Choose one of 'lt', 'lte', 'gt', 'gte', 'eq', 'neq'", operator, k)
errors = append(errors, err)
}
_, err := time.Parse(time.RFC3339, timestamp)
if err != nil {
err = fmt.Errorf("'%s' is not a valid timestamp for %s. It should be in the form 'YYYY-MM-DDTHH:mm:ssZ'", timestamp, k)
errors = append(errors, err)
}
return
} | go | func validatePasswordExpiresAtQuery(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
values := strings.SplitN(value, ":", 2)
if len(values) != 2 {
err := fmt.Errorf("%s '%s' does not match expected format: {operator}:{timestamp}", k, value)
errors = append(errors, err)
}
operator, timestamp := values[0], values[1]
validOperators := map[string]bool{
"lt": true,
"lte": true,
"gt": true,
"gte": true,
"eq": true,
"neq": true,
}
if !validOperators[operator] {
err := fmt.Errorf("'%s' is not a valid operator for %s. Choose one of 'lt', 'lte', 'gt', 'gte', 'eq', 'neq'", operator, k)
errors = append(errors, err)
}
_, err := time.Parse(time.RFC3339, timestamp)
if err != nil {
err = fmt.Errorf("'%s' is not a valid timestamp for %s. It should be in the form 'YYYY-MM-DDTHH:mm:ssZ'", timestamp, k)
errors = append(errors, err)
}
return
} | [
"func",
"validatePasswordExpiresAtQuery",
"(",
"v",
"interface",
"{",
"}",
",",
"k",
"string",
")",
"(",
"ws",
"[",
"]",
"string",
",",
"errors",
"[",
"]",
"error",
")",
"{",
"value",
":=",
"v",
".",
"(",
"string",
")",
"\n",
"values",
":=",
"strings",
".",
"SplitN",
"(",
"value",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"values",
")",
"!=",
"2",
"{",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"k",
",",
"value",
")",
"\n",
"errors",
"=",
"append",
"(",
"errors",
",",
"err",
")",
"\n",
"}",
"\n",
"operator",
",",
"timestamp",
":=",
"values",
"[",
"0",
"]",
",",
"values",
"[",
"1",
"]",
"\n\n",
"validOperators",
":=",
"map",
"[",
"string",
"]",
"bool",
"{",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"true",
",",
"}",
"\n",
"if",
"!",
"validOperators",
"[",
"operator",
"]",
"{",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"operator",
",",
"k",
")",
"\n",
"errors",
"=",
"append",
"(",
"errors",
",",
"err",
")",
"\n",
"}",
"\n\n",
"_",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"time",
".",
"RFC3339",
",",
"timestamp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"timestamp",
",",
"k",
")",
"\n",
"errors",
"=",
"append",
"(",
"errors",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Ensure that password_expires_at query matches format explained in
// https://developer.openstack.org/api-ref/identity/v3/#list-users | [
"Ensure",
"that",
"password_expires_at",
"query",
"matches",
"format",
"explained",
"in",
"https",
":",
"//",
"developer",
".",
"openstack",
".",
"org",
"/",
"api",
"-",
"ref",
"/",
"identity",
"/",
"v3",
"/",
"#list",
"-",
"users"
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/identity_user_v3.go#L44-L73 |
terraform-providers/terraform-provider-openstack | openstack/dns_recordset_v2.go | ToRecordSetCreateMap | func (opts RecordSetCreateOpts) ToRecordSetCreateMap() (map[string]interface{}, error) {
b, err := BuildRequest(opts, "")
if err != nil {
return nil, err
}
if m, ok := b[""].(map[string]interface{}); ok {
return m, nil
}
return nil, fmt.Errorf("Expected map but got %T", b[""])
} | go | func (opts RecordSetCreateOpts) ToRecordSetCreateMap() (map[string]interface{}, error) {
b, err := BuildRequest(opts, "")
if err != nil {
return nil, err
}
if m, ok := b[""].(map[string]interface{}); ok {
return m, nil
}
return nil, fmt.Errorf("Expected map but got %T", b[""])
} | [
"func",
"(",
"opts",
"RecordSetCreateOpts",
")",
"ToRecordSetCreateMap",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"BuildRequest",
"(",
"opts",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"m",
",",
"ok",
":=",
"b",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"return",
"m",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"b",
"[",
"\"",
"\"",
"]",
")",
"\n",
"}"
] | // ToRecordSetCreateMap casts a CreateOpts struct to a map.
// It overrides recordsets.ToRecordSetCreateMap to add the ValueSpecs field. | [
"ToRecordSetCreateMap",
"casts",
"a",
"CreateOpts",
"struct",
"to",
"a",
"map",
".",
"It",
"overrides",
"recordsets",
".",
"ToRecordSetCreateMap",
"to",
"add",
"the",
"ValueSpecs",
"field",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/dns_recordset_v2.go#L23-L34 |
terraform-providers/terraform-provider-openstack | openstack/dns_recordset_v2.go | dnsRecordSetV2RecordsStateFunc | func dnsRecordSetV2RecordsStateFunc(v interface{}) string {
if addr, ok := v.(string); ok {
re := regexp.MustCompile("[][]")
addr = re.ReplaceAllString(addr, "")
return addr
}
return ""
} | go | func dnsRecordSetV2RecordsStateFunc(v interface{}) string {
if addr, ok := v.(string); ok {
re := regexp.MustCompile("[][]")
addr = re.ReplaceAllString(addr, "")
return addr
}
return ""
} | [
"func",
"dnsRecordSetV2RecordsStateFunc",
"(",
"v",
"interface",
"{",
"}",
")",
"string",
"{",
"if",
"addr",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
";",
"ok",
"{",
"re",
":=",
"regexp",
".",
"MustCompile",
"(",
"\"",
"\"",
")",
"\n",
"addr",
"=",
"re",
".",
"ReplaceAllString",
"(",
"addr",
",",
"\"",
"\"",
")",
"\n\n",
"return",
"addr",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // dnsRecordSetV2RecordsStateFunc will strip brackets from IPv6 addresses. | [
"dnsRecordSetV2RecordsStateFunc",
"will",
"strip",
"brackets",
"from",
"IPv6",
"addresses",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/dns_recordset_v2.go#L82-L91 |
terraform-providers/terraform-provider-openstack | openstack/db_database_v1.go | databaseDatabaseV1StateRefreshFunc | func databaseDatabaseV1StateRefreshFunc(client *gophercloud.ServiceClient, instanceID string, dbName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
pages, err := databases.List(client, instanceID).AllPages()
if err != nil {
return nil, "", fmt.Errorf("Unable to retrieve OpenStack databases: %s", err)
}
allDatabases, err := databases.ExtractDBs(pages)
if err != nil {
return nil, "", fmt.Errorf("Unable to extract OpenStack databases: %s", err)
}
for _, v := range allDatabases {
if v.Name == dbName {
return v, "ACTIVE", nil
}
}
return nil, "BUILD", nil
}
} | go | func databaseDatabaseV1StateRefreshFunc(client *gophercloud.ServiceClient, instanceID string, dbName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
pages, err := databases.List(client, instanceID).AllPages()
if err != nil {
return nil, "", fmt.Errorf("Unable to retrieve OpenStack databases: %s", err)
}
allDatabases, err := databases.ExtractDBs(pages)
if err != nil {
return nil, "", fmt.Errorf("Unable to extract OpenStack databases: %s", err)
}
for _, v := range allDatabases {
if v.Name == dbName {
return v, "ACTIVE", nil
}
}
return nil, "BUILD", nil
}
} | [
"func",
"databaseDatabaseV1StateRefreshFunc",
"(",
"client",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"instanceID",
"string",
",",
"dbName",
"string",
")",
"resource",
".",
"StateRefreshFunc",
"{",
"return",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"string",
",",
"error",
")",
"{",
"pages",
",",
"err",
":=",
"databases",
".",
"List",
"(",
"client",
",",
"instanceID",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"allDatabases",
",",
"err",
":=",
"databases",
".",
"ExtractDBs",
"(",
"pages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"v",
":=",
"range",
"allDatabases",
"{",
"if",
"v",
".",
"Name",
"==",
"dbName",
"{",
"return",
"v",
",",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // databaseDatabaseV1StateRefreshFunc returns a resource.StateRefreshFunc
// that is used to watch a database. | [
"databaseDatabaseV1StateRefreshFunc",
"returns",
"a",
"resource",
".",
"StateRefreshFunc",
"that",
"is",
"used",
"to",
"watch",
"a",
"database",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/db_database_v1.go#L14-L34 |
terraform-providers/terraform-provider-openstack | openstack/db_user_v1.go | databaseUserV1StateRefreshFunc | func databaseUserV1StateRefreshFunc(client *gophercloud.ServiceClient, instanceID string, userName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
pages, err := users.List(client, instanceID).AllPages()
if err != nil {
return nil, "", fmt.Errorf("Unable to retrieve OpenStack database users: %s", err)
}
allUsers, err := users.ExtractUsers(pages)
if err != nil {
return nil, "", fmt.Errorf("Unable to extract OpenStack database users: %s", err)
}
for _, v := range allUsers {
if v.Name == userName {
return v, "ACTIVE", nil
}
}
return nil, "BUILD", nil
}
} | go | func databaseUserV1StateRefreshFunc(client *gophercloud.ServiceClient, instanceID string, userName string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
pages, err := users.List(client, instanceID).AllPages()
if err != nil {
return nil, "", fmt.Errorf("Unable to retrieve OpenStack database users: %s", err)
}
allUsers, err := users.ExtractUsers(pages)
if err != nil {
return nil, "", fmt.Errorf("Unable to extract OpenStack database users: %s", err)
}
for _, v := range allUsers {
if v.Name == userName {
return v, "ACTIVE", nil
}
}
return nil, "BUILD", nil
}
} | [
"func",
"databaseUserV1StateRefreshFunc",
"(",
"client",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"instanceID",
"string",
",",
"userName",
"string",
")",
"resource",
".",
"StateRefreshFunc",
"{",
"return",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"string",
",",
"error",
")",
"{",
"pages",
",",
"err",
":=",
"users",
".",
"List",
"(",
"client",
",",
"instanceID",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"allUsers",
",",
"err",
":=",
"users",
".",
"ExtractUsers",
"(",
"pages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"v",
":=",
"range",
"allUsers",
"{",
"if",
"v",
".",
"Name",
"==",
"userName",
"{",
"return",
"v",
",",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // databaseUserV1StateRefreshFunc returns a resource.StateRefreshFunc that is used to watch db user. | [
"databaseUserV1StateRefreshFunc",
"returns",
"a",
"resource",
".",
"StateRefreshFunc",
"that",
"is",
"used",
"to",
"watch",
"db",
"user",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/db_user_v1.go#L35-L55 |
terraform-providers/terraform-provider-openstack | openstack/db_user_v1.go | databaseUserV1Exists | func databaseUserV1Exists(client *gophercloud.ServiceClient, instanceID string, userName string) (bool, users.User, error) {
var exists bool
var err error
var userObj users.User
pages, err := users.List(client, instanceID).AllPages()
if err != nil {
return exists, userObj, err
}
allUsers, err := users.ExtractUsers(pages)
if err != nil {
return exists, userObj, err
}
for _, v := range allUsers {
if v.Name == userName {
exists = true
return exists, v, nil
}
}
return false, userObj, err
} | go | func databaseUserV1Exists(client *gophercloud.ServiceClient, instanceID string, userName string) (bool, users.User, error) {
var exists bool
var err error
var userObj users.User
pages, err := users.List(client, instanceID).AllPages()
if err != nil {
return exists, userObj, err
}
allUsers, err := users.ExtractUsers(pages)
if err != nil {
return exists, userObj, err
}
for _, v := range allUsers {
if v.Name == userName {
exists = true
return exists, v, nil
}
}
return false, userObj, err
} | [
"func",
"databaseUserV1Exists",
"(",
"client",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"instanceID",
"string",
",",
"userName",
"string",
")",
"(",
"bool",
",",
"users",
".",
"User",
",",
"error",
")",
"{",
"var",
"exists",
"bool",
"\n",
"var",
"err",
"error",
"\n",
"var",
"userObj",
"users",
".",
"User",
"\n\n",
"pages",
",",
"err",
":=",
"users",
".",
"List",
"(",
"client",
",",
"instanceID",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"exists",
",",
"userObj",
",",
"err",
"\n",
"}",
"\n\n",
"allUsers",
",",
"err",
":=",
"users",
".",
"ExtractUsers",
"(",
"pages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"exists",
",",
"userObj",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"v",
":=",
"range",
"allUsers",
"{",
"if",
"v",
".",
"Name",
"==",
"userName",
"{",
"exists",
"=",
"true",
"\n",
"return",
"exists",
",",
"v",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
",",
"userObj",
",",
"err",
"\n",
"}"
] | // databaseUserV1Exists is used to check whether user exists on particular database instance | [
"databaseUserV1Exists",
"is",
"used",
"to",
"check",
"whether",
"user",
"exists",
"on",
"particular",
"database",
"instance"
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/db_user_v1.go#L58-L81 |
terraform-providers/terraform-provider-openstack | openstack/lb_v2_shared.go | chooseLBV2Client | func chooseLBV2Client(d *schema.ResourceData, config *Config) (*gophercloud.ServiceClient, error) {
if config.useOctavia {
return config.loadBalancerV2Client(GetRegion(d, config))
}
return config.networkingV2Client(GetRegion(d, config))
} | go | func chooseLBV2Client(d *schema.ResourceData, config *Config) (*gophercloud.ServiceClient, error) {
if config.useOctavia {
return config.loadBalancerV2Client(GetRegion(d, config))
}
return config.networkingV2Client(GetRegion(d, config))
} | [
"func",
"chooseLBV2Client",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"config",
"*",
"Config",
")",
"(",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"error",
")",
"{",
"if",
"config",
".",
"useOctavia",
"{",
"return",
"config",
".",
"loadBalancerV2Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"}",
"\n",
"return",
"config",
".",
"networkingV2Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"}"
] | // chooseLBV2Client will determine which load balacing client to use:
// Either the Octavia/LBaaS client or the Neutron/Networking v2 client. | [
"chooseLBV2Client",
"will",
"determine",
"which",
"load",
"balacing",
"client",
"to",
"use",
":",
"Either",
"the",
"Octavia",
"/",
"LBaaS",
"client",
"or",
"the",
"Neutron",
"/",
"Networking",
"v2",
"client",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/lb_v2_shared.go#L30-L35 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_identity_user_v3.go | dataSourceIdentityUserV3Read | func dataSourceIdentityUserV3Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
identityClient, err := config.identityV3Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack identity client: %s", err)
}
enabled := d.Get("enabled").(bool)
listOpts := users.ListOpts{
DomainID: d.Get("domain_id").(string),
Enabled: &enabled,
IdPID: d.Get("idp_id").(string),
Name: d.Get("name").(string),
PasswordExpiresAt: d.Get("password_expires_at").(string),
ProtocolID: d.Get("protocol_id").(string),
UniqueID: d.Get("unique_id").(string),
}
log.Printf("[DEBUG] openstack_identity_user_v3 list options: %#v", listOpts)
var user users.User
allPages, err := users.List(identityClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query openstack_identity_user_v3: %s", err)
}
allUsers, err := users.ExtractUsers(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve openstack_identity_user_v3: %s", err)
}
if len(allUsers) < 1 {
return fmt.Errorf("Your openstack_identity_user_v3 query returned no results. " +
"Please change your search criteria and try again.")
}
if len(allUsers) > 1 {
return fmt.Errorf("Your openstack_identity_user_v3 query returned more than one result.")
}
user = allUsers[0]
return dataSourceIdentityUserV3Attributes(d, &user)
} | go | func dataSourceIdentityUserV3Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
identityClient, err := config.identityV3Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack identity client: %s", err)
}
enabled := d.Get("enabled").(bool)
listOpts := users.ListOpts{
DomainID: d.Get("domain_id").(string),
Enabled: &enabled,
IdPID: d.Get("idp_id").(string),
Name: d.Get("name").(string),
PasswordExpiresAt: d.Get("password_expires_at").(string),
ProtocolID: d.Get("protocol_id").(string),
UniqueID: d.Get("unique_id").(string),
}
log.Printf("[DEBUG] openstack_identity_user_v3 list options: %#v", listOpts)
var user users.User
allPages, err := users.List(identityClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query openstack_identity_user_v3: %s", err)
}
allUsers, err := users.ExtractUsers(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve openstack_identity_user_v3: %s", err)
}
if len(allUsers) < 1 {
return fmt.Errorf("Your openstack_identity_user_v3 query returned no results. " +
"Please change your search criteria and try again.")
}
if len(allUsers) > 1 {
return fmt.Errorf("Your openstack_identity_user_v3 query returned more than one result.")
}
user = allUsers[0]
return dataSourceIdentityUserV3Attributes(d, &user)
} | [
"func",
"dataSourceIdentityUserV3Read",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"meta",
"interface",
"{",
"}",
")",
"error",
"{",
"config",
":=",
"meta",
".",
"(",
"*",
"Config",
")",
"\n",
"identityClient",
",",
"err",
":=",
"config",
".",
"identityV3Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"enabled",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"bool",
")",
"\n",
"listOpts",
":=",
"users",
".",
"ListOpts",
"{",
"DomainID",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"Enabled",
":",
"&",
"enabled",
",",
"IdPID",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"Name",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"PasswordExpiresAt",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"ProtocolID",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"UniqueID",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"listOpts",
")",
"\n\n",
"var",
"user",
"users",
".",
"User",
"\n",
"allPages",
",",
"err",
":=",
"users",
".",
"List",
"(",
"identityClient",
",",
"listOpts",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"allUsers",
",",
"err",
":=",
"users",
".",
"ExtractUsers",
"(",
"allPages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allUsers",
")",
"<",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allUsers",
")",
">",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"user",
"=",
"allUsers",
"[",
"0",
"]",
"\n\n",
"return",
"dataSourceIdentityUserV3Attributes",
"(",
"d",
",",
"&",
"user",
")",
"\n",
"}"
] | // dataSourceIdentityUserV3Read performs the user lookup. | [
"dataSourceIdentityUserV3Read",
"performs",
"the",
"user",
"lookup",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_user_v3.go#L71-L114 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_identity_user_v3.go | dataSourceIdentityUserV3Attributes | func dataSourceIdentityUserV3Attributes(d *schema.ResourceData, user *users.User) error {
log.Printf("[DEBUG] openstack_identity_user_v3 details: %#v", user)
d.SetId(user.ID)
d.Set("default_project_id", user.DefaultProjectID)
d.Set("description", user.Description)
d.Set("domain_id", user.DomainID)
d.Set("enabled", user.Enabled)
d.Set("name", user.Name)
d.Set("password_expires_at", user.PasswordExpiresAt.Format(time.RFC3339))
return nil
} | go | func dataSourceIdentityUserV3Attributes(d *schema.ResourceData, user *users.User) error {
log.Printf("[DEBUG] openstack_identity_user_v3 details: %#v", user)
d.SetId(user.ID)
d.Set("default_project_id", user.DefaultProjectID)
d.Set("description", user.Description)
d.Set("domain_id", user.DomainID)
d.Set("enabled", user.Enabled)
d.Set("name", user.Name)
d.Set("password_expires_at", user.PasswordExpiresAt.Format(time.RFC3339))
return nil
} | [
"func",
"dataSourceIdentityUserV3Attributes",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"user",
"*",
"users",
".",
"User",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"user",
")",
"\n\n",
"d",
".",
"SetId",
"(",
"user",
".",
"ID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"user",
".",
"DefaultProjectID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"user",
".",
"Description",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"user",
".",
"DomainID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"user",
".",
"Enabled",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"user",
".",
"Name",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"user",
".",
"PasswordExpiresAt",
".",
"Format",
"(",
"time",
".",
"RFC3339",
")",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // dataSourceIdentityUserV3Attributes populates the fields of an User resource. | [
"dataSourceIdentityUserV3Attributes",
"populates",
"the",
"fields",
"of",
"an",
"User",
"resource",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_user_v3.go#L117-L129 |
terraform-providers/terraform-provider-openstack | openstack/resource_openstack_sharedfilesystem_share_v2.go | waitForSFV2Share | func waitForSFV2Share(sfsClient *gophercloud.ServiceClient, id string, target string, pending []string, timeout time.Duration) error {
log.Printf("[DEBUG] Waiting for share %s to become %s.", id, target)
stateConf := &resource.StateChangeConf{
Target: []string{target},
Pending: pending,
Refresh: resourceSFV2ShareRefreshFunc(sfsClient, id),
Timeout: timeout,
Delay: 1 * time.Second,
MinTimeout: 1 * time.Second,
}
_, err := stateConf.WaitForState()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
switch target {
case "deleted":
return nil
default:
return fmt.Errorf("Error: share %s not found: %s", id, err)
}
}
errorMessage := fmt.Sprintf("Error waiting for share %s to become %s", id, target)
msg := resourceSFSV2ShareManilaMessage(sfsClient, id)
if msg == nil {
return fmt.Errorf("%s: %s", errorMessage, err)
}
return fmt.Errorf("%s: %s: the latest manila message (%s): %s", errorMessage, err, msg.CreatedAt, msg.UserMessage)
}
return nil
} | go | func waitForSFV2Share(sfsClient *gophercloud.ServiceClient, id string, target string, pending []string, timeout time.Duration) error {
log.Printf("[DEBUG] Waiting for share %s to become %s.", id, target)
stateConf := &resource.StateChangeConf{
Target: []string{target},
Pending: pending,
Refresh: resourceSFV2ShareRefreshFunc(sfsClient, id),
Timeout: timeout,
Delay: 1 * time.Second,
MinTimeout: 1 * time.Second,
}
_, err := stateConf.WaitForState()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
switch target {
case "deleted":
return nil
default:
return fmt.Errorf("Error: share %s not found: %s", id, err)
}
}
errorMessage := fmt.Sprintf("Error waiting for share %s to become %s", id, target)
msg := resourceSFSV2ShareManilaMessage(sfsClient, id)
if msg == nil {
return fmt.Errorf("%s: %s", errorMessage, err)
}
return fmt.Errorf("%s: %s: the latest manila message (%s): %s", errorMessage, err, msg.CreatedAt, msg.UserMessage)
}
return nil
} | [
"func",
"waitForSFV2Share",
"(",
"sfsClient",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"id",
"string",
",",
"target",
"string",
",",
"pending",
"[",
"]",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"id",
",",
"target",
")",
"\n\n",
"stateConf",
":=",
"&",
"resource",
".",
"StateChangeConf",
"{",
"Target",
":",
"[",
"]",
"string",
"{",
"target",
"}",
",",
"Pending",
":",
"pending",
",",
"Refresh",
":",
"resourceSFV2ShareRefreshFunc",
"(",
"sfsClient",
",",
"id",
")",
",",
"Timeout",
":",
"timeout",
",",
"Delay",
":",
"1",
"*",
"time",
".",
"Second",
",",
"MinTimeout",
":",
"1",
"*",
"time",
".",
"Second",
",",
"}",
"\n\n",
"_",
",",
"err",
":=",
"stateConf",
".",
"WaitForState",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"gophercloud",
".",
"ErrDefault404",
")",
";",
"ok",
"{",
"switch",
"target",
"{",
"case",
"\"",
"\"",
":",
"return",
"nil",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"id",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"errorMessage",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"id",
",",
"target",
")",
"\n",
"msg",
":=",
"resourceSFSV2ShareManilaMessage",
"(",
"sfsClient",
",",
"id",
")",
"\n",
"if",
"msg",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"errorMessage",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"errorMessage",
",",
"err",
",",
"msg",
".",
"CreatedAt",
",",
"msg",
".",
"UserMessage",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Full list of the share statuses: https://developer.openstack.org/api-ref/shared-file-system/#shares | [
"Full",
"list",
"of",
"the",
"share",
"statuses",
":",
"https",
":",
"//",
"developer",
".",
"openstack",
".",
"org",
"/",
"api",
"-",
"ref",
"/",
"shared",
"-",
"file",
"-",
"system",
"/",
"#shares"
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/resource_openstack_sharedfilesystem_share_v2.go#L437-L468 |
terraform-providers/terraform-provider-openstack | openstack/db_configuration_v1.go | databaseConfigurationV1StateRefreshFunc | func databaseConfigurationV1StateRefreshFunc(client *gophercloud.ServiceClient, cgroupID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
i, err := configurations.Get(client, cgroupID).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
return i, "DELETED", nil
}
return nil, "", err
}
return i, "ACTIVE", nil
}
} | go | func databaseConfigurationV1StateRefreshFunc(client *gophercloud.ServiceClient, cgroupID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
i, err := configurations.Get(client, cgroupID).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
return i, "DELETED", nil
}
return nil, "", err
}
return i, "ACTIVE", nil
}
} | [
"func",
"databaseConfigurationV1StateRefreshFunc",
"(",
"client",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"cgroupID",
"string",
")",
"resource",
".",
"StateRefreshFunc",
"{",
"return",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"string",
",",
"error",
")",
"{",
"i",
",",
"err",
":=",
"configurations",
".",
"Get",
"(",
"client",
",",
"cgroupID",
")",
".",
"Extract",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"gophercloud",
".",
"ErrDefault404",
")",
";",
"ok",
"{",
"return",
"i",
",",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"i",
",",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // databaseConfigurationV1StateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// an cloud database instance. | [
"databaseConfigurationV1StateRefreshFunc",
"returns",
"a",
"resource",
".",
"StateRefreshFunc",
"that",
"is",
"used",
"to",
"watch",
"an",
"cloud",
"database",
"instance",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/db_configuration_v1.go#L43-L55 |
terraform-providers/terraform-provider-openstack | openstack/resource_openstack_compute_instance_v2.go | ServerV2StateRefreshFunc | func ServerV2StateRefreshFunc(client *gophercloud.ServiceClient, instanceID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
s, err := servers.Get(client, instanceID).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
return s, "DELETED", nil
}
return nil, "", err
}
return s, s.Status, nil
}
} | go | func ServerV2StateRefreshFunc(client *gophercloud.ServiceClient, instanceID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
s, err := servers.Get(client, instanceID).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
return s, "DELETED", nil
}
return nil, "", err
}
return s, s.Status, nil
}
} | [
"func",
"ServerV2StateRefreshFunc",
"(",
"client",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"instanceID",
"string",
")",
"resource",
".",
"StateRefreshFunc",
"{",
"return",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"string",
",",
"error",
")",
"{",
"s",
",",
"err",
":=",
"servers",
".",
"Get",
"(",
"client",
",",
"instanceID",
")",
".",
"Extract",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"gophercloud",
".",
"ErrDefault404",
")",
";",
"ok",
"{",
"return",
"s",
",",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"s",
",",
"s",
".",
"Status",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // ServerV2StateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// an OpenStack instance. | [
"ServerV2StateRefreshFunc",
"returns",
"a",
"resource",
".",
"StateRefreshFunc",
"that",
"is",
"used",
"to",
"watch",
"an",
"OpenStack",
"instance",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/resource_openstack_compute_instance_v2.go#L950-L962 |
terraform-providers/terraform-provider-openstack | openstack/resource_openstack_compute_instance_v2.go | suppressAvailabilityZoneDetailDiffs | func suppressAvailabilityZoneDetailDiffs(k, old, new string, d *schema.ResourceData) bool {
if strings.Contains(new, ":") {
parts := strings.Split(new, ":")
az := parts[0]
if az == old {
return true
}
}
return false
} | go | func suppressAvailabilityZoneDetailDiffs(k, old, new string, d *schema.ResourceData) bool {
if strings.Contains(new, ":") {
parts := strings.Split(new, ":")
az := parts[0]
if az == old {
return true
}
}
return false
} | [
"func",
"suppressAvailabilityZoneDetailDiffs",
"(",
"k",
",",
"old",
",",
"new",
"string",
",",
"d",
"*",
"schema",
".",
"ResourceData",
")",
"bool",
"{",
"if",
"strings",
".",
"Contains",
"(",
"new",
",",
"\"",
"\"",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"new",
",",
"\"",
"\"",
")",
"\n",
"az",
":=",
"parts",
"[",
"0",
"]",
"\n\n",
"if",
"az",
"==",
"old",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] | // suppressAvailabilityZoneDetailDiffs will suppress diffs when a user specifies an
// availability zone in the format of `az:host:node` and Nova/Compute responds with
// only `az`. | [
"suppressAvailabilityZoneDetailDiffs",
"will",
"suppress",
"diffs",
"when",
"a",
"user",
"specifies",
"an",
"availability",
"zone",
"in",
"the",
"format",
"of",
"az",
":",
"host",
":",
"node",
"and",
"Nova",
"/",
"Compute",
"responds",
"with",
"only",
"az",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/resource_openstack_compute_instance_v2.go#L1258-L1269 |
terraform-providers/terraform-provider-openstack | openstack/config.go | LoadAndValidate | func (c *Config) LoadAndValidate() error {
// Make sure at least one of auth_url or cloud was specified.
if c.IdentityEndpoint == "" && c.Cloud == "" {
return fmt.Errorf("One of 'auth_url' or 'cloud' must be specified")
}
validEndpoint := false
validEndpoints := []string{
"internal", "internalURL",
"admin", "adminURL",
"public", "publicURL",
"",
}
for _, endpoint := range validEndpoints {
if c.EndpointType == endpoint {
validEndpoint = true
}
}
if !validEndpoint {
return fmt.Errorf("Invalid endpoint type provided")
}
clientOpts := new(clientconfig.ClientOpts)
// If a cloud entry was given, base AuthOptions on a clouds.yaml file.
if c.Cloud != "" {
clientOpts.Cloud = c.Cloud
cloud, err := clientconfig.GetCloudFromYAML(clientOpts)
if err != nil {
return err
}
if c.Region == "" && cloud.RegionName != "" {
c.Region = cloud.RegionName
}
if c.CACertFile == "" && cloud.CACertFile != "" {
c.CACertFile = cloud.CACertFile
}
if c.ClientCertFile == "" && cloud.ClientCertFile != "" {
c.ClientCertFile = cloud.ClientCertFile
}
if c.ClientKeyFile == "" && cloud.ClientKeyFile != "" {
c.ClientKeyFile = cloud.ClientKeyFile
}
if c.Insecure == nil && cloud.Verify != nil {
v := (!*cloud.Verify)
c.Insecure = &v
}
} else {
authInfo := &clientconfig.AuthInfo{
AuthURL: c.IdentityEndpoint,
DefaultDomain: c.DefaultDomain,
DomainID: c.DomainID,
DomainName: c.DomainName,
Password: c.Password,
ProjectDomainID: c.ProjectDomainID,
ProjectDomainName: c.ProjectDomainName,
ProjectID: c.TenantID,
ProjectName: c.TenantName,
Token: c.Token,
UserDomainID: c.UserDomainID,
UserDomainName: c.UserDomainName,
Username: c.Username,
UserID: c.UserID,
ApplicationCredentialID: c.ApplicationCredentialID,
ApplicationCredentialName: c.ApplicationCredentialName,
ApplicationCredentialSecret: c.ApplicationCredentialSecret,
}
clientOpts.AuthInfo = authInfo
}
ao, err := clientconfig.AuthOptions(clientOpts)
if err != nil {
return err
}
client, err := openstack.NewClient(ao.IdentityEndpoint)
if err != nil {
return err
}
// Set UserAgent
client.UserAgent.Prepend(terraform.UserAgentString())
config := &tls.Config{}
if c.CACertFile != "" {
caCert, _, err := pathorcontents.Read(c.CACertFile)
if err != nil {
return fmt.Errorf("Error reading CA Cert: %s", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM([]byte(caCert))
config.RootCAs = caCertPool
}
if c.Insecure == nil {
config.InsecureSkipVerify = false
} else {
config.InsecureSkipVerify = *c.Insecure
}
if c.ClientCertFile != "" && c.ClientKeyFile != "" {
clientCert, _, err := pathorcontents.Read(c.ClientCertFile)
if err != nil {
return fmt.Errorf("Error reading Client Cert: %s", err)
}
clientKey, _, err := pathorcontents.Read(c.ClientKeyFile)
if err != nil {
return fmt.Errorf("Error reading Client Key: %s", err)
}
cert, err := tls.X509KeyPair([]byte(clientCert), []byte(clientKey))
if err != nil {
return err
}
config.Certificates = []tls.Certificate{cert}
config.BuildNameToCertificate()
}
// if OS_DEBUG is set, log the requests and responses
var osDebug bool
if os.Getenv("OS_DEBUG") != "" {
osDebug = true
}
transport := &http.Transport{Proxy: http.ProxyFromEnvironment, TLSClientConfig: config}
client.HTTPClient = http.Client{
Transport: &LogRoundTripper{
Rt: transport,
OsDebug: osDebug,
MaxRetries: c.MaxRetries,
},
}
// If using Swift Authentication, there's no need to validate authentication normally.
if !c.Swauth {
err = openstack.Authenticate(client, *ao)
if err != nil {
return err
}
}
if c.MaxRetries < 0 {
return fmt.Errorf("max_retries should be a positive value")
}
c.OsClient = client
return nil
} | go | func (c *Config) LoadAndValidate() error {
// Make sure at least one of auth_url or cloud was specified.
if c.IdentityEndpoint == "" && c.Cloud == "" {
return fmt.Errorf("One of 'auth_url' or 'cloud' must be specified")
}
validEndpoint := false
validEndpoints := []string{
"internal", "internalURL",
"admin", "adminURL",
"public", "publicURL",
"",
}
for _, endpoint := range validEndpoints {
if c.EndpointType == endpoint {
validEndpoint = true
}
}
if !validEndpoint {
return fmt.Errorf("Invalid endpoint type provided")
}
clientOpts := new(clientconfig.ClientOpts)
// If a cloud entry was given, base AuthOptions on a clouds.yaml file.
if c.Cloud != "" {
clientOpts.Cloud = c.Cloud
cloud, err := clientconfig.GetCloudFromYAML(clientOpts)
if err != nil {
return err
}
if c.Region == "" && cloud.RegionName != "" {
c.Region = cloud.RegionName
}
if c.CACertFile == "" && cloud.CACertFile != "" {
c.CACertFile = cloud.CACertFile
}
if c.ClientCertFile == "" && cloud.ClientCertFile != "" {
c.ClientCertFile = cloud.ClientCertFile
}
if c.ClientKeyFile == "" && cloud.ClientKeyFile != "" {
c.ClientKeyFile = cloud.ClientKeyFile
}
if c.Insecure == nil && cloud.Verify != nil {
v := (!*cloud.Verify)
c.Insecure = &v
}
} else {
authInfo := &clientconfig.AuthInfo{
AuthURL: c.IdentityEndpoint,
DefaultDomain: c.DefaultDomain,
DomainID: c.DomainID,
DomainName: c.DomainName,
Password: c.Password,
ProjectDomainID: c.ProjectDomainID,
ProjectDomainName: c.ProjectDomainName,
ProjectID: c.TenantID,
ProjectName: c.TenantName,
Token: c.Token,
UserDomainID: c.UserDomainID,
UserDomainName: c.UserDomainName,
Username: c.Username,
UserID: c.UserID,
ApplicationCredentialID: c.ApplicationCredentialID,
ApplicationCredentialName: c.ApplicationCredentialName,
ApplicationCredentialSecret: c.ApplicationCredentialSecret,
}
clientOpts.AuthInfo = authInfo
}
ao, err := clientconfig.AuthOptions(clientOpts)
if err != nil {
return err
}
client, err := openstack.NewClient(ao.IdentityEndpoint)
if err != nil {
return err
}
// Set UserAgent
client.UserAgent.Prepend(terraform.UserAgentString())
config := &tls.Config{}
if c.CACertFile != "" {
caCert, _, err := pathorcontents.Read(c.CACertFile)
if err != nil {
return fmt.Errorf("Error reading CA Cert: %s", err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM([]byte(caCert))
config.RootCAs = caCertPool
}
if c.Insecure == nil {
config.InsecureSkipVerify = false
} else {
config.InsecureSkipVerify = *c.Insecure
}
if c.ClientCertFile != "" && c.ClientKeyFile != "" {
clientCert, _, err := pathorcontents.Read(c.ClientCertFile)
if err != nil {
return fmt.Errorf("Error reading Client Cert: %s", err)
}
clientKey, _, err := pathorcontents.Read(c.ClientKeyFile)
if err != nil {
return fmt.Errorf("Error reading Client Key: %s", err)
}
cert, err := tls.X509KeyPair([]byte(clientCert), []byte(clientKey))
if err != nil {
return err
}
config.Certificates = []tls.Certificate{cert}
config.BuildNameToCertificate()
}
// if OS_DEBUG is set, log the requests and responses
var osDebug bool
if os.Getenv("OS_DEBUG") != "" {
osDebug = true
}
transport := &http.Transport{Proxy: http.ProxyFromEnvironment, TLSClientConfig: config}
client.HTTPClient = http.Client{
Transport: &LogRoundTripper{
Rt: transport,
OsDebug: osDebug,
MaxRetries: c.MaxRetries,
},
}
// If using Swift Authentication, there's no need to validate authentication normally.
if !c.Swauth {
err = openstack.Authenticate(client, *ao)
if err != nil {
return err
}
}
if c.MaxRetries < 0 {
return fmt.Errorf("max_retries should be a positive value")
}
c.OsClient = client
return nil
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"LoadAndValidate",
"(",
")",
"error",
"{",
"// Make sure at least one of auth_url or cloud was specified.",
"if",
"c",
".",
"IdentityEndpoint",
"==",
"\"",
"\"",
"&&",
"c",
".",
"Cloud",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"validEndpoint",
":=",
"false",
"\n",
"validEndpoints",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"}",
"\n\n",
"for",
"_",
",",
"endpoint",
":=",
"range",
"validEndpoints",
"{",
"if",
"c",
".",
"EndpointType",
"==",
"endpoint",
"{",
"validEndpoint",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"validEndpoint",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"clientOpts",
":=",
"new",
"(",
"clientconfig",
".",
"ClientOpts",
")",
"\n\n",
"// If a cloud entry was given, base AuthOptions on a clouds.yaml file.",
"if",
"c",
".",
"Cloud",
"!=",
"\"",
"\"",
"{",
"clientOpts",
".",
"Cloud",
"=",
"c",
".",
"Cloud",
"\n\n",
"cloud",
",",
"err",
":=",
"clientconfig",
".",
"GetCloudFromYAML",
"(",
"clientOpts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"Region",
"==",
"\"",
"\"",
"&&",
"cloud",
".",
"RegionName",
"!=",
"\"",
"\"",
"{",
"c",
".",
"Region",
"=",
"cloud",
".",
"RegionName",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"CACertFile",
"==",
"\"",
"\"",
"&&",
"cloud",
".",
"CACertFile",
"!=",
"\"",
"\"",
"{",
"c",
".",
"CACertFile",
"=",
"cloud",
".",
"CACertFile",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"ClientCertFile",
"==",
"\"",
"\"",
"&&",
"cloud",
".",
"ClientCertFile",
"!=",
"\"",
"\"",
"{",
"c",
".",
"ClientCertFile",
"=",
"cloud",
".",
"ClientCertFile",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"ClientKeyFile",
"==",
"\"",
"\"",
"&&",
"cloud",
".",
"ClientKeyFile",
"!=",
"\"",
"\"",
"{",
"c",
".",
"ClientKeyFile",
"=",
"cloud",
".",
"ClientKeyFile",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"Insecure",
"==",
"nil",
"&&",
"cloud",
".",
"Verify",
"!=",
"nil",
"{",
"v",
":=",
"(",
"!",
"*",
"cloud",
".",
"Verify",
")",
"\n",
"c",
".",
"Insecure",
"=",
"&",
"v",
"\n",
"}",
"\n",
"}",
"else",
"{",
"authInfo",
":=",
"&",
"clientconfig",
".",
"AuthInfo",
"{",
"AuthURL",
":",
"c",
".",
"IdentityEndpoint",
",",
"DefaultDomain",
":",
"c",
".",
"DefaultDomain",
",",
"DomainID",
":",
"c",
".",
"DomainID",
",",
"DomainName",
":",
"c",
".",
"DomainName",
",",
"Password",
":",
"c",
".",
"Password",
",",
"ProjectDomainID",
":",
"c",
".",
"ProjectDomainID",
",",
"ProjectDomainName",
":",
"c",
".",
"ProjectDomainName",
",",
"ProjectID",
":",
"c",
".",
"TenantID",
",",
"ProjectName",
":",
"c",
".",
"TenantName",
",",
"Token",
":",
"c",
".",
"Token",
",",
"UserDomainID",
":",
"c",
".",
"UserDomainID",
",",
"UserDomainName",
":",
"c",
".",
"UserDomainName",
",",
"Username",
":",
"c",
".",
"Username",
",",
"UserID",
":",
"c",
".",
"UserID",
",",
"ApplicationCredentialID",
":",
"c",
".",
"ApplicationCredentialID",
",",
"ApplicationCredentialName",
":",
"c",
".",
"ApplicationCredentialName",
",",
"ApplicationCredentialSecret",
":",
"c",
".",
"ApplicationCredentialSecret",
",",
"}",
"\n",
"clientOpts",
".",
"AuthInfo",
"=",
"authInfo",
"\n",
"}",
"\n\n",
"ao",
",",
"err",
":=",
"clientconfig",
".",
"AuthOptions",
"(",
"clientOpts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"client",
",",
"err",
":=",
"openstack",
".",
"NewClient",
"(",
"ao",
".",
"IdentityEndpoint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Set UserAgent",
"client",
".",
"UserAgent",
".",
"Prepend",
"(",
"terraform",
".",
"UserAgentString",
"(",
")",
")",
"\n\n",
"config",
":=",
"&",
"tls",
".",
"Config",
"{",
"}",
"\n",
"if",
"c",
".",
"CACertFile",
"!=",
"\"",
"\"",
"{",
"caCert",
",",
"_",
",",
"err",
":=",
"pathorcontents",
".",
"Read",
"(",
"c",
".",
"CACertFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"caCertPool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n",
"caCertPool",
".",
"AppendCertsFromPEM",
"(",
"[",
"]",
"byte",
"(",
"caCert",
")",
")",
"\n",
"config",
".",
"RootCAs",
"=",
"caCertPool",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"Insecure",
"==",
"nil",
"{",
"config",
".",
"InsecureSkipVerify",
"=",
"false",
"\n",
"}",
"else",
"{",
"config",
".",
"InsecureSkipVerify",
"=",
"*",
"c",
".",
"Insecure",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"ClientCertFile",
"!=",
"\"",
"\"",
"&&",
"c",
".",
"ClientKeyFile",
"!=",
"\"",
"\"",
"{",
"clientCert",
",",
"_",
",",
"err",
":=",
"pathorcontents",
".",
"Read",
"(",
"c",
".",
"ClientCertFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"clientKey",
",",
"_",
",",
"err",
":=",
"pathorcontents",
".",
"Read",
"(",
"c",
".",
"ClientKeyFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"cert",
",",
"err",
":=",
"tls",
".",
"X509KeyPair",
"(",
"[",
"]",
"byte",
"(",
"clientCert",
")",
",",
"[",
"]",
"byte",
"(",
"clientKey",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"config",
".",
"Certificates",
"=",
"[",
"]",
"tls",
".",
"Certificate",
"{",
"cert",
"}",
"\n",
"config",
".",
"BuildNameToCertificate",
"(",
")",
"\n",
"}",
"\n\n",
"// if OS_DEBUG is set, log the requests and responses",
"var",
"osDebug",
"bool",
"\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"osDebug",
"=",
"true",
"\n",
"}",
"\n\n",
"transport",
":=",
"&",
"http",
".",
"Transport",
"{",
"Proxy",
":",
"http",
".",
"ProxyFromEnvironment",
",",
"TLSClientConfig",
":",
"config",
"}",
"\n",
"client",
".",
"HTTPClient",
"=",
"http",
".",
"Client",
"{",
"Transport",
":",
"&",
"LogRoundTripper",
"{",
"Rt",
":",
"transport",
",",
"OsDebug",
":",
"osDebug",
",",
"MaxRetries",
":",
"c",
".",
"MaxRetries",
",",
"}",
",",
"}",
"\n\n",
"// If using Swift Authentication, there's no need to validate authentication normally.",
"if",
"!",
"c",
".",
"Swauth",
"{",
"err",
"=",
"openstack",
".",
"Authenticate",
"(",
"client",
",",
"*",
"ao",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"MaxRetries",
"<",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"c",
".",
"OsClient",
"=",
"client",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // LoadAndValidate performs the authentication and initial configuration
// of an OpenStack Provider Client. This sets up the HTTP client and
// authenticates to an OpenStack cloud.
//
// Individual Service Clients are created later in this file. | [
"LoadAndValidate",
"performs",
"the",
"authentication",
"and",
"initial",
"configuration",
"of",
"an",
"OpenStack",
"Provider",
"Client",
".",
"This",
"sets",
"up",
"the",
"HTTP",
"client",
"and",
"authenticates",
"to",
"an",
"OpenStack",
"cloud",
".",
"Individual",
"Service",
"Clients",
"are",
"created",
"later",
"in",
"this",
"file",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/config.go#L57-L215 |
terraform-providers/terraform-provider-openstack | openstack/config.go | determineEndpoint | func (c *Config) determineEndpoint(client *gophercloud.ServiceClient, service string) *gophercloud.ServiceClient {
finalEndpoint := client.ResourceBaseURL()
if v, ok := c.EndpointOverrides[service]; ok {
if endpoint, ok := v.(string); ok && endpoint != "" {
finalEndpoint = endpoint
client.Endpoint = endpoint
client.ResourceBase = ""
}
}
log.Printf("[DEBUG] OpenStack Endpoint for %s: %s", service, finalEndpoint)
return client
} | go | func (c *Config) determineEndpoint(client *gophercloud.ServiceClient, service string) *gophercloud.ServiceClient {
finalEndpoint := client.ResourceBaseURL()
if v, ok := c.EndpointOverrides[service]; ok {
if endpoint, ok := v.(string); ok && endpoint != "" {
finalEndpoint = endpoint
client.Endpoint = endpoint
client.ResourceBase = ""
}
}
log.Printf("[DEBUG] OpenStack Endpoint for %s: %s", service, finalEndpoint)
return client
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"determineEndpoint",
"(",
"client",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"service",
"string",
")",
"*",
"gophercloud",
".",
"ServiceClient",
"{",
"finalEndpoint",
":=",
"client",
".",
"ResourceBaseURL",
"(",
")",
"\n\n",
"if",
"v",
",",
"ok",
":=",
"c",
".",
"EndpointOverrides",
"[",
"service",
"]",
";",
"ok",
"{",
"if",
"endpoint",
",",
"ok",
":=",
"v",
".",
"(",
"string",
")",
";",
"ok",
"&&",
"endpoint",
"!=",
"\"",
"\"",
"{",
"finalEndpoint",
"=",
"endpoint",
"\n",
"client",
".",
"Endpoint",
"=",
"endpoint",
"\n",
"client",
".",
"ResourceBase",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"service",
",",
"finalEndpoint",
")",
"\n\n",
"return",
"client",
"\n",
"}"
] | // determineEndpoint is a helper method to determine if the user wants to
// override an endpoint returned from the catalog. | [
"determineEndpoint",
"is",
"a",
"helper",
"method",
"to",
"determine",
"if",
"the",
"user",
"wants",
"to",
"override",
"an",
"endpoint",
"returned",
"from",
"the",
"catalog",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/config.go#L219-L233 |
terraform-providers/terraform-provider-openstack | openstack/config.go | determineRegion | func (c *Config) determineRegion(region string) string {
// If a resource-level region was not specified, and a provider-level region was set,
// use the provider-level region.
if region == "" && c.Region != "" {
region = c.Region
}
log.Printf("[DEBUG] OpenStack Region is: %s", region)
return region
} | go | func (c *Config) determineRegion(region string) string {
// If a resource-level region was not specified, and a provider-level region was set,
// use the provider-level region.
if region == "" && c.Region != "" {
region = c.Region
}
log.Printf("[DEBUG] OpenStack Region is: %s", region)
return region
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"determineRegion",
"(",
"region",
"string",
")",
"string",
"{",
"// If a resource-level region was not specified, and a provider-level region was set,",
"// use the provider-level region.",
"if",
"region",
"==",
"\"",
"\"",
"&&",
"c",
".",
"Region",
"!=",
"\"",
"\"",
"{",
"region",
"=",
"c",
".",
"Region",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"region",
")",
"\n",
"return",
"region",
"\n",
"}"
] | // determineRegion is a helper method to determine the region based on
// the user's settings. | [
"determineRegion",
"is",
"a",
"helper",
"method",
"to",
"determine",
"the",
"region",
"based",
"on",
"the",
"user",
"s",
"settings",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/config.go#L237-L246 |
terraform-providers/terraform-provider-openstack | openstack/config.go | blockStorageV1Client | func (c *Config) blockStorageV1Client(region string) (*gophercloud.ServiceClient, error) {
client, err := openstack.NewBlockStorageV1(c.OsClient, gophercloud.EndpointOpts{
Region: c.determineRegion(region),
Availability: c.getEndpointType(),
})
if err != nil {
return client, err
}
// Check if an endpoint override was specified for the volume service.
client = c.determineEndpoint(client, "volume")
return client, nil
} | go | func (c *Config) blockStorageV1Client(region string) (*gophercloud.ServiceClient, error) {
client, err := openstack.NewBlockStorageV1(c.OsClient, gophercloud.EndpointOpts{
Region: c.determineRegion(region),
Availability: c.getEndpointType(),
})
if err != nil {
return client, err
}
// Check if an endpoint override was specified for the volume service.
client = c.determineEndpoint(client, "volume")
return client, nil
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"blockStorageV1Client",
"(",
"region",
"string",
")",
"(",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"error",
")",
"{",
"client",
",",
"err",
":=",
"openstack",
".",
"NewBlockStorageV1",
"(",
"c",
".",
"OsClient",
",",
"gophercloud",
".",
"EndpointOpts",
"{",
"Region",
":",
"c",
".",
"determineRegion",
"(",
"region",
")",
",",
"Availability",
":",
"c",
".",
"getEndpointType",
"(",
")",
",",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"client",
",",
"err",
"\n",
"}",
"\n\n",
"// Check if an endpoint override was specified for the volume service.",
"client",
"=",
"c",
".",
"determineEndpoint",
"(",
"client",
",",
"\"",
"\"",
")",
"\n\n",
"return",
"client",
",",
"nil",
"\n",
"}"
] | // The following methods assist with the creation of individual Service Clients
// which interact with the various OpenStack services. | [
"The",
"following",
"methods",
"assist",
"with",
"the",
"creation",
"of",
"individual",
"Service",
"Clients",
"which",
"interact",
"with",
"the",
"various",
"OpenStack",
"services",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/config.go#L263-L277 |
terraform-providers/terraform-provider-openstack | openstack/networking_network_v2.go | networkingNetworkV2Name | func networkingNetworkV2Name(d *schema.ResourceData, meta interface{}, networkID string) (string, error) {
config := meta.(*Config)
networkingClient, err := config.networkingV2Client(GetRegion(d, config))
if err != nil {
return "", fmt.Errorf("Error creating OpenStack network client: %s", err)
}
opts := networks.ListOpts{ID: networkID}
pager := networks.List(networkingClient, opts)
networkName := ""
err = pager.EachPage(func(page pagination.Page) (bool, error) {
networkList, err := networks.ExtractNetworks(page)
if err != nil {
return false, err
}
for _, n := range networkList {
if n.ID == networkID {
networkName = n.Name
return false, nil
}
}
return true, nil
})
return networkName, err
} | go | func networkingNetworkV2Name(d *schema.ResourceData, meta interface{}, networkID string) (string, error) {
config := meta.(*Config)
networkingClient, err := config.networkingV2Client(GetRegion(d, config))
if err != nil {
return "", fmt.Errorf("Error creating OpenStack network client: %s", err)
}
opts := networks.ListOpts{ID: networkID}
pager := networks.List(networkingClient, opts)
networkName := ""
err = pager.EachPage(func(page pagination.Page) (bool, error) {
networkList, err := networks.ExtractNetworks(page)
if err != nil {
return false, err
}
for _, n := range networkList {
if n.ID == networkID {
networkName = n.Name
return false, nil
}
}
return true, nil
})
return networkName, err
} | [
"func",
"networkingNetworkV2Name",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"meta",
"interface",
"{",
"}",
",",
"networkID",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"config",
":=",
"meta",
".",
"(",
"*",
"Config",
")",
"\n",
"networkingClient",
",",
"err",
":=",
"config",
".",
"networkingV2Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"opts",
":=",
"networks",
".",
"ListOpts",
"{",
"ID",
":",
"networkID",
"}",
"\n",
"pager",
":=",
"networks",
".",
"List",
"(",
"networkingClient",
",",
"opts",
")",
"\n",
"networkName",
":=",
"\"",
"\"",
"\n\n",
"err",
"=",
"pager",
".",
"EachPage",
"(",
"func",
"(",
"page",
"pagination",
".",
"Page",
")",
"(",
"bool",
",",
"error",
")",
"{",
"networkList",
",",
"err",
":=",
"networks",
".",
"ExtractNetworks",
"(",
"page",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"n",
":=",
"range",
"networkList",
"{",
"if",
"n",
".",
"ID",
"==",
"networkID",
"{",
"networkName",
"=",
"n",
".",
"Name",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"true",
",",
"nil",
"\n",
"}",
")",
"\n\n",
"return",
"networkName",
",",
"err",
"\n",
"}"
] | // networkingNetworkV2Name retrieves network name by the provided ID. | [
"networkingNetworkV2Name",
"retrieves",
"network",
"name",
"by",
"the",
"provided",
"ID",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/networking_network_v2.go#L62-L90 |
terraform-providers/terraform-provider-openstack | openstack/networking_floatingip_v2.go | networkingFloatingIPV2ID | func networkingFloatingIPV2ID(client *gophercloud.ServiceClient, floatingIP string) (string, error) {
listOpts := floatingips.ListOpts{
FloatingIP: floatingIP,
}
allPages, err := floatingips.List(client, listOpts).AllPages()
if err != nil {
return "", err
}
allFloatingIPs, err := floatingips.ExtractFloatingIPs(allPages)
if err != nil {
return "", err
}
if len(allFloatingIPs) == 0 {
return "", fmt.Errorf("there are no openstack_networking_floatingip_v2 with %s IP", floatingIP)
}
if len(allFloatingIPs) > 1 {
return "", fmt.Errorf("there are more than one openstack_networking_floatingip_v2 with %s IP", floatingIP)
}
return allFloatingIPs[0].ID, nil
} | go | func networkingFloatingIPV2ID(client *gophercloud.ServiceClient, floatingIP string) (string, error) {
listOpts := floatingips.ListOpts{
FloatingIP: floatingIP,
}
allPages, err := floatingips.List(client, listOpts).AllPages()
if err != nil {
return "", err
}
allFloatingIPs, err := floatingips.ExtractFloatingIPs(allPages)
if err != nil {
return "", err
}
if len(allFloatingIPs) == 0 {
return "", fmt.Errorf("there are no openstack_networking_floatingip_v2 with %s IP", floatingIP)
}
if len(allFloatingIPs) > 1 {
return "", fmt.Errorf("there are more than one openstack_networking_floatingip_v2 with %s IP", floatingIP)
}
return allFloatingIPs[0].ID, nil
} | [
"func",
"networkingFloatingIPV2ID",
"(",
"client",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"floatingIP",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"listOpts",
":=",
"floatingips",
".",
"ListOpts",
"{",
"FloatingIP",
":",
"floatingIP",
",",
"}",
"\n\n",
"allPages",
",",
"err",
":=",
"floatingips",
".",
"List",
"(",
"client",
",",
"listOpts",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"allFloatingIPs",
",",
"err",
":=",
"floatingips",
".",
"ExtractFloatingIPs",
"(",
"allPages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allFloatingIPs",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"floatingIP",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"allFloatingIPs",
")",
">",
"1",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"floatingIP",
")",
"\n",
"}",
"\n\n",
"return",
"allFloatingIPs",
"[",
"0",
"]",
".",
"ID",
",",
"nil",
"\n",
"}"
] | // networkingFloatingIPV2ID retrieves floating IP ID by the provided IP address. | [
"networkingFloatingIPV2ID",
"retrieves",
"floating",
"IP",
"ID",
"by",
"the",
"provided",
"IP",
"address",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/networking_floatingip_v2.go#L18-L41 |
terraform-providers/terraform-provider-openstack | openstack/containerinfra_shared_v1.go | containerInfraClusterV1StateRefreshFunc | func containerInfraClusterV1StateRefreshFunc(client *gophercloud.ServiceClient, clusterID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
c, err := clusters.Get(client, clusterID).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
return c, "DELETE_COMPLETE", nil
}
return nil, "", err
}
errorStatuses := []string{
"CREATE_FAILED",
"UPDATE_FAILED",
"DELETE_FAILED",
"RESUME_FAILED",
"ROLLBACK_FAILED",
}
for _, errorStatus := range errorStatuses {
if c.Status == errorStatus {
err = fmt.Errorf("openstack_containerinfra_cluster_v1 is in an error state: %s", c.StatusReason)
return c, c.Status, err
}
}
return c, c.Status, nil
}
} | go | func containerInfraClusterV1StateRefreshFunc(client *gophercloud.ServiceClient, clusterID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
c, err := clusters.Get(client, clusterID).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
return c, "DELETE_COMPLETE", nil
}
return nil, "", err
}
errorStatuses := []string{
"CREATE_FAILED",
"UPDATE_FAILED",
"DELETE_FAILED",
"RESUME_FAILED",
"ROLLBACK_FAILED",
}
for _, errorStatus := range errorStatuses {
if c.Status == errorStatus {
err = fmt.Errorf("openstack_containerinfra_cluster_v1 is in an error state: %s", c.StatusReason)
return c, c.Status, err
}
}
return c, c.Status, nil
}
} | [
"func",
"containerInfraClusterV1StateRefreshFunc",
"(",
"client",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"clusterID",
"string",
")",
"resource",
".",
"StateRefreshFunc",
"{",
"return",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"string",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"clusters",
".",
"Get",
"(",
"client",
",",
"clusterID",
")",
".",
"Extract",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"gophercloud",
".",
"ErrDefault404",
")",
";",
"ok",
"{",
"return",
"c",
",",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"errorStatuses",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"}",
"\n",
"for",
"_",
",",
"errorStatus",
":=",
"range",
"errorStatuses",
"{",
"if",
"c",
".",
"Status",
"==",
"errorStatus",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
".",
"StatusReason",
")",
"\n",
"return",
"c",
",",
"c",
".",
"Status",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"c",
",",
"c",
".",
"Status",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // ContainerInfraClusterV1StateRefreshFunc returns a resource.StateRefreshFunc
// that is used to watch a container infra Cluster. | [
"ContainerInfraClusterV1StateRefreshFunc",
"returns",
"a",
"resource",
".",
"StateRefreshFunc",
"that",
"is",
"used",
"to",
"watch",
"a",
"container",
"infra",
"Cluster",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/containerinfra_shared_v1.go#L63-L89 |
terraform-providers/terraform-provider-openstack | openstack/containerinfra_shared_v1.go | containerInfraClusterV1Flavor | func containerInfraClusterV1Flavor(d *schema.ResourceData) (string, error) {
if flavor := d.Get("flavor").(string); flavor != "" {
return flavor, nil
}
// Try the OS_MAGNUM_FLAVOR environment variable
if v := os.Getenv("OS_MAGNUM_FLAVOR"); v != "" {
return v, nil
}
return "", nil
} | go | func containerInfraClusterV1Flavor(d *schema.ResourceData) (string, error) {
if flavor := d.Get("flavor").(string); flavor != "" {
return flavor, nil
}
// Try the OS_MAGNUM_FLAVOR environment variable
if v := os.Getenv("OS_MAGNUM_FLAVOR"); v != "" {
return v, nil
}
return "", nil
} | [
"func",
"containerInfraClusterV1Flavor",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"flavor",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
";",
"flavor",
"!=",
"\"",
"\"",
"{",
"return",
"flavor",
",",
"nil",
"\n",
"}",
"\n",
"// Try the OS_MAGNUM_FLAVOR environment variable",
"if",
"v",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
";",
"v",
"!=",
"\"",
"\"",
"{",
"return",
"v",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}"
] | // containerInfraClusterV1Flavor will determine the flavor for a container infra
// cluster based on either what was set in the configuration or environment
// variable. | [
"containerInfraClusterV1Flavor",
"will",
"determine",
"the",
"flavor",
"for",
"a",
"container",
"infra",
"cluster",
"based",
"on",
"either",
"what",
"was",
"set",
"in",
"the",
"configuration",
"or",
"environment",
"variable",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/containerinfra_shared_v1.go#L94-L104 |
terraform-providers/terraform-provider-openstack | openstack/fw_rule_v1.go | ToRuleCreateMap | func (opts RuleCreateOpts) ToRuleCreateMap() (map[string]interface{}, error) {
b, err := BuildRequest(opts, "firewall_rule")
if err != nil {
return nil, err
}
if m := b["firewall_rule"].(map[string]interface{}); m["protocol"] == "any" {
m["protocol"] = nil
}
return b, nil
} | go | func (opts RuleCreateOpts) ToRuleCreateMap() (map[string]interface{}, error) {
b, err := BuildRequest(opts, "firewall_rule")
if err != nil {
return nil, err
}
if m := b["firewall_rule"].(map[string]interface{}); m["protocol"] == "any" {
m["protocol"] = nil
}
return b, nil
} | [
"func",
"(",
"opts",
"RuleCreateOpts",
")",
"ToRuleCreateMap",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"BuildRequest",
"(",
"opts",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"m",
":=",
"b",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"m",
"[",
"\"",
"\"",
"]",
"==",
"\"",
"\"",
"{",
"m",
"[",
"\"",
"\"",
"]",
"=",
"nil",
"\n",
"}",
"\n\n",
"return",
"b",
",",
"nil",
"\n",
"}"
] | // ToRuleCreateMap casts a CreateOpts struct to a map.
// It overrides rules.ToRuleCreateMap to add the ValueSpecs field. | [
"ToRuleCreateMap",
"casts",
"a",
"CreateOpts",
"struct",
"to",
"a",
"map",
".",
"It",
"overrides",
"rules",
".",
"ToRuleCreateMap",
"to",
"add",
"the",
"ValueSpecs",
"field",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/fw_rule_v1.go#L16-L27 |
terraform-providers/terraform-provider-openstack | openstack/compute_instance_v2_networking.go | getAllInstanceNetworks | func getAllInstanceNetworks(d *schema.ResourceData, meta interface{}) ([]InstanceNetwork, error) {
var instanceNetworks []InstanceNetwork
networks := d.Get("network").([]interface{})
for _, v := range networks {
network := v.(map[string]interface{})
networkID := network["uuid"].(string)
networkName := network["name"].(string)
portID := network["port"].(string)
if networkID == "" && networkName == "" && portID == "" {
return nil, fmt.Errorf(
"At least one of network.uuid, network.name, or network.port must be set.")
}
// If a user specified both an ID and name, that makes things easy
// since both name and ID are already satisfied. No need to query
// further.
if networkID != "" && networkName != "" {
v := InstanceNetwork{
UUID: networkID,
Name: networkName,
Port: portID,
FixedIP: network["fixed_ip_v4"].(string),
AccessNetwork: network["access_network"].(bool),
}
instanceNetworks = append(instanceNetworks, v)
continue
}
// But if at least one of name or ID was missing, we have to query
// for that other piece.
//
// Priority is given to a port since a network ID or name usually isn't
// specified when using a port.
//
// Next priority is given to the network ID since it's guaranteed to be
// an exact match.
queryType := "name"
queryTerm := networkName
if networkID != "" {
queryType = "id"
queryTerm = networkID
}
if portID != "" {
queryType = "port"
queryTerm = portID
}
networkInfo, err := getInstanceNetworkInfo(d, meta, queryType, queryTerm)
if err != nil {
return nil, err
}
v := InstanceNetwork{
Port: portID,
FixedIP: network["fixed_ip_v4"].(string),
AccessNetwork: network["access_network"].(bool),
}
if networkInfo["uuid"] != nil {
v.UUID = networkInfo["uuid"].(string)
}
if networkInfo["name"] != nil {
v.Name = networkInfo["name"].(string)
}
instanceNetworks = append(instanceNetworks, v)
}
log.Printf("[DEBUG] getAllInstanceNetworks: %#v", instanceNetworks)
return instanceNetworks, nil
} | go | func getAllInstanceNetworks(d *schema.ResourceData, meta interface{}) ([]InstanceNetwork, error) {
var instanceNetworks []InstanceNetwork
networks := d.Get("network").([]interface{})
for _, v := range networks {
network := v.(map[string]interface{})
networkID := network["uuid"].(string)
networkName := network["name"].(string)
portID := network["port"].(string)
if networkID == "" && networkName == "" && portID == "" {
return nil, fmt.Errorf(
"At least one of network.uuid, network.name, or network.port must be set.")
}
// If a user specified both an ID and name, that makes things easy
// since both name and ID are already satisfied. No need to query
// further.
if networkID != "" && networkName != "" {
v := InstanceNetwork{
UUID: networkID,
Name: networkName,
Port: portID,
FixedIP: network["fixed_ip_v4"].(string),
AccessNetwork: network["access_network"].(bool),
}
instanceNetworks = append(instanceNetworks, v)
continue
}
// But if at least one of name or ID was missing, we have to query
// for that other piece.
//
// Priority is given to a port since a network ID or name usually isn't
// specified when using a port.
//
// Next priority is given to the network ID since it's guaranteed to be
// an exact match.
queryType := "name"
queryTerm := networkName
if networkID != "" {
queryType = "id"
queryTerm = networkID
}
if portID != "" {
queryType = "port"
queryTerm = portID
}
networkInfo, err := getInstanceNetworkInfo(d, meta, queryType, queryTerm)
if err != nil {
return nil, err
}
v := InstanceNetwork{
Port: portID,
FixedIP: network["fixed_ip_v4"].(string),
AccessNetwork: network["access_network"].(bool),
}
if networkInfo["uuid"] != nil {
v.UUID = networkInfo["uuid"].(string)
}
if networkInfo["name"] != nil {
v.Name = networkInfo["name"].(string)
}
instanceNetworks = append(instanceNetworks, v)
}
log.Printf("[DEBUG] getAllInstanceNetworks: %#v", instanceNetworks)
return instanceNetworks, nil
} | [
"func",
"getAllInstanceNetworks",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"meta",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"InstanceNetwork",
",",
"error",
")",
"{",
"var",
"instanceNetworks",
"[",
"]",
"InstanceNetwork",
"\n\n",
"networks",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"networks",
"{",
"network",
":=",
"v",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"networkID",
":=",
"network",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"networkName",
":=",
"network",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"portID",
":=",
"network",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n\n",
"if",
"networkID",
"==",
"\"",
"\"",
"&&",
"networkName",
"==",
"\"",
"\"",
"&&",
"portID",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// If a user specified both an ID and name, that makes things easy",
"// since both name and ID are already satisfied. No need to query",
"// further.",
"if",
"networkID",
"!=",
"\"",
"\"",
"&&",
"networkName",
"!=",
"\"",
"\"",
"{",
"v",
":=",
"InstanceNetwork",
"{",
"UUID",
":",
"networkID",
",",
"Name",
":",
"networkName",
",",
"Port",
":",
"portID",
",",
"FixedIP",
":",
"network",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
",",
"AccessNetwork",
":",
"network",
"[",
"\"",
"\"",
"]",
".",
"(",
"bool",
")",
",",
"}",
"\n",
"instanceNetworks",
"=",
"append",
"(",
"instanceNetworks",
",",
"v",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// But if at least one of name or ID was missing, we have to query",
"// for that other piece.",
"//",
"// Priority is given to a port since a network ID or name usually isn't",
"// specified when using a port.",
"//",
"// Next priority is given to the network ID since it's guaranteed to be",
"// an exact match.",
"queryType",
":=",
"\"",
"\"",
"\n",
"queryTerm",
":=",
"networkName",
"\n",
"if",
"networkID",
"!=",
"\"",
"\"",
"{",
"queryType",
"=",
"\"",
"\"",
"\n",
"queryTerm",
"=",
"networkID",
"\n",
"}",
"\n",
"if",
"portID",
"!=",
"\"",
"\"",
"{",
"queryType",
"=",
"\"",
"\"",
"\n",
"queryTerm",
"=",
"portID",
"\n",
"}",
"\n\n",
"networkInfo",
",",
"err",
":=",
"getInstanceNetworkInfo",
"(",
"d",
",",
"meta",
",",
"queryType",
",",
"queryTerm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"v",
":=",
"InstanceNetwork",
"{",
"Port",
":",
"portID",
",",
"FixedIP",
":",
"network",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
",",
"AccessNetwork",
":",
"network",
"[",
"\"",
"\"",
"]",
".",
"(",
"bool",
")",
",",
"}",
"\n",
"if",
"networkInfo",
"[",
"\"",
"\"",
"]",
"!=",
"nil",
"{",
"v",
".",
"UUID",
"=",
"networkInfo",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"if",
"networkInfo",
"[",
"\"",
"\"",
"]",
"!=",
"nil",
"{",
"v",
".",
"Name",
"=",
"networkInfo",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"}",
"\n\n",
"instanceNetworks",
"=",
"append",
"(",
"instanceNetworks",
",",
"v",
")",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"instanceNetworks",
")",
"\n",
"return",
"instanceNetworks",
",",
"nil",
"\n",
"}"
] | // getAllInstanceNetworks loops through the networks defined in the Terraform
// configuration and structures that information into something standard that
// can be consumed by both OpenStack and Terraform.
//
// This would be simple, except we have ensure both the network name and
// network ID have been determined. This isn't just for the convenience of a
// user specifying a human-readable network name, but the network information
// returned by an OpenStack instance only has the network name set! So if a
// user specified a network ID, there's no way to correlate it to the instance
// unless we know both the name and ID.
//
// Not only that, but we have to account for two OpenStack network services
// running: nova-network (legacy) and Neutron (current).
//
// In addition, if a port was specified, not all of the port information
// will be displayed, such as multiple fixed and floating IPs. This resource
// isn't currently configured for that type of flexibility. It's better to
// reference the actual port resource itself.
//
// So, let's begin the journey. | [
"getAllInstanceNetworks",
"loops",
"through",
"the",
"networks",
"defined",
"in",
"the",
"Terraform",
"configuration",
"and",
"structures",
"that",
"information",
"into",
"something",
"standard",
"that",
"can",
"be",
"consumed",
"by",
"both",
"OpenStack",
"and",
"Terraform",
".",
"This",
"would",
"be",
"simple",
"except",
"we",
"have",
"ensure",
"both",
"the",
"network",
"name",
"and",
"network",
"ID",
"have",
"been",
"determined",
".",
"This",
"isn",
"t",
"just",
"for",
"the",
"convenience",
"of",
"a",
"user",
"specifying",
"a",
"human",
"-",
"readable",
"network",
"name",
"but",
"the",
"network",
"information",
"returned",
"by",
"an",
"OpenStack",
"instance",
"only",
"has",
"the",
"network",
"name",
"set!",
"So",
"if",
"a",
"user",
"specified",
"a",
"network",
"ID",
"there",
"s",
"no",
"way",
"to",
"correlate",
"it",
"to",
"the",
"instance",
"unless",
"we",
"know",
"both",
"the",
"name",
"and",
"ID",
".",
"Not",
"only",
"that",
"but",
"we",
"have",
"to",
"account",
"for",
"two",
"OpenStack",
"network",
"services",
"running",
":",
"nova",
"-",
"network",
"(",
"legacy",
")",
"and",
"Neutron",
"(",
"current",
")",
".",
"In",
"addition",
"if",
"a",
"port",
"was",
"specified",
"not",
"all",
"of",
"the",
"port",
"information",
"will",
"be",
"displayed",
"such",
"as",
"multiple",
"fixed",
"and",
"floating",
"IPs",
".",
"This",
"resource",
"isn",
"t",
"currently",
"configured",
"for",
"that",
"type",
"of",
"flexibility",
".",
"It",
"s",
"better",
"to",
"reference",
"the",
"actual",
"port",
"resource",
"itself",
".",
"So",
"let",
"s",
"begin",
"the",
"journey",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L71-L142 |
terraform-providers/terraform-provider-openstack | openstack/compute_instance_v2_networking.go | getInstanceNetworkInfo | func getInstanceNetworkInfo(
d *schema.ResourceData, meta interface{}, queryType, queryTerm string) (map[string]interface{}, error) {
config := meta.(*Config)
if _, ok := os.LookupEnv("OS_NOVA_NETWORK"); !ok {
networkClient, err := config.networkingV2Client(GetRegion(d, config))
if err == nil {
networkInfo, err := getInstanceNetworkInfoNeutron(networkClient, queryType, queryTerm)
if err != nil {
return nil, fmt.Errorf("Error trying to get network information from the Network API: %s", err)
}
return networkInfo, nil
}
}
log.Printf("[DEBUG] Unable to obtain a network client")
computeClient, err := config.computeV2Client(GetRegion(d, config))
if err != nil {
return nil, fmt.Errorf("Error creating OpenStack compute client: %s", err)
}
networkInfo, err := getInstanceNetworkInfoNovaNet(computeClient, queryType, queryTerm)
if err != nil {
return nil, fmt.Errorf("Error trying to get network information from the Nova API: %s", err)
}
return networkInfo, nil
} | go | func getInstanceNetworkInfo(
d *schema.ResourceData, meta interface{}, queryType, queryTerm string) (map[string]interface{}, error) {
config := meta.(*Config)
if _, ok := os.LookupEnv("OS_NOVA_NETWORK"); !ok {
networkClient, err := config.networkingV2Client(GetRegion(d, config))
if err == nil {
networkInfo, err := getInstanceNetworkInfoNeutron(networkClient, queryType, queryTerm)
if err != nil {
return nil, fmt.Errorf("Error trying to get network information from the Network API: %s", err)
}
return networkInfo, nil
}
}
log.Printf("[DEBUG] Unable to obtain a network client")
computeClient, err := config.computeV2Client(GetRegion(d, config))
if err != nil {
return nil, fmt.Errorf("Error creating OpenStack compute client: %s", err)
}
networkInfo, err := getInstanceNetworkInfoNovaNet(computeClient, queryType, queryTerm)
if err != nil {
return nil, fmt.Errorf("Error trying to get network information from the Nova API: %s", err)
}
return networkInfo, nil
} | [
"func",
"getInstanceNetworkInfo",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"meta",
"interface",
"{",
"}",
",",
"queryType",
",",
"queryTerm",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"config",
":=",
"meta",
".",
"(",
"*",
"Config",
")",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"os",
".",
"LookupEnv",
"(",
"\"",
"\"",
")",
";",
"!",
"ok",
"{",
"networkClient",
",",
"err",
":=",
"config",
".",
"networkingV2Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"networkInfo",
",",
"err",
":=",
"getInstanceNetworkInfoNeutron",
"(",
"networkClient",
",",
"queryType",
",",
"queryTerm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"networkInfo",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n\n",
"computeClient",
",",
"err",
":=",
"config",
".",
"computeV2Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"networkInfo",
",",
"err",
":=",
"getInstanceNetworkInfoNovaNet",
"(",
"computeClient",
",",
"queryType",
",",
"queryTerm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"networkInfo",
",",
"nil",
"\n",
"}"
] | // getInstanceNetworkInfo will query for network information in order to make
// an accurate determination of a network's name and a network's ID.
//
// We will try to first query the Neutron network service and fall back to the
// legacy nova-network service if that fails.
//
// If OS_NOVA_NETWORK is set, query nova-network even if Neutron is available.
// This is to be able to explicitly test the nova-network API. | [
"getInstanceNetworkInfo",
"will",
"query",
"for",
"network",
"information",
"in",
"order",
"to",
"make",
"an",
"accurate",
"determination",
"of",
"a",
"network",
"s",
"name",
"and",
"a",
"network",
"s",
"ID",
".",
"We",
"will",
"try",
"to",
"first",
"query",
"the",
"Neutron",
"network",
"service",
"and",
"fall",
"back",
"to",
"the",
"legacy",
"nova",
"-",
"network",
"service",
"if",
"that",
"fails",
".",
"If",
"OS_NOVA_NETWORK",
"is",
"set",
"query",
"nova",
"-",
"network",
"even",
"if",
"Neutron",
"is",
"available",
".",
"This",
"is",
"to",
"be",
"able",
"to",
"explicitly",
"test",
"the",
"nova",
"-",
"network",
"API",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L152-L182 |
terraform-providers/terraform-provider-openstack | openstack/compute_instance_v2_networking.go | getInstanceNetworkInfoNovaNet | func getInstanceNetworkInfoNovaNet(
client *gophercloud.ServiceClient, queryType, queryTerm string) (map[string]interface{}, error) {
// If somehow a port ended up here, we should just error out.
if queryType == "port" {
return nil, fmt.Errorf(
"Unable to query a port (%s) using the Nova API", queryTerm)
}
// test to see if the tenantnetworks api is available
log.Printf("[DEBUG] testing for os-tenant-networks")
tenantNetworksAvailable := true
allPages, err := tenantnetworks.List(client).AllPages()
if err != nil {
switch err.(type) {
case gophercloud.ErrDefault404:
tenantNetworksAvailable = false
case gophercloud.ErrDefault403:
tenantNetworksAvailable = false
case gophercloud.ErrUnexpectedResponseCode:
tenantNetworksAvailable = false
default:
return nil, fmt.Errorf(
"An error occurred while querying the Nova API for network information: %s", err)
}
}
if !tenantNetworksAvailable {
// we can't query the APIs for more information, but in some cases
// the information provided is enough
log.Printf("[DEBUG] os-tenant-networks disabled.")
return map[string]interface{}{queryType: queryTerm}, nil
}
networkList, err := tenantnetworks.ExtractNetworks(allPages)
if err != nil {
return nil, fmt.Errorf(
"An error occurred while querying the Nova API for network information: %s", err)
}
var networkFound bool
var network tenantnetworks.Network
for _, v := range networkList {
if queryType == "id" && v.ID == queryTerm {
networkFound = true
network = v
break
}
if queryType == "name" && v.Name == queryTerm {
networkFound = true
network = v
break
}
}
if networkFound {
v := map[string]interface{}{
"uuid": network.ID,
"name": network.Name,
}
log.Printf("[DEBUG] getInstanceNetworkInfoNovaNet: %#v", v)
return v, nil
}
return nil, fmt.Errorf("Could not find any matching network for %s %s", queryType, queryTerm)
} | go | func getInstanceNetworkInfoNovaNet(
client *gophercloud.ServiceClient, queryType, queryTerm string) (map[string]interface{}, error) {
// If somehow a port ended up here, we should just error out.
if queryType == "port" {
return nil, fmt.Errorf(
"Unable to query a port (%s) using the Nova API", queryTerm)
}
// test to see if the tenantnetworks api is available
log.Printf("[DEBUG] testing for os-tenant-networks")
tenantNetworksAvailable := true
allPages, err := tenantnetworks.List(client).AllPages()
if err != nil {
switch err.(type) {
case gophercloud.ErrDefault404:
tenantNetworksAvailable = false
case gophercloud.ErrDefault403:
tenantNetworksAvailable = false
case gophercloud.ErrUnexpectedResponseCode:
tenantNetworksAvailable = false
default:
return nil, fmt.Errorf(
"An error occurred while querying the Nova API for network information: %s", err)
}
}
if !tenantNetworksAvailable {
// we can't query the APIs for more information, but in some cases
// the information provided is enough
log.Printf("[DEBUG] os-tenant-networks disabled.")
return map[string]interface{}{queryType: queryTerm}, nil
}
networkList, err := tenantnetworks.ExtractNetworks(allPages)
if err != nil {
return nil, fmt.Errorf(
"An error occurred while querying the Nova API for network information: %s", err)
}
var networkFound bool
var network tenantnetworks.Network
for _, v := range networkList {
if queryType == "id" && v.ID == queryTerm {
networkFound = true
network = v
break
}
if queryType == "name" && v.Name == queryTerm {
networkFound = true
network = v
break
}
}
if networkFound {
v := map[string]interface{}{
"uuid": network.ID,
"name": network.Name,
}
log.Printf("[DEBUG] getInstanceNetworkInfoNovaNet: %#v", v)
return v, nil
}
return nil, fmt.Errorf("Could not find any matching network for %s %s", queryType, queryTerm)
} | [
"func",
"getInstanceNetworkInfoNovaNet",
"(",
"client",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"queryType",
",",
"queryTerm",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"// If somehow a port ended up here, we should just error out.",
"if",
"queryType",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"queryTerm",
")",
"\n",
"}",
"\n\n",
"// test to see if the tenantnetworks api is available",
"log",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"tenantNetworksAvailable",
":=",
"true",
"\n\n",
"allPages",
",",
"err",
":=",
"tenantnetworks",
".",
"List",
"(",
"client",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"switch",
"err",
".",
"(",
"type",
")",
"{",
"case",
"gophercloud",
".",
"ErrDefault404",
":",
"tenantNetworksAvailable",
"=",
"false",
"\n",
"case",
"gophercloud",
".",
"ErrDefault403",
":",
"tenantNetworksAvailable",
"=",
"false",
"\n",
"case",
"gophercloud",
".",
"ErrUnexpectedResponseCode",
":",
"tenantNetworksAvailable",
"=",
"false",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"tenantNetworksAvailable",
"{",
"// we can't query the APIs for more information, but in some cases",
"// the information provided is enough",
"log",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"queryType",
":",
"queryTerm",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"networkList",
",",
"err",
":=",
"tenantnetworks",
".",
"ExtractNetworks",
"(",
"allPages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"networkFound",
"bool",
"\n",
"var",
"network",
"tenantnetworks",
".",
"Network",
"\n\n",
"for",
"_",
",",
"v",
":=",
"range",
"networkList",
"{",
"if",
"queryType",
"==",
"\"",
"\"",
"&&",
"v",
".",
"ID",
"==",
"queryTerm",
"{",
"networkFound",
"=",
"true",
"\n",
"network",
"=",
"v",
"\n",
"break",
"\n",
"}",
"\n\n",
"if",
"queryType",
"==",
"\"",
"\"",
"&&",
"v",
".",
"Name",
"==",
"queryTerm",
"{",
"networkFound",
"=",
"true",
"\n",
"network",
"=",
"v",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"networkFound",
"{",
"v",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"network",
".",
"ID",
",",
"\"",
"\"",
":",
"network",
".",
"Name",
",",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"v",
")",
"\n",
"return",
"v",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"queryType",
",",
"queryTerm",
")",
"\n",
"}"
] | // getInstanceNetworkInfoNovaNet will query the os-tenant-networks API for
// the network information. | [
"getInstanceNetworkInfoNovaNet",
"will",
"query",
"the",
"os",
"-",
"tenant",
"-",
"networks",
"API",
"for",
"the",
"network",
"information",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L186-L255 |
terraform-providers/terraform-provider-openstack | openstack/compute_instance_v2_networking.go | getInstanceNetworkInfoNeutron | func getInstanceNetworkInfoNeutron(
client *gophercloud.ServiceClient, queryType, queryTerm string) (map[string]interface{}, error) {
// If a port was specified, use it to look up the network ID
// and then query the network as if a network ID was originally used.
if queryType == "port" {
listOpts := ports.ListOpts{
ID: queryTerm,
}
allPages, err := ports.List(client, listOpts).AllPages()
if err != nil {
return nil, fmt.Errorf("Unable to retrieve networks from the Network API: %s", err)
}
allPorts, err := ports.ExtractPorts(allPages)
if err != nil {
return nil, fmt.Errorf("Unable to retrieve networks from the Network API: %s", err)
}
var port ports.Port
switch len(allPorts) {
case 0:
return nil, fmt.Errorf("Could not find any matching port for %s %s", queryType, queryTerm)
case 1:
port = allPorts[0]
default:
return nil, fmt.Errorf("More than one port found for %s %s", queryType, queryTerm)
}
queryType = "id"
queryTerm = port.NetworkID
}
listOpts := networks.ListOpts{
Status: "ACTIVE",
}
switch queryType {
case "name":
listOpts.Name = queryTerm
default:
listOpts.ID = queryTerm
}
allPages, err := networks.List(client, listOpts).AllPages()
if err != nil {
return nil, fmt.Errorf("Unable to retrieve networks from the Network API: %s", err)
}
allNetworks, err := networks.ExtractNetworks(allPages)
if err != nil {
return nil, fmt.Errorf("Unable to retrieve networks from the Network API: %s", err)
}
var network networks.Network
switch len(allNetworks) {
case 0:
return nil, fmt.Errorf("Could not find any matching network for %s %s", queryType, queryTerm)
case 1:
network = allNetworks[0]
default:
return nil, fmt.Errorf("More than one network found for %s %s", queryType, queryTerm)
}
v := map[string]interface{}{
"uuid": network.ID,
"name": network.Name,
}
log.Printf("[DEBUG] getInstanceNetworkInfoNeutron: %#v", v)
return v, nil
} | go | func getInstanceNetworkInfoNeutron(
client *gophercloud.ServiceClient, queryType, queryTerm string) (map[string]interface{}, error) {
// If a port was specified, use it to look up the network ID
// and then query the network as if a network ID was originally used.
if queryType == "port" {
listOpts := ports.ListOpts{
ID: queryTerm,
}
allPages, err := ports.List(client, listOpts).AllPages()
if err != nil {
return nil, fmt.Errorf("Unable to retrieve networks from the Network API: %s", err)
}
allPorts, err := ports.ExtractPorts(allPages)
if err != nil {
return nil, fmt.Errorf("Unable to retrieve networks from the Network API: %s", err)
}
var port ports.Port
switch len(allPorts) {
case 0:
return nil, fmt.Errorf("Could not find any matching port for %s %s", queryType, queryTerm)
case 1:
port = allPorts[0]
default:
return nil, fmt.Errorf("More than one port found for %s %s", queryType, queryTerm)
}
queryType = "id"
queryTerm = port.NetworkID
}
listOpts := networks.ListOpts{
Status: "ACTIVE",
}
switch queryType {
case "name":
listOpts.Name = queryTerm
default:
listOpts.ID = queryTerm
}
allPages, err := networks.List(client, listOpts).AllPages()
if err != nil {
return nil, fmt.Errorf("Unable to retrieve networks from the Network API: %s", err)
}
allNetworks, err := networks.ExtractNetworks(allPages)
if err != nil {
return nil, fmt.Errorf("Unable to retrieve networks from the Network API: %s", err)
}
var network networks.Network
switch len(allNetworks) {
case 0:
return nil, fmt.Errorf("Could not find any matching network for %s %s", queryType, queryTerm)
case 1:
network = allNetworks[0]
default:
return nil, fmt.Errorf("More than one network found for %s %s", queryType, queryTerm)
}
v := map[string]interface{}{
"uuid": network.ID,
"name": network.Name,
}
log.Printf("[DEBUG] getInstanceNetworkInfoNeutron: %#v", v)
return v, nil
} | [
"func",
"getInstanceNetworkInfoNeutron",
"(",
"client",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"queryType",
",",
"queryTerm",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"// If a port was specified, use it to look up the network ID",
"// and then query the network as if a network ID was originally used.",
"if",
"queryType",
"==",
"\"",
"\"",
"{",
"listOpts",
":=",
"ports",
".",
"ListOpts",
"{",
"ID",
":",
"queryTerm",
",",
"}",
"\n",
"allPages",
",",
"err",
":=",
"ports",
".",
"List",
"(",
"client",
",",
"listOpts",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"allPorts",
",",
"err",
":=",
"ports",
".",
"ExtractPorts",
"(",
"allPages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"port",
"ports",
".",
"Port",
"\n",
"switch",
"len",
"(",
"allPorts",
")",
"{",
"case",
"0",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"queryType",
",",
"queryTerm",
")",
"\n",
"case",
"1",
":",
"port",
"=",
"allPorts",
"[",
"0",
"]",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"queryType",
",",
"queryTerm",
")",
"\n",
"}",
"\n\n",
"queryType",
"=",
"\"",
"\"",
"\n",
"queryTerm",
"=",
"port",
".",
"NetworkID",
"\n",
"}",
"\n\n",
"listOpts",
":=",
"networks",
".",
"ListOpts",
"{",
"Status",
":",
"\"",
"\"",
",",
"}",
"\n\n",
"switch",
"queryType",
"{",
"case",
"\"",
"\"",
":",
"listOpts",
".",
"Name",
"=",
"queryTerm",
"\n",
"default",
":",
"listOpts",
".",
"ID",
"=",
"queryTerm",
"\n",
"}",
"\n\n",
"allPages",
",",
"err",
":=",
"networks",
".",
"List",
"(",
"client",
",",
"listOpts",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"allNetworks",
",",
"err",
":=",
"networks",
".",
"ExtractNetworks",
"(",
"allPages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"network",
"networks",
".",
"Network",
"\n",
"switch",
"len",
"(",
"allNetworks",
")",
"{",
"case",
"0",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"queryType",
",",
"queryTerm",
")",
"\n",
"case",
"1",
":",
"network",
"=",
"allNetworks",
"[",
"0",
"]",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"queryType",
",",
"queryTerm",
")",
"\n",
"}",
"\n\n",
"v",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"network",
".",
"ID",
",",
"\"",
"\"",
":",
"network",
".",
"Name",
",",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"v",
")",
"\n",
"return",
"v",
",",
"nil",
"\n",
"}"
] | // getInstanceNetworkInfoNeutron will query the neutron API for the network
// information. | [
"getInstanceNetworkInfoNeutron",
"will",
"query",
"the",
"neutron",
"API",
"for",
"the",
"network",
"information",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L259-L330 |
terraform-providers/terraform-provider-openstack | openstack/compute_instance_v2_networking.go | getInstanceAddresses | func getInstanceAddresses(addresses map[string]interface{}) []InstanceAddresses {
var allInstanceAddresses []InstanceAddresses
for networkName, v := range addresses {
instanceAddresses := InstanceAddresses{
NetworkName: networkName,
}
for _, v := range v.([]interface{}) {
instanceNIC := InstanceNIC{}
var exists bool
v := v.(map[string]interface{})
if v, ok := v["OS-EXT-IPS-MAC:mac_addr"].(string); ok {
instanceNIC.MAC = v
}
if v["OS-EXT-IPS:type"] == "fixed" || v["OS-EXT-IPS:type"] == nil {
switch v["version"].(float64) {
case 6:
instanceNIC.FixedIPv6 = fmt.Sprintf("[%s]", v["addr"].(string))
default:
instanceNIC.FixedIPv4 = v["addr"].(string)
}
}
// To associate IPv4 and IPv6 on the right NIC,
// key on the mac address and fill in the blanks.
for i, v := range instanceAddresses.InstanceNICs {
if v.MAC == instanceNIC.MAC {
exists = true
if instanceNIC.FixedIPv6 != "" {
instanceAddresses.InstanceNICs[i].FixedIPv6 = instanceNIC.FixedIPv6
}
if instanceNIC.FixedIPv4 != "" {
instanceAddresses.InstanceNICs[i].FixedIPv4 = instanceNIC.FixedIPv4
}
}
}
if !exists {
instanceAddresses.InstanceNICs = append(instanceAddresses.InstanceNICs, instanceNIC)
}
}
allInstanceAddresses = append(allInstanceAddresses, instanceAddresses)
}
log.Printf("[DEBUG] Addresses: %#v", addresses)
log.Printf("[DEBUG] allInstanceAddresses: %#v", allInstanceAddresses)
return allInstanceAddresses
} | go | func getInstanceAddresses(addresses map[string]interface{}) []InstanceAddresses {
var allInstanceAddresses []InstanceAddresses
for networkName, v := range addresses {
instanceAddresses := InstanceAddresses{
NetworkName: networkName,
}
for _, v := range v.([]interface{}) {
instanceNIC := InstanceNIC{}
var exists bool
v := v.(map[string]interface{})
if v, ok := v["OS-EXT-IPS-MAC:mac_addr"].(string); ok {
instanceNIC.MAC = v
}
if v["OS-EXT-IPS:type"] == "fixed" || v["OS-EXT-IPS:type"] == nil {
switch v["version"].(float64) {
case 6:
instanceNIC.FixedIPv6 = fmt.Sprintf("[%s]", v["addr"].(string))
default:
instanceNIC.FixedIPv4 = v["addr"].(string)
}
}
// To associate IPv4 and IPv6 on the right NIC,
// key on the mac address and fill in the blanks.
for i, v := range instanceAddresses.InstanceNICs {
if v.MAC == instanceNIC.MAC {
exists = true
if instanceNIC.FixedIPv6 != "" {
instanceAddresses.InstanceNICs[i].FixedIPv6 = instanceNIC.FixedIPv6
}
if instanceNIC.FixedIPv4 != "" {
instanceAddresses.InstanceNICs[i].FixedIPv4 = instanceNIC.FixedIPv4
}
}
}
if !exists {
instanceAddresses.InstanceNICs = append(instanceAddresses.InstanceNICs, instanceNIC)
}
}
allInstanceAddresses = append(allInstanceAddresses, instanceAddresses)
}
log.Printf("[DEBUG] Addresses: %#v", addresses)
log.Printf("[DEBUG] allInstanceAddresses: %#v", allInstanceAddresses)
return allInstanceAddresses
} | [
"func",
"getInstanceAddresses",
"(",
"addresses",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"[",
"]",
"InstanceAddresses",
"{",
"var",
"allInstanceAddresses",
"[",
"]",
"InstanceAddresses",
"\n\n",
"for",
"networkName",
",",
"v",
":=",
"range",
"addresses",
"{",
"instanceAddresses",
":=",
"InstanceAddresses",
"{",
"NetworkName",
":",
"networkName",
",",
"}",
"\n\n",
"for",
"_",
",",
"v",
":=",
"range",
"v",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
"{",
"instanceNIC",
":=",
"InstanceNIC",
"{",
"}",
"\n",
"var",
"exists",
"bool",
"\n\n",
"v",
":=",
"v",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"v",
",",
"ok",
":=",
"v",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
";",
"ok",
"{",
"instanceNIC",
".",
"MAC",
"=",
"v",
"\n",
"}",
"\n\n",
"if",
"v",
"[",
"\"",
"\"",
"]",
"==",
"\"",
"\"",
"||",
"v",
"[",
"\"",
"\"",
"]",
"==",
"nil",
"{",
"switch",
"v",
"[",
"\"",
"\"",
"]",
".",
"(",
"float64",
")",
"{",
"case",
"6",
":",
"instanceNIC",
".",
"FixedIPv6",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
")",
"\n",
"default",
":",
"instanceNIC",
".",
"FixedIPv4",
"=",
"v",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// To associate IPv4 and IPv6 on the right NIC,",
"// key on the mac address and fill in the blanks.",
"for",
"i",
",",
"v",
":=",
"range",
"instanceAddresses",
".",
"InstanceNICs",
"{",
"if",
"v",
".",
"MAC",
"==",
"instanceNIC",
".",
"MAC",
"{",
"exists",
"=",
"true",
"\n",
"if",
"instanceNIC",
".",
"FixedIPv6",
"!=",
"\"",
"\"",
"{",
"instanceAddresses",
".",
"InstanceNICs",
"[",
"i",
"]",
".",
"FixedIPv6",
"=",
"instanceNIC",
".",
"FixedIPv6",
"\n",
"}",
"\n",
"if",
"instanceNIC",
".",
"FixedIPv4",
"!=",
"\"",
"\"",
"{",
"instanceAddresses",
".",
"InstanceNICs",
"[",
"i",
"]",
".",
"FixedIPv4",
"=",
"instanceNIC",
".",
"FixedIPv4",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"exists",
"{",
"instanceAddresses",
".",
"InstanceNICs",
"=",
"append",
"(",
"instanceAddresses",
".",
"InstanceNICs",
",",
"instanceNIC",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"allInstanceAddresses",
"=",
"append",
"(",
"allInstanceAddresses",
",",
"instanceAddresses",
")",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"addresses",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"allInstanceAddresses",
")",
"\n\n",
"return",
"allInstanceAddresses",
"\n",
"}"
] | // getInstanceAddresses parses a Gophercloud server.Server's Address field into
// a structured InstanceAddresses struct. | [
"getInstanceAddresses",
"parses",
"a",
"Gophercloud",
"server",
".",
"Server",
"s",
"Address",
"field",
"into",
"a",
"structured",
"InstanceAddresses",
"struct",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L334-L386 |
terraform-providers/terraform-provider-openstack | openstack/compute_instance_v2_networking.go | expandInstanceNetworks | func expandInstanceNetworks(allInstanceNetworks []InstanceNetwork) []servers.Network {
var networks []servers.Network
for _, v := range allInstanceNetworks {
n := servers.Network{
UUID: v.UUID,
Port: v.Port,
FixedIP: v.FixedIP,
}
networks = append(networks, n)
}
return networks
} | go | func expandInstanceNetworks(allInstanceNetworks []InstanceNetwork) []servers.Network {
var networks []servers.Network
for _, v := range allInstanceNetworks {
n := servers.Network{
UUID: v.UUID,
Port: v.Port,
FixedIP: v.FixedIP,
}
networks = append(networks, n)
}
return networks
} | [
"func",
"expandInstanceNetworks",
"(",
"allInstanceNetworks",
"[",
"]",
"InstanceNetwork",
")",
"[",
"]",
"servers",
".",
"Network",
"{",
"var",
"networks",
"[",
"]",
"servers",
".",
"Network",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"allInstanceNetworks",
"{",
"n",
":=",
"servers",
".",
"Network",
"{",
"UUID",
":",
"v",
".",
"UUID",
",",
"Port",
":",
"v",
".",
"Port",
",",
"FixedIP",
":",
"v",
".",
"FixedIP",
",",
"}",
"\n",
"networks",
"=",
"append",
"(",
"networks",
",",
"n",
")",
"\n",
"}",
"\n\n",
"return",
"networks",
"\n",
"}"
] | // expandInstanceNetworks takes network information found in []InstanceNetwork
// and builds a Gophercloud []servers.Network for use in creating an Instance. | [
"expandInstanceNetworks",
"takes",
"network",
"information",
"found",
"in",
"[]",
"InstanceNetwork",
"and",
"builds",
"a",
"Gophercloud",
"[]",
"servers",
".",
"Network",
"for",
"use",
"in",
"creating",
"an",
"Instance",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L390-L402 |
terraform-providers/terraform-provider-openstack | openstack/compute_instance_v2_networking.go | flattenInstanceNetworks | func flattenInstanceNetworks(
d *schema.ResourceData, meta interface{}) ([]map[string]interface{}, error) {
config := meta.(*Config)
computeClient, err := config.computeV2Client(GetRegion(d, config))
if err != nil {
return nil, fmt.Errorf("Error creating OpenStack compute client: %s", err)
}
server, err := servers.Get(computeClient, d.Id()).Extract()
if err != nil {
return nil, CheckDeleted(d, err, "server")
}
allInstanceAddresses := getInstanceAddresses(server.Addresses)
allInstanceNetworks, err := getAllInstanceNetworks(d, meta)
if err != nil {
return nil, err
}
networks := []map[string]interface{}{}
// If there were no instance networks returned, this means that there
// was not a network specified in the Terraform configuration. When this
// happens, the instance will be launched on a "default" network, if one
// is available. If there isn't, the instance will fail to launch, so
// this is a safe assumption at this point.
if len(allInstanceNetworks) == 0 {
for _, instanceAddresses := range allInstanceAddresses {
for _, instanceNIC := range instanceAddresses.InstanceNICs {
v := map[string]interface{}{
"name": instanceAddresses.NetworkName,
"fixed_ip_v4": instanceNIC.FixedIPv4,
"fixed_ip_v6": instanceNIC.FixedIPv6,
"mac": instanceNIC.MAC,
}
// Use the same method as getAllInstanceNetworks to get the network uuid
networkInfo, err := getInstanceNetworkInfo(d, meta, "name", instanceAddresses.NetworkName)
if err != nil {
log.Printf("[WARN] Error getting default network uuid: %s", err)
} else {
if v["uuid"] != nil {
v["uuid"] = networkInfo["uuid"].(string)
} else {
log.Printf("[WARN] Could not get default network uuid")
}
}
networks = append(networks, v)
}
}
log.Printf("[DEBUG] flattenInstanceNetworks: %#v", networks)
return networks, nil
}
// Loop through all networks and addresses, merge relevant address details.
for _, instanceNetwork := range allInstanceNetworks {
for _, instanceAddresses := range allInstanceAddresses {
// Skip if instanceAddresses has no NICs
if len(instanceAddresses.InstanceNICs) == 0 {
continue
}
if instanceNetwork.Name == instanceAddresses.NetworkName {
// Only use one NIC since it's possible the user defined another NIC
// on this same network in another Terraform network block.
instanceNIC := instanceAddresses.InstanceNICs[0]
copy(instanceAddresses.InstanceNICs, instanceAddresses.InstanceNICs[1:])
v := map[string]interface{}{
"name": instanceAddresses.NetworkName,
"fixed_ip_v4": instanceNIC.FixedIPv4,
"fixed_ip_v6": instanceNIC.FixedIPv6,
"mac": instanceNIC.MAC,
"uuid": instanceNetwork.UUID,
"port": instanceNetwork.Port,
"access_network": instanceNetwork.AccessNetwork,
}
networks = append(networks, v)
}
}
}
log.Printf("[DEBUG] flattenInstanceNetworks: %#v", networks)
return networks, nil
} | go | func flattenInstanceNetworks(
d *schema.ResourceData, meta interface{}) ([]map[string]interface{}, error) {
config := meta.(*Config)
computeClient, err := config.computeV2Client(GetRegion(d, config))
if err != nil {
return nil, fmt.Errorf("Error creating OpenStack compute client: %s", err)
}
server, err := servers.Get(computeClient, d.Id()).Extract()
if err != nil {
return nil, CheckDeleted(d, err, "server")
}
allInstanceAddresses := getInstanceAddresses(server.Addresses)
allInstanceNetworks, err := getAllInstanceNetworks(d, meta)
if err != nil {
return nil, err
}
networks := []map[string]interface{}{}
// If there were no instance networks returned, this means that there
// was not a network specified in the Terraform configuration. When this
// happens, the instance will be launched on a "default" network, if one
// is available. If there isn't, the instance will fail to launch, so
// this is a safe assumption at this point.
if len(allInstanceNetworks) == 0 {
for _, instanceAddresses := range allInstanceAddresses {
for _, instanceNIC := range instanceAddresses.InstanceNICs {
v := map[string]interface{}{
"name": instanceAddresses.NetworkName,
"fixed_ip_v4": instanceNIC.FixedIPv4,
"fixed_ip_v6": instanceNIC.FixedIPv6,
"mac": instanceNIC.MAC,
}
// Use the same method as getAllInstanceNetworks to get the network uuid
networkInfo, err := getInstanceNetworkInfo(d, meta, "name", instanceAddresses.NetworkName)
if err != nil {
log.Printf("[WARN] Error getting default network uuid: %s", err)
} else {
if v["uuid"] != nil {
v["uuid"] = networkInfo["uuid"].(string)
} else {
log.Printf("[WARN] Could not get default network uuid")
}
}
networks = append(networks, v)
}
}
log.Printf("[DEBUG] flattenInstanceNetworks: %#v", networks)
return networks, nil
}
// Loop through all networks and addresses, merge relevant address details.
for _, instanceNetwork := range allInstanceNetworks {
for _, instanceAddresses := range allInstanceAddresses {
// Skip if instanceAddresses has no NICs
if len(instanceAddresses.InstanceNICs) == 0 {
continue
}
if instanceNetwork.Name == instanceAddresses.NetworkName {
// Only use one NIC since it's possible the user defined another NIC
// on this same network in another Terraform network block.
instanceNIC := instanceAddresses.InstanceNICs[0]
copy(instanceAddresses.InstanceNICs, instanceAddresses.InstanceNICs[1:])
v := map[string]interface{}{
"name": instanceAddresses.NetworkName,
"fixed_ip_v4": instanceNIC.FixedIPv4,
"fixed_ip_v6": instanceNIC.FixedIPv6,
"mac": instanceNIC.MAC,
"uuid": instanceNetwork.UUID,
"port": instanceNetwork.Port,
"access_network": instanceNetwork.AccessNetwork,
}
networks = append(networks, v)
}
}
}
log.Printf("[DEBUG] flattenInstanceNetworks: %#v", networks)
return networks, nil
} | [
"func",
"flattenInstanceNetworks",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"meta",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"config",
":=",
"meta",
".",
"(",
"*",
"Config",
")",
"\n",
"computeClient",
",",
"err",
":=",
"config",
".",
"computeV2Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"server",
",",
"err",
":=",
"servers",
".",
"Get",
"(",
"computeClient",
",",
"d",
".",
"Id",
"(",
")",
")",
".",
"Extract",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"CheckDeleted",
"(",
"d",
",",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"allInstanceAddresses",
":=",
"getInstanceAddresses",
"(",
"server",
".",
"Addresses",
")",
"\n",
"allInstanceNetworks",
",",
"err",
":=",
"getAllInstanceNetworks",
"(",
"d",
",",
"meta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"networks",
":=",
"[",
"]",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n\n",
"// If there were no instance networks returned, this means that there",
"// was not a network specified in the Terraform configuration. When this",
"// happens, the instance will be launched on a \"default\" network, if one",
"// is available. If there isn't, the instance will fail to launch, so",
"// this is a safe assumption at this point.",
"if",
"len",
"(",
"allInstanceNetworks",
")",
"==",
"0",
"{",
"for",
"_",
",",
"instanceAddresses",
":=",
"range",
"allInstanceAddresses",
"{",
"for",
"_",
",",
"instanceNIC",
":=",
"range",
"instanceAddresses",
".",
"InstanceNICs",
"{",
"v",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"instanceAddresses",
".",
"NetworkName",
",",
"\"",
"\"",
":",
"instanceNIC",
".",
"FixedIPv4",
",",
"\"",
"\"",
":",
"instanceNIC",
".",
"FixedIPv6",
",",
"\"",
"\"",
":",
"instanceNIC",
".",
"MAC",
",",
"}",
"\n\n",
"// Use the same method as getAllInstanceNetworks to get the network uuid",
"networkInfo",
",",
"err",
":=",
"getInstanceNetworkInfo",
"(",
"d",
",",
"meta",
",",
"\"",
"\"",
",",
"instanceAddresses",
".",
"NetworkName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"if",
"v",
"[",
"\"",
"\"",
"]",
"!=",
"nil",
"{",
"v",
"[",
"\"",
"\"",
"]",
"=",
"networkInfo",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"}",
"else",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"networks",
"=",
"append",
"(",
"networks",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"networks",
")",
"\n",
"return",
"networks",
",",
"nil",
"\n",
"}",
"\n\n",
"// Loop through all networks and addresses, merge relevant address details.",
"for",
"_",
",",
"instanceNetwork",
":=",
"range",
"allInstanceNetworks",
"{",
"for",
"_",
",",
"instanceAddresses",
":=",
"range",
"allInstanceAddresses",
"{",
"// Skip if instanceAddresses has no NICs",
"if",
"len",
"(",
"instanceAddresses",
".",
"InstanceNICs",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"instanceNetwork",
".",
"Name",
"==",
"instanceAddresses",
".",
"NetworkName",
"{",
"// Only use one NIC since it's possible the user defined another NIC",
"// on this same network in another Terraform network block.",
"instanceNIC",
":=",
"instanceAddresses",
".",
"InstanceNICs",
"[",
"0",
"]",
"\n",
"copy",
"(",
"instanceAddresses",
".",
"InstanceNICs",
",",
"instanceAddresses",
".",
"InstanceNICs",
"[",
"1",
":",
"]",
")",
"\n",
"v",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"instanceAddresses",
".",
"NetworkName",
",",
"\"",
"\"",
":",
"instanceNIC",
".",
"FixedIPv4",
",",
"\"",
"\"",
":",
"instanceNIC",
".",
"FixedIPv6",
",",
"\"",
"\"",
":",
"instanceNIC",
".",
"MAC",
",",
"\"",
"\"",
":",
"instanceNetwork",
".",
"UUID",
",",
"\"",
"\"",
":",
"instanceNetwork",
".",
"Port",
",",
"\"",
"\"",
":",
"instanceNetwork",
".",
"AccessNetwork",
",",
"}",
"\n",
"networks",
"=",
"append",
"(",
"networks",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"networks",
")",
"\n",
"return",
"networks",
",",
"nil",
"\n",
"}"
] | // flattenInstanceNetworks collects instance network information from different
// sources and aggregates it all together into a map array. | [
"flattenInstanceNetworks",
"collects",
"instance",
"network",
"information",
"from",
"different",
"sources",
"and",
"aggregates",
"it",
"all",
"together",
"into",
"a",
"map",
"array",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L406-L492 |
terraform-providers/terraform-provider-openstack | openstack/compute_instance_v2_networking.go | getInstanceAccessAddresses | func getInstanceAccessAddresses(
d *schema.ResourceData, networks []map[string]interface{}) (string, string) {
var hostv4, hostv6 string
// Loop through all networks
// If the network has a valid fixed v4 or fixed v6 address
// and hostv4 or hostv6 is not set, set hostv4/hostv6.
// If the network is an "access_network" overwrite hostv4/hostv6.
for _, n := range networks {
var accessNetwork bool
if an, ok := n["access_network"].(bool); ok && an {
accessNetwork = true
}
if fixedIPv4, ok := n["fixed_ip_v4"].(string); ok && fixedIPv4 != "" {
if hostv4 == "" || accessNetwork {
hostv4 = fixedIPv4
}
}
if fixedIPv6, ok := n["fixed_ip_v6"].(string); ok && fixedIPv6 != "" {
if hostv6 == "" || accessNetwork {
hostv6 = fixedIPv6
}
}
}
log.Printf("[DEBUG] OpenStack Instance Network Access Addresses: %s, %s", hostv4, hostv6)
return hostv4, hostv6
} | go | func getInstanceAccessAddresses(
d *schema.ResourceData, networks []map[string]interface{}) (string, string) {
var hostv4, hostv6 string
// Loop through all networks
// If the network has a valid fixed v4 or fixed v6 address
// and hostv4 or hostv6 is not set, set hostv4/hostv6.
// If the network is an "access_network" overwrite hostv4/hostv6.
for _, n := range networks {
var accessNetwork bool
if an, ok := n["access_network"].(bool); ok && an {
accessNetwork = true
}
if fixedIPv4, ok := n["fixed_ip_v4"].(string); ok && fixedIPv4 != "" {
if hostv4 == "" || accessNetwork {
hostv4 = fixedIPv4
}
}
if fixedIPv6, ok := n["fixed_ip_v6"].(string); ok && fixedIPv6 != "" {
if hostv6 == "" || accessNetwork {
hostv6 = fixedIPv6
}
}
}
log.Printf("[DEBUG] OpenStack Instance Network Access Addresses: %s, %s", hostv4, hostv6)
return hostv4, hostv6
} | [
"func",
"getInstanceAccessAddresses",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"networks",
"[",
"]",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"string",
",",
"string",
")",
"{",
"var",
"hostv4",
",",
"hostv6",
"string",
"\n\n",
"// Loop through all networks",
"// If the network has a valid fixed v4 or fixed v6 address",
"// and hostv4 or hostv6 is not set, set hostv4/hostv6.",
"// If the network is an \"access_network\" overwrite hostv4/hostv6.",
"for",
"_",
",",
"n",
":=",
"range",
"networks",
"{",
"var",
"accessNetwork",
"bool",
"\n\n",
"if",
"an",
",",
"ok",
":=",
"n",
"[",
"\"",
"\"",
"]",
".",
"(",
"bool",
")",
";",
"ok",
"&&",
"an",
"{",
"accessNetwork",
"=",
"true",
"\n",
"}",
"\n\n",
"if",
"fixedIPv4",
",",
"ok",
":=",
"n",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
";",
"ok",
"&&",
"fixedIPv4",
"!=",
"\"",
"\"",
"{",
"if",
"hostv4",
"==",
"\"",
"\"",
"||",
"accessNetwork",
"{",
"hostv4",
"=",
"fixedIPv4",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"fixedIPv6",
",",
"ok",
":=",
"n",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
";",
"ok",
"&&",
"fixedIPv6",
"!=",
"\"",
"\"",
"{",
"if",
"hostv6",
"==",
"\"",
"\"",
"||",
"accessNetwork",
"{",
"hostv6",
"=",
"fixedIPv6",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"hostv4",
",",
"hostv6",
")",
"\n\n",
"return",
"hostv4",
",",
"hostv6",
"\n",
"}"
] | // getInstanceAccessAddresses determines the best IP address to communicate
// with the instance. It does this by looping through all networks and looking
// for a valid IP address. Priority is given to a network that was flagged as
// an access_network. | [
"getInstanceAccessAddresses",
"determines",
"the",
"best",
"IP",
"address",
"to",
"communicate",
"with",
"the",
"instance",
".",
"It",
"does",
"this",
"by",
"looping",
"through",
"all",
"networks",
"and",
"looking",
"for",
"a",
"valid",
"IP",
"address",
".",
"Priority",
"is",
"given",
"to",
"a",
"network",
"that",
"was",
"flagged",
"as",
"an",
"access_network",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L498-L530 |
terraform-providers/terraform-provider-openstack | openstack/types.go | RoundTrip | func (lrt *LogRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
defer func() {
if request.Body != nil {
request.Body.Close()
}
}()
// for future reference, this is how to access the Transport struct:
//tlsconfig := lrt.Rt.(*http.Transport).TLSClientConfig
var err error
if lrt.OsDebug {
log.Printf("[DEBUG] OpenStack Request URL: %s %s", request.Method, request.URL)
log.Printf("[DEBUG] OpenStack Request Headers:\n%s", FormatHeaders(request.Header, "\n"))
if request.Body != nil {
request.Body, err = lrt.logRequest(request.Body, request.Header.Get("Content-Type"))
if err != nil {
return nil, err
}
}
}
response, err := lrt.Rt.RoundTrip(request)
// If the first request didn't return a response, retry up to `max_retries`.
retry := 1
for response == nil {
if retry > lrt.MaxRetries {
if lrt.OsDebug {
log.Printf("[DEBUG] OpenStack connection error, retries exhausted. Aborting")
}
err = fmt.Errorf("OpenStack connection error, retries exhausted. Aborting. Last error was: %s", err)
return nil, err
}
if lrt.OsDebug {
log.Printf("[DEBUG] OpenStack connection error, retry number %d: %s", retry, err)
}
response, err = lrt.Rt.RoundTrip(request)
retry += 1
}
if lrt.OsDebug {
log.Printf("[DEBUG] OpenStack Response Code: %d", response.StatusCode)
log.Printf("[DEBUG] OpenStack Response Headers:\n%s", FormatHeaders(response.Header, "\n"))
response.Body, err = lrt.logResponse(response.Body, response.Header.Get("Content-Type"))
}
return response, err
} | go | func (lrt *LogRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
defer func() {
if request.Body != nil {
request.Body.Close()
}
}()
// for future reference, this is how to access the Transport struct:
//tlsconfig := lrt.Rt.(*http.Transport).TLSClientConfig
var err error
if lrt.OsDebug {
log.Printf("[DEBUG] OpenStack Request URL: %s %s", request.Method, request.URL)
log.Printf("[DEBUG] OpenStack Request Headers:\n%s", FormatHeaders(request.Header, "\n"))
if request.Body != nil {
request.Body, err = lrt.logRequest(request.Body, request.Header.Get("Content-Type"))
if err != nil {
return nil, err
}
}
}
response, err := lrt.Rt.RoundTrip(request)
// If the first request didn't return a response, retry up to `max_retries`.
retry := 1
for response == nil {
if retry > lrt.MaxRetries {
if lrt.OsDebug {
log.Printf("[DEBUG] OpenStack connection error, retries exhausted. Aborting")
}
err = fmt.Errorf("OpenStack connection error, retries exhausted. Aborting. Last error was: %s", err)
return nil, err
}
if lrt.OsDebug {
log.Printf("[DEBUG] OpenStack connection error, retry number %d: %s", retry, err)
}
response, err = lrt.Rt.RoundTrip(request)
retry += 1
}
if lrt.OsDebug {
log.Printf("[DEBUG] OpenStack Response Code: %d", response.StatusCode)
log.Printf("[DEBUG] OpenStack Response Headers:\n%s", FormatHeaders(response.Header, "\n"))
response.Body, err = lrt.logResponse(response.Body, response.Header.Get("Content-Type"))
}
return response, err
} | [
"func",
"(",
"lrt",
"*",
"LogRoundTripper",
")",
"RoundTrip",
"(",
"request",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"request",
".",
"Body",
"!=",
"nil",
"{",
"request",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// for future reference, this is how to access the Transport struct:",
"//tlsconfig := lrt.Rt.(*http.Transport).TLSClientConfig",
"var",
"err",
"error",
"\n\n",
"if",
"lrt",
".",
"OsDebug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"request",
".",
"Method",
",",
"request",
".",
"URL",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"FormatHeaders",
"(",
"request",
".",
"Header",
",",
"\"",
"\\n",
"\"",
")",
")",
"\n\n",
"if",
"request",
".",
"Body",
"!=",
"nil",
"{",
"request",
".",
"Body",
",",
"err",
"=",
"lrt",
".",
"logRequest",
"(",
"request",
".",
"Body",
",",
"request",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"response",
",",
"err",
":=",
"lrt",
".",
"Rt",
".",
"RoundTrip",
"(",
"request",
")",
"\n\n",
"// If the first request didn't return a response, retry up to `max_retries`.",
"retry",
":=",
"1",
"\n",
"for",
"response",
"==",
"nil",
"{",
"if",
"retry",
">",
"lrt",
".",
"MaxRetries",
"{",
"if",
"lrt",
".",
"OsDebug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"lrt",
".",
"OsDebug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"retry",
",",
"err",
")",
"\n",
"}",
"\n",
"response",
",",
"err",
"=",
"lrt",
".",
"Rt",
".",
"RoundTrip",
"(",
"request",
")",
"\n",
"retry",
"+=",
"1",
"\n",
"}",
"\n\n",
"if",
"lrt",
".",
"OsDebug",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"response",
".",
"StatusCode",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"FormatHeaders",
"(",
"response",
".",
"Header",
",",
"\"",
"\\n",
"\"",
")",
")",
"\n\n",
"response",
".",
"Body",
",",
"err",
"=",
"lrt",
".",
"logResponse",
"(",
"response",
".",
"Body",
",",
"response",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"return",
"response",
",",
"err",
"\n",
"}"
] | // RoundTrip performs a round-trip HTTP request and logs relevant information about it. | [
"RoundTrip",
"performs",
"a",
"round",
"-",
"trip",
"HTTP",
"request",
"and",
"logs",
"relevant",
"information",
"about",
"it",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/types.go#L35-L87 |
terraform-providers/terraform-provider-openstack | openstack/types.go | logRequest | func (lrt *LogRoundTripper) logRequest(original io.ReadCloser, contentType string) (io.ReadCloser, error) {
defer original.Close()
var bs bytes.Buffer
_, err := io.Copy(&bs, original)
if err != nil {
return nil, err
}
// Handle request contentType
if strings.HasPrefix(contentType, "application/json") {
debugInfo := lrt.formatJSON(bs.Bytes())
log.Printf("[DEBUG] OpenStack Request Body: %s", debugInfo)
}
return ioutil.NopCloser(strings.NewReader(bs.String())), nil
} | go | func (lrt *LogRoundTripper) logRequest(original io.ReadCloser, contentType string) (io.ReadCloser, error) {
defer original.Close()
var bs bytes.Buffer
_, err := io.Copy(&bs, original)
if err != nil {
return nil, err
}
// Handle request contentType
if strings.HasPrefix(contentType, "application/json") {
debugInfo := lrt.formatJSON(bs.Bytes())
log.Printf("[DEBUG] OpenStack Request Body: %s", debugInfo)
}
return ioutil.NopCloser(strings.NewReader(bs.String())), nil
} | [
"func",
"(",
"lrt",
"*",
"LogRoundTripper",
")",
"logRequest",
"(",
"original",
"io",
".",
"ReadCloser",
",",
"contentType",
"string",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"defer",
"original",
".",
"Close",
"(",
")",
"\n\n",
"var",
"bs",
"bytes",
".",
"Buffer",
"\n",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"&",
"bs",
",",
"original",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Handle request contentType",
"if",
"strings",
".",
"HasPrefix",
"(",
"contentType",
",",
"\"",
"\"",
")",
"{",
"debugInfo",
":=",
"lrt",
".",
"formatJSON",
"(",
"bs",
".",
"Bytes",
"(",
")",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"debugInfo",
")",
"\n",
"}",
"\n\n",
"return",
"ioutil",
".",
"NopCloser",
"(",
"strings",
".",
"NewReader",
"(",
"bs",
".",
"String",
"(",
")",
")",
")",
",",
"nil",
"\n",
"}"
] | // logRequest will log the HTTP Request details.
// If the body is JSON, it will attempt to be pretty-formatted. | [
"logRequest",
"will",
"log",
"the",
"HTTP",
"Request",
"details",
".",
"If",
"the",
"body",
"is",
"JSON",
"it",
"will",
"attempt",
"to",
"be",
"pretty",
"-",
"formatted",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/types.go#L91-L107 |
terraform-providers/terraform-provider-openstack | openstack/types.go | formatJSON | func (lrt *LogRoundTripper) formatJSON(raw []byte) string {
var rawData interface{}
err := json.Unmarshal(raw, &rawData)
if err != nil {
log.Printf("[DEBUG] Unable to parse OpenStack JSON: %s", err)
return string(raw)
}
data, ok := rawData.(map[string]interface{})
if !ok {
pretty, err := json.MarshalIndent(rawData, "", " ")
if err != nil {
log.Printf("[DEBUG] Unable to re-marshal OpenStack JSON: %s", err)
return string(raw)
}
return string(pretty)
}
// Mask known password fields
if v, ok := data["auth"].(map[string]interface{}); ok {
if v, ok := v["identity"].(map[string]interface{}); ok {
if v, ok := v["password"].(map[string]interface{}); ok {
if v, ok := v["user"].(map[string]interface{}); ok {
v["password"] = "***"
}
}
if v, ok := v["application_credential"].(map[string]interface{}); ok {
v["secret"] = "***"
}
if v, ok := v["token"].(map[string]interface{}); ok {
v["id"] = "***"
}
}
}
// Ignore the catalog
if v, ok := data["token"].(map[string]interface{}); ok {
if _, ok := v["catalog"]; ok {
return ""
}
}
pretty, err := json.MarshalIndent(data, "", " ")
if err != nil {
log.Printf("[DEBUG] Unable to re-marshal OpenStack JSON: %s", err)
return string(raw)
}
return string(pretty)
} | go | func (lrt *LogRoundTripper) formatJSON(raw []byte) string {
var rawData interface{}
err := json.Unmarshal(raw, &rawData)
if err != nil {
log.Printf("[DEBUG] Unable to parse OpenStack JSON: %s", err)
return string(raw)
}
data, ok := rawData.(map[string]interface{})
if !ok {
pretty, err := json.MarshalIndent(rawData, "", " ")
if err != nil {
log.Printf("[DEBUG] Unable to re-marshal OpenStack JSON: %s", err)
return string(raw)
}
return string(pretty)
}
// Mask known password fields
if v, ok := data["auth"].(map[string]interface{}); ok {
if v, ok := v["identity"].(map[string]interface{}); ok {
if v, ok := v["password"].(map[string]interface{}); ok {
if v, ok := v["user"].(map[string]interface{}); ok {
v["password"] = "***"
}
}
if v, ok := v["application_credential"].(map[string]interface{}); ok {
v["secret"] = "***"
}
if v, ok := v["token"].(map[string]interface{}); ok {
v["id"] = "***"
}
}
}
// Ignore the catalog
if v, ok := data["token"].(map[string]interface{}); ok {
if _, ok := v["catalog"]; ok {
return ""
}
}
pretty, err := json.MarshalIndent(data, "", " ")
if err != nil {
log.Printf("[DEBUG] Unable to re-marshal OpenStack JSON: %s", err)
return string(raw)
}
return string(pretty)
} | [
"func",
"(",
"lrt",
"*",
"LogRoundTripper",
")",
"formatJSON",
"(",
"raw",
"[",
"]",
"byte",
")",
"string",
"{",
"var",
"rawData",
"interface",
"{",
"}",
"\n\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"raw",
",",
"&",
"rawData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"string",
"(",
"raw",
")",
"\n",
"}",
"\n\n",
"data",
",",
"ok",
":=",
"rawData",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"!",
"ok",
"{",
"pretty",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"rawData",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"string",
"(",
"raw",
")",
"\n",
"}",
"\n\n",
"return",
"string",
"(",
"pretty",
")",
"\n",
"}",
"\n\n",
"// Mask known password fields",
"if",
"v",
",",
"ok",
":=",
"data",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"if",
"v",
",",
"ok",
":=",
"v",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"if",
"v",
",",
"ok",
":=",
"v",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"if",
"v",
",",
"ok",
":=",
"v",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"v",
"[",
"\"",
"\"",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"v",
",",
"ok",
":=",
"v",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"v",
"[",
"\"",
"\"",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"v",
",",
"ok",
":=",
"v",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"v",
"[",
"\"",
"\"",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Ignore the catalog",
"if",
"v",
",",
"ok",
":=",
"data",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"if",
"_",
",",
"ok",
":=",
"v",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n\n",
"pretty",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"data",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"string",
"(",
"raw",
")",
"\n",
"}",
"\n\n",
"return",
"string",
"(",
"pretty",
")",
"\n",
"}"
] | // formatJSON will try to pretty-format a JSON body.
// It will also mask known fields which contain sensitive information. | [
"formatJSON",
"will",
"try",
"to",
"pretty",
"-",
"format",
"a",
"JSON",
"body",
".",
"It",
"will",
"also",
"mask",
"known",
"fields",
"which",
"contain",
"sensitive",
"information",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/types.go#L132-L183 |
terraform-providers/terraform-provider-openstack | openstack/types.go | ToSubnetCreateMap | func (opts SubnetCreateOpts) ToSubnetCreateMap() (map[string]interface{}, error) {
b, err := BuildRequest(opts, "subnet")
if err != nil {
return nil, err
}
if m := b["subnet"].(map[string]interface{}); m["gateway_ip"] == "" {
m["gateway_ip"] = nil
}
return b, nil
} | go | func (opts SubnetCreateOpts) ToSubnetCreateMap() (map[string]interface{}, error) {
b, err := BuildRequest(opts, "subnet")
if err != nil {
return nil, err
}
if m := b["subnet"].(map[string]interface{}); m["gateway_ip"] == "" {
m["gateway_ip"] = nil
}
return b, nil
} | [
"func",
"(",
"opts",
"SubnetCreateOpts",
")",
"ToSubnetCreateMap",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"BuildRequest",
"(",
"opts",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"m",
":=",
"b",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"m",
"[",
"\"",
"\"",
"]",
"==",
"\"",
"\"",
"{",
"m",
"[",
"\"",
"\"",
"]",
"=",
"nil",
"\n",
"}",
"\n\n",
"return",
"b",
",",
"nil",
"\n",
"}"
] | // ToSubnetCreateMap casts a CreateOpts struct to a map.
// It overrides subnets.ToSubnetCreateMap to add the ValueSpecs field. | [
"ToSubnetCreateMap",
"casts",
"a",
"CreateOpts",
"struct",
"to",
"a",
"map",
".",
"It",
"overrides",
"subnets",
".",
"ToSubnetCreateMap",
"to",
"add",
"the",
"ValueSpecs",
"field",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/types.go#L253-L264 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_identity_endpoint_v3.go | dataSourceIdentityEndpointV3Read | func dataSourceIdentityEndpointV3Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
identityClient, err := config.identityV3Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack identity client: %s", err)
}
availability := gophercloud.AvailabilityPublic
switch d.Get("interface") {
case "internal":
availability = gophercloud.AvailabilityInternal
case "admin":
availability = gophercloud.AvailabilityAdmin
}
listOpts := endpoints.ListOpts{
Availability: availability,
ServiceID: d.Get("service_id").(string),
}
log.Printf("[DEBUG] openstack_identity_endpoint_v3 list options: %#v", listOpts)
var endpoint endpoints.Endpoint
allPages, err := endpoints.List(identityClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query openstack_identity_endpoint_v3: %s", err)
}
allEndpoints, err := endpoints.ExtractEndpoints(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve openstack_identity_endpoint_v3: %s", err)
}
serviceName := d.Get("service_name").(string)
if len(allEndpoints) > 1 && serviceName != "" {
var filteredEndpoints []endpoints.Endpoint
// Query all services to further filter results
allServicePages, err := services.List(identityClient, nil).AllPages()
if err != nil {
return fmt.Errorf("Unable to query openstack_identity_endpoint_v3 services: %s", err)
}
allServices, err := services.ExtractServices(allServicePages)
if err != nil {
return fmt.Errorf("Unable to retrieve openstack_identity_endpoint_v3 services: %s", err)
}
for _, endpoint := range allEndpoints {
for _, service := range allServices {
if v, ok := service.Extra["name"].(string); ok {
if endpoint.ServiceID == service.ID && serviceName == v {
endpoint.Name = v
filteredEndpoints = append(filteredEndpoints, endpoint)
}
}
}
}
allEndpoints = filteredEndpoints
}
if len(allEndpoints) < 1 {
return fmt.Errorf("Your openstack_identity_endpoint_v3 query returned no results. " +
"Please change your search criteria and try again.")
}
if len(allEndpoints) > 1 {
return fmt.Errorf("Your openstack_identity_endpoint_v3 query returned more than one result")
}
endpoint = allEndpoints[0]
return dataSourceIdentityEndpointV3Attributes(d, &endpoint)
} | go | func dataSourceIdentityEndpointV3Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
identityClient, err := config.identityV3Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating OpenStack identity client: %s", err)
}
availability := gophercloud.AvailabilityPublic
switch d.Get("interface") {
case "internal":
availability = gophercloud.AvailabilityInternal
case "admin":
availability = gophercloud.AvailabilityAdmin
}
listOpts := endpoints.ListOpts{
Availability: availability,
ServiceID: d.Get("service_id").(string),
}
log.Printf("[DEBUG] openstack_identity_endpoint_v3 list options: %#v", listOpts)
var endpoint endpoints.Endpoint
allPages, err := endpoints.List(identityClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to query openstack_identity_endpoint_v3: %s", err)
}
allEndpoints, err := endpoints.ExtractEndpoints(allPages)
if err != nil {
return fmt.Errorf("Unable to retrieve openstack_identity_endpoint_v3: %s", err)
}
serviceName := d.Get("service_name").(string)
if len(allEndpoints) > 1 && serviceName != "" {
var filteredEndpoints []endpoints.Endpoint
// Query all services to further filter results
allServicePages, err := services.List(identityClient, nil).AllPages()
if err != nil {
return fmt.Errorf("Unable to query openstack_identity_endpoint_v3 services: %s", err)
}
allServices, err := services.ExtractServices(allServicePages)
if err != nil {
return fmt.Errorf("Unable to retrieve openstack_identity_endpoint_v3 services: %s", err)
}
for _, endpoint := range allEndpoints {
for _, service := range allServices {
if v, ok := service.Extra["name"].(string); ok {
if endpoint.ServiceID == service.ID && serviceName == v {
endpoint.Name = v
filteredEndpoints = append(filteredEndpoints, endpoint)
}
}
}
}
allEndpoints = filteredEndpoints
}
if len(allEndpoints) < 1 {
return fmt.Errorf("Your openstack_identity_endpoint_v3 query returned no results. " +
"Please change your search criteria and try again.")
}
if len(allEndpoints) > 1 {
return fmt.Errorf("Your openstack_identity_endpoint_v3 query returned more than one result")
}
endpoint = allEndpoints[0]
return dataSourceIdentityEndpointV3Attributes(d, &endpoint)
} | [
"func",
"dataSourceIdentityEndpointV3Read",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"meta",
"interface",
"{",
"}",
")",
"error",
"{",
"config",
":=",
"meta",
".",
"(",
"*",
"Config",
")",
"\n",
"identityClient",
",",
"err",
":=",
"config",
".",
"identityV3Client",
"(",
"GetRegion",
"(",
"d",
",",
"config",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"availability",
":=",
"gophercloud",
".",
"AvailabilityPublic",
"\n",
"switch",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
"{",
"case",
"\"",
"\"",
":",
"availability",
"=",
"gophercloud",
".",
"AvailabilityInternal",
"\n",
"case",
"\"",
"\"",
":",
"availability",
"=",
"gophercloud",
".",
"AvailabilityAdmin",
"\n",
"}",
"\n\n",
"listOpts",
":=",
"endpoints",
".",
"ListOpts",
"{",
"Availability",
":",
"availability",
",",
"ServiceID",
":",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
",",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"listOpts",
")",
"\n\n",
"var",
"endpoint",
"endpoints",
".",
"Endpoint",
"\n",
"allPages",
",",
"err",
":=",
"endpoints",
".",
"List",
"(",
"identityClient",
",",
"listOpts",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"allEndpoints",
",",
"err",
":=",
"endpoints",
".",
"ExtractEndpoints",
"(",
"allPages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"serviceName",
":=",
"d",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
"\n",
"if",
"len",
"(",
"allEndpoints",
")",
">",
"1",
"&&",
"serviceName",
"!=",
"\"",
"\"",
"{",
"var",
"filteredEndpoints",
"[",
"]",
"endpoints",
".",
"Endpoint",
"\n\n",
"// Query all services to further filter results",
"allServicePages",
",",
"err",
":=",
"services",
".",
"List",
"(",
"identityClient",
",",
"nil",
")",
".",
"AllPages",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"allServices",
",",
"err",
":=",
"services",
".",
"ExtractServices",
"(",
"allServicePages",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"endpoint",
":=",
"range",
"allEndpoints",
"{",
"for",
"_",
",",
"service",
":=",
"range",
"allServices",
"{",
"if",
"v",
",",
"ok",
":=",
"service",
".",
"Extra",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
";",
"ok",
"{",
"if",
"endpoint",
".",
"ServiceID",
"==",
"service",
".",
"ID",
"&&",
"serviceName",
"==",
"v",
"{",
"endpoint",
".",
"Name",
"=",
"v",
"\n",
"filteredEndpoints",
"=",
"append",
"(",
"filteredEndpoints",
",",
"endpoint",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"allEndpoints",
"=",
"filteredEndpoints",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allEndpoints",
")",
"<",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"allEndpoints",
")",
">",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"endpoint",
"=",
"allEndpoints",
"[",
"0",
"]",
"\n\n",
"return",
"dataSourceIdentityEndpointV3Attributes",
"(",
"d",
",",
"&",
"endpoint",
")",
"\n",
"}"
] | // dataSourceIdentityEndpointV3Read performs the endpoint lookup. | [
"dataSourceIdentityEndpointV3Read",
"performs",
"the",
"endpoint",
"lookup",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_endpoint_v3.go#L57-L130 |
terraform-providers/terraform-provider-openstack | openstack/data_source_openstack_identity_endpoint_v3.go | dataSourceIdentityEndpointV3Attributes | func dataSourceIdentityEndpointV3Attributes(d *schema.ResourceData, endpoint *endpoints.Endpoint) error {
log.Printf("[DEBUG] openstack_identity_endpoint_v3 details: %#v", endpoint)
d.SetId(endpoint.ID)
d.Set("interface", endpoint.Availability)
d.Set("region", endpoint.Region)
d.Set("service_id", endpoint.ServiceID)
d.Set("service_name", endpoint.Name)
d.Set("url", endpoint.URL)
return nil
} | go | func dataSourceIdentityEndpointV3Attributes(d *schema.ResourceData, endpoint *endpoints.Endpoint) error {
log.Printf("[DEBUG] openstack_identity_endpoint_v3 details: %#v", endpoint)
d.SetId(endpoint.ID)
d.Set("interface", endpoint.Availability)
d.Set("region", endpoint.Region)
d.Set("service_id", endpoint.ServiceID)
d.Set("service_name", endpoint.Name)
d.Set("url", endpoint.URL)
return nil
} | [
"func",
"dataSourceIdentityEndpointV3Attributes",
"(",
"d",
"*",
"schema",
".",
"ResourceData",
",",
"endpoint",
"*",
"endpoints",
".",
"Endpoint",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"endpoint",
")",
"\n\n",
"d",
".",
"SetId",
"(",
"endpoint",
".",
"ID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"endpoint",
".",
"Availability",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"endpoint",
".",
"Region",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"endpoint",
".",
"ServiceID",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"endpoint",
".",
"Name",
")",
"\n",
"d",
".",
"Set",
"(",
"\"",
"\"",
",",
"endpoint",
".",
"URL",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // dataSourceIdentityEndpointV3Attributes populates the fields of an Endpoint resource. | [
"dataSourceIdentityEndpointV3Attributes",
"populates",
"the",
"fields",
"of",
"an",
"Endpoint",
"resource",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_endpoint_v3.go#L133-L144 |
terraform-providers/terraform-provider-openstack | openstack/db_instance_v1.go | databaseInstanceV1StateRefreshFunc | func databaseInstanceV1StateRefreshFunc(client *gophercloud.ServiceClient, instanceID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
i, err := instances.Get(client, instanceID).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
return i, "DELETED", nil
}
return nil, "", err
}
if i.Status == "error" {
return i, i.Status, fmt.Errorf("There was an error creating the database instance.")
}
return i, i.Status, nil
}
} | go | func databaseInstanceV1StateRefreshFunc(client *gophercloud.ServiceClient, instanceID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
i, err := instances.Get(client, instanceID).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
return i, "DELETED", nil
}
return nil, "", err
}
if i.Status == "error" {
return i, i.Status, fmt.Errorf("There was an error creating the database instance.")
}
return i, i.Status, nil
}
} | [
"func",
"databaseInstanceV1StateRefreshFunc",
"(",
"client",
"*",
"gophercloud",
".",
"ServiceClient",
",",
"instanceID",
"string",
")",
"resource",
".",
"StateRefreshFunc",
"{",
"return",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"string",
",",
"error",
")",
"{",
"i",
",",
"err",
":=",
"instances",
".",
"Get",
"(",
"client",
",",
"instanceID",
")",
".",
"Extract",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"gophercloud",
".",
"ErrDefault404",
")",
";",
"ok",
"{",
"return",
"i",
",",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"i",
".",
"Status",
"==",
"\"",
"\"",
"{",
"return",
"i",
",",
"i",
".",
"Status",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"i",
",",
"i",
".",
"Status",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // databaseInstanceV1StateRefreshFunc returns a resource.StateRefreshFunc
// that is used to watch a database instance. | [
"databaseInstanceV1StateRefreshFunc",
"returns",
"a",
"resource",
".",
"StateRefreshFunc",
"that",
"is",
"used",
"to",
"watch",
"a",
"database",
"instance",
"."
] | train | https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/db_instance_v1.go#L71-L87 |
hashicorp/raft-boltdb | bolt_store.go | readOnly | func (o *Options) readOnly() bool {
return o != nil && o.BoltOptions != nil && o.BoltOptions.ReadOnly
} | go | func (o *Options) readOnly() bool {
return o != nil && o.BoltOptions != nil && o.BoltOptions.ReadOnly
} | [
"func",
"(",
"o",
"*",
"Options",
")",
"readOnly",
"(",
")",
"bool",
"{",
"return",
"o",
"!=",
"nil",
"&&",
"o",
".",
"BoltOptions",
"!=",
"nil",
"&&",
"o",
".",
"BoltOptions",
".",
"ReadOnly",
"\n",
"}"
] | // readOnly returns true if the contained bolt options say to open
// the DB in readOnly mode [this can be useful to tools that want
// to examine the log] | [
"readOnly",
"returns",
"true",
"if",
"the",
"contained",
"bolt",
"options",
"say",
"to",
"open",
"the",
"DB",
"in",
"readOnly",
"mode",
"[",
"this",
"can",
"be",
"useful",
"to",
"tools",
"that",
"want",
"to",
"examine",
"the",
"log",
"]"
] | train | https://github.com/hashicorp/raft-boltdb/blob/6e5ba93211eaf8d9a2ad7e41ffad8c6f160f9fe3/bolt_store.go#L54-L56 |
hashicorp/raft-boltdb | bolt_store.go | New | func New(options Options) (*BoltStore, error) {
// Try to connect
handle, err := bolt.Open(options.Path, dbFileMode, options.BoltOptions)
if err != nil {
return nil, err
}
handle.NoSync = options.NoSync
// Create the new store
store := &BoltStore{
conn: handle,
path: options.Path,
}
// If the store was opened read-only, don't try and create buckets
if !options.readOnly() {
// Set up our buckets
if err := store.initialize(); err != nil {
store.Close()
return nil, err
}
}
return store, nil
} | go | func New(options Options) (*BoltStore, error) {
// Try to connect
handle, err := bolt.Open(options.Path, dbFileMode, options.BoltOptions)
if err != nil {
return nil, err
}
handle.NoSync = options.NoSync
// Create the new store
store := &BoltStore{
conn: handle,
path: options.Path,
}
// If the store was opened read-only, don't try and create buckets
if !options.readOnly() {
// Set up our buckets
if err := store.initialize(); err != nil {
store.Close()
return nil, err
}
}
return store, nil
} | [
"func",
"New",
"(",
"options",
"Options",
")",
"(",
"*",
"BoltStore",
",",
"error",
")",
"{",
"// Try to connect",
"handle",
",",
"err",
":=",
"bolt",
".",
"Open",
"(",
"options",
".",
"Path",
",",
"dbFileMode",
",",
"options",
".",
"BoltOptions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"handle",
".",
"NoSync",
"=",
"options",
".",
"NoSync",
"\n\n",
"// Create the new store",
"store",
":=",
"&",
"BoltStore",
"{",
"conn",
":",
"handle",
",",
"path",
":",
"options",
".",
"Path",
",",
"}",
"\n\n",
"// If the store was opened read-only, don't try and create buckets",
"if",
"!",
"options",
".",
"readOnly",
"(",
")",
"{",
"// Set up our buckets",
"if",
"err",
":=",
"store",
".",
"initialize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"store",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"store",
",",
"nil",
"\n",
"}"
] | // New uses the supplied options to open the BoltDB and prepare it for use as a raft backend. | [
"New",
"uses",
"the",
"supplied",
"options",
"to",
"open",
"the",
"BoltDB",
"and",
"prepare",
"it",
"for",
"use",
"as",
"a",
"raft",
"backend",
"."
] | train | https://github.com/hashicorp/raft-boltdb/blob/6e5ba93211eaf8d9a2ad7e41ffad8c6f160f9fe3/bolt_store.go#L64-L87 |
hashicorp/raft-boltdb | bolt_store.go | initialize | func (b *BoltStore) initialize() error {
tx, err := b.conn.Begin(true)
if err != nil {
return err
}
defer tx.Rollback()
// Create all the buckets
if _, err := tx.CreateBucketIfNotExists(dbLogs); err != nil {
return err
}
if _, err := tx.CreateBucketIfNotExists(dbConf); err != nil {
return err
}
return tx.Commit()
} | go | func (b *BoltStore) initialize() error {
tx, err := b.conn.Begin(true)
if err != nil {
return err
}
defer tx.Rollback()
// Create all the buckets
if _, err := tx.CreateBucketIfNotExists(dbLogs); err != nil {
return err
}
if _, err := tx.CreateBucketIfNotExists(dbConf); err != nil {
return err
}
return tx.Commit()
} | [
"func",
"(",
"b",
"*",
"BoltStore",
")",
"initialize",
"(",
")",
"error",
"{",
"tx",
",",
"err",
":=",
"b",
".",
"conn",
".",
"Begin",
"(",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"tx",
".",
"Rollback",
"(",
")",
"\n\n",
"// Create all the buckets",
"if",
"_",
",",
"err",
":=",
"tx",
".",
"CreateBucketIfNotExists",
"(",
"dbLogs",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"tx",
".",
"CreateBucketIfNotExists",
"(",
"dbConf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"tx",
".",
"Commit",
"(",
")",
"\n",
"}"
] | // initialize is used to set up all of the buckets. | [
"initialize",
"is",
"used",
"to",
"set",
"up",
"all",
"of",
"the",
"buckets",
"."
] | train | https://github.com/hashicorp/raft-boltdb/blob/6e5ba93211eaf8d9a2ad7e41ffad8c6f160f9fe3/bolt_store.go#L90-L106 |
hashicorp/raft-boltdb | bolt_store.go | FirstIndex | func (b *BoltStore) FirstIndex() (uint64, error) {
tx, err := b.conn.Begin(false)
if err != nil {
return 0, err
}
defer tx.Rollback()
curs := tx.Bucket(dbLogs).Cursor()
if first, _ := curs.First(); first == nil {
return 0, nil
} else {
return bytesToUint64(first), nil
}
} | go | func (b *BoltStore) FirstIndex() (uint64, error) {
tx, err := b.conn.Begin(false)
if err != nil {
return 0, err
}
defer tx.Rollback()
curs := tx.Bucket(dbLogs).Cursor()
if first, _ := curs.First(); first == nil {
return 0, nil
} else {
return bytesToUint64(first), nil
}
} | [
"func",
"(",
"b",
"*",
"BoltStore",
")",
"FirstIndex",
"(",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"tx",
",",
"err",
":=",
"b",
".",
"conn",
".",
"Begin",
"(",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"defer",
"tx",
".",
"Rollback",
"(",
")",
"\n\n",
"curs",
":=",
"tx",
".",
"Bucket",
"(",
"dbLogs",
")",
".",
"Cursor",
"(",
")",
"\n",
"if",
"first",
",",
"_",
":=",
"curs",
".",
"First",
"(",
")",
";",
"first",
"==",
"nil",
"{",
"return",
"0",
",",
"nil",
"\n",
"}",
"else",
"{",
"return",
"bytesToUint64",
"(",
"first",
")",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // FirstIndex returns the first known index from the Raft log. | [
"FirstIndex",
"returns",
"the",
"first",
"known",
"index",
"from",
"the",
"Raft",
"log",
"."
] | train | https://github.com/hashicorp/raft-boltdb/blob/6e5ba93211eaf8d9a2ad7e41ffad8c6f160f9fe3/bolt_store.go#L114-L127 |
hashicorp/raft-boltdb | bolt_store.go | LastIndex | func (b *BoltStore) LastIndex() (uint64, error) {
tx, err := b.conn.Begin(false)
if err != nil {
return 0, err
}
defer tx.Rollback()
curs := tx.Bucket(dbLogs).Cursor()
if last, _ := curs.Last(); last == nil {
return 0, nil
} else {
return bytesToUint64(last), nil
}
} | go | func (b *BoltStore) LastIndex() (uint64, error) {
tx, err := b.conn.Begin(false)
if err != nil {
return 0, err
}
defer tx.Rollback()
curs := tx.Bucket(dbLogs).Cursor()
if last, _ := curs.Last(); last == nil {
return 0, nil
} else {
return bytesToUint64(last), nil
}
} | [
"func",
"(",
"b",
"*",
"BoltStore",
")",
"LastIndex",
"(",
")",
"(",
"uint64",
",",
"error",
")",
"{",
"tx",
",",
"err",
":=",
"b",
".",
"conn",
".",
"Begin",
"(",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"defer",
"tx",
".",
"Rollback",
"(",
")",
"\n\n",
"curs",
":=",
"tx",
".",
"Bucket",
"(",
"dbLogs",
")",
".",
"Cursor",
"(",
")",
"\n",
"if",
"last",
",",
"_",
":=",
"curs",
".",
"Last",
"(",
")",
";",
"last",
"==",
"nil",
"{",
"return",
"0",
",",
"nil",
"\n",
"}",
"else",
"{",
"return",
"bytesToUint64",
"(",
"last",
")",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // LastIndex returns the last known index from the Raft log. | [
"LastIndex",
"returns",
"the",
"last",
"known",
"index",
"from",
"the",
"Raft",
"log",
"."
] | train | https://github.com/hashicorp/raft-boltdb/blob/6e5ba93211eaf8d9a2ad7e41ffad8c6f160f9fe3/bolt_store.go#L130-L143 |
hashicorp/raft-boltdb | bolt_store.go | GetLog | func (b *BoltStore) GetLog(idx uint64, log *raft.Log) error {
tx, err := b.conn.Begin(false)
if err != nil {
return err
}
defer tx.Rollback()
bucket := tx.Bucket(dbLogs)
val := bucket.Get(uint64ToBytes(idx))
if val == nil {
return raft.ErrLogNotFound
}
return decodeMsgPack(val, log)
} | go | func (b *BoltStore) GetLog(idx uint64, log *raft.Log) error {
tx, err := b.conn.Begin(false)
if err != nil {
return err
}
defer tx.Rollback()
bucket := tx.Bucket(dbLogs)
val := bucket.Get(uint64ToBytes(idx))
if val == nil {
return raft.ErrLogNotFound
}
return decodeMsgPack(val, log)
} | [
"func",
"(",
"b",
"*",
"BoltStore",
")",
"GetLog",
"(",
"idx",
"uint64",
",",
"log",
"*",
"raft",
".",
"Log",
")",
"error",
"{",
"tx",
",",
"err",
":=",
"b",
".",
"conn",
".",
"Begin",
"(",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"tx",
".",
"Rollback",
"(",
")",
"\n\n",
"bucket",
":=",
"tx",
".",
"Bucket",
"(",
"dbLogs",
")",
"\n",
"val",
":=",
"bucket",
".",
"Get",
"(",
"uint64ToBytes",
"(",
"idx",
")",
")",
"\n\n",
"if",
"val",
"==",
"nil",
"{",
"return",
"raft",
".",
"ErrLogNotFound",
"\n",
"}",
"\n",
"return",
"decodeMsgPack",
"(",
"val",
",",
"log",
")",
"\n",
"}"
] | // GetLog is used to retrieve a log from BoltDB at a given index. | [
"GetLog",
"is",
"used",
"to",
"retrieve",
"a",
"log",
"from",
"BoltDB",
"at",
"a",
"given",
"index",
"."
] | train | https://github.com/hashicorp/raft-boltdb/blob/6e5ba93211eaf8d9a2ad7e41ffad8c6f160f9fe3/bolt_store.go#L146-L160 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.