github.com/henvic/wedeploycli@v1.7.6-0.20200319005353-3630f582f284/listinstances/list.go (about)

     1  package listinstances
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"sync"
     7  	"time"
     8  
     9  	"github.com/henvic/uilive"
    10  	"github.com/henvic/wedeploycli/config"
    11  	"github.com/henvic/wedeploycli/formatter"
    12  	"github.com/henvic/wedeploycli/services"
    13  )
    14  
    15  // List services object
    16  type List struct {
    17  	Project         string
    18  	Service         string
    19  	PoolingInterval time.Duration
    20  
    21  	Instances  []services.Instance
    22  	lastError  error
    23  	updated    chan struct{}
    24  	watchMutex sync.RWMutex
    25  
    26  	SelectNumber bool
    27  
    28  	livew     *uilive.Writer
    29  	outStream io.Writer
    30  
    31  	servicesClient *services.Client
    32  
    33  	w *formatter.TabWriter
    34  
    35  	once bool
    36  
    37  	retry int
    38  
    39  	wectx     config.Context
    40  	ctx       context.Context
    41  	selectors []string
    42  }
    43  
    44  // New creates a list using the values of a passed Filter
    45  func New(projectID, serviceID string) *List {
    46  	return &List{
    47  		Project:         projectID,
    48  		Service:         serviceID,
    49  		PoolingInterval: time.Second,
    50  		updated:         make(chan struct{}, 1),
    51  	}
    52  }
    53  
    54  func (l *List) fetch() ([]services.Instance, error) {
    55  	ctx, cancel := context.WithTimeout(l.ctx, 30*time.Second)
    56  	defer cancel()
    57  	return l.servicesClient.Instances(ctx, l.Project, l.Service)
    58  }
    59  
    60  func (l *List) prepare(ctx context.Context, wectx config.Context) {
    61  	l.ctx = ctx
    62  	l.wectx = wectx
    63  
    64  	l.servicesClient = services.New(l.wectx)
    65  
    66  	l.livew = uilive.New()
    67  	l.outStream = l.livew
    68  	l.w = formatter.NewTabWriter(l.outStream)
    69  }
    70  
    71  // Watch list instances
    72  func (l *List) Watch(ctx context.Context, wectx config.Context) {
    73  	l.prepare(ctx, wectx)
    74  
    75  	go l.update()
    76  	l.watch()
    77  }
    78  
    79  // Once runs the list only once
    80  func (l *List) Once(ctx context.Context, wectx config.Context) error {
    81  	l.once = true
    82  
    83  	l.PoolingInterval = time.Minute
    84  	l.prepare(ctx, wectx)
    85  	l.updateHandler()
    86  	l.w.Init(l.outStream)
    87  	l.watchHandler()
    88  
    89  	l.watchMutex.RLock()
    90  	var le = l.lastError
    91  	l.watchMutex.RUnlock()
    92  	return le
    93  }