forked from toolshed/abra
Revert "Revert "feat: backup revolution""
This reverts commit 2c515ce70a
.
This commit is contained in:
@ -14,6 +14,70 @@ import (
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// GetService retrieves a service container based on a label. If prompt is true
|
||||
// and the retrievd count of service containers does not match 1, then a prompt
|
||||
// is presented to let the user choose. An error is returned when no service is
|
||||
// found.
|
||||
func GetServiceByLabel(c context.Context, cl *client.Client, label string, prompt bool) (swarm.Service, error) {
|
||||
services, err := cl.ServiceList(c, types.ServiceListOptions{})
|
||||
if err != nil {
|
||||
return swarm.Service{}, err
|
||||
}
|
||||
|
||||
if len(services) == 0 {
|
||||
return swarm.Service{}, fmt.Errorf("no services deployed?")
|
||||
}
|
||||
|
||||
var matchingServices []swarm.Service
|
||||
for _, service := range services {
|
||||
if enabled, exists := service.Spec.Labels[label]; exists && enabled == "true" {
|
||||
matchingServices = append(matchingServices, service)
|
||||
}
|
||||
}
|
||||
|
||||
if len(matchingServices) == 0 {
|
||||
return swarm.Service{}, fmt.Errorf("no services deployed matching label '%s'?", label)
|
||||
}
|
||||
|
||||
if len(matchingServices) > 1 {
|
||||
var servicesRaw []string
|
||||
for _, service := range matchingServices {
|
||||
serviceName := service.Spec.Name
|
||||
created := formatter.HumanDuration(service.CreatedAt.Unix())
|
||||
servicesRaw = append(servicesRaw, fmt.Sprintf("%s (created %v)", serviceName, created))
|
||||
}
|
||||
|
||||
if !prompt {
|
||||
err := fmt.Errorf("expected 1 service but found %v: %s", len(matchingServices), strings.Join(servicesRaw, " "))
|
||||
return swarm.Service{}, err
|
||||
}
|
||||
|
||||
logrus.Warnf("ambiguous service list received, prompting for input")
|
||||
|
||||
var response string
|
||||
prompt := &survey.Select{
|
||||
Message: "which service are you looking for?",
|
||||
Options: servicesRaw,
|
||||
}
|
||||
|
||||
if err := survey.AskOne(prompt, &response); err != nil {
|
||||
return swarm.Service{}, err
|
||||
}
|
||||
|
||||
chosenService := strings.TrimSpace(strings.Split(response, " ")[0])
|
||||
for _, service := range matchingServices {
|
||||
serviceName := strings.ToLower(service.Spec.Name)
|
||||
if serviceName == chosenService {
|
||||
return service, nil
|
||||
}
|
||||
}
|
||||
|
||||
logrus.Panic("failed to match chosen service")
|
||||
}
|
||||
|
||||
return matchingServices[0], nil
|
||||
}
|
||||
|
||||
// GetService retrieves a service container. If prompt is true and the retrievd
|
||||
// count of service containers does not match 1, then a prompt is presented to
|
||||
// let the user choose. A count of 0 is handled gracefully.
|
||||
|
Reference in New Issue
Block a user