repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
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", ":", "\"trig...
// 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", "." ]
f33c874a09dcfac90f008abeee9171d88431e212
https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L476-L482
train
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", "{", "if", "d", "<", "time", ".", "Nanosecond", "{", "return", "ErrDurationTooShort", "\n", "}", "\n", "w", ".", "mu", ".", "Lock", "(", ")", "\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", "." ]
f33c874a09dcfac90f008abeee9171d88431e212
https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L534-L609
train
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", ...
// 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", "." ]
f33c874a09dcfac90f008abeee9171d88431e212
https://github.com/radovskyb/watcher/blob/f33c874a09dcfac90f008abeee9171d88431e212/watcher.go#L701-L713
train
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" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L28-L33
train
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", ...
// 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" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L56-L62
train
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", ":=", "cm...
// 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" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L75-L95
train
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", "args", "=", "args", "[", "1", ":", "len", "(", "args", ")", "]", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "...
// 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" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L99-L131
train
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", "]", "=...
// 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" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/common.go#L135-L145
train
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" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/build.go#L20-L22
train
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", "(", ")", "{", "b", ".", "watcher", ".", "update", "<-", "struct", "{", "}", "{", "}", "\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", "." ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/build.go#L26-L62
train
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", "(", "\"watch-vendor\"", ")", "\n", "var", "watchVendor", "bool", "\n", "var", "err", "error", "\n", "if", "watchVendorStr", ...
// MustRegisterWatcher creates a new Watcher and starts listening to // given folders
[ "MustRegisterWatcher", "creates", "a", "new", "Watcher", "and", "starts", "listening", "to", "given", "folders" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L37-L63
train
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", "for", "{", "select", "{", "case", "event", ":=", "<-", "w", ".", "watcher", ".", "Events", ":", "if", "event", ".", "Op", "&", "fsnotify", ".", "Chm...
// 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" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L67-L101
train
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", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"Could not get root working directory: %s\"", ",", "err"...
// 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" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L126-L160
train
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", "(", "\"Could not watch folder: %s\"", ",",...
// 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" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L164-L168
train
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", "path", ":=", "os", ".", "Getenv", ...
// prepareRootDir prepares working directory depending on root directory
[ "prepareRootDir", "prepares", "working", "directory", "depending", "on", "root", "directory" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/watch.go#L171-L184
train
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", "(", "\"Running %s...\\n\"", ",", "\\n", ")", "\n", "p", ".", "Get", "(", "\"run\"", ...
// Run initializes runner with given parameters.
[ "Run", "initializes", "runner", "with", "given", "parameters", "." ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/run.go#L31-L54
train
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", "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" ]
59980168ee35c24b8dc3c3bb3dec2ed749fa5c44
https://github.com/canthefason/go-watcher/blob/59980168ee35c24b8dc3c3bb3dec2ed749fa5c44/run.go#L58-L62
train
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", "sf", ".", "mutex", ".", "Lock", "(", ")", "\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", "." ]
6d5bd61810093eae37d7d605d0cbdd845969b5b2
https://github.com/sony/sonyflake/blob/6d5bd61810093eae37d7d605d0cbdd845969b5b2/sonyflake.go#L86-L106
train
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", "=", "uin...
// Decompose returns a set of Sonyflake ID parts.
[ "Decompose", "returns", "a", "set", "of", "Sonyflake", "ID", "parts", "." ]
6d5bd61810093eae37d7d605d0cbdd845969b5b2
https://github.com/sony/sonyflake/blob/6d5bd61810093eae37d7d605d0cbdd845969b5b2/sonyflake.go#L168-L183
train
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", "return", "uint16", "(", "ip", ...
// 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", "." ]
6d5bd61810093eae37d7d605d0cbdd845969b5b2
https://github.com/sony/sonyflake/blob/6d5bd61810093eae37d7d605d0cbdd845969b5b2/awsutil/awsutil.go#L37-L44
train
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", "(", "\"/usr/sbin/ntpdate\"", ",", "\"-q\"", ",", "server", ")", ".", "CombinedOutput", "(", ...
// 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", "." ]
6d5bd61810093eae37d7d605d0cbdd845969b5b2
https://github.com/sony/sonyflake/blob/6d5bd61810093eae37d7d605d0cbdd845969b5b2/awsutil/awsutil.go#L47-L64
train
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", "!=", "...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/dns_zone_v2.go#L21-L36
train
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", ".", "i...
// dataSourceIdentityRoleV3Read performs the role lookup.
[ "dataSourceIdentityRoleV3Read", "performs", "the", "role", "lookup", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_role_v3.go#L38-L74
train
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", "(", "\"%s/%s/%s/%s/%s\"", ",", "domainID", ",", "projectID", ",", "groupID", ...
// 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" ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/identity_role_assignment_v3.go#L14-L16
train
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", "{", "rawAPs", ":=", "d", ".", "Get", "(", "\"allocation_pool\"", ")", ".", "(", "*", "schema", ".", "Set", ")", ...
// 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", "alloca...
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/resource_openstack_networking_subnet_v2.go#L474-L493
train
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", ".", ...
// dataSourceIdentityProjectV3Read performs the project lookup.
[ "dataSourceIdentityProjectV3Read", "performs", "the", "project", "lookup", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_project_v3.go#L60-L102
train
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", "(", "\"[DEBUG] openstack_identity_project_v3 details: %#v\"", ",", "project", ")",...
// dataSourceIdentityProjectV3Attributes populates the fields of an Project resource.
[ "dataSourceIdentityProjectV3Attributes", "populates", "the", "fields", "of", "an", "Project", "resource", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_project_v3.go#L105-L117
train
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", "(", "\"[DEBUG] Re...
// dataSourceComputeFlavorV2Attributes populates the fields of a Flavor resource.
[ "dataSourceComputeFlavorV2Attributes", "populates", "the", "fields", "of", "a", "Flavor", "resource", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_compute_flavor_v2.go#L198-L223
train
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"...
// resourceObjectstorageTempurlV1Create performs the image lookup.
[ "resourceObjectstorageTempurlV1Create", "performs", "the", "image", "lookup", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/resource_openstack_objectstorage_tempurl_v1.go#L85-L127
train
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", "(", "\"url\"", ")", ".", "(", "string", ")", "\n", "u", ",", "err", ":=",...
// resourceObjectstorageTempurlV1Read performs the image lookup.
[ "resourceObjectstorageTempurlV1Read", "performs", "the", "image", "lookup", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/resource_openstack_objectstorage_tempurl_v1.go#L130-L159
train
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", ",", ...
// 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" ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L22-L31
train
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", "(", "\"region\"", ")", ";", "ok", "{", "return", "v", ".", "(", "string", ")", "\...
// 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", ...
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L47-L53
train
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", "[", "\"value_specs\"", "]", "!=", "nil", "{", "for", "k", ",", "v", ":=", "range", "b...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L57-L66
train
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", ...
// MapValueSpecs converts ResourceData into a map
[ "MapValueSpecs", "converts", "ResourceData", "into", "a", "map" ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L69-L75
train
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", ...
// RedactHeaders processes a headers object, returning a redacted list
[ "RedactHeaders", "processes", "a", "headers", "object", "returning", "a", "redacted", "list" ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L84-L95
train
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", "return", "strings",...
// FormatHeaders processes a headers object plus a deliminator, returning a string
[ "FormatHeaders", "processes", "a", "headers", "object", "plus", "a", "deliminator", "returning", "a", "string" ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L98-L103
train
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", "!=", "\"min\"", "&&", "direction", "!=", "\"max\"", "{", "return", "false", ",", "fmt", ".", "Errorf"...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/util.go#L278-L336
train
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", "(", "\"[DEBUG] openstack_images_image details: %#v\"", ",", "image", ")", "\n", "d", "...
// dataSourceImagesImageV2Attributes populates the fields of an Image resource.
[ "dataSourceImagesImageV2Attributes", "populates", "the", "fields", "of", "an", "Image", "resource", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_images_image_v2.go#L262-L284
train
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", "[", ...
// Returns the most recent Image out of a slice of images.
[ "Returns", "the", "most", "recent", "Image", "out", "of", "a", "slice", "of", "images", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_images_image_v2.go#L297-L301
train
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", ".", "...
// dataSourceIdentityGroupV3Read performs the group lookup.
[ "dataSourceIdentityGroupV3Read", "performs", "the", "group", "lookup", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_group_v3.go#L38-L75
train
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", ...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/dns_recordset_v2.go#L23-L34
train
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", ...
// dnsRecordSetV2RecordsStateFunc will strip brackets from IPv6 addresses.
[ "dnsRecordSetV2RecordsStateFunc", "will", "strip", "brackets", "from", "IPv6", "addresses", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/dns_recordset_v2.go#L82-L91
train
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", "{", "}", ",...
// databaseDatabaseV1StateRefreshFunc returns a resource.StateRefreshFunc // that is used to watch a database.
[ "databaseDatabaseV1StateRefreshFunc", "returns", "a", "resource", ".", "StateRefreshFunc", "that", "is", "used", "to", "watch", "a", "database", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/db_database_v1.go#L14-L34
train
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", "{", "}", ",",...
// databaseUserV1StateRefreshFunc returns a resource.StateRefreshFunc that is used to watch db user.
[ "databaseUserV1StateRefreshFunc", "returns", "a", "resource", ".", "StateRefreshFunc", "that", "is", "used", "to", "watch", "db", "user", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/db_user_v1.go#L35-L55
train
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...
// databaseUserV1Exists is used to check whether user exists on particular database instance
[ "databaseUserV1Exists", "is", "used", "to", "check", "whether", "user", "exists", "on", "particular", "database", "instance" ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/db_user_v1.go#L58-L81
train
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", ".", "i...
// dataSourceIdentityUserV3Read performs the user lookup.
[ "dataSourceIdentityUserV3Read", "performs", "the", "user", "lookup", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_user_v3.go#L71-L114
train
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", "(", "\"[DEBUG] openstack_identity_user_v3 details: %#v\"", ",", "user", ")", "\n", "d", ...
// dataSourceIdentityUserV3Attributes populates the fields of an User resource.
[ "dataSourceIdentityUserV3Attributes", "populates", "the", "fields", "of", "an", "User", "resource", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_user_v3.go#L117-L129
train
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", ",", "err...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/db_configuration_v1.go#L43-L55
train
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", ")", ...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/resource_openstack_compute_instance_v2.go#L950-L962
train
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", "(", ")",...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/config.go#L219-L233
train
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", "region", "==", "\"\"", "&&", "c", ".", "Region", "!=", "\"\"", "{", "region", "=", "c", ".", "Region", "\n", "}", "\n", "log", ".", "Printf...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/config.go#L237-L246
train
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",...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/config.go#L263-L277
train
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", "ne...
// networkingNetworkV2Name retrieves network name by the provided ID.
[ "networkingNetworkV2Name", "retrieves", "network", "name", "by", "the", "provided", "ID", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/networking_network_v2.go#L62-L90
train
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", ",", "...
// networkingFloatingIPV2ID retrieves floating IP ID by the provided IP address.
[ "networkingFloatingIPV2ID", "retrieves", "floating", "IP", "ID", "by", "the", "provided", "IP", "address", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/networking_floatingip_v2.go#L18-L41
train
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", ",", "er...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/containerinfra_shared_v1.go#L63-L89
train
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", "(", "\"flavor\"", ")", ".", "(", "string", ")", ";", "flavor", "!=", "\"\"", "{",...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/containerinfra_shared_v1.go#L94-L104
train
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", ",", "\"firewall_rule\"", ")", "\n", "if", "err"...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/fw_rule_v1.go#L16-L27
train
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"...
// 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",...
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L152-L182
train
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", "queryType", "==", "\"po...
// getInstanceNetworkInfoNovaNet will query the os-tenant-networks API for // the network information.
[ "getInstanceNetworkInfoNovaNet", "will", "query", "the", "os", "-", "tenant", "-", "networks", "API", "for", "the", "network", "information", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L186-L255
train
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", "queryType", "==", "\"po...
// getInstanceNetworkInfoNeutron will query the neutron API for the network // information.
[ "getInstanceNetworkInfoNeutron", "will", "query", "the", "neutron", "API", "for", "the", "network", "information", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L259-L330
train
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", "for", "networkName", ",", "v", ":=", "range", "add...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L334-L386
train
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", ".", "(", "*", ...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L406-L492
train
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", ...
// 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", ".", "...
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/compute_instance_v2_networking.go#L498-L530
train
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", "{...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/types.go#L35-L87
train
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", "var", ...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/types.go#L91-L107
train
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", "err", ":=", "json", ".", "Unmarshal", "(", "raw", ",", "&", "rawData", ")", "\n", "if", ...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/types.go#L132-L183
train
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", ",", "\"subnet\"", ")", "\n", "if", "err", ...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/types.go#L253-L264
train
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", ".", ...
// dataSourceIdentityEndpointV3Read performs the endpoint lookup.
[ "dataSourceIdentityEndpointV3Read", "performs", "the", "endpoint", "lookup", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_endpoint_v3.go#L57-L130
train
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", "(", "\"[DEBUG] openstack_identity_endpoint_v3 details: %#v\"", ",", "endpoint", ...
// dataSourceIdentityEndpointV3Attributes populates the fields of an Endpoint resource.
[ "dataSourceIdentityEndpointV3Attributes", "populates", "the", "fields", "of", "an", "Endpoint", "resource", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/data_source_openstack_identity_endpoint_v3.go#L133-L144
train
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"...
// 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", "." ]
a4c13eee81a7ca8682741b049cb067610bdf45b2
https://github.com/terraform-providers/terraform-provider-openstack/blob/a4c13eee81a7ca8682741b049cb067610bdf45b2/openstack/db_instance_v1.go#L71-L87
train
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", ")", "{", "handle", ",", "err", ":=", "bolt", ".", "Open", "(", "options", ".", "Path", ",", "dbFileMode", ",", "options", ".", "BoltOptions", ")", "\n", "if", "err",...
// 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", "." ]
6e5ba93211eaf8d9a2ad7e41ffad8c6f160f9fe3
https://github.com/hashicorp/raft-boltdb/blob/6e5ba93211eaf8d9a2ad7e41ffad8c6f160f9fe3/bolt_store.go#L64-L87
train
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", ".", ...
// initialize is used to set up all of the buckets.
[ "initialize", "is", "used", "to", "set", "up", "all", "of", "the", "buckets", "." ]
6e5ba93211eaf8d9a2ad7e41ffad8c6f160f9fe3
https://github.com/hashicorp/raft-boltdb/blob/6e5ba93211eaf8d9a2ad7e41ffad8c6f160f9fe3/bolt_store.go#L90-L106
train
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", "{", "...
// 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", "." ]
6e5ba93211eaf8d9a2ad7e41ffad8c6f160f9fe3
https://github.com/hashicorp/raft-boltdb/blob/6e5ba93211eaf8d9a2ad7e41ffad8c6f160f9fe3/bolt_store.go#L146-L160
train
mailgun/mailgun-go
domains.go
ListDomains
func (mg *MailgunImpl) ListDomains(opts *ListOptions) *DomainsIterator { var limit int if opts != nil { limit = opts.Limit } if limit == 0 { limit = 100 } return &DomainsIterator{ mg: mg, url: generatePublicApiUrl(mg, domainsEndpoint), domainsListResponse: domainsListResponse{TotalCount: -1}, limit: limit, } }
go
func (mg *MailgunImpl) ListDomains(opts *ListOptions) *DomainsIterator { var limit int if opts != nil { limit = opts.Limit } if limit == 0 { limit = 100 } return &DomainsIterator{ mg: mg, url: generatePublicApiUrl(mg, domainsEndpoint), domainsListResponse: domainsListResponse{TotalCount: -1}, limit: limit, } }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "ListDomains", "(", "opts", "*", "ListOptions", ")", "*", "DomainsIterator", "{", "var", "limit", "int", "\n", "if", "opts", "!=", "nil", "{", "limit", "=", "opts", ".", "Limit", "\n", "}", "\n", "if", "lim...
// ListDomains retrieves a set of domains from Mailgun.
[ "ListDomains", "retrieves", "a", "set", "of", "domains", "from", "Mailgun", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/domains.go#L83-L98
train
mailgun/mailgun-go
domains.go
GetDomain
func (mg *MailgunImpl) GetDomain(ctx context.Context, domain string) (DomainResponse, error) { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + domain) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp DomainResponse err := getResponseFromJSON(ctx, r, &resp) return resp, err }
go
func (mg *MailgunImpl) GetDomain(ctx context.Context, domain string) (DomainResponse, error) { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + domain) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp DomainResponse err := getResponseFromJSON(ctx, r, &resp) return resp, err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "GetDomain", "(", "ctx", "context", ".", "Context", ",", "domain", "string", ")", "(", "DomainResponse", ",", "error", ")", "{", "r", ":=", "newHTTPRequest", "(", "generatePublicApiUrl", "(", "mg", ",", "domainsE...
// GetDomain retrieves detailed information about the named domain.
[ "GetDomain", "retrieves", "detailed", "information", "about", "the", "named", "domain", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/domains.go#L235-L242
train
mailgun/mailgun-go
domains.go
CreateDomain
func (mg *MailgunImpl) CreateDomain(ctx context.Context, name string, opts *CreateDomainOptions) (DomainResponse, error) { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint)) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) payload := newUrlEncodedPayload() payload.addValue("name", name) if opts != nil { if opts.SpamAction != "" { payload.addValue("spam_action", string(opts.SpamAction)) } if opts.Wildcard { payload.addValue("wildcard", boolToString(opts.Wildcard)) } if opts.ForceDKIMAuthority { payload.addValue("force_dkim_authority", boolToString(opts.ForceDKIMAuthority)) } if opts.DKIMKeySize != 0 { payload.addValue("dkim_key_size", strconv.Itoa(opts.DKIMKeySize)) } if len(opts.IPS) != 0 { payload.addValue("ips", strings.Join(opts.IPS, ",")) } if len(opts.Password) != 0 { payload.addValue("smtp_password", opts.Password) } } var resp DomainResponse err := postResponseFromJSON(ctx, r, payload, &resp) return resp, err }
go
func (mg *MailgunImpl) CreateDomain(ctx context.Context, name string, opts *CreateDomainOptions) (DomainResponse, error) { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint)) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) payload := newUrlEncodedPayload() payload.addValue("name", name) if opts != nil { if opts.SpamAction != "" { payload.addValue("spam_action", string(opts.SpamAction)) } if opts.Wildcard { payload.addValue("wildcard", boolToString(opts.Wildcard)) } if opts.ForceDKIMAuthority { payload.addValue("force_dkim_authority", boolToString(opts.ForceDKIMAuthority)) } if opts.DKIMKeySize != 0 { payload.addValue("dkim_key_size", strconv.Itoa(opts.DKIMKeySize)) } if len(opts.IPS) != 0 { payload.addValue("ips", strings.Join(opts.IPS, ",")) } if len(opts.Password) != 0 { payload.addValue("smtp_password", opts.Password) } } var resp DomainResponse err := postResponseFromJSON(ctx, r, payload, &resp) return resp, err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "CreateDomain", "(", "ctx", "context", ".", "Context", ",", "name", "string", ",", "opts", "*", "CreateDomainOptions", ")", "(", "DomainResponse", ",", "error", ")", "{", "r", ":=", "newHTTPRequest", "(", "genera...
// CreateDomain instructs Mailgun to create a new domain for your account. // The name parameter identifies the domain. // The smtpPassword parameter provides an access credential for the domain. // The spamAction domain must be one of Delete, Tag, or Disabled. // The wildcard parameter instructs Mailgun to treat all subdomains of this domain uniformly if true, // and as different domains if false.
[ "CreateDomain", "instructs", "Mailgun", "to", "create", "a", "new", "domain", "for", "your", "account", ".", "The", "name", "parameter", "identifies", "the", "domain", ".", "The", "smtpPassword", "parameter", "provides", "an", "access", "credential", "for", "the...
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/domains.go#L271-L302
train
mailgun/mailgun-go
domains.go
GetDomainConnection
func (mg *MailgunImpl) GetDomainConnection(ctx context.Context, domain string) (DomainConnection, error) { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + domain + "/connection") r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp domainConnectionResponse err := getResponseFromJSON(ctx, r, &resp) return resp.Connection, err }
go
func (mg *MailgunImpl) GetDomainConnection(ctx context.Context, domain string) (DomainConnection, error) { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + domain + "/connection") r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp domainConnectionResponse err := getResponseFromJSON(ctx, r, &resp) return resp.Connection, err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "GetDomainConnection", "(", "ctx", "context", ".", "Context", ",", "domain", "string", ")", "(", "DomainConnection", ",", "error", ")", "{", "r", ":=", "newHTTPRequest", "(", "generatePublicApiUrl", "(", "mg", ",",...
// GetDomainConnection returns delivery connection settings for the defined domain
[ "GetDomainConnection", "returns", "delivery", "connection", "settings", "for", "the", "defined", "domain" ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/domains.go#L305-L312
train
mailgun/mailgun-go
domains.go
UpdateDomainConnection
func (mg *MailgunImpl) UpdateDomainConnection(ctx context.Context, domain string, settings DomainConnection) error { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + domain + "/connection") r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) payload := newUrlEncodedPayload() payload.addValue("require_tls", boolToString(settings.RequireTLS)) payload.addValue("skip_verification", boolToString(settings.SkipVerification)) _, err := makePutRequest(ctx, r, payload) return err }
go
func (mg *MailgunImpl) UpdateDomainConnection(ctx context.Context, domain string, settings DomainConnection) error { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + domain + "/connection") r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) payload := newUrlEncodedPayload() payload.addValue("require_tls", boolToString(settings.RequireTLS)) payload.addValue("skip_verification", boolToString(settings.SkipVerification)) _, err := makePutRequest(ctx, r, payload) return err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "UpdateDomainConnection", "(", "ctx", "context", ".", "Context", ",", "domain", "string", ",", "settings", "DomainConnection", ")", "error", "{", "r", ":=", "newHTTPRequest", "(", "generatePublicApiUrl", "(", "mg", "...
// Updates the specified delivery connection settings for the defined domain
[ "Updates", "the", "specified", "delivery", "connection", "settings", "for", "the", "defined", "domain" ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/domains.go#L315-L325
train
mailgun/mailgun-go
domains.go
DeleteDomain
func (mg *MailgunImpl) DeleteDomain(ctx context.Context, name string) error { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + name) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) _, err := makeDeleteRequest(ctx, r) return err }
go
func (mg *MailgunImpl) DeleteDomain(ctx context.Context, name string) error { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + name) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) _, err := makeDeleteRequest(ctx, r) return err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "DeleteDomain", "(", "ctx", "context", ".", "Context", ",", "name", "string", ")", "error", "{", "r", ":=", "newHTTPRequest", "(", "generatePublicApiUrl", "(", "mg", ",", "domainsEndpoint", ")", "+", "\"/\"", "+"...
// DeleteDomain instructs Mailgun to dispose of the named domain name
[ "DeleteDomain", "instructs", "Mailgun", "to", "dispose", "of", "the", "named", "domain", "name" ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/domains.go#L328-L334
train
mailgun/mailgun-go
domains.go
GetDomainTracking
func (mg *MailgunImpl) GetDomainTracking(ctx context.Context, domain string) (DomainTracking, error) { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + domain + "/tracking") r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp domainTrackingResponse err := getResponseFromJSON(ctx, r, &resp) return resp.Tracking, err }
go
func (mg *MailgunImpl) GetDomainTracking(ctx context.Context, domain string) (DomainTracking, error) { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + domain + "/tracking") r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp domainTrackingResponse err := getResponseFromJSON(ctx, r, &resp) return resp.Tracking, err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "GetDomainTracking", "(", "ctx", "context", ".", "Context", ",", "domain", "string", ")", "(", "DomainTracking", ",", "error", ")", "{", "r", ":=", "newHTTPRequest", "(", "generatePublicApiUrl", "(", "mg", ",", "...
// GetDomainTracking returns tracking settings for a domain
[ "GetDomainTracking", "returns", "tracking", "settings", "for", "a", "domain" ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/domains.go#L337-L344
train
mailgun/mailgun-go
webhooks.go
ListWebhooks
func (mg *MailgunImpl) ListWebhooks(ctx context.Context) (map[string]string, error) { r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint)) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var envelope struct { Webhooks map[string]interface{} `json:"webhooks"` } err := getResponseFromJSON(ctx, r, &envelope) hooks := make(map[string]string, 0) if err != nil { return hooks, err } for k, v := range envelope.Webhooks { object := v.(map[string]interface{}) url := object["url"] hooks[k] = url.(string) } return hooks, nil }
go
func (mg *MailgunImpl) ListWebhooks(ctx context.Context) (map[string]string, error) { r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint)) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var envelope struct { Webhooks map[string]interface{} `json:"webhooks"` } err := getResponseFromJSON(ctx, r, &envelope) hooks := make(map[string]string, 0) if err != nil { return hooks, err } for k, v := range envelope.Webhooks { object := v.(map[string]interface{}) url := object["url"] hooks[k] = url.(string) } return hooks, nil }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "ListWebhooks", "(", "ctx", "context", ".", "Context", ")", "(", "map", "[", "string", "]", "string", ",", "error", ")", "{", "r", ":=", "newHTTPRequest", "(", "generateDomainApiUrl", "(", "mg", ",", "webhooksE...
// ListWebhooks returns the complete set of webhooks configured for your domain. // Note that a zero-length mapping is not an error.
[ "ListWebhooks", "returns", "the", "complete", "set", "of", "webhooks", "configured", "for", "your", "domain", ".", "Note", "that", "a", "zero", "-", "length", "mapping", "is", "not", "an", "error", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/webhooks.go#L17-L35
train
mailgun/mailgun-go
webhooks.go
DeleteWebhook
func (mg *MailgunImpl) DeleteWebhook(ctx context.Context, t string) error { r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) _, err := makeDeleteRequest(ctx, r) return err }
go
func (mg *MailgunImpl) DeleteWebhook(ctx context.Context, t string) error { r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) _, err := makeDeleteRequest(ctx, r) return err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "DeleteWebhook", "(", "ctx", "context", ".", "Context", ",", "t", "string", ")", "error", "{", "r", ":=", "newHTTPRequest", "(", "generateDomainApiUrl", "(", "mg", ",", "webhooksEndpoint", ")", "+", "\"/\"", "+",...
// DeleteWebhook removes the specified webhook from your domain's configuration.
[ "DeleteWebhook", "removes", "the", "specified", "webhook", "from", "your", "domain", "s", "configuration", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/webhooks.go#L52-L58
train
mailgun/mailgun-go
webhooks.go
GetWebhook
func (mg *MailgunImpl) GetWebhook(ctx context.Context, t string) (string, error) { r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var envelope struct { Webhook struct { Url string `json:"url"` } `json:"webhook"` } err := getResponseFromJSON(ctx, r, &envelope) return envelope.Webhook.Url, err }
go
func (mg *MailgunImpl) GetWebhook(ctx context.Context, t string) (string, error) { r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var envelope struct { Webhook struct { Url string `json:"url"` } `json:"webhook"` } err := getResponseFromJSON(ctx, r, &envelope) return envelope.Webhook.Url, err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "GetWebhook", "(", "ctx", "context", ".", "Context", ",", "t", "string", ")", "(", "string", ",", "error", ")", "{", "r", ":=", "newHTTPRequest", "(", "generateDomainApiUrl", "(", "mg", ",", "webhooksEndpoint", ...
// GetWebhook retrieves the currently assigned webhook URL associated with the provided type of webhook.
[ "GetWebhook", "retrieves", "the", "currently", "assigned", "webhook", "URL", "associated", "with", "the", "provided", "type", "of", "webhook", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/webhooks.go#L61-L72
train
mailgun/mailgun-go
webhooks.go
UpdateWebhook
func (mg *MailgunImpl) UpdateWebhook(ctx context.Context, t string, urls []string) error { r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) p := newUrlEncodedPayload() for _, url := range urls { p.addValue("url", url) } _, err := makePutRequest(ctx, r, p) return err }
go
func (mg *MailgunImpl) UpdateWebhook(ctx context.Context, t string, urls []string) error { r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) p := newUrlEncodedPayload() for _, url := range urls { p.addValue("url", url) } _, err := makePutRequest(ctx, r, p) return err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "UpdateWebhook", "(", "ctx", "context", ".", "Context", ",", "t", "string", ",", "urls", "[", "]", "string", ")", "error", "{", "r", ":=", "newHTTPRequest", "(", "generateDomainApiUrl", "(", "mg", ",", "webhook...
// UpdateWebhook replaces one webhook setting for another.
[ "UpdateWebhook", "replaces", "one", "webhook", "setting", "for", "another", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/webhooks.go#L75-L85
train
mailgun/mailgun-go
webhooks.go
VerifyWebhookSignature
func (mg *MailgunImpl) VerifyWebhookSignature(sig Signature) (verified bool, err error) { h := hmac.New(sha256.New, []byte(mg.APIKey())) io.WriteString(h, sig.TimeStamp) io.WriteString(h, sig.Token) calculatedSignature := h.Sum(nil) signature, err := hex.DecodeString(sig.Signature) if err != nil { return false, err } if len(calculatedSignature) != len(signature) { return false, nil } return subtle.ConstantTimeCompare(signature, calculatedSignature) == 1, nil }
go
func (mg *MailgunImpl) VerifyWebhookSignature(sig Signature) (verified bool, err error) { h := hmac.New(sha256.New, []byte(mg.APIKey())) io.WriteString(h, sig.TimeStamp) io.WriteString(h, sig.Token) calculatedSignature := h.Sum(nil) signature, err := hex.DecodeString(sig.Signature) if err != nil { return false, err } if len(calculatedSignature) != len(signature) { return false, nil } return subtle.ConstantTimeCompare(signature, calculatedSignature) == 1, nil }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "VerifyWebhookSignature", "(", "sig", "Signature", ")", "(", "verified", "bool", ",", "err", "error", ")", "{", "h", ":=", "hmac", ".", "New", "(", "sha256", ".", "New", ",", "[", "]", "byte", "(", "mg", ...
// Use this method to parse the webhook signature given as JSON in the webhook response
[ "Use", "this", "method", "to", "parse", "the", "webhook", "signature", "given", "as", "JSON", "in", "the", "webhook", "response" ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/webhooks.go#L101-L116
train
mailgun/mailgun-go
rest_shim.go
newError
func newError(url string, expected []int, got *httpResponse) error { return &UnexpectedResponseError{ URL: url, Expected: expected, Actual: got.Code, Data: got.Data, } }
go
func newError(url string, expected []int, got *httpResponse) error { return &UnexpectedResponseError{ URL: url, Expected: expected, Actual: got.Code, Data: got.Data, } }
[ "func", "newError", "(", "url", "string", ",", "expected", "[", "]", "int", ",", "got", "*", "httpResponse", ")", "error", "{", "return", "&", "UnexpectedResponseError", "{", "URL", ":", "url", ",", "Expected", ":", "expected", ",", "Actual", ":", "got",...
// newError creates a new error condition to be returned.
[ "newError", "creates", "a", "new", "error", "condition", "to", "be", "returned", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/rest_shim.go#L35-L42
train
mailgun/mailgun-go
rest_shim.go
makeRequest
func makeRequest(ctx context.Context, r *httpRequest, method string, p payload) (*httpResponse, error) { r.addHeader("User-Agent", MailgunGoUserAgent) rsp, err := r.makeRequest(ctx, method, p) if (err == nil) && notGood(rsp.Code, expected) { return rsp, newError(r.URL, expected, rsp) } return rsp, err }
go
func makeRequest(ctx context.Context, r *httpRequest, method string, p payload) (*httpResponse, error) { r.addHeader("User-Agent", MailgunGoUserAgent) rsp, err := r.makeRequest(ctx, method, p) if (err == nil) && notGood(rsp.Code, expected) { return rsp, newError(r.URL, expected, rsp) } return rsp, err }
[ "func", "makeRequest", "(", "ctx", "context", ".", "Context", ",", "r", "*", "httpRequest", ",", "method", "string", ",", "p", "payload", ")", "(", "*", "httpResponse", ",", "error", ")", "{", "r", ".", "addHeader", "(", "\"User-Agent\"", ",", "MailgunGo...
// makeRequest shim performs a generic request, checking for a positive outcome. // See simplehttp.MakeRequest for more details.
[ "makeRequest", "shim", "performs", "a", "generic", "request", "checking", "for", "a", "positive", "outcome", ".", "See", "simplehttp", ".", "MakeRequest", "for", "more", "details", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/rest_shim.go#L61-L68
train
mailgun/mailgun-go
rest_shim.go
getResponseFromJSON
func getResponseFromJSON(ctx context.Context, r *httpRequest, v interface{}) error { r.addHeader("User-Agent", MailgunGoUserAgent) response, err := r.makeGetRequest(ctx) if err != nil { return err } if notGood(response.Code, expected) { return newError(r.URL, expected, response) } return response.parseFromJSON(v) }
go
func getResponseFromJSON(ctx context.Context, r *httpRequest, v interface{}) error { r.addHeader("User-Agent", MailgunGoUserAgent) response, err := r.makeGetRequest(ctx) if err != nil { return err } if notGood(response.Code, expected) { return newError(r.URL, expected, response) } return response.parseFromJSON(v) }
[ "func", "getResponseFromJSON", "(", "ctx", "context", ".", "Context", ",", "r", "*", "httpRequest", ",", "v", "interface", "{", "}", ")", "error", "{", "r", ".", "addHeader", "(", "\"User-Agent\"", ",", "MailgunGoUserAgent", ")", "\n", "response", ",", "er...
// getResponseFromJSON shim performs a GET request, checking for a positive outcome. // See simplehttp.GetResponseFromJSON for more details.
[ "getResponseFromJSON", "shim", "performs", "a", "GET", "request", "checking", "for", "a", "positive", "outcome", ".", "See", "simplehttp", ".", "GetResponseFromJSON", "for", "more", "details", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/rest_shim.go#L72-L82
train
mailgun/mailgun-go
rest_shim.go
postResponseFromJSON
func postResponseFromJSON(ctx context.Context, r *httpRequest, p payload, v interface{}) error { r.addHeader("User-Agent", MailgunGoUserAgent) response, err := r.makePostRequest(ctx, p) if err != nil { return err } if notGood(response.Code, expected) { return newError(r.URL, expected, response) } return response.parseFromJSON(v) }
go
func postResponseFromJSON(ctx context.Context, r *httpRequest, p payload, v interface{}) error { r.addHeader("User-Agent", MailgunGoUserAgent) response, err := r.makePostRequest(ctx, p) if err != nil { return err } if notGood(response.Code, expected) { return newError(r.URL, expected, response) } return response.parseFromJSON(v) }
[ "func", "postResponseFromJSON", "(", "ctx", "context", ".", "Context", ",", "r", "*", "httpRequest", ",", "p", "payload", ",", "v", "interface", "{", "}", ")", "error", "{", "r", ".", "addHeader", "(", "\"User-Agent\"", ",", "MailgunGoUserAgent", ")", "\n"...
// postResponseFromJSON shim performs a POST request, checking for a positive outcome. // See simplehttp.PostResponseFromJSON for more details.
[ "postResponseFromJSON", "shim", "performs", "a", "POST", "request", "checking", "for", "a", "positive", "outcome", ".", "See", "simplehttp", ".", "PostResponseFromJSON", "for", "more", "details", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/rest_shim.go#L86-L96
train
mailgun/mailgun-go
rest_shim.go
GetStatusFromErr
func GetStatusFromErr(err error) int { obj, ok := err.(*UnexpectedResponseError) if !ok { return -1 } return obj.Actual }
go
func GetStatusFromErr(err error) int { obj, ok := err.(*UnexpectedResponseError) if !ok { return -1 } return obj.Actual }
[ "func", "GetStatusFromErr", "(", "err", "error", ")", "int", "{", "obj", ",", "ok", ":=", "err", ".", "(", "*", "UnexpectedResponseError", ")", "\n", "if", "!", "ok", "{", "return", "-", "1", "\n", "}", "\n", "return", "obj", ".", "Actual", "\n", "...
// Extract the http status code from error object
[ "Extract", "the", "http", "status", "code", "from", "error", "object" ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/rest_shim.go#L157-L163
train
mailgun/mailgun-go
ips.go
ListIPS
func (mg *MailgunImpl) ListIPS(ctx context.Context, dedicated bool) ([]IPAddress, error) { r := newHTTPRequest(generatePublicApiUrl(mg, ipsEndpoint)) r.setClient(mg.Client()) if dedicated { r.addParameter("dedicated", "true") } r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp ipAddressListResponse if err := getResponseFromJSON(ctx, r, &resp); err != nil { return nil, err } var result []IPAddress for _, ip := range resp.Items { result = append(result, IPAddress{IP: ip}) } return result, nil }
go
func (mg *MailgunImpl) ListIPS(ctx context.Context, dedicated bool) ([]IPAddress, error) { r := newHTTPRequest(generatePublicApiUrl(mg, ipsEndpoint)) r.setClient(mg.Client()) if dedicated { r.addParameter("dedicated", "true") } r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp ipAddressListResponse if err := getResponseFromJSON(ctx, r, &resp); err != nil { return nil, err } var result []IPAddress for _, ip := range resp.Items { result = append(result, IPAddress{IP: ip}) } return result, nil }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "ListIPS", "(", "ctx", "context", ".", "Context", ",", "dedicated", "bool", ")", "(", "[", "]", "IPAddress", ",", "error", ")", "{", "r", ":=", "newHTTPRequest", "(", "generatePublicApiUrl", "(", "mg", ",", "...
// ListIPS returns a list of IPs assigned to your account
[ "ListIPS", "returns", "a", "list", "of", "IPs", "assigned", "to", "your", "account" ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/ips.go#L22-L39
train
mailgun/mailgun-go
ips.go
GetIP
func (mg *MailgunImpl) GetIP(ctx context.Context, ip string) (IPAddress, error) { r := newHTTPRequest(generatePublicApiUrl(mg, ipsEndpoint) + "/" + ip) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp IPAddress err := getResponseFromJSON(ctx, r, &resp) return resp, err }
go
func (mg *MailgunImpl) GetIP(ctx context.Context, ip string) (IPAddress, error) { r := newHTTPRequest(generatePublicApiUrl(mg, ipsEndpoint) + "/" + ip) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp IPAddress err := getResponseFromJSON(ctx, r, &resp) return resp, err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "GetIP", "(", "ctx", "context", ".", "Context", ",", "ip", "string", ")", "(", "IPAddress", ",", "error", ")", "{", "r", ":=", "newHTTPRequest", "(", "generatePublicApiUrl", "(", "mg", ",", "ipsEndpoint", ")", ...
// GetIP returns information about the specified IP
[ "GetIP", "returns", "information", "about", "the", "specified", "IP" ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/ips.go#L42-L49
train
mailgun/mailgun-go
ips.go
ListDomainIPS
func (mg *MailgunImpl) ListDomainIPS(ctx context.Context) ([]IPAddress, error) { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + mg.domain + "/ips") r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp ipAddressListResponse if err := getResponseFromJSON(ctx, r, &resp); err != nil { return nil, err } var result []IPAddress for _, ip := range resp.Items { result = append(result, IPAddress{IP: ip}) } return result, nil }
go
func (mg *MailgunImpl) ListDomainIPS(ctx context.Context) ([]IPAddress, error) { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + mg.domain + "/ips") r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp ipAddressListResponse if err := getResponseFromJSON(ctx, r, &resp); err != nil { return nil, err } var result []IPAddress for _, ip := range resp.Items { result = append(result, IPAddress{IP: ip}) } return result, nil }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "ListDomainIPS", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "IPAddress", ",", "error", ")", "{", "r", ":=", "newHTTPRequest", "(", "generatePublicApiUrl", "(", "mg", ",", "domainsEndpoint", ")", ...
// ListDomainIPS returns a list of IPs currently assigned to the specified domain.
[ "ListDomainIPS", "returns", "a", "list", "of", "IPs", "currently", "assigned", "to", "the", "specified", "domain", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/ips.go#L52-L66
train
mailgun/mailgun-go
ips.go
AddDomainIP
func (mg *MailgunImpl) AddDomainIP(ctx context.Context, ip string) error { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + mg.domain + "/ips") r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) payload := newUrlEncodedPayload() payload.addValue("ip", ip) _, err := makePostRequest(ctx, r, payload) return err }
go
func (mg *MailgunImpl) AddDomainIP(ctx context.Context, ip string) error { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + mg.domain + "/ips") r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) payload := newUrlEncodedPayload() payload.addValue("ip", ip) _, err := makePostRequest(ctx, r, payload) return err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "AddDomainIP", "(", "ctx", "context", ".", "Context", ",", "ip", "string", ")", "error", "{", "r", ":=", "newHTTPRequest", "(", "generatePublicApiUrl", "(", "mg", ",", "domainsEndpoint", ")", "+", "\"/\"", "+", ...
// Assign a dedicated IP to the domain specified.
[ "Assign", "a", "dedicated", "IP", "to", "the", "domain", "specified", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/ips.go#L69-L78
train
mailgun/mailgun-go
ips.go
DeleteDomainIP
func (mg *MailgunImpl) DeleteDomainIP(ctx context.Context, ip string) error { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + mg.domain + "/ips/" + ip) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) _, err := makeDeleteRequest(ctx, r) return err }
go
func (mg *MailgunImpl) DeleteDomainIP(ctx context.Context, ip string) error { r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + mg.domain + "/ips/" + ip) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) _, err := makeDeleteRequest(ctx, r) return err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "DeleteDomainIP", "(", "ctx", "context", ".", "Context", ",", "ip", "string", ")", "error", "{", "r", ":=", "newHTTPRequest", "(", "generatePublicApiUrl", "(", "mg", ",", "domainsEndpoint", ")", "+", "\"/\"", "+"...
// Unassign an IP from the domain specified.
[ "Unassign", "an", "IP", "from", "the", "domain", "specified", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/ips.go#L81-L87
train
mailgun/mailgun-go
credentials.go
CreateCredential
func (mg *MailgunImpl) CreateCredential(ctx context.Context, login, password string) error { if (login == "") || (password == "") { return ErrEmptyParam } r := newHTTPRequest(generateCredentialsUrl(mg, "")) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) p := newUrlEncodedPayload() p.addValue("login", login) p.addValue("password", password) _, err := makePostRequest(ctx, r, p) return err }
go
func (mg *MailgunImpl) CreateCredential(ctx context.Context, login, password string) error { if (login == "") || (password == "") { return ErrEmptyParam } r := newHTTPRequest(generateCredentialsUrl(mg, "")) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) p := newUrlEncodedPayload() p.addValue("login", login) p.addValue("password", password) _, err := makePostRequest(ctx, r, p) return err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "CreateCredential", "(", "ctx", "context", ".", "Context", ",", "login", ",", "password", "string", ")", "error", "{", "if", "(", "login", "==", "\"\"", ")", "||", "(", "password", "==", "\"\"", ")", "{", "...
// CreateCredential attempts to create associate a new principle with your domain.
[ "CreateCredential", "attempts", "to", "create", "associate", "a", "new", "principle", "with", "your", "domain", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/credentials.go#L178-L190
train
mailgun/mailgun-go
credentials.go
ChangeCredentialPassword
func (mg *MailgunImpl) ChangeCredentialPassword(ctx context.Context, id, password string) error { if (id == "") || (password == "") { return ErrEmptyParam } r := newHTTPRequest(generateCredentialsUrl(mg, id)) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) p := newUrlEncodedPayload() p.addValue("password", password) _, err := makePutRequest(ctx, r, p) return err }
go
func (mg *MailgunImpl) ChangeCredentialPassword(ctx context.Context, id, password string) error { if (id == "") || (password == "") { return ErrEmptyParam } r := newHTTPRequest(generateCredentialsUrl(mg, id)) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) p := newUrlEncodedPayload() p.addValue("password", password) _, err := makePutRequest(ctx, r, p) return err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "ChangeCredentialPassword", "(", "ctx", "context", ".", "Context", ",", "id", ",", "password", "string", ")", "error", "{", "if", "(", "id", "==", "\"\"", ")", "||", "(", "password", "==", "\"\"", ")", "{", ...
// ChangeCredentialPassword attempts to alter the indicated credential's password.
[ "ChangeCredentialPassword", "attempts", "to", "alter", "the", "indicated", "credential", "s", "password", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/credentials.go#L193-L204
train
mailgun/mailgun-go
credentials.go
DeleteCredential
func (mg *MailgunImpl) DeleteCredential(ctx context.Context, id string) error { if id == "" { return ErrEmptyParam } r := newHTTPRequest(generateCredentialsUrl(mg, id)) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) _, err := makeDeleteRequest(ctx, r) return err }
go
func (mg *MailgunImpl) DeleteCredential(ctx context.Context, id string) error { if id == "" { return ErrEmptyParam } r := newHTTPRequest(generateCredentialsUrl(mg, id)) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) _, err := makeDeleteRequest(ctx, r) return err }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "DeleteCredential", "(", "ctx", "context", ".", "Context", ",", "id", "string", ")", "error", "{", "if", "id", "==", "\"\"", "{", "return", "ErrEmptyParam", "\n", "}", "\n", "r", ":=", "newHTTPRequest", "(", ...
// DeleteCredential attempts to remove the indicated principle from the domain.
[ "DeleteCredential", "attempts", "to", "remove", "the", "indicated", "principle", "from", "the", "domain", "." ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/credentials.go#L207-L216
train
mailgun/mailgun-go
template_versions.go
AddTemplateVersion
func (mg *MailgunImpl) AddTemplateVersion(ctx context.Context, templateName string, version *TemplateVersion) error { r := newHTTPRequest(generateApiUrl(mg, templatesEndpoint) + "/" + templateName + "/versions") r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) payload := newUrlEncodedPayload() payload.addValue("template", version.Template) if version.Tag != "" { payload.addValue("tag", string(version.Tag)) } if version.Engine != "" { payload.addValue("engine", string(version.Engine)) } if version.Comment != "" { payload.addValue("comment", version.Comment) } if version.Active { payload.addValue("active", boolToString(version.Active)) } var resp templateResp if err := postResponseFromJSON(ctx, r, payload, &resp); err != nil { return err } *version = resp.Item.Version return nil }
go
func (mg *MailgunImpl) AddTemplateVersion(ctx context.Context, templateName string, version *TemplateVersion) error { r := newHTTPRequest(generateApiUrl(mg, templatesEndpoint) + "/" + templateName + "/versions") r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) payload := newUrlEncodedPayload() payload.addValue("template", version.Template) if version.Tag != "" { payload.addValue("tag", string(version.Tag)) } if version.Engine != "" { payload.addValue("engine", string(version.Engine)) } if version.Comment != "" { payload.addValue("comment", version.Comment) } if version.Active { payload.addValue("active", boolToString(version.Active)) } var resp templateResp if err := postResponseFromJSON(ctx, r, payload, &resp); err != nil { return err } *version = resp.Item.Version return nil }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "AddTemplateVersion", "(", "ctx", "context", ".", "Context", ",", "templateName", "string", ",", "version", "*", "TemplateVersion", ")", "error", "{", "r", ":=", "newHTTPRequest", "(", "generateApiUrl", "(", "mg", ...
// AddTemplateVersion adds a template version to a template
[ "AddTemplateVersion", "adds", "a", "template", "version", "to", "a", "template" ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/template_versions.go#L26-L53
train
mailgun/mailgun-go
template_versions.go
GetTemplateVersion
func (mg *MailgunImpl) GetTemplateVersion(ctx context.Context, templateName, tag string) (TemplateVersion, error) { r := newHTTPRequest(generateApiUrl(mg, templatesEndpoint) + "/" + templateName + "/versions/" + tag) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp templateResp err := getResponseFromJSON(ctx, r, &resp) if err != nil { return TemplateVersion{}, err } return resp.Item.Version, nil }
go
func (mg *MailgunImpl) GetTemplateVersion(ctx context.Context, templateName, tag string) (TemplateVersion, error) { r := newHTTPRequest(generateApiUrl(mg, templatesEndpoint) + "/" + templateName + "/versions/" + tag) r.setClient(mg.Client()) r.setBasicAuth(basicAuthUser, mg.APIKey()) var resp templateResp err := getResponseFromJSON(ctx, r, &resp) if err != nil { return TemplateVersion{}, err } return resp.Item.Version, nil }
[ "func", "(", "mg", "*", "MailgunImpl", ")", "GetTemplateVersion", "(", "ctx", "context", ".", "Context", ",", "templateName", ",", "tag", "string", ")", "(", "TemplateVersion", ",", "error", ")", "{", "r", ":=", "newHTTPRequest", "(", "generateApiUrl", "(", ...
// GetTemplateVersion gets a specific version of a template
[ "GetTemplateVersion", "gets", "a", "specific", "version", "of", "a", "template" ]
df421608b66e7dd4c03112d5bb01525c51f344a2
https://github.com/mailgun/mailgun-go/blob/df421608b66e7dd4c03112d5bb01525c51f344a2/template_versions.go#L56-L67
train