filename
stringlengths 4
198
| content
stringlengths 25
939k
| environment
list | variablearg
list | constarg
list | variableargjson
stringclasses 1
value | constargjson
stringlengths 2
3.9k
| lang
stringclasses 3
values | constargcount
float64 0
129
⌀ | variableargcount
float64 0
0
⌀ | sentence
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|
go/src/github.com/influxdata/platform/tsdb/tsi1/index.go | package tsi1
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"runtime"
"strconv"
"sync"
"sync/atomic"
"unsafe"
"bytes"
"sort"
"github.com/cespare/xxhash"
"github.com/influxdata/influxdb/query"
"github.com/influxdata/influxql"
"github.com/influxdata/platform/models"
"github.com/influxdata/platform/pkg/slices"
"github.com/influxdata/platform/tsdb"
"go.uber.org/zap"
)
// IndexName is the name of the index.
const IndexName = tsdb.TSI1IndexName
// DefaultSeriesIDSetCacheSize is the default number of series ID sets to cache.
const DefaultSeriesIDSetCacheSize = 100
// ErrCompactionInterrupted is returned if compactions are disabled or
// an index is closed while a compaction is occurring.
var ErrCompactionInterrupted = errors.New("tsi1: compaction interrupted")
func init() {
if os.Getenv("INFLUXDB_EXP_TSI_PARTITIONS") != "" {
i, err := strconv.Atoi(os.Getenv("INFLUXDB_EXP_TSI_PARTITIONS"))
if err != nil {
panic(err)
}
DefaultPartitionN = uint64(i)
}
// TODO(edd): To remove when feature finalised.
var err error
if os.Getenv("INFLUXDB_EXP_TSI_CACHING") != "" {
EnableBitsetCache, err = strconv.ParseBool(os.Getenv("INFLUXDB_EXP_TSI_CACHING"))
if err != nil {
panic(err)
}
}
}
// DefaultPartitionN determines how many shards the index will be partitioned into.
//
// NOTE: Currently, this must not be change once a database is created. Further,
// it must also be a power of 2.
//
var DefaultPartitionN uint64 = 8
// EnableBitsetCache determines if bitsets are cached.
var EnableBitsetCache = true
// An IndexOption is a functional option for changing the configuration of
// an Index.
type IndexOption func(i *Index)
// WithPath sets the root path of the Index
var WithPath = func(path string) IndexOption {
return func(i *Index) {
i.path = path
}
}
// DisableCompactions disables compactions on the Index.
var DisableCompactions = func() IndexOption {
return func(i *Index) {
i.disableCompactions = true
}
}
// DisableFsync disables flushing and syncing of underlying files. Primarily this
// impacts the LogFiles. This option can be set when working with the index in
// an offline manner, for cases where a hard failure can be overcome by re-running the tooling.
var DisableFsync = func() IndexOption {
return func(i *Index) {
i.disableFsync = true
}
}
// WithLogFileBufferSize sets the size of the buffer used within LogFiles.
// Typically appending an entry to a LogFile involves writing 11 or 12 bytes, so
// depending on how many new series are being created within a batch, it may
// be appropriate to set this.
var WithLogFileBufferSize = func(sz int) IndexOption {
return func(i *Index) {
if sz > 1<<17 { // 128K
sz = 1 << 17
} else if sz < 1<<12 {
sz = 1 << 12 // 4K (runtime default)
}
i.logfileBufferSize = sz
}
}
// Index represents a collection of layered index files and WAL.
type Index struct {
mu sync.RWMutex
partitions []*Partition
opened bool
tagValueCache *TagValueSeriesIDCache
// The following may be set when initializing an Index.
path string // Root directory of the index partitions.
disableCompactions bool // Initially disables compactions on the index.
maxLogFileSize int64 // Maximum size of a LogFile before it's compacted.
logfileBufferSize int // The size of the buffer used by the LogFile.
disableFsync bool // Disables flushing buffers and fsyning files. Used when working with indexes offline.
logger *zap.Logger // Index's logger.
// The following must be set when initializing an Index.
sfile *tsdb.SeriesFile // series lookup file
database string // Name of database.
// Index's version.
version int
// Number of partitions used by the index.
PartitionN uint64
}
func (i *Index) UniqueReferenceID() uintptr {
return uintptr(unsafe.Pointer(i))
}
// NewIndex returns a new instance of Index.
func NewIndex(sfile *tsdb.SeriesFile, database string, c Config, options ...IndexOption) *Index {
idx := &Index{
tagValueCache: NewTagValueSeriesIDCache(DefaultSeriesIDSetCacheSize),
maxLogFileSize: int64(c.MaxIndexLogFileSize),
logger: zap.NewNop(),
version: Version,
sfile: sfile,
database: database,
PartitionN: DefaultPartitionN,
}
for _, option := range options {
option(idx)
}
return idx
}
// Bytes estimates the memory footprint of this Index, in bytes.
func (i *Index) Bytes() int {
var b int
i.mu.RLock()
b += 24 // mu RWMutex is 24 bytes
b += int(unsafe.Sizeof(i.partitions))
for _, p := range i.partitions {
b += int(unsafe.Sizeof(p)) + p.bytes()
}
b += int(unsafe.Sizeof(i.opened))
b += int(unsafe.Sizeof(i.path)) + len(i.path)
b += int(unsafe.Sizeof(i.disableCompactions))
b += int(unsafe.Sizeof(i.maxLogFileSize))
b += int(unsafe.Sizeof(i.logger))
b += int(unsafe.Sizeof(i.sfile))
// Do not count SeriesFile because it belongs to the code that constructed this Index.
b += int(unsafe.Sizeof(i.database)) + len(i.database)
b += int(unsafe.Sizeof(i.version))
b += int(unsafe.Sizeof(i.PartitionN))
i.mu.RUnlock()
return b
}
// Database returns the name of the database the index was initialized with.
func (i *Index) Database() string {
return i.database
}
// WithLogger sets the logger on the index after it's been created.
//
// It's not safe to call WithLogger after the index has been opened, or before
// it has been closed.
func (i *Index) WithLogger(l *zap.Logger) {
i.logger = l.With(zap.String("index", "tsi"))
}
// Type returns the type of Index this is.
func (i *Index) Type() string { return IndexName }
// SeriesFile returns the series file attached to the index.
func (i *Index) SeriesFile() *tsdb.SeriesFile { return i.sfile }
// SeriesIDSet returns the set of series ids associated with series in this
// index. Any series IDs for series no longer present in the index are filtered out.
func (i *Index) SeriesIDSet() *tsdb.SeriesIDSet {
seriesIDSet := tsdb.NewSeriesIDSet()
others := make([]*tsdb.SeriesIDSet, 0, i.PartitionN)
for _, p := range i.partitions {
others = append(others, p.seriesIDSet)
}
seriesIDSet.Merge(others...)
return seriesIDSet
}
// Open opens the index.
func (i *Index) Open() error {
i.mu.Lock()
defer i.mu.Unlock()
if i.opened {
return errors.New("index already open")
}
// Ensure root exists.
if err := os.MkdirAll(i.path, 0777); err != nil {
return err
}
// Initialize index partitions.
i.partitions = make([]*Partition, i.PartitionN)
for j := 0; j < len(i.partitions); j++ {
p := NewPartition(i.sfile, filepath.Join(i.path, fmt.Sprint(j)))
p.MaxLogFileSize = i.maxLogFileSize
p.nosync = i.disableFsync
p.logbufferSize = i.logfileBufferSize
p.logger = i.logger.With(zap.String("tsi1_partition", fmt.Sprint(j+1)))
i.partitions[j] = p
}
// Open all the Partitions in parallel.
partitionN := len(i.partitions)
n := i.availableThreads()
// Store results.
errC := make(chan error, partitionN)
// Run fn on each partition using a fixed number of goroutines.
var pidx uint32 // Index of maximum Partition being worked on.
for k := 0; k < n; k++ {
go func(k int) {
for {
idx := int(atomic.AddUint32(&pidx, 1) - 1) // Get next partition to work on.
if idx >= partitionN {
return // No more work.
}
err := i.partitions[idx].Open()
errC <- err
}
}(k)
}
// Check for error
for i := 0; i < partitionN; i++ {
if err := <-errC; err != nil {
return err
}
}
// Mark opened.
i.opened = true
i.logger.Info("Index opened", zap.Int("partitions", partitionN))
return nil
}
// Compact requests a compaction of partitions.
func (i *Index) Compact() {
i.mu.Lock()
defer i.mu.Unlock()
for _, p := range i.partitions {
p.Compact()
}
}
func (i *Index) EnableCompactions() {
for _, p := range i.partitions {
p.EnableCompactions()
}
}
func (i *Index) DisableCompactions() {
for _, p := range i.partitions {
p.DisableCompactions()
}
}
// Wait blocks until all outstanding compactions have completed.
func (i *Index) Wait() {
for _, p := range i.partitions {
p.Wait()
}
}
// Close closes the index.
func (i *Index) Close() error {
// Lock index and close partitions.
i.mu.Lock()
defer i.mu.Unlock()
for _, p := range i.partitions {
if err := p.Close(); err != nil {
return err
}
}
// Mark index as closed.
i.opened = false
return nil
}
// Path returns the path the index was opened with.
func (i *Index) Path() string { return i.path }
// PartitionAt returns the partition by index.
func (i *Index) PartitionAt(index int) *Partition {
return i.partitions[index]
}
// partition returns the appropriate Partition for a provided series key.
func (i *Index) partition(key []byte) *Partition {
return i.partitions[int(xxhash.Sum64(key)&(i.PartitionN-1))]
}
// partitionIdx returns the index of the partition that key belongs in.
func (i *Index) partitionIdx(key []byte) int {
return int(xxhash.Sum64(key) & (i.PartitionN - 1))
}
// availableThreads returns the minimum of GOMAXPROCS and the number of
// partitions in the Index.
func (i *Index) availableThreads() int {
n := runtime.GOMAXPROCS(0)
if len(i.partitions) < n {
return len(i.partitions)
}
return n
}
// ForEachMeasurementName iterates over all measurement names in the index,
// applying fn. It returns the first error encountered, if any.
//
// ForEachMeasurementName does not call fn on each partition concurrently so the
// call may provide a non-goroutine safe fn.
func (i *Index) ForEachMeasurementName(fn func(name []byte) error) error {
itr, err := i.MeasurementIterator()
if err != nil {
return err
} else if itr == nil {
return nil
}
defer itr.Close()
// Iterate over all measurements.
for {
e, err := itr.Next()
if err != nil {
return err
} else if e == nil {
break
}
if err := fn(e); err != nil {
return err
}
}
return nil
}
// MeasurementExists returns true if a measurement exists.
func (i *Index) MeasurementExists(name []byte) (bool, error) {
n := i.availableThreads()
// Store errors
var found uint32 // Use this to signal we found the measurement.
errC := make(chan error, i.PartitionN)
// Check each partition for the measurement concurrently.
var pidx uint32 // Index of maximum Partition being worked on.
for k := 0; k < n; k++ {
go func() {
for {
idx := int(atomic.AddUint32(&pidx, 1) - 1) // Get next partition to check
if idx >= len(i.partitions) {
return // No more work.
}
// Check if the measurement has been found. If it has don't
// need to check this partition and can just move on.
if atomic.LoadUint32(&found) == 1 {
errC <- nil
continue
}
b, err := i.partitions[idx].MeasurementExists(name)
if b {
atomic.StoreUint32(&found, 1)
}
errC <- err
}
}()
}
// Check for error
for i := 0; i < cap(errC); i++ {
if err := <-errC; err != nil {
return false, err
}
}
// Check if we found the measurement.
return atomic.LoadUint32(&found) == 1, nil
}
// MeasurementHasSeries returns true if a measurement has non-tombstoned series.
func (i *Index) MeasurementHasSeries(name []byte) (bool, error) {
for _, p := range i.partitions {
if v, err := p.MeasurementHasSeries(name); err != nil {
return false, err
} else if v {
return true, nil
}
}
return false, nil
}
// fetchByteValues is a helper for gathering values from each partition in the index,
// based on some criteria.
//
// fn is a function that works on partition idx and calls into some method on
// the partition that returns some ordered values.
func (i *Index) fetchByteValues(fn func(idx int) ([][]byte, error)) ([][]byte, error) {
n := i.availableThreads()
// Store results.
names := make([][][]byte, i.PartitionN)
errC := make(chan error, i.PartitionN)
var pidx uint32 // Index of maximum Partition being worked on.
for k := 0; k < n; k++ {
go func() {
for {
idx := int(atomic.AddUint32(&pidx, 1) - 1) // Get next partition to work on.
if idx >= len(i.partitions) {
return // No more work.
}
pnames, err := fn(idx)
// This is safe since there are no readers on names until all
// the writers are done.
names[idx] = pnames
errC <- err
}
}()
}
// Check for error
for i := 0; i < cap(errC); i++ {
if err := <-errC; err != nil {
return nil, err
}
}
// It's now safe to read from names.
return slices.MergeSortedBytes(names[:]...), nil
}
// MeasurementIterator returns an iterator over all measurements.
func (i *Index) MeasurementIterator() (tsdb.MeasurementIterator, error) {
itrs := make([]tsdb.MeasurementIterator, 0, len(i.partitions))
for _, p := range i.partitions {
itr, err := p.MeasurementIterator()
if err != nil {
tsdb.MeasurementIterators(itrs).Close()
return nil, err
} else if itr != nil {
itrs = append(itrs, itr)
}
}
return tsdb.MergeMeasurementIterators(itrs...), nil
}
func (i *Index) MeasurementSeriesByExprIterator(name []byte, expr influxql.Expr) (tsdb.SeriesIDIterator, error) {
return i.measurementSeriesByExprIterator(name, expr)
}
// measurementSeriesByExprIterator returns a series iterator for a measurement
// that is filtered by expr. See MeasurementSeriesByExprIterator for more details.
//
// measurementSeriesByExprIterator guarantees to never take any locks on the
// series file.
func (i *Index) measurementSeriesByExprIterator(name []byte, expr influxql.Expr) (tsdb.SeriesIDIterator, error) {
// Return all series for the measurement if there are no tag expressions.
release := i.sfile.Retain()
defer release()
if expr == nil {
itr, err := i.measurementSeriesIDIterator(name)
if err != nil {
return nil, err
}
return tsdb.FilterUndeletedSeriesIDIterator(i.sfile, itr), nil
}
itr, err := i.seriesByExprIterator(name, expr)
if err != nil {
return nil, err
}
return tsdb.FilterUndeletedSeriesIDIterator(i.sfile, itr), nil
}
// MeasurementSeriesIDIterator returns an iterator over all non-tombstoned series
// for the provided measurement.
func (i *Index) MeasurementSeriesIDIterator(name []byte) (tsdb.SeriesIDIterator, error) {
itr, err := i.measurementSeriesIDIterator(name)
if err != nil {
return nil, err
}
release := i.sfile.Retain()
defer release()
return tsdb.FilterUndeletedSeriesIDIterator(i.sfile, itr), nil
}
// measurementSeriesIDIterator returns an iterator over all series in a measurement.
func (i *Index) measurementSeriesIDIterator(name []byte) (tsdb.SeriesIDIterator, error) {
itrs := make([]tsdb.SeriesIDIterator, 0, len(i.partitions))
for _, p := range i.partitions {
itr, err := p.MeasurementSeriesIDIterator(name)
if err != nil {
tsdb.SeriesIDIterators(itrs).Close()
return nil, err
} else if itr != nil {
itrs = append(itrs, itr)
}
}
return tsdb.MergeSeriesIDIterators(itrs...), nil
}
// MeasurementNamesByRegex returns measurement names for the provided regex.
func (i *Index) MeasurementNamesByRegex(re *regexp.Regexp) ([][]byte, error) {
return i.fetchByteValues(func(idx int) ([][]byte, error) {
return i.partitions[idx].MeasurementNamesByRegex(re)
})
}
// DropMeasurement deletes a measurement from the index. It returns the first
// error encountered, if any.
func (i *Index) DropMeasurement(name []byte) error {
n := i.availableThreads()
// Store results.
errC := make(chan error, i.PartitionN)
var pidx uint32 // Index of maximum Partition being worked on.
for k := 0; k < n; k++ {
go func() {
for {
idx := int(atomic.AddUint32(&pidx, 1) - 1) // Get next partition to work on.
if idx >= len(i.partitions) {
return // No more work.
}
errC <- i.partitions[idx].DropMeasurement(name)
}
}()
}
// Check for error
for i := 0; i < cap(errC); i++ {
if err := <-errC; err != nil {
return err
}
}
return nil
}
// CreateSeriesListIfNotExists creates a list of series if they doesn't exist in bulk.
func (i *Index) CreateSeriesListIfNotExists(collection *tsdb.SeriesCollection) error {
// Create the series list on the series file first. This validates all of the types for
// the collection.
err := i.sfile.CreateSeriesListIfNotExists(collection)
if err != nil {
return err
}
// We need to move different series into collections for each partition
// to process.
pCollections := make([]tsdb.SeriesCollection, i.PartitionN)
// Determine partition for series using each series key.
for iter := collection.Iterator(); iter.Next(); {
pCollection := &pCollections[i.partitionIdx(iter.Key())]
pCollection.Names = append(pCollection.Names, iter.Name())
pCollection.Tags = append(pCollection.Tags, iter.Tags())
pCollection.SeriesIDs = append(pCollection.SeriesIDs, iter.SeriesID())
}
// Process each subset of series on each partition.
n := i.availableThreads()
// Store errors.
errC := make(chan error, i.PartitionN)
var pidx uint32 // Index of maximum Partition being worked on.
for k := 0; k < n; k++ {
go func() {
i.mu.RLock()
partitionN := len(i.partitions)
i.mu.RUnlock()
for {
idx := int(atomic.AddUint32(&pidx, 1) - 1) // Get next partition to work on.
if idx >= partitionN {
return // No more work.
}
i.mu.RLock()
partition := i.partitions[idx]
i.mu.RUnlock()
ids, err := partition.createSeriesListIfNotExists(&pCollections[idx])
if len(ids) == 0 {
errC <- err
continue
}
// Some cached bitset results may need to be updated.
i.tagValueCache.RLock()
for j, id := range ids {
if id.IsZero() {
continue
}
name := pCollections[idx].Names[j]
tags := pCollections[idx].Tags[j]
if i.tagValueCache.measurementContainsSets(name) {
for _, pair := range tags {
// TODO(edd): It's not clear to me yet whether it will be better to take a lock
// on every series id set, or whether to gather them all up under the cache rlock
// and then take the cache lock and update them all at once (without invoking a lock
// on each series id set).
//
// Taking the cache lock will block all queries, but is one lock. Taking each series set
// lock might be many lock/unlocks but will only block a query that needs that particular set.
//
// Need to think on it, but I think taking a lock on each series id set is the way to go.
//
// One other option here is to take a lock on the series id set when we first encounter it
// and then keep it locked until we're done with all the ids.
//
// Note: this will only add `id` to the set if it exists.
i.tagValueCache.addToSet(name, pair.Key, pair.Value, id) // Takes a lock on the series id set
}
}
}
i.tagValueCache.RUnlock()
errC <- err
}
}()
}
// Check for error
for i := 0; i < cap(errC); i++ {
if err := <-errC; err != nil {
return err
}
}
return nil
}
// CreateSeriesIfNotExists creates a series if it doesn't exist or is deleted.
// TODO(edd): This should go.
func (i *Index) CreateSeriesIfNotExists(key, name []byte, tags models.Tags, typ models.FieldType) error {
collection := &tsdb.SeriesCollection{
Keys: [][]byte{key},
Names: [][]byte{name},
Tags: []models.Tags{tags},
Types: []models.FieldType{typ},
}
err := i.sfile.CreateSeriesListIfNotExists(collection)
if err != nil {
return err
}
ids, err := i.partition(key).createSeriesListIfNotExists(collection)
if err != nil {
return err
}
if len(ids) == 0 || ids[0].IsZero() {
return nil // No new series, nothing further to update.
}
// If there are cached sets for any of the tag pairs, they will need to be
// updated with the series id.
i.tagValueCache.RLock()
if i.tagValueCache.measurementContainsSets(name) {
for _, pair := range tags {
// TODO(edd): It's not clear to me yet whether it will be better to take a lock
// on every series id set, or whether to gather them all up under the cache rlock
// and then take the cache lock and update them all at once (without invoking a lock
// on each series id set).
//
// Taking the cache lock will block all queries, but is one lock. Taking each series set
// lock might be many lock/unlocks but will only block a query that needs that particular set.
//
// Need to think on it, but I think taking a lock on each series id set is the way to go.
//
// Note this will only add `id` to the set if it exists.
i.tagValueCache.addToSet(name, pair.Key, pair.Value, ids[0]) // Takes a lock on the series id set
}
}
i.tagValueCache.RUnlock()
return nil
}
// InitializeSeries is a no-op. This only applies to the in-memory index.
func (i *Index) InitializeSeries(*tsdb.SeriesCollection) error {
return nil
}
// DropSeries drops the provided series from the index. If cascade is true
// and this is the last series to the measurement, the measurment will also be dropped.
func (i *Index) DropSeries(seriesID tsdb.SeriesID, key []byte, cascade bool) error {
// Remove from partition.
if err := i.partition(key).DropSeries(seriesID); err != nil {
return err
}
if !cascade {
return nil
}
// Extract measurement name & tags.
name, tags := models.ParseKeyBytes(key)
// If there are cached sets for any of the tag pairs, they will need to be
// updated with the series id.
i.tagValueCache.RLock()
if i.tagValueCache.measurementContainsSets(name) {
for _, pair := range tags {
i.tagValueCache.delete(name, pair.Key, pair.Value, seriesID) // Takes a lock on the series id set
}
}
i.tagValueCache.RUnlock()
// Check if that was the last series for the measurement in the entire index.
if ok, err := i.MeasurementHasSeries(name); err != nil {
return err
} else if ok {
return nil
}
// If no more series exist in the measurement then delete the measurement.
if err := i.DropMeasurement(name); err != nil {
return err
}
return nil
}
// DropSeriesGlobal is a no-op on the tsi1 index.
func (i *Index) DropSeriesGlobal(key []byte) error { return nil }
// DropMeasurementIfSeriesNotExist drops a measurement only if there are no more
// series for the measurment.
func (i *Index) DropMeasurementIfSeriesNotExist(name []byte) error {
// Check if that was the last series for the measurement in the entire index.
if ok, err := i.MeasurementHasSeries(name); err != nil {
return err
} else if ok {
return nil
}
// If no more series exist in the measurement then delete the measurement.
return i.DropMeasurement(name)
}
// SeriesN returns the series cardinality in the index. It is the sum of all
// partition cardinalities.
func (i *Index) SeriesN() int64 {
var total int64
for _, p := range i.partitions {
total += int64(p.seriesIDSet.Cardinality())
}
return total
}
// HasTagKey returns true if tag key exists. It returns the first error
// encountered if any.
func (i *Index) HasTagKey(name, key []byte) (bool, error) {
n := i.availableThreads()
// Store errors
var found uint32 // Use this to signal we found the tag key.
errC := make(chan error, i.PartitionN)
// Check each partition for the tag key concurrently.
var pidx uint32 // Index of maximum Partition being worked on.
for k := 0; k < n; k++ {
go func() {
for {
idx := int(atomic.AddUint32(&pidx, 1) - 1) // Get next partition to check
if idx >= len(i.partitions) {
return // No more work.
}
// Check if the tag key has already been found. If it has, we
// don't need to check this partition and can just move on.
if atomic.LoadUint32(&found) == 1 {
errC <- nil
continue
}
b, err := i.partitions[idx].HasTagKey(name, key)
if b {
atomic.StoreUint32(&found, 1)
}
errC <- err
}
}()
}
// Check for error
for i := 0; i < cap(errC); i++ {
if err := <-errC; err != nil {
return false, err
}
}
// Check if we found the tag key.
return atomic.LoadUint32(&found) == 1, nil
}
// HasTagValue returns true if tag value exists.
func (i *Index) HasTagValue(name, key, value []byte) (bool, error) {
n := i.availableThreads()
// Store errors
var found uint32 // Use this to signal we found the tag key.
errC := make(chan error, i.PartitionN)
// Check each partition for the tag key concurrently.
var pidx uint32 // Index of maximum Partition being worked on.
for k := 0; k < n; k++ {
go func() {
for {
idx := int(atomic.AddUint32(&pidx, 1) - 1) // Get next partition to check
if idx >= len(i.partitions) {
return // No more work.
}
// Check if the tag key has already been found. If it has, we
// don't need to check this partition and can just move on.
if atomic.LoadUint32(&found) == 1 {
errC <- nil
continue
}
b, err := i.partitions[idx].HasTagValue(name, key, value)
if b {
atomic.StoreUint32(&found, 1)
}
errC <- err
}
}()
}
// Check for error
for i := 0; i < cap(errC); i++ {
if err := <-errC; err != nil {
return false, err
}
}
// Check if we found the tag key.
return atomic.LoadUint32(&found) == 1, nil
}
// TagKeyIterator returns an iterator for all keys across a single measurement.
func (i *Index) TagKeyIterator(name []byte) (tsdb.TagKeyIterator, error) {
a := make([]tsdb.TagKeyIterator, 0, len(i.partitions))
for _, p := range i.partitions {
itr := p.TagKeyIterator(name)
if itr != nil {
a = append(a, itr)
}
}
return tsdb.MergeTagKeyIterators(a...), nil
}
// TagValueIterator returns an iterator for all values across a single key.
func (i *Index) TagValueIterator(name, key []byte) (tsdb.TagValueIterator, error) {
a := make([]tsdb.TagValueIterator, 0, len(i.partitions))
for _, p := range i.partitions {
itr := p.TagValueIterator(name, key)
if itr != nil {
a = append(a, itr)
}
}
return tsdb.MergeTagValueIterators(a...), nil
}
// TagKeySeriesIDIterator returns a series iterator for all values across a single key.
func (i *Index) TagKeySeriesIDIterator(name, key []byte) (tsdb.SeriesIDIterator, error) {
release := i.sfile.Retain()
defer release()
itr, err := i.tagKeySeriesIDIterator(name, key)
if err != nil {
return nil, err
}
return tsdb.FilterUndeletedSeriesIDIterator(i.sfile, itr), nil
}
// tagKeySeriesIDIterator returns a series iterator for all values across a single key.
func (i *Index) tagKeySeriesIDIterator(name, key []byte) (tsdb.SeriesIDIterator, error) {
a := make([]tsdb.SeriesIDIterator, 0, len(i.partitions))
for _, p := range i.partitions {
itr := p.TagKeySeriesIDIterator(name, key)
if itr != nil {
a = append(a, itr)
}
}
return tsdb.MergeSeriesIDIterators(a...), nil
}
// TagValueSeriesIDIterator returns a series iterator for a single tag value.
func (i *Index) TagValueSeriesIDIterator(name, key, value []byte) (tsdb.SeriesIDIterator, error) {
release := i.sfile.Retain()
defer release()
itr, err := i.tagValueSeriesIDIterator(name, key, value)
if err != nil {
return nil, err
}
return tsdb.FilterUndeletedSeriesIDIterator(i.sfile, itr), nil
}
// tagValueSeriesIDIterator returns a series iterator for a single tag value.
func (i *Index) tagValueSeriesIDIterator(name, key, value []byte) (tsdb.SeriesIDIterator, error) {
// Check series ID set cache...
if EnableBitsetCache {
if ss := i.tagValueCache.Get(name, key, value); ss != nil {
// Return a clone because the set is mutable.
return tsdb.NewSeriesIDSetIterator(ss.Clone()), nil
}
}
a := make([]tsdb.SeriesIDIterator, 0, len(i.partitions))
for _, p := range i.partitions {
itr, err := p.TagValueSeriesIDIterator(name, key, value)
if err != nil {
return nil, err
} else if itr != nil {
a = append(a, itr)
}
}
itr := tsdb.MergeSeriesIDIterators(a...)
if !EnableBitsetCache {
return itr, nil
}
// Check if the iterator contains only series id sets. Cache them...
if ssitr, ok := itr.(tsdb.SeriesIDSetIterator); ok {
ss := ssitr.SeriesIDSet()
ss.SetCOW(true) // This is important to speed the clone up.
i.tagValueCache.Put(name, key, value, ss)
}
return itr, nil
}
func (i *Index) TagSets(name []byte, opt query.IteratorOptions) ([]*query.TagSet, error) {
release := i.sfile.Retain()
defer release()
itr, err := i.MeasurementSeriesByExprIterator(name, opt.Condition)
if err != nil {
return nil, err
} else if itr == nil {
return nil, nil
}
defer itr.Close()
// measurementSeriesByExprIterator filters deleted series IDs; no need to
// do so here.
var dims []string
if len(opt.Dimensions) > 0 {
dims = make([]string, len(opt.Dimensions))
copy(dims, opt.Dimensions)
sort.Strings(dims)
}
// For every series, get the tag values for the requested tag keys i.e.
// dimensions. This is the TagSet for that series. Series with the same
// TagSet are then grouped together, because for the purpose of GROUP BY
// they are part of the same composite series.
tagSets := make(map[string]*query.TagSet, 64)
var seriesN, maxSeriesN int
if opt.MaxSeriesN > 0 {
maxSeriesN = opt.MaxSeriesN
} else {
maxSeriesN = int(^uint(0) >> 1)
}
// The tag sets require a string for each series key in the set, The series
// file formatted keys need to be parsed into models format. Since they will
// end up as strings we can re-use an intermediate buffer for this process.
var keyBuf []byte
var tagsBuf models.Tags // Buffer for tags. Tags are not needed outside of each loop iteration.
for {
se, err := itr.Next()
if err != nil {
return nil, err
} else if se.SeriesID.IsZero() {
break
}
// Skip if the series has been tombstoned.
key := i.sfile.SeriesKey(se.SeriesID)
if len(key) == 0 {
continue
}
if seriesN&0x3fff == 0x3fff {
// check every 16384 series if the query has been canceled
select {
case <-opt.InterruptCh:
return nil, query.ErrQueryInterrupted
default:
}
}
if seriesN > maxSeriesN {
return nil, fmt.Errorf("max-select-series limit exceeded: (%d/%d)", seriesN, opt.MaxSeriesN)
}
// NOTE - must not escape this loop iteration.
_, tagsBuf = tsdb.ParseSeriesKeyInto(key, tagsBuf)
var tagsAsKey []byte
if len(dims) > 0 {
tagsAsKey = tsdb.MakeTagsKey(dims, tagsBuf)
}
tagSet, ok := tagSets[string(tagsAsKey)]
if !ok {
// This TagSet is new, create a new entry for it.
tagSet = &query.TagSet{
Tags: nil,
Key: tagsAsKey,
}
}
// Associate the series and filter with the Tagset.
keyBuf = models.AppendMakeKey(keyBuf, name, tagsBuf)
tagSet.AddFilter(string(keyBuf), se.Expr)
keyBuf = keyBuf[:0]
// Ensure it's back in the map.
tagSets[string(tagsAsKey)] = tagSet
seriesN++
}
// Sort the series in each tag set.
for _, t := range tagSets {
sort.Sort(t)
}
// The TagSets have been created, as a map of TagSets. Just send
// the values back as a slice, sorting for consistency.
sortedTagsSets := make([]*query.TagSet, 0, len(tagSets))
for _, v := range tagSets {
sortedTagsSets = append(sortedTagsSets, v)
}
sort.Sort(tsdb.ByTagKey(sortedTagsSets))
return sortedTagsSets, nil
}
// MeasurementTagKeysByExpr extracts the tag keys wanted by the expression.
func (i *Index) MeasurementTagKeysByExpr(name []byte, expr influxql.Expr) (map[string]struct{}, error) {
n := i.availableThreads()
// Store results.
keys := make([]map[string]struct{}, i.PartitionN)
errC := make(chan error, i.PartitionN)
var pidx uint32 // Index of maximum Partition being worked on.
for k := 0; k < n; k++ {
go func() {
for {
idx := int(atomic.AddUint32(&pidx, 1) - 1) // Get next partition to work on.
if idx >= len(i.partitions) {
return // No more work.
}
// This is safe since there are no readers on keys until all
// the writers are done.
tagKeys, err := i.partitions[idx].MeasurementTagKeysByExpr(name, expr)
keys[idx] = tagKeys
errC <- err
}
}()
}
// Check for error
for i := 0; i < cap(errC); i++ {
if err := <-errC; err != nil {
return nil, err
}
}
// Merge into single map.
result := keys[0]
for k := 1; k < len(i.partitions); k++ {
for k := range keys[k] {
result[k] = struct{}{}
}
}
return result, nil
}
// DiskSizeBytes returns the size of the index on disk.
func (i *Index) DiskSizeBytes() int64 {
fs, err := i.RetainFileSet()
if err != nil {
i.logger.Warn("Index is closing down")
return 0
}
defer fs.Release()
var manifestSize int64
// Get MANIFEST sizes from each partition.
for _, p := range i.partitions {
manifestSize += p.manifestSize
}
return fs.Size() + manifestSize
}
// TagKeyCardinality always returns zero.
// It is not possible to determine cardinality of tags across index files, and
// thus it cannot be done across partitions.
func (i *Index) TagKeyCardinality(name, key []byte) int {
return 0
}
// RetainFileSet returns the set of all files across all partitions.
// This is only needed when all files need to be retained for an operation.
func (i *Index) RetainFileSet() (*FileSet, error) {
i.mu.RLock()
defer i.mu.RUnlock()
fs, _ := NewFileSet(nil, i.sfile, nil)
for _, p := range i.partitions {
pfs, err := p.RetainFileSet()
if err != nil {
fs.Close()
return nil, err
}
fs.files = append(fs.files, pfs.files...)
}
return fs, nil
}
// SetFieldName is a no-op on this index.
func (i *Index) SetFieldName(measurement []byte, name string) {}
// Rebuild rebuilds an index. It's a no-op for this index.
func (i *Index) Rebuild() {}
// MeasurementCardinalityStats returns cardinality stats for all measurements.
func (i *Index) MeasurementCardinalityStats() MeasurementCardinalityStats {
i.mu.RLock()
defer i.mu.RUnlock()
stats := NewMeasurementCardinalityStats()
for _, p := range i.partitions {
stats.Add(p.MeasurementCardinalityStats())
}
return stats
}
func (i *Index) seriesByExprIterator(name []byte, expr influxql.Expr) (tsdb.SeriesIDIterator, error) {
switch expr := expr.(type) {
case *influxql.BinaryExpr:
switch expr.Op {
case influxql.AND, influxql.OR:
// Get the series IDs and filter expressions for the LHS.
litr, err := i.seriesByExprIterator(name, expr.LHS)
if err != nil {
return nil, err
}
// Get the series IDs and filter expressions for the RHS.
ritr, err := i.seriesByExprIterator(name, expr.RHS)
if err != nil {
if litr != nil {
litr.Close()
}
return nil, err
}
// Intersect iterators if expression is "AND".
if expr.Op == influxql.AND {
return tsdb.IntersectSeriesIDIterators(litr, ritr), nil
}
// Union iterators if expression is "OR".
return tsdb.UnionSeriesIDIterators(litr, ritr), nil
default:
return i.seriesByBinaryExprIterator(name, expr)
}
case *influxql.ParenExpr:
return i.seriesByExprIterator(name, expr.Expr)
case *influxql.BooleanLiteral:
if expr.Val {
return i.measurementSeriesIDIterator(name)
}
return nil, nil
default:
return nil, nil
}
}
// seriesByBinaryExprIterator returns a series iterator and a filtering expression.
func (i *Index) seriesByBinaryExprIterator(name []byte, n *influxql.BinaryExpr) (tsdb.SeriesIDIterator, error) {
// If this binary expression has another binary expression, then this
// is some expression math and we should just pass it to the underlying query.
if _, ok := n.LHS.(*influxql.BinaryExpr); ok {
itr, err := i.measurementSeriesIDIterator(name)
if err != nil {
return nil, err
}
return tsdb.NewSeriesIDExprIterator(itr, n), nil
} else if _, ok := n.RHS.(*influxql.BinaryExpr); ok {
itr, err := i.measurementSeriesIDIterator(name)
if err != nil {
return nil, err
}
return tsdb.NewSeriesIDExprIterator(itr, n), nil
}
// Retrieve the variable reference from the correct side of the expression.
key, ok := n.LHS.(*influxql.VarRef)
value := n.RHS
if !ok {
key, ok = n.RHS.(*influxql.VarRef)
if !ok {
// This is an expression we do not know how to evaluate. Let the
// query engine take care of this.
itr, err := i.measurementSeriesIDIterator(name)
if err != nil {
return nil, err
}
return tsdb.NewSeriesIDExprIterator(itr, n), nil
}
value = n.LHS
}
// For fields, return all series from this measurement.
if key.Val != "_name" && (key.Type == influxql.AnyField || (key.Type != influxql.Tag && key.Type != influxql.Unknown)) {
itr, err := i.measurementSeriesIDIterator(name)
if err != nil {
return nil, err
}
return tsdb.NewSeriesIDExprIterator(itr, n), nil
} else if value, ok := value.(*influxql.VarRef); ok {
// Check if the RHS is a variable and if it is a field.
if value.Val != "_name" && (key.Type == influxql.AnyField || (value.Type != influxql.Tag && value.Type != influxql.Unknown)) {
itr, err := i.measurementSeriesIDIterator(name)
if err != nil {
return nil, err
}
return tsdb.NewSeriesIDExprIterator(itr, n), nil
}
}
// Create iterator based on value type.
switch value := value.(type) {
case *influxql.StringLiteral:
return i.seriesByBinaryExprStringIterator(name, []byte(key.Val), []byte(value.Val), n.Op)
case *influxql.RegexLiteral:
return i.seriesByBinaryExprRegexIterator(name, []byte(key.Val), value.Val, n.Op)
case *influxql.VarRef:
return i.seriesByBinaryExprVarRefIterator(name, []byte(key.Val), value, n.Op)
default:
// We do not know how to evaluate this expression so pass it
// on to the query engine.
itr, err := i.measurementSeriesIDIterator(name)
if err != nil {
return nil, err
}
return tsdb.NewSeriesIDExprIterator(itr, n), nil
}
}
func (i *Index) seriesByBinaryExprStringIterator(name, key, value []byte, op influxql.Token) (tsdb.SeriesIDIterator, error) {
// Special handling for "_name" to match measurement name.
if bytes.Equal(key, []byte("_name")) {
if (op == influxql.EQ && bytes.Equal(value, name)) || (op == influxql.NEQ && !bytes.Equal(value, name)) {
return i.measurementSeriesIDIterator(name)
}
return nil, nil
}
if op == influxql.EQ {
// Match a specific value.
if len(value) != 0 {
return i.tagValueSeriesIDIterator(name, key, value)
}
mitr, err := i.measurementSeriesIDIterator(name)
if err != nil {
return nil, err
}
kitr, err := i.tagKeySeriesIDIterator(name, key)
if err != nil {
if mitr != nil {
mitr.Close()
}
return nil, err
}
// Return all measurement series that have no values from this tag key.
return tsdb.DifferenceSeriesIDIterators(mitr, kitr), nil
}
// Return all measurement series without this tag value.
if len(value) != 0 {
mitr, err := i.measurementSeriesIDIterator(name)
if err != nil {
return nil, err
}
vitr, err := i.tagValueSeriesIDIterator(name, key, value)
if err != nil {
if mitr != nil {
mitr.Close()
}
return nil, err
}
return tsdb.DifferenceSeriesIDIterators(mitr, vitr), nil
}
// Return all series across all values of this tag key.
return i.tagKeySeriesIDIterator(name, key)
}
func (i *Index) seriesByBinaryExprRegexIterator(name, key []byte, value *regexp.Regexp, op influxql.Token) (tsdb.SeriesIDIterator, error) {
// Special handling for "_name" to match measurement name.
if bytes.Equal(key, []byte("_name")) {
match := value.Match(name)
if (op == influxql.EQREGEX && match) || (op == influxql.NEQREGEX && !match) {
mitr, err := i.measurementSeriesIDIterator(name)
if err != nil {
return nil, err
}
return tsdb.NewSeriesIDExprIterator(mitr, &influxql.BooleanLiteral{Val: true}), nil
}
return nil, nil
}
return i.matchTagValueSeriesIDIterator(name, key, value, op == influxql.EQREGEX)
}
func (i *Index) seriesByBinaryExprVarRefIterator(name, key []byte, value *influxql.VarRef, op influxql.Token) (tsdb.SeriesIDIterator, error) {
itr0, err := i.tagKeySeriesIDIterator(name, key)
if err != nil {
return nil, err
}
itr1, err := i.tagKeySeriesIDIterator(name, []byte(value.Val))
if err != nil {
if itr0 != nil {
itr0.Close()
}
return nil, err
}
if op == influxql.EQ {
return tsdb.IntersectSeriesIDIterators(itr0, itr1), nil
}
return tsdb.DifferenceSeriesIDIterators(itr0, itr1), nil
}
// MatchTagValueSeriesIDIterator returns a series iterator for tags which match value.
// If matches is false, returns iterators which do not match value.
func (i *Index) MatchTagValueSeriesIDIterator(name, key []byte, value *regexp.Regexp, matches bool) (tsdb.SeriesIDIterator, error) {
release := i.sfile.Retain()
defer release()
itr, err := i.matchTagValueSeriesIDIterator(name, key, value, matches)
if err != nil {
return nil, err
}
return tsdb.FilterUndeletedSeriesIDIterator(i.sfile, itr), nil
}
// matchTagValueSeriesIDIterator returns a series iterator for tags which match
// value. See MatchTagValueSeriesIDIterator for more details.
//
// It guarantees to never take any locks on the underlying series file.
func (i *Index) matchTagValueSeriesIDIterator(name, key []byte, value *regexp.Regexp, matches bool) (tsdb.SeriesIDIterator, error) {
matchEmpty := value.MatchString("")
if matches {
if matchEmpty {
return i.matchTagValueEqualEmptySeriesIDIterator(name, key, value)
}
return i.matchTagValueEqualNotEmptySeriesIDIterator(name, key, value)
}
if matchEmpty {
return i.matchTagValueNotEqualEmptySeriesIDIterator(name, key, value)
}
return i.matchTagValueNotEqualNotEmptySeriesIDIterator(name, key, value)
}
func (i *Index) matchTagValueEqualEmptySeriesIDIterator(name, key []byte, value *regexp.Regexp) (tsdb.SeriesIDIterator, error) {
vitr, err := i.TagValueIterator(name, key)
if err != nil {
return nil, err
} else if vitr == nil {
return i.measurementSeriesIDIterator(name)
}
defer vitr.Close()
var itrs []tsdb.SeriesIDIterator
if err := func() error {
for {
e, err := vitr.Next()
if err != nil {
return err
} else if e == nil {
break
}
if !value.Match(e) {
itr, err := i.tagValueSeriesIDIterator(name, key, e)
if err != nil {
return err
} else if itr != nil {
itrs = append(itrs, itr)
}
}
}
return nil
}(); err != nil {
tsdb.SeriesIDIterators(itrs).Close()
return nil, err
}
mitr, err := i.measurementSeriesIDIterator(name)
if err != nil {
tsdb.SeriesIDIterators(itrs).Close()
return nil, err
}
return tsdb.DifferenceSeriesIDIterators(mitr, tsdb.MergeSeriesIDIterators(itrs...)), nil
}
func (i *Index) matchTagValueEqualNotEmptySeriesIDIterator(name, key []byte, value *regexp.Regexp) (tsdb.SeriesIDIterator, error) {
vitr, err := i.TagValueIterator(name, key)
if err != nil {
return nil, err
} else if vitr == nil {
return nil, nil
}
defer vitr.Close()
var itrs []tsdb.SeriesIDIterator
for {
e, err := vitr.Next()
if err != nil {
tsdb.SeriesIDIterators(itrs).Close()
return nil, err
} else if e == nil {
break
}
if value.Match(e) {
itr, err := i.tagValueSeriesIDIterator(name, key, e)
if err != nil {
tsdb.SeriesIDIterators(itrs).Close()
return nil, err
} else if itr != nil {
itrs = append(itrs, itr)
}
}
}
return tsdb.MergeSeriesIDIterators(itrs...), nil
}
func (i *Index) matchTagValueNotEqualEmptySeriesIDIterator(name, key []byte, value *regexp.Regexp) (tsdb.SeriesIDIterator, error) {
vitr, err := i.TagValueIterator(name, key)
if err != nil {
return nil, err
} else if vitr == nil {
return nil, nil
}
defer vitr.Close()
var itrs []tsdb.SeriesIDIterator
for {
e, err := vitr.Next()
if err != nil {
tsdb.SeriesIDIterators(itrs).Close()
return nil, err
} else if e == nil {
break
}
if !value.Match(e) {
itr, err := i.tagValueSeriesIDIterator(name, key, e)
if err != nil {
tsdb.SeriesIDIterators(itrs).Close()
return nil, err
} else if itr != nil {
itrs = append(itrs, itr)
}
}
}
return tsdb.MergeSeriesIDIterators(itrs...), nil
}
func (i *Index) matchTagValueNotEqualNotEmptySeriesIDIterator(name, key []byte, value *regexp.Regexp) (tsdb.SeriesIDIterator, error) {
vitr, err := i.TagValueIterator(name, key)
if err != nil {
return nil, err
} else if vitr == nil {
return i.measurementSeriesIDIterator(name)
}
defer vitr.Close()
var itrs []tsdb.SeriesIDIterator
for {
e, err := vitr.Next()
if err != nil {
tsdb.SeriesIDIterators(itrs).Close()
return nil, err
} else if e == nil {
break
}
if value.Match(e) {
itr, err := i.tagValueSeriesIDIterator(name, key, e)
if err != nil {
tsdb.SeriesIDIterators(itrs).Close()
return nil, err
} else if itr != nil {
itrs = append(itrs, itr)
}
}
}
mitr, err := i.measurementSeriesIDIterator(name)
if err != nil {
tsdb.SeriesIDIterators(itrs).Close()
return nil, err
}
return tsdb.DifferenceSeriesIDIterators(mitr, tsdb.MergeSeriesIDIterators(itrs...)), nil
}
// IsIndexDir returns true if directory contains at least one partition directory.
func IsIndexDir(path string) (bool, error) {
fis, err := ioutil.ReadDir(path)
if err != nil {
return false, err
}
for _, fi := range fis {
if !fi.IsDir() {
continue
} else if ok, err := IsPartitionDir(filepath.Join(path, fi.Name())); err != nil {
return false, err
} else if ok {
return true, nil
}
}
return false, nil
}
| [
"\"INFLUXDB_EXP_TSI_PARTITIONS\"",
"\"INFLUXDB_EXP_TSI_PARTITIONS\"",
"\"INFLUXDB_EXP_TSI_CACHING\"",
"\"INFLUXDB_EXP_TSI_CACHING\""
]
| []
| [
"INFLUXDB_EXP_TSI_PARTITIONS",
"INFLUXDB_EXP_TSI_CACHING"
]
| [] | ["INFLUXDB_EXP_TSI_PARTITIONS", "INFLUXDB_EXP_TSI_CACHING"] | go | 2 | 0 | |
logger/logger.go | package logger
import (
"fmt"
"github.com/fatih/color"
"log"
"os"
)
var (
logFlag = log.Ldate | log.Ltime
myLog = log.New(os.Stdout, "", logFlag)
)
func init() {
isTest := os.Getenv("GO_ENV") == "test"
if isTest {
os.MkdirAll("../log", 0777)
logfile, _ := os.OpenFile("../log/test.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
myLog = log.New(logfile, "", logFlag)
}
}
// Print log
func Print(v ...interface{}) {
myLog.Print(v...)
}
// Println log
func Println(v ...interface{}) {
myLog.Println(v...)
}
// Debug log
func Debug(v ...interface{}) {
myLog.Println("[debug]", fmt.Sprint(v...))
}
// Info log
func Info(v ...interface{}) {
myLog.Println(v...)
}
// Warn log
func Warn(v ...interface{}) {
c := color.YellowString(fmt.Sprint(v...))
myLog.Println(c)
}
// Error log
func Error(v ...interface{}) {
c := color.RedString(fmt.Sprint(v...))
myLog.Println(c)
}
| [
"\"GO_ENV\""
]
| []
| [
"GO_ENV"
]
| [] | ["GO_ENV"] | go | 1 | 0 | |
cmd/cp-main.go | /*
* MinIO Client (C) 2014, 2015 MinIO, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"syscall"
"github.com/cheggaaa/pb"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/mc/pkg/probe"
)
// cp command flags.
var (
cpFlags = []cli.Flag{
cli.BoolFlag{
Name: "recursive, r",
Usage: "copy recursively",
},
cli.StringFlag{
Name: "older-than",
Usage: "copy objects older than L days, M hours and N minutes",
},
cli.StringFlag{
Name: "newer-than",
Usage: "copy objects newer than L days, M hours and N minutes",
},
cli.StringFlag{
Name: "storage-class, sc",
Usage: "set storage class for new object(s) on target",
},
cli.StringFlag{
Name: "encrypt",
Usage: "encrypt/decrypt objects (using server-side encryption with server managed keys)",
},
cli.StringFlag{
Name: "attr",
Usage: "add custom metadata for the object",
},
}
)
// ErrInvalidMetadata reflects invalid metadata format
var ErrInvalidMetadata = errors.New("specified metadata should be of form key1=value1,key2=value2,... and so on")
// Copy command.
var cpCmd = cli.Command{
Name: "cp",
Usage: "copy objects",
Action: mainCopy,
Before: setGlobalsFromContext,
Flags: append(append(cpFlags, ioFlags...), globalFlags...),
CustomHelpTemplate: `NAME:
{{.HelpName}} - {{.Usage}}
USAGE:
{{.HelpName}} [FLAGS] SOURCE [SOURCE...] TARGET
FLAGS:
{{range .VisibleFlags}}{{.}}
{{end}}
ENVIRONMENT VARIABLES:
MC_ENCRYPT: list of comma delimited prefixes
MC_ENCRYPT_KEY: list of comma delimited prefix=secret values
EXAMPLES:
1. Copy a list of objects from local file system to Amazon S3 cloud storage.
$ {{.HelpName}} Music/*.ogg s3/jukebox/
2. Copy a folder recursively from MinIO cloud storage to Amazon S3 cloud storage.
$ {{.HelpName}} --recursive play/mybucket/burningman2011/ s3/mybucket/
3. Copy multiple local folders recursively to MinIO cloud storage.
$ {{.HelpName}} --recursive backup/2014/ backup/2015/ play/archive/
4. Copy a bucket recursively from aliased Amazon S3 cloud storage to local filesystem on Windows.
$ {{.HelpName}} --recursive s3\documents\2014\ C:\Backups\2014
5. Copy files older than 7 days and 10 hours from MinIO cloud storage to Amazon S3 cloud storage.
$ {{.HelpName}} --older-than 7d10h play/mybucket/burningman2011/ s3/mybucket/
6. Copy files newer than 7 days and 10 hours from MinIO cloud storage to a local path.
$ {{.HelpName}} --newer-than 7d10h play/mybucket/burningman2011/ ~/latest/
7. Copy an object with name containing unicode characters to Amazon S3 cloud storage.
$ {{.HelpName}} 本語 s3/andoria/
8. Copy a local folder with space separated characters to Amazon S3 cloud storage.
$ {{.HelpName}} --recursive 'workdir/documents/May 2014/' s3/miniocloud
9. Copy a folder with encrypted objects recursively from Amazon S3 to MinIO cloud storage.
$ {{.HelpName}} --recursive --encrypt-key "s3/documents/=32byteslongsecretkeymustbegiven1,myminio/documents/=32byteslongsecretkeymustbegiven2" s3/documents/ myminio/documents/
10. Copy a list of objects from local file system to MinIO cloud storage with specified metadata.
$ {{.HelpName}} --attr key1=value1,key2=value2 Music/*.mp4 play/mybucket/
11. Copy a folder recursively from MinIO cloud storage to Amazon S3 cloud storage with specified metadata.
$ {{.HelpName}} --attr key1=value1,key2=value2 --recursive play/mybucket/burningman2011/ s3/mybucket/
`,
}
// copyMessage container for file copy messages
type copyMessage struct {
Status string `json:"status"`
Source string `json:"source"`
Target string `json:"target"`
Size int64 `json:"size"`
TotalCount int64 `json:"totalCount"`
TotalSize int64 `json:"totalSize"`
}
// String colorized copy message
func (c copyMessage) String() string {
return console.Colorize("Copy", fmt.Sprintf("`%s` -> `%s`", c.Source, c.Target))
}
// JSON jsonified copy message
func (c copyMessage) JSON() string {
c.Status = "success"
copyMessageBytes, e := json.MarshalIndent(c, "", " ")
fatalIf(probe.NewError(e), "Failed to marshal copy message.")
return string(copyMessageBytes)
}
// copyStatMessage container for copy accounting message
type copyStatMessage struct {
Total int64
Transferred int64
Speed float64
}
// copyStatMessage copy accounting message
func (c copyStatMessage) String() string {
speedBox := pb.Format(int64(c.Speed)).To(pb.U_BYTES).String()
if speedBox == "" {
speedBox = "0 MB"
} else {
speedBox = speedBox + "/s"
}
message := fmt.Sprintf("Total: %s, Transferred: %s, Speed: %s", pb.Format(c.Total).To(pb.U_BYTES),
pb.Format(c.Transferred).To(pb.U_BYTES), speedBox)
return message
}
// Progress - an interface which describes current amount
// of data written.
type Progress interface {
Get() int64
}
// ProgressReader can be used to update the progress of
// an on-going transfer progress.
type ProgressReader interface {
io.Reader
Progress
}
// doCopy - Copy a singe file from source to destination
func doCopy(ctx context.Context, cpURLs URLs, pg ProgressReader, encKeyDB map[string][]prefixSSEPair) URLs {
if cpURLs.Error != nil {
cpURLs.Error = cpURLs.Error.Trace()
return cpURLs
}
sourceAlias := cpURLs.SourceAlias
sourceURL := cpURLs.SourceContent.URL
targetAlias := cpURLs.TargetAlias
targetURL := cpURLs.TargetContent.URL
length := cpURLs.SourceContent.Size
if progressReader, ok := pg.(*progressBar); ok {
progressReader.SetCaption(cpURLs.SourceContent.URL.String() + ": ")
} else {
sourcePath := filepath.ToSlash(filepath.Join(sourceAlias, sourceURL.Path))
targetPath := filepath.ToSlash(filepath.Join(targetAlias, targetURL.Path))
printMsg(copyMessage{
Source: sourcePath,
Target: targetPath,
Size: length,
TotalCount: cpURLs.TotalCount,
TotalSize: cpURLs.TotalSize,
})
}
return uploadSourceToTargetURL(ctx, cpURLs, pg, encKeyDB)
}
// doCopyFake - Perform a fake copy to update the progress bar appropriately.
func doCopyFake(cpURLs URLs, pg Progress) URLs {
if progressReader, ok := pg.(*progressBar); ok {
progressReader.ProgressBar.Add64(cpURLs.SourceContent.Size)
}
return cpURLs
}
// doPrepareCopyURLs scans the source URL and prepares a list of objects for copying.
func doPrepareCopyURLs(session *sessionV8, trapCh <-chan bool, cancelCopy context.CancelFunc) {
// Separate source and target. 'cp' can take only one target,
// but any number of sources.
sourceURLs := session.Header.CommandArgs[:len(session.Header.CommandArgs)-1]
targetURL := session.Header.CommandArgs[len(session.Header.CommandArgs)-1] // Last one is target
var totalBytes int64
var totalObjects int64
// Access recursive flag inside the session header.
isRecursive := session.Header.CommandBoolFlags["recursive"]
olderThan := session.Header.CommandStringFlags["older-than"]
newerThan := session.Header.CommandStringFlags["newer-than"]
encryptKeys := session.Header.CommandStringFlags["encrypt-key"]
encrypt := session.Header.CommandStringFlags["encrypt"]
encKeyDB, err := parseAndValidateEncryptionKeys(encryptKeys, encrypt)
fatalIf(err, "Unable to parse encryption keys.")
// Create a session data file to store the processed URLs.
dataFP := session.NewDataWriter()
var scanBar scanBarFunc
if !globalQuiet && !globalJSON { // set up progress bar
scanBar = scanBarFactory()
}
URLsCh := prepareCopyURLs(sourceURLs, targetURL, isRecursive, encKeyDB)
done := false
for !done {
select {
case cpURLs, ok := <-URLsCh:
if !ok { // Done with URL preparation
done = true
break
}
if cpURLs.Error != nil {
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
if !globalQuiet && !globalJSON {
console.Eraseline()
}
if strings.Contains(cpURLs.Error.ToGoError().Error(), " is a folder.") {
errorIf(cpURLs.Error.Trace(), "Folder cannot be copied. Please use `...` suffix.")
} else {
errorIf(cpURLs.Error.Trace(), "Unable to prepare URL for copying.")
}
break
}
jsonData, e := json.Marshal(cpURLs)
if e != nil {
session.Delete()
fatalIf(probe.NewError(e), "Unable to prepare URL for copying. Error in JSON marshaling.")
}
// Skip objects older than --older-than parameter if specified
if olderThan != "" && isOlder(cpURLs.SourceContent.Time, olderThan) {
continue
}
// Skip objects newer than --newer-than parameter if specified
if newerThan != "" && isNewer(cpURLs.SourceContent.Time, newerThan) {
continue
}
fmt.Fprintln(dataFP, string(jsonData))
if !globalQuiet && !globalJSON {
scanBar(cpURLs.SourceContent.URL.String())
}
totalBytes += cpURLs.SourceContent.Size
totalObjects++
case <-trapCh:
cancelCopy()
// Print in new line and adjust to top so that we don't print over the ongoing scan bar
if !globalQuiet && !globalJSON {
console.Eraseline()
}
session.Delete() // If we are interrupted during the URL scanning, we drop the session.
os.Exit(0)
}
}
session.Header.TotalBytes = totalBytes
session.Header.TotalObjects = totalObjects
session.Save()
}
func doCopySession(session *sessionV8, encKeyDB map[string][]prefixSSEPair) error {
trapCh := signalTrap(os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)
ctx, cancelCopy := context.WithCancel(context.Background())
defer cancelCopy()
if !session.HasData() {
doPrepareCopyURLs(session, trapCh, cancelCopy)
}
// Prepare URL scanner from session data file.
urlScanner := bufio.NewScanner(session.NewDataReader())
// isCopied returns true if an object has been already copied
// or not. This is useful when we resume from a session.
isCopied := isLastFactory(session.Header.LastCopied)
// Store a progress bar or an accounter
var pg ProgressReader
// Enable progress bar reader only during default mode.
if !globalQuiet && !globalJSON { // set up progress bar
pg = newProgressBar(session.Header.TotalBytes)
} else {
pg = newAccounter(session.Header.TotalBytes)
}
var quitCh = make(chan struct{})
var statusCh = make(chan URLs)
parallel, queueCh := newParallelManager(statusCh)
go func() {
gracefulStop := func() {
close(queueCh)
parallel.wait()
close(statusCh)
}
for {
select {
case <-quitCh:
gracefulStop()
return
default:
if !urlScanner.Scan() {
// No more entries, quit immediately
gracefulStop()
return
}
if e := urlScanner.Err(); e != nil {
// Error while reading. quit immediately
gracefulStop()
return
}
var cpURLs URLs
// Unmarshal copyURLs from each line. This expects each line to be
// an entire JSON object.
if e := json.Unmarshal([]byte(urlScanner.Text()), &cpURLs); e != nil {
errorIf(probe.NewError(e), "Unable to unmarshal %s", urlScanner.Text())
continue
}
// Save total count.
cpURLs.TotalCount = session.Header.TotalObjects
// Save totalSize.
cpURLs.TotalSize = session.Header.TotalBytes
// Check and handle storage class if passed in command line args
if _, ok := session.Header.CommandStringFlags["storage-class"]; ok {
if cpURLs.TargetContent.Metadata == nil {
cpURLs.TargetContent.Metadata = make(map[string]string)
}
cpURLs.TargetContent.Metadata["X-Amz-Storage-Class"] = session.Header.CommandStringFlags["storage-class"]
}
// metaMap, metaSet := session.Header.UserMetaData
// Check and handle metadata if passed in command line args
if len(session.Header.UserMetaData) != 0 {
if cpURLs.TargetContent.UserMetadata == nil {
cpURLs.TargetContent.UserMetadata = make(map[string]string)
}
for metaDataKey, metaDataVal := range session.Header.UserMetaData {
cpURLs.TargetContent.UserMetadata[metaDataKey] = metaDataVal
}
}
// Verify if previously copied, notify progress bar.
if isCopied(cpURLs.SourceContent.URL.String()) {
queueCh <- func() URLs {
return doCopyFake(cpURLs, pg)
}
} else {
queueCh <- func() URLs {
return doCopy(ctx, cpURLs, pg, encKeyDB)
}
}
}
}
}()
var retErr error
loop:
for {
select {
case <-trapCh:
quitCh <- struct{}{}
cancelCopy()
// Receive interrupt notification.
if !globalQuiet && !globalJSON {
console.Eraseline()
}
session.CloseAndDie()
case cpURLs, ok := <-statusCh:
// Status channel is closed, we should return.
if !ok {
break loop
}
if cpURLs.Error == nil {
session.Header.LastCopied = cpURLs.SourceContent.URL.String()
session.Save()
} else {
// Set exit status for any copy error
retErr = exitStatus(globalErrorExitStatus)
// Print in new line and adjust to top so that we
// don't print over the ongoing progress bar.
if !globalQuiet && !globalJSON {
console.Eraseline()
}
errorIf(cpURLs.Error.Trace(cpURLs.SourceContent.URL.String()),
fmt.Sprintf("Failed to copy `%s`.", cpURLs.SourceContent.URL.String()))
if isErrIgnored(cpURLs.Error) {
continue loop
}
// For critical errors we should exit. Session
// can be resumed after the user figures out
// the problem.
session.CloseAndDie()
}
}
}
if progressReader, ok := pg.(*progressBar); ok {
if progressReader.ProgressBar.Get() > 0 {
progressReader.ProgressBar.Finish()
}
} else {
if accntReader, ok := pg.(*accounter); ok {
printMsg(accntReader.Stat())
}
}
return retErr
}
// validate the passed metadataString and populate the map
func getMetaDataEntry(metadataString string) (map[string]string, *probe.Error) {
metaDataMap := make(map[string]string)
for _, metaData := range strings.Split(metadataString, ",") {
metaDataEntry := strings.Split(metaData, "=")
if len(metaDataEntry) == 2 {
metaDataMap[metaDataEntry[0]] = metaDataEntry[1]
} else {
return nil, probe.NewError(ErrInvalidMetadata)
}
}
return metaDataMap, nil
}
// mainCopy is the entry point for cp command.
func mainCopy(ctx *cli.Context) error {
// Parse encryption keys per command.
encKeyDB, err := getEncKeys(ctx)
fatalIf(err, "Unable to parse encryption keys.")
// Parse metadata.
userMetaMap := make(map[string]string)
if ctx.String("attr") != "" {
userMetaMap, err = getMetaDataEntry(ctx.String("attr"))
fatalIf(err, "Unable to parse attribute %v", ctx.String("attr"))
}
// check 'copy' cli arguments.
checkCopySyntax(ctx, encKeyDB)
// Additional command speific theme customization.
console.SetColor("Copy", color.New(color.FgGreen, color.Bold))
recursive := ctx.Bool("recursive")
olderThan := ctx.String("older-than")
newerThan := ctx.String("newer-than")
storageClass := ctx.String("storage-class")
sseKeys := os.Getenv("MC_ENCRYPT_KEY")
if key := ctx.String("encrypt-key"); key != "" {
sseKeys = key
}
sse := ctx.String("encrypt")
session := newSessionV8()
session.Header.CommandType = "cp"
session.Header.CommandBoolFlags["recursive"] = recursive
session.Header.CommandStringFlags["older-than"] = olderThan
session.Header.CommandStringFlags["newer-than"] = newerThan
session.Header.CommandStringFlags["storage-class"] = storageClass
session.Header.CommandStringFlags["encrypt-key"] = sseKeys
session.Header.CommandStringFlags["encrypt"] = sse
session.Header.UserMetaData = userMetaMap
var e error
if session.Header.RootPath, e = os.Getwd(); e != nil {
session.Delete()
fatalIf(probe.NewError(e), "Unable to get current working folder.")
}
// extract URLs.
session.Header.CommandArgs = ctx.Args()
e = doCopySession(session, encKeyDB)
session.Delete()
return e
}
| [
"\"MC_ENCRYPT_KEY\""
]
| []
| [
"MC_ENCRYPT_KEY"
]
| [] | ["MC_ENCRYPT_KEY"] | go | 1 | 0 | |
docs/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
import os
import sys
import django
if os.getenv("READTHEDOCS", default=False) == "True":
sys.path.insert(0, os.path.abspath(".."))
os.environ["DJANGO_READ_DOT_ENV_FILE"] = "True"
os.environ["USE_DOCKER"] = "no"
else:
sys.path.insert(0, os.path.abspath("/app"))
os.environ["DATABASE_URL"] = "sqlite:///readthedocs.db"
os.environ["CELERY_BROKER_URL"] = os.getenv("REDIS_URL", "redis://redis:6379")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
django.setup()
# -- Project information -----------------------------------------------------
project = "Coders Headquarters"
copyright = """2021, Rashed Al Suwaidi"""
author = "Rashed Al Suwaidi"
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
]
# Add any paths that contain templates here, relative to this directory.
# templates_path = ["_templates"]
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "alabaster"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ["_static"]
| []
| []
| [
"USE_DOCKER",
"DATABASE_URL",
"CELERY_BROKER_URL",
"DJANGO_READ_DOT_ENV_FILE",
"REDIS_URL",
"READTHEDOCS"
]
| [] | ["USE_DOCKER", "DATABASE_URL", "CELERY_BROKER_URL", "DJANGO_READ_DOT_ENV_FILE", "REDIS_URL", "READTHEDOCS"] | python | 6 | 0 | |
Rest_API_Beginner/wsgi.py | """
WSGI config for Rest_API_Beginner project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Rest_API_Beginner.settings')
application = get_wsgi_application()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
services/horizon/internal/integration/protocol16_test.go | package integration
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stellar/go/clients/horizonclient"
"github.com/stellar/go/keypair"
protocol "github.com/stellar/go/protocols/horizon"
"github.com/stellar/go/protocols/horizon/effects"
"github.com/stellar/go/protocols/horizon/operations"
"github.com/stellar/go/services/horizon/internal/codes"
"github.com/stellar/go/services/horizon/internal/test/integration"
"github.com/stellar/go/txnbuild"
"github.com/stellar/go/xdr"
)
func NewProtocol16Test(t *testing.T) *integration.Test {
// TODO, this should be removed once a core version with CAP 35 is released
if os.Getenv("HORIZON_INTEGRATION_ENABLE_CAP_35") != "true" {
t.Skip("skipping CAP35 test, set HORIZON_INTEGRATION_ENABLE_CAP_35=true if you want to run it")
}
config := integration.Config{
ProtocolVersion: 16,
CoreDockerImage: "2opremio/stellar-core:cap35",
}
return integration.NewTest(t, config)
}
func TestProtocol16Basics(t *testing.T) {
tt := assert.New(t)
itest := NewProtocol16Test(t)
master := itest.Master()
t.Run("Sanity", func(t *testing.T) {
root, err := itest.Client().Root()
tt.NoError(err)
tt.LessOrEqual(int32(16), root.CoreSupportedProtocolVersion)
tt.Equal(int32(16), root.CurrentProtocolVersion)
// Submit a simple tx
op := txnbuild.Payment{
Destination: master.Address(),
Amount: "10",
Asset: txnbuild.NativeAsset{},
}
txResp := itest.MustSubmitOperations(itest.MasterAccount(), master, &op)
tt.Equal(master.Address(), txResp.Account)
tt.Equal("1", txResp.AccountSequence)
})
}
func TestHappyClawbackAccount(t *testing.T) {
tt := assert.New(t)
itest := NewProtocol16Test(t)
master := itest.Master()
asset, fromKey, _ := setupClawbackAccountTest(tt, itest, master)
// Clawback all of the asset
submissionResp := itest.MustSubmitOperations(itest.MasterAccount(), master, &txnbuild.Clawback{
From: fromKey.Address(),
Amount: "10",
Asset: asset,
})
assertClawbackAccountSuccess(tt, itest, master, fromKey, "0.0000000", submissionResp)
// Check the operation details
opDetailsResponse, err := itest.Client().Operations(horizonclient.OperationRequest{
ForTransaction: submissionResp.Hash,
})
tt.NoError(err)
if tt.Len(opDetailsResponse.Embedded.Records, 1) {
clawbackOp := opDetailsResponse.Embedded.Records[0].(operations.Clawback)
tt.Equal("PTS", clawbackOp.Code)
tt.Equal(fromKey.Address(), clawbackOp.From)
tt.Equal("10.0000000", clawbackOp.Amount)
}
// Check the operation effects
effectsResponse, err := itest.Client().Effects(horizonclient.EffectRequest{
ForTransaction: submissionResp.Hash,
})
tt.NoError(err)
if tt.Len(effectsResponse.Embedded.Records, 2) {
accountCredited := effectsResponse.Embedded.Records[0].(effects.AccountCredited)
tt.Equal(master.Address(), accountCredited.Account)
tt.Equal("10.0000000", accountCredited.Amount)
tt.Equal(master.Address(), accountCredited.Issuer)
tt.Equal("PTS", accountCredited.Code)
accountDebited := effectsResponse.Embedded.Records[1].(effects.AccountDebited)
tt.Equal(fromKey.Address(), accountDebited.Account)
tt.Equal("10.0000000", accountDebited.Amount)
tt.Equal(master.Address(), accountDebited.Issuer)
tt.Equal("PTS", accountDebited.Code)
}
}
func TestHappyClawbackAccountPartial(t *testing.T) {
tt := assert.New(t)
itest := NewProtocol16Test(t)
master := itest.Master()
asset, fromKey, _ := setupClawbackAccountTest(tt, itest, master)
// Partial clawback of the asset
submissionResp := itest.MustSubmitOperations(itest.MasterAccount(), master, &txnbuild.Clawback{
From: fromKey.Address(),
Amount: "5",
Asset: asset,
})
assertClawbackAccountSuccess(tt, itest, master, fromKey, "5.0000000", submissionResp)
}
func TestHappyClawbackAccountSellingLiabilities(t *testing.T) {
tt := assert.New(t)
itest := NewProtocol16Test(t)
master := itest.Master()
asset, fromKey, fromAccount := setupClawbackAccountTest(tt, itest, master)
// Add a selling liability
submissionResp := itest.MustSubmitOperations(fromAccount, fromKey, &txnbuild.ManageSellOffer{
Buying: txnbuild.NativeAsset{},
Selling: asset,
Amount: "5",
Price: "1",
SourceAccount: fromAccount.GetAccountID(),
})
tt.True(submissionResp.Successful)
// Full clawback of the asset, with a deauthorize/reauthorize sandwich
submissionResp = itest.MustSubmitOperations(itest.MasterAccount(), master,
&txnbuild.SetTrustLineFlags{
Trustor: fromAccount.GetAccountID(),
Asset: asset,
ClearFlags: []txnbuild.TrustLineFlag{txnbuild.TrustLineAuthorized},
},
&txnbuild.Clawback{
From: fromKey.Address(),
Amount: "10",
Asset: asset,
},
&txnbuild.SetTrustLineFlags{
Trustor: fromAccount.GetAccountID(),
Asset: asset,
SetFlags: []txnbuild.TrustLineFlag{txnbuild.TrustLineAuthorized},
},
)
assertClawbackAccountSuccess(tt, itest, master, fromKey, "0.0000000", submissionResp)
}
func TestSadClawbackAccountInsufficientFunds(t *testing.T) {
tt := assert.New(t)
itest := NewProtocol16Test(t)
master := itest.Master()
asset, fromKey, _ := setupClawbackAccountTest(tt, itest, master)
// Attempt to clawback more than the account holds.
submissionResp, err := itest.SubmitOperations(itest.MasterAccount(), master, &txnbuild.Clawback{
From: fromKey.Address(),
Amount: "20",
Asset: asset,
})
tt.Error(err)
assertClawbackAccountFailed(tt, itest, master, fromKey, submissionResp)
}
func TestSadClawbackAccountSufficientFundsSellingLiabilities(t *testing.T) {
tt := assert.New(t)
itest := NewProtocol16Test(t)
master := itest.Master()
asset, fromKey, fromAccount := setupClawbackAccountTest(tt, itest, master)
// Add a selling liability
submissionResp := itest.MustSubmitOperations(fromAccount, fromKey, &txnbuild.ManageSellOffer{
Buying: txnbuild.NativeAsset{},
Selling: asset,
Amount: "5",
Price: "1",
SourceAccount: fromAccount.GetAccountID(),
})
// Attempt to clawback more than is available.
submissionResp, err := itest.SubmitOperations(itest.MasterAccount(), master, &txnbuild.Clawback{
From: fromKey.Address(),
Amount: "10",
Asset: asset,
})
tt.Error(err)
assertClawbackAccountFailed(tt, itest, master, fromKey, submissionResp)
}
func setupClawbackAccountTest(tt *assert.Assertions, itest *integration.Test, master *keypair.Full) (txnbuild.CreditAsset, *keypair.Full, txnbuild.Account) {
// Give the master account the revocable flag (needed to set the clawback flag)
setRevocableFlag := txnbuild.SetOptions{
SetFlags: []txnbuild.AccountFlag{
txnbuild.AuthRevocable,
},
}
itest.MustSubmitOperations(itest.MasterAccount(), master, &setRevocableFlag)
// Give the master account the clawback flag
setClawBackFlag := txnbuild.SetOptions{
SetFlags: []txnbuild.AccountFlag{
txnbuild.AuthClawbackEnabled,
},
}
itest.MustSubmitOperations(itest.MasterAccount(), master, &setClawBackFlag)
// Make sure the clawback flag was set
accountDetails := itest.MustGetAccount(master)
tt.True(accountDetails.Flags.AuthClawbackEnabled)
// Create another account from which to claw an asset back
keyPairs, accounts := itest.CreateAccounts(1, "100")
accountKeyPair := keyPairs[0]
account := accounts[0]
// Add some assets to the account with asset which allows clawback
// Time machine to Spain before Euros were a thing
pesetasAsset := txnbuild.CreditAsset{Code: "PTS", Issuer: master.Address()}
itest.MustEstablishTrustline(accountKeyPair, account, pesetasAsset)
pesetasPayment := txnbuild.Payment{
Destination: accountKeyPair.Address(),
Amount: "10",
Asset: pesetasAsset,
}
itest.MustSubmitOperations(itest.MasterAccount(), master, &pesetasPayment)
accountDetails = itest.MustGetAccount(accountKeyPair)
if tt.Len(accountDetails.Balances, 2) {
pts := accountDetails.Balances[0]
tt.Equal("PTS", pts.Code)
if tt.NotNil(pts.IsClawbackEnabled) {
tt.True(*pts.IsClawbackEnabled)
}
tt.Equal("10.0000000", pts.Balance)
}
return pesetasAsset, accountKeyPair, account
}
func assertClawbackAccountSuccess(tt *assert.Assertions, itest *integration.Test, master, accountKeyPair *keypair.Full, expectedBalance string, submissionResp protocol.Transaction) {
tt.True(submissionResp.Successful)
assertAccountBalance(tt, itest, accountKeyPair, expectedBalance)
}
func assertClawbackAccountFailed(tt *assert.Assertions, itest *integration.Test, master, accountKeyPair *keypair.Full, submissionResp protocol.Transaction) {
tt.False(submissionResp.Successful)
assertAccountBalance(tt, itest, accountKeyPair, "10.0000000")
}
func assertAccountBalance(tt *assert.Assertions, itest *integration.Test, accountKeyPair *keypair.Full, expectedBalance string) {
accountDetails := itest.MustGetAccount(accountKeyPair)
if tt.Len(accountDetails.Balances, 2) {
pts := accountDetails.Balances[0]
tt.Equal("PTS", pts.Code)
if tt.NotNil(pts.IsClawbackEnabled) {
tt.True(*pts.IsClawbackEnabled)
}
tt.Equal(expectedBalance, pts.Balance)
}
}
func TestHappyClawbackClaimableBalance(t *testing.T) {
tt := assert.New(t)
itest := NewProtocol16Test(t)
master := itest.Master()
// Give the master account the revocable flag (needed to set the clawback flag)
setRevocableFlag := txnbuild.SetOptions{
SetFlags: []txnbuild.AccountFlag{
txnbuild.AuthRevocable,
},
}
itest.MustSubmitOperations(itest.MasterAccount(), master, &setRevocableFlag)
// Give the master account the clawback flag
setClawBackFlag := txnbuild.SetOptions{
SetFlags: []txnbuild.AccountFlag{
txnbuild.AuthClawbackEnabled,
},
}
itest.MustSubmitOperations(itest.MasterAccount(), master, &setClawBackFlag)
// Make sure the clawback flag was set
accountDetails := itest.MustGetAccount(master)
tt.True(accountDetails.Flags.AuthClawbackEnabled)
// Create another account as a claimable balance claimant
keyPairs, accounts := itest.CreateAccounts(1, "100")
accountKeyPair := keyPairs[0]
account := accounts[0]
// Time machine to Spain before Euros were a thing
pesetasAsset := txnbuild.CreditAsset{Code: "PTS", Issuer: master.Address()}
itest.MustEstablishTrustline(accountKeyPair, account, pesetasAsset)
// Make a claimable balance from the master account (and asset issuer) to the account with an asset which allows clawback
pesetasCreateCB := txnbuild.CreateClaimableBalance{
Amount: "10",
Asset: pesetasAsset,
Destinations: []txnbuild.Claimant{
txnbuild.NewClaimant(accountKeyPair.Address(), nil),
},
}
itest.MustSubmitOperations(itest.MasterAccount(), master, &pesetasCreateCB)
// Check that the claimable balance was created, clawback is enabled and obtain the id to claw it back later on
listCBResp, err := itest.Client().ClaimableBalances(horizonclient.ClaimableBalanceRequest{
Claimant: accountKeyPair.Address(),
})
tt.NoError(err)
cbID := ""
if tt.Len(listCBResp.Embedded.Records, 1) {
cb := listCBResp.Embedded.Records[0]
tt.True(cb.Flags.ClawbackEnabled)
cbID = cb.BalanceID
tt.Equal(master.Address(), cb.Sponsor)
}
// check that its operations and transactions can be obtained
transactionsResp, err := itest.Client().Transactions(horizonclient.TransactionRequest{
ForClaimableBalance: cbID,
})
assert.NoError(t, err)
assert.Len(t, transactionsResp.Embedded.Records, 1)
operationsResp, err := itest.Client().Operations(horizonclient.OperationRequest{
ForClaimableBalance: cbID,
})
assert.NoError(t, err)
if assert.Len(t, operationsResp.Embedded.Records, 1) {
assert.IsType(t, operationsResp.Embedded.Records[0], operations.CreateClaimableBalance{})
}
// Clawback the claimable balance
pesetasClawbackCB := txnbuild.ClawbackClaimableBalance{
BalanceID: cbID,
}
clawbackCBResp := itest.MustSubmitOperations(itest.MasterAccount(), master, &pesetasClawbackCB)
// Make sure the claimable balance is clawed back (gone)
_, err = itest.Client().ClaimableBalance(cbID)
// Not found
tt.Error(err)
// check that its operations and transactions can still be obtained
transactionsResp, err = itest.Client().Transactions(horizonclient.TransactionRequest{
ForClaimableBalance: cbID,
})
assert.NoError(t, err)
assert.Len(t, transactionsResp.Embedded.Records, 2)
operationsResp, err = itest.Client().Operations(horizonclient.OperationRequest{
ForClaimableBalance: cbID,
})
assert.NoError(t, err)
if assert.Len(t, operationsResp.Embedded.Records, 2) {
assert.IsType(t, operationsResp.Embedded.Records[0], operations.CreateClaimableBalance{})
assert.IsType(t, operationsResp.Embedded.Records[1], operations.ClawbackClaimableBalance{})
}
// Check the operation details
opDetailsResponse, err := itest.Client().Operations(horizonclient.OperationRequest{
ForTransaction: clawbackCBResp.Hash,
})
tt.NoError(err)
if tt.Len(opDetailsResponse.Embedded.Records, 1) {
clawbackOp := opDetailsResponse.Embedded.Records[0].(operations.ClawbackClaimableBalance)
tt.Equal(cbID, *clawbackOp.ClaimableBalanceID)
}
// Check the operation effects
effectsResponse, err := itest.Client().Effects(horizonclient.EffectRequest{
ForTransaction: clawbackCBResp.Hash,
})
tt.NoError(err)
if tt.Len(effectsResponse.Embedded.Records, 3) {
claimableBalanceClawedBack := effectsResponse.Embedded.Records[0].(effects.ClaimableBalanceClawedBack)
tt.Equal(master.Address(), claimableBalanceClawedBack.Account)
tt.Equal(cbID, claimableBalanceClawedBack.BalanceID)
accountCredited := effectsResponse.Embedded.Records[1].(effects.AccountCredited)
tt.Equal(master.Address(), accountCredited.Account)
tt.Equal("10.0000000", accountCredited.Amount)
tt.Equal(accountCredited.Issuer, master.Address())
tt.Equal(accountCredited.Code, "PTS")
cbSponsorshipRemoved := effectsResponse.Embedded.Records[2].(effects.ClaimableBalanceSponsorshipRemoved)
tt.Equal(master.Address(), cbSponsorshipRemoved.Account)
tt.Equal(cbID, cbSponsorshipRemoved.BalanceID)
tt.Equal(master.Address(), cbSponsorshipRemoved.FormerSponsor)
}
}
func TestHappySetTrustLineFlags(t *testing.T) {
tt := assert.New(t)
itest := NewProtocol16Test(t)
master := itest.Master()
// Give the master account the revocable flag (needed to set the clawback flag)
setRevocableFlag := txnbuild.SetOptions{
SetFlags: []txnbuild.AccountFlag{
txnbuild.AuthRevocable,
},
}
itest.MustSubmitOperations(itest.MasterAccount(), master, &setRevocableFlag)
// Give the master account the clawback flag
setClawBackFlag := txnbuild.SetOptions{
SetFlags: []txnbuild.AccountFlag{
txnbuild.AuthClawbackEnabled,
},
}
itest.MustSubmitOperations(itest.MasterAccount(), master, &setClawBackFlag)
// Make sure the clawback flag was set
accountDetails := itest.MustGetAccount(master)
tt.True(accountDetails.Flags.AuthClawbackEnabled)
// Create another account fot the Trustline
keyPairs, accounts := itest.CreateAccounts(1, "100")
accountKeyPair := keyPairs[0]
account := accounts[0]
// Time machine to Spain before Euros were a thing
pesetasAsset := txnbuild.CreditAsset{Code: "PTS", Issuer: master.Address()}
itest.MustEstablishTrustline(accountKeyPair, account, pesetasAsset)
// Confirm that the Trustline has the clawback flag
accountDetails = itest.MustGetAccount(accountKeyPair)
if tt.Len(accountDetails.Balances, 2) {
pts := accountDetails.Balances[0]
tt.Equal("PTS", pts.Code)
if tt.NotNil(pts.IsClawbackEnabled) {
tt.True(*pts.IsClawbackEnabled)
}
}
// Clear the clawback flag
setTrustlineFlags := txnbuild.SetTrustLineFlags{
Trustor: accountKeyPair.Address(),
Asset: pesetasAsset,
ClearFlags: []txnbuild.TrustLineFlag{
txnbuild.TrustLineClawbackEnabled,
},
}
submissionResp := itest.MustSubmitOperations(itest.MasterAccount(), master, &setTrustlineFlags)
// make sure it was cleared
accountDetails = itest.MustGetAccount(accountKeyPair)
if tt.Len(accountDetails.Balances, 2) {
pts := accountDetails.Balances[0]
tt.Equal("PTS", pts.Code)
tt.Nil(pts.IsClawbackEnabled)
}
// Check the operation details
opDetailsResponse, err := itest.Client().Operations(horizonclient.OperationRequest{
ForTransaction: submissionResp.Hash,
})
tt.NoError(err)
if tt.Len(opDetailsResponse.Embedded.Records, 1) {
setTrustlineFlagsDetails := opDetailsResponse.Embedded.Records[0].(operations.SetTrustLineFlags)
tt.Equal("PTS", setTrustlineFlagsDetails.Code)
tt.Equal(master.Address(), setTrustlineFlagsDetails.Issuer)
tt.Equal(accountKeyPair.Address(), setTrustlineFlagsDetails.Trustor)
if tt.Len(setTrustlineFlagsDetails.ClearFlags, 1) {
tt.True(xdr.TrustLineFlags(setTrustlineFlagsDetails.ClearFlags[0]).IsClawbackEnabledFlag())
}
if tt.Len(setTrustlineFlagsDetails.ClearFlagsS, 1) {
tt.Equal(setTrustlineFlagsDetails.ClearFlagsS[0], "clawback_enabled")
}
tt.Len(setTrustlineFlagsDetails.SetFlags, 0)
tt.Len(setTrustlineFlagsDetails.SetFlagsS, 0)
}
// Check the operation effects
effectsResponse, err := itest.Client().Effects(horizonclient.EffectRequest{
ForTransaction: submissionResp.Hash,
})
tt.NoError(err)
if tt.Len(effectsResponse.Embedded.Records, 1) {
trustlineFlagsUpdated := effectsResponse.Embedded.Records[0].(effects.TrustlineFlagsUpdated)
tt.Equal(master.Address(), trustlineFlagsUpdated.Account)
tt.Equal(master.Address(), trustlineFlagsUpdated.Issuer)
tt.Equal("PTS", trustlineFlagsUpdated.Code)
tt.Nil(trustlineFlagsUpdated.Authorized)
tt.Nil(trustlineFlagsUpdated.AuthorizedToMaintainLiabilities)
if tt.NotNil(trustlineFlagsUpdated.ClawbackEnabled) {
tt.False(*trustlineFlagsUpdated.ClawbackEnabled)
}
}
// Try to set the clawback flag (we shouldn't be able to)
setTrustlineFlags = txnbuild.SetTrustLineFlags{
Trustor: accountKeyPair.Address(),
Asset: pesetasAsset,
SetFlags: []txnbuild.TrustLineFlag{
txnbuild.TrustLineClawbackEnabled,
},
}
_, err = itest.SubmitOperations(itest.MasterAccount(), master, &setTrustlineFlags)
if tt.Error(err) {
clientErr, ok := err.(*horizonclient.Error)
if tt.True(ok) {
tt.Equal(400, clientErr.Problem.Status)
resCodes, err := clientErr.ResultCodes()
tt.NoError(err)
tt.Equal(codes.OpMalformed, resCodes.OperationCodes[0])
}
}
}
| [
"\"HORIZON_INTEGRATION_ENABLE_CAP_35\""
]
| []
| [
"HORIZON_INTEGRATION_ENABLE_CAP_35"
]
| [] | ["HORIZON_INTEGRATION_ENABLE_CAP_35"] | go | 1 | 0 | |
github-push/handler.go | package function
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"github.com/alexellis/hmac"
"github.com/openfaas/openfaas-cloud/sdk"
)
// Source name for this function when auditing
const Source = "github-push"
//SCM identifier
const SCM = "github"
var audit sdk.Audit
// Handle a serverless request
func Handle(req []byte) string {
if audit == nil {
audit = sdk.AuditLogger{}
}
event := os.Getenv("Http_X_Github_Event")
if event != "push" {
auditEvent := sdk.AuditEvent{
Message: "bad event: " + event,
Source: Source,
}
audit.Post(auditEvent)
return fmt.Sprintf("%s cannot handle event: %s", Source, event)
}
xHubSignature := os.Getenv("Http_X_Hub_Signature")
shouldValidate := readBool("validate_hmac")
if shouldValidate {
webhookSecretKey, secretErr := sdk.ReadSecret("github-webhook-secret")
if secretErr != nil {
return secretErr.Error()
}
validateErr := hmac.Validate(req, xHubSignature, webhookSecretKey)
if validateErr != nil {
log.Fatal(validateErr)
}
}
pushEvent := sdk.PushEvent{}
err := json.Unmarshal(req, &pushEvent)
if err != nil {
return err.Error()
}
pushEvent.SCM = SCM
var found bool
if readBool("validate_customers") {
customersURL := os.Getenv("customers_url")
customers, getErr := getCustomers(customersURL)
if getErr != nil {
return getErr.Error()
}
found = validCustomer(customers, pushEvent.Repository.Owner.Login)
if !found {
auditEvent := sdk.AuditEvent{
Message: "Customer not found",
Owner: pushEvent.Repository.Owner.Login,
Repo: pushEvent.Repository.Name,
Source: Source,
}
audit.Post(auditEvent)
return fmt.Sprintf("Customer: %s not found in CUSTOMERS file via %s", pushEvent.Repository.Owner.Login, customersURL)
}
}
eventInfo := sdk.BuildEventFromPushEvent(pushEvent)
status := sdk.BuildStatus(eventInfo, sdk.EmptyAuthToken)
if len(pushEvent.Ref) == 0 ||
pushEvent.Ref != "refs/heads/master" {
msg := "refusing to build non-master branch: " + pushEvent.Ref
auditEvent := sdk.AuditEvent{
Message: msg,
Owner: pushEvent.Repository.Owner.Login,
Repo: pushEvent.Repository.Name,
Source: Source,
}
audit.Post(auditEvent)
status.AddStatus(sdk.StatusFailure, msg, sdk.StackContext)
reportStatus(status)
return msg
}
serviceValue := sdk.FormatServiceName(pushEvent.Repository.Owner.Login, pushEvent.Repository.Name)
status.AddStatus(sdk.StatusPending, fmt.Sprintf("%s stack deploy is in progress", serviceValue), sdk.StackContext)
reportStatus(status)
statusCode, postErr := postEvent(pushEvent)
if postErr != nil {
status.AddStatus(sdk.StatusFailure, postErr.Error(), sdk.StackContext)
reportStatus(status)
return postErr.Error()
}
auditEvent := sdk.AuditEvent{
Message: "Git-tar invoked",
Owner: pushEvent.Repository.Owner.Login,
Repo: pushEvent.Repository.Name,
Source: Source,
}
sdk.PostAudit(auditEvent)
return fmt.Sprintf("Push - %v, git-tar status: %d\n", pushEvent, statusCode)
}
// getCustomers reads a list of customers separated by new lines
// who are valid users of OpenFaaS cloud
func getCustomers(customerURL string) ([]string, error) {
customers := []string{}
if len(customerURL) == 0 {
return nil, fmt.Errorf("customerURL was nil")
}
c := http.Client{}
httpReq, _ := http.NewRequest(http.MethodGet, customerURL, nil)
res, reqErr := c.Do(httpReq)
if reqErr != nil {
return customers, reqErr
}
if res.Body != nil {
defer res.Body.Close()
pageBody, _ := ioutil.ReadAll(res.Body)
customers = strings.Split(string(pageBody), "\n")
for i, c := range customers {
customers[i] = strings.ToLower(c)
}
}
return customers, nil
}
func postEvent(pushEvent sdk.PushEvent) (int, error) {
gatewayURL := os.Getenv("gateway_url")
payloadSecret, err := sdk.ReadSecret("payload-secret")
if err != nil {
return http.StatusUnauthorized, err
}
body, _ := json.Marshal(pushEvent)
c := http.Client{}
bodyReader := bytes.NewBuffer(body)
httpReq, _ := http.NewRequest(http.MethodPost, gatewayURL+"async-function/git-tar", bodyReader)
digest := hmac.Sign(body, []byte(payloadSecret))
httpReq.Header.Add(sdk.CloudSignatureHeader, "sha1="+hex.EncodeToString(digest))
res, reqErr := c.Do(httpReq)
if reqErr != nil {
return http.StatusServiceUnavailable, reqErr
}
if res.Body != nil {
defer res.Body.Close()
}
return res.StatusCode, nil
}
func readBool(key string) bool {
if val, exists := os.LookupEnv(key); exists {
return val == "true" || val == "1"
}
return false
}
func enableStatusReporting() bool {
return os.Getenv("report_status") == "true"
}
func reportStatus(status *sdk.Status) {
if !enableStatusReporting() {
return
}
hmacKey, keyErr := sdk.ReadSecret("payload-secret")
if keyErr != nil {
log.Printf("failed to load hmac key for status, error " + keyErr.Error())
return
}
gatewayURL := os.Getenv("gateway_url")
_, reportErr := status.Report(gatewayURL, hmacKey)
if reportErr != nil {
log.Printf("failed to report status, error: %s", reportErr.Error())
}
}
func init() {
}
func validCustomer(customers []string, owner string) bool {
found := false
for _, customer := range customers {
if len(customer) > 0 &&
strings.EqualFold(customer, owner) {
found = true
break
}
}
return found
}
| [
"\"Http_X_Github_Event\"",
"\"Http_X_Hub_Signature\"",
"\"customers_url\"",
"\"gateway_url\"",
"\"report_status\"",
"\"gateway_url\""
]
| []
| [
"Http_X_Hub_Signature",
"report_status",
"customers_url",
"Http_X_Github_Event",
"gateway_url"
]
| [] | ["Http_X_Hub_Signature", "report_status", "customers_url", "Http_X_Github_Event", "gateway_url"] | go | 5 | 0 | |
ssh/ssh_suite_test.go | package ssh_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"testing"
)
func TestSsh(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "SSH Suite")
}
| []
| []
| []
| [] | [] | go | null | null | null |
vendor/github.com/bmc-toolbox/bmclib/discover/discover.go | package discover
import (
"context"
"os"
"github.com/bmc-toolbox/bmclib/errors"
"github.com/bmc-toolbox/bmclib/internal/httpclient"
"github.com/bmc-toolbox/bmclib/logging"
"github.com/bmc-toolbox/bmclib/providers/dummy/ibmc"
"github.com/go-logr/logr"
)
const (
ProbeHpIlo = "hpilo"
ProbeIdrac8 = "idrac8"
ProbeIdrac9 = "idrac9"
ProbeSupermicrox = "supermicrox"
ProbeSupermicrox11 = "supermicrox11"
ProbeHpC7000 = "hpc7000"
ProbeM1000e = "m1000e"
ProbeQuanta = "quanta"
ProbeHpCl100 = "hpcl100"
)
// ScanAndConnect will scan the bmc trying to learn the device type and return a working connection.
func ScanAndConnect(host string, username string, password string, options ...Option) (bmcConnection interface{}, err error) {
opts := &Options{HintCallback: func(_ string) error { return nil }}
for _, optFn := range options {
optFn(opts)
}
if opts.Logger == nil {
// create a default logger
opts.Logger = logging.DefaultLogger()
}
opts.Logger.V(1).Info("detecting vendor", "step", "ScanAndConnect", "host", host)
// return a connection to our dummy device.
if os.Getenv("BMCLIB_TEST") == "1" {
opts.Logger.V(1).Info("returning connection to dummy ibmc device.", "step", "ScanAndConnect", "host", host)
bmc, err := ibmc.New(host, username, password)
return bmc, err
}
client, err := httpclient.Build()
if err != nil {
return nil, err
}
var probe = Probe{client: client, username: username, password: password, host: host}
var devices = map[string]func(context.Context, logr.Logger) (interface{}, error){
ProbeHpIlo: probe.hpIlo,
ProbeIdrac8: probe.idrac8,
ProbeIdrac9: probe.idrac9,
ProbeSupermicrox11: probe.supermicrox11,
ProbeSupermicrox: probe.supermicrox,
ProbeHpC7000: probe.hpC7000,
ProbeM1000e: probe.m1000e,
ProbeQuanta: probe.quanta,
ProbeHpCl100: probe.hpCl100,
}
order := []string{ProbeHpIlo,
ProbeIdrac8,
ProbeIdrac9,
ProbeSupermicrox11,
ProbeSupermicrox,
ProbeHpC7000,
ProbeM1000e,
ProbeQuanta,
ProbeHpCl100,
}
if opts.Hint != "" {
swapProbe(order, opts.Hint)
}
for _, probeID := range order {
probeDevice := devices[probeID]
opts.Logger.V(1).Info("probing to identify device", "step", "ScanAndConnect", "host", host, "vendor", probeID)
bmcConnection, err := probeDevice(opts.Context, opts.Logger)
// if the device didn't match continue to probe
if err != nil {
// log error if probe is not successful
opts.Logger.V(1).Info("probe failed", "step", "ScanAndConnect", "host", host, "vendor", probeID, "error", err)
continue
}
if hintErr := opts.HintCallback(probeID); hintErr != nil {
return nil, hintErr
}
// return a bmcConnection
if bmcConnection != nil {
return bmcConnection, nil
}
}
return nil, errors.ErrVendorUnknown
}
// Options to pass in
type Options struct {
// Hint is a probe ID that hints which probe should be probed first.
Hint string
// HintCallBack is a function that is called back with a probe ID that might be used
// for the next ScanAndConnect attempt. The callback is called only on successful scan.
// If your code persists the hint as "best effort", always return a nil error. Callback is
// synchronous.
HintCallback func(string) error
Logger logr.Logger
Context context.Context
}
// Option is part of the functional options pattern, see the `With*` functions and
// https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis
type Option func(*Options)
// WithProbeHint sets the Options.Hint option.
func WithProbeHint(hint string) Option { return func(args *Options) { args.Hint = hint } }
// WithHintCallBack sets the Options.HintCallback option.
func WithHintCallBack(fn func(string) error) Option {
return func(args *Options) { args.HintCallback = fn }
}
// WithLogger sets the Options.Logger option
func WithLogger(log logr.Logger) Option { return func(args *Options) { args.Logger = log } }
// WithContext sets the Options.Context option
func WithContext(ctx context.Context) Option { return func(args *Options) { args.Context = ctx } }
func swapProbe(order []string, hint string) {
// With so few elements and since `==` uses SIMD,
// looping is faster than having yet another hash map.
for i := range order {
if order[i] == hint {
order[0], order[i] = order[i], order[0]
break
}
}
}
| [
"\"BMCLIB_TEST\""
]
| []
| [
"BMCLIB_TEST"
]
| [] | ["BMCLIB_TEST"] | go | 1 | 0 | |
pkg/gitserver/getbuildconfigs.go | package gitserver
import (
"fmt"
"io"
"os"
kapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/client/restclient"
buildapi "github.com/openshift/origin/pkg/build/api"
"github.com/openshift/origin/pkg/client"
)
const gitRepositoryAnnotationKey = "openshift.io/git-repository"
func GetRepositoryBuildConfigs(name string, out io.Writer) error {
client, err := getClient()
if err != nil {
return err
}
ns := os.Getenv("POD_NAMESPACE")
buildConfigList, err := client.BuildConfigs(ns).List(kapi.ListOptions{})
if err != nil {
return err
}
matchingBuildConfigs := []*buildapi.BuildConfig{}
for _, bc := range buildConfigList.Items {
repoAnnotation, hasAnnotation := bc.Annotations[gitRepositoryAnnotationKey]
if hasAnnotation {
if repoAnnotation == name {
matchingBuildConfigs = append(matchingBuildConfigs, &bc)
}
continue
}
if bc.Name == name {
matchingBuildConfigs = append(matchingBuildConfigs, &bc)
}
}
for _, bc := range matchingBuildConfigs {
var ref string
if bc.Spec.Source.Git != nil {
ref = bc.Spec.Source.Git.Ref
}
if ref == "" {
ref = "master"
}
fmt.Fprintf(out, "%s %s\n", bc.Name, ref)
}
return nil
}
func getClient() (client.Interface, error) {
clientConfig, err := restclient.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("failed to get client config: %v", err)
}
osClient, err := client.New(clientConfig)
if err != nil {
return nil, fmt.Errorf("error obtaining OpenShift client: %v", err)
}
return osClient, nil
}
| [
"\"POD_NAMESPACE\""
]
| []
| [
"POD_NAMESPACE"
]
| [] | ["POD_NAMESPACE"] | go | 1 | 0 | |
signed_url/signedURL_test.go | package signedURL
import (
"fmt"
"os"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
// To run this test in verbose mode:
// go clean -testcache ./...
// go test github.com/doc-ai/tensorio-models/signed_url -test.v -count=1
// Need to set GOOGLE_ACCESS_ID to the client e-mails for the repo.
// Need to set PRIVATE_PEM_KEY to the contents of the *.pem file.
// Need to set FLEA_CGS_UPLOAD_BUCKET to a test bucket name
// To generate a *.pem file do:
// - Go to ttps://console.cloud.google.com/iam-admin/
// - Click on the appropriate service account
// - Edit it and Create a key in legacy P12 format - and downlosd it
// - Run: openssl pkcs12 -in key.p12 -passin pass:notasecret -out key.pem -nodes (or whatever password is used)
func Test_URLSigning(t *testing.T) {
if os.Getenv("GOOGLE_ACCESS_ID") == "" ||
os.Getenv("PRIVATE_PEM_KEY") == "" {
fmt.Println("Running this test requires GOOGLE_ACCESS_ID and PRIVATE_PEM_KEY env variables")
return
}
bucket := os.Getenv("FLEA_GCS_UPLOAD_BUCKET")
if bucket == "" {
panic("Please, specify FLEA_GCS_UPLOAD_BUCKET to run this test")
}
fmt.Println("These URLs will expire in 3 minutes. Please, copy and type the curl commands to test!")
signer := NewURLSignerFromEnvVar(bucket)
url, err := signer.GetSignedURL("PUT", "url-signing-test.txt", time.Now().Add(time.Minute*3), "text/plain")
assert.NoError(t, err)
fmt.Println("curl -X PUT -H \"Content-Type: text/plain\" -d \"Uploaded at: $(date)\\n\" \"" + url + "\"")
url, err = signer.GetSignedURL("GET", "url-signing-test.txt", time.Now().Add(time.Minute*3), "") // "text/plain")
assert.NoError(t, err)
fmt.Println("curl \"" + url + "\"")
}
| [
"\"GOOGLE_ACCESS_ID\"",
"\"PRIVATE_PEM_KEY\"",
"\"FLEA_GCS_UPLOAD_BUCKET\""
]
| []
| [
"FLEA_GCS_UPLOAD_BUCKET",
"GOOGLE_ACCESS_ID",
"PRIVATE_PEM_KEY"
]
| [] | ["FLEA_GCS_UPLOAD_BUCKET", "GOOGLE_ACCESS_ID", "PRIVATE_PEM_KEY"] | go | 3 | 0 | |
src/main/java/com/zebrunner/agent/core/registrar/ci/TravisCiContextResolver.java | package com.zebrunner.agent.core.registrar.ci;
import com.zebrunner.agent.core.registrar.domain.CiContextDTO;
import com.zebrunner.agent.core.registrar.domain.CiType;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@NoArgsConstructor(access = AccessLevel.PACKAGE)
class TravisCiContextResolver implements CiContextResolver {
// https://docs.travis-ci.com/user/environment-variables/#default-environment-variables
private static final String TRAVIS_ENV_VARIABLE = "TRAVIS";
private static final List<String> ENV_VARIABLE_PREFIXES = Arrays.asList(
"TRAVIS",
"USER"
);
@Override
public CiContextDTO resolve() {
Map<String, String> envVariables = System.getenv();
if (envVariables.containsKey(TRAVIS_ENV_VARIABLE)) {
envVariables = collectEnvironmentVariables(envVariables);
return new CiContextDTO(CiType.TRAVIS_CI, envVariables);
}
return null;
}
private Map<String, String> collectEnvironmentVariables(Map<String, String> envVariables) {
return envVariables.keySet()
.stream()
.filter(key -> ENV_VARIABLE_PREFIXES.stream()
.anyMatch(key::startsWith))
.collect(Collectors.toMap(Function.identity(), envVariables::get));
}
}
| []
| []
| []
| [] | [] | java | 0 | 0 | |
lxd/instance/drivers/driver_lxc.go | package drivers
import (
"bufio"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/flosch/pongo2"
"github.com/pkg/errors"
"golang.org/x/sys/unix"
liblxc "gopkg.in/lxc/go-lxc.v2"
yaml "gopkg.in/yaml.v2"
"github.com/lxc/lxd/lxd/apparmor"
"github.com/lxc/lxd/lxd/backup"
"github.com/lxc/lxd/lxd/cgroup"
"github.com/lxc/lxd/lxd/cluster"
"github.com/lxc/lxd/lxd/daemon"
"github.com/lxc/lxd/lxd/db"
"github.com/lxc/lxd/lxd/db/query"
"github.com/lxc/lxd/lxd/device"
deviceConfig "github.com/lxc/lxd/lxd/device/config"
"github.com/lxc/lxd/lxd/instance"
"github.com/lxc/lxd/lxd/instance/instancetype"
"github.com/lxc/lxd/lxd/instance/operationlock"
"github.com/lxc/lxd/lxd/maas"
"github.com/lxc/lxd/lxd/network"
"github.com/lxc/lxd/lxd/operations"
"github.com/lxc/lxd/lxd/project"
"github.com/lxc/lxd/lxd/revert"
"github.com/lxc/lxd/lxd/seccomp"
"github.com/lxc/lxd/lxd/state"
storagePools "github.com/lxc/lxd/lxd/storage"
storageDrivers "github.com/lxc/lxd/lxd/storage/drivers"
"github.com/lxc/lxd/lxd/template"
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/idmap"
"github.com/lxc/lxd/shared/instancewriter"
log "github.com/lxc/lxd/shared/log15"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/netutils"
"github.com/lxc/lxd/shared/osarch"
"github.com/lxc/lxd/shared/units"
)
// Helper functions
func lxcSetConfigItem(c *liblxc.Container, key string, value string) error {
if c == nil {
return fmt.Errorf("Uninitialized go-lxc struct")
}
if !util.RuntimeLiblxcVersionAtLeast(2, 1, 0) {
switch key {
case "lxc.uts.name":
key = "lxc.utsname"
case "lxc.pty.max":
key = "lxc.pts"
case "lxc.tty.dir":
key = "lxc.devttydir"
case "lxc.tty.max":
key = "lxc.tty"
case "lxc.apparmor.profile":
key = "lxc.aa_profile"
case "lxc.apparmor.allow_incomplete":
key = "lxc.aa_allow_incomplete"
case "lxc.selinux.context":
key = "lxc.se_context"
case "lxc.mount.fstab":
key = "lxc.mount"
case "lxc.console.path":
key = "lxc.console"
case "lxc.seccomp.profile":
key = "lxc.seccomp"
case "lxc.signal.halt":
key = "lxc.haltsignal"
case "lxc.signal.reboot":
key = "lxc.rebootsignal"
case "lxc.signal.stop":
key = "lxc.stopsignal"
case "lxc.log.syslog":
key = "lxc.syslog"
case "lxc.log.level":
key = "lxc.loglevel"
case "lxc.log.file":
key = "lxc.logfile"
case "lxc.init.cmd":
key = "lxc.init_cmd"
case "lxc.init.uid":
key = "lxc.init_uid"
case "lxc.init.gid":
key = "lxc.init_gid"
case "lxc.idmap":
key = "lxc.id_map"
}
}
if strings.HasPrefix(key, "lxc.prlimit.") {
if !util.RuntimeLiblxcVersionAtLeast(2, 1, 0) {
return fmt.Errorf(`Process limits require liblxc >= 2.1`)
}
}
err := c.SetConfigItem(key, value)
if err != nil {
return fmt.Errorf("Failed to set LXC config: %s=%s", key, value)
}
return nil
}
func lxcStatusCode(state liblxc.State) api.StatusCode {
return map[int]api.StatusCode{
1: api.Stopped,
2: api.Starting,
3: api.Running,
4: api.Stopping,
5: api.Aborting,
6: api.Freezing,
7: api.Frozen,
8: api.Thawed,
9: api.Error,
}[int(state)]
}
// Loader functions
func lxcCreate(s *state.State, args db.InstanceArgs) (instance.Instance, error) {
// Create the container struct
c := &lxc{
state: s,
id: args.ID,
project: args.Project,
name: args.Name,
node: args.Node,
description: args.Description,
ephemeral: args.Ephemeral,
architecture: args.Architecture,
dbType: args.Type,
snapshot: args.Snapshot,
stateful: args.Stateful,
creationDate: args.CreationDate,
lastUsedDate: args.LastUsedDate,
profiles: args.Profiles,
localConfig: args.Config,
localDevices: args.Devices,
expiryDate: args.ExpiryDate,
}
// Cleanup the zero values
if c.expiryDate.IsZero() {
c.expiryDate = time.Time{}
}
if c.creationDate.IsZero() {
c.creationDate = time.Time{}
}
if c.lastUsedDate.IsZero() {
c.lastUsedDate = time.Time{}
}
ctxMap := log.Ctx{
"project": args.Project,
"name": c.name,
"ephemeral": c.ephemeral,
}
logger.Info("Creating container", ctxMap)
// Load the config
err := c.init()
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
// Validate expanded config
err = instance.ValidConfig(s.OS, c.expandedConfig, false, true)
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
err = instance.ValidDevices(s, s.Cluster, c.Type(), c.expandedDevices, true)
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, errors.Wrap(err, "Invalid devices")
}
// Retrieve the container's storage pool
_, rootDiskDevice, err := shared.GetRootDiskDevice(c.expandedDevices.CloneNative())
if err != nil {
c.Delete()
return nil, err
}
if rootDiskDevice["pool"] == "" {
c.Delete()
return nil, fmt.Errorf("The container's root device is missing the pool property")
}
storagePool := rootDiskDevice["pool"]
// Get the storage pool ID for the container
poolID, dbPool, err := s.Cluster.StoragePoolGet(storagePool)
if err != nil {
c.Delete()
return nil, err
}
// Fill in any default volume config
volumeConfig := map[string]string{}
err = storagePools.VolumeFillDefault(storagePool, volumeConfig, dbPool)
if err != nil {
c.Delete()
return nil, err
}
// Create a new database entry for the container's storage volume
if c.IsSnapshot() {
_, err = s.Cluster.StoragePoolVolumeSnapshotCreate(args.Project, args.Name, "", db.StoragePoolVolumeTypeContainer, poolID, volumeConfig, time.Time{})
} else {
_, err = s.Cluster.StoragePoolVolumeCreate(args.Project, args.Name, "", db.StoragePoolVolumeTypeContainer, poolID, volumeConfig)
}
if err != nil {
c.Delete()
return nil, err
}
// Initialize the container storage.
pool, err := storagePools.GetPoolByInstance(c.state, c)
if err != nil {
c.Delete()
s.Cluster.StoragePoolVolumeDelete(args.Project, args.Name, db.StoragePoolVolumeTypeContainer, poolID)
logger.Error("Failed to initialize container storage", ctxMap)
return nil, err
}
c.storagePool = pool
// Setup initial idmap config
var idmap *idmap.IdmapSet
base := int64(0)
if !c.IsPrivileged() {
idmap, base, err = findIdmap(
s,
args.Name,
c.expandedConfig["security.idmap.isolated"],
c.expandedConfig["security.idmap.base"],
c.expandedConfig["security.idmap.size"],
c.expandedConfig["raw.idmap"],
)
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
}
var jsonIdmap string
if idmap != nil {
idmapBytes, err := json.Marshal(idmap.Idmap)
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
jsonIdmap = string(idmapBytes)
} else {
jsonIdmap = "[]"
}
err = c.VolatileSet(map[string]string{"volatile.idmap.next": jsonIdmap})
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
err = c.VolatileSet(map[string]string{"volatile.idmap.base": fmt.Sprintf("%v", base)})
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
// Invalid idmap cache
c.idmapset = nil
// Set last_state if not currently set
if c.localConfig["volatile.last_state.idmap"] == "" {
err = c.VolatileSet(map[string]string{"volatile.last_state.idmap": "[]"})
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
}
// Re-run init to update the idmap
err = c.init()
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
if !c.IsSnapshot() {
// Add devices to container.
for k, m := range c.expandedDevices {
err = c.deviceAdd(k, m)
if err != nil && err != device.ErrUnsupportedDevType {
c.Delete()
return nil, errors.Wrapf(err, "Failed to add device '%s'", k)
}
}
// Update MAAS (must run after the MAC addresses have been generated).
err = c.maasUpdate(nil)
if err != nil {
c.Delete()
logger.Error("Failed creating container", ctxMap)
return nil, err
}
}
logger.Info("Created container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-created",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return c, nil
}
func lxcLoad(s *state.State, args db.InstanceArgs, profiles []api.Profile) (instance.Instance, error) {
// Create the container struct
c := lxcInstantiate(s, args, nil)
// Setup finalizer
runtime.SetFinalizer(c, lxcUnload)
// Expand config and devices
err := c.(*lxc).expandConfig(profiles)
if err != nil {
return nil, err
}
err = c.(*lxc).expandDevices(profiles)
if err != nil {
return nil, err
}
return c, nil
}
// Unload is called by the garbage collector
func lxcUnload(c *lxc) {
runtime.SetFinalizer(c, nil)
if c.c != nil {
c.c.Release()
c.c = nil
}
}
// Create a container struct without initializing it.
func lxcInstantiate(s *state.State, args db.InstanceArgs, expandedDevices deviceConfig.Devices) instance.Instance {
c := &lxc{
state: s,
id: args.ID,
project: args.Project,
name: args.Name,
description: args.Description,
ephemeral: args.Ephemeral,
architecture: args.Architecture,
dbType: args.Type,
snapshot: args.Snapshot,
creationDate: args.CreationDate,
lastUsedDate: args.LastUsedDate,
profiles: args.Profiles,
localConfig: args.Config,
localDevices: args.Devices,
stateful: args.Stateful,
node: args.Node,
expiryDate: args.ExpiryDate,
}
// Cleanup the zero values
if c.expiryDate.IsZero() {
c.expiryDate = time.Time{}
}
if c.creationDate.IsZero() {
c.creationDate = time.Time{}
}
if c.lastUsedDate.IsZero() {
c.lastUsedDate = time.Time{}
}
// This is passed during expanded config validation.
if expandedDevices != nil {
c.expandedDevices = expandedDevices
}
return c
}
// The LXC container driver.
type lxc struct {
// Properties
architecture int
dbType instancetype.Type
snapshot bool
creationDate time.Time
lastUsedDate time.Time
ephemeral bool
id int
project string
name string
description string
stateful bool
// Config
expandedConfig map[string]string
expandedDevices deviceConfig.Devices
fromHook bool
localConfig map[string]string
localDevices deviceConfig.Devices
profiles []string
// Cache
c *liblxc.Container
cConfig bool
state *state.State
idmapset *idmap.IdmapSet
// Storage
// Do not use this variable directly, instead use their associated get functions so they
// will be initialised on demand.
storagePool storagePools.Pool
// Clustering
node string
// Progress tracking
op *operations.Operation
expiryDate time.Time
}
// Type returns the instance type.
func (c *lxc) Type() instancetype.Type {
return c.dbType
}
func idmapSize(state *state.State, isolatedStr string, size string) (int64, error) {
isolated := false
if shared.IsTrue(isolatedStr) {
isolated = true
}
var idMapSize int64
if size == "" || size == "auto" {
if isolated {
idMapSize = 65536
} else {
if len(state.OS.IdmapSet.Idmap) != 2 {
return 0, fmt.Errorf("bad initial idmap: %v", state.OS.IdmapSet)
}
idMapSize = state.OS.IdmapSet.Idmap[0].Maprange
}
} else {
size, err := strconv.ParseInt(size, 10, 64)
if err != nil {
return 0, err
}
idMapSize = size
}
return idMapSize, nil
}
var idmapLock sync.Mutex
func findIdmap(state *state.State, cName string, isolatedStr string, configBase string, configSize string, rawIdmap string) (*idmap.IdmapSet, int64, error) {
isolated := false
if shared.IsTrue(isolatedStr) {
isolated = true
}
rawMaps, err := instance.ParseRawIdmap(rawIdmap)
if err != nil {
return nil, 0, err
}
if !isolated {
newIdmapset := idmap.IdmapSet{Idmap: make([]idmap.IdmapEntry, len(state.OS.IdmapSet.Idmap))}
copy(newIdmapset.Idmap, state.OS.IdmapSet.Idmap)
for _, ent := range rawMaps {
err := newIdmapset.AddSafe(ent)
if err != nil && err == idmap.ErrHostIdIsSubId {
return nil, 0, err
}
}
return &newIdmapset, 0, nil
}
size, err := idmapSize(state, isolatedStr, configSize)
if err != nil {
return nil, 0, err
}
mkIdmap := func(offset int64, size int64) (*idmap.IdmapSet, error) {
set := &idmap.IdmapSet{Idmap: []idmap.IdmapEntry{
{Isuid: true, Nsid: 0, Hostid: offset, Maprange: size},
{Isgid: true, Nsid: 0, Hostid: offset, Maprange: size},
}}
for _, ent := range rawMaps {
err := set.AddSafe(ent)
if err != nil && err == idmap.ErrHostIdIsSubId {
return nil, err
}
}
return set, nil
}
if configBase != "" {
offset, err := strconv.ParseInt(configBase, 10, 64)
if err != nil {
return nil, 0, err
}
set, err := mkIdmap(offset, size)
if err != nil && err == idmap.ErrHostIdIsSubId {
return nil, 0, err
}
return set, offset, nil
}
idmapLock.Lock()
defer idmapLock.Unlock()
cts, err := instance.LoadNodeAll(state, instancetype.Container)
if err != nil {
return nil, 0, err
}
offset := state.OS.IdmapSet.Idmap[0].Hostid + 65536
mapentries := idmap.ByHostid{}
for _, container := range cts {
if container.Type() != instancetype.Container {
continue
}
name := container.Name()
/* Don't change our map Just Because. */
if name == cName {
continue
}
if container.IsPrivileged() {
continue
}
if !shared.IsTrue(container.ExpandedConfig()["security.idmap.isolated"]) {
continue
}
cBase := int64(0)
if container.ExpandedConfig()["volatile.idmap.base"] != "" {
cBase, err = strconv.ParseInt(container.ExpandedConfig()["volatile.idmap.base"], 10, 64)
if err != nil {
return nil, 0, err
}
}
cSize, err := idmapSize(state, container.ExpandedConfig()["security.idmap.isolated"], container.ExpandedConfig()["security.idmap.size"])
if err != nil {
return nil, 0, err
}
mapentries = append(mapentries, &idmap.IdmapEntry{Hostid: int64(cBase), Maprange: cSize})
}
sort.Sort(mapentries)
for i := range mapentries {
if i == 0 {
if mapentries[0].Hostid < offset+size {
offset = mapentries[0].Hostid + mapentries[0].Maprange
continue
}
set, err := mkIdmap(offset, size)
if err != nil && err == idmap.ErrHostIdIsSubId {
return nil, 0, err
}
return set, offset, nil
}
if mapentries[i-1].Hostid+mapentries[i-1].Maprange > offset {
offset = mapentries[i-1].Hostid + mapentries[i-1].Maprange
continue
}
offset = mapentries[i-1].Hostid + mapentries[i-1].Maprange
if offset+size < mapentries[i].Hostid {
set, err := mkIdmap(offset, size)
if err != nil && err == idmap.ErrHostIdIsSubId {
return nil, 0, err
}
return set, offset, nil
}
offset = mapentries[i].Hostid + mapentries[i].Maprange
}
if offset+size < state.OS.IdmapSet.Idmap[0].Hostid+state.OS.IdmapSet.Idmap[0].Maprange {
set, err := mkIdmap(offset, size)
if err != nil && err == idmap.ErrHostIdIsSubId {
return nil, 0, err
}
return set, offset, nil
}
return nil, 0, fmt.Errorf("Not enough uid/gid available for the container")
}
func (c *lxc) init() error {
// Compute the expanded config and device list
err := c.expandConfig(nil)
if err != nil {
return err
}
err = c.expandDevices(nil)
if err != nil {
return err
}
return nil
}
func (c *lxc) initLXC(config bool) error {
// No need to go through all that for snapshots
if c.IsSnapshot() {
return nil
}
// Check if being called from a hook
if c.fromHook {
return fmt.Errorf("You can't use go-lxc from inside a LXC hook")
}
// Check if already initialized
if c.c != nil {
if !config || c.cConfig {
return nil
}
}
// Load the go-lxc struct
cname := project.Instance(c.Project(), c.Name())
cc, err := liblxc.NewContainer(cname, c.state.OS.LxcPath)
if err != nil {
return err
}
// Load cgroup abstraction
cg, err := c.cgroup(cc)
if err != nil {
return err
}
freeContainer := true
defer func() {
if freeContainer {
cc.Release()
}
}()
// Setup logging
logfile := c.LogFilePath()
err = lxcSetConfigItem(cc, "lxc.log.file", logfile)
if err != nil {
return err
}
logLevel := "warn"
if daemon.Debug {
logLevel = "trace"
} else if daemon.Verbose {
logLevel = "info"
}
err = lxcSetConfigItem(cc, "lxc.log.level", logLevel)
if err != nil {
return err
}
if util.RuntimeLiblxcVersionAtLeast(3, 0, 0) {
// Default size log buffer
err = lxcSetConfigItem(cc, "lxc.console.buffer.size", "auto")
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.console.size", "auto")
if err != nil {
return err
}
// File to dump ringbuffer contents to when requested or
// container shutdown.
consoleBufferLogFile := c.ConsoleBufferLogPath()
err = lxcSetConfigItem(cc, "lxc.console.logfile", consoleBufferLogFile)
if err != nil {
return err
}
}
// Allow for lightweight init
c.cConfig = config
if !config {
if c.c != nil {
c.c.Release()
}
c.c = cc
freeContainer = false
return nil
}
if c.IsPrivileged() {
// Base config
toDrop := "sys_time sys_module sys_rawio"
if !c.state.OS.AppArmorStacking || c.state.OS.AppArmorStacked {
toDrop = toDrop + " mac_admin mac_override"
}
err = lxcSetConfigItem(cc, "lxc.cap.drop", toDrop)
if err != nil {
return err
}
}
// Set an appropriate /proc, /sys/ and /sys/fs/cgroup
mounts := []string{}
if c.IsPrivileged() && !c.state.OS.RunningInUserNS {
mounts = append(mounts, "proc:mixed")
mounts = append(mounts, "sys:mixed")
} else {
mounts = append(mounts, "proc:rw")
mounts = append(mounts, "sys:rw")
}
cgInfo := cgroup.GetInfo()
if cgInfo.Namespacing {
if cgInfo.Layout == cgroup.CgroupsUnified {
mounts = append(mounts, "cgroup:rw:force")
} else {
mounts = append(mounts, "cgroup:mixed")
}
} else {
mounts = append(mounts, "cgroup:mixed")
}
err = lxcSetConfigItem(cc, "lxc.mount.auto", strings.Join(mounts, " "))
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.autodev", "1")
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.pty.max", "1024")
if err != nil {
return err
}
bindMounts := []string{
"/dev/fuse",
"/dev/net/tun",
"/proc/sys/fs/binfmt_misc",
"/sys/firmware/efi/efivars",
"/sys/fs/fuse/connections",
"/sys/fs/pstore",
"/sys/kernel/config",
"/sys/kernel/debug",
"/sys/kernel/security",
"/sys/kernel/tracing",
}
if c.IsPrivileged() && !c.state.OS.RunningInUserNS {
err = lxcSetConfigItem(cc, "lxc.mount.entry", "mqueue dev/mqueue mqueue rw,relatime,create=dir,optional 0 0")
if err != nil {
return err
}
} else {
bindMounts = append(bindMounts, "/dev/mqueue")
}
for _, mnt := range bindMounts {
if !shared.PathExists(mnt) {
continue
}
if shared.IsDir(mnt) {
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s %s none rbind,create=dir,optional 0 0", mnt, strings.TrimPrefix(mnt, "/")))
if err != nil {
return err
}
} else {
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s %s none bind,create=file,optional 0 0", mnt, strings.TrimPrefix(mnt, "/")))
if err != nil {
return err
}
}
}
// For lxcfs
templateConfDir := os.Getenv("LXD_LXC_TEMPLATE_CONFIG")
if templateConfDir == "" {
templateConfDir = "/usr/share/lxc/config"
}
if shared.PathExists(fmt.Sprintf("%s/common.conf.d/", templateConfDir)) {
err = lxcSetConfigItem(cc, "lxc.include", fmt.Sprintf("%s/common.conf.d/", templateConfDir))
if err != nil {
return err
}
}
// Configure devices cgroup
if c.IsPrivileged() && !c.state.OS.RunningInUserNS && c.state.OS.CGInfo.Supports(cgroup.Devices, cg) {
err = lxcSetConfigItem(cc, "lxc.cgroup.devices.deny", "a")
if err != nil {
return err
}
devices := []string{
"b *:* m", // Allow mknod of block devices
"c *:* m", // Allow mknod of char devices
"c 136:* rwm", // /dev/pts devices
"c 1:3 rwm", // /dev/null
"c 1:5 rwm", // /dev/zero
"c 1:7 rwm", // /dev/full
"c 1:8 rwm", // /dev/random
"c 1:9 rwm", // /dev/urandom
"c 5:0 rwm", // /dev/tty
"c 5:1 rwm", // /dev/console
"c 5:2 rwm", // /dev/ptmx
"c 10:229 rwm", // /dev/fuse
"c 10:200 rwm", // /dev/net/tun
}
for _, dev := range devices {
err = lxcSetConfigItem(cc, "lxc.cgroup.devices.allow", dev)
if err != nil {
return err
}
}
}
if c.IsNesting() {
/*
* mount extra /proc and /sys to work around kernel
* restrictions on remounting them when covered
*/
err = lxcSetConfigItem(cc, "lxc.mount.entry", "proc dev/.lxc/proc proc create=dir,optional 0 0")
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.mount.entry", "sys dev/.lxc/sys sysfs create=dir,optional 0 0")
if err != nil {
return err
}
}
// Setup architecture
personality, err := osarch.ArchitecturePersonality(c.architecture)
if err != nil {
personality, err = osarch.ArchitecturePersonality(c.state.OS.Architectures[0])
if err != nil {
return err
}
}
err = lxcSetConfigItem(cc, "lxc.arch", personality)
if err != nil {
return err
}
// Setup the hooks
err = lxcSetConfigItem(cc, "lxc.hook.version", "1")
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.hook.pre-start", fmt.Sprintf("/proc/%d/exe callhook %s %d start", os.Getpid(), shared.VarPath(""), c.id))
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.hook.stop", fmt.Sprintf("%s callhook %s %d stopns", c.state.OS.ExecPath, shared.VarPath(""), c.id))
if err != nil {
return err
}
err = lxcSetConfigItem(cc, "lxc.hook.post-stop", fmt.Sprintf("%s callhook %s %d stop", c.state.OS.ExecPath, shared.VarPath(""), c.id))
if err != nil {
return err
}
// Setup the console
err = lxcSetConfigItem(cc, "lxc.tty.max", "0")
if err != nil {
return err
}
// Setup the hostname
err = lxcSetConfigItem(cc, "lxc.uts.name", c.Name())
if err != nil {
return err
}
// Setup devlxd
if c.expandedConfig["security.devlxd"] == "" || shared.IsTrue(c.expandedConfig["security.devlxd"]) {
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s dev/lxd none bind,create=dir 0 0", shared.VarPath("devlxd")))
if err != nil {
return err
}
}
// Setup AppArmor
if c.state.OS.AppArmorAvailable {
if c.state.OS.AppArmorConfined || !c.state.OS.AppArmorAdmin {
// If confined but otherwise able to use AppArmor, use our own profile
curProfile := util.AppArmorProfile()
curProfile = strings.TrimSuffix(curProfile, " (enforce)")
err := lxcSetConfigItem(cc, "lxc.apparmor.profile", curProfile)
if err != nil {
return err
}
} else {
// If not currently confined, use the container's profile
profile := apparmor.ProfileFull(c)
/* In the nesting case, we want to enable the inside
* LXD to load its profile. Unprivileged containers can
* load profiles, but privileged containers cannot, so
* let's not use a namespace so they can fall back to
* the old way of nesting, i.e. using the parent's
* profile.
*/
if c.state.OS.AppArmorStacking && !c.state.OS.AppArmorStacked {
profile = fmt.Sprintf("%s//&:%s:", profile, apparmor.Namespace(c))
}
err := lxcSetConfigItem(cc, "lxc.apparmor.profile", profile)
if err != nil {
return err
}
}
}
// Setup Seccomp if necessary
if seccomp.InstanceNeedsPolicy(c) {
err = lxcSetConfigItem(cc, "lxc.seccomp.profile", seccomp.ProfilePath(c))
if err != nil {
return err
}
// Setup notification socket
// System requirement errors are handled during policy generation instead of here
ok, err := seccomp.InstanceNeedsIntercept(c.state, c)
if err == nil && ok {
err = lxcSetConfigItem(cc, "lxc.seccomp.notify.proxy", fmt.Sprintf("unix:%s", shared.VarPath("seccomp.socket")))
if err != nil {
return err
}
}
}
// Setup idmap
idmapset, err := c.NextIdmap()
if err != nil {
return err
}
if idmapset != nil {
lines := idmapset.ToLxcString()
for _, line := range lines {
err := lxcSetConfigItem(cc, "lxc.idmap", line)
if err != nil {
return err
}
}
}
// Setup environment
for k, v := range c.expandedConfig {
if strings.HasPrefix(k, "environment.") {
err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("%s=%s", strings.TrimPrefix(k, "environment."), v))
if err != nil {
return err
}
}
}
// Setup NVIDIA runtime
if shared.IsTrue(c.expandedConfig["nvidia.runtime"]) {
hookDir := os.Getenv("LXD_LXC_HOOK")
if hookDir == "" {
hookDir = "/usr/share/lxc/hooks"
}
hookPath := filepath.Join(hookDir, "nvidia")
if !shared.PathExists(hookPath) {
return fmt.Errorf("The NVIDIA LXC hook couldn't be found")
}
_, err := exec.LookPath("nvidia-container-cli")
if err != nil {
return fmt.Errorf("The NVIDIA container tools couldn't be found")
}
err = lxcSetConfigItem(cc, "lxc.environment", "NVIDIA_VISIBLE_DEVICES=none")
if err != nil {
return err
}
nvidiaDriver := c.expandedConfig["nvidia.driver.capabilities"]
if nvidiaDriver == "" {
err = lxcSetConfigItem(cc, "lxc.environment", "NVIDIA_DRIVER_CAPABILITIES=compute,utility")
if err != nil {
return err
}
} else {
err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("NVIDIA_DRIVER_CAPABILITIES=%s", nvidiaDriver))
if err != nil {
return err
}
}
nvidiaRequireCuda := c.expandedConfig["nvidia.require.cuda"]
if nvidiaRequireCuda == "" {
err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("NVIDIA_REQUIRE_CUDA=%s", nvidiaRequireCuda))
if err != nil {
return err
}
}
nvidiaRequireDriver := c.expandedConfig["nvidia.require.driver"]
if nvidiaRequireDriver == "" {
err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("NVIDIA_REQUIRE_DRIVER=%s", nvidiaRequireDriver))
if err != nil {
return err
}
}
err = lxcSetConfigItem(cc, "lxc.hook.mount", hookPath)
if err != nil {
return err
}
}
// Memory limits
if c.state.OS.CGInfo.Supports(cgroup.Memory, cg) {
memory := c.expandedConfig["limits.memory"]
memoryEnforce := c.expandedConfig["limits.memory.enforce"]
memorySwap := c.expandedConfig["limits.memory.swap"]
memorySwapPriority := c.expandedConfig["limits.memory.swap.priority"]
// Configure the memory limits
if memory != "" {
var valueInt int64
if strings.HasSuffix(memory, "%") {
percent, err := strconv.ParseInt(strings.TrimSuffix(memory, "%"), 10, 64)
if err != nil {
return err
}
memoryTotal, err := shared.DeviceTotalMemory()
if err != nil {
return err
}
valueInt = int64((memoryTotal / 100) * percent)
} else {
valueInt, err = units.ParseByteSizeString(memory)
if err != nil {
return err
}
}
if memoryEnforce == "soft" {
err = cg.SetMemorySoftLimit(fmt.Sprintf("%d", valueInt))
if err != nil {
return err
}
} else {
if c.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) && (memorySwap == "" || shared.IsTrue(memorySwap)) {
err = cg.SetMemoryMaxUsage(fmt.Sprintf("%d", valueInt))
if err != nil {
return err
}
err = cg.SetMemorySwapMax(fmt.Sprintf("%d", valueInt))
if err != nil {
return err
}
} else {
err = cg.SetMemoryMaxUsage(fmt.Sprintf("%d", valueInt))
if err != nil {
return err
}
}
// Set soft limit to value 10% less than hard limit
err = cg.SetMemorySoftLimit(fmt.Sprintf("%.0f", float64(valueInt)*0.9))
if err != nil {
return err
}
}
}
if c.state.OS.CGInfo.Supports(cgroup.MemorySwappiness, cg) {
// Configure the swappiness
if memorySwap != "" && !shared.IsTrue(memorySwap) {
err = cg.SetMemorySwappiness("0")
if err != nil {
return err
}
} else if memorySwapPriority != "" {
priority, err := strconv.Atoi(memorySwapPriority)
if err != nil {
return err
}
err = cg.SetMemorySwappiness(fmt.Sprintf("%d", 60-10+priority))
if err != nil {
return err
}
}
}
}
// CPU limits
cpuPriority := c.expandedConfig["limits.cpu.priority"]
cpuAllowance := c.expandedConfig["limits.cpu.allowance"]
if (cpuPriority != "" || cpuAllowance != "") && c.state.OS.CGInfo.Supports(cgroup.CPU, cg) {
cpuShares, cpuCfsQuota, cpuCfsPeriod, err := cgroup.ParseCPU(cpuAllowance, cpuPriority)
if err != nil {
return err
}
if cpuShares != "1024" {
err = cg.SetCPUShare(cpuShares)
if err != nil {
return err
}
}
if cpuCfsPeriod != "-1" {
err = cg.SetCPUCfsPeriod(cpuCfsPeriod)
if err != nil {
return err
}
}
if cpuCfsQuota != "-1" {
err = cg.SetCPUCfsQuota(cpuCfsQuota)
if err != nil {
return err
}
}
}
// Processes
if c.state.OS.CGInfo.Supports(cgroup.Pids, cg) {
processes := c.expandedConfig["limits.processes"]
if processes != "" {
valueInt, err := strconv.ParseInt(processes, 10, 64)
if err != nil {
return err
}
err = cg.SetMaxProcesses(valueInt)
if err != nil {
return err
}
}
}
// Hugepages
if c.state.OS.CGInfo.Supports(cgroup.Hugetlb, cg) {
for i, key := range shared.HugePageSizeKeys {
value := c.expandedConfig[key]
if value != "" {
valueInt, err := units.ParseByteSizeString(value)
if err != nil {
return err
}
value = fmt.Sprintf("%d", valueInt)
err = cg.SetMaxHugepages(shared.HugePageSizeSuffix[i], value)
if err != nil {
return err
}
}
}
}
// Setup process limits
for k, v := range c.expandedConfig {
if strings.HasPrefix(k, "limits.kernel.") {
prlimitSuffix := strings.TrimPrefix(k, "limits.kernel.")
prlimitKey := fmt.Sprintf("lxc.prlimit.%s", prlimitSuffix)
err = lxcSetConfigItem(cc, prlimitKey, v)
if err != nil {
return err
}
}
}
// Setup shmounts
if c.state.OS.LXCFeatures["mount_injection_file"] {
err = lxcSetConfigItem(cc, "lxc.mount.auto", fmt.Sprintf("shmounts:%s:/dev/.lxd-mounts", c.ShmountsPath()))
} else {
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s dev/.lxd-mounts none bind,create=dir 0 0", c.ShmountsPath()))
}
if err != nil {
return err
}
// Apply raw.lxc
if lxcConfig, ok := c.expandedConfig["raw.lxc"]; ok {
f, err := ioutil.TempFile("", "lxd_config_")
if err != nil {
return err
}
err = shared.WriteAll(f, []byte(lxcConfig))
f.Close()
defer os.Remove(f.Name())
if err != nil {
return err
}
if err := cc.LoadConfigFile(f.Name()); err != nil {
return fmt.Errorf("Failed to load raw.lxc")
}
}
if c.c != nil {
c.c.Release()
}
c.c = cc
freeContainer = false
return nil
}
func (c *lxc) devlxdEventSend(eventType string, eventMessage interface{}) error {
event := shared.Jmap{}
event["type"] = eventType
event["timestamp"] = time.Now()
event["metadata"] = eventMessage
return c.state.DevlxdEvents.Send(strconv.Itoa(c.ID()), eventType, eventMessage)
}
// runHooks executes the callback functions returned from a function.
func (c *lxc) runHooks(hooks []func() error) error {
// Run any post start hooks.
if len(hooks) > 0 {
for _, hook := range hooks {
err := hook()
if err != nil {
return err
}
}
}
return nil
}
// RegisterDevices calls the Register() function on all of the instance's devices.
func (c *lxc) RegisterDevices() {
devices := c.ExpandedDevices()
for _, dev := range devices.Sorted() {
d, _, err := c.deviceLoad(dev.Name, dev.Config)
if err == device.ErrUnsupportedDevType {
continue
}
if err != nil {
logger.Error("Failed to load device to register", log.Ctx{"err": err, "instance": c.Name(), "device": dev.Name})
continue
}
// Check whether device wants to register for any events.
err = d.Register()
if err != nil {
logger.Error("Failed to register device", log.Ctx{"err": err, "instance": c.Name(), "device": dev.Name})
continue
}
}
}
// deviceLoad instantiates and validates a new device and returns it along with enriched config.
func (c *lxc) deviceLoad(deviceName string, rawConfig deviceConfig.Device) (device.Device, deviceConfig.Device, error) {
var configCopy deviceConfig.Device
var err error
// Create copy of config and load some fields from volatile if device is nic or infiniband.
if shared.StringInSlice(rawConfig["type"], []string{"nic", "infiniband"}) {
configCopy, err = c.FillNetworkDevice(deviceName, rawConfig)
if err != nil {
return nil, nil, err
}
} else {
// Othewise copy the config so it cannot be modified by device.
configCopy = rawConfig.Clone()
}
d, err := device.New(c, c.state, deviceName, configCopy, c.deviceVolatileGetFunc(deviceName), c.deviceVolatileSetFunc(deviceName))
// Return device and config copy even if error occurs as caller may still use device.
return d, configCopy, err
}
// deviceAdd loads a new device and calls its Add() function.
func (c *lxc) deviceAdd(deviceName string, rawConfig deviceConfig.Device) error {
d, _, err := c.deviceLoad(deviceName, rawConfig)
if err != nil {
return err
}
return d.Add()
}
// deviceStart loads a new device and calls its Start() function. After processing the runtime
// config returned from Start(), it also runs the device's Register() function irrespective of
// whether the container is running or not.
func (c *lxc) deviceStart(deviceName string, rawConfig deviceConfig.Device, isRunning bool) (*deviceConfig.RunConfig, error) {
d, configCopy, err := c.deviceLoad(deviceName, rawConfig)
if err != nil {
return nil, err
}
if canHotPlug, _ := d.CanHotPlug(); isRunning && !canHotPlug {
return nil, fmt.Errorf("Device cannot be started when container is running")
}
runConf, err := d.Start()
if err != nil {
return nil, err
}
// If runConf supplied, perform any container specific setup of device.
if runConf != nil {
// Shift device file ownership if needed before mounting into container.
// This needs to be done whether or not container is running.
if len(runConf.Mounts) > 0 {
err := c.deviceStaticShiftMounts(runConf.Mounts)
if err != nil {
return nil, err
}
}
// If container is running and then live attach device.
if isRunning {
// Attach mounts if requested.
if len(runConf.Mounts) > 0 {
err = c.deviceHandleMounts(runConf.Mounts)
if err != nil {
return nil, err
}
}
// Add cgroup rules if requested.
if len(runConf.CGroups) > 0 {
err = c.deviceAddCgroupRules(runConf.CGroups)
if err != nil {
return nil, err
}
}
// Attach network interface if requested.
if len(runConf.NetworkInterface) > 0 {
err = c.deviceAttachNIC(configCopy, runConf.NetworkInterface)
if err != nil {
return nil, err
}
}
// If running, run post start hooks now (if not running LXD will run them
// once the instance is started).
err = c.runHooks(runConf.PostHooks)
if err != nil {
return nil, err
}
}
}
return runConf, nil
}
// deviceStaticShiftMounts statically shift device mount files ownership to active idmap if needed.
func (c *lxc) deviceStaticShiftMounts(mounts []deviceConfig.MountEntryItem) error {
idmapSet, err := c.CurrentIdmap()
if err != nil {
return fmt.Errorf("Failed to get idmap for device: %s", err)
}
// If there is an idmap being applied and LXD not running in a user namespace then shift the
// device files before they are mounted.
if idmapSet != nil && !c.state.OS.RunningInUserNS {
for _, mount := range mounts {
// Skip UID/GID shifting if OwnerShift mode is not static, or the host-side
// DevPath is empty (meaning an unmount request that doesn't need shifting).
if mount.OwnerShift != deviceConfig.MountOwnerShiftStatic || mount.DevPath == "" {
continue
}
err := idmapSet.ShiftFile(mount.DevPath)
if err != nil {
// uidshift failing is weird, but not a big problem. Log and proceed.
logger.Debugf("Failed to uidshift device %s: %s\n", mount.DevPath, err)
}
}
}
return nil
}
// deviceAddCgroupRules live adds cgroup rules to a container.
func (c *lxc) deviceAddCgroupRules(cgroups []deviceConfig.RunConfigItem) error {
cg, err := c.cgroup(nil)
if err != nil {
return err
}
for _, rule := range cgroups {
// Only apply devices cgroup rules if container is running privileged and host has devices cgroup controller.
if strings.HasPrefix(rule.Key, "devices.") && (!c.isCurrentlyPrivileged() || c.state.OS.RunningInUserNS || !c.state.OS.CGInfo.Supports(cgroup.Devices, cg)) {
continue
}
// Add the new device cgroup rule.
err := c.CGroupSet(rule.Key, rule.Value)
if err != nil {
return fmt.Errorf("Failed to add cgroup rule for device")
}
}
return nil
}
// deviceAttachNIC live attaches a NIC device to a container.
func (c *lxc) deviceAttachNIC(configCopy map[string]string, netIF []deviceConfig.RunConfigItem) error {
devName := ""
for _, dev := range netIF {
if dev.Key == "link" {
devName = dev.Value
break
}
}
if devName == "" {
return fmt.Errorf("Device didn't provide a link property to use")
}
// Load the go-lxc struct.
err := c.initLXC(false)
if err != nil {
return err
}
// Add the interface to the container.
err = c.c.AttachInterface(devName, configCopy["name"])
if err != nil {
return fmt.Errorf("Failed to attach interface: %s to %s: %s", devName, configCopy["name"], err)
}
return nil
}
// deviceUpdate loads a new device and calls its Update() function.
func (c *lxc) deviceUpdate(deviceName string, rawConfig deviceConfig.Device, oldDevices deviceConfig.Devices, isRunning bool) error {
d, _, err := c.deviceLoad(deviceName, rawConfig)
if err != nil {
return err
}
err = d.Update(oldDevices, isRunning)
if err != nil {
return err
}
return nil
}
// deviceStop loads a new device and calls its Stop() function.
func (c *lxc) deviceStop(deviceName string, rawConfig deviceConfig.Device, stopHookNetnsPath string) error {
d, configCopy, err := c.deviceLoad(deviceName, rawConfig)
// If deviceLoad fails with unsupported device type then return.
if err == device.ErrUnsupportedDevType {
return err
}
// If deviceLoad fails for any other reason then just log the error and proceed, as in the
// scenario that a new version of LXD has additional validation restrictions than older
// versions we still need to allow previously valid devices to be stopped.
if err != nil {
// If there is no device returned, then we cannot proceed, so return as error.
if d == nil {
return fmt.Errorf("Device stop validation failed for '%s': %v", deviceName, err)
}
logger.Errorf("Device stop validation failed for '%s': %v", deviceName, err)
}
canHotPlug, _ := d.CanHotPlug()
// An empty netns path means we haven't been called from the LXC stop hook, so are running.
if stopHookNetnsPath == "" && !canHotPlug {
return fmt.Errorf("Device cannot be stopped when container is running")
}
runConf, err := d.Stop()
if err != nil {
return err
}
if runConf != nil {
// If network interface settings returned, then detach NIC from container.
if len(runConf.NetworkInterface) > 0 {
err = c.deviceDetachNIC(configCopy, runConf.NetworkInterface, stopHookNetnsPath)
if err != nil {
return err
}
}
// Add cgroup rules if requested and container is running.
if len(runConf.CGroups) > 0 && stopHookNetnsPath == "" {
err = c.deviceAddCgroupRules(runConf.CGroups)
if err != nil {
return err
}
}
// Detach mounts if requested and container is running.
if len(runConf.Mounts) > 0 && stopHookNetnsPath == "" {
err = c.deviceHandleMounts(runConf.Mounts)
if err != nil {
return err
}
}
// Run post stop hooks irrespective of run state of instance.
err = c.runHooks(runConf.PostHooks)
if err != nil {
return err
}
}
return nil
}
// deviceDetachNIC detaches a NIC device from a container.
func (c *lxc) deviceDetachNIC(configCopy map[string]string, netIF []deviceConfig.RunConfigItem, stopHookNetnsPath string) error {
// Get requested device name to detach interface back to on the host.
devName := ""
for _, dev := range netIF {
if dev.Key == "link" {
devName = dev.Value
break
}
}
if devName == "" {
return fmt.Errorf("Device didn't provide a link property to use")
}
// If container is running, perform live detach of interface back to host.
if stopHookNetnsPath == "" {
// For some reason, having network config confuses detach, so get our own go-lxc struct.
cname := project.Instance(c.Project(), c.Name())
cc, err := liblxc.NewContainer(cname, c.state.OS.LxcPath)
if err != nil {
return err
}
defer cc.Release()
// Get interfaces inside container.
ifaces, err := cc.Interfaces()
if err != nil {
return fmt.Errorf("Failed to list network interfaces: %v", err)
}
// If interface doesn't exist inside container, cannot proceed.
if !shared.StringInSlice(configCopy["name"], ifaces) {
return nil
}
err = cc.DetachInterfaceRename(configCopy["name"], devName)
if err != nil {
return errors.Wrapf(err, "Failed to detach interface: %s to %s", configCopy["name"], devName)
}
} else {
// Currently liblxc does not move devices back to the host on stop that were added
// after the the container was started. For this reason we utilise the lxc.hook.stop
// hook so that we can capture the netns path, enter the namespace and move the nics
// back to the host and rename them if liblxc hasn't already done it.
// We can only move back devices that have an expected host_name record and where
// that device doesn't already exist on the host as if a device exists on the host
// we can't know whether that is because liblxc has moved it back already or whether
// it is a conflicting device.
if !shared.PathExists(fmt.Sprintf("/sys/class/net/%s", devName)) {
err := c.detachInterfaceRename(stopHookNetnsPath, configCopy["name"], devName)
if err != nil {
return errors.Wrapf(err, "Failed to detach interface: %s to %s", configCopy["name"], devName)
}
}
}
return nil
}
// deviceHandleMounts live attaches or detaches mounts on a container.
// If the mount DevPath is empty the mount action is treated as unmount.
func (c *lxc) deviceHandleMounts(mounts []deviceConfig.MountEntryItem) error {
for _, mount := range mounts {
if mount.DevPath != "" {
flags := 0
// Convert options into flags.
for _, opt := range mount.Opts {
if opt == "bind" {
flags |= unix.MS_BIND
} else if opt == "rbind" {
flags |= unix.MS_BIND | unix.MS_REC
}
}
shiftfs := false
if mount.OwnerShift == deviceConfig.MountOwnerShiftDynamic {
shiftfs = true
}
// Mount it into the container.
err := c.insertMount(mount.DevPath, mount.TargetPath, mount.FSType, flags, shiftfs)
if err != nil {
return fmt.Errorf("Failed to add mount for device inside container: %s", err)
}
} else {
relativeTargetPath := strings.TrimPrefix(mount.TargetPath, "/")
if c.FileExists(relativeTargetPath) == nil {
err := c.removeMount(mount.TargetPath)
if err != nil {
return fmt.Errorf("Error unmounting the device path inside container: %s", err)
}
err = c.FileRemove(relativeTargetPath)
if err != nil {
// Only warn here and don't fail as removing a directory
// mount may fail if there was already files inside
// directory before it was mouted over preventing delete.
logger.Warnf("Could not remove the device path inside container: %s", err)
}
}
}
}
return nil
}
// deviceRemove loads a new device and calls its Remove() function.
func (c *lxc) deviceRemove(deviceName string, rawConfig deviceConfig.Device) error {
d, _, err := c.deviceLoad(deviceName, rawConfig)
// If deviceLoad fails with unsupported device type then return.
if err == device.ErrUnsupportedDevType {
return err
}
// If deviceLoad fails for any other reason then just log the error and proceed, as in the
// scenario that a new version of LXD has additional validation restrictions than older
// versions we still need to allow previously valid devices to be stopped.
if err != nil {
logger.Errorf("Device remove validation failed for '%s': %v", deviceName, err)
}
return d.Remove()
}
// deviceVolatileGetFunc returns a function that retrieves a named device's volatile config and
// removes its device prefix from the keys.
func (c *lxc) deviceVolatileGetFunc(devName string) func() map[string]string {
return func() map[string]string {
volatile := make(map[string]string)
prefix := fmt.Sprintf("volatile.%s.", devName)
for k, v := range c.localConfig {
if strings.HasPrefix(k, prefix) {
volatile[strings.TrimPrefix(k, prefix)] = v
}
}
return volatile
}
}
// deviceVolatileSetFunc returns a function that can be called to save a named device's volatile
// config using keys that do not have the device's name prefixed.
func (c *lxc) deviceVolatileSetFunc(devName string) func(save map[string]string) error {
return func(save map[string]string) error {
volatileSave := make(map[string]string)
for k, v := range save {
volatileSave[fmt.Sprintf("volatile.%s.%s", devName, k)] = v
}
return c.VolatileSet(volatileSave)
}
}
// deviceResetVolatile resets a device's volatile data when its removed or updated in such a way
// that it is removed then added immediately afterwards.
func (c *lxc) deviceResetVolatile(devName string, oldConfig, newConfig deviceConfig.Device) error {
volatileClear := make(map[string]string)
devicePrefix := fmt.Sprintf("volatile.%s.", devName)
// If the device type has changed, remove all old volatile keys.
// This will occur if the newConfig is empty (i.e the device is actually being removed) or
// if the device type is being changed but keeping the same name.
if newConfig["type"] != oldConfig["type"] || newConfig.NICType() != oldConfig.NICType() {
for k := range c.localConfig {
if !strings.HasPrefix(k, devicePrefix) {
continue
}
volatileClear[k] = ""
}
return c.VolatileSet(volatileClear)
}
// If the device type remains the same, then just remove any volatile keys that have
// the same key name present in the new config (i.e the new config is replacing the
// old volatile key).
for k := range c.localConfig {
if !strings.HasPrefix(k, devicePrefix) {
continue
}
devKey := strings.TrimPrefix(k, devicePrefix)
if _, found := newConfig[devKey]; found {
volatileClear[k] = ""
}
}
return c.VolatileSet(volatileClear)
}
// DeviceEventHandler actions the results of a RunConfig after an event has occurred on a device.
func (c *lxc) DeviceEventHandler(runConf *deviceConfig.RunConfig) error {
// Device events can only be processed when the container is running.
if !c.IsRunning() {
return nil
}
if runConf == nil {
return nil
}
// Shift device file ownership if needed before mounting devices into container.
if len(runConf.Mounts) > 0 {
err := c.deviceStaticShiftMounts(runConf.Mounts)
if err != nil {
return err
}
err = c.deviceHandleMounts(runConf.Mounts)
if err != nil {
return err
}
}
// Add cgroup rules if requested.
if len(runConf.CGroups) > 0 {
err := c.deviceAddCgroupRules(runConf.CGroups)
if err != nil {
return err
}
}
// Run any post hooks requested.
err := c.runHooks(runConf.PostHooks)
if err != nil {
return err
}
// Generate uevent inside container if requested.
if len(runConf.Uevents) > 0 {
for _, eventParts := range runConf.Uevents {
ueventArray := make([]string, 4)
ueventArray[0] = "forkuevent"
ueventArray[1] = "inject"
ueventArray[2] = fmt.Sprintf("%d", c.InitPID())
length := 0
for _, part := range eventParts {
length = length + len(part) + 1
}
ueventArray[3] = fmt.Sprintf("%d", length)
ueventArray = append(ueventArray, eventParts...)
_, err := shared.RunCommand(c.state.OS.ExecPath, ueventArray...)
if err != nil {
return err
}
}
}
return nil
}
// Config handling
func (c *lxc) expandConfig(profiles []api.Profile) error {
if profiles == nil && len(c.profiles) > 0 {
var err error
profiles, err = c.state.Cluster.ProfilesGet(c.project, c.profiles)
if err != nil {
return err
}
}
c.expandedConfig = db.ProfilesExpandConfig(c.localConfig, profiles)
return nil
}
func (c *lxc) expandDevices(profiles []api.Profile) error {
if profiles == nil && len(c.profiles) > 0 {
var err error
profiles, err = c.state.Cluster.ProfilesGet(c.project, c.profiles)
if err != nil {
return err
}
}
c.expandedDevices = db.ProfilesExpandDevices(c.localDevices, profiles)
return nil
}
// Start functions
func (c *lxc) startCommon() (string, []func() error, error) {
var ourStart bool
postStartHooks := []func() error{}
// Load the go-lxc struct
err := c.initLXC(true)
if err != nil {
return "", postStartHooks, errors.Wrap(err, "Load go-lxc struct")
}
// Check that we're not already running
if c.IsRunning() {
return "", postStartHooks, fmt.Errorf("The container is already running")
}
// Load any required kernel modules
kernelModules := c.expandedConfig["linux.kernel_modules"]
if kernelModules != "" {
for _, module := range strings.Split(kernelModules, ",") {
module = strings.TrimPrefix(module, " ")
err := util.LoadModule(module)
if err != nil {
return "", postStartHooks, fmt.Errorf("Failed to load kernel module '%s': %s", module, err)
}
}
}
/* Deal with idmap changes */
nextIdmap, err := c.NextIdmap()
if err != nil {
return "", postStartHooks, errors.Wrap(err, "Set ID map")
}
diskIdmap, err := c.DiskIdmap()
if err != nil {
return "", postStartHooks, errors.Wrap(err, "Set last ID map")
}
if !nextIdmap.Equals(diskIdmap) && !(diskIdmap == nil && c.state.OS.Shiftfs) {
if shared.IsTrue(c.expandedConfig["security.protection.shift"]) {
return "", postStartHooks, fmt.Errorf("Container is protected against filesystem shifting")
}
logger.Debugf("Container idmap changed, remapping")
c.updateProgress("Remapping container filesystem")
ourStart, err = c.mount()
if err != nil {
return "", postStartHooks, errors.Wrap(err, "Storage start")
}
storageType, err := c.getStorageType()
if err != nil {
return "", postStartHooks, errors.Wrap(err, "Storage type")
}
if diskIdmap != nil {
if storageType == "zfs" {
err = diskIdmap.UnshiftRootfs(c.RootfsPath(), storageDrivers.ShiftZFSSkipper)
} else if storageType == "btrfs" {
err = storageDrivers.UnshiftBtrfsRootfs(c.RootfsPath(), diskIdmap)
} else {
err = diskIdmap.UnshiftRootfs(c.RootfsPath(), nil)
}
if err != nil {
if ourStart {
c.unmount()
}
return "", postStartHooks, err
}
}
if nextIdmap != nil && !c.state.OS.Shiftfs {
if storageType == "zfs" {
err = nextIdmap.ShiftRootfs(c.RootfsPath(), storageDrivers.ShiftZFSSkipper)
} else if storageType == "btrfs" {
err = storageDrivers.ShiftBtrfsRootfs(c.RootfsPath(), nextIdmap)
} else {
err = nextIdmap.ShiftRootfs(c.RootfsPath(), nil)
}
if err != nil {
if ourStart {
c.unmount()
}
return "", postStartHooks, err
}
}
jsonDiskIdmap := "[]"
if nextIdmap != nil && !c.state.OS.Shiftfs {
idmapBytes, err := json.Marshal(nextIdmap.Idmap)
if err != nil {
return "", postStartHooks, err
}
jsonDiskIdmap = string(idmapBytes)
}
err = c.VolatileSet(map[string]string{"volatile.last_state.idmap": jsonDiskIdmap})
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Set volatile.last_state.idmap config key on container %q (id %d)", c.name, c.id)
}
c.updateProgress("")
}
var idmapBytes []byte
if nextIdmap == nil {
idmapBytes = []byte("[]")
} else {
idmapBytes, err = json.Marshal(nextIdmap.Idmap)
if err != nil {
return "", postStartHooks, err
}
}
if c.localConfig["volatile.idmap.current"] != string(idmapBytes) {
err = c.VolatileSet(map[string]string{"volatile.idmap.current": string(idmapBytes)})
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Set volatile.idmap.current config key on container %q (id %d)", c.name, c.id)
}
}
// Generate the Seccomp profile
if err := seccomp.CreateProfile(c.state, c); err != nil {
return "", postStartHooks, err
}
// Cleanup any existing leftover devices
c.removeUnixDevices()
c.removeDiskDevices()
// Create any missing directories.
err = os.MkdirAll(c.LogPath(), 0700)
if err != nil {
return "", postStartHooks, err
}
err = os.MkdirAll(c.DevicesPath(), 0711)
if err != nil {
return "", postStartHooks, err
}
err = os.MkdirAll(c.ShmountsPath(), 0711)
if err != nil {
return "", postStartHooks, err
}
// Create the devices
nicID := -1
// Setup devices in sorted order, this ensures that device mounts are added in path order.
for _, dev := range c.expandedDevices.Sorted() {
// Start the device.
runConf, err := c.deviceStart(dev.Name, dev.Config, false)
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to start device %q", dev.Name)
}
if runConf == nil {
continue
}
// Process rootfs setup.
if runConf.RootFS.Path != "" {
if !util.RuntimeLiblxcVersionAtLeast(2, 1, 0) {
// Set the rootfs backend type if supported (must happen before any other lxc.rootfs)
err := lxcSetConfigItem(c.c, "lxc.rootfs.backend", "dir")
if err == nil {
value := c.c.ConfigItem("lxc.rootfs.backend")
if len(value) == 0 || value[0] != "dir" {
lxcSetConfigItem(c.c, "lxc.rootfs.backend", "")
}
}
}
if util.RuntimeLiblxcVersionAtLeast(2, 1, 0) {
rootfsPath := fmt.Sprintf("dir:%s", runConf.RootFS.Path)
err = lxcSetConfigItem(c.c, "lxc.rootfs.path", rootfsPath)
} else {
err = lxcSetConfigItem(c.c, "lxc.rootfs", runConf.RootFS.Path)
}
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device rootfs '%s'", dev.Name)
}
if len(runConf.RootFS.Opts) > 0 {
err = lxcSetConfigItem(c.c, "lxc.rootfs.options", strings.Join(runConf.RootFS.Opts, ","))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device rootfs '%s'", dev.Name)
}
}
if c.state.OS.Shiftfs && !c.IsPrivileged() && diskIdmap == nil {
// Host side mark mount.
err = lxcSetConfigItem(c.c, "lxc.hook.pre-start", fmt.Sprintf("/bin/mount -t shiftfs -o mark,passthrough=3 %s %s", c.RootfsPath(), c.RootfsPath()))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
// Container side shift mount.
err = lxcSetConfigItem(c.c, "lxc.hook.pre-mount", fmt.Sprintf("/bin/mount -t shiftfs -o passthrough=3 %s %s", c.RootfsPath(), c.RootfsPath()))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
// Host side umount of mark mount.
err = lxcSetConfigItem(c.c, "lxc.hook.start-host", fmt.Sprintf("/bin/umount -l %s", c.RootfsPath()))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
}
}
// Pass any cgroups rules into LXC.
if len(runConf.CGroups) > 0 {
for _, rule := range runConf.CGroups {
err = lxcSetConfigItem(c.c, fmt.Sprintf("lxc.cgroup.%s", rule.Key), rule.Value)
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device cgroup '%s'", dev.Name)
}
}
}
// Pass any mounts into LXC.
if len(runConf.Mounts) > 0 {
for _, mount := range runConf.Mounts {
if shared.StringInSlice("propagation", mount.Opts) && !util.RuntimeLiblxcVersionAtLeast(3, 0, 0) {
return "", postStartHooks, errors.Wrapf(fmt.Errorf("liblxc 3.0 is required for mount propagation configuration"), "Failed to setup device mount '%s'", dev.Name)
}
if mount.OwnerShift == deviceConfig.MountOwnerShiftDynamic && !c.IsPrivileged() {
if !c.state.OS.Shiftfs {
return "", postStartHooks, errors.Wrapf(fmt.Errorf("shiftfs is required but isn't supported on system"), "Failed to setup device mount '%s'", dev.Name)
}
err = lxcSetConfigItem(c.c, "lxc.hook.pre-start", fmt.Sprintf("/bin/mount -t shiftfs -o mark,passthrough=3 %s %s", mount.DevPath, mount.DevPath))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
err = lxcSetConfigItem(c.c, "lxc.hook.pre-mount", fmt.Sprintf("/bin/mount -t shiftfs -o passthrough=3 %s %s", mount.DevPath, mount.DevPath))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
err = lxcSetConfigItem(c.c, "lxc.hook.start-host", fmt.Sprintf("/bin/umount -l %s", mount.DevPath))
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
}
mntVal := fmt.Sprintf("%s %s %s %s %d %d", shared.EscapePathFstab(mount.DevPath), shared.EscapePathFstab(mount.TargetPath), mount.FSType, strings.Join(mount.Opts, ","), mount.Freq, mount.PassNo)
err = lxcSetConfigItem(c.c, "lxc.mount.entry", mntVal)
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device mount '%s'", dev.Name)
}
}
}
// Pass any network setup config into LXC.
if len(runConf.NetworkInterface) > 0 {
// Increment nicID so that LXC network index is unique per device.
nicID++
networkKeyPrefix := "lxc.net"
if !util.RuntimeLiblxcVersionAtLeast(2, 1, 0) {
networkKeyPrefix = "lxc.network"
}
for _, nicItem := range runConf.NetworkInterface {
err = lxcSetConfigItem(c.c, fmt.Sprintf("%s.%d.%s", networkKeyPrefix, nicID, nicItem.Key), nicItem.Value)
if err != nil {
return "", postStartHooks, errors.Wrapf(err, "Failed to setup device network interface '%s'", dev.Name)
}
}
}
// Add any post start hooks.
if len(runConf.PostHooks) > 0 {
postStartHooks = append(postStartHooks, runConf.PostHooks...)
}
}
// Rotate the log file
logfile := c.LogFilePath()
if shared.PathExists(logfile) {
os.Remove(logfile + ".old")
err := os.Rename(logfile, logfile+".old")
if err != nil {
return "", postStartHooks, err
}
}
// Storage is guaranteed to be mountable now (must be called after devices setup).
ourStart, err = c.mount()
if err != nil {
return "", postStartHooks, err
}
// Generate the LXC config
configPath := filepath.Join(c.LogPath(), "lxc.conf")
err = c.c.SaveConfigFile(configPath)
if err != nil {
os.Remove(configPath)
return "", postStartHooks, err
}
// Set ownership to match container root
currentIdmapset, err := c.CurrentIdmap()
if err != nil {
if ourStart {
c.unmount()
}
return "", postStartHooks, err
}
uid := int64(0)
if currentIdmapset != nil {
uid, _ = currentIdmapset.ShiftFromNs(0, 0)
}
err = os.Chown(c.Path(), int(uid), 0)
if err != nil {
if ourStart {
c.unmount()
}
return "", postStartHooks, err
}
// We only need traversal by root in the container
err = os.Chmod(c.Path(), 0100)
if err != nil {
if ourStart {
c.unmount()
}
return "", postStartHooks, err
}
// Update the backup.yaml file
err = c.UpdateBackupFile()
if err != nil {
if ourStart {
c.unmount()
}
return "", postStartHooks, err
}
// If starting stateless, wipe state
if !c.IsStateful() && shared.PathExists(c.StatePath()) {
os.RemoveAll(c.StatePath())
}
// Unmount any previously mounted shiftfs
unix.Unmount(c.RootfsPath(), unix.MNT_DETACH)
return configPath, postStartHooks, nil
}
// detachInterfaceRename enters the container's network namespace and moves the named interface
// in ifName back to the network namespace of the running process as the name specified in hostName.
func (c *lxc) detachInterfaceRename(netns string, ifName string, hostName string) error {
lxdPID := os.Getpid()
// Run forknet detach
_, err := shared.RunCommand(
c.state.OS.ExecPath,
"forknet",
"detach",
netns,
fmt.Sprintf("%d", lxdPID),
ifName,
hostName,
)
// Process forknet detach response
if err != nil {
return err
}
return nil
}
// Start starts the instance.
func (c *lxc) Start(stateful bool) error {
var ctxMap log.Ctx
// Setup a new operation
op, err := operationlock.Create(c.id, "start", false, false)
if err != nil {
return errors.Wrap(err, "Create container start operation")
}
defer op.Done(nil)
if !daemon.SharedMountsSetup {
return fmt.Errorf("Daemon failed to setup shared mounts base: %v. Does security.nesting need to be turned on?", err)
}
// Run the shared start code
configPath, postStartHooks, err := c.startCommon()
if err != nil {
return errors.Wrap(err, "Common start logic")
}
// Ensure that the container storage volume is mounted.
_, err = c.mount()
if err != nil {
return errors.Wrap(err, "Storage start")
}
ctxMap = log.Ctx{
"project": c.project,
"name": c.name,
"action": op.Action(),
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"stateful": stateful}
logger.Info("Starting container", ctxMap)
// If stateful, restore now
if stateful {
if !c.stateful {
return fmt.Errorf("Container has no existing state to restore")
}
criuMigrationArgs := instance.CriuMigrationArgs{
Cmd: liblxc.MIGRATE_RESTORE,
StateDir: c.StatePath(),
Function: "snapshot",
Stop: false,
ActionScript: false,
DumpDir: "",
PreDumpDir: "",
}
err := c.Migrate(&criuMigrationArgs)
if err != nil && !c.IsRunning() {
return errors.Wrap(err, "Migrate")
}
os.RemoveAll(c.StatePath())
c.stateful = false
err = c.state.Cluster.ContainerSetStateful(c.id, false)
if err != nil {
logger.Error("Failed starting container", ctxMap)
return errors.Wrap(err, "Start container")
}
// Run any post start hooks.
err = c.runHooks(postStartHooks)
if err != nil {
// Attempt to stop container.
op.Done(err)
c.Stop(false)
return err
}
logger.Info("Started container", ctxMap)
return nil
} else if c.stateful {
/* stateless start required when we have state, let's delete it */
err := os.RemoveAll(c.StatePath())
if err != nil {
return err
}
c.stateful = false
err = c.state.Cluster.ContainerSetStateful(c.id, false)
if err != nil {
return errors.Wrap(err, "Persist stateful flag")
}
}
name := project.Instance(c.Project(), c.name)
// Start the LXC container
_, err = shared.RunCommand(
c.state.OS.ExecPath,
"forkstart",
name,
c.state.OS.LxcPath,
configPath)
if err != nil && !c.IsRunning() {
// Attempt to extract the LXC errors
lxcLog := ""
logPath := filepath.Join(c.LogPath(), "lxc.log")
if shared.PathExists(logPath) {
logContent, err := ioutil.ReadFile(logPath)
if err == nil {
for _, line := range strings.Split(string(logContent), "\n") {
fields := strings.Fields(line)
if len(fields) < 4 {
continue
}
// We only care about errors
if fields[2] != "ERROR" {
continue
}
// Prepend the line break
if len(lxcLog) == 0 {
lxcLog += "\n"
}
lxcLog += fmt.Sprintf(" %s\n", strings.Join(fields[0:], " "))
}
}
}
logger.Error("Failed starting container", ctxMap)
// Return the actual error
return err
}
// Run any post start hooks.
err = c.runHooks(postStartHooks)
if err != nil {
// Attempt to stop container.
op.Done(err)
c.Stop(false)
return err
}
logger.Info("Started container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-started",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return nil
}
// OnHook is the top-level hook handler.
func (c *lxc) OnHook(hookName string, args map[string]string) error {
switch hookName {
case instance.HookStart:
return c.onStart(args)
case instance.HookStopNS:
return c.onStopNS(args)
case instance.HookStop:
return c.onStop(args)
default:
return instance.ErrNotImplemented
}
}
// onStart implements the start hook.
func (c *lxc) onStart(_ map[string]string) error {
// Make sure we can't call go-lxc functions by mistake
c.fromHook = true
// Start the storage for this container
ourStart, err := c.mount()
if err != nil {
return err
}
// Load the container AppArmor profile
err = apparmor.LoadProfile(c.state, c)
if err != nil {
if ourStart {
c.unmount()
}
return err
}
// Template anything that needs templating
key := "volatile.apply_template"
if c.localConfig[key] != "" {
// Run any template that needs running
err = c.templateApplyNow(c.localConfig[key])
if err != nil {
apparmor.Destroy(c.state, c)
if ourStart {
c.unmount()
}
return err
}
// Remove the volatile key from the DB
err := c.state.Cluster.ContainerConfigRemove(c.id, key)
if err != nil {
apparmor.Destroy(c.state, c)
if ourStart {
c.unmount()
}
return err
}
}
err = c.templateApplyNow("start")
if err != nil {
apparmor.Destroy(c.state, c)
if ourStart {
c.unmount()
}
return err
}
// Trigger a rebalance
cgroup.TaskSchedulerTrigger("container", c.name, "started")
// Apply network priority
if c.expandedConfig["limits.network.priority"] != "" {
go func(c *lxc) {
c.fromHook = false
err := c.setNetworkPriority()
if err != nil {
logger.Error("Failed to apply network priority", log.Ctx{"container": c.name, "err": err})
}
}(c)
}
// Database updates
err = c.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
// Record current state
err = tx.ContainerSetState(c.id, "RUNNING")
if err != nil {
return errors.Wrap(err, "Error updating container state")
}
// Update time container last started time
err = tx.ContainerLastUsedUpdate(c.id, time.Now().UTC())
if err != nil {
return errors.Wrap(err, "Error updating last used")
}
return nil
})
if err != nil {
return err
}
return nil
}
// Stop functions
func (c *lxc) Stop(stateful bool) error {
var ctxMap log.Ctx
// Check that we're not already stopped
if !c.IsRunning() {
return fmt.Errorf("The container is already stopped")
}
// Setup a new operation
op, err := operationlock.Create(c.id, "stop", false, true)
if err != nil {
return err
}
ctxMap = log.Ctx{
"project": c.project,
"name": c.name,
"action": op.Action(),
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"stateful": stateful}
logger.Info("Stopping container", ctxMap)
// Handle stateful stop
if stateful {
// Cleanup any existing state
stateDir := c.StatePath()
os.RemoveAll(stateDir)
err := os.MkdirAll(stateDir, 0700)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
criuMigrationArgs := instance.CriuMigrationArgs{
Cmd: liblxc.MIGRATE_DUMP,
StateDir: stateDir,
Function: "snapshot",
Stop: true,
ActionScript: false,
DumpDir: "",
PreDumpDir: "",
}
// Checkpoint
err = c.Migrate(&criuMigrationArgs)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
err = op.Wait()
if err != nil && c.IsRunning() {
logger.Error("Failed stopping container", ctxMap)
return err
}
c.stateful = true
err = c.state.Cluster.ContainerSetStateful(c.id, true)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
op.Done(nil)
logger.Info("Stopped container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-stopped",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return nil
} else if shared.PathExists(c.StatePath()) {
os.RemoveAll(c.StatePath())
}
// Load the go-lxc struct
if c.expandedConfig["raw.lxc"] != "" {
err = c.initLXC(true)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
} else {
err = c.initLXC(false)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
}
// Load cgroup abstraction
cg, err := c.cgroup(nil)
if err != nil {
op.Done(err)
return err
}
// Fork-bomb mitigation, prevent forking from this point on
if c.state.OS.CGInfo.Supports(cgroup.Pids, cg) {
// Attempt to disable forking new processes
cg.SetMaxProcesses(0)
} else if c.state.OS.CGInfo.Supports(cgroup.Freezer, cg) {
// Attempt to freeze the container
freezer := make(chan bool, 1)
go func() {
c.Freeze()
freezer <- true
}()
select {
case <-freezer:
case <-time.After(time.Second * 5):
c.Unfreeze()
}
}
if err := c.c.Stop(); err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
err = op.Wait()
if err != nil && c.IsRunning() {
logger.Error("Failed stopping container", ctxMap)
return err
}
logger.Info("Stopped container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-stopped",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return nil
}
// Shutdown stops the instance.
func (c *lxc) Shutdown(timeout time.Duration) error {
var ctxMap log.Ctx
// Check that we're not already stopped
if !c.IsRunning() {
return fmt.Errorf("The container is already stopped")
}
// Setup a new operation
op, err := operationlock.Create(c.id, "stop", true, true)
if err != nil {
return err
}
ctxMap = log.Ctx{
"project": c.project,
"name": c.name,
"action": "shutdown",
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"timeout": timeout}
logger.Info("Shutting down container", ctxMap)
// Load the go-lxc struct
if c.expandedConfig["raw.lxc"] != "" {
err = c.initLXC(true)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
} else {
err = c.initLXC(false)
if err != nil {
op.Done(err)
logger.Error("Failed stopping container", ctxMap)
return err
}
}
if err := c.c.Shutdown(timeout); err != nil {
op.Done(err)
logger.Error("Failed shutting down container", ctxMap)
return err
}
err = op.Wait()
if err != nil && c.IsRunning() {
logger.Error("Failed shutting down container", ctxMap)
return err
}
logger.Info("Shut down container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-shutdown",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return nil
}
// onStopNS is triggered by LXC's stop hook once a container is shutdown but before the container's
// namespaces have been closed. The netns path of the stopped container is provided.
func (c *lxc) onStopNS(args map[string]string) error {
target := args["target"]
netns := args["netns"]
// Validate target
if !shared.StringInSlice(target, []string{"stop", "reboot"}) {
logger.Error("Container sent invalid target to OnStopNS", log.Ctx{"container": c.Name(), "target": target})
return fmt.Errorf("Invalid stop target: %s", target)
}
// Clean up devices.
c.cleanupDevices(netns)
return nil
}
// onStop is triggered by LXC's post-stop hook once a container is shutdown and after the
// container's namespaces have been closed.
func (c *lxc) onStop(args map[string]string) error {
target := args["target"]
// Validate target
if !shared.StringInSlice(target, []string{"stop", "reboot"}) {
logger.Error("Container sent invalid target to OnStop", log.Ctx{"container": c.Name(), "target": target})
return fmt.Errorf("Invalid stop target: %s", target)
}
// Pick up the existing stop operation lock created in Stop() function.
op := operationlock.Get(c.id)
if op != nil && op.Action() != "stop" {
return fmt.Errorf("Container is already running a %s operation", op.Action())
}
// Make sure we can't call go-lxc functions by mistake
c.fromHook = true
// Remove directory ownership (to avoid issue if uidmap is re-used)
err := os.Chown(c.Path(), 0, 0)
if err != nil {
if op != nil {
op.Done(err)
}
return err
}
err = os.Chmod(c.Path(), 0100)
if err != nil {
if op != nil {
op.Done(err)
}
return err
}
// Stop the storage for this container
_, err = c.unmount()
if err != nil {
if op != nil {
op.Done(err)
}
return err
}
// Log user actions
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"action": target,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"stateful": false}
if op == nil {
logger.Info(fmt.Sprintf("Container initiated %s", target), ctxMap)
}
// Record power state
err = c.state.Cluster.ContainerSetState(c.id, "STOPPED")
if err != nil {
logger.Error("Failed to set container state", log.Ctx{"container": c.Name(), "err": err})
}
go func(c *lxc, target string, op *operationlock.InstanceOperation) {
c.fromHook = false
err = nil
// Unlock on return
if op != nil {
defer op.Done(err)
}
// Wait for other post-stop actions to be done
c.IsRunning()
// Unload the apparmor profile
err = apparmor.Destroy(c.state, c)
if err != nil {
logger.Error("Failed to destroy apparmor namespace", log.Ctx{"container": c.Name(), "err": err})
}
// Clean all the unix devices
err = c.removeUnixDevices()
if err != nil {
logger.Error("Unable to remove unix devices", log.Ctx{"container": c.Name(), "err": err})
}
// Clean all the disk devices
err = c.removeDiskDevices()
if err != nil {
logger.Error("Unable to remove disk devices", log.Ctx{"container": c.Name(), "err": err})
}
// Log and emit lifecycle if not user triggered
if op == nil {
logger.Info("Shut down container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-shutdown",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
}
// Reboot the container
if target == "reboot" {
// Start the container again
err = c.Start(false)
return
}
// Trigger a rebalance
cgroup.TaskSchedulerTrigger("container", c.name, "stopped")
// Destroy ephemeral containers
if c.ephemeral {
err = c.Delete()
}
}(c, target, op)
return nil
}
// cleanupDevices performs any needed device cleanup steps when container is stopped.
func (c *lxc) cleanupDevices(netns string) {
for _, dev := range c.expandedDevices.Sorted() {
// Use the device interface if device supports it.
err := c.deviceStop(dev.Name, dev.Config, netns)
if err == device.ErrUnsupportedDevType {
continue
} else if err != nil {
logger.Errorf("Failed to stop device '%s': %v", dev.Name, err)
}
}
}
// Freeze functions.
func (c *lxc) Freeze() error {
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate}
// Check that we're running
if !c.IsRunning() {
return fmt.Errorf("The container isn't running")
}
cg, err := c.cgroup(nil)
if err != nil {
return err
}
// Check if the CGroup is available
if !c.state.OS.CGInfo.Supports(cgroup.Freezer, cg) {
logger.Info("Unable to freeze container (lack of kernel support)", ctxMap)
return nil
}
// Check that we're not already frozen
if c.IsFrozen() {
return fmt.Errorf("The container is already frozen")
}
logger.Info("Freezing container", ctxMap)
// Load the go-lxc struct
err = c.initLXC(false)
if err != nil {
ctxMap["err"] = err
logger.Error("Failed freezing container", ctxMap)
return err
}
err = c.c.Freeze()
if err != nil {
ctxMap["err"] = err
logger.Error("Failed freezing container", ctxMap)
return err
}
logger.Info("Froze container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-paused",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return err
}
// Unfreeze unfreezes the instance.
func (c *lxc) Unfreeze() error {
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate}
// Check that we're running
if !c.IsRunning() {
return fmt.Errorf("The container isn't running")
}
cg, err := c.cgroup(nil)
if err != nil {
return err
}
// Check if the CGroup is available
if !c.state.OS.CGInfo.Supports(cgroup.Freezer, cg) {
logger.Info("Unable to unfreeze container (lack of kernel support)", ctxMap)
return nil
}
// Check that we're frozen
if !c.IsFrozen() {
return fmt.Errorf("The container is already running")
}
logger.Info("Unfreezing container", ctxMap)
// Load the go-lxc struct
err = c.initLXC(false)
if err != nil {
logger.Error("Failed unfreezing container", ctxMap)
return err
}
err = c.c.Unfreeze()
if err != nil {
logger.Error("Failed unfreezing container", ctxMap)
}
logger.Info("Unfroze container", ctxMap)
c.state.Events.SendLifecycle(c.project, "container-resumed",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
return err
}
// Get lxc container state, with 1 second timeout
// If we don't get a reply, assume the lxc monitor is hung
func (c *lxc) getLxcState() (liblxc.State, error) {
if c.IsSnapshot() {
return liblxc.StateMap["STOPPED"], nil
}
// Load the go-lxc struct
err := c.initLXC(false)
if err != nil {
return liblxc.StateMap["STOPPED"], err
}
monitor := make(chan liblxc.State, 1)
go func(c *liblxc.Container) {
monitor <- c.State()
}(c.c)
select {
case state := <-monitor:
return state, nil
case <-time.After(5 * time.Second):
return liblxc.StateMap["FROZEN"], fmt.Errorf("Monitor is hung")
}
}
// Render renders the state of the instance.
func (c *lxc) Render(options ...func(response interface{}) error) (interface{}, interface{}, error) {
// Ignore err as the arch string on error is correct (unknown)
architectureName, _ := osarch.ArchitectureName(c.architecture)
if c.IsSnapshot() {
// Prepare the ETag
etag := []interface{}{c.expiryDate}
snapState := api.InstanceSnapshot{
CreatedAt: c.creationDate,
ExpandedConfig: c.expandedConfig,
ExpandedDevices: c.expandedDevices.CloneNative(),
LastUsedAt: c.lastUsedDate,
Name: strings.SplitN(c.name, "/", 2)[1],
Stateful: c.stateful,
Size: -1, // Default to uninitialised/error state (0 means no CoW usage).
}
snapState.Architecture = architectureName
snapState.Config = c.localConfig
snapState.Devices = c.localDevices.CloneNative()
snapState.Ephemeral = c.ephemeral
snapState.Profiles = c.profiles
snapState.ExpiresAt = c.expiryDate
for _, option := range options {
err := option(&snapState)
if err != nil {
return nil, nil, err
}
}
return &snapState, etag, nil
}
// Prepare the ETag
etag := []interface{}{c.architecture, c.localConfig, c.localDevices, c.ephemeral, c.profiles}
// FIXME: Render shouldn't directly access the go-lxc struct
cState, err := c.getLxcState()
if err != nil {
return nil, nil, errors.Wrap(err, "Get container stated")
}
statusCode := lxcStatusCode(cState)
instState := api.Instance{
ExpandedConfig: c.expandedConfig,
ExpandedDevices: c.expandedDevices.CloneNative(),
Name: c.name,
Status: statusCode.String(),
StatusCode: statusCode,
Location: c.node,
Type: c.Type().String(),
}
instState.Description = c.description
instState.Architecture = architectureName
instState.Config = c.localConfig
instState.CreatedAt = c.creationDate
instState.Devices = c.localDevices.CloneNative()
instState.Ephemeral = c.ephemeral
instState.LastUsedAt = c.lastUsedDate
instState.Profiles = c.profiles
instState.Stateful = c.stateful
for _, option := range options {
err := option(&instState)
if err != nil {
return nil, nil, err
}
}
return &instState, etag, nil
}
// RenderFull renders the full state of the instance.
func (c *lxc) RenderFull() (*api.InstanceFull, interface{}, error) {
if c.IsSnapshot() {
return nil, nil, fmt.Errorf("RenderFull only works with containers")
}
// Get the Container struct
base, etag, err := c.Render()
if err != nil {
return nil, nil, err
}
// Convert to ContainerFull
ct := api.InstanceFull{Instance: *base.(*api.Instance)}
// Add the ContainerState
ct.State, err = c.RenderState()
if err != nil {
return nil, nil, err
}
// Add the ContainerSnapshots
snaps, err := c.Snapshots()
if err != nil {
return nil, nil, err
}
for _, snap := range snaps {
render, _, err := snap.Render()
if err != nil {
return nil, nil, err
}
if ct.Snapshots == nil {
ct.Snapshots = []api.InstanceSnapshot{}
}
ct.Snapshots = append(ct.Snapshots, *render.(*api.InstanceSnapshot))
}
// Add the ContainerBackups
backups, err := c.Backups()
if err != nil {
return nil, nil, err
}
for _, backup := range backups {
render := backup.Render()
if ct.Backups == nil {
ct.Backups = []api.InstanceBackup{}
}
ct.Backups = append(ct.Backups, *render)
}
return &ct, etag, nil
}
// RenderState renders just the running state of the instance.
func (c *lxc) RenderState() (*api.InstanceState, error) {
cState, err := c.getLxcState()
if err != nil {
return nil, err
}
statusCode := lxcStatusCode(cState)
status := api.InstanceState{
Status: statusCode.String(),
StatusCode: statusCode,
}
if c.IsRunning() {
pid := c.InitPID()
status.CPU = c.cpuState()
status.Memory = c.memoryState()
status.Network = c.networkState()
status.Pid = int64(pid)
status.Processes = c.processesState()
}
status.Disk = c.diskState()
return &status, nil
}
// Snapshots returns the snapshots of the instance.
func (c *lxc) Snapshots() ([]instance.Instance, error) {
var snaps []db.Instance
if c.IsSnapshot() {
return []instance.Instance{}, nil
}
// Get all the snapshots
err := c.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
var err error
snaps, err = tx.ContainerGetSnapshotsFull(c.Project(), c.name)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
// Build the snapshot list
containers, err := instance.LoadAllInternal(c.state, snaps)
if err != nil {
return nil, err
}
instances := make([]instance.Instance, len(containers))
for k, v := range containers {
instances[k] = instance.Instance(v)
}
return instances, nil
}
// Backups returns the backups of the instance.
func (c *lxc) Backups() ([]backup.Backup, error) {
// Get all the backups
backupNames, err := c.state.Cluster.ContainerGetBackups(c.project, c.name)
if err != nil {
return nil, err
}
// Build the backup list
backups := []backup.Backup{}
for _, backupName := range backupNames {
backup, err := instance.BackupLoadByName(c.state, c.project, backupName)
if err != nil {
return nil, err
}
backups = append(backups, *backup)
}
return backups, nil
}
// Restore restores a snapshot.
func (c *lxc) Restore(sourceContainer instance.Instance, stateful bool) error {
var ctxMap log.Ctx
// Initialize storage interface for the container and mount the rootfs for criu state check.
pool, err := storagePools.GetPoolByInstance(c.state, c)
if err != nil {
return err
}
// Ensure that storage is mounted for state path checks and for backup.yaml updates.
ourStart, err := pool.MountInstance(c, nil)
if err != nil {
return err
}
if ourStart {
defer pool.UnmountInstance(c, nil)
}
// Check for CRIU if necessary, before doing a bunch of filesystem manipulations.
if shared.PathExists(c.StatePath()) {
_, err := exec.LookPath("criu")
if err != nil {
return fmt.Errorf("Failed to restore container state. CRIU isn't installed")
}
}
// Stop the container.
wasRunning := false
if c.IsRunning() {
wasRunning = true
ephemeral := c.IsEphemeral()
if ephemeral {
// Unset ephemeral flag.
args := db.InstanceArgs{
Architecture: c.Architecture(),
Config: c.LocalConfig(),
Description: c.Description(),
Devices: c.LocalDevices(),
Ephemeral: false,
Profiles: c.Profiles(),
Project: c.Project(),
Type: c.Type(),
Snapshot: c.IsSnapshot(),
}
err := c.Update(args, false)
if err != nil {
return err
}
// On function return, set the flag back on.
defer func() {
args.Ephemeral = ephemeral
c.Update(args, false)
}()
}
// This will unmount the container storage.
err := c.Stop(false)
if err != nil {
return err
}
// Ensure that storage is mounted for state path checks and for backup.yaml updates.
ourStart, err := pool.MountInstance(c, nil)
if err != nil {
return err
}
if ourStart {
defer pool.UnmountInstance(c, nil)
}
}
ctxMap = log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"source": sourceContainer.Name()}
logger.Info("Restoring container", ctxMap)
// Restore the rootfs.
err = pool.RestoreInstanceSnapshot(c, sourceContainer, nil)
if err != nil {
return err
}
// Restore the configuration.
args := db.InstanceArgs{
Architecture: sourceContainer.Architecture(),
Config: sourceContainer.LocalConfig(),
Description: sourceContainer.Description(),
Devices: sourceContainer.LocalDevices(),
Ephemeral: sourceContainer.IsEphemeral(),
Profiles: sourceContainer.Profiles(),
Project: sourceContainer.Project(),
Type: sourceContainer.Type(),
Snapshot: sourceContainer.IsSnapshot(),
}
// Don't pass as user-requested as there's no way to fix a bad config.
err = c.Update(args, false)
if err != nil {
logger.Error("Failed restoring container configuration", ctxMap)
return err
}
// The old backup file may be out of date (e.g. it doesn't have all the current snapshots of
// the container listed); let's write a new one to be safe.
err = c.UpdateBackupFile()
if err != nil {
return err
}
// If the container wasn't running but was stateful, should we restore it as running?
if stateful == true {
if !shared.PathExists(c.StatePath()) {
return fmt.Errorf("Stateful snapshot restore requested by snapshot is stateless")
}
logger.Debug("Performing stateful restore", ctxMap)
c.stateful = true
criuMigrationArgs := instance.CriuMigrationArgs{
Cmd: liblxc.MIGRATE_RESTORE,
StateDir: c.StatePath(),
Function: "snapshot",
Stop: false,
ActionScript: false,
DumpDir: "",
PreDumpDir: "",
}
// Checkpoint.
err := c.Migrate(&criuMigrationArgs)
if err != nil {
return err
}
// Remove the state from the parent container; we only keep this in snapshots.
err2 := os.RemoveAll(c.StatePath())
if err2 != nil {
logger.Error("Failed to delete snapshot state", log.Ctx{"path": c.StatePath(), "err": err2})
}
if err != nil {
logger.Info("Failed restoring container", ctxMap)
return err
}
logger.Debug("Performed stateful restore", ctxMap)
logger.Info("Restored container", ctxMap)
return nil
}
c.state.Events.SendLifecycle(c.project, "container-snapshot-restored",
fmt.Sprintf("/1.0/containers/%s", c.name), map[string]interface{}{
"snapshot_name": c.name,
})
// Restart the container.
if wasRunning {
logger.Info("Restored container", ctxMap)
return c.Start(false)
}
logger.Info("Restored container", ctxMap)
return nil
}
func (c *lxc) cleanup() {
// Unmount any leftovers
c.removeUnixDevices()
c.removeDiskDevices()
// Remove the security profiles
apparmor.DeleteProfile(c.state, c)
seccomp.DeleteProfile(c)
// Remove the devices path
os.Remove(c.DevicesPath())
// Remove the shmounts path
os.RemoveAll(c.ShmountsPath())
}
// Delete deletes the instance.
func (c *lxc) Delete() error {
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate}
logger.Info("Deleting container", ctxMap)
if shared.IsTrue(c.expandedConfig["security.protection.delete"]) && !c.IsSnapshot() {
err := fmt.Errorf("Container is protected")
logger.Warn("Failed to delete container", log.Ctx{"name": c.Name(), "err": err})
return err
}
pool, err := storagePools.GetPoolByInstance(c.state, c)
if err != nil && err != db.ErrNoSuchObject {
return err
} else if pool != nil {
// Check if we're dealing with "lxd import".
// "lxd import" is used for disaster recovery, where you already have a container
// and snapshots on disk but no DB entry. As such if something has gone wrong during
// the creation of the instance and we are now being asked to delete the instance,
// we should not remove the storage volumes themselves as this would cause data loss.
isImport := false
cName, _, _ := shared.InstanceGetParentAndSnapshotName(c.Name())
importingFilePath := storagePools.InstanceImportingFilePath(c.Type(), pool.Name(), c.Project(), cName)
if shared.PathExists(importingFilePath) {
isImport = true
}
if c.IsSnapshot() {
if !isImport {
// Remove snapshot volume and database record.
err = pool.DeleteInstanceSnapshot(c, nil)
if err != nil {
return err
}
}
} else {
// Remove all snapshots by initialising each snapshot as an Instance and
// calling its Delete function.
err := instance.DeleteSnapshots(c.state, c.Project(), c.Name())
if err != nil {
logger.Error("Failed to delete instance snapshots", log.Ctx{"project": c.Project(), "instance": c.Name(), "err": err})
return err
}
if !isImport {
// Remove the storage volume, snapshot volumes and database records.
err = pool.DeleteInstance(c, nil)
if err != nil {
return err
}
}
}
}
// Perform other cleanup steps if not snapshot.
if !c.IsSnapshot() {
// Remove all backups.
backups, err := c.Backups()
if err != nil {
return err
}
for _, backup := range backups {
err = backup.Delete()
if err != nil {
return err
}
}
// Delete the MAAS entry.
err = c.maasDelete()
if err != nil {
logger.Error("Failed deleting container MAAS record", log.Ctx{"name": c.Name(), "err": err})
return err
}
// Remove devices from container.
for k, m := range c.expandedDevices {
err = c.deviceRemove(k, m)
if err != nil && err != device.ErrUnsupportedDevType {
return errors.Wrapf(err, "Failed to remove device '%s'", k)
}
}
// Clean things up.
c.cleanup()
}
// Remove the database record of the instance or snapshot instance.
if err := c.state.Cluster.InstanceRemove(c.project, c.Name()); err != nil {
logger.Error("Failed deleting container entry", log.Ctx{"name": c.Name(), "err": err})
return err
}
logger.Info("Deleted container", ctxMap)
if c.IsSnapshot() {
c.state.Events.SendLifecycle(c.project, "container-snapshot-deleted",
fmt.Sprintf("/1.0/containers/%s", c.name), map[string]interface{}{
"snapshot_name": c.name,
})
} else {
c.state.Events.SendLifecycle(c.project, "container-deleted",
fmt.Sprintf("/1.0/containers/%s", c.name), nil)
}
return nil
}
// Rename renames the instance.
func (c *lxc) Rename(newName string) error {
oldName := c.Name()
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"newname": newName}
logger.Info("Renaming container", ctxMap)
// Sanity checks.
err := instance.ValidName(newName, c.IsSnapshot())
if err != nil {
return err
}
if c.IsRunning() {
return fmt.Errorf("Renaming of running container not allowed")
}
// Clean things up.
c.cleanup()
pool, err := storagePools.GetPoolByInstance(c.state, c)
if err != nil {
return errors.Wrap(err, "Load instance storage pool")
}
if c.IsSnapshot() {
_, newSnapName, _ := shared.InstanceGetParentAndSnapshotName(newName)
err = pool.RenameInstanceSnapshot(c, newSnapName, nil)
if err != nil {
return errors.Wrap(err, "Rename instance snapshot")
}
} else {
err = pool.RenameInstance(c, newName, nil)
if err != nil {
return errors.Wrap(err, "Rename instance")
}
}
if !c.IsSnapshot() {
// Rename all the instance snapshot database entries.
results, err := c.state.Cluster.ContainerGetSnapshots(c.project, oldName)
if err != nil {
logger.Error("Failed to get container snapshots", ctxMap)
return err
}
for _, sname := range results {
// Rename the snapshot.
oldSnapName := strings.SplitN(sname, shared.SnapshotDelimiter, 2)[1]
baseSnapName := filepath.Base(sname)
err := c.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
return tx.InstanceSnapshotRename(c.project, oldName, oldSnapName, baseSnapName)
})
if err != nil {
logger.Error("Failed renaming snapshot", ctxMap)
return err
}
}
}
// Rename the instance database entry.
err = c.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
if c.IsSnapshot() {
oldParts := strings.SplitN(oldName, shared.SnapshotDelimiter, 2)
newParts := strings.SplitN(newName, shared.SnapshotDelimiter, 2)
return tx.InstanceSnapshotRename(c.project, oldParts[0], oldParts[1], newParts[1])
}
return tx.InstanceRename(c.project, oldName, newName)
})
if err != nil {
logger.Error("Failed renaming container", ctxMap)
return err
}
// Rename the logging path.
os.RemoveAll(shared.LogPath(newName))
if shared.PathExists(c.LogPath()) {
err := os.Rename(c.LogPath(), shared.LogPath(newName))
if err != nil {
logger.Error("Failed renaming container", ctxMap)
return err
}
}
// Rename the MAAS entry.
if !c.IsSnapshot() {
err = c.maasRename(newName)
if err != nil {
return err
}
}
revert := revert.New()
defer revert.Fail()
// Set the new name in the struct.
c.name = newName
revert.Add(func() { c.name = oldName })
// Rename the backups.
backups, err := c.Backups()
if err != nil {
return err
}
for _, backup := range backups {
b := backup
oldName := b.Name()
backupName := strings.Split(oldName, "/")[1]
newName := fmt.Sprintf("%s/%s", newName, backupName)
err = b.Rename(newName)
if err != nil {
return err
}
revert.Add(func() { b.Rename(oldName) })
}
// Invalidate the go-lxc cache.
if c.c != nil {
c.c.Release()
c.c = nil
}
c.cConfig = false
// Update lease files.
network.UpdateDNSMasqStatic(c.state, "")
logger.Info("Renamed container", ctxMap)
if c.IsSnapshot() {
c.state.Events.SendLifecycle(c.project, "container-snapshot-renamed",
fmt.Sprintf("/1.0/containers/%s", oldName), map[string]interface{}{
"new_name": newName,
"snapshot_name": oldName,
})
} else {
c.state.Events.SendLifecycle(c.project, "container-renamed",
fmt.Sprintf("/1.0/containers/%s", oldName), map[string]interface{}{
"new_name": newName,
})
}
revert.Success()
return nil
}
// CGroupSet sets a cgroup value for the instance.
func (c *lxc) CGroupSet(key string, value string) error {
// Load the go-lxc struct
err := c.initLXC(false)
if err != nil {
return err
}
// Make sure the container is running
if !c.IsRunning() {
return fmt.Errorf("Can't set cgroups on a stopped container")
}
err = c.c.SetCgroupItem(key, value)
if err != nil {
return fmt.Errorf("Failed to set cgroup %s=\"%s\": %s", key, value, err)
}
return nil
}
// VolatileSet sets volatile config.
func (c *lxc) VolatileSet(changes map[string]string) error {
// Sanity check
for key := range changes {
if !strings.HasPrefix(key, "volatile.") {
return fmt.Errorf("Only volatile keys can be modified with VolatileSet")
}
}
// Update the database
var err error
if c.IsSnapshot() {
err = c.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
return tx.InstanceSnapshotConfigUpdate(c.id, changes)
})
} else {
err = c.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
return tx.ContainerConfigUpdate(c.id, changes)
})
}
if err != nil {
return errors.Wrap(err, "Failed to volatile config")
}
// Apply the change locally
for key, value := range changes {
if value == "" {
delete(c.expandedConfig, key)
delete(c.localConfig, key)
continue
}
c.expandedConfig[key] = value
c.localConfig[key] = value
}
return nil
}
// Update applies updated config.
func (c *lxc) Update(args db.InstanceArgs, userRequested bool) error {
// Set sane defaults for unset keys
if args.Project == "" {
args.Project = project.Default
}
if args.Architecture == 0 {
args.Architecture = c.architecture
}
if args.Config == nil {
args.Config = map[string]string{}
}
if args.Devices == nil {
args.Devices = deviceConfig.Devices{}
}
if args.Profiles == nil {
args.Profiles = []string{}
}
if userRequested {
// Validate the new config
err := instance.ValidConfig(c.state.OS, args.Config, false, false)
if err != nil {
return errors.Wrap(err, "Invalid config")
}
// Validate the new devices without using expanded devices validation (expensive checks disabled).
err = instance.ValidDevices(c.state, c.state.Cluster, c.Type(), args.Devices, false)
if err != nil {
return errors.Wrap(err, "Invalid devices")
}
}
// Validate the new profiles
profiles, err := c.state.Cluster.Profiles(args.Project)
if err != nil {
return errors.Wrap(err, "Failed to get profiles")
}
checkedProfiles := []string{}
for _, profile := range args.Profiles {
if !shared.StringInSlice(profile, profiles) {
return fmt.Errorf("Requested profile '%s' doesn't exist", profile)
}
if shared.StringInSlice(profile, checkedProfiles) {
return fmt.Errorf("Duplicate profile found in request")
}
checkedProfiles = append(checkedProfiles, profile)
}
// Validate the new architecture
if args.Architecture != 0 {
_, err = osarch.ArchitectureName(args.Architecture)
if err != nil {
return fmt.Errorf("Invalid architecture id: %s", err)
}
}
// Get a copy of the old configuration
oldDescription := c.Description()
oldArchitecture := 0
err = shared.DeepCopy(&c.architecture, &oldArchitecture)
if err != nil {
return err
}
oldEphemeral := false
err = shared.DeepCopy(&c.ephemeral, &oldEphemeral)
if err != nil {
return err
}
oldExpandedDevices := deviceConfig.Devices{}
err = shared.DeepCopy(&c.expandedDevices, &oldExpandedDevices)
if err != nil {
return err
}
oldExpandedConfig := map[string]string{}
err = shared.DeepCopy(&c.expandedConfig, &oldExpandedConfig)
if err != nil {
return err
}
oldLocalDevices := deviceConfig.Devices{}
err = shared.DeepCopy(&c.localDevices, &oldLocalDevices)
if err != nil {
return err
}
oldLocalConfig := map[string]string{}
err = shared.DeepCopy(&c.localConfig, &oldLocalConfig)
if err != nil {
return err
}
oldProfiles := []string{}
err = shared.DeepCopy(&c.profiles, &oldProfiles)
if err != nil {
return err
}
oldExpiryDate := c.expiryDate
// Define a function which reverts everything. Defer this function
// so that it doesn't need to be explicitly called in every failing
// return path. Track whether or not we want to undo the changes
// using a closure.
undoChanges := true
defer func() {
if undoChanges {
c.description = oldDescription
c.architecture = oldArchitecture
c.ephemeral = oldEphemeral
c.expandedConfig = oldExpandedConfig
c.expandedDevices = oldExpandedDevices
c.localConfig = oldLocalConfig
c.localDevices = oldLocalDevices
c.profiles = oldProfiles
c.expiryDate = oldExpiryDate
if c.c != nil {
c.c.Release()
c.c = nil
}
c.cConfig = false
c.initLXC(true)
cgroup.TaskSchedulerTrigger("container", c.name, "changed")
}
}()
// Apply the various changes
c.description = args.Description
c.architecture = args.Architecture
c.ephemeral = args.Ephemeral
c.localConfig = args.Config
c.localDevices = args.Devices
c.profiles = args.Profiles
c.expiryDate = args.ExpiryDate
// Expand the config and refresh the LXC config
err = c.expandConfig(nil)
if err != nil {
return errors.Wrap(err, "Expand config")
}
err = c.expandDevices(nil)
if err != nil {
return errors.Wrap(err, "Expand devices")
}
// Diff the configurations
changedConfig := []string{}
for key := range oldExpandedConfig {
if oldExpandedConfig[key] != c.expandedConfig[key] {
if !shared.StringInSlice(key, changedConfig) {
changedConfig = append(changedConfig, key)
}
}
}
for key := range c.expandedConfig {
if oldExpandedConfig[key] != c.expandedConfig[key] {
if !shared.StringInSlice(key, changedConfig) {
changedConfig = append(changedConfig, key)
}
}
}
// Diff the devices
removeDevices, addDevices, updateDevices, updateDiff := oldExpandedDevices.Update(c.expandedDevices, func(oldDevice deviceConfig.Device, newDevice deviceConfig.Device) []string {
// This function needs to return a list of fields that are excluded from differences
// between oldDevice and newDevice. The result of this is that as long as the
// devices are otherwise identical except for the fields returned here, then the
// device is considered to be being "updated" rather than "added & removed".
if oldDevice["type"] != newDevice["type"] || oldDevice.NICType() != newDevice.NICType() {
return []string{} // Device types aren't the same, so this cannot be an update.
}
d, err := device.New(c, c.state, "", newDevice, nil, nil)
if err != nil {
return []string{} // Couldn't create Device, so this cannot be an update.
}
_, updateFields := d.CanHotPlug()
return updateFields
})
if userRequested {
// Do some validation of the config diff
err = instance.ValidConfig(c.state.OS, c.expandedConfig, false, true)
if err != nil {
return errors.Wrap(err, "Invalid expanded config")
}
// Do full expanded validation of the devices diff.
err = instance.ValidDevices(c.state, c.state.Cluster, c.Type(), c.expandedDevices, true)
if err != nil {
return errors.Wrap(err, "Invalid expanded devices")
}
}
// Run through initLXC to catch anything we missed
if userRequested {
if c.c != nil {
c.c.Release()
c.c = nil
}
c.cConfig = false
err = c.initLXC(true)
if err != nil {
return errors.Wrap(err, "Initialize LXC")
}
}
cg, err := c.cgroup(nil)
if err != nil {
return err
}
// If apparmor changed, re-validate the apparmor profile
if shared.StringInSlice("raw.apparmor", changedConfig) || shared.StringInSlice("security.nesting", changedConfig) {
err = apparmor.ParseProfile(c.state, c)
if err != nil {
return errors.Wrap(err, "Parse AppArmor profile")
}
}
if shared.StringInSlice("security.idmap.isolated", changedConfig) || shared.StringInSlice("security.idmap.base", changedConfig) || shared.StringInSlice("security.idmap.size", changedConfig) || shared.StringInSlice("raw.idmap", changedConfig) || shared.StringInSlice("security.privileged", changedConfig) {
var idmap *idmap.IdmapSet
base := int64(0)
if !c.IsPrivileged() {
// update the idmap
idmap, base, err = findIdmap(
c.state,
c.Name(),
c.expandedConfig["security.idmap.isolated"],
c.expandedConfig["security.idmap.base"],
c.expandedConfig["security.idmap.size"],
c.expandedConfig["raw.idmap"],
)
if err != nil {
return errors.Wrap(err, "Failed to get ID map")
}
}
var jsonIdmap string
if idmap != nil {
idmapBytes, err := json.Marshal(idmap.Idmap)
if err != nil {
return err
}
jsonIdmap = string(idmapBytes)
} else {
jsonIdmap = "[]"
}
c.localConfig["volatile.idmap.next"] = jsonIdmap
c.localConfig["volatile.idmap.base"] = fmt.Sprintf("%v", base)
// Invalid idmap cache
c.idmapset = nil
}
// Use the device interface to apply update changes.
err = c.updateDevices(removeDevices, addDevices, updateDevices, oldExpandedDevices)
if err != nil {
return err
}
// Update MAAS (must run after the MAC addresses have been generated).
updateMAAS := false
for _, key := range []string{"maas.subnet.ipv4", "maas.subnet.ipv6", "ipv4.address", "ipv6.address"} {
if shared.StringInSlice(key, updateDiff) {
updateMAAS = true
break
}
}
if !c.IsSnapshot() && updateMAAS {
err = c.maasUpdate(oldExpandedDevices.CloneNative())
if err != nil {
return err
}
}
// Apply the live changes
isRunning := c.IsRunning()
if isRunning {
// Live update the container config
for _, key := range changedConfig {
value := c.expandedConfig[key]
if key == "raw.apparmor" || key == "security.nesting" {
// Update the AppArmor profile
err = apparmor.LoadProfile(c.state, c)
if err != nil {
return err
}
} else if key == "security.devlxd" {
if value == "" || shared.IsTrue(value) {
err = c.insertMount(shared.VarPath("devlxd"), "/dev/lxd", "none", unix.MS_BIND, false)
if err != nil {
return err
}
} else if c.FileExists("/dev/lxd") == nil {
err = c.removeMount("/dev/lxd")
if err != nil {
return err
}
err = c.FileRemove("/dev/lxd")
if err != nil {
return err
}
}
} else if key == "linux.kernel_modules" && value != "" {
for _, module := range strings.Split(value, ",") {
module = strings.TrimPrefix(module, " ")
err := util.LoadModule(module)
if err != nil {
return fmt.Errorf("Failed to load kernel module '%s': %s", module, err)
}
}
} else if key == "limits.disk.priority" {
if !c.state.OS.CGInfo.Supports(cgroup.Blkio, cg) {
continue
}
priorityInt := 5
diskPriority := c.expandedConfig["limits.disk.priority"]
if diskPriority != "" {
priorityInt, err = strconv.Atoi(diskPriority)
if err != nil {
return err
}
}
// Minimum valid value is 10
priority := priorityInt * 100
if priority == 0 {
priority = 10
}
cg.SetBlkioWeight(fmt.Sprintf("%d", priority))
if err != nil {
return err
}
} else if key == "limits.memory" || strings.HasPrefix(key, "limits.memory.") {
// Skip if no memory CGroup
if !c.state.OS.CGInfo.Supports(cgroup.Memory, cg) {
continue
}
// Set the new memory limit
memory := c.expandedConfig["limits.memory"]
memoryEnforce := c.expandedConfig["limits.memory.enforce"]
memorySwap := c.expandedConfig["limits.memory.swap"]
// Parse memory
if memory == "" {
memory = "-1"
} else if strings.HasSuffix(memory, "%") {
percent, err := strconv.ParseInt(strings.TrimSuffix(memory, "%"), 10, 64)
if err != nil {
return err
}
memoryTotal, err := shared.DeviceTotalMemory()
if err != nil {
return err
}
memory = fmt.Sprintf("%d", int64((memoryTotal/100)*percent))
} else {
valueInt, err := units.ParseByteSizeString(memory)
if err != nil {
return err
}
memory = fmt.Sprintf("%d", valueInt)
}
// Store the old values for revert
oldMemswLimit := ""
if c.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) {
oldMemswLimit, err = cg.GetMemorySwapLimit()
if err != nil {
oldMemswLimit = ""
}
}
oldLimit, err := cg.GetMaxMemory()
if err != nil {
oldLimit = ""
}
oldSoftLimit, err := cg.GetMemorySoftLimit()
if err != nil {
oldSoftLimit = ""
}
revertMemory := func() {
if oldSoftLimit != "" {
cg.SetMemorySoftLimit(oldSoftLimit)
}
if oldLimit != "" {
cg.SetMemoryMaxUsage(oldLimit)
}
if oldMemswLimit != "" {
cg.SetMemorySwapMax(oldMemswLimit)
}
}
// Reset everything
if c.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) {
err = cg.SetMemorySwapMax("-1")
if err != nil {
revertMemory()
return err
}
}
err = cg.SetMemoryMaxUsage("-1")
if err != nil {
revertMemory()
return err
}
err = cg.SetMemorySoftLimit("-1")
if err != nil {
revertMemory()
return err
}
// Set the new values
if memoryEnforce == "soft" {
// Set new limit
err = cg.SetMemorySoftLimit(memory)
if err != nil {
revertMemory()
return err
}
} else {
if c.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) && (memorySwap == "" || shared.IsTrue(memorySwap)) {
err = cg.SetMemoryMaxUsage(memory)
if err != nil {
revertMemory()
return err
}
err = cg.SetMemorySwapMax(memory)
if err != nil {
revertMemory()
return err
}
} else {
err = cg.SetMemoryMaxUsage(memory)
if err != nil {
revertMemory()
return err
}
}
// Set soft limit to value 10% less than hard limit
valueInt, err := strconv.ParseInt(memory, 10, 64)
if err != nil {
revertMemory()
return err
}
err = cg.SetMemorySoftLimit(fmt.Sprintf("%.0f", float64(valueInt)*0.9))
if err != nil {
revertMemory()
return err
}
}
if !c.state.OS.CGInfo.Supports(cgroup.MemorySwappiness, cg) {
continue
}
// Configure the swappiness
if key == "limits.memory.swap" || key == "limits.memory.swap.priority" {
memorySwap := c.expandedConfig["limits.memory.swap"]
memorySwapPriority := c.expandedConfig["limits.memory.swap.priority"]
if memorySwap != "" && !shared.IsTrue(memorySwap) {
err = cg.SetMemorySwappiness("0")
if err != nil {
return err
}
} else {
priority := 0
if memorySwapPriority != "" {
priority, err = strconv.Atoi(memorySwapPriority)
if err != nil {
return err
}
}
err = cg.SetMemorySwappiness(fmt.Sprintf("%d", 60-10+priority))
if err != nil {
return err
}
}
}
} else if key == "limits.network.priority" {
err := c.setNetworkPriority()
if err != nil {
return err
}
} else if key == "limits.cpu" {
// Trigger a scheduler re-run
cgroup.TaskSchedulerTrigger("container", c.name, "changed")
} else if key == "limits.cpu.priority" || key == "limits.cpu.allowance" {
// Skip if no cpu CGroup
if !c.state.OS.CGInfo.Supports(cgroup.CPU, cg) {
continue
}
// Apply new CPU limits
cpuShares, cpuCfsQuota, cpuCfsPeriod, err := cgroup.ParseCPU(c.expandedConfig["limits.cpu.allowance"], c.expandedConfig["limits.cpu.priority"])
if err != nil {
return err
}
err = cg.SetCPUShare(cpuShares)
if err != nil {
return err
}
err = cg.SetCPUCfsPeriod(cpuCfsPeriod)
if err != nil {
return err
}
err = cg.SetCPUCfsQuota(cpuCfsQuota)
if err != nil {
return err
}
} else if key == "limits.processes" {
if !c.state.OS.CGInfo.Supports(cgroup.Pids, cg) {
continue
}
if value == "" {
err = cg.SetMaxProcesses(-1)
if err != nil {
return err
}
} else {
valueInt, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
err = cg.SetMaxProcesses(valueInt)
if err != nil {
return err
}
}
} else if strings.HasPrefix(key, "limits.hugepages.") {
if !c.state.OS.CGInfo.Supports(cgroup.Hugetlb, cg) {
continue
}
pageType := ""
switch key {
case "limits.hugepages.64KB":
pageType = "64KB"
case "limits.hugepages.1MB":
pageType = "1MB"
case "limits.hugepages.2MB":
pageType = "2MB"
case "limits.hugepages.1GB":
pageType = "1GB"
}
if value != "" {
valueInt, err := units.ParseByteSizeString(value)
if err != nil {
return err
}
value = fmt.Sprintf("%d", valueInt)
}
err = cg.SetMaxHugepages(pageType, value)
if err != nil {
return err
}
}
}
}
// Finally, apply the changes to the database
err = query.Retry(func() error {
tx, err := c.state.Cluster.Begin()
if err != nil {
return err
}
// Snapshots should update only their descriptions and expiry date.
if c.IsSnapshot() {
err = db.InstanceSnapshotUpdate(tx, c.id, c.description, c.expiryDate)
if err != nil {
tx.Rollback()
return errors.Wrap(err, "Snapshot update")
}
} else {
err = db.ContainerConfigClear(tx, c.id)
if err != nil {
tx.Rollback()
return err
}
err = db.ContainerConfigInsert(tx, c.id, c.localConfig)
if err != nil {
tx.Rollback()
return errors.Wrap(err, "Config insert")
}
err = db.ContainerProfilesInsert(tx, c.id, c.project, c.profiles)
if err != nil {
tx.Rollback()
return errors.Wrap(err, "Profiles insert")
}
err = db.DevicesAdd(tx, "instance", int64(c.id), c.localDevices)
if err != nil {
tx.Rollback()
return errors.Wrap(err, "Device add")
}
err = db.ContainerUpdate(tx, c.id, c.description, c.architecture, c.ephemeral, c.expiryDate)
if err != nil {
tx.Rollback()
return errors.Wrap(err, "Container update")
}
}
if err := db.TxCommit(tx); err != nil {
return err
}
return nil
})
if err != nil {
return errors.Wrap(err, "Failed to update database")
}
// Only update the backup file if it already exists (indicating the instance is mounted).
if shared.PathExists(filepath.Join(c.Path(), "backup.yaml")) {
err := c.UpdateBackupFile()
if err != nil && !os.IsNotExist(err) {
return errors.Wrap(err, "Failed to write backup file")
}
}
// Send devlxd notifications
if isRunning {
// Config changes (only for user.* keys
for _, key := range changedConfig {
if !strings.HasPrefix(key, "user.") {
continue
}
msg := map[string]string{
"key": key,
"old_value": oldExpandedConfig[key],
"value": c.expandedConfig[key],
}
err = c.devlxdEventSend("config", msg)
if err != nil {
return err
}
}
// Device changes
for k, m := range removeDevices {
msg := map[string]interface{}{
"action": "removed",
"name": k,
"config": m,
}
err = c.devlxdEventSend("device", msg)
if err != nil {
return err
}
}
for k, m := range updateDevices {
msg := map[string]interface{}{
"action": "updated",
"name": k,
"config": m,
}
err = c.devlxdEventSend("device", msg)
if err != nil {
return err
}
}
for k, m := range addDevices {
msg := map[string]interface{}{
"action": "added",
"name": k,
"config": m,
}
err = c.devlxdEventSend("device", msg)
if err != nil {
return err
}
}
}
// Success, update the closure to mark that the changes should be kept.
undoChanges = false
var endpoint string
if c.IsSnapshot() {
cName, sName, _ := shared.InstanceGetParentAndSnapshotName(c.name)
endpoint = fmt.Sprintf("/1.0/containers/%s/snapshots/%s", cName, sName)
} else {
endpoint = fmt.Sprintf("/1.0/containers/%s", c.name)
}
c.state.Events.SendLifecycle(c.project, "container-updated", endpoint, nil)
return nil
}
func (c *lxc) updateDevices(removeDevices deviceConfig.Devices, addDevices deviceConfig.Devices, updateDevices deviceConfig.Devices, oldExpandedDevices deviceConfig.Devices) error {
isRunning := c.IsRunning()
// Remove devices in reverse order to how they were added.
for _, dev := range removeDevices.Reversed() {
if isRunning {
err := c.deviceStop(dev.Name, dev.Config, "")
if err == device.ErrUnsupportedDevType {
continue // No point in trying to remove device below.
} else if err != nil {
return errors.Wrapf(err, "Failed to stop device %q", dev.Name)
}
}
err := c.deviceRemove(dev.Name, dev.Config)
if err != nil && err != device.ErrUnsupportedDevType {
return errors.Wrapf(err, "Failed to remove device %q", dev.Name)
}
// Check whether we are about to add the same device back with updated config and
// if not, or if the device type has changed, then remove all volatile keys for
// this device (as its an actual removal or a device type change).
err = c.deviceResetVolatile(dev.Name, dev.Config, addDevices[dev.Name])
if err != nil {
return errors.Wrapf(err, "Failed to reset volatile data for device %q", dev.Name)
}
}
// Add devices in sorted order, this ensures that device mounts are added in path order.
for _, dev := range addDevices.Sorted() {
err := c.deviceAdd(dev.Name, dev.Config)
if err == device.ErrUnsupportedDevType {
continue // No point in trying to start device below.
} else if err != nil {
return errors.Wrapf(err, "Failed to add device %q", dev.Name)
}
if isRunning {
_, err := c.deviceStart(dev.Name, dev.Config, isRunning)
if err != nil && err != device.ErrUnsupportedDevType {
return errors.Wrapf(err, "Failed to start device %q", dev.Name)
}
}
}
for _, dev := range updateDevices.Sorted() {
err := c.deviceUpdate(dev.Name, dev.Config, oldExpandedDevices, isRunning)
if err != nil && err != device.ErrUnsupportedDevType {
return errors.Wrapf(err, "Failed to update device %q", dev.Name)
}
}
return nil
}
// Export backs up the instance.
func (c *lxc) Export(w io.Writer, properties map[string]string) error {
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate}
if c.IsRunning() {
return fmt.Errorf("Cannot export a running instance as an image")
}
logger.Info("Exporting instance", ctxMap)
// Start the storage.
ourStart, err := c.mount()
if err != nil {
logger.Error("Failed exporting instance", ctxMap)
return err
}
if ourStart {
defer c.unmount()
}
// Get IDMap to unshift container as the tarball is created.
idmap, err := c.DiskIdmap()
if err != nil {
logger.Error("Failed exporting instance", ctxMap)
return err
}
// Create the tarball.
tarWriter := instancewriter.NewInstanceTarWriter(w, idmap)
// Keep track of the first path we saw for each path with nlink>1.
cDir := c.Path()
// Path inside the tar image is the pathname starting after cDir.
offset := len(cDir) + 1
writeToTar := func(path string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
err = tarWriter.WriteFile(path[offset:], path, fi, false)
if err != nil {
logger.Debugf("Error tarring up %s: %s", path, err)
return err
}
return nil
}
// Look for metadata.yaml.
fnam := filepath.Join(cDir, "metadata.yaml")
if !shared.PathExists(fnam) {
// Generate a new metadata.yaml.
tempDir, err := ioutil.TempDir("", "lxd_lxd_metadata_")
if err != nil {
tarWriter.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
defer os.RemoveAll(tempDir)
// Get the instance's architecture.
var arch string
if c.IsSnapshot() {
parentName, _, _ := shared.InstanceGetParentAndSnapshotName(c.name)
parent, err := instance.LoadByProjectAndName(c.state, c.project, parentName)
if err != nil {
tarWriter.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
arch, _ = osarch.ArchitectureName(parent.Architecture())
} else {
arch, _ = osarch.ArchitectureName(c.architecture)
}
if arch == "" {
arch, err = osarch.ArchitectureName(c.state.OS.Architectures[0])
if err != nil {
logger.Error("Failed exporting instance", ctxMap)
return err
}
}
// Fill in the metadata.
meta := api.ImageMetadata{}
meta.Architecture = arch
meta.CreationDate = time.Now().UTC().Unix()
meta.Properties = properties
data, err := yaml.Marshal(&meta)
if err != nil {
tarWriter.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
// Write the actual file.
fnam = filepath.Join(tempDir, "metadata.yaml")
err = ioutil.WriteFile(fnam, data, 0644)
if err != nil {
tarWriter.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
fi, err := os.Lstat(fnam)
if err != nil {
tarWriter.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
tmpOffset := len(path.Dir(fnam)) + 1
if err := tarWriter.WriteFile(fnam[tmpOffset:], fnam, fi, false); err != nil {
tarWriter.Close()
logger.Debugf("Error writing to tarfile: %s", err)
logger.Error("Failed exporting instance", ctxMap)
return err
}
} else {
if properties != nil {
// Parse the metadata.
content, err := ioutil.ReadFile(fnam)
if err != nil {
tarWriter.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
metadata := new(api.ImageMetadata)
err = yaml.Unmarshal(content, &metadata)
if err != nil {
tarWriter.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
metadata.Properties = properties
// Generate a new metadata.yaml.
tempDir, err := ioutil.TempDir("", "lxd_lxd_metadata_")
if err != nil {
tarWriter.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
defer os.RemoveAll(tempDir)
data, err := yaml.Marshal(&metadata)
if err != nil {
tarWriter.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
// Write the actual file.
fnam = filepath.Join(tempDir, "metadata.yaml")
err = ioutil.WriteFile(fnam, data, 0644)
if err != nil {
tarWriter.Close()
logger.Error("Failed exporting instance", ctxMap)
return err
}
}
// Include metadata.yaml in the tarball.
fi, err := os.Lstat(fnam)
if err != nil {
tarWriter.Close()
logger.Debugf("Error statting %s during export", fnam)
logger.Error("Failed exporting instance", ctxMap)
return err
}
if properties != nil {
tmpOffset := len(path.Dir(fnam)) + 1
err = tarWriter.WriteFile(fnam[tmpOffset:], fnam, fi, false)
} else {
err = tarWriter.WriteFile(fnam[offset:], fnam, fi, false)
}
if err != nil {
tarWriter.Close()
logger.Debugf("Error writing to tarfile: %s", err)
logger.Error("Failed exporting instance", ctxMap)
return err
}
}
// Include all the rootfs files.
fnam = c.RootfsPath()
err = filepath.Walk(fnam, writeToTar)
if err != nil {
logger.Error("Failed exporting instance", ctxMap)
return err
}
// Include all the templates.
fnam = c.TemplatesPath()
if shared.PathExists(fnam) {
err = filepath.Walk(fnam, writeToTar)
if err != nil {
logger.Error("Failed exporting instance", ctxMap)
return err
}
}
err = tarWriter.Close()
if err != nil {
logger.Error("Failed exporting instance", ctxMap)
return err
}
logger.Info("Exported instance", ctxMap)
return nil
}
func collectCRIULogFile(c instance.Instance, imagesDir string, function string, method string) error {
t := time.Now().Format(time.RFC3339)
newPath := shared.LogPath(c.Name(), fmt.Sprintf("%s_%s_%s.log", function, method, t))
return shared.FileCopy(filepath.Join(imagesDir, fmt.Sprintf("%s.log", method)), newPath)
}
func getCRIULogErrors(imagesDir string, method string) (string, error) {
f, err := os.Open(path.Join(imagesDir, fmt.Sprintf("%s.log", method)))
if err != nil {
return "", err
}
defer f.Close()
scanner := bufio.NewScanner(f)
ret := []string{}
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, "Error") || strings.Contains(line, "Warn") {
ret = append(ret, scanner.Text())
}
}
return strings.Join(ret, "\n"), nil
}
// Migrate migrates the instance to another node.
func (c *lxc) Migrate(args *instance.CriuMigrationArgs) error {
ctxMap := log.Ctx{
"project": c.project,
"name": c.name,
"created": c.creationDate,
"ephemeral": c.ephemeral,
"used": c.lastUsedDate,
"statedir": args.StateDir,
"actionscript": args.ActionScript,
"predumpdir": args.PreDumpDir,
"features": args.Features,
"stop": args.Stop}
_, err := exec.LookPath("criu")
if err != nil {
return fmt.Errorf("Unable to perform container live migration. CRIU isn't installed")
}
logger.Info("Migrating container", ctxMap)
prettyCmd := ""
switch args.Cmd {
case liblxc.MIGRATE_PRE_DUMP:
prettyCmd = "pre-dump"
case liblxc.MIGRATE_DUMP:
prettyCmd = "dump"
case liblxc.MIGRATE_RESTORE:
prettyCmd = "restore"
case liblxc.MIGRATE_FEATURE_CHECK:
prettyCmd = "feature-check"
default:
prettyCmd = "unknown"
logger.Warn("Unknown migrate call", log.Ctx{"cmd": args.Cmd})
}
pool, err := c.getStoragePool()
if err != nil {
return err
}
preservesInodes := pool.Driver().Info().PreservesInodes
/* This feature was only added in 2.0.1, let's not ask for it
* before then or migrations will fail.
*/
if !util.RuntimeLiblxcVersionAtLeast(2, 0, 1) {
preservesInodes = false
}
finalStateDir := args.StateDir
var migrateErr error
/* For restore, we need an extra fork so that we daemonize monitor
* instead of having it be a child of LXD, so let's hijack the command
* here and do the extra fork.
*/
if args.Cmd == liblxc.MIGRATE_RESTORE {
// Run the shared start
_, postStartHooks, err := c.startCommon()
if err != nil {
return err
}
/*
* For unprivileged containers we need to shift the
* perms on the images images so that they can be
* opened by the process after it is in its user
* namespace.
*/
idmapset, err := c.CurrentIdmap()
if err != nil {
return err
}
if idmapset != nil {
ourStart, err := c.mount()
if err != nil {
return err
}
storageType, err := c.getStorageType()
if err != nil {
return errors.Wrap(err, "Storage type")
}
if storageType == "zfs" {
err = idmapset.ShiftRootfs(args.StateDir, storageDrivers.ShiftZFSSkipper)
} else if storageType == "btrfs" {
err = storageDrivers.ShiftBtrfsRootfs(args.StateDir, idmapset)
} else {
err = idmapset.ShiftRootfs(args.StateDir, nil)
}
if ourStart {
_, err2 := c.unmount()
if err != nil {
return err
}
if err2 != nil {
return err2
}
}
}
configPath := filepath.Join(c.LogPath(), "lxc.conf")
if args.DumpDir != "" {
finalStateDir = fmt.Sprintf("%s/%s", args.StateDir, args.DumpDir)
}
_, migrateErr = shared.RunCommand(
c.state.OS.ExecPath,
"forkmigrate",
c.name,
c.state.OS.LxcPath,
configPath,
finalStateDir,
fmt.Sprintf("%v", preservesInodes))
if migrateErr == nil {
// Run any post start hooks.
err := c.runHooks(postStartHooks)
if err != nil {
// Attempt to stop container.
c.Stop(false)
return err
}
}
} else if args.Cmd == liblxc.MIGRATE_FEATURE_CHECK {
err := c.initLXC(true)
if err != nil {
return err
}
opts := liblxc.MigrateOptions{
FeaturesToCheck: args.Features,
}
migrateErr = c.c.Migrate(args.Cmd, opts)
if migrateErr != nil {
logger.Info("CRIU feature check failed", ctxMap)
return migrateErr
}
return nil
} else {
err := c.initLXC(true)
if err != nil {
return err
}
script := ""
if args.ActionScript {
script = filepath.Join(args.StateDir, "action.sh")
}
if args.DumpDir != "" {
finalStateDir = fmt.Sprintf("%s/%s", args.StateDir, args.DumpDir)
}
// TODO: make this configurable? Ultimately I think we don't
// want to do that; what we really want to do is have "modes"
// of criu operation where one is "make this succeed" and the
// other is "make this fast". Anyway, for now, let's choose a
// really big size so it almost always succeeds, even if it is
// slow.
ghostLimit := uint64(256 * 1024 * 1024)
opts := liblxc.MigrateOptions{
Stop: args.Stop,
Directory: finalStateDir,
Verbose: true,
PreservesInodes: preservesInodes,
ActionScript: script,
GhostLimit: ghostLimit,
}
if args.PreDumpDir != "" {
opts.PredumpDir = fmt.Sprintf("../%s", args.PreDumpDir)
}
if !c.IsRunning() {
// otherwise the migration will needlessly fail
args.Stop = false
}
migrateErr = c.c.Migrate(args.Cmd, opts)
}
collectErr := collectCRIULogFile(c, finalStateDir, args.Function, prettyCmd)
if collectErr != nil {
logger.Error("Error collecting checkpoint log file", log.Ctx{"err": collectErr})
}
if migrateErr != nil {
log, err2 := getCRIULogErrors(finalStateDir, prettyCmd)
if err2 == nil {
logger.Info("Failed migrating container", ctxMap)
migrateErr = fmt.Errorf("%s %s failed\n%s", args.Function, prettyCmd, log)
}
return migrateErr
}
logger.Info("Migrated container", ctxMap)
return nil
}
// DeferTemplateApply sets volatile key to apply template on next start. Used when instance's
// volume isn't mounted.
func (c *lxc) DeferTemplateApply(trigger string) error {
err := c.VolatileSet(map[string]string{"volatile.apply_template": trigger})
if err != nil {
return errors.Wrap(err, "Failed to set apply_template volatile key")
}
return nil
}
func (c *lxc) templateApplyNow(trigger string) error {
// If there's no metadata, just return
fname := filepath.Join(c.Path(), "metadata.yaml")
if !shared.PathExists(fname) {
return nil
}
// Parse the metadata
content, err := ioutil.ReadFile(fname)
if err != nil {
return errors.Wrap(err, "Failed to read metadata")
}
metadata := new(api.ImageMetadata)
err = yaml.Unmarshal(content, &metadata)
if err != nil {
return errors.Wrapf(err, "Could not parse %s", fname)
}
// Find rootUID and rootGID
idmapset, err := c.DiskIdmap()
if err != nil {
return errors.Wrap(err, "Failed to set ID map")
}
rootUID := int64(0)
rootGID := int64(0)
// Get the right uid and gid for the container
if idmapset != nil {
rootUID, rootGID = idmapset.ShiftIntoNs(0, 0)
}
// Figure out the container architecture
arch, err := osarch.ArchitectureName(c.architecture)
if err != nil {
arch, err = osarch.ArchitectureName(c.state.OS.Architectures[0])
if err != nil {
return errors.Wrap(err, "Failed to detect system architecture")
}
}
// Generate the container metadata
containerMeta := make(map[string]string)
containerMeta["name"] = c.name
containerMeta["architecture"] = arch
if c.ephemeral {
containerMeta["ephemeral"] = "true"
} else {
containerMeta["ephemeral"] = "false"
}
if c.IsPrivileged() {
containerMeta["privileged"] = "true"
} else {
containerMeta["privileged"] = "false"
}
// Go through the templates
for tplPath, tpl := range metadata.Templates {
var w *os.File
// Check if the template should be applied now
found := false
for _, tplTrigger := range tpl.When {
if tplTrigger == trigger {
found = true
break
}
}
if !found {
continue
}
// Open the file to template, create if needed
fullpath := filepath.Join(c.RootfsPath(), strings.TrimLeft(tplPath, "/"))
if shared.PathExists(fullpath) {
if tpl.CreateOnly {
continue
}
// Open the existing file
w, err = os.Create(fullpath)
if err != nil {
return errors.Wrap(err, "Failed to create template file")
}
} else {
// Create the directories leading to the file
shared.MkdirAllOwner(path.Dir(fullpath), 0755, int(rootUID), int(rootGID))
// Create the file itself
w, err = os.Create(fullpath)
if err != nil {
return err
}
// Fix ownership and mode
w.Chown(int(rootUID), int(rootGID))
w.Chmod(0644)
}
defer w.Close()
// Read the template
tplString, err := ioutil.ReadFile(filepath.Join(c.TemplatesPath(), tpl.Template))
if err != nil {
return errors.Wrap(err, "Failed to read template file")
}
// Restrict filesystem access to within the container's rootfs
tplSet := pongo2.NewSet(fmt.Sprintf("%s-%s", c.name, tpl.Template), template.ChrootLoader{Path: c.RootfsPath()})
tplRender, err := tplSet.FromString("{% autoescape off %}" + string(tplString) + "{% endautoescape %}")
if err != nil {
return errors.Wrap(err, "Failed to render template")
}
configGet := func(confKey, confDefault *pongo2.Value) *pongo2.Value {
val, ok := c.expandedConfig[confKey.String()]
if !ok {
return confDefault
}
return pongo2.AsValue(strings.TrimRight(val, "\r\n"))
}
// Render the template
tplRender.ExecuteWriter(pongo2.Context{"trigger": trigger,
"path": tplPath,
"container": containerMeta,
"instance": containerMeta,
"config": c.expandedConfig,
"devices": c.expandedDevices,
"properties": tpl.Properties,
"config_get": configGet}, w)
}
return nil
}
// FileExists returns whether file exists inside instance.
func (c *lxc) FileExists(path string) error {
// Setup container storage if needed
var ourStart bool
var err error
if !c.IsRunning() {
ourStart, err = c.mount()
if err != nil {
return err
}
}
// Check if the file exists in the container
_, stderr, err := shared.RunCommandSplit(
nil,
c.state.OS.ExecPath,
"forkfile",
"exists",
c.RootfsPath(),
fmt.Sprintf("%d", c.InitPID()),
path,
)
// Tear down container storage if needed
if !c.IsRunning() && ourStart {
_, err := c.unmount()
if err != nil {
return err
}
}
// Process forkcheckfile response
if stderr != "" {
if strings.HasPrefix(stderr, "error:") {
return fmt.Errorf(strings.TrimPrefix(strings.TrimSuffix(stderr, "\n"), "error: "))
}
for _, line := range strings.Split(strings.TrimRight(stderr, "\n"), "\n") {
logger.Debugf("forkcheckfile: %s", line)
}
}
if err != nil {
return err
}
return nil
}
// FilePull gets a file from the instance.
func (c *lxc) FilePull(srcpath string, dstpath string) (int64, int64, os.FileMode, string, []string, error) {
// Check for ongoing operations (that may involve shifting).
op := operationlock.Get(c.id)
if op != nil {
op.Wait()
}
var ourStart bool
var err error
// Setup container storage if needed
if !c.IsRunning() {
ourStart, err = c.mount()
if err != nil {
return -1, -1, 0, "", nil, err
}
}
// Get the file from the container
_, stderr, err := shared.RunCommandSplit(
nil,
c.state.OS.ExecPath,
"forkfile",
"pull",
c.RootfsPath(),
fmt.Sprintf("%d", c.InitPID()),
srcpath,
dstpath,
)
// Tear down container storage if needed
if !c.IsRunning() && ourStart {
_, err := c.unmount()
if err != nil {
return -1, -1, 0, "", nil, err
}
}
uid := int64(-1)
gid := int64(-1)
mode := -1
fileType := "unknown"
var dirEnts []string
var errStr string
// Process forkgetfile response
for _, line := range strings.Split(strings.TrimRight(stderr, "\n"), "\n") {
if line == "" {
continue
}
// Extract errors
if strings.HasPrefix(line, "error: ") {
errStr = strings.TrimPrefix(line, "error: ")
continue
}
if strings.HasPrefix(line, "errno: ") {
errno := strings.TrimPrefix(line, "errno: ")
if errno == "2" {
return -1, -1, 0, "", nil, os.ErrNotExist
}
return -1, -1, 0, "", nil, fmt.Errorf(errStr)
}
// Extract the uid
if strings.HasPrefix(line, "uid: ") {
uid, err = strconv.ParseInt(strings.TrimPrefix(line, "uid: "), 10, 64)
if err != nil {
return -1, -1, 0, "", nil, err
}
continue
}
// Extract the gid
if strings.HasPrefix(line, "gid: ") {
gid, err = strconv.ParseInt(strings.TrimPrefix(line, "gid: "), 10, 64)
if err != nil {
return -1, -1, 0, "", nil, err
}
continue
}
// Extract the mode
if strings.HasPrefix(line, "mode: ") {
mode, err = strconv.Atoi(strings.TrimPrefix(line, "mode: "))
if err != nil {
return -1, -1, 0, "", nil, err
}
continue
}
if strings.HasPrefix(line, "type: ") {
fileType = strings.TrimPrefix(line, "type: ")
continue
}
if strings.HasPrefix(line, "entry: ") {
ent := strings.TrimPrefix(line, "entry: ")
ent = strings.Replace(ent, "\x00", "\n", -1)
dirEnts = append(dirEnts, ent)
continue
}
logger.Debugf("forkgetfile: %s", line)
}
if err != nil {
return -1, -1, 0, "", nil, err
}
// Unmap uid and gid if needed
if !c.IsRunning() {
idmapset, err := c.DiskIdmap()
if err != nil {
return -1, -1, 0, "", nil, err
}
if idmapset != nil {
uid, gid = idmapset.ShiftFromNs(uid, gid)
}
}
return uid, gid, os.FileMode(mode), fileType, dirEnts, nil
}
// FilePush sends a file into the instance.
func (c *lxc) FilePush(fileType string, srcpath string, dstpath string, uid int64, gid int64, mode int, write string) error {
// Check for ongoing operations (that may involve shifting).
op := operationlock.Get(c.id)
if op != nil {
op.Wait()
}
var rootUID int64
var rootGID int64
var errStr string
// Map uid and gid if needed
if !c.IsRunning() {
idmapset, err := c.DiskIdmap()
if err != nil {
return err
}
if idmapset != nil {
uid, gid = idmapset.ShiftIntoNs(uid, gid)
rootUID, rootGID = idmapset.ShiftIntoNs(0, 0)
}
}
var ourStart bool
var err error
// Setup container storage if needed
if !c.IsRunning() {
ourStart, err = c.mount()
if err != nil {
return err
}
}
defaultMode := 0640
if fileType == "directory" {
defaultMode = 0750
}
// Push the file to the container
_, stderr, err := shared.RunCommandSplit(
nil,
c.state.OS.ExecPath,
"forkfile",
"push",
c.RootfsPath(),
fmt.Sprintf("%d", c.InitPID()),
srcpath,
dstpath,
fileType,
fmt.Sprintf("%d", uid),
fmt.Sprintf("%d", gid),
fmt.Sprintf("%d", mode),
fmt.Sprintf("%d", rootUID),
fmt.Sprintf("%d", rootGID),
fmt.Sprintf("%d", int(os.FileMode(defaultMode)&os.ModePerm)),
write,
)
// Tear down container storage if needed
if !c.IsRunning() && ourStart {
_, err := c.unmount()
if err != nil {
return err
}
}
// Process forkgetfile response
for _, line := range strings.Split(strings.TrimRight(stderr, "\n"), "\n") {
if line == "" {
continue
}
// Extract errors
if strings.HasPrefix(line, "error: ") {
errStr = strings.TrimPrefix(line, "error: ")
continue
}
if strings.HasPrefix(line, "errno: ") {
errno := strings.TrimPrefix(line, "errno: ")
if errno == "2" {
return os.ErrNotExist
}
return fmt.Errorf(errStr)
}
}
if err != nil {
return err
}
return nil
}
// FileRemove removes a file inside the instance.
func (c *lxc) FileRemove(path string) error {
var errStr string
var ourStart bool
var err error
// Setup container storage if needed
if !c.IsRunning() {
ourStart, err = c.mount()
if err != nil {
return err
}
}
// Remove the file from the container
_, stderr, err := shared.RunCommandSplit(
nil,
c.state.OS.ExecPath,
"forkfile",
"remove",
c.RootfsPath(),
fmt.Sprintf("%d", c.InitPID()),
path,
)
// Tear down container storage if needed
if !c.IsRunning() && ourStart {
_, err := c.unmount()
if err != nil {
return err
}
}
// Process forkremovefile response
for _, line := range strings.Split(strings.TrimRight(stderr, "\n"), "\n") {
if line == "" {
continue
}
// Extract errors
if strings.HasPrefix(line, "error: ") {
errStr = strings.TrimPrefix(line, "error: ")
continue
}
if strings.HasPrefix(line, "errno: ") {
errno := strings.TrimPrefix(line, "errno: ")
if errno == "2" {
return os.ErrNotExist
}
return fmt.Errorf(errStr)
}
}
if err != nil {
return err
}
return nil
}
// Console attaches to the instance console.
func (c *lxc) Console() (*os.File, chan error, error) {
chDisconnect := make(chan error, 1)
args := []string{
c.state.OS.ExecPath,
"forkconsole",
project.Instance(c.Project(), c.Name()),
c.state.OS.LxcPath,
filepath.Join(c.LogPath(), "lxc.conf"),
"tty=0",
"escape=-1"}
idmapset, err := c.CurrentIdmap()
if err != nil {
return nil, nil, err
}
var rootUID, rootGID int64
if idmapset != nil {
rootUID, rootGID = idmapset.ShiftIntoNs(0, 0)
}
master, slave, err := shared.OpenPty(rootUID, rootGID)
if err != nil {
return nil, nil, err
}
cmd := exec.Cmd{}
cmd.Path = c.state.OS.ExecPath
cmd.Args = args
cmd.Stdin = slave
cmd.Stdout = slave
cmd.Stderr = slave
err = cmd.Start()
if err != nil {
return nil, nil, err
}
go func() {
err = cmd.Wait()
master.Close()
slave.Close()
}()
go func() {
<-chDisconnect
cmd.Process.Kill()
}()
return master, chDisconnect, nil
}
// ConsoleLog returns console log.
func (c *lxc) ConsoleLog(opts liblxc.ConsoleLogOptions) (string, error) {
msg, err := c.c.ConsoleLog(opts)
if err != nil {
return "", err
}
return string(msg), nil
}
// Exec executes a command inside the instance.
func (c *lxc) Exec(req api.InstanceExecPost, stdin *os.File, stdout *os.File, stderr *os.File) (instance.Cmd, error) {
// Prepare the environment
envSlice := []string{}
for k, v := range req.Environment {
envSlice = append(envSlice, fmt.Sprintf("%s=%s", k, v))
}
// Setup logfile
logPath := filepath.Join(c.LogPath(), "forkexec.log")
logFile, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_SYNC, 0644)
if err != nil {
return nil, err
}
// Prepare the subcommand
cname := project.Instance(c.Project(), c.Name())
args := []string{
c.state.OS.ExecPath,
"forkexec",
cname,
c.state.OS.LxcPath,
filepath.Join(c.LogPath(), "lxc.conf"),
req.Cwd,
fmt.Sprintf("%d", req.User),
fmt.Sprintf("%d", req.Group),
}
args = append(args, "--")
args = append(args, "env")
args = append(args, envSlice...)
args = append(args, "--")
args = append(args, "cmd")
args = append(args, req.Command...)
cmd := exec.Cmd{}
cmd.Path = c.state.OS.ExecPath
cmd.Args = args
cmd.Stdin = nil
cmd.Stdout = logFile
cmd.Stderr = logFile
// Mitigation for CVE-2019-5736
useRexec := false
if c.expandedConfig["raw.idmap"] != "" {
err := instance.AllowedUnprivilegedOnlyMap(c.expandedConfig["raw.idmap"])
if err != nil {
useRexec = true
}
}
if shared.IsTrue(c.expandedConfig["security.privileged"]) {
useRexec = true
}
if useRexec {
cmd.Env = append(os.Environ(), "LXC_MEMFD_REXEC=1")
}
// Setup communication PIPE
rStatus, wStatus, err := os.Pipe()
defer rStatus.Close()
if err != nil {
return nil, err
}
cmd.ExtraFiles = []*os.File{stdin, stdout, stderr, wStatus}
err = cmd.Start()
if err != nil {
wStatus.Close()
return nil, err
}
wStatus.Close()
attachedPid := shared.ReadPid(rStatus)
if attachedPid <= 0 {
logger.Errorf("Failed to retrieve PID of executing child process")
return nil, fmt.Errorf("Failed to retrieve PID of executing child process")
}
logger.Debugf("Retrieved PID %d of executing child process", attachedPid)
instCmd := &lxcCmd{
cmd: &cmd,
attachedChildPid: int(attachedPid),
}
return instCmd, nil
}
func (c *lxc) cpuState() api.InstanceStateCPU {
cpu := api.InstanceStateCPU{}
// CPU usage in seconds
cg, err := c.cgroup(nil)
if err != nil {
return cpu
}
if !c.state.OS.CGInfo.Supports(cgroup.CPUAcct, cg) {
return cpu
}
value, err := cg.GetCPUAcctUsage()
if err != nil {
cpu.Usage = -1
return cpu
}
valueInt, err := strconv.ParseInt(value, 10, 64)
if err != nil {
cpu.Usage = -1
return cpu
}
cpu.Usage = valueInt
return cpu
}
func (c *lxc) diskState() map[string]api.InstanceStateDisk {
disk := map[string]api.InstanceStateDisk{}
for _, dev := range c.expandedDevices.Sorted() {
if dev.Config["type"] != "disk" {
continue
}
var usage int64
if dev.Config["path"] == "/" {
pool, err := storagePools.GetPoolByInstance(c.state, c)
if err != nil {
logger.Error("Error loading storage pool", log.Ctx{"project": c.Project(), "instance": c.Name(), "err": err})
continue
}
usage, err = pool.GetInstanceUsage(c)
if err != nil {
if err != storageDrivers.ErrNotSupported {
logger.Error("Error getting disk usage", log.Ctx{"project": c.Project(), "instance": c.Name(), "err": err})
}
continue
}
} else if dev.Config["pool"] != "" {
pool, err := storagePools.GetPoolByName(c.state, dev.Config["pool"])
if err != nil {
logger.Error("Error loading storage pool", log.Ctx{"project": c.Project(), "poolName": dev.Config["pool"], "err": err})
continue
}
usage, err = pool.GetCustomVolumeUsage(c.Project(), dev.Config["source"])
if err != nil {
if err != storageDrivers.ErrNotSupported {
logger.Error("Error getting volume usage", log.Ctx{"project": c.Project(), "volume": dev.Config["source"], "err": err})
}
continue
}
} else {
continue
}
disk[dev.Name] = api.InstanceStateDisk{Usage: usage}
}
return disk
}
func (c *lxc) memoryState() api.InstanceStateMemory {
memory := api.InstanceStateMemory{}
cg, err := c.cgroup(nil)
if err != nil {
return memory
}
if !c.state.OS.CGInfo.Supports(cgroup.Memory, cg) {
return memory
}
// Memory in bytes
value, err := cg.GetMemoryUsage()
valueInt, err1 := strconv.ParseInt(value, 10, 64)
if err == nil && err1 == nil {
memory.Usage = valueInt
}
// Memory peak in bytes
if c.state.OS.CGInfo.Supports(cgroup.MemoryMaxUsage, cg) {
value, err = cg.GetMemoryMaxUsage()
valueInt, err1 = strconv.ParseInt(value, 10, 64)
if err == nil && err1 == nil {
memory.UsagePeak = valueInt
}
}
if c.state.OS.CGInfo.Supports(cgroup.MemorySwapUsage, cg) {
// Swap in bytes
if memory.Usage > 0 {
value, err := cg.GetMemorySwapUsage()
valueInt, err1 := strconv.ParseInt(value, 10, 64)
if err == nil && err1 == nil {
memory.SwapUsage = valueInt - memory.Usage
}
}
// Swap peak in bytes
if memory.UsagePeak > 0 {
value, err = cg.GetMemorySwMaxUsage()
valueInt, err1 = strconv.ParseInt(value, 10, 64)
if err == nil && err1 == nil {
memory.SwapUsagePeak = valueInt - memory.UsagePeak
}
}
}
return memory
}
func (c *lxc) networkState() map[string]api.InstanceStateNetwork {
result := map[string]api.InstanceStateNetwork{}
pid := c.InitPID()
if pid < 1 {
return result
}
couldUseNetnsGetifaddrs := c.state.OS.NetnsGetifaddrs
if couldUseNetnsGetifaddrs {
nw, err := netutils.NetnsGetifaddrs(int32(pid))
if err != nil {
couldUseNetnsGetifaddrs = false
logger.Error("Failed to retrieve network information via netlink", log.Ctx{"container": c.name, "pid": pid})
} else {
result = nw
}
}
if !couldUseNetnsGetifaddrs {
// Get the network state from the container
out, err := shared.RunCommand(
c.state.OS.ExecPath,
"forknet",
"info",
fmt.Sprintf("%d", pid))
// Process forkgetnet response
if err != nil {
logger.Error("Error calling 'lxd forkgetnet", log.Ctx{"container": c.name, "err": err, "pid": pid})
return result
}
// If we can use netns_getifaddrs() but it failed and the setns() +
// netns_getifaddrs() succeeded we should just always fallback to the
// setns() + netns_getifaddrs() style retrieval.
c.state.OS.NetnsGetifaddrs = false
nw := map[string]api.InstanceStateNetwork{}
err = json.Unmarshal([]byte(out), &nw)
if err != nil {
logger.Error("Failure to read forkgetnet json", log.Ctx{"container": c.name, "err": err})
return result
}
result = nw
}
// Get host_name from volatile data if not set already.
for name, dev := range result {
if dev.HostName == "" {
dev.HostName = c.localConfig[fmt.Sprintf("volatile.%s.host_name", name)]
result[name] = dev
}
}
return result
}
func (c *lxc) processesState() int64 {
// Return 0 if not running
pid := c.InitPID()
if pid == -1 {
return 0
}
cg, err := c.cgroup(nil)
if err != nil {
return 0
}
if c.state.OS.CGInfo.Supports(cgroup.Pids, cg) {
value, err := cg.GetProcessesUsage()
if err != nil {
return -1
}
valueInt, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return -1
}
return valueInt
}
pids := []int64{int64(pid)}
// Go through the pid list, adding new pids at the end so we go through them all
for i := 0; i < len(pids); i++ {
fname := fmt.Sprintf("/proc/%d/task/%d/children", pids[i], pids[i])
fcont, err := ioutil.ReadFile(fname)
if err != nil {
// the process terminated during execution of this loop
continue
}
content := strings.Split(string(fcont), " ")
for j := 0; j < len(content); j++ {
pid, err := strconv.ParseInt(content[j], 10, 64)
if err == nil {
pids = append(pids, pid)
}
}
}
return int64(len(pids))
}
// getStoragePool returns the current storage pool handle. To avoid a DB lookup each time this
// function is called, the handle is cached internally in the lxc struct.
func (c *lxc) getStoragePool() (storagePools.Pool, error) {
if c.storagePool != nil {
return c.storagePool, nil
}
pool, err := storagePools.GetPoolByInstance(c.state, c)
if err != nil {
return nil, err
}
c.storagePool = pool
return c.storagePool, nil
}
// getStorageType returns the storage type of the instance's storage pool.
func (c *lxc) getStorageType() (string, error) {
pool, err := c.getStoragePool()
if err != nil {
return "", err
}
return pool.Driver().Info().Name, nil
}
// StorageStart mounts the instance's rootfs volume. Deprecated.
func (c *lxc) StorageStart() (bool, error) {
return c.mount()
}
// mount the instance's rootfs volume if needed.
func (c *lxc) mount() (bool, error) {
pool, err := c.getStoragePool()
if err != nil {
return false, err
}
if c.IsSnapshot() {
ourMount, err := pool.MountInstanceSnapshot(c, nil)
if err != nil {
return false, err
}
return ourMount, nil
}
ourMount, err := pool.MountInstance(c, nil)
if err != nil {
return false, err
}
return ourMount, nil
}
// StorageStop unmounts the instance's rootfs volume. Deprecated.
func (c *lxc) StorageStop() (bool, error) {
return c.unmount()
}
// unmount the instance's rootfs volume if needed.
func (c *lxc) unmount() (bool, error) {
pool, err := c.getStoragePool()
if err != nil {
return false, err
}
if c.IsSnapshot() {
unmounted, err := pool.UnmountInstanceSnapshot(c, nil)
if err != nil {
return false, err
}
return unmounted, nil
}
unmounted, err := pool.UnmountInstance(c, nil)
if err != nil {
return false, err
}
return unmounted, nil
}
// Mount handling
func (c *lxc) insertMountLXD(source, target, fstype string, flags int, mntnsPID int, shiftfs bool) error {
pid := mntnsPID
if pid <= 0 {
// Get the init PID
pid = c.InitPID()
if pid == -1 {
// Container isn't running
return fmt.Errorf("Can't insert mount into stopped container")
}
}
// Create the temporary mount target
var tmpMount string
var err error
if shared.IsDir(source) {
tmpMount, err = ioutil.TempDir(c.ShmountsPath(), "lxdmount_")
if err != nil {
return fmt.Errorf("Failed to create shmounts path: %s", err)
}
} else {
f, err := ioutil.TempFile(c.ShmountsPath(), "lxdmount_")
if err != nil {
return fmt.Errorf("Failed to create shmounts path: %s", err)
}
tmpMount = f.Name()
f.Close()
}
defer os.Remove(tmpMount)
// Mount the filesystem
err = unix.Mount(source, tmpMount, fstype, uintptr(flags), "")
if err != nil {
return fmt.Errorf("Failed to setup temporary mount: %s", err)
}
defer unix.Unmount(tmpMount, unix.MNT_DETACH)
// Setup host side shiftfs as needed
if shiftfs {
err = unix.Mount(tmpMount, tmpMount, "shiftfs", 0, "mark,passthrough=3")
if err != nil {
return fmt.Errorf("Failed to setup host side shiftfs mount: %s", err)
}
defer unix.Unmount(tmpMount, unix.MNT_DETACH)
}
// Move the mount inside the container
mntsrc := filepath.Join("/dev/.lxd-mounts", filepath.Base(tmpMount))
pidStr := fmt.Sprintf("%d", pid)
_, err = shared.RunCommand(c.state.OS.ExecPath, "forkmount", "lxd-mount", pidStr, mntsrc, target, fmt.Sprintf("%v", shiftfs))
if err != nil {
return err
}
return nil
}
func (c *lxc) insertMountLXC(source, target, fstype string, flags int) error {
cname := project.Instance(c.Project(), c.Name())
configPath := filepath.Join(c.LogPath(), "lxc.conf")
if fstype == "" {
fstype = "none"
}
if !strings.HasPrefix(target, "/") {
target = "/" + target
}
_, err := shared.RunCommand(c.state.OS.ExecPath, "forkmount", "lxc-mount", cname, c.state.OS.LxcPath, configPath, source, target, fstype, fmt.Sprintf("%d", flags))
if err != nil {
return err
}
return nil
}
func (c *lxc) insertMount(source, target, fstype string, flags int, shiftfs bool) error {
if c.state.OS.LXCFeatures["mount_injection_file"] && !shiftfs {
return c.insertMountLXC(source, target, fstype, flags)
}
return c.insertMountLXD(source, target, fstype, flags, -1, shiftfs)
}
func (c *lxc) removeMount(mount string) error {
// Get the init PID
pid := c.InitPID()
if pid == -1 {
// Container isn't running
return fmt.Errorf("Can't remove mount from stopped container")
}
if c.state.OS.LXCFeatures["mount_injection_file"] {
configPath := filepath.Join(c.LogPath(), "lxc.conf")
cname := project.Instance(c.Project(), c.Name())
if !strings.HasPrefix(mount, "/") {
mount = "/" + mount
}
_, err := shared.RunCommand(c.state.OS.ExecPath, "forkmount", "lxc-umount", cname, c.state.OS.LxcPath, configPath, mount)
if err != nil {
return err
}
} else {
// Remove the mount from the container
pidStr := fmt.Sprintf("%d", pid)
_, err := shared.RunCommand(c.state.OS.ExecPath, "forkmount", "lxd-umount", pidStr, mount)
if err != nil {
return err
}
}
return nil
}
// InsertSeccompUnixDevice inserts a seccomp device.
func (c *lxc) InsertSeccompUnixDevice(prefix string, m deviceConfig.Device, pid int) error {
if pid < 0 {
return fmt.Errorf("Invalid request PID specified")
}
rootLink := fmt.Sprintf("/proc/%d/root", pid)
rootPath, err := os.Readlink(rootLink)
if err != nil {
return err
}
uid, gid, _, _, err := seccomp.TaskIDs(pid)
if err != nil {
return err
}
idmapset, err := c.CurrentIdmap()
if err != nil {
return err
}
nsuid, nsgid := idmapset.ShiftFromNs(uid, gid)
m["uid"] = fmt.Sprintf("%d", nsuid)
m["gid"] = fmt.Sprintf("%d", nsgid)
if !path.IsAbs(m["path"]) {
cwdLink := fmt.Sprintf("/proc/%d/cwd", pid)
prefixPath, err := os.Readlink(cwdLink)
if err != nil {
return err
}
prefixPath = strings.TrimPrefix(prefixPath, rootPath)
m["path"] = filepath.Join(rootPath, prefixPath, m["path"])
} else {
m["path"] = filepath.Join(rootPath, m["path"])
}
idmapSet, err := c.CurrentIdmap()
if err != nil {
return err
}
d, err := device.UnixDeviceCreate(c.state, idmapSet, c.DevicesPath(), prefix, m, true)
if err != nil {
return fmt.Errorf("Failed to setup device: %s", err)
}
devPath := d.HostPath
tgtPath := d.RelativePath
// Bind-mount it into the container
defer os.Remove(devPath)
return c.insertMountLXD(devPath, tgtPath, "none", unix.MS_BIND, pid, false)
}
func (c *lxc) removeUnixDevices() error {
// Check that we indeed have devices to remove
if !shared.PathExists(c.DevicesPath()) {
return nil
}
// Load the directory listing
dents, err := ioutil.ReadDir(c.DevicesPath())
if err != nil {
return err
}
// Go through all the unix devices
for _, f := range dents {
// Skip non-Unix devices
if !strings.HasPrefix(f.Name(), "forkmknod.unix.") && !strings.HasPrefix(f.Name(), "unix.") && !strings.HasPrefix(f.Name(), "infiniband.unix.") {
continue
}
// Remove the entry
devicePath := filepath.Join(c.DevicesPath(), f.Name())
err := os.Remove(devicePath)
if err != nil {
logger.Error("Failed removing unix device", log.Ctx{"err": err, "path": devicePath})
}
}
return nil
}
// FillNetworkDevice takes a nic or infiniband device type and enriches it with automatically
// generated name and hwaddr properties if these are missing from the device.
func (c *lxc) FillNetworkDevice(name string, m deviceConfig.Device) (deviceConfig.Device, error) {
var err error
newDevice := m.Clone()
// Function to try and guess an available name
nextInterfaceName := func() (string, error) {
devNames := []string{}
// Include all static interface names
for _, dev := range c.expandedDevices.Sorted() {
if dev.Config["name"] != "" && !shared.StringInSlice(dev.Config["name"], devNames) {
devNames = append(devNames, dev.Config["name"])
}
}
// Include all currently allocated interface names
for k, v := range c.expandedConfig {
if !strings.HasPrefix(k, "volatile.") {
continue
}
fields := strings.SplitN(k, ".", 3)
if len(fields) != 3 {
continue
}
if fields[2] != "name" || shared.StringInSlice(v, devNames) {
continue
}
devNames = append(devNames, v)
}
// Attempt to include all existing interfaces
cname := project.Instance(c.Project(), c.Name())
cc, err := liblxc.NewContainer(cname, c.state.OS.LxcPath)
if err == nil {
defer cc.Release()
interfaces, err := cc.Interfaces()
if err == nil {
for _, name := range interfaces {
if shared.StringInSlice(name, devNames) {
continue
}
devNames = append(devNames, name)
}
}
}
i := 0
name := ""
for {
if m["type"] == "infiniband" {
name = fmt.Sprintf("ib%d", i)
} else {
name = fmt.Sprintf("eth%d", i)
}
// Find a free device name
if !shared.StringInSlice(name, devNames) {
return name, nil
}
i++
}
}
updateKey := func(key string, value string) error {
tx, err := c.state.Cluster.Begin()
if err != nil {
return err
}
err = db.ContainerConfigInsert(tx, c.id, map[string]string{key: value})
if err != nil {
tx.Rollback()
return err
}
err = db.TxCommit(tx)
if err != nil {
return err
}
return nil
}
// Fill in the MAC address
if !shared.StringInSlice(m.NICType(), []string{"physical", "ipvlan", "sriov"}) && m["hwaddr"] == "" {
configKey := fmt.Sprintf("volatile.%s.hwaddr", name)
volatileHwaddr := c.localConfig[configKey]
if volatileHwaddr == "" {
// Generate a new MAC address
volatileHwaddr, err = instance.DeviceNextInterfaceHWAddr()
if err != nil {
return nil, err
}
// Update the database
err = query.Retry(func() error {
err := updateKey(configKey, volatileHwaddr)
if err != nil {
// Check if something else filled it in behind our back
value, err1 := c.state.Cluster.ContainerConfigGet(c.id, configKey)
if err1 != nil || value == "" {
return err
}
c.localConfig[configKey] = value
c.expandedConfig[configKey] = value
return nil
}
c.localConfig[configKey] = volatileHwaddr
c.expandedConfig[configKey] = volatileHwaddr
return nil
})
if err != nil {
return nil, err
}
}
newDevice["hwaddr"] = volatileHwaddr
}
// Fill in the name
if m["name"] == "" {
configKey := fmt.Sprintf("volatile.%s.name", name)
volatileName := c.localConfig[configKey]
if volatileName == "" {
// Generate a new interface name
volatileName, err := nextInterfaceName()
if err != nil {
return nil, err
}
// Update the database
err = updateKey(configKey, volatileName)
if err != nil {
// Check if something else filled it in behind our back
value, err1 := c.state.Cluster.ContainerConfigGet(c.id, configKey)
if err1 != nil || value == "" {
return nil, err
}
c.localConfig[configKey] = value
c.expandedConfig[configKey] = value
} else {
c.localConfig[configKey] = volatileName
c.expandedConfig[configKey] = volatileName
}
}
newDevice["name"] = volatileName
}
return newDevice, nil
}
func (c *lxc) removeDiskDevices() error {
// Check that we indeed have devices to remove
if !shared.PathExists(c.DevicesPath()) {
return nil
}
// Load the directory listing
dents, err := ioutil.ReadDir(c.DevicesPath())
if err != nil {
return err
}
// Go through all the unix devices
for _, f := range dents {
// Skip non-disk devices
if !strings.HasPrefix(f.Name(), "disk.") {
continue
}
// Always try to unmount the host side
_ = unix.Unmount(filepath.Join(c.DevicesPath(), f.Name()), unix.MNT_DETACH)
// Remove the entry
diskPath := filepath.Join(c.DevicesPath(), f.Name())
err := os.Remove(diskPath)
if err != nil {
logger.Error("Failed to remove disk device path", log.Ctx{"err": err, "path": diskPath})
}
}
return nil
}
// Network I/O limits
func (c *lxc) setNetworkPriority() error {
cg, err := c.cgroup(nil)
if err != nil {
return err
}
// Check that the container is running
if !c.IsRunning() {
return fmt.Errorf("Can't set network priority on stopped container")
}
// Don't bother if the cgroup controller doesn't exist
if !c.state.OS.CGInfo.Supports(cgroup.NetPrio, cg) {
return nil
}
// Extract the current priority
networkPriority := c.expandedConfig["limits.network.priority"]
if networkPriority == "" {
networkPriority = "0"
}
networkInt, err := strconv.Atoi(networkPriority)
if err != nil {
return err
}
// Get all the interfaces
netifs, err := net.Interfaces()
if err != nil {
return err
}
// Check that we at least succeeded to set an entry
success := false
var lastError error
for _, netif := range netifs {
err = cg.SetNetIfPrio(fmt.Sprintf("%s %d", netif.Name, networkInt))
if err == nil {
success = true
} else {
lastError = err
}
}
if !success {
return fmt.Errorf("Failed to set network device priority: %s", lastError)
}
return nil
}
// IsStateful returns is instance is stateful.
func (c *lxc) IsStateful() bool {
return c.stateful
}
// IsEphemeral returns if instance is ephemeral.
func (c *lxc) IsEphemeral() bool {
return c.ephemeral
}
// IsFrozen returns if instance is frozen.
func (c *lxc) IsFrozen() bool {
return c.State() == "FROZEN"
}
// IsNesting returns if instance is nested.
func (c *lxc) IsNesting() bool {
return shared.IsTrue(c.expandedConfig["security.nesting"])
}
func (c *lxc) isCurrentlyPrivileged() bool {
if !c.IsRunning() {
return c.IsPrivileged()
}
idmap, err := c.CurrentIdmap()
if err != nil {
return c.IsPrivileged()
}
return idmap == nil
}
// IsPrivileged returns if instance is privileged.
func (c *lxc) IsPrivileged() bool {
return shared.IsTrue(c.expandedConfig["security.privileged"])
}
// IsRunning returns if instance is running.
func (c *lxc) IsRunning() bool {
state := c.State()
return state != "BROKEN" && state != "STOPPED"
}
// IsSnapshot returns if instance is a snapshot.
func (c *lxc) IsSnapshot() bool {
return c.snapshot
}
// Architecture returns architecture of instance.
func (c *lxc) Architecture() int {
return c.architecture
}
// CreationDate returns creation date of instance.
func (c *lxc) CreationDate() time.Time {
return c.creationDate
}
// LastUsedDate returns last used date time of instance.
func (c *lxc) LastUsedDate() time.Time {
return c.lastUsedDate
}
// ExpandedConfig returns expanded config.
func (c *lxc) ExpandedConfig() map[string]string {
return c.expandedConfig
}
// ExpandedDevices returns expanded devices config.
func (c *lxc) ExpandedDevices() deviceConfig.Devices {
return c.expandedDevices
}
// ID gets instances's ID.
func (c *lxc) ID() int {
return c.id
}
// InitPID returns PID of init process.
func (c *lxc) InitPID() int {
// Load the go-lxc struct
err := c.initLXC(false)
if err != nil {
return -1
}
return c.c.InitPid()
}
// LocalConfig returns local config.
func (c *lxc) LocalConfig() map[string]string {
return c.localConfig
}
// LocalDevices returns local device config.
func (c *lxc) LocalDevices() deviceConfig.Devices {
return c.localDevices
}
// CurrentIdmap returns current IDMAP.
func (c *lxc) CurrentIdmap() (*idmap.IdmapSet, error) {
jsonIdmap, ok := c.LocalConfig()["volatile.idmap.current"]
if !ok {
return c.DiskIdmap()
}
return idmap.JSONUnmarshal(jsonIdmap)
}
// DiskIdmap returns DISK IDMAP.
func (c *lxc) DiskIdmap() (*idmap.IdmapSet, error) {
jsonIdmap, ok := c.LocalConfig()["volatile.last_state.idmap"]
if !ok {
return nil, nil
}
return idmap.JSONUnmarshal(jsonIdmap)
}
// NextIdmap returns next IDMAP.
func (c *lxc) NextIdmap() (*idmap.IdmapSet, error) {
jsonIdmap, ok := c.LocalConfig()["volatile.idmap.next"]
if !ok {
return c.CurrentIdmap()
}
return idmap.JSONUnmarshal(jsonIdmap)
}
// Location returns instance location.
func (c *lxc) Location() string {
return c.node
}
// Project returns instance project.
func (c *lxc) Project() string {
return c.project
}
// Name returns instance name.
func (c *lxc) Name() string {
return c.name
}
// Description returns instance description.
func (c *lxc) Description() string {
return c.description
}
// Profiles returns instance profiles.
func (c *lxc) Profiles() []string {
return c.profiles
}
// State returns instance state.
func (c *lxc) State() string {
state, err := c.getLxcState()
if err != nil {
return api.Error.String()
}
return state.String()
}
// Path instance path.
func (c *lxc) Path() string {
return storagePools.InstancePath(c.Type(), c.Project(), c.Name(), c.IsSnapshot())
}
// DevicesPath devices path.
func (c *lxc) DevicesPath() string {
name := project.Instance(c.Project(), c.Name())
return shared.VarPath("devices", name)
}
// ShmountsPath shared mounts path.
func (c *lxc) ShmountsPath() string {
name := project.Instance(c.Project(), c.Name())
return shared.VarPath("shmounts", name)
}
// LogPath log path.
func (c *lxc) LogPath() string {
name := project.Instance(c.Project(), c.Name())
return shared.LogPath(name)
}
// LogFilePath log file path.
func (c *lxc) LogFilePath() string {
return filepath.Join(c.LogPath(), "lxc.log")
}
// ConsoleBufferLogPath console buffer log path.
func (c *lxc) ConsoleBufferLogPath() string {
return filepath.Join(c.LogPath(), "console.log")
}
// RootfsPath root filesystem path.
func (c *lxc) RootfsPath() string {
return filepath.Join(c.Path(), "rootfs")
}
// TemplatesPath templates path.
func (c *lxc) TemplatesPath() string {
return filepath.Join(c.Path(), "templates")
}
// StatePath state path.
func (c *lxc) StatePath() string {
/* FIXME: backwards compatibility: we used to use Join(RootfsPath(),
* "state"), which was bad. Let's just check to see if that directory
* exists.
*/
oldStatePath := filepath.Join(c.RootfsPath(), "state")
if shared.IsDir(oldStatePath) {
return oldStatePath
}
return filepath.Join(c.Path(), "state")
}
// StoragePool storage pool name.
func (c *lxc) StoragePool() (string, error) {
poolName, err := c.state.Cluster.InstancePool(c.Project(), c.Name())
if err != nil {
return "", err
}
return poolName, nil
}
// SetOperation handles progress tracking.
func (c *lxc) SetOperation(op *operations.Operation) {
c.op = op
}
// ExpiryDate sets expiry date.
func (c *lxc) ExpiryDate() time.Time {
if c.IsSnapshot() {
return c.expiryDate
}
// Return zero time if the container is not a snapshot
return time.Time{}
}
func (c *lxc) updateProgress(progress string) {
if c.op == nil {
return
}
meta := c.op.Metadata()
if meta == nil {
meta = make(map[string]interface{})
}
if meta["container_progress"] != progress {
meta["container_progress"] = progress
c.op.UpdateMetadata(meta)
}
}
// Internal MAAS handling.
func (c *lxc) maasInterfaces(devices map[string]map[string]string) ([]maas.ContainerInterface, error) {
interfaces := []maas.ContainerInterface{}
for k, m := range devices {
if m["type"] != "nic" {
continue
}
if m["maas.subnet.ipv4"] == "" && m["maas.subnet.ipv6"] == "" {
continue
}
m, err := c.FillNetworkDevice(k, m)
if err != nil {
return nil, err
}
subnets := []maas.ContainerInterfaceSubnet{}
// IPv4
if m["maas.subnet.ipv4"] != "" {
subnet := maas.ContainerInterfaceSubnet{
Name: m["maas.subnet.ipv4"],
Address: m["ipv4.address"],
}
subnets = append(subnets, subnet)
}
// IPv6
if m["maas.subnet.ipv6"] != "" {
subnet := maas.ContainerInterfaceSubnet{
Name: m["maas.subnet.ipv6"],
Address: m["ipv6.address"],
}
subnets = append(subnets, subnet)
}
iface := maas.ContainerInterface{
Name: m["name"],
MACAddress: m["hwaddr"],
Subnets: subnets,
}
interfaces = append(interfaces, iface)
}
return interfaces, nil
}
func (c *lxc) maasUpdate(oldDevices map[string]map[string]string) error {
// Check if MAAS is configured
maasURL, err := cluster.ConfigGetString(c.state.Cluster, "maas.api.url")
if err != nil {
return err
}
if maasURL == "" {
return nil
}
// Check if there's something that uses MAAS
interfaces, err := c.maasInterfaces(c.expandedDevices.CloneNative())
if err != nil {
return err
}
var oldInterfaces []maas.ContainerInterface
if oldDevices != nil {
oldInterfaces, err = c.maasInterfaces(oldDevices)
if err != nil {
return err
}
}
if len(interfaces) == 0 && len(oldInterfaces) == 0 {
return nil
}
// See if we're connected to MAAS
if c.state.MAAS == nil {
return fmt.Errorf("Can't perform the operation because MAAS is currently unavailable")
}
exists, err := c.state.MAAS.DefinedContainer(project.Instance(c.project, c.name))
if err != nil {
return err
}
if exists {
if len(interfaces) == 0 && len(oldInterfaces) > 0 {
return c.state.MAAS.DeleteContainer(project.Instance(c.project, c.name))
}
return c.state.MAAS.UpdateContainer(project.Instance(c.project, c.name), interfaces)
}
return c.state.MAAS.CreateContainer(project.Instance(c.project, c.name), interfaces)
}
func (c *lxc) maasRename(newName string) error {
maasURL, err := cluster.ConfigGetString(c.state.Cluster, "maas.api.url")
if err != nil {
return err
}
if maasURL == "" {
return nil
}
interfaces, err := c.maasInterfaces(c.expandedDevices.CloneNative())
if err != nil {
return err
}
if len(interfaces) == 0 {
return nil
}
if c.state.MAAS == nil {
return fmt.Errorf("Can't perform the operation because MAAS is currently unavailable")
}
exists, err := c.state.MAAS.DefinedContainer(project.Instance(c.project, c.name))
if err != nil {
return err
}
if !exists {
return c.maasUpdate(nil)
}
return c.state.MAAS.RenameContainer(project.Instance(c.project, c.name), project.Instance(c.project, newName))
}
func (c *lxc) maasDelete() error {
maasURL, err := cluster.ConfigGetString(c.state.Cluster, "maas.api.url")
if err != nil {
return err
}
if maasURL == "" {
return nil
}
interfaces, err := c.maasInterfaces(c.expandedDevices.CloneNative())
if err != nil {
return err
}
if len(interfaces) == 0 {
return nil
}
if c.state.MAAS == nil {
return fmt.Errorf("Can't perform the operation because MAAS is currently unavailable")
}
exists, err := c.state.MAAS.DefinedContainer(project.Instance(c.project, c.name))
if err != nil {
return err
}
if !exists {
return nil
}
return c.state.MAAS.DeleteContainer(project.Instance(c.project, c.name))
}
func (c *lxc) cgroup(cc *liblxc.Container) (*cgroup.CGroup, error) {
rw := lxcCgroupReadWriter{}
if cc != nil {
rw.cc = cc
rw.conf = true
} else {
rw.cc = c.c
}
cg, err := cgroup.New(&rw)
if err != nil {
return nil, err
}
cg.UnifiedCapable = liblxc.HasApiExtension("cgroup2")
return cg, nil
}
type lxcCgroupReadWriter struct {
cc *liblxc.Container
conf bool
}
func (rw *lxcCgroupReadWriter) Get(version cgroup.Backend, controller string, key string) (string, error) {
if rw.conf {
lxcKey := fmt.Sprintf("lxc.cgroup.%s", key)
if version == cgroup.V2 {
lxcKey = fmt.Sprintf("lxc.cgroup2.%s", key)
}
return strings.Join(rw.cc.ConfigItem(lxcKey), "\n"), nil
}
return strings.Join(rw.cc.CgroupItem(key), "\n"), nil
}
func (rw *lxcCgroupReadWriter) Set(version cgroup.Backend, controller string, key string, value string) error {
if rw.conf {
if version == cgroup.V1 {
return lxcSetConfigItem(rw.cc, fmt.Sprintf("lxc.cgroup.%s", key), value)
}
return lxcSetConfigItem(rw.cc, fmt.Sprintf("lxc.cgroup2.%s", key), value)
}
return rw.cc.SetCgroupItem(key, value)
}
// UpdateBackupFile writes the instance's backup.yaml file to storage.
func (c *lxc) UpdateBackupFile() error {
pool, err := c.getStoragePool()
if err != nil {
return err
}
return pool.UpdateInstanceBackupFile(c, nil)
}
// SaveConfigFile generates the LXC config file on disk.
func (c *lxc) SaveConfigFile() error {
err := c.initLXC(true)
if err != nil {
return errors.Wrapf(err, "Failed to generate LXC config")
}
// Generate the LXC config.
configPath := filepath.Join(c.LogPath(), "lxc.conf")
err = c.c.SaveConfigFile(configPath)
if err != nil {
os.Remove(configPath)
return errors.Wrapf(err, "Failed to save LXC config to file %q", configPath)
}
return nil
}
| [
"\"LXD_LXC_TEMPLATE_CONFIG\"",
"\"LXD_LXC_HOOK\""
]
| []
| [
"LXD_LXC_TEMPLATE_CONFIG",
"LXD_LXC_HOOK"
]
| [] | ["LXD_LXC_TEMPLATE_CONFIG", "LXD_LXC_HOOK"] | go | 2 | 0 | |
examples/paperwallet/main.go | package main
import (
"context"
"os"
"strconv"
"github.com/rodrigo-brito/ninjabot"
"github.com/rodrigo-brito/ninjabot/examples/strategies"
"github.com/rodrigo-brito/ninjabot/exchange"
"github.com/rodrigo-brito/ninjabot/storage"
log "github.com/sirupsen/logrus"
)
func main() {
var (
ctx = context.Background()
telegramToken = os.Getenv("TELEGRAM_TOKEN")
telegramUser, _ = strconv.Atoi(os.Getenv("TELEGRAM_USER"))
)
settings := ninjabot.Settings{
Pairs: []string{
"BTCUSDT",
"ETHUSDT",
"BNBUSDT",
"LTCUSDT",
},
Telegram: ninjabot.TelegramSettings{
Enabled: true,
Token: telegramToken,
Users: []int{telegramUser},
},
}
// Use binance for realtime data feed
binance, err := exchange.NewBinance(ctx)
if err != nil {
log.Fatal(err)
}
// creating a storage to save trades
storage, err := storage.FromMemory()
if err != nil {
log.Fatal(err)
}
// creating a paper wallet to simulate an exchange waller for fake operataions
paperWallet := exchange.NewPaperWallet(
ctx,
"USDT",
exchange.WithPaperFee(0.001, 0.001),
exchange.WithPaperAsset("USDT", 10000),
exchange.WithDataFeed(binance),
)
// initializing my strategy
strategy := new(strategies.CrossEMA)
// initializer ninjabot
bot, err := ninjabot.NewBot(
ctx,
settings,
paperWallet,
strategy,
ninjabot.WithStorage(storage),
ninjabot.WithPaperWallet(paperWallet),
)
if err != nil {
log.Fatalln(err)
}
err = bot.Run(ctx)
if err != nil {
log.Fatalln(err)
}
}
| [
"\"TELEGRAM_TOKEN\"",
"\"TELEGRAM_USER\""
]
| []
| [
"TELEGRAM_USER",
"TELEGRAM_TOKEN"
]
| [] | ["TELEGRAM_USER", "TELEGRAM_TOKEN"] | go | 2 | 0 | |
python/services/binaryauthorization/alpha/policy.py | # Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from connector import channel
from google3.cloud.graphite.mmv2.services.google.binary_authorization import policy_pb2
from google3.cloud.graphite.mmv2.services.google.binary_authorization import (
policy_pb2_grpc,
)
from typing import List
class Policy(object):
def __init__(
self,
admission_whitelist_patterns: list = None,
cluster_admission_rules: dict = None,
kubernetes_namespace_admission_rules: dict = None,
kubernetes_service_account_admission_rules: dict = None,
istio_service_identity_admission_rules: dict = None,
default_admission_rule: dict = None,
description: str = None,
global_policy_evaluation_mode: str = None,
self_link: str = None,
project: str = None,
update_time: str = None,
service_account_file: str = "",
):
channel.initialize()
self.admission_whitelist_patterns = admission_whitelist_patterns
self.cluster_admission_rules = cluster_admission_rules
self.kubernetes_namespace_admission_rules = kubernetes_namespace_admission_rules
self.kubernetes_service_account_admission_rules = (
kubernetes_service_account_admission_rules
)
self.istio_service_identity_admission_rules = (
istio_service_identity_admission_rules
)
self.default_admission_rule = default_admission_rule
self.description = description
self.global_policy_evaluation_mode = global_policy_evaluation_mode
self.project = project
self.service_account_file = service_account_file
def apply(self):
stub = policy_pb2_grpc.BinaryauthorizationAlphaPolicyServiceStub(
channel.Channel()
)
request = policy_pb2.ApplyBinaryauthorizationAlphaPolicyRequest()
if PolicyAdmissionWhitelistPatternsArray.to_proto(
self.admission_whitelist_patterns
):
request.resource.admission_whitelist_patterns.extend(
PolicyAdmissionWhitelistPatternsArray.to_proto(
self.admission_whitelist_patterns
)
)
if Primitive.to_proto(self.cluster_admission_rules):
request.resource.cluster_admission_rules = Primitive.to_proto(
self.cluster_admission_rules
)
if Primitive.to_proto(self.kubernetes_namespace_admission_rules):
request.resource.kubernetes_namespace_admission_rules = Primitive.to_proto(
self.kubernetes_namespace_admission_rules
)
if Primitive.to_proto(self.kubernetes_service_account_admission_rules):
request.resource.kubernetes_service_account_admission_rules = (
Primitive.to_proto(self.kubernetes_service_account_admission_rules)
)
if Primitive.to_proto(self.istio_service_identity_admission_rules):
request.resource.istio_service_identity_admission_rules = (
Primitive.to_proto(self.istio_service_identity_admission_rules)
)
if PolicyDefaultAdmissionRule.to_proto(self.default_admission_rule):
request.resource.default_admission_rule.CopyFrom(
PolicyDefaultAdmissionRule.to_proto(self.default_admission_rule)
)
else:
request.resource.ClearField("default_admission_rule")
if Primitive.to_proto(self.description):
request.resource.description = Primitive.to_proto(self.description)
if PolicyGlobalPolicyEvaluationModeEnum.to_proto(
self.global_policy_evaluation_mode
):
request.resource.global_policy_evaluation_mode = (
PolicyGlobalPolicyEvaluationModeEnum.to_proto(
self.global_policy_evaluation_mode
)
)
if Primitive.to_proto(self.project):
request.resource.project = Primitive.to_proto(self.project)
request.service_account_file = self.service_account_file
response = stub.ApplyBinaryauthorizationAlphaPolicy(request)
self.admission_whitelist_patterns = (
PolicyAdmissionWhitelistPatternsArray.from_proto(
response.admission_whitelist_patterns
)
)
self.cluster_admission_rules = Primitive.from_proto(
response.cluster_admission_rules
)
self.kubernetes_namespace_admission_rules = Primitive.from_proto(
response.kubernetes_namespace_admission_rules
)
self.kubernetes_service_account_admission_rules = Primitive.from_proto(
response.kubernetes_service_account_admission_rules
)
self.istio_service_identity_admission_rules = Primitive.from_proto(
response.istio_service_identity_admission_rules
)
self.default_admission_rule = PolicyDefaultAdmissionRule.from_proto(
response.default_admission_rule
)
self.description = Primitive.from_proto(response.description)
self.global_policy_evaluation_mode = (
PolicyGlobalPolicyEvaluationModeEnum.from_proto(
response.global_policy_evaluation_mode
)
)
self.self_link = Primitive.from_proto(response.self_link)
self.project = Primitive.from_proto(response.project)
self.update_time = Primitive.from_proto(response.update_time)
def delete(self):
stub = policy_pb2_grpc.BinaryauthorizationAlphaPolicyServiceStub(
channel.Channel()
)
request = policy_pb2.DeleteBinaryauthorizationAlphaPolicyRequest()
request.service_account_file = self.service_account_file
if PolicyAdmissionWhitelistPatternsArray.to_proto(
self.admission_whitelist_patterns
):
request.resource.admission_whitelist_patterns.extend(
PolicyAdmissionWhitelistPatternsArray.to_proto(
self.admission_whitelist_patterns
)
)
if Primitive.to_proto(self.cluster_admission_rules):
request.resource.cluster_admission_rules = Primitive.to_proto(
self.cluster_admission_rules
)
if Primitive.to_proto(self.kubernetes_namespace_admission_rules):
request.resource.kubernetes_namespace_admission_rules = Primitive.to_proto(
self.kubernetes_namespace_admission_rules
)
if Primitive.to_proto(self.kubernetes_service_account_admission_rules):
request.resource.kubernetes_service_account_admission_rules = (
Primitive.to_proto(self.kubernetes_service_account_admission_rules)
)
if Primitive.to_proto(self.istio_service_identity_admission_rules):
request.resource.istio_service_identity_admission_rules = (
Primitive.to_proto(self.istio_service_identity_admission_rules)
)
if PolicyDefaultAdmissionRule.to_proto(self.default_admission_rule):
request.resource.default_admission_rule.CopyFrom(
PolicyDefaultAdmissionRule.to_proto(self.default_admission_rule)
)
else:
request.resource.ClearField("default_admission_rule")
if Primitive.to_proto(self.description):
request.resource.description = Primitive.to_proto(self.description)
if PolicyGlobalPolicyEvaluationModeEnum.to_proto(
self.global_policy_evaluation_mode
):
request.resource.global_policy_evaluation_mode = (
PolicyGlobalPolicyEvaluationModeEnum.to_proto(
self.global_policy_evaluation_mode
)
)
if Primitive.to_proto(self.project):
request.resource.project = Primitive.to_proto(self.project)
response = stub.DeleteBinaryauthorizationAlphaPolicy(request)
@classmethod
def list(self, service_account_file=""):
stub = policy_pb2_grpc.BinaryauthorizationAlphaPolicyServiceStub(
channel.Channel()
)
request = policy_pb2.ListBinaryauthorizationAlphaPolicyRequest()
request.service_account_file = service_account_file
return stub.ListBinaryauthorizationAlphaPolicy(request).items
def to_proto(self):
resource = policy_pb2.BinaryauthorizationAlphaPolicy()
if PolicyAdmissionWhitelistPatternsArray.to_proto(
self.admission_whitelist_patterns
):
resource.admission_whitelist_patterns.extend(
PolicyAdmissionWhitelistPatternsArray.to_proto(
self.admission_whitelist_patterns
)
)
if Primitive.to_proto(self.cluster_admission_rules):
resource.cluster_admission_rules = Primitive.to_proto(
self.cluster_admission_rules
)
if Primitive.to_proto(self.kubernetes_namespace_admission_rules):
resource.kubernetes_namespace_admission_rules = Primitive.to_proto(
self.kubernetes_namespace_admission_rules
)
if Primitive.to_proto(self.kubernetes_service_account_admission_rules):
resource.kubernetes_service_account_admission_rules = Primitive.to_proto(
self.kubernetes_service_account_admission_rules
)
if Primitive.to_proto(self.istio_service_identity_admission_rules):
resource.istio_service_identity_admission_rules = Primitive.to_proto(
self.istio_service_identity_admission_rules
)
if PolicyDefaultAdmissionRule.to_proto(self.default_admission_rule):
resource.default_admission_rule.CopyFrom(
PolicyDefaultAdmissionRule.to_proto(self.default_admission_rule)
)
else:
resource.ClearField("default_admission_rule")
if Primitive.to_proto(self.description):
resource.description = Primitive.to_proto(self.description)
if PolicyGlobalPolicyEvaluationModeEnum.to_proto(
self.global_policy_evaluation_mode
):
resource.global_policy_evaluation_mode = (
PolicyGlobalPolicyEvaluationModeEnum.to_proto(
self.global_policy_evaluation_mode
)
)
if Primitive.to_proto(self.project):
resource.project = Primitive.to_proto(self.project)
return resource
class PolicyAdmissionWhitelistPatterns(object):
def __init__(self, name_pattern: str = None):
self.name_pattern = name_pattern
@classmethod
def to_proto(self, resource):
if not resource:
return None
res = policy_pb2.BinaryauthorizationAlphaPolicyAdmissionWhitelistPatterns()
if Primitive.to_proto(resource.name_pattern):
res.name_pattern = Primitive.to_proto(resource.name_pattern)
return res
@classmethod
def from_proto(self, resource):
if not resource:
return None
return PolicyAdmissionWhitelistPatterns(
name_pattern=Primitive.from_proto(resource.name_pattern),
)
class PolicyAdmissionWhitelistPatternsArray(object):
@classmethod
def to_proto(self, resources):
if not resources:
return resources
return [PolicyAdmissionWhitelistPatterns.to_proto(i) for i in resources]
@classmethod
def from_proto(self, resources):
return [PolicyAdmissionWhitelistPatterns.from_proto(i) for i in resources]
class PolicyClusterAdmissionRules(object):
def __init__(
self,
evaluation_mode: str = None,
require_attestations_by: list = None,
enforcement_mode: str = None,
):
self.evaluation_mode = evaluation_mode
self.require_attestations_by = require_attestations_by
self.enforcement_mode = enforcement_mode
@classmethod
def to_proto(self, resource):
if not resource:
return None
res = policy_pb2.BinaryauthorizationAlphaPolicyClusterAdmissionRules()
if PolicyClusterAdmissionRulesEvaluationModeEnum.to_proto(
resource.evaluation_mode
):
res.evaluation_mode = (
PolicyClusterAdmissionRulesEvaluationModeEnum.to_proto(
resource.evaluation_mode
)
)
if Primitive.to_proto(resource.require_attestations_by):
res.require_attestations_by.extend(
Primitive.to_proto(resource.require_attestations_by)
)
if PolicyClusterAdmissionRulesEnforcementModeEnum.to_proto(
resource.enforcement_mode
):
res.enforcement_mode = (
PolicyClusterAdmissionRulesEnforcementModeEnum.to_proto(
resource.enforcement_mode
)
)
return res
@classmethod
def from_proto(self, resource):
if not resource:
return None
return PolicyClusterAdmissionRules(
evaluation_mode=PolicyClusterAdmissionRulesEvaluationModeEnum.from_proto(
resource.evaluation_mode
),
require_attestations_by=Primitive.from_proto(
resource.require_attestations_by
),
enforcement_mode=PolicyClusterAdmissionRulesEnforcementModeEnum.from_proto(
resource.enforcement_mode
),
)
class PolicyClusterAdmissionRulesArray(object):
@classmethod
def to_proto(self, resources):
if not resources:
return resources
return [PolicyClusterAdmissionRules.to_proto(i) for i in resources]
@classmethod
def from_proto(self, resources):
return [PolicyClusterAdmissionRules.from_proto(i) for i in resources]
class PolicyKubernetesNamespaceAdmissionRules(object):
def __init__(
self,
evaluation_mode: str = None,
require_attestations_by: list = None,
enforcement_mode: str = None,
):
self.evaluation_mode = evaluation_mode
self.require_attestations_by = require_attestations_by
self.enforcement_mode = enforcement_mode
@classmethod
def to_proto(self, resource):
if not resource:
return None
res = (
policy_pb2.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRules()
)
if PolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum.to_proto(
resource.evaluation_mode
):
res.evaluation_mode = (
PolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum.to_proto(
resource.evaluation_mode
)
)
if Primitive.to_proto(resource.require_attestations_by):
res.require_attestations_by.extend(
Primitive.to_proto(resource.require_attestations_by)
)
if PolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum.to_proto(
resource.enforcement_mode
):
res.enforcement_mode = (
PolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum.to_proto(
resource.enforcement_mode
)
)
return res
@classmethod
def from_proto(self, resource):
if not resource:
return None
return PolicyKubernetesNamespaceAdmissionRules(
evaluation_mode=PolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum.from_proto(
resource.evaluation_mode
),
require_attestations_by=Primitive.from_proto(
resource.require_attestations_by
),
enforcement_mode=PolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum.from_proto(
resource.enforcement_mode
),
)
class PolicyKubernetesNamespaceAdmissionRulesArray(object):
@classmethod
def to_proto(self, resources):
if not resources:
return resources
return [PolicyKubernetesNamespaceAdmissionRules.to_proto(i) for i in resources]
@classmethod
def from_proto(self, resources):
return [
PolicyKubernetesNamespaceAdmissionRules.from_proto(i) for i in resources
]
class PolicyKubernetesServiceAccountAdmissionRules(object):
def __init__(
self,
evaluation_mode: str = None,
require_attestations_by: list = None,
enforcement_mode: str = None,
):
self.evaluation_mode = evaluation_mode
self.require_attestations_by = require_attestations_by
self.enforcement_mode = enforcement_mode
@classmethod
def to_proto(self, resource):
if not resource:
return None
res = (
policy_pb2.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRules()
)
if PolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum.to_proto(
resource.evaluation_mode
):
res.evaluation_mode = (
PolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum.to_proto(
resource.evaluation_mode
)
)
if Primitive.to_proto(resource.require_attestations_by):
res.require_attestations_by.extend(
Primitive.to_proto(resource.require_attestations_by)
)
if PolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum.to_proto(
resource.enforcement_mode
):
res.enforcement_mode = PolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum.to_proto(
resource.enforcement_mode
)
return res
@classmethod
def from_proto(self, resource):
if not resource:
return None
return PolicyKubernetesServiceAccountAdmissionRules(
evaluation_mode=PolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum.from_proto(
resource.evaluation_mode
),
require_attestations_by=Primitive.from_proto(
resource.require_attestations_by
),
enforcement_mode=PolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum.from_proto(
resource.enforcement_mode
),
)
class PolicyKubernetesServiceAccountAdmissionRulesArray(object):
@classmethod
def to_proto(self, resources):
if not resources:
return resources
return [
PolicyKubernetesServiceAccountAdmissionRules.to_proto(i) for i in resources
]
@classmethod
def from_proto(self, resources):
return [
PolicyKubernetesServiceAccountAdmissionRules.from_proto(i)
for i in resources
]
class PolicyIstioServiceIdentityAdmissionRules(object):
def __init__(
self,
evaluation_mode: str = None,
require_attestations_by: list = None,
enforcement_mode: str = None,
):
self.evaluation_mode = evaluation_mode
self.require_attestations_by = require_attestations_by
self.enforcement_mode = enforcement_mode
@classmethod
def to_proto(self, resource):
if not resource:
return None
res = (
policy_pb2.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRules()
)
if PolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum.to_proto(
resource.evaluation_mode
):
res.evaluation_mode = (
PolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum.to_proto(
resource.evaluation_mode
)
)
if Primitive.to_proto(resource.require_attestations_by):
res.require_attestations_by.extend(
Primitive.to_proto(resource.require_attestations_by)
)
if PolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum.to_proto(
resource.enforcement_mode
):
res.enforcement_mode = (
PolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum.to_proto(
resource.enforcement_mode
)
)
return res
@classmethod
def from_proto(self, resource):
if not resource:
return None
return PolicyIstioServiceIdentityAdmissionRules(
evaluation_mode=PolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum.from_proto(
resource.evaluation_mode
),
require_attestations_by=Primitive.from_proto(
resource.require_attestations_by
),
enforcement_mode=PolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum.from_proto(
resource.enforcement_mode
),
)
class PolicyIstioServiceIdentityAdmissionRulesArray(object):
@classmethod
def to_proto(self, resources):
if not resources:
return resources
return [PolicyIstioServiceIdentityAdmissionRules.to_proto(i) for i in resources]
@classmethod
def from_proto(self, resources):
return [
PolicyIstioServiceIdentityAdmissionRules.from_proto(i) for i in resources
]
class PolicyDefaultAdmissionRule(object):
def __init__(
self,
evaluation_mode: str = None,
require_attestations_by: list = None,
enforcement_mode: str = None,
):
self.evaluation_mode = evaluation_mode
self.require_attestations_by = require_attestations_by
self.enforcement_mode = enforcement_mode
@classmethod
def to_proto(self, resource):
if not resource:
return None
res = policy_pb2.BinaryauthorizationAlphaPolicyDefaultAdmissionRule()
if PolicyDefaultAdmissionRuleEvaluationModeEnum.to_proto(
resource.evaluation_mode
):
res.evaluation_mode = PolicyDefaultAdmissionRuleEvaluationModeEnum.to_proto(
resource.evaluation_mode
)
if Primitive.to_proto(resource.require_attestations_by):
res.require_attestations_by.extend(
Primitive.to_proto(resource.require_attestations_by)
)
if PolicyDefaultAdmissionRuleEnforcementModeEnum.to_proto(
resource.enforcement_mode
):
res.enforcement_mode = (
PolicyDefaultAdmissionRuleEnforcementModeEnum.to_proto(
resource.enforcement_mode
)
)
return res
@classmethod
def from_proto(self, resource):
if not resource:
return None
return PolicyDefaultAdmissionRule(
evaluation_mode=PolicyDefaultAdmissionRuleEvaluationModeEnum.from_proto(
resource.evaluation_mode
),
require_attestations_by=Primitive.from_proto(
resource.require_attestations_by
),
enforcement_mode=PolicyDefaultAdmissionRuleEnforcementModeEnum.from_proto(
resource.enforcement_mode
),
)
class PolicyDefaultAdmissionRuleArray(object):
@classmethod
def to_proto(self, resources):
if not resources:
return resources
return [PolicyDefaultAdmissionRule.to_proto(i) for i in resources]
@classmethod
def from_proto(self, resources):
return [PolicyDefaultAdmissionRule.from_proto(i) for i in resources]
class PolicyClusterAdmissionRulesEvaluationModeEnum(object):
@classmethod
def to_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum.Value(
"BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum%s"
% resource
)
@classmethod
def from_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum.Name(
resource
)[
len(
"BinaryauthorizationAlphaPolicyClusterAdmissionRulesEvaluationModeEnum"
) :
]
class PolicyClusterAdmissionRulesEnforcementModeEnum(object):
@classmethod
def to_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum.Value(
"BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum%s"
% resource
)
@classmethod
def from_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum.Name(
resource
)[
len(
"BinaryauthorizationAlphaPolicyClusterAdmissionRulesEnforcementModeEnum"
) :
]
class PolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum(object):
@classmethod
def to_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum.Value(
"BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum%s"
% resource
)
@classmethod
def from_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum.Name(
resource
)[
len(
"BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEvaluationModeEnum"
) :
]
class PolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum(object):
@classmethod
def to_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum.Value(
"BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum%s"
% resource
)
@classmethod
def from_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum.Name(
resource
)[
len(
"BinaryauthorizationAlphaPolicyKubernetesNamespaceAdmissionRulesEnforcementModeEnum"
) :
]
class PolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum(object):
@classmethod
def to_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum.Value(
"BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum%s"
% resource
)
@classmethod
def from_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum.Name(
resource
)[
len(
"BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEvaluationModeEnum"
) :
]
class PolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum(object):
@classmethod
def to_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum.Value(
"BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum%s"
% resource
)
@classmethod
def from_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum.Name(
resource
)[
len(
"BinaryauthorizationAlphaPolicyKubernetesServiceAccountAdmissionRulesEnforcementModeEnum"
) :
]
class PolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum(object):
@classmethod
def to_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum.Value(
"BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum%s"
% resource
)
@classmethod
def from_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum.Name(
resource
)[
len(
"BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEvaluationModeEnum"
) :
]
class PolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum(object):
@classmethod
def to_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum.Value(
"BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum%s"
% resource
)
@classmethod
def from_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum.Name(
resource
)[
len(
"BinaryauthorizationAlphaPolicyIstioServiceIdentityAdmissionRulesEnforcementModeEnum"
) :
]
class PolicyDefaultAdmissionRuleEvaluationModeEnum(object):
@classmethod
def to_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum.Value(
"BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum%s"
% resource
)
@classmethod
def from_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum.Name(
resource
)[
len(
"BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEvaluationModeEnum"
) :
]
class PolicyDefaultAdmissionRuleEnforcementModeEnum(object):
@classmethod
def to_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum.Value(
"BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum%s"
% resource
)
@classmethod
def from_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum.Name(
resource
)[
len(
"BinaryauthorizationAlphaPolicyDefaultAdmissionRuleEnforcementModeEnum"
) :
]
class PolicyGlobalPolicyEvaluationModeEnum(object):
@classmethod
def to_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum.Value(
"BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum%s" % resource
)
@classmethod
def from_proto(self, resource):
if not resource:
return resource
return policy_pb2.BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum.Name(
resource
)[
len("BinaryauthorizationAlphaPolicyGlobalPolicyEvaluationModeEnum") :
]
class Primitive(object):
@classmethod
def to_proto(self, s):
if not s:
return ""
return s
@classmethod
def from_proto(self, s):
return s
| []
| []
| []
| [] | [] | python | null | null | null |
python/paddle/fluid/tests/unittests/test_dist_fleet_base.py | # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
"""
high level unit test for distribute fleet.
"""
import os
import sys
import subprocess
import six
import shutil
import numpy as np
import argparse
from contextlib import closing
import socket
import time
import tempfile
import unittest
import paddle.fluid as fluid
import paddle.distributed.fleet.base.role_maker as role_maker
from paddle.distributed.fleet.base.util_factory import fleet_util
from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler import fleet
from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler.distributed_strategy import StrategyFactory
__all__ = ['FleetDistRunnerBase', 'TestFleetBase', 'runtime_main']
RUN_STEP = 5
LEARNING_RATE = 0.01
DIST_UT_PORT = 0
class FleetDistRunnerBase(object):
"""
run_pserver,run_trainer : after init role, using transpiler split program
net : implment by child class, the network of model
do training : exe run program
"""
def build_role(self, args):
if args.role.upper() == "PSERVER":
role = role_maker.UserDefinedRoleMaker(
is_collective=False,
init_gloo=True,
path=args.gloo_path,
current_id=args.current_id,
role=role_maker.Role.SERVER,
worker_endpoints=args.trainer_endpoints.split(","),
server_endpoints=args.endpoints.split(","))
else:
role = role_maker.UserDefinedRoleMaker(
is_collective=False,
init_gloo=True,
path=args.gloo_path,
current_id=args.current_id,
role=role_maker.Role.WORKER,
worker_endpoints=args.trainer_endpoints.split(","),
server_endpoints=args.endpoints.split(","))
self.role = role
return role
def build_strategy(self, args):
self.strategy = None
if args.mode == "async":
self.strategy = StrategyFactory.create_async_strategy()
elif args.mode == "sync":
self.strategy = StrategyFactory.create_sync_strategy()
elif args.mode == "half_async":
self.strategy = StrategyFactory.create_half_async_strategy()
elif args.mode == "geo":
self.strategy = StrategyFactory.create_geo_strategy(
args.geo_sgd_need_push_nums)
self.dump_param = os.getenv("dump_param", "").split(",")
self.dump_fields = os.getenv("dump_fields", "").split(",")
self.dump_fields_path = os.getenv("dump_fields_path", "")
debug = int(os.getenv("Debug", "0"))
if debug:
self.strategy.set_debug_opt({
"dump_param": self.dump_param,
"dump_fields": self.dump_fields,
"dump_fields_path": self.dump_fields_path
})
return self.strategy
def build_optimizer(self, avg_cost, strategy):
use_grad_clip = int(os.getenv('GRAD_CLIP', 0))
if use_grad_clip:
# 1: clip_by_value; 2: clip_by_norm; 3:clip_by_global_norm
if use_grad_clip == 1:
fluid.clip.set_gradient_clip(
clip=fluid.clip.GradientClipByValue(2.0))
elif use_grad_clip == 2:
fluid.clip.set_gradient_clip(
clip=fluid.clip.GradientClipByNorm(2.0))
elif use_grad_clip == 3:
fluid.clip.set_gradient_clip(
clip=fluid.clip.GradientClipByGlobalNorm(2.0))
use_decay = int(os.getenv("DECAY", "0"))
if use_decay:
optimizer = fluid.optimizer.SGD(
learning_rate=fluid.layers.exponential_decay(
learning_rate=LEARNING_RATE,
decay_steps=500,
decay_rate=0.969,
staircase=True))
else:
optimizer = fluid.optimizer.SGD(LEARNING_RATE)
optimizer = fleet.distributed_optimizer(optimizer, strategy)
optimizer.minimize(avg_cost)
def run_pserver(self, args):
fleet.init_server()
fleet.run_server()
def run_dataset_trainer(self, args):
out = self.do_dataset_training(fleet)
def run_pyreader_trainer(self, args):
out = self.do_pyreader_training(fleet)
def net(self, args, batch_size=4, lr=0.01):
raise NotImplementedError(
"get_model should be implemented by child classes.")
def do_dataset_training(self, fleet):
raise NotImplementedError(
"do_dataset_training should be implemented by child classes.")
def do_pyreader_training(self, fleet):
raise NotImplementedError(
"do_pyreader_training should be implemented by child classes.")
class TestFleetBase(unittest.TestCase):
"""
start_pserver,start_trainer : add start cmd to test
run_cluster : using multi process to test distribute program
"""
def _setup_config(self):
raise NotImplementedError("tests should have _setup_config implemented")
def setUp(self):
self._mode = "sync"
self._reader = "pyreader"
self._trainers = 2
self._pservers = 2
self._port_set = set()
global DIST_UT_PORT
if DIST_UT_PORT == 0 and os.getenv("PADDLE_DIST_UT_PORT"):
DIST_UT_PORT = int(os.getenv("PADDLE_DIST_UT_PORT"))
if DIST_UT_PORT:
print("set begin_port:", DIST_UT_PORT)
self._ps_endpoints = "127.0.0.1:%s,127.0.0.1:%s" % (
DIST_UT_PORT, DIST_UT_PORT + 1)
self._tr_endpoints = "127.0.0.1:%s,127.0.0.1:%s" % (
DIST_UT_PORT + 2, DIST_UT_PORT + 3)
DIST_UT_PORT += 4
else:
self._ps_endpoints = "127.0.0.1:%s,127.0.0.1:%s" % (
self._find_free_port(), self._find_free_port())
self._tr_endpoints = "127.0.0.1:%s,127.0.0.1:%s" % (
self._find_free_port(), self._find_free_port())
self._python_interp = sys.executable
self._geo_sgd_need_push_nums = 5
self._grad_clip_mode = 0
self._setup_config()
def _find_free_port(self):
def __free_port():
with closing(socket.socket(socket.AF_INET,
socket.SOCK_STREAM)) as s:
s.bind(('', 0))
return s.getsockname()[1]
while True:
port = __free_port()
if port not in self._port_set:
self._port_set.add(port)
return port
def _start_pserver(self, cmd, required_envs):
ps0_cmd, ps1_cmd = cmd.format(0), cmd.format(1)
ps0_pipe = open(tempfile.gettempdir() + "/ps0_err.log", "wb+")
ps1_pipe = open(tempfile.gettempdir() + "/ps1_err.log", "wb+")
ps0_proc = subprocess.Popen(
ps0_cmd.strip().split(" "),
stdout=subprocess.PIPE,
stderr=ps0_pipe,
env=required_envs)
ps1_proc = subprocess.Popen(
ps1_cmd.strip().split(" "),
stdout=subprocess.PIPE,
stderr=ps1_pipe,
env=required_envs)
return ps0_proc, ps1_proc, ps0_pipe, ps1_pipe
def _start_trainer(self, cmd, required_envs):
tr0_cmd, tr1_cmd = cmd.format(0), cmd.format(1)
tr0_pipe = open(tempfile.gettempdir() + "/tr0_err.log", "wb+")
tr1_pipe = open(tempfile.gettempdir() + "/tr1_err.log", "wb+")
tr0_proc = subprocess.Popen(
tr0_cmd.strip().split(" "),
stdout=subprocess.PIPE,
stderr=tr0_pipe,
env=required_envs)
tr1_proc = subprocess.Popen(
tr1_cmd.strip().split(" "),
stdout=subprocess.PIPE,
stderr=tr1_pipe,
env=required_envs)
return tr0_proc, tr1_proc, tr0_pipe, tr1_pipe
def _run_cluster(self, model, envs):
env = {'GRAD_CLIP': str(self._grad_clip_mode)}
python_path = self._python_interp
gloo_path = tempfile.mkdtemp()
if os.getenv('WITH_COVERAGE', 'OFF') == 'ON':
envs['COVERAGE_FILE'] = os.getenv('COVERAGE_FILE', '')
python_path += " -m coverage run --branch -p"
env.update(envs)
tr_cmd = "{0} {1} --role trainer --endpoints {2} --trainer_endpoints {3} --current_id {{}} --trainers {4} --mode {5} --geo_sgd_need_push_nums {6} --reader {7} --gloo_path {8}".format(
python_path, model, self._ps_endpoints, self._tr_endpoints,
self._trainers, self._mode, self._geo_sgd_need_push_nums,
self._reader, gloo_path)
ps_cmd = "{0} {1} --role pserver --endpoints {2} --trainer_endpoints {3} --current_id {{}} --trainers {4} --mode {5} --geo_sgd_need_push_nums {6} --reader {7} --gloo_path {8}".format(
python_path, model, self._ps_endpoints, self._tr_endpoints,
self._trainers, self._mode, self._geo_sgd_need_push_nums,
self._reader, gloo_path)
# Run dist train to compare with local results
ps0, ps1, ps0_pipe, ps1_pipe = self._start_pserver(ps_cmd, env)
tr0, tr1, tr0_pipe, tr1_pipe = self._start_trainer(tr_cmd, env)
# Wait until trainer process terminate
while True:
stat0 = tr0.poll()
time.sleep(0.1)
if stat0 is not None:
break
while True:
stat1 = tr1.poll()
time.sleep(0.1)
if stat1 is not None:
break
tr0_out, tr0_err = tr0.communicate()
tr1_out, tr1_err = tr1.communicate()
tr0_ret = tr0.returncode
tr1_ret = tr0.returncode
self.assertEqual(tr0_ret, 0, "something wrong in tr0, please check")
self.assertEqual(tr1_ret, 0, "something wrong in tr1, please check")
# close trainer file
tr0_pipe.close()
tr1_pipe.close()
ps0_pipe.close()
ps1_pipe.close()
ps0.terminate()
ps1.terminate()
shutil.rmtree(gloo_path)
return 0, 0
def check_with_place(self,
model_file,
delta=1e-3,
check_error_log=False,
need_envs={}):
required_envs = {
"PATH": os.getenv("PATH", ""),
"PYTHONPATH": os.getenv("PYTHONPATH", ""),
"LD_LIBRARY_PATH": os.getenv("LD_LIBRARY_PATH", ""),
"FLAGS_rpc_deadline": "5000", # 5sec to fail fast
"http_proxy": ""
}
required_envs.update(need_envs)
if check_error_log:
required_envs["GLOG_v"] = "3"
required_envs["GLOG_logtostderr"] = "1"
tr0_losses, tr1_losses = self._run_cluster(model_file, required_envs)
def runtime_main(test_class):
parser = argparse.ArgumentParser(description='Run Fleet test.')
parser.add_argument(
'--role', type=str, required=True, choices=['pserver', 'trainer'])
parser.add_argument('--endpoints', type=str, required=False, default="")
parser.add_argument(
'--trainer_endpoints', type=str, required=False, default="")
parser.add_argument('--gloo_path', type=str, required=False, default="")
parser.add_argument('--current_id', type=int, required=False, default=0)
parser.add_argument('--trainers', type=int, required=False, default=1)
parser.add_argument('--mode', type=str, required=False, default='geo')
parser.add_argument(
'--geo_sgd_need_push_nums', type=int, required=False, default=2)
parser.add_argument('--reader', type=str, required=False, default='dataset')
args = parser.parse_args()
model = test_class()
role = model.build_role(args)
fleet.init(role)
strategy = model.build_strategy(args)
avg_cost = model.net(args)
model.build_optimizer(avg_cost, strategy)
fleet_util._set_strategy(strategy)
fleet_util._set_role_maker(role)
if args.role == "pserver":
model.run_pserver(args)
else:
if args.reader == "dataset":
model.run_dataset_trainer(args)
else:
model.run_pyreader_trainer(args)
| []
| []
| [
"GRAD_CLIP",
"WITH_COVERAGE",
"PADDLE_DIST_UT_PORT",
"DECAY",
"LD_LIBRARY_PATH",
"Debug",
"dump_fields_path",
"dump_fields",
"dump_param",
"COVERAGE_FILE",
"PATH",
"PYTHONPATH"
]
| [] | ["GRAD_CLIP", "WITH_COVERAGE", "PADDLE_DIST_UT_PORT", "DECAY", "LD_LIBRARY_PATH", "Debug", "dump_fields_path", "dump_fields", "dump_param", "COVERAGE_FILE", "PATH", "PYTHONPATH"] | python | 12 | 0 | |
beautiful-days-at-the-movies/main.go | // https://www.hackerrank.com/challenges/beautiful-days-at-the-movies
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
// Helper function to calculate the absolute value of an integer
func abs(n int32) int32 {
if n >= 0 {
return n
} else {
return -n
}
}
// Complete the beautifulDays function below.
func beautifulDays(i int32, j int32, k int32) int32 {
// Declare and initialize the variables
var sCurrentNumber, sCurrentReversedNumber string
var i32CurrentReversedNumber int32
var i32BeautifulCounter int32 = 0
// Do the loop
for p := i; p <= j; p++ {
sCurrentNumber = strconv.FormatInt(int64(p), 10)
sCurrentReversedNumber = ""
for q := len(sCurrentNumber) - 1; q >= 0; q-- {
sCurrentReversedNumber += string(sCurrentNumber[q])
}
i64CurrentReversedNumber, err := strconv.ParseInt(sCurrentReversedNumber, 10, 64)
checkError(err)
i32CurrentReversedNumber = int32(i64CurrentReversedNumber)
if abs(p - i32CurrentReversedNumber) % k == 0 {
i32BeautifulCounter++
}
}
return i32BeautifulCounter
}
func main() {
reader := bufio.NewReaderSize(os.Stdin, 1024 * 1024)
stdout, err := os.Create(os.Getenv("OUTPUT_PATH"))
checkError(err)
defer stdout.Close()
writer := bufio.NewWriterSize(stdout, 1024 * 1024)
ijk := strings.Split(readLine(reader), " ")
iTemp, err := strconv.ParseInt(ijk[0], 10, 64)
checkError(err)
i := int32(iTemp)
jTemp, err := strconv.ParseInt(ijk[1], 10, 64)
checkError(err)
j := int32(jTemp)
kTemp, err := strconv.ParseInt(ijk[2], 10, 64)
checkError(err)
k := int32(kTemp)
result := beautifulDays(i, j, k)
fmt.Fprintf(writer, "%d\n", result)
writer.Flush()
}
func readLine(reader *bufio.Reader) string {
str, _, err := reader.ReadLine()
if err == io.EOF {
return ""
}
return strings.TrimRight(string(str), "\r\n")
}
func checkError(err error) {
if err != nil {
panic(err)
}
}
| [
"\"OUTPUT_PATH\""
]
| []
| [
"OUTPUT_PATH"
]
| [] | ["OUTPUT_PATH"] | go | 1 | 0 | |
myproject/wsgi.py | """
WSGI config for myproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
application = get_wsgi_application()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
tools/search_by_distance.py | # standard lib
import os
import pdb
import time
import json
import copy
import argparse
import importlib
import os.path as osp
from copy import deepcopy
# 3rd-parth lib
import torch
import torch.distributed as dist
# mm lib
import mmcv
from mmcv import Config
from mmcv.runner import init_dist, get_dist_info, load_state_dict
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from openselfsup import __version__
from openselfsup.apis import set_random_seed
from openselfsup.datasets import build_dataset, build_dataloader
from openselfsup.models import build_model
from openselfsup.utils import collect_env, get_root_logger, traverse_replace
# gaia lib
import gaiavision
from gaiavision import broadcast_object
from gaiavision.model_space import (ModelSpaceManager,
build_sample_rule,
build_model_sampler,
unfold_dict,
fold_dict)
import gaiassl
from gaiassl.datasets import ScaleManipulator, manipulate_dataset
from gaiassl.apis import multi_gpu_test_with_distance,multi_gpu_test_with_dense_distance
DISTANCES = {
'mse': torch.nn.MSELoss,
'kl': torch.nn.KLDivLoss,
'ressl':torch.nn.KLDivLoss
}
def parse_args():
parser = argparse.ArgumentParser(description='Search a model')
parser.add_argument('config', help='train config file path')
parser.add_argument('checkpoint', help='train config file path')
parser.add_argument(
'--dense',
type=bool,
default=False,
help='whether compare dense feature similarity')
parser.add_argument(
'--model_space_path',
type=str,
help='path of file that records model information')
parser.add_argument(
'--work_dir',
type=str,
default=None,
help='the dir to save logs and models')
parser.add_argument(
'--gpus',
type=int,
default=1,
help='number of gpus to use '
'(only applicable to non-distributed training)')
parser.add_argument('--seed', type=int, default=None, help='random seed')
parser.add_argument('--out-name', default='metrics.json', help='output result file name')
parser.add_argument('--metric-tag', default='distance',
help='tag of metric in search process')
parser.add_argument(
'--deterministic',
action='store_true',
help='whether to set deterministic options for CUDNN backend.')
parser.add_argument(
'--launcher',
choices=['none', 'pytorch', 'slurm', 'mpi'],
default='none',
help='job launcher')
parser.add_argument('--local_rank', type=int, default=0)
parser.add_argument('--port', type=int, default=29500,
help='port only works when launcher=="slurm"')
args = parser.parse_args()
if 'LOCAL_RANK' not in os.environ:
os.environ['LOCAL_RANK'] = str(args.local_rank)
metric_dir = os.path.join(args.work_dir, 'search_subnet')
args.metric_dir = metric_dir
return args
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
# set cudnn_benchmark
if cfg.get('cudnn_benchmark', False):
torch.backends.cudnn.benchmark = True
# update configs according to CLI args
if args.work_dir is not None:
cfg.work_dir = args.work_dir
cfg.gpus = args.gpus
# check memcached package exists
if importlib.util.find_spec('mc') is None:
traverse_replace(cfg, 'memcached', False)
# init distributed env first, since logger depends on the dist info.
if args.launcher == 'none':
distributed = False
assert cfg.model.type not in \
['DeepCluster', 'MOCO', 'SimCLR', 'ODC', 'NPID'], \
"{} does not support non-dist training.".format(cfg.model.type)
else:
distributed = True
if args.launcher == 'slurm':
cfg.dist_params['port'] = args.port
init_dist(args.launcher, **cfg.dist_params)
rank, world_size = get_dist_info()
# create work_dir
mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))
os.makedirs(args.metric_dir, exist_ok=True)
save_path = os.path.join(args.metric_dir, args.out_name)
# init the logger before other steps
timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())
log_file = osp.join(cfg.work_dir, 'train_{}.log'.format(timestamp))
logger = get_root_logger(log_file=log_file, log_level=cfg.log_level)
# init the meta dict to record some important information such as
# environment info and seed, which will be logged
meta = dict()
# log env info
env_info_dict = collect_env()
env_info = '\n'.join([('{}: {}'.format(k, v))
for k, v in env_info_dict.items()])
dash_line = '-' * 60 + '\n'
logger.info('Environment info:\n' + dash_line + env_info + '\n' +
dash_line)
meta['env_info'] = env_info
# log some basic info
logger.info('Distributed training: {}'.format(distributed))
logger.info('Config:\n{}'.format(cfg.text))
# load model information, CLI > cfg
if args.model_space_path is not None:
cfg.model_space_path = args.model_space_path
assert cfg.get('model_space_path', None) is not None
logger.info('Model space:\n{}'.format(cfg.model_space_path))
# set random seeds
if args.seed is not None:
logger.info('Set random seed to {}, deterministic: {}'.format(
args.seed, args.deterministic))
set_random_seed(args.seed, deterministic=args.deterministic)
cfg.seed = args.seed
meta['seed'] = args.seed
# prepare model and pretrained weights
model = build_model(cfg.model)
ckpt = torch.load(args.checkpoint)['state_dict']
load_state_dict(model, ckpt)
model = MMDistributedDataParallel(
model.cuda(),
device_ids=[torch.cuda.current_device()],
broadcast_buffers=False)
#pdb.set_trace()
distance = cfg.get('distance', 'cosine')
# collect model of interests
sampled_model_metas = []
model_space = ModelSpaceManager.load(cfg.model_space_path)
rule = build_sample_rule(cfg.model_sampling_rules)
sub_model_space = model_space.ms_manager.apply_rule(rule)
model_metas = sub_model_space.ms_manager.pack()
dist.barrier()
if rank == 0:
print("Please notice, the encoder_k always keeps largest architecture")
for each in model_metas:
each['arch'].pop('encoder_k')
#pdb.set_trace()
# set up distance
model_metas_no_id = copy.deepcopy(model_metas)
for each in model_metas_no_id:
each.pop('index')
new_model_metas_no_id = []
new_model_metas = []
for each_no_id, each in zip(model_metas_no_id, model_metas):
if each_no_id not in new_model_metas_no_id:
new_model_metas.append(each)
new_model_metas_no_id.append(each_no_id)
model_metas = new_model_metas
#pdb.set_trace()
for i, model_meta in enumerate(model_metas):
# sync model_meta between ranks
model_meta = broadcast_object(model_meta)
dataset = build_dataset(cfg.data.train)
teacher_data_loader = build_dataloader(
dataset,
imgs_per_gpu=cfg.data.imgs_per_gpu,
workers_per_gpu=cfg.data.workers_per_gpu,
dist=True,
shuffle=False)
student_data_loader = build_dataloader(
dataset,
imgs_per_gpu=cfg.data.imgs_per_gpu,
workers_per_gpu=cfg.data.workers_per_gpu,
dist=True,
shuffle=False)
#pdb.set_trace()
# TODO:run test
print("start running")
if args.dense:
print("dense")
outputs = multi_gpu_test_with_dense_distance(model, model_meta, teacher_data_loader, student_data_loader, distance, rank)
else:
print("global")
outputs = multi_gpu_test_with_distance(model, model_meta, teacher_data_loader, student_data_loader, distance, rank)
print("End")
#pdb.set_trace()
result_model_meta = deepcopy(model_meta)
metrics = {}
if rank == 0:
# TODO: replace the ugly workaround
koi = list(outputs.keys())
for name in koi:
metrics[name] = outputs[name]
metric_meta = result_model_meta.setdefault('metric', {})
metric_meta[args.metric_tag] = metrics
result_model_meta['metric'] = metric_meta
sampled_model_metas.append(result_model_meta)
logger.info('-- model meta:')
logger.info(json.dumps(sampled_model_metas[-1], indent=4))
dist.barrier()
if rank == 0:
sub_model_space = ModelSpaceManager.load(sampled_model_metas)
sub_model_space.ms_manager.dump(save_path)
dist.barrier()
if rank == 0:
sub_model_space = ModelSpaceManager.load(sampled_model_metas)
sub_model_space.ms_manager.dump(save_path)
if __name__ == '__main__':
main()
| []
| []
| [
"LOCAL_RANK"
]
| [] | ["LOCAL_RANK"] | python | 1 | 0 | |
theproject/manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "theproject.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
| []
| []
| []
| [] | [] | python | 0 | 0 | |
backend/TipEx/celery.py | # coding: utf-8
from __future__ import absolute_import
import os
from django.apps import apps
from celery import Celery
from .celerybeat_schedule import CELERYBEAT_SCHEDULE
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "TipEx.settings.local")
app = Celery("TipEx_tasks")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()])
app.conf.update(CELERYBEAT_SCHEDULE=CELERYBEAT_SCHEDULE)
| []
| []
| []
| [] | [] | python | 0 | 0 | |
main.go | package main
import (
"context"
"log"
"net/http"
"os"
"github.com/biblika/biblika-api/api"
"github.com/biblika/biblika-api/proto/book"
"github.com/biblika/biblika-api/proto/passage"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
)
func main() {
r := runtime.NewServeMux()
err := book.RegisterBookServiceHandlerServer(context.Background(), r, &api.BookService{})
if err != nil {
log.Fatalf("failed to register book service: %v", err)
}
err = passage.RegisterPassageServiceHandlerServer(context.Background(), r, &api.PassageService{})
if err != nil {
log.Fatalf("failed to register passage service: %v", err)
}
port := os.Getenv("PORT")
if len(port) < 1 {
port = ":8080"
}
log.Fatal(http.ListenAndServe(port, r))
}
| [
"\"PORT\""
]
| []
| [
"PORT"
]
| [] | ["PORT"] | go | 1 | 0 | |
config/wsgi.py | """
WSGI config for the Church IMS project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production")
application = get_wsgi_application()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
small_projects/discord_auth_ex/discord_auth_ex/wsgi.py | """
WSGI config for discord_auth_ex project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'discord_auth_ex.settings')
application = get_wsgi_application()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
workflow/controller/controller.go | package controller
import (
"context"
"encoding/json"
"fmt"
"os"
"strconv"
"syscall"
"time"
"github.com/argoproj/pkg/errors"
syncpkg "github.com/argoproj/pkg/sync"
log "github.com/sirupsen/logrus"
"golang.org/x/time/rate"
apiv1 "k8s.io/api/core/v1"
apierr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/types"
runtimeutil "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
v1 "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/leaderelection"
"k8s.io/client-go/tools/leaderelection/resourcelock"
apiwatch "k8s.io/client-go/tools/watch"
"k8s.io/client-go/util/workqueue"
"upper.io/db.v3/lib/sqlbuilder"
"github.com/argoproj/argo-workflows/v3"
"github.com/argoproj/argo-workflows/v3/config"
argoErr "github.com/argoproj/argo-workflows/v3/errors"
"github.com/argoproj/argo-workflows/v3/persist/sqldb"
wfv1 "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
wfclientset "github.com/argoproj/argo-workflows/v3/pkg/client/clientset/versioned"
"github.com/argoproj/argo-workflows/v3/pkg/client/informers/externalversions"
wfextvv1alpha1 "github.com/argoproj/argo-workflows/v3/pkg/client/informers/externalversions/workflow/v1alpha1"
authutil "github.com/argoproj/argo-workflows/v3/util/auth"
"github.com/argoproj/argo-workflows/v3/util/diff"
"github.com/argoproj/argo-workflows/v3/util/env"
errorsutil "github.com/argoproj/argo-workflows/v3/util/errors"
"github.com/argoproj/argo-workflows/v3/workflow/artifactrepositories"
"github.com/argoproj/argo-workflows/v3/workflow/common"
controllercache "github.com/argoproj/argo-workflows/v3/workflow/controller/cache"
"github.com/argoproj/argo-workflows/v3/workflow/controller/estimation"
"github.com/argoproj/argo-workflows/v3/workflow/controller/indexes"
"github.com/argoproj/argo-workflows/v3/workflow/controller/informer"
"github.com/argoproj/argo-workflows/v3/workflow/controller/pod"
"github.com/argoproj/argo-workflows/v3/workflow/cron"
"github.com/argoproj/argo-workflows/v3/workflow/events"
"github.com/argoproj/argo-workflows/v3/workflow/hydrator"
"github.com/argoproj/argo-workflows/v3/workflow/metrics"
"github.com/argoproj/argo-workflows/v3/workflow/signal"
"github.com/argoproj/argo-workflows/v3/workflow/sync"
"github.com/argoproj/argo-workflows/v3/workflow/ttlcontroller"
"github.com/argoproj/argo-workflows/v3/workflow/util"
)
// WorkflowController is the controller for workflow resources
type WorkflowController struct {
// namespace of the workflow controller
namespace string
managedNamespace string
configController config.Controller
// Config is the workflow controller's configuration
Config config.Config
// get the artifact repository
artifactRepositories artifactrepositories.Interface
// cliExecutorImage is the executor image as specified from the command line
cliExecutorImage string
// cliExecutorImagePullPolicy is the executor imagePullPolicy as specified from the command line
cliExecutorImagePullPolicy string
containerRuntimeExecutor string
// restConfig is used by controller to send a SIGUSR1 to the wait sidecar using remotecommand.NewSPDYExecutor().
restConfig *rest.Config
kubeclientset kubernetes.Interface
rateLimiter *rate.Limiter
dynamicInterface dynamic.Interface
wfclientset wfclientset.Interface
// datastructures to support the processing of workflows and workflow pods
wfInformer cache.SharedIndexInformer
wftmplInformer wfextvv1alpha1.WorkflowTemplateInformer
cwftmplInformer wfextvv1alpha1.ClusterWorkflowTemplateInformer
podInformer cache.SharedIndexInformer
configMapInformer cache.SharedIndexInformer
wfQueue workqueue.RateLimitingInterface
podQueue workqueue.RateLimitingInterface
podCleanupQueue workqueue.RateLimitingInterface // pods to be deleted or labelled depend on GC strategy
throttler sync.Throttler
workflowKeyLock syncpkg.KeyLock // used to lock workflows for exclusive modification or access
session sqlbuilder.Database
offloadNodeStatusRepo sqldb.OffloadNodeStatusRepo
hydrator hydrator.Interface
wfArchive sqldb.WorkflowArchive
estimatorFactory estimation.EstimatorFactory
syncManager *sync.Manager
metrics *metrics.Metrics
eventRecorderManager events.EventRecorderManager
archiveLabelSelector labels.Selector
cacheFactory controllercache.Factory
wfTaskSetInformer wfextvv1alpha1.WorkflowTaskSetInformer
}
const (
workflowResyncPeriod = 20 * time.Minute
workflowTemplateResyncPeriod = 20 * time.Minute
podResyncPeriod = 30 * time.Minute
clusterWorkflowTemplateResyncPeriod = 20 * time.Minute
workflowExistenceCheckPeriod = 1 * time.Minute
workflowTaskSetResyncPeriod = 20 * time.Minute
)
// NewWorkflowController instantiates a new WorkflowController
func NewWorkflowController(ctx context.Context, restConfig *rest.Config, kubeclientset kubernetes.Interface, wfclientset wfclientset.Interface, namespace, managedNamespace, executorImage, executorImagePullPolicy, containerRuntimeExecutor, configMap string) (*WorkflowController, error) {
dynamicInterface, err := dynamic.NewForConfig(restConfig)
if err != nil {
return nil, err
}
wfc := WorkflowController{
restConfig: restConfig,
kubeclientset: kubeclientset,
dynamicInterface: dynamicInterface,
wfclientset: wfclientset,
namespace: namespace,
managedNamespace: managedNamespace,
cliExecutorImage: executorImage,
cliExecutorImagePullPolicy: executorImagePullPolicy,
containerRuntimeExecutor: containerRuntimeExecutor,
configController: config.NewController(namespace, configMap, kubeclientset, config.EmptyConfigFunc),
workflowKeyLock: syncpkg.NewKeyLock(),
cacheFactory: controllercache.NewCacheFactory(kubeclientset, namespace),
eventRecorderManager: events.NewEventRecorderManager(kubeclientset),
}
wfc.UpdateConfig(ctx)
wfc.metrics = metrics.New(wfc.getMetricsServerConfig())
workqueue.SetProvider(wfc.metrics) // must execute SetProvider before we created the queues
wfc.wfQueue = wfc.metrics.RateLimiterWithBusyWorkers(&fixedItemIntervalRateLimiter{}, "workflow_queue")
wfc.throttler = wfc.newThrottler()
wfc.podQueue = wfc.metrics.RateLimiterWithBusyWorkers(workqueue.DefaultControllerRateLimiter(), "pod_queue")
wfc.podCleanupQueue = wfc.metrics.RateLimiterWithBusyWorkers(workqueue.DefaultControllerRateLimiter(), "pod_cleanup_queue")
return &wfc, nil
}
func (wfc *WorkflowController) newThrottler() sync.Throttler {
f := func(key string) { wfc.wfQueue.AddRateLimited(key) }
return sync.ChainThrottler{
sync.NewThrottler(wfc.Config.Parallelism, sync.SingleBucket, f),
sync.NewThrottler(wfc.Config.NamespaceParallelism, sync.NamespaceBucket, f),
}
}
// RunTTLController runs the workflow TTL controller
func (wfc *WorkflowController) runTTLController(ctx context.Context, workflowTTLWorkers int) {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
ttlCtrl := ttlcontroller.NewController(wfc.wfclientset, wfc.wfInformer, wfc.metrics)
err := ttlCtrl.Run(ctx.Done(), workflowTTLWorkers)
if err != nil {
panic(err)
}
}
func (wfc *WorkflowController) runCronController(ctx context.Context) {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
cronController := cron.NewCronController(wfc.wfclientset, wfc.dynamicInterface, wfc.namespace, wfc.GetManagedNamespace(), wfc.Config.InstanceID, wfc.metrics, wfc.eventRecorderManager)
cronController.Run(ctx)
}
var indexers = cache.Indexers{
indexes.ClusterWorkflowTemplateIndex: indexes.MetaNamespaceLabelIndexFunc(common.LabelKeyClusterWorkflowTemplate),
indexes.CronWorkflowIndex: indexes.MetaNamespaceLabelIndexFunc(common.LabelKeyCronWorkflow),
indexes.WorkflowTemplateIndex: indexes.MetaNamespaceLabelIndexFunc(common.LabelKeyWorkflowTemplate),
indexes.SemaphoreConfigIndexName: indexes.WorkflowSemaphoreKeysIndexFunc(),
indexes.WorkflowPhaseIndex: indexes.MetaWorkflowPhaseIndexFunc(),
indexes.ConditionsIndex: indexes.ConditionsIndexFunc,
indexes.UIDIndex: indexes.MetaUIDFunc,
}
// Run starts an Workflow resource controller
func (wfc *WorkflowController) Run(ctx context.Context, wfWorkers, workflowTTLWorkers, podWorkers, podCleanupWorkers int) {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
ctx, cancel := context.WithCancel(ctx)
defer cancel()
defer wfc.wfQueue.ShutDown()
defer wfc.podQueue.ShutDown()
defer wfc.podCleanupQueue.ShutDown()
log.WithField("version", argo.GetVersion().Version).Info("Starting Workflow Controller")
log.Infof("Workers: workflow: %d, pod: %d, pod cleanup: %d", wfWorkers, podWorkers, podCleanupWorkers)
wfc.wfInformer = util.NewWorkflowInformer(wfc.dynamicInterface, wfc.GetManagedNamespace(), workflowResyncPeriod, wfc.tweakListOptions, indexers)
wfc.wftmplInformer = informer.NewTolerantWorkflowTemplateInformer(wfc.dynamicInterface, workflowTemplateResyncPeriod, wfc.managedNamespace)
wfc.wfTaskSetInformer = wfc.newWorkflowTaskSetInformer()
wfc.addWorkflowInformerHandlers(ctx)
wfc.podInformer = wfc.newPodInformer(ctx)
wfc.updateEstimatorFactory()
wfc.configMapInformer = wfc.newConfigMapInformer()
// Create Synchronization Manager
wfc.createSynchronizationManager(ctx)
// init managers: throttler and SynchronizationManager
if err := wfc.initManagers(ctx); err != nil {
log.Fatal(err)
}
go wfc.runConfigMapWatcher(ctx.Done())
go wfc.configController.Run(ctx.Done(), wfc.updateConfig)
go wfc.wfInformer.Run(ctx.Done())
go wfc.wftmplInformer.Informer().Run(ctx.Done())
go wfc.podInformer.Run(ctx.Done())
go wfc.configMapInformer.Run(ctx.Done())
go wfc.wfTaskSetInformer.Informer().Run(ctx.Done())
// Wait for all involved caches to be synced, before processing items from the queue is started
if !cache.WaitForCacheSync(ctx.Done(), wfc.wfInformer.HasSynced, wfc.wftmplInformer.Informer().HasSynced, wfc.podInformer.HasSynced) {
log.Fatal("Timed out waiting for caches to sync")
}
wfc.createClusterWorkflowTemplateInformer(ctx)
// Start the metrics server
go wfc.metrics.RunServer(ctx)
leaderElectionOff := os.Getenv("LEADER_ELECTION_DISABLE")
if leaderElectionOff == "true" {
log.Info("Leader election is turned off. Running in single-instance mode")
logCtx := log.WithField("id", "single-instance")
go wfc.startLeading(ctx, logCtx, podCleanupWorkers, workflowTTLWorkers, wfWorkers, podWorkers)
} else {
nodeID, ok := os.LookupEnv("LEADER_ELECTION_IDENTITY")
if !ok {
log.Fatal("LEADER_ELECTION_IDENTITY must be set so that the workflow controllers can elect a leader")
}
logCtx := log.WithField("id", nodeID)
leaderName := "workflow-controller"
if wfc.Config.InstanceID != "" {
leaderName = fmt.Sprintf("%s-%s", leaderName, wfc.Config.InstanceID)
}
go leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
Lock: &resourcelock.LeaseLock{
LeaseMeta: metav1.ObjectMeta{Name: leaderName, Namespace: wfc.namespace}, Client: wfc.kubeclientset.CoordinationV1(),
LockConfig: resourcelock.ResourceLockConfig{Identity: nodeID, EventRecorder: wfc.eventRecorderManager.Get(wfc.namespace)},
},
ReleaseOnCancel: true,
LeaseDuration: env.LookupEnvDurationOr("LEADER_ELECTION_LEASE_DURATION", 15*time.Second),
RenewDeadline: env.LookupEnvDurationOr("LEADER_ELECTION_RENEW_DEADLINE", 10*time.Second),
RetryPeriod: env.LookupEnvDurationOr("LEADER_ELECTION_RETRY_PERIOD", 5*time.Second),
Callbacks: leaderelection.LeaderCallbacks{
OnStartedLeading: func(ctx context.Context) {
wfc.startLeading(ctx, logCtx, podCleanupWorkers, workflowTTLWorkers, wfWorkers, podWorkers)
},
OnStoppedLeading: func() {
logCtx.Info("stopped leading")
cancel()
},
OnNewLeader: func(identity string) {
logCtx.WithField("leader", identity).Info("new leader")
},
},
})
}
<-ctx.Done()
}
func (wfc *WorkflowController) startLeading(ctx context.Context, logCtx *log.Entry, podCleanupWorkers int, workflowTTLWorkers int, wfWorkers int, podWorkers int) {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
logCtx.Info("started leading")
for i := 0; i < podCleanupWorkers; i++ {
go wait.UntilWithContext(ctx, wfc.runPodCleanup, time.Second)
}
go wfc.workflowGarbageCollector(ctx.Done())
go wfc.archivedWorkflowGarbageCollector(ctx.Done())
go wfc.runTTLController(ctx, workflowTTLWorkers)
go wfc.runCronController(ctx)
go wait.Until(wfc.syncWorkflowPhaseMetrics, 15*time.Second, ctx.Done())
go wait.Until(wfc.syncPodPhaseMetrics, 15*time.Second, ctx.Done())
go wait.Until(wfc.syncManager.CheckWorkflowExistence, workflowExistenceCheckPeriod, ctx.Done())
for i := 0; i < wfWorkers; i++ {
go wait.Until(wfc.runWorker, time.Second, ctx.Done())
}
for i := 0; i < podWorkers; i++ {
go wait.Until(wfc.podWorker, time.Second, ctx.Done())
}
}
func (wfc *WorkflowController) waitForCacheSync(ctx context.Context) {
// Wait for all involved caches to be synced, before processing items from the queue is started
if !cache.WaitForCacheSync(ctx.Done(), wfc.wfInformer.HasSynced, wfc.wftmplInformer.Informer().HasSynced, wfc.podInformer.HasSynced) {
panic("Timed out waiting for caches to sync")
}
if wfc.cwftmplInformer != nil {
if !cache.WaitForCacheSync(ctx.Done(), wfc.cwftmplInformer.Informer().HasSynced) {
panic("Timed out waiting for caches to sync")
}
}
}
// Create and the Synchronization Manager
func (wfc *WorkflowController) createSynchronizationManager(ctx context.Context) {
getSyncLimit := func(lockKey string) (int, error) {
lockName, err := sync.DecodeLockName(lockKey)
if err != nil {
return 0, err
}
configMap, err := wfc.kubeclientset.CoreV1().ConfigMaps(lockName.Namespace).Get(ctx, lockName.ResourceName, metav1.GetOptions{})
if err != nil {
return 0, err
}
value, found := configMap.Data[lockName.Key]
if !found {
return 0, argoErr.New(argoErr.CodeBadRequest, fmt.Sprintf("Sync configuration key '%s' not found in ConfigMap", lockName.Key))
}
return strconv.Atoi(value)
}
nextWorkflow := func(key string) {
wfc.wfQueue.AddRateLimited(key)
}
isWFDeleted := func(key string) bool {
_, exists, err := wfc.wfInformer.GetIndexer().GetByKey(key)
if err != nil {
log.WithFields(log.Fields{"key": key, "error": err}).Error("Failed to get workflow from informer")
return false
}
return exists
}
wfc.syncManager = sync.NewLockManager(getSyncLimit, nextWorkflow, isWFDeleted)
}
// list all running workflows to initialize throttler and syncManager
func (wfc *WorkflowController) initManagers(ctx context.Context) error {
labelSelector := labels.NewSelector().Add(util.InstanceIDRequirement(wfc.Config.InstanceID))
req, _ := labels.NewRequirement(common.LabelKeyPhase, selection.Equals, []string{string(wfv1.WorkflowRunning)})
if req != nil {
labelSelector = labelSelector.Add(*req)
}
listOpts := metav1.ListOptions{LabelSelector: labelSelector.String()}
wfList, err := wfc.wfclientset.ArgoprojV1alpha1().Workflows(wfc.namespace).List(ctx, listOpts)
if err != nil {
return err
}
if err := wfc.throttler.Init(wfList.Items); err != nil {
return err
}
wfc.syncManager.Initialize(wfList.Items)
return nil
}
func (wfc *WorkflowController) runConfigMapWatcher(stopCh <-chan struct{}) {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
ctx := context.Background()
retryWatcher, err := apiwatch.NewRetryWatcher("1", &cache.ListWatch{
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
return wfc.kubeclientset.CoreV1().ConfigMaps(wfc.managedNamespace).Watch(ctx, metav1.ListOptions{})
},
})
if err != nil {
panic(err)
}
defer retryWatcher.Stop()
for {
select {
case event := <-retryWatcher.ResultChan():
cm, ok := event.Object.(*apiv1.ConfigMap)
if !ok {
log.Errorf("invalid config map object received in config watcher. Ignored processing")
continue
}
log.Debugf("received config map %s/%s update", cm.Namespace, cm.Name)
wfc.notifySemaphoreConfigUpdate(cm)
case <-stopCh:
return
}
}
}
// notifySemaphoreConfigUpdate will notify semaphore config update to pending workflows
func (wfc *WorkflowController) notifySemaphoreConfigUpdate(cm *apiv1.ConfigMap) {
wfs, err := wfc.wfInformer.GetIndexer().ByIndex(indexes.SemaphoreConfigIndexName, fmt.Sprintf("%s/%s", cm.Namespace, cm.Name))
if err != nil {
log.Errorf("failed get the workflow from informer. %v", err)
}
for _, obj := range wfs {
un, ok := obj.(*unstructured.Unstructured)
if !ok {
log.Warnf("received object from indexer %s is not an unstructured", indexes.SemaphoreConfigIndexName)
continue
}
wfc.wfQueue.AddRateLimited(fmt.Sprintf("%s/%s", un.GetNamespace(), un.GetName()))
}
}
// Check if the controller has RBAC access to ClusterWorkflowTemplates
func (wfc *WorkflowController) createClusterWorkflowTemplateInformer(ctx context.Context) {
cwftGetAllowed, err := authutil.CanI(ctx, wfc.kubeclientset, "get", "clusterworkflowtemplates", wfc.namespace, "")
errors.CheckError(err)
cwftListAllowed, err := authutil.CanI(ctx, wfc.kubeclientset, "list", "clusterworkflowtemplates", wfc.namespace, "")
errors.CheckError(err)
cwftWatchAllowed, err := authutil.CanI(ctx, wfc.kubeclientset, "watch", "clusterworkflowtemplates", wfc.namespace, "")
errors.CheckError(err)
if cwftGetAllowed && cwftListAllowed && cwftWatchAllowed {
wfc.cwftmplInformer = informer.NewTolerantClusterWorkflowTemplateInformer(wfc.dynamicInterface, clusterWorkflowTemplateResyncPeriod)
go wfc.cwftmplInformer.Informer().Run(ctx.Done())
} else {
log.Warnf("Controller doesn't have RBAC access for ClusterWorkflowTemplates")
}
}
func (wfc *WorkflowController) UpdateConfig(ctx context.Context) {
config, err := wfc.configController.Get(ctx)
if err != nil {
log.Fatalf("Failed to register watch for controller config map: %v", err)
}
err = wfc.updateConfig(config)
if err != nil {
log.Fatalf("Failed to update config: %v", err)
}
}
func (wfc *WorkflowController) queuePodForCleanup(namespace string, podName string, action podCleanupAction) {
wfc.podCleanupQueue.AddRateLimited(newPodCleanupKey(namespace, podName, action))
}
func (wfc *WorkflowController) queuePodForCleanupAfter(namespace string, podName string, action podCleanupAction, duration time.Duration) {
wfc.podCleanupQueue.AddAfter(newPodCleanupKey(namespace, podName, action), duration)
}
func (wfc *WorkflowController) runPodCleanup(ctx context.Context) {
for wfc.processNextPodCleanupItem(ctx) {
}
}
// all pods will ultimately be cleaned up by either deleting them, or labelling them
func (wfc *WorkflowController) processNextPodCleanupItem(ctx context.Context) bool {
key, quit := wfc.podCleanupQueue.Get()
if quit {
return false
}
defer wfc.podCleanupQueue.Done(key)
namespace, podName, action := parsePodCleanupKey(key.(podCleanupKey))
logCtx := log.WithFields(log.Fields{"key": key, "action": action})
logCtx.Info("cleaning up pod")
err := func() error {
pods := wfc.kubeclientset.CoreV1().Pods(namespace)
switch action {
case shutdownPod:
// to shutdown a pod, we signal the wait container to terminate, the wait container in turn will
// kill the main container (using whatever mechanism the executor uses), and will then exit itself
// once the main container exited
pod, err := wfc.getPod(namespace, podName)
if pod == nil || err != nil {
return err
}
for _, c := range pod.Spec.Containers {
if c.Name == common.WaitContainerName {
if err := signal.SignalContainer(wfc.restConfig, pod, common.WaitContainerName, syscall.SIGTERM); err != nil {
return err
}
return nil // done
}
}
// no wait container found
fallthrough
case terminateContainers:
if terminationGracePeriod, err := wfc.signalContainers(namespace, podName, syscall.SIGTERM); err != nil {
return err
} else if terminationGracePeriod > 0 {
wfc.queuePodForCleanupAfter(namespace, podName, killContainers, terminationGracePeriod)
}
case killContainers:
if _, err := wfc.signalContainers(namespace, podName, syscall.SIGKILL); err != nil {
return err
}
case labelPodCompleted:
_, err := pods.Patch(
ctx,
podName,
types.MergePatchType,
[]byte(`{"metadata": {"labels": {"workflows.argoproj.io/completed": "true"}}}`),
metav1.PatchOptions{},
)
if err != nil {
return err
}
case deletePod:
propagation := metav1.DeletePropagationBackground
err := pods.Delete(ctx, podName, metav1.DeleteOptions{
PropagationPolicy: &propagation,
GracePeriodSeconds: wfc.Config.PodGCGracePeriodSeconds,
})
if err != nil && !apierr.IsNotFound(err) {
return err
}
}
return nil
}()
if err != nil {
logCtx.WithError(err).Warn("failed to clean-up pod")
if errorsutil.IsTransientErr(err) {
wfc.podCleanupQueue.AddRateLimited(key)
}
}
return true
}
func (wfc *WorkflowController) getPod(namespace string, podName string) (*apiv1.Pod, error) {
obj, exists, err := wfc.podInformer.GetStore().GetByKey(namespace + "/" + podName)
if err != nil {
return nil, err
}
if !exists {
return nil, nil
}
pod, ok := obj.(*apiv1.Pod)
if !ok {
return nil, fmt.Errorf("object is not a pod")
}
return pod, nil
}
func (wfc *WorkflowController) signalContainers(namespace string, podName string, sig syscall.Signal) (time.Duration, error) {
pod, err := wfc.getPod(namespace, podName)
if pod == nil || err != nil {
return 0, err
}
for _, c := range pod.Status.ContainerStatuses {
if c.Name == common.WaitContainerName || c.State.Terminated != nil {
continue
}
if err := signal.SignalContainer(wfc.restConfig, pod, c.Name, sig); err != nil {
return 0, err
}
}
if pod.Spec.TerminationGracePeriodSeconds == nil {
return 30 * time.Second, nil
}
return time.Duration(*pod.Spec.TerminationGracePeriodSeconds) * time.Second, nil
}
func (wfc *WorkflowController) workflowGarbageCollector(stopCh <-chan struct{}) {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
periodicity := env.LookupEnvDurationOr("WORKFLOW_GC_PERIOD", 5*time.Minute)
log.Infof("Performing periodic GC every %v", periodicity)
ticker := time.NewTicker(periodicity)
for {
select {
case <-stopCh:
ticker.Stop()
return
case <-ticker.C:
if wfc.offloadNodeStatusRepo.IsEnabled() {
log.Info("Performing periodic workflow GC")
oldRecords, err := wfc.offloadNodeStatusRepo.ListOldOffloads(wfc.GetManagedNamespace())
if err != nil {
log.WithField("err", err).Error("Failed to list old offloaded nodes")
continue
}
log.WithField("len_wfs", len(oldRecords)).Info("Deleting old offloads that are not live")
for uid, versions := range oldRecords {
if err := wfc.deleteOffloadedNodesForWorkflow(uid, versions); err != nil {
log.WithError(err).WithField("uid", uid).Error("Failed to delete old offloaded nodes")
}
}
log.Info("Workflow GC finished")
}
}
}
}
func (wfc *WorkflowController) deleteOffloadedNodesForWorkflow(uid string, versions []string) error {
workflows, err := wfc.wfInformer.GetIndexer().ByIndex(indexes.UIDIndex, uid)
if err != nil {
return err
}
var wf *wfv1.Workflow
switch l := len(workflows); l {
case 0:
log.WithField("uid", uid).Info("Workflow missing, probably deleted")
case 1:
un := workflows[0].(*unstructured.Unstructured)
wf, err = util.FromUnstructured(un)
if err != nil {
return err
}
key := wf.ObjectMeta.Namespace + "/" + wf.ObjectMeta.Name
wfc.workflowKeyLock.Lock(key)
defer wfc.workflowKeyLock.Unlock(key)
// workflow might still be hydrated
if wfc.hydrator.IsHydrated(wf) {
log.WithField("uid", wf.UID).Info("Hydrated workflow encountered")
err = wfc.hydrator.Dehydrate(wf)
if err != nil {
return err
}
}
default:
return fmt.Errorf("expected no more than 1 workflow, got %d", l)
}
for _, version := range versions {
// skip delete if offload is live
if wf != nil && wf.Status.OffloadNodeStatusVersion == version {
continue
}
if err := wfc.offloadNodeStatusRepo.Delete(uid, version); err != nil {
return err
}
}
return nil
}
func (wfc *WorkflowController) archivedWorkflowGarbageCollector(stopCh <-chan struct{}) {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
periodicity := env.LookupEnvDurationOr("ARCHIVED_WORKFLOW_GC_PERIOD", 24*time.Hour)
if wfc.Config.Persistence == nil {
log.Info("Persistence disabled - so archived workflow GC disabled - you must restart the controller if you enable this")
return
}
if !wfc.Config.Persistence.Archive {
log.Info("Archive disabled - so archived workflow GC disabled - you must restart the controller if you enable this")
return
}
ttl := wfc.Config.Persistence.ArchiveTTL
if ttl == config.TTL(0) {
log.Info("Archived workflows TTL zero - so archived workflow GC disabled - you must restart the controller if you enable this")
return
}
log.WithFields(log.Fields{"ttl": ttl, "periodicity": periodicity}).Info("Performing archived workflow GC")
ticker := time.NewTicker(periodicity)
defer ticker.Stop()
for {
select {
case <-stopCh:
return
case <-ticker.C:
log.Info("Performing archived workflow GC")
err := wfc.wfArchive.DeleteExpiredWorkflows(time.Duration(ttl))
if err != nil {
log.WithField("err", err).Error("Failed to delete archived workflows")
}
}
}
}
func (wfc *WorkflowController) runWorker() {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
ctx := context.Background()
for wfc.processNextItem(ctx) {
}
}
// processNextItem is the worker logic for handling workflow updates
func (wfc *WorkflowController) processNextItem(ctx context.Context) bool {
key, quit := wfc.wfQueue.Get()
if quit {
return false
}
defer wfc.wfQueue.Done(key)
obj, exists, err := wfc.wfInformer.GetIndexer().GetByKey(key.(string))
if err != nil {
log.WithFields(log.Fields{"key": key, "error": err}).Error("Failed to get workflow from informer")
return true
}
if !exists {
// This happens after a workflow was labeled with completed=true
// or was deleted, but the work queue still had an entry for it.
return true
}
wfc.workflowKeyLock.Lock(key.(string))
defer wfc.workflowKeyLock.Unlock(key.(string))
// The workflow informer receives unstructured objects to deal with the possibility of invalid
// workflow manifests that are unable to unmarshal to workflow objects
un, ok := obj.(*unstructured.Unstructured)
if !ok {
log.WithFields(log.Fields{"key": key}).Warn("Index is not an unstructured")
return true
}
wf, err := util.FromUnstructured(un)
if err != nil {
log.WithFields(log.Fields{"key": key, "error": err}).Warn("Failed to unmarshal key to workflow object")
woc := newWorkflowOperationCtx(wf, wfc)
woc.markWorkflowFailed(ctx, fmt.Sprintf("cannot unmarshall spec: %s", err.Error()))
woc.persistUpdates(ctx)
return true
}
if wf.Labels[common.LabelKeyCompleted] == "true" {
// can get here if we already added the completed=true label,
// but we are still draining the controller's workflow workqueue
return true
}
// this will ensure we process every incomplete workflow once every 20m
wfc.wfQueue.AddAfter(key, workflowResyncPeriod)
woc := newWorkflowOperationCtx(wf, wfc)
if !wfc.throttler.Admit(key.(string)) {
log.WithField("key", key).Info("Workflow processing has been postponed due to max parallelism limit")
if woc.wf.Status.Phase == wfv1.WorkflowUnknown {
woc.markWorkflowPhase(ctx, wfv1.WorkflowPending, "Workflow processing has been postponed because too many workflows are already running")
woc.persistUpdates(ctx)
}
return true
}
// make sure this is removed from the throttler is complete
defer func() {
// must be done with woc
if woc.wf.Labels[common.LabelKeyCompleted] == "true" {
wfc.throttler.Remove(key.(string))
}
}()
err = wfc.hydrator.Hydrate(woc.wf)
if err != nil {
woc.log.Errorf("hydration failed: %v", err)
woc.markWorkflowError(ctx, err)
woc.persistUpdates(ctx)
return true
}
startTime := time.Now()
woc.operate(ctx)
wfc.metrics.OperationCompleted(time.Since(startTime).Seconds())
if woc.wf.Status.Fulfilled() {
err := woc.completeTaskSet(ctx)
if err != nil {
log.WithError(err).Warn("error to complete the taskset")
}
}
// TODO: operate should return error if it was unable to operate properly
// so we can requeue the work for a later time
// See: https://github.com/kubernetes/client-go/blob/master/examples/workqueue/main.go
// c.handleErr(err, key)
return true
}
func (wfc *WorkflowController) podWorker() {
for wfc.processNextPodItem() {
}
}
// processNextPodItem is the worker logic for handling pod updates.
// For pods updates, this simply means to "wake up" the workflow by
// adding the corresponding workflow key into the workflow workqueue.
func (wfc *WorkflowController) processNextPodItem() bool {
key, quit := wfc.podQueue.Get()
if quit {
return false
}
defer wfc.podQueue.Done(key)
obj, exists, err := wfc.podInformer.GetIndexer().GetByKey(key.(string))
if err != nil {
log.WithFields(log.Fields{"key": key, "error": err}).Error("Failed to get pod from informer index")
return true
}
if !exists {
// we can get here if pod was queued into the pod workqueue,
// but it was either deleted or labeled completed by the time
// we dequeued it.
return true
}
err = wfc.enqueueWfFromPodLabel(obj)
if err != nil {
log.WithError(err).Warnf("Failed to enqueue the workflow for %s", key)
}
return true
}
// enqueueWfFromPodLabel will extract the workflow name from pod label and
// enqueue workflow for processing
func (wfc *WorkflowController) enqueueWfFromPodLabel(obj interface{}) error {
pod, ok := obj.(*apiv1.Pod)
if !ok {
return fmt.Errorf("Key in index is not a pod")
}
if pod.Labels == nil {
return fmt.Errorf("Pod did not have labels")
}
workflowName, ok := pod.Labels[common.LabelKeyWorkflow]
if !ok {
// Ignore pods unrelated to workflow (this shouldn't happen unless the watch is setup incorrectly)
return fmt.Errorf("Watch returned pod unrelated to any workflow")
}
wfc.wfQueue.AddRateLimited(pod.ObjectMeta.Namespace + "/" + workflowName)
return nil
}
func (wfc *WorkflowController) tweakListOptions(options *metav1.ListOptions) {
labelSelector := labels.NewSelector().
Add(util.InstanceIDRequirement(wfc.Config.InstanceID))
options.LabelSelector = labelSelector.String()
}
func getWfPriority(obj interface{}) (int32, time.Time) {
un, ok := obj.(*unstructured.Unstructured)
if !ok {
return 0, time.Now()
}
priority, hasPriority, err := unstructured.NestedInt64(un.Object, "spec", "priority")
if err != nil {
return 0, un.GetCreationTimestamp().Time
}
if !hasPriority {
priority = 0
}
return int32(priority), un.GetCreationTimestamp().Time
}
func (wfc *WorkflowController) addWorkflowInformerHandlers(ctx context.Context) {
wfc.wfInformer.AddEventHandler(
cache.FilteringResourceEventHandler{
FilterFunc: func(obj interface{}) bool {
return !common.UnstructuredHasCompletedLabel(obj)
},
Handler: cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err == nil {
// for a new workflow, we do not want to rate limit its execution using AddRateLimited
wfc.wfQueue.AddAfter(key, wfc.Config.InitialDelay.Duration)
priority, creation := getWfPriority(obj)
wfc.throttler.Add(key, priority, creation)
}
},
UpdateFunc: func(old, new interface{}) {
oldWf, newWf := old.(*unstructured.Unstructured), new.(*unstructured.Unstructured)
// this check is very important to prevent doing many reconciliations we do not need to do
if oldWf.GetResourceVersion() == newWf.GetResourceVersion() {
return
}
key, err := cache.MetaNamespaceKeyFunc(new)
if err == nil {
wfc.wfQueue.AddRateLimited(key)
priority, creation := getWfPriority(new)
wfc.throttler.Add(key, priority, creation)
}
},
DeleteFunc: func(obj interface{}) {
// IndexerInformer uses a delta queue, therefore for deletes we have to use this
// key function.
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err == nil {
wfc.releaseAllWorkflowLocks(obj)
// no need to add to the queue - this workflow is done
wfc.throttler.Remove(key)
}
},
},
},
)
wfc.wfInformer.AddEventHandler(cache.FilteringResourceEventHandler{
FilterFunc: func(obj interface{}) bool {
un, ok := obj.(*unstructured.Unstructured)
// no need to check the `common.LabelKeyCompleted` as we already know it must be complete
return ok && un.GetLabels()[common.LabelKeyWorkflowArchivingStatus] == "Pending"
},
Handler: cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
wfc.archiveWorkflow(ctx, obj)
},
UpdateFunc: func(_, obj interface{}) {
wfc.archiveWorkflow(ctx, obj)
},
},
},
)
wfc.wfInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
DeleteFunc: func(obj interface{}) {
wf, ok := obj.(*unstructured.Unstructured)
if ok { // maybe cache.DeletedFinalStateUnknown
wfc.metrics.StopRealtimeMetricsForKey(string(wf.GetUID()))
}
},
})
}
func (wfc *WorkflowController) archiveWorkflow(ctx context.Context, obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err != nil {
log.Error("failed to get key for object")
return
}
wfc.workflowKeyLock.Lock(key)
defer wfc.workflowKeyLock.Unlock(key)
err = wfc.archiveWorkflowAux(ctx, obj)
if err != nil {
log.WithField("key", key).WithError(err).Error("failed to archive workflow")
}
}
func (wfc *WorkflowController) archiveWorkflowAux(ctx context.Context, obj interface{}) error {
un, ok := obj.(*unstructured.Unstructured)
if !ok {
return nil
}
wf, err := util.FromUnstructured(un)
if err != nil {
return fmt.Errorf("failed to convert to workflow from unstructured: %w", err)
}
err = wfc.hydrator.Hydrate(wf)
if err != nil {
return fmt.Errorf("failed to hydrate workflow: %w", err)
}
log.WithFields(log.Fields{"namespace": wf.Namespace, "workflow": wf.Name, "uid": wf.UID}).Info("archiving workflow")
err = wfc.wfArchive.ArchiveWorkflow(wf)
if err != nil {
return fmt.Errorf("failed to archive workflow: %w", err)
}
data, err := json.Marshal(map[string]interface{}{
"metadata": metav1.ObjectMeta{
Labels: map[string]string{
common.LabelKeyWorkflowArchivingStatus: "Archived",
},
},
})
if err != nil {
return fmt.Errorf("failed to marshal patch: %w", err)
}
_, err = wfc.wfclientset.ArgoprojV1alpha1().Workflows(un.GetNamespace()).Patch(
ctx,
un.GetName(),
types.MergePatchType,
data,
metav1.PatchOptions{},
)
if err != nil {
// from this point on we have successfully archived the workflow, and it is possible for the workflow to have actually
// been deleted, so it's not a problem to get a `IsNotFound` error
if apierr.IsNotFound(err) {
return nil
}
return fmt.Errorf("failed to archive workflow: %w", err)
}
return nil
}
func (wfc *WorkflowController) newWorkflowPodWatch(ctx context.Context) *cache.ListWatch {
c := wfc.kubeclientset.CoreV1().Pods(wfc.GetManagedNamespace())
// completed=false
incompleteReq, _ := labels.NewRequirement(common.LabelKeyCompleted, selection.Equals, []string{"false"})
labelSelector := labels.NewSelector().
Add(*incompleteReq).
Add(util.InstanceIDRequirement(wfc.Config.InstanceID))
listFunc := func(options metav1.ListOptions) (runtime.Object, error) {
options.LabelSelector = labelSelector.String()
return c.List(ctx, options)
}
watchFunc := func(options metav1.ListOptions) (watch.Interface, error) {
options.Watch = true
options.LabelSelector = labelSelector.String()
return c.Watch(ctx, options)
}
return &cache.ListWatch{ListFunc: listFunc, WatchFunc: watchFunc}
}
func (wfc *WorkflowController) newPodInformer(ctx context.Context) cache.SharedIndexInformer {
source := wfc.newWorkflowPodWatch(ctx)
informer := cache.NewSharedIndexInformer(source, &apiv1.Pod{}, podResyncPeriod, cache.Indexers{
indexes.WorkflowIndex: indexes.MetaWorkflowIndexFunc,
indexes.NodeIDIndex: indexes.MetaNodeIDIndexFunc,
indexes.PodPhaseIndex: indexes.PodPhaseIndexFunc,
})
informer.AddEventHandler(
cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err != nil {
return
}
wfc.podQueue.Add(key)
},
UpdateFunc: func(old, new interface{}) {
key, err := cache.MetaNamespaceKeyFunc(new)
if err != nil {
return
}
oldPod, newPod := old.(*apiv1.Pod), new.(*apiv1.Pod)
if oldPod.ResourceVersion == newPod.ResourceVersion {
return
}
if !pod.SignificantPodChange(oldPod, newPod) {
log.WithField("key", key).Info("insignificant pod change")
diff.LogChanges(oldPod, newPod)
return
}
wfc.podQueue.Add(key)
},
DeleteFunc: func(obj interface{}) {
// IndexerInformer uses a delta queue, therefore for deletes we have to use this
// key function.
// Enqueue the workflow for deleted pod
_ = wfc.enqueueWfFromPodLabel(obj)
},
},
)
return informer
}
func (wfc *WorkflowController) newConfigMapInformer() cache.SharedIndexInformer {
return v1.NewFilteredConfigMapInformer(wfc.kubeclientset, wfc.GetManagedNamespace(), 20*time.Minute, cache.Indexers{
indexes.ConfigMapLabelsIndex: indexes.ConfigMapIndexFunc,
}, func(opts *metav1.ListOptions) {
opts.LabelSelector = indexes.ConfigMapTypeLabel
})
}
// call this func whenever the configuration changes, or when the workflow informer changes
func (wfc *WorkflowController) updateEstimatorFactory() {
wfc.estimatorFactory = estimation.NewEstimatorFactory(wfc.wfInformer, wfc.hydrator, wfc.wfArchive)
}
// setWorkflowDefaults sets values in the workflow.Spec with defaults from the
// workflowController. Values in the workflow will be given the upper hand over the defaults.
// The defaults for the workflow controller are set in the workflow-controller config map
func (wfc *WorkflowController) setWorkflowDefaults(wf *wfv1.Workflow) error {
if wfc.Config.WorkflowDefaults != nil {
err := util.MergeTo(wfc.Config.WorkflowDefaults, wf)
if err != nil {
return err
}
}
return nil
}
func (wfc *WorkflowController) GetManagedNamespace() string {
if wfc.managedNamespace != "" {
return wfc.managedNamespace
}
return wfc.Config.Namespace
}
func (wfc *WorkflowController) GetContainerRuntimeExecutor(labels labels.Labels) string {
executor, err := wfc.Config.GetContainerRuntimeExecutor(labels)
if err != nil {
log.WithError(err).Info("failed to determine container runtime executor")
}
if executor == "" && wfc.containerRuntimeExecutor != "" {
return wfc.containerRuntimeExecutor
}
return executor
}
func (wfc *WorkflowController) getMetricsServerConfig() (metrics.ServerConfig, metrics.ServerConfig) {
// Metrics config
path := wfc.Config.MetricsConfig.Path
if path == "" {
path = metrics.DefaultMetricsServerPath
}
port := wfc.Config.MetricsConfig.Port
if port == 0 {
port = metrics.DefaultMetricsServerPort
}
metricsConfig := metrics.ServerConfig{
Enabled: wfc.Config.MetricsConfig.Enabled == nil || *wfc.Config.MetricsConfig.Enabled,
Path: path,
Port: port,
TTL: time.Duration(wfc.Config.MetricsConfig.MetricsTTL),
IgnoreErrors: wfc.Config.MetricsConfig.IgnoreErrors,
}
// Telemetry config
path = metricsConfig.Path
if wfc.Config.TelemetryConfig.Path != "" {
path = wfc.Config.TelemetryConfig.Path
}
port = metricsConfig.Port
if wfc.Config.TelemetryConfig.Port > 0 {
port = wfc.Config.TelemetryConfig.Port
}
telemetryConfig := metrics.ServerConfig{
Enabled: wfc.Config.TelemetryConfig.Enabled == nil || *wfc.Config.TelemetryConfig.Enabled,
Path: path,
Port: port,
IgnoreErrors: wfc.Config.TelemetryConfig.IgnoreErrors,
}
return metricsConfig, telemetryConfig
}
func (wfc *WorkflowController) releaseAllWorkflowLocks(obj interface{}) {
un, ok := obj.(*unstructured.Unstructured)
if !ok {
log.WithFields(log.Fields{"key": obj}).Warn("Key in index is not an unstructured")
return
}
wf, err := util.FromUnstructured(un)
if err != nil {
log.WithFields(log.Fields{"key": obj}).Warn("Invalid workflow object")
return
}
if wf.Status.Synchronization != nil {
wfc.syncManager.ReleaseAll(wf)
}
}
func (wfc *WorkflowController) isArchivable(wf *wfv1.Workflow) bool {
return wfc.archiveLabelSelector.Matches(labels.Set(wf.Labels))
}
func (wfc *WorkflowController) syncWorkflowPhaseMetrics() {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
for _, phase := range []wfv1.NodePhase{wfv1.NodePending, wfv1.NodeRunning, wfv1.NodeSucceeded, wfv1.NodeFailed, wfv1.NodeError} {
keys, err := wfc.wfInformer.GetIndexer().IndexKeys(indexes.WorkflowPhaseIndex, string(phase))
errors.CheckError(err)
wfc.metrics.SetWorkflowPhaseGauge(phase, len(keys))
}
for _, x := range []wfv1.Condition{
{Type: wfv1.ConditionTypePodRunning, Status: metav1.ConditionTrue},
{Type: wfv1.ConditionTypePodRunning, Status: metav1.ConditionFalse},
} {
keys, err := wfc.wfInformer.GetIndexer().IndexKeys(indexes.ConditionsIndex, indexes.ConditionValue(x))
errors.CheckError(err)
metrics.WorkflowConditionMetric.WithLabelValues(string(x.Type), string(x.Status)).Set(float64(len(keys)))
}
}
func (wfc *WorkflowController) syncPodPhaseMetrics() {
defer runtimeutil.HandleCrash(runtimeutil.PanicHandlers...)
for _, phase := range []apiv1.PodPhase{apiv1.PodRunning, apiv1.PodPending} {
objs, err := wfc.podInformer.GetIndexer().IndexKeys(indexes.PodPhaseIndex, string(phase))
if err != nil {
log.WithError(err).Error("failed to list active pods")
return
}
wfc.metrics.SetPodPhaseGauge(phase, len(objs))
}
}
func (wfc *WorkflowController) newWorkflowTaskSetInformer() wfextvv1alpha1.WorkflowTaskSetInformer {
informer := externalversions.NewSharedInformerFactoryWithOptions(
wfc.wfclientset,
workflowTaskSetResyncPeriod,
externalversions.WithNamespace(wfc.GetManagedNamespace()),
externalversions.WithTweakListOptions(func(x *metav1.ListOptions) {
r := util.InstanceIDRequirement(wfc.Config.InstanceID)
x.LabelSelector = r.String()
})).Argoproj().V1alpha1().WorkflowTaskSets()
informer.Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
UpdateFunc: func(old, new interface{}) {
key, err := cache.MetaNamespaceKeyFunc(new)
if err == nil {
wfc.wfQueue.Add(key)
}
},
})
return informer
}
| [
"\"LEADER_ELECTION_DISABLE\""
]
| []
| [
"LEADER_ELECTION_DISABLE"
]
| [] | ["LEADER_ELECTION_DISABLE"] | go | 1 | 0 | |
src/cmd/go/go_test.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main_test
import (
"bytes"
"debug/elf"
"debug/macho"
"fmt"
"go/format"
"internal/race"
"internal/testenv"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"testing"
"time"
)
var (
canRun = true // whether we can run go or ./testgo
canRace = false // whether we can run the race detector
canCgo = false // whether we can use cgo
canMSan = false // whether we can run the memory sanitizer
exeSuffix string // ".exe" on Windows
skipExternal = false // skip external tests
)
func tooSlow(t *testing.T) {
if testing.Short() {
// In -short mode; skip test, except run it on the {darwin,linux,windows}/amd64 builders.
if testenv.Builder() != "" && runtime.GOARCH == "amd64" && (runtime.GOOS == "linux" || runtime.GOOS == "darwin" || runtime.GOOS == "windows") {
return
}
t.Skip("skipping test in -short mode")
}
}
func init() {
switch runtime.GOOS {
case "android", "nacl":
canRun = false
case "darwin":
switch runtime.GOARCH {
case "arm", "arm64":
canRun = false
}
case "linux":
switch runtime.GOARCH {
case "arm":
// many linux/arm machines are too slow to run
// the full set of external tests.
skipExternal = true
case "mips", "mipsle", "mips64", "mips64le":
// Also slow.
skipExternal = true
if testenv.Builder() != "" {
// On the builders, skip the cmd/go
// tests. They're too slow and already
// covered by other ports. There's
// nothing os/arch specific in the
// tests.
canRun = false
}
}
case "freebsd":
switch runtime.GOARCH {
case "arm":
// many freebsd/arm machines are too slow to run
// the full set of external tests.
skipExternal = true
canRun = false
}
case "plan9":
switch runtime.GOARCH {
case "arm":
// many plan9/arm machines are too slow to run
// the full set of external tests.
skipExternal = true
}
case "windows":
exeSuffix = ".exe"
}
}
// testGOROOT is the GOROOT to use when running testgo, a cmd/go binary
// build from this process's current GOROOT, but run from a different
// (temp) directory.
var testGOROOT string
var testCC string
// The TestMain function creates a go command for testing purposes and
// deletes it after the tests have been run.
func TestMain(m *testing.M) {
if os.Getenv("GO_GCFLAGS") != "" {
fmt.Fprintf(os.Stderr, "testing: warning: no tests to run\n") // magic string for cmd/go
fmt.Printf("cmd/go test is not compatible with $GO_GCFLAGS being set\n")
fmt.Printf("SKIP\n")
return
}
os.Unsetenv("GOROOT_FINAL")
if canRun {
args := []string{"build", "-tags", "testgo", "-o", "testgo" + exeSuffix}
if race.Enabled {
args = append(args, "-race")
}
gotool, err := testenv.GoTool()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
goEnv := func(name string) string {
out, err := exec.Command(gotool, "env", name).CombinedOutput()
if err != nil {
fmt.Fprintf(os.Stderr, "go env %s: %v\n%s", name, err, out)
os.Exit(2)
}
return strings.TrimSpace(string(out))
}
testGOROOT = goEnv("GOROOT")
// The whole GOROOT/pkg tree was installed using the GOHOSTOS/GOHOSTARCH
// toolchain (installed in GOROOT/pkg/tool/GOHOSTOS_GOHOSTARCH).
// The testgo.exe we are about to create will be built for GOOS/GOARCH,
// which means it will use the GOOS/GOARCH toolchain
// (installed in GOROOT/pkg/tool/GOOS_GOARCH).
// If these are not the same toolchain, then the entire standard library
// will look out of date (the compilers in those two different tool directories
// are built for different architectures and have different buid IDs),
// which will cause many tests to do unnecessary rebuilds and some
// tests to attempt to overwrite the installed standard library.
// Bail out entirely in this case.
hostGOOS := goEnv("GOHOSTOS")
hostGOARCH := goEnv("GOHOSTARCH")
if hostGOOS != runtime.GOOS || hostGOARCH != runtime.GOARCH {
fmt.Fprintf(os.Stderr, "testing: warning: no tests to run\n") // magic string for cmd/go
fmt.Printf("cmd/go test is not compatible with GOOS/GOARCH != GOHOSTOS/GOHOSTARCH (%s/%s != %s/%s)\n", runtime.GOOS, runtime.GOARCH, hostGOOS, hostGOARCH)
fmt.Printf("SKIP\n")
return
}
out, err := exec.Command(gotool, args...).CombinedOutput()
if err != nil {
fmt.Fprintf(os.Stderr, "building testgo failed: %v\n%s", err, out)
os.Exit(2)
}
out, err = exec.Command(gotool, "env", "CC").CombinedOutput()
if err != nil {
fmt.Fprintf(os.Stderr, "could not find testing CC: %v\n%s", err, out)
os.Exit(2)
}
testCC = strings.TrimSpace(string(out))
if out, err := exec.Command("./testgo"+exeSuffix, "env", "CGO_ENABLED").Output(); err != nil {
fmt.Fprintf(os.Stderr, "running testgo failed: %v\n", err)
canRun = false
} else {
canCgo, err = strconv.ParseBool(strings.TrimSpace(string(out)))
if err != nil {
fmt.Fprintf(os.Stderr, "can't parse go env CGO_ENABLED output: %v\n", strings.TrimSpace(string(out)))
}
}
// As of Sept 2017, MSan is only supported on linux/amd64.
// https://github.com/google/sanitizers/wiki/MemorySanitizer#getting-memorysanitizer
canMSan = canCgo && runtime.GOOS == "linux" && runtime.GOARCH == "amd64"
switch runtime.GOOS {
case "linux", "darwin", "freebsd", "windows":
// The race detector doesn't work on Alpine Linux:
// golang.org/issue/14481
canRace = canCgo && runtime.GOARCH == "amd64" && !isAlpineLinux()
}
}
// Don't let these environment variables confuse the test.
os.Unsetenv("GOBIN")
os.Unsetenv("GOPATH")
os.Unsetenv("GIT_ALLOW_PROTOCOL")
if home, ccacheDir := os.Getenv("HOME"), os.Getenv("CCACHE_DIR"); home != "" && ccacheDir == "" {
// On some systems the default C compiler is ccache.
// Setting HOME to a non-existent directory will break
// those systems. Set CCACHE_DIR to cope. Issue 17668.
os.Setenv("CCACHE_DIR", filepath.Join(home, ".ccache"))
}
os.Setenv("HOME", "/test-go-home-does-not-exist")
if os.Getenv("GOCACHE") == "" {
os.Setenv("GOCACHE", "off") // because $HOME is gone
}
r := m.Run()
if canRun {
os.Remove("testgo" + exeSuffix)
}
os.Exit(r)
}
func isAlpineLinux() bool {
if runtime.GOOS != "linux" {
return false
}
fi, err := os.Lstat("/etc/alpine-release")
return err == nil && fi.Mode().IsRegular()
}
// The length of an mtime tick on this system. This is an estimate of
// how long we need to sleep to ensure that the mtime of two files is
// different.
// We used to try to be clever but that didn't always work (see golang.org/issue/12205).
var mtimeTick time.Duration = 1 * time.Second
// Manage a single run of the testgo binary.
type testgoData struct {
t *testing.T
temps []string
wd string
env []string
tempdir string
ran bool
inParallel bool
stdout, stderr bytes.Buffer
}
// testgo sets up for a test that runs testgo.
func testgo(t *testing.T) *testgoData {
t.Helper()
testenv.MustHaveGoBuild(t)
if skipExternal {
t.Skipf("skipping external tests on %s/%s", runtime.GOOS, runtime.GOARCH)
}
return &testgoData{t: t}
}
// must gives a fatal error if err is not nil.
func (tg *testgoData) must(err error) {
tg.t.Helper()
if err != nil {
tg.t.Fatal(err)
}
}
// check gives a test non-fatal error if err is not nil.
func (tg *testgoData) check(err error) {
tg.t.Helper()
if err != nil {
tg.t.Error(err)
}
}
// parallel runs the test in parallel by calling t.Parallel.
func (tg *testgoData) parallel() {
tg.t.Helper()
if tg.ran {
tg.t.Fatal("internal testsuite error: call to parallel after run")
}
if tg.wd != "" {
tg.t.Fatal("internal testsuite error: call to parallel after cd")
}
for _, e := range tg.env {
if strings.HasPrefix(e, "GOROOT=") || strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
val := e[strings.Index(e, "=")+1:]
if strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata") {
tg.t.Fatalf("internal testsuite error: call to parallel with testdata in environment (%s)", e)
}
}
}
tg.inParallel = true
tg.t.Parallel()
}
// pwd returns the current directory.
func (tg *testgoData) pwd() string {
tg.t.Helper()
wd, err := os.Getwd()
if err != nil {
tg.t.Fatalf("could not get working directory: %v", err)
}
return wd
}
// cd changes the current directory to the named directory. Note that
// using this means that the test must not be run in parallel with any
// other tests.
func (tg *testgoData) cd(dir string) {
tg.t.Helper()
if tg.inParallel {
tg.t.Fatal("internal testsuite error: changing directory when running in parallel")
}
if tg.wd == "" {
tg.wd = tg.pwd()
}
abs, err := filepath.Abs(dir)
tg.must(os.Chdir(dir))
if err == nil {
tg.setenv("PWD", abs)
}
}
// sleep sleeps for one tick, where a tick is a conservative estimate
// of how long it takes for a file modification to get a different
// mtime.
func (tg *testgoData) sleep() {
time.Sleep(mtimeTick)
}
// setenv sets an environment variable to use when running the test go
// command.
func (tg *testgoData) setenv(name, val string) {
tg.t.Helper()
if tg.inParallel && (name == "GOROOT" || name == "GOPATH" || name == "GOBIN") && (strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata")) {
tg.t.Fatalf("internal testsuite error: call to setenv with testdata (%s=%s) after parallel", name, val)
}
tg.unsetenv(name)
tg.env = append(tg.env, name+"="+val)
}
// unsetenv removes an environment variable.
func (tg *testgoData) unsetenv(name string) {
if tg.env == nil {
tg.env = append([]string(nil), os.Environ()...)
}
for i, v := range tg.env {
if strings.HasPrefix(v, name+"=") {
tg.env = append(tg.env[:i], tg.env[i+1:]...)
break
}
}
}
func (tg *testgoData) goTool() string {
if tg.wd == "" {
return "./testgo" + exeSuffix
}
return filepath.Join(tg.wd, "testgo"+exeSuffix)
}
// doRun runs the test go command, recording stdout and stderr and
// returning exit status.
func (tg *testgoData) doRun(args []string) error {
tg.t.Helper()
if !canRun {
panic("testgoData.doRun called but canRun false")
}
if tg.inParallel {
for _, arg := range args {
if strings.HasPrefix(arg, "testdata") || strings.HasPrefix(arg, "./testdata") {
tg.t.Fatal("internal testsuite error: parallel run using testdata")
}
}
}
hasGoroot := false
for _, v := range tg.env {
if strings.HasPrefix(v, "GOROOT=") {
hasGoroot = true
break
}
}
prog := tg.goTool()
if !hasGoroot {
tg.setenv("GOROOT", testGOROOT)
}
tg.t.Logf("running testgo %v", args)
cmd := exec.Command(prog, args...)
tg.stdout.Reset()
tg.stderr.Reset()
cmd.Stdout = &tg.stdout
cmd.Stderr = &tg.stderr
cmd.Env = tg.env
status := cmd.Run()
if tg.stdout.Len() > 0 {
tg.t.Log("standard output:")
tg.t.Log(tg.stdout.String())
}
if tg.stderr.Len() > 0 {
tg.t.Log("standard error:")
tg.t.Log(tg.stderr.String())
}
tg.ran = true
return status
}
// run runs the test go command, and expects it to succeed.
func (tg *testgoData) run(args ...string) {
tg.t.Helper()
if status := tg.doRun(args); status != nil {
tg.t.Logf("go %v failed unexpectedly: %v", args, status)
tg.t.FailNow()
}
}
// runFail runs the test go command, and expects it to fail.
func (tg *testgoData) runFail(args ...string) {
tg.t.Helper()
if status := tg.doRun(args); status == nil {
tg.t.Fatal("testgo succeeded unexpectedly")
} else {
tg.t.Log("testgo failed as expected:", status)
}
}
// runGit runs a git command, and expects it to succeed.
func (tg *testgoData) runGit(dir string, args ...string) {
tg.t.Helper()
cmd := exec.Command("git", args...)
tg.stdout.Reset()
tg.stderr.Reset()
cmd.Stdout = &tg.stdout
cmd.Stderr = &tg.stderr
cmd.Dir = dir
cmd.Env = tg.env
status := cmd.Run()
if tg.stdout.Len() > 0 {
tg.t.Log("git standard output:")
tg.t.Log(tg.stdout.String())
}
if tg.stderr.Len() > 0 {
tg.t.Log("git standard error:")
tg.t.Log(tg.stderr.String())
}
if status != nil {
tg.t.Logf("git %v failed unexpectedly: %v", args, status)
tg.t.FailNow()
}
}
// getStdout returns standard output of the testgo run as a string.
func (tg *testgoData) getStdout() string {
tg.t.Helper()
if !tg.ran {
tg.t.Fatal("internal testsuite error: stdout called before run")
}
return tg.stdout.String()
}
// getStderr returns standard error of the testgo run as a string.
func (tg *testgoData) getStderr() string {
tg.t.Helper()
if !tg.ran {
tg.t.Fatal("internal testsuite error: stdout called before run")
}
return tg.stderr.String()
}
// doGrepMatch looks for a regular expression in a buffer, and returns
// whether it is found. The regular expression is matched against
// each line separately, as with the grep command.
func (tg *testgoData) doGrepMatch(match string, b *bytes.Buffer) bool {
tg.t.Helper()
if !tg.ran {
tg.t.Fatal("internal testsuite error: grep called before run")
}
re := regexp.MustCompile(match)
for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
if re.Match(ln) {
return true
}
}
return false
}
// doGrep looks for a regular expression in a buffer and fails if it
// is not found. The name argument is the name of the output we are
// searching, "output" or "error". The msg argument is logged on
// failure.
func (tg *testgoData) doGrep(match string, b *bytes.Buffer, name, msg string) {
tg.t.Helper()
if !tg.doGrepMatch(match, b) {
tg.t.Log(msg)
tg.t.Logf("pattern %v not found in standard %s", match, name)
tg.t.FailNow()
}
}
// grepStdout looks for a regular expression in the test run's
// standard output and fails, logging msg, if it is not found.
func (tg *testgoData) grepStdout(match, msg string) {
tg.t.Helper()
tg.doGrep(match, &tg.stdout, "output", msg)
}
// grepStderr looks for a regular expression in the test run's
// standard error and fails, logging msg, if it is not found.
func (tg *testgoData) grepStderr(match, msg string) {
tg.t.Helper()
tg.doGrep(match, &tg.stderr, "error", msg)
}
// grepBoth looks for a regular expression in the test run's standard
// output or stand error and fails, logging msg, if it is not found.
func (tg *testgoData) grepBoth(match, msg string) {
tg.t.Helper()
if !tg.doGrepMatch(match, &tg.stdout) && !tg.doGrepMatch(match, &tg.stderr) {
tg.t.Log(msg)
tg.t.Logf("pattern %v not found in standard output or standard error", match)
tg.t.FailNow()
}
}
// doGrepNot looks for a regular expression in a buffer and fails if
// it is found. The name and msg arguments are as for doGrep.
func (tg *testgoData) doGrepNot(match string, b *bytes.Buffer, name, msg string) {
tg.t.Helper()
if tg.doGrepMatch(match, b) {
tg.t.Log(msg)
tg.t.Logf("pattern %v found unexpectedly in standard %s", match, name)
tg.t.FailNow()
}
}
// grepStdoutNot looks for a regular expression in the test run's
// standard output and fails, logging msg, if it is found.
func (tg *testgoData) grepStdoutNot(match, msg string) {
tg.t.Helper()
tg.doGrepNot(match, &tg.stdout, "output", msg)
}
// grepStderrNot looks for a regular expression in the test run's
// standard error and fails, logging msg, if it is found.
func (tg *testgoData) grepStderrNot(match, msg string) {
tg.t.Helper()
tg.doGrepNot(match, &tg.stderr, "error", msg)
}
// grepBothNot looks for a regular expression in the test run's
// standard output or stand error and fails, logging msg, if it is
// found.
func (tg *testgoData) grepBothNot(match, msg string) {
tg.t.Helper()
if tg.doGrepMatch(match, &tg.stdout) || tg.doGrepMatch(match, &tg.stderr) {
tg.t.Log(msg)
tg.t.Fatalf("pattern %v found unexpectedly in standard output or standard error", match)
}
}
// doGrepCount counts the number of times a regexp is seen in a buffer.
func (tg *testgoData) doGrepCount(match string, b *bytes.Buffer) int {
tg.t.Helper()
if !tg.ran {
tg.t.Fatal("internal testsuite error: doGrepCount called before run")
}
re := regexp.MustCompile(match)
c := 0
for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
if re.Match(ln) {
c++
}
}
return c
}
// grepCountBoth returns the number of times a regexp is seen in both
// standard output and standard error.
func (tg *testgoData) grepCountBoth(match string) int {
tg.t.Helper()
return tg.doGrepCount(match, &tg.stdout) + tg.doGrepCount(match, &tg.stderr)
}
// creatingTemp records that the test plans to create a temporary file
// or directory. If the file or directory exists already, it will be
// removed. When the test completes, the file or directory will be
// removed if it exists.
func (tg *testgoData) creatingTemp(path string) {
tg.t.Helper()
if filepath.IsAbs(path) && !strings.HasPrefix(path, tg.tempdir) {
tg.t.Fatalf("internal testsuite error: creatingTemp(%q) with absolute path not in temporary directory", path)
}
// If we have changed the working directory, make sure we have
// an absolute path, because we are going to change directory
// back before we remove the temporary.
if tg.wd != "" && !filepath.IsAbs(path) {
path = filepath.Join(tg.pwd(), path)
}
tg.must(os.RemoveAll(path))
tg.temps = append(tg.temps, path)
}
// makeTempdir makes a temporary directory for a run of testgo. If
// the temporary directory was already created, this does nothing.
func (tg *testgoData) makeTempdir() {
tg.t.Helper()
if tg.tempdir == "" {
var err error
tg.tempdir, err = ioutil.TempDir("", "gotest")
tg.must(err)
}
}
// tempFile adds a temporary file for a run of testgo.
func (tg *testgoData) tempFile(path, contents string) {
tg.t.Helper()
tg.makeTempdir()
tg.must(os.MkdirAll(filepath.Join(tg.tempdir, filepath.Dir(path)), 0755))
bytes := []byte(contents)
if strings.HasSuffix(path, ".go") {
formatted, err := format.Source(bytes)
if err == nil {
bytes = formatted
}
}
tg.must(ioutil.WriteFile(filepath.Join(tg.tempdir, path), bytes, 0644))
}
// tempDir adds a temporary directory for a run of testgo.
func (tg *testgoData) tempDir(path string) {
tg.t.Helper()
tg.makeTempdir()
if err := os.MkdirAll(filepath.Join(tg.tempdir, path), 0755); err != nil && !os.IsExist(err) {
tg.t.Fatal(err)
}
}
// path returns the absolute pathname to file with the temporary
// directory.
func (tg *testgoData) path(name string) string {
tg.t.Helper()
if tg.tempdir == "" {
tg.t.Fatalf("internal testsuite error: path(%q) with no tempdir", name)
}
if name == "." {
return tg.tempdir
}
return filepath.Join(tg.tempdir, name)
}
// mustExist fails if path does not exist.
func (tg *testgoData) mustExist(path string) {
tg.t.Helper()
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
tg.t.Fatalf("%s does not exist but should", path)
}
tg.t.Fatalf("%s stat failed: %v", path, err)
}
}
// mustNotExist fails if path exists.
func (tg *testgoData) mustNotExist(path string) {
tg.t.Helper()
if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) {
tg.t.Fatalf("%s exists but should not (%v)", path, err)
}
}
// mustHaveContent succeeds if filePath is a path to a file,
// and that file is readable and not empty.
func (tg *testgoData) mustHaveContent(filePath string) {
tg.mustExist(filePath)
f, err := os.Stat(filePath)
if err != nil {
tg.t.Fatal(err)
}
if f.Size() == 0 {
tg.t.Fatalf("expected %s to have data, but is empty", filePath)
}
}
// wantExecutable fails with msg if path is not executable.
func (tg *testgoData) wantExecutable(path, msg string) {
tg.t.Helper()
if st, err := os.Stat(path); err != nil {
if !os.IsNotExist(err) {
tg.t.Log(err)
}
tg.t.Fatal(msg)
} else {
if runtime.GOOS != "windows" && st.Mode()&0111 == 0 {
tg.t.Fatalf("binary %s exists but is not executable", path)
}
}
}
// wantArchive fails if path is not an archive.
func (tg *testgoData) wantArchive(path string) {
tg.t.Helper()
f, err := os.Open(path)
if err != nil {
tg.t.Fatal(err)
}
buf := make([]byte, 100)
io.ReadFull(f, buf)
f.Close()
if !bytes.HasPrefix(buf, []byte("!<arch>\n")) {
tg.t.Fatalf("file %s exists but is not an archive", path)
}
}
// isStale reports whether pkg is stale, and why
func (tg *testgoData) isStale(pkg string) (bool, string) {
tg.t.Helper()
tg.run("list", "-f", "{{.Stale}}:{{.StaleReason}}", pkg)
v := strings.TrimSpace(tg.getStdout())
f := strings.SplitN(v, ":", 2)
if len(f) == 2 {
switch f[0] {
case "true":
return true, f[1]
case "false":
return false, f[1]
}
}
tg.t.Fatalf("unexpected output checking staleness of package %v: %v", pkg, v)
panic("unreachable")
}
// wantStale fails with msg if pkg is not stale.
func (tg *testgoData) wantStale(pkg, reason, msg string) {
tg.t.Helper()
stale, why := tg.isStale(pkg)
if !stale {
tg.t.Fatal(msg)
}
if reason == "" && why != "" || !strings.Contains(why, reason) {
tg.t.Errorf("wrong reason for Stale=true: %q, want %q", why, reason)
}
}
// wantNotStale fails with msg if pkg is stale.
func (tg *testgoData) wantNotStale(pkg, reason, msg string) {
tg.t.Helper()
stale, why := tg.isStale(pkg)
if stale {
tg.t.Fatal(msg)
}
if reason == "" && why != "" || !strings.Contains(why, reason) {
tg.t.Errorf("wrong reason for Stale=false: %q, want %q", why, reason)
}
}
// cleanup cleans up a test that runs testgo.
func (tg *testgoData) cleanup() {
tg.t.Helper()
if tg.wd != "" {
if err := os.Chdir(tg.wd); err != nil {
// We are unlikely to be able to continue.
fmt.Fprintln(os.Stderr, "could not restore working directory, crashing:", err)
os.Exit(2)
}
}
for _, path := range tg.temps {
tg.check(os.RemoveAll(path))
}
if tg.tempdir != "" {
tg.check(os.RemoveAll(tg.tempdir))
}
}
// failSSH puts an ssh executable in the PATH that always fails.
// This is to stub out uses of ssh by go get.
func (tg *testgoData) failSSH() {
tg.t.Helper()
wd, err := os.Getwd()
if err != nil {
tg.t.Fatal(err)
}
fail := filepath.Join(wd, "testdata/failssh")
tg.setenv("PATH", fmt.Sprintf("%v%c%v", fail, filepath.ListSeparator, os.Getenv("PATH")))
}
func TestBuildComplex(t *testing.T) {
// Simple smoke test for build configuration.
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("build", "-x", "-o", os.DevNull, "complex")
if _, err := exec.LookPath("gccgo"); err == nil {
t.Skip("golang.org/issue/22472")
tg.run("build", "-x", "-o", os.DevNull, "-compiler=gccgo", "complex")
}
}
func TestFileLineInErrorMessages(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("err.go", `package main; import "bar"`)
path := tg.path("err.go")
tg.runFail("run", path)
shortPath := path
if rel, err := filepath.Rel(tg.pwd(), path); err == nil && len(rel) < len(path) {
shortPath = rel
}
tg.grepStderr("^"+regexp.QuoteMeta(shortPath)+":", "missing file:line in error message")
}
func TestProgramNameInCrashMessages(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("triv.go", `package main; func main() {}`)
tg.runFail("build", "-ldflags", "-crash_for_testing", tg.path("triv.go"))
tg.grepStderr(`[/\\]tool[/\\].*[/\\]link`, "missing linker name in error message")
}
func TestBrokenTestsWithoutTestFunctionsAllFail(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.runFail("test", "./testdata/src/badtest/...")
tg.grepBothNot("^ok", "test passed unexpectedly")
tg.grepBoth("FAIL.*badtest/badexec", "test did not run everything")
tg.grepBoth("FAIL.*badtest/badsyntax", "test did not run everything")
tg.grepBoth("FAIL.*badtest/badvar", "test did not run everything")
}
func TestGoBuildDashAInDevBranch(t *testing.T) {
if testing.Short() {
t.Skip("don't rebuild the standard library in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.run("install", "math") // should be up to date already but just in case
tg.setenv("TESTGO_IS_GO_RELEASE", "0")
tg.run("build", "-v", "-a", "math")
tg.grepStderr("runtime", "testgo build -a math in dev branch DID NOT build runtime, but should have")
// Everything is out of date. Rebuild to leave things in a better state.
tg.run("install", "std")
}
func TestGoBuildDashAInReleaseBranch(t *testing.T) {
if testing.Short() {
t.Skip("don't rebuild the standard library in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.run("install", "math", "net/http") // should be up to date already but just in case
tg.setenv("TESTGO_IS_GO_RELEASE", "1")
tg.run("install", "-v", "-a", "math")
tg.grepStderr("runtime", "testgo build -a math in release branch DID NOT build runtime, but should have")
// Now runtime.a is updated (newer mtime), so everything would look stale if not for being a release.
tg.run("build", "-v", "net/http")
tg.grepStderrNot("strconv", "testgo build -v net/http in release branch with newer runtime.a DID build strconv but should not have")
tg.grepStderrNot("golang.org/x/net/http2/hpack", "testgo build -v net/http in release branch with newer runtime.a DID build .../golang.org/x/net/http2/hpack but should not have")
tg.grepStderrNot("net/http", "testgo build -v net/http in release branch with newer runtime.a DID build net/http but should not have")
// Everything is out of date. Rebuild to leave things in a better state.
tg.run("install", "std")
}
func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) {
if testing.Short() {
t.Skip("don't rebuild the standard library in short mode")
}
tg := testgo(t)
defer tg.cleanup()
addNL := func(name string) (restore func()) {
data, err := ioutil.ReadFile(name)
if err != nil {
t.Fatal(err)
}
old := data
data = append(data, '\n')
if err := ioutil.WriteFile(name, append(data, '\n'), 0666); err != nil {
t.Fatal(err)
}
tg.sleep()
return func() {
if err := ioutil.WriteFile(name, old, 0666); err != nil {
t.Fatal(err)
}
}
}
tg.tempFile("d1/src/p1/p1.go", `package p1`)
tg.setenv("GOPATH", tg.path("d1"))
tg.run("install", "-a", "p1")
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, before any changes")
// Changing mtime of runtime/internal/sys/sys.go
// should have no effect: only the content matters.
// In fact this should be true even outside a release branch.
sys := runtime.GOROOT() + "/src/runtime/internal/sys/sys.go"
tg.sleep()
restore := addNL(sys)
restore()
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after updating mtime of runtime/internal/sys/sys.go")
// But changing content of any file should have an effect.
// Previously zversion.go was the only one that mattered;
// now they all matter, so keep using sys.go.
restore = addNL(sys)
defer restore()
tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go")
restore()
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after changing back to old release")
addNL(sys)
tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go again")
tg.run("install", "p1")
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with new release")
// Restore to "old" release.
restore()
tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after restoring sys.go")
tg.run("install", "p1")
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with old release")
// Everything is out of date. Rebuild to leave things in a better state.
tg.run("install", "std")
}
func TestGoListStandard(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.cd(runtime.GOROOT() + "/src")
tg.run("list", "-f", "{{if not .Standard}}{{.ImportPath}}{{end}}", "./...")
stdout := tg.getStdout()
for _, line := range strings.Split(stdout, "\n") {
if strings.HasPrefix(line, "_/") && strings.HasSuffix(line, "/src") {
// $GOROOT/src shows up if there are any .go files there.
// We don't care.
continue
}
if line == "" {
continue
}
t.Errorf("package in GOROOT not listed as standard: %v", line)
}
// Similarly, expanding std should include some of our vendored code.
tg.run("list", "std", "cmd")
tg.grepStdout("golang.org/x/net/http2/hpack", "list std cmd did not mention vendored hpack")
tg.grepStdout("golang.org/x/arch/x86/x86asm", "list std cmd did not mention vendored x86asm")
}
func TestGoInstallCleansUpAfterGoBuild(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.tempFile("src/mycmd/main.go", `package main; func main(){}`)
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("src/mycmd"))
doesNotExist := func(file, msg string) {
if _, err := os.Stat(file); err == nil {
t.Fatal(msg)
} else if !os.IsNotExist(err) {
t.Fatal(msg, "error:", err)
}
}
tg.run("build")
tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary")
tg.run("install")
doesNotExist("mycmd"+exeSuffix, "testgo install did not remove command binary")
tg.run("build")
tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (second time)")
// Running install with arguments does not remove the target,
// even in the same directory.
tg.run("install", "mycmd")
tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary when run in mycmd")
tg.run("build")
tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (third time)")
// And especially not outside the directory.
tg.cd(tg.path("."))
if data, err := ioutil.ReadFile("src/mycmd/mycmd" + exeSuffix); err != nil {
t.Fatal("could not read file:", err)
} else {
if err := ioutil.WriteFile("mycmd"+exeSuffix, data, 0555); err != nil {
t.Fatal("could not write file:", err)
}
}
tg.run("install", "mycmd")
tg.wantExecutable("src/mycmd/mycmd"+exeSuffix, "testgo install mycmd removed command binary from its source dir when run outside mycmd")
tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary from current dir when run outside mycmd")
}
func TestGoInstallRebuildsStalePackagesInOtherGOPATH(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("d1/src/p1/p1.go", `package p1
import "p2"
func F() { p2.F() }`)
tg.tempFile("d2/src/p2/p2.go", `package p2
func F() {}`)
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", tg.path("d1")+sep+tg.path("d2"))
tg.run("install", "-i", "p1")
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly")
tg.wantNotStale("p2", "", "./testgo list claims p2 is stale, incorrectly")
tg.sleep()
if f, err := os.OpenFile(tg.path("d2/src/p2/p2.go"), os.O_WRONLY|os.O_APPEND, 0); err != nil {
t.Fatal(err)
} else if _, err = f.WriteString(`func G() {}`); err != nil {
t.Fatal(err)
} else {
tg.must(f.Close())
}
tg.wantStale("p2", "build ID mismatch", "./testgo list claims p2 is NOT stale, incorrectly")
tg.wantStale("p1", "stale dependency: p2", "./testgo list claims p1 is NOT stale, incorrectly")
tg.run("install", "-i", "p1")
tg.wantNotStale("p2", "", "./testgo list claims p2 is stale after reinstall, incorrectly")
tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after reinstall, incorrectly")
}
func TestGoInstallDetectsRemovedFiles(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/mypkg/x.go", `package mypkg`)
tg.tempFile("src/mypkg/y.go", `package mypkg`)
tg.tempFile("src/mypkg/z.go", `// +build missingtag
package mypkg`)
tg.setenv("GOPATH", tg.path("."))
tg.run("install", "mypkg")
tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale, incorrectly")
// z.go was not part of the build; removing it is okay.
tg.must(os.Remove(tg.path("src/mypkg/z.go")))
tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale after removing z.go; should not be stale")
// y.go was part of the package; removing it should be detected.
tg.must(os.Remove(tg.path("src/mypkg/y.go")))
tg.wantStale("mypkg", "build ID mismatch", "./testgo list mypkg claims mypkg is NOT stale after removing y.go; should be stale")
}
func TestWildcardMatchesSyntaxErrorDirs(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.tempFile("src/mypkg/x.go", `package mypkg`)
tg.tempFile("src/mypkg/y.go", `pkg mypackage`)
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("src/mypkg"))
tg.runFail("list", "./...")
tg.runFail("build", "./...")
tg.runFail("install", "./...")
}
func TestGoListWithTags(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("src/mypkg/x.go", "// +build thetag\n\npackage mypkg\n")
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("./src"))
tg.run("list", "-tags=thetag", "./my...")
tg.grepStdout("mypkg", "did not find mypkg")
}
func TestGoInstallErrorOnCrossCompileToBin(t *testing.T) {
if testing.Short() {
t.Skip("don't install into GOROOT in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("src/mycmd/x.go", `package main
func main() {}`)
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("src/mycmd"))
tg.run("build", "mycmd")
goarch := "386"
if runtime.GOARCH == "386" {
goarch = "amd64"
}
tg.setenv("GOOS", "linux")
tg.setenv("GOARCH", goarch)
tg.run("install", "mycmd")
tg.setenv("GOBIN", tg.path("."))
tg.runFail("install", "mycmd")
tg.run("install", "cmd/pack")
}
func TestGoInstallDetectsRemovedFilesInPackageMain(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/mycmd/x.go", `package main
func main() {}`)
tg.tempFile("src/mycmd/y.go", `package main`)
tg.tempFile("src/mycmd/z.go", `// +build missingtag
package main`)
tg.setenv("GOPATH", tg.path("."))
tg.run("install", "mycmd")
tg.wantNotStale("mycmd", "", "./testgo list mypkg claims mycmd is stale, incorrectly")
// z.go was not part of the build; removing it is okay.
tg.must(os.Remove(tg.path("src/mycmd/z.go")))
tg.wantNotStale("mycmd", "", "./testgo list mycmd claims mycmd is stale after removing z.go; should not be stale")
// y.go was part of the package; removing it should be detected.
tg.must(os.Remove(tg.path("src/mycmd/y.go")))
tg.wantStale("mycmd", "build ID mismatch", "./testgo list mycmd claims mycmd is NOT stale after removing y.go; should be stale")
}
func testLocalRun(tg *testgoData, exepath, local, match string) {
tg.t.Helper()
out, err := exec.Command(exepath).Output()
if err != nil {
tg.t.Fatalf("error running %v: %v", exepath, err)
}
if !regexp.MustCompile(match).Match(out) {
tg.t.Log(string(out))
tg.t.Errorf("testdata/%s/easy.go did not generate expected output", local)
}
}
func testLocalEasy(tg *testgoData, local string) {
tg.t.Helper()
exepath := "./easy" + exeSuffix
tg.creatingTemp(exepath)
tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easy.go"))
testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
}
func testLocalEasySub(tg *testgoData, local string) {
tg.t.Helper()
exepath := "./easysub" + exeSuffix
tg.creatingTemp(exepath)
tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easysub", "main.go"))
testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
}
func testLocalHard(tg *testgoData, local string) {
tg.t.Helper()
exepath := "./hard" + exeSuffix
tg.creatingTemp(exepath)
tg.run("build", "-o", exepath, filepath.Join("testdata", local, "hard.go"))
testLocalRun(tg, exepath, local, `(?m)^sub\.Hello`)
}
func testLocalInstall(tg *testgoData, local string) {
tg.t.Helper()
tg.runFail("install", filepath.Join("testdata", local, "easy.go"))
}
func TestLocalImportsEasy(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
testLocalEasy(tg, "local")
}
func TestLocalImportsEasySub(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
testLocalEasySub(tg, "local")
}
func TestLocalImportsHard(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
testLocalHard(tg, "local")
}
func TestLocalImportsGoInstallShouldFail(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
testLocalInstall(tg, "local")
}
const badDirName = `#$%:, &()*;<=>?\^{}`
func copyBad(tg *testgoData) {
tg.t.Helper()
if runtime.GOOS == "windows" {
tg.t.Skipf("skipping test because %q is an invalid directory name", badDirName)
}
tg.must(filepath.Walk("testdata/local",
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
var data []byte
data, err = ioutil.ReadFile(path)
if err != nil {
return err
}
newpath := strings.Replace(path, "local", badDirName, 1)
tg.tempFile(newpath, string(data))
return nil
}))
tg.cd(tg.path("."))
}
func TestBadImportsEasy(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
copyBad(tg)
testLocalEasy(tg, badDirName)
}
func TestBadImportsEasySub(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
copyBad(tg)
testLocalEasySub(tg, badDirName)
}
func TestBadImportsHard(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
copyBad(tg)
testLocalHard(tg, badDirName)
}
func TestBadImportsGoInstallShouldFail(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
copyBad(tg)
testLocalInstall(tg, badDirName)
}
func TestInternalPackagesInGOROOTAreRespected(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.runFail("build", "-v", "./testdata/testinternal")
tg.grepBoth(`testinternal(\/|\\)p\.go\:3\:8\: use of internal package not allowed`, "wrong error message for testdata/testinternal")
}
func TestInternalPackagesOutsideGOROOTAreRespected(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.runFail("build", "-v", "./testdata/testinternal2")
tg.grepBoth(`testinternal2(\/|\\)p\.go\:3\:8\: use of internal package not allowed`, "wrote error message for testdata/testinternal2")
}
func TestRunInternal(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
dir := filepath.Join(tg.pwd(), "testdata")
tg.setenv("GOPATH", dir)
tg.run("run", filepath.Join(dir, "src/run/good.go"))
tg.runFail("run", filepath.Join(dir, "src/run/bad.go"))
tg.grepStderr(`testdata(\/|\\)src(\/|\\)run(\/|\\)bad\.go\:3\:8\: use of internal package not allowed`, "unexpected error for run/bad.go")
}
func testMove(t *testing.T, vcs, url, base, config string) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src")
tg.setenv("GOPATH", tg.path("."))
tg.run("get", "-d", url)
tg.run("get", "-d", "-u", url)
switch vcs {
case "svn":
// SVN doesn't believe in text files so we can't just edit the config.
// Check out a different repo into the wrong place.
tg.must(os.RemoveAll(tg.path("src/code.google.com/p/rsc-svn")))
tg.run("get", "-d", "-u", "code.google.com/p/rsc-svn2/trunk")
tg.must(os.Rename(tg.path("src/code.google.com/p/rsc-svn2"), tg.path("src/code.google.com/p/rsc-svn")))
default:
path := tg.path(filepath.Join("src", config))
data, err := ioutil.ReadFile(path)
tg.must(err)
data = bytes.Replace(data, []byte(base), []byte(base+"XXX"), -1)
tg.must(ioutil.WriteFile(path, data, 0644))
}
if vcs == "git" {
// git will ask for a username and password when we
// run go get -d -f -u. An empty username and
// password will work. Prevent asking by setting
// GIT_ASKPASS.
tg.creatingTemp("sink" + exeSuffix)
tg.tempFile("src/sink/sink.go", `package main; func main() {}`)
tg.run("build", "-o", "sink"+exeSuffix, "sink")
tg.setenv("GIT_ASKPASS", filepath.Join(tg.pwd(), "sink"+exeSuffix))
}
tg.runFail("get", "-d", "-u", url)
tg.grepStderr("is a custom import path for", "go get -d -u "+url+" failed for wrong reason")
tg.runFail("get", "-d", "-f", "-u", url)
tg.grepStderr("validating server certificate|[nN]ot [fF]ound", "go get -d -f -u "+url+" failed for wrong reason")
}
func TestInternalPackageErrorsAreHandled(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("list", "./testdata/testinternal3")
}
func TestInternalCache(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/testinternal4"))
tg.runFail("build", "p")
tg.grepStderr("internal", "did not fail to build p")
}
func TestMoveGit(t *testing.T) {
testMove(t, "git", "rsc.io/pdf", "pdf", "rsc.io/pdf/.git/config")
}
func TestMoveHG(t *testing.T) {
testMove(t, "hg", "vcs-test.golang.org/go/custom-hg-hello", "custom-hg-hello", "vcs-test.golang.org/go/custom-hg-hello/.hg/hgrc")
}
// TODO(rsc): Set up a test case on SourceForge (?) for svn.
// func testMoveSVN(t *testing.T) {
// testMove(t, "svn", "code.google.com/p/rsc-svn/trunk", "-", "-")
// }
func TestImportCommandMatch(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
tg.run("build", "./testdata/importcom/works.go")
}
func TestImportCommentMismatch(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
tg.runFail("build", "./testdata/importcom/wrongplace.go")
tg.grepStderr(`wrongplace expects import "my/x"`, "go build did not mention incorrect import")
}
func TestImportCommentSyntaxError(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
tg.runFail("build", "./testdata/importcom/bad.go")
tg.grepStderr("cannot parse import comment", "go build did not mention syntax error")
}
func TestImportCommentConflict(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
tg.runFail("build", "./testdata/importcom/conflict.go")
tg.grepStderr("found import comments", "go build did not mention comment conflict")
}
func TestImportCycle(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcycle"))
tg.runFail("build", "selfimport")
count := tg.grepCountBoth("import cycle not allowed")
if count == 0 {
t.Fatal("go build did not mention cyclical import")
}
if count > 1 {
t.Fatal("go build mentioned import cycle more than once")
}
}
// cmd/go: custom import path checking should not apply to Go packages without import comment.
func TestIssue10952(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
if _, err := exec.LookPath("git"); err != nil {
t.Skip("skipping because git binary not found")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src")
tg.setenv("GOPATH", tg.path("."))
const importPath = "github.com/zombiezen/go-get-issue-10952"
tg.run("get", "-d", "-u", importPath)
repoDir := tg.path("src/" + importPath)
tg.runGit(repoDir, "remote", "set-url", "origin", "https://"+importPath+".git")
tg.run("get", "-d", "-u", importPath)
}
func TestIssue16471(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
if _, err := exec.LookPath("git"); err != nil {
t.Skip("skipping because git binary not found")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src")
tg.setenv("GOPATH", tg.path("."))
tg.must(os.MkdirAll(tg.path("src/rsc.io/go-get-issue-10952"), 0755))
tg.runGit(tg.path("src/rsc.io"), "clone", "https://github.com/zombiezen/go-get-issue-10952")
tg.runFail("get", "-u", "rsc.io/go-get-issue-10952")
tg.grepStderr("rsc.io/go-get-issue-10952 is a custom import path for https://github.com/rsc/go-get-issue-10952, but .* is checked out from https://github.com/zombiezen/go-get-issue-10952", "did not detect updated import path")
}
// Test git clone URL that uses SCP-like syntax and custom import path checking.
func TestIssue11457(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
if _, err := exec.LookPath("git"); err != nil {
t.Skip("skipping because git binary not found")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src")
tg.setenv("GOPATH", tg.path("."))
const importPath = "rsc.io/go-get-issue-11457"
tg.run("get", "-d", "-u", importPath)
repoDir := tg.path("src/" + importPath)
tg.runGit(repoDir, "remote", "set-url", "origin", "[email protected]:rsc/go-get-issue-11457")
// At this time, custom import path checking compares remotes verbatim (rather than
// just the host and path, skipping scheme and user), so we expect go get -u to fail.
// However, the goal of this test is to verify that gitRemoteRepo correctly parsed
// the SCP-like syntax, and we expect it to appear in the error message.
tg.runFail("get", "-d", "-u", importPath)
want := " is checked out from ssh://[email protected]/rsc/go-get-issue-11457"
if !strings.HasSuffix(strings.TrimSpace(tg.getStderr()), want) {
t.Error("expected clone URL to appear in stderr")
}
}
func TestGetGitDefaultBranch(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
if _, err := exec.LookPath("git"); err != nil {
t.Skip("skipping because git binary not found")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src")
tg.setenv("GOPATH", tg.path("."))
// This repo has two branches, master and another-branch.
// The another-branch is the default that you get from 'git clone'.
// The go get command variants should not override this.
const importPath = "github.com/rsc/go-get-default-branch"
tg.run("get", "-d", importPath)
repoDir := tg.path("src/" + importPath)
tg.runGit(repoDir, "branch", "--contains", "HEAD")
tg.grepStdout(`\* another-branch`, "not on correct default branch")
tg.run("get", "-d", "-u", importPath)
tg.runGit(repoDir, "branch", "--contains", "HEAD")
tg.grepStdout(`\* another-branch`, "not on correct default branch")
}
func TestAccidentalGitCheckout(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
if _, err := exec.LookPath("git"); err != nil {
t.Skip("skipping because git binary not found")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src")
tg.setenv("GOPATH", tg.path("."))
tg.runFail("get", "-u", "vcs-test.golang.org/go/test1-svn-git")
tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
tg.runFail("get", "-u", "vcs-test.golang.org/go/test2-svn-git/test2main")
tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
}
func TestErrorMessageForSyntaxErrorInTestGoFileSaysFAIL(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("test", "syntaxerror")
tg.grepStderr("FAIL", "go test did not say FAIL")
}
func TestWildcardsDoNotLookInUselessDirectories(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("list", "...")
tg.grepBoth("badpkg", "go list ... failure does not mention badpkg")
tg.run("list", "m...")
}
func TestRelativeImportsGoTest(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "./testdata/testimport")
}
func TestRelativeImportsGoTestDashI(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// don't let test -i overwrite runtime
tg.wantNotStale("runtime", "", "must be non-stale before test -i")
tg.run("test", "-i", "./testdata/testimport")
}
func TestRelativeImportsInCommandLinePackage(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
files, err := filepath.Glob("./testdata/testimport/*.go")
tg.must(err)
tg.run(append([]string{"test"}, files...)...)
}
func TestNonCanonicalImportPaths(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("build", "canonical/d")
tg.grepStderr("package canonical/d", "did not report canonical/d")
tg.grepStderr("imports canonical/b", "did not report canonical/b")
tg.grepStderr("imports canonical/a/: non-canonical", "did not report canonical/a/")
}
func TestVersionControlErrorMessageIncludesCorrectDirectory(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/shadow/root1"))
tg.runFail("get", "-u", "foo")
// TODO(iant): We should not have to use strconv.Quote here.
// The code in vcs.go should be changed so that it is not required.
quoted := strconv.Quote(filepath.Join("testdata", "shadow", "root1", "src", "foo"))
quoted = quoted[1 : len(quoted)-1]
tg.grepStderr(regexp.QuoteMeta(quoted), "go get -u error does not mention shadow/root1/src/foo")
}
func TestInstallFailsWithNoBuildableFiles(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.setenv("CGO_ENABLED", "0")
tg.runFail("install", "cgotest")
tg.grepStderr("build constraints exclude all Go files", "go install cgotest did not report 'build constraints exclude all Go files'")
}
// Issue 21895
func TestMSanAndRaceRequireCgo(t *testing.T) {
if !canMSan && !canRace {
t.Skip("skipping because both msan and the race detector are not supported")
}
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("triv.go", `package main; func main() {}`)
tg.setenv("CGO_ENABLED", "0")
if canRace {
tg.runFail("install", "-race", "triv.go")
tg.grepStderr("-race requires cgo", "did not correctly report that -race requires cgo")
tg.grepStderrNot("-msan", "reported that -msan instead of -race requires cgo")
}
if canMSan {
tg.runFail("install", "-msan", "triv.go")
tg.grepStderr("-msan requires cgo", "did not correctly report that -msan requires cgo")
tg.grepStderrNot("-race", "reported that -race instead of -msan requires cgo")
}
}
func TestRelativeGOBINFail(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("triv.go", `package main; func main() {}`)
tg.setenv("GOBIN", ".")
tg.runFail("install")
tg.grepStderr("cannot install, GOBIN must be an absolute path", "go install must fail if $GOBIN is a relative path")
}
// Test that without $GOBIN set, binaries get installed
// into the GOPATH bin directory.
func TestInstallIntoGOPATH(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("install", "go-cmd-test")
tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
}
// Issue 12407
func TestBuildOutputToDevNull(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("build", "-o", os.DevNull, "go-cmd-test")
}
func TestPackageMainTestImportsArchiveNotBinary(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
gobin := filepath.Join(tg.pwd(), "testdata", "bin")
tg.creatingTemp(gobin)
tg.setenv("GOBIN", gobin)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.must(os.Chtimes("./testdata/src/main_test/m.go", time.Now(), time.Now()))
tg.sleep()
tg.run("test", "main_test")
tg.run("install", "main_test")
tg.wantNotStale("main_test", "", "after go install, main listed as stale")
tg.run("test", "main_test")
}
func TestPackageMainTestCompilerFlags(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.tempFile("src/p1/p1.go", "package main\n")
tg.tempFile("src/p1/p1_test.go", "package main\nimport \"testing\"\nfunc Test(t *testing.T){}\n")
tg.run("test", "-c", "-n", "p1")
tg.grepBothNot(`[\\/]compile.* -p main.*p1\.go`, "should not have run compile -p main p1.go")
tg.grepStderr(`[\\/]compile.* -p p1.*p1\.go`, "should have run compile -p p1 p1.go")
}
// The runtime version string takes one of two forms:
// "go1.X[.Y]" for Go releases, and "devel +hash" at tip.
// Determine whether we are in a released copy by
// inspecting the version.
var isGoRelease = strings.HasPrefix(runtime.Version(), "go1")
// Issue 12690
func TestPackageNotStaleWithTrailingSlash(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// Make sure the packages below are not stale.
tg.wantNotStale("runtime", "", "must be non-stale before test runs")
tg.wantNotStale("os", "", "must be non-stale before test runs")
tg.wantNotStale("io", "", "must be non-stale before test runs")
goroot := runtime.GOROOT()
tg.setenv("GOROOT", goroot+"/")
tg.wantNotStale("runtime", "", "with trailing slash in GOROOT, runtime listed as stale")
tg.wantNotStale("os", "", "with trailing slash in GOROOT, os listed as stale")
tg.wantNotStale("io", "", "with trailing slash in GOROOT, io listed as stale")
}
// With $GOBIN set, binaries get installed to $GOBIN.
func TestInstallIntoGOBIN(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
tg.creatingTemp(gobin)
tg.setenv("GOBIN", gobin)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("install", "go-cmd-test")
tg.wantExecutable("testdata/bin1/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin1/go-cmd-test")
}
// Issue 11065
func TestInstallToCurrentDirectoryCreatesExecutable(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
pkg := filepath.Join(tg.pwd(), "testdata", "src", "go-cmd-test")
tg.creatingTemp(filepath.Join(pkg, "go-cmd-test"+exeSuffix))
tg.setenv("GOBIN", pkg)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.cd(pkg)
tg.run("install")
tg.wantExecutable("go-cmd-test"+exeSuffix, "go install did not write to current directory")
}
// Without $GOBIN set, installing a program outside $GOPATH should fail
// (there is nowhere to install it).
func TestInstallWithoutDestinationFails(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.runFail("install", "testdata/src/go-cmd-test/helloworld.go")
tg.grepStderr("no install location for .go files listed on command line", "wrong error")
}
// With $GOBIN set, should install there.
func TestInstallToGOBINCommandLinePackage(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
tg.creatingTemp(gobin)
tg.setenv("GOBIN", gobin)
tg.run("install", "testdata/src/go-cmd-test/helloworld.go")
tg.wantExecutable("testdata/bin1/helloworld"+exeSuffix, "go install testdata/src/go-cmd-test/helloworld.go did not write testdata/bin1/helloworld")
}
func TestGoGetNonPkg(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.tempDir("gobin")
tg.setenv("GOPATH", tg.path("."))
tg.setenv("GOBIN", tg.path("gobin"))
tg.runFail("get", "-d", "golang.org/x/tools")
tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
tg.runFail("get", "-d", "-u", "golang.org/x/tools")
tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
tg.runFail("get", "-d", "golang.org/x/tools")
tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
}
func TestGoGetTestOnlyPkg(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.tempDir("gopath")
tg.setenv("GOPATH", tg.path("gopath"))
tg.run("get", "golang.org/x/tour/content")
tg.run("get", "-t", "golang.org/x/tour/content")
}
func TestInstalls(t *testing.T) {
if testing.Short() {
t.Skip("don't install into GOROOT in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("gobin")
tg.setenv("GOPATH", tg.path("."))
goroot := runtime.GOROOT()
tg.setenv("GOROOT", goroot)
// cmd/fix installs into tool
tg.run("env", "GOOS")
goos := strings.TrimSpace(tg.getStdout())
tg.setenv("GOOS", goos)
tg.run("env", "GOARCH")
goarch := strings.TrimSpace(tg.getStdout())
tg.setenv("GOARCH", goarch)
fixbin := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch, "fix") + exeSuffix
tg.must(os.RemoveAll(fixbin))
tg.run("install", "cmd/fix")
tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool")
tg.must(os.Remove(fixbin))
tg.setenv("GOBIN", tg.path("gobin"))
tg.run("install", "cmd/fix")
tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool with $GOBIN set")
tg.unsetenv("GOBIN")
// gopath program installs into GOBIN
tg.tempFile("src/progname/p.go", `package main; func main() {}`)
tg.setenv("GOBIN", tg.path("gobin"))
tg.run("install", "progname")
tg.unsetenv("GOBIN")
tg.wantExecutable(tg.path("gobin/progname")+exeSuffix, "did not install progname to $GOBIN/progname")
// gopath program installs into GOPATH/bin
tg.run("install", "progname")
tg.wantExecutable(tg.path("bin/progname")+exeSuffix, "did not install progname to $GOPATH/bin/progname")
}
func TestRejectRelativeDotPathInGOPATHCommandLinePackage(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", ".")
tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
}
func TestRejectRelativePathsInGOPATH(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", sep+filepath.Join(tg.pwd(), "testdata")+sep+".")
tg.runFail("build", "go-cmd-test")
tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
}
func TestRejectRelativePathsInGOPATHCommandLinePackage(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", "testdata")
tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
}
// Issue 21928.
func TestRejectBlankPathsInGOPATH(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", " "+sep+filepath.Join(tg.pwd(), "testdata"))
tg.runFail("build", "go-cmd-test")
tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
}
// Issue 21928.
func TestIgnoreEmptyPathsInGOPATH(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", ""+sep+filepath.Join(tg.pwd(), "testdata"))
tg.run("install", "go-cmd-test")
tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
}
// Issue 4104.
func TestGoTestWithPackageListedMultipleTimes(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.run("test", "errors", "errors", "errors", "errors", "errors")
if strings.Contains(strings.TrimSpace(tg.getStdout()), "\n") {
t.Error("go test errors errors errors errors errors tested the same package multiple times")
}
}
func TestGoListHasAConsistentOrder(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.run("list", "std")
first := tg.getStdout()
tg.run("list", "std")
if first != tg.getStdout() {
t.Error("go list std ordering is inconsistent")
}
}
func TestGoListStdDoesNotIncludeCommands(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.run("list", "std")
tg.grepStdoutNot("cmd/", "go list std shows commands")
}
func TestGoListCmdOnlyShowsCommands(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.run("list", "cmd")
out := strings.TrimSpace(tg.getStdout())
for _, line := range strings.Split(out, "\n") {
if !strings.Contains(line, "cmd/") {
t.Error("go list cmd shows non-commands")
break
}
}
}
func TestGoListDedupsPackages(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("list", "xtestonly", "./testdata/src/xtestonly/...")
got := strings.TrimSpace(tg.getStdout())
const want = "xtestonly"
if got != want {
t.Errorf("got %q; want %q", got, want)
}
}
func TestGoListDeps(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src/p1/p2/p3/p4")
tg.setenv("GOPATH", tg.path("."))
tg.tempFile("src/p1/p.go", "package p1\nimport _ \"p1/p2\"\n")
tg.tempFile("src/p1/p2/p.go", "package p2\nimport _ \"p1/p2/p3\"\n")
tg.tempFile("src/p1/p2/p3/p.go", "package p3\nimport _ \"p1/p2/p3/p4\"\n")
tg.tempFile("src/p1/p2/p3/p4/p.go", "package p4\n")
tg.run("list", "-f", "{{.Deps}}", "p1")
tg.grepStdout("p1/p2/p3/p4", "Deps(p1) does not mention p4")
}
// Issue 4096. Validate the output of unsuccessful go install foo/quxx.
func TestUnsuccessfulGoInstallShouldMentionMissingPackage(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.runFail("install", "foo/quxx")
if tg.grepCountBoth(`cannot find package "foo/quxx" in any of`) != 1 {
t.Error(`go install foo/quxx expected error: .*cannot find package "foo/quxx" in any of`)
}
}
func TestGOROOTSearchFailureReporting(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.runFail("install", "foo/quxx")
if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("foo", "quxx"))+` \(from \$GOROOT\)$`) != 1 {
t.Error(`go install foo/quxx expected error: .*foo/quxx (from $GOROOT)`)
}
}
func TestMultipleGOPATHEntriesReportedSeparately(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
tg.runFail("install", "foo/quxx")
if tg.grepCountBoth(`testdata[/\\].[/\\]src[/\\]foo[/\\]quxx`) != 2 {
t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)\n.*testdata/b/src/foo/quxx`)
}
}
// Test (from $GOPATH) annotation is reported for the first GOPATH entry,
func TestMentionGOPATHInFirstGOPATHEntry(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
tg.runFail("install", "foo/quxx")
if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "a", "src", "foo", "quxx"))+` \(from \$GOPATH\)$`) != 1 {
t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)`)
}
}
// but not on the second.
func TestMentionGOPATHNotOnSecondEntry(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
tg.runFail("install", "foo/quxx")
if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "b", "src", "foo", "quxx"))+`$`) != 1 {
t.Error(`go install foo/quxx expected error: .*testdata/b/src/foo/quxx`)
}
}
func homeEnvName() string {
switch runtime.GOOS {
case "windows":
return "USERPROFILE"
case "plan9":
return "home"
default:
return "HOME"
}
}
func TestDefaultGOPATH(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("home/go")
tg.setenv(homeEnvName(), tg.path("home"))
tg.run("env", "GOPATH")
tg.grepStdout(regexp.QuoteMeta(tg.path("home/go")), "want GOPATH=$HOME/go")
tg.setenv("GOROOT", tg.path("home/go"))
tg.run("env", "GOPATH")
tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go")
tg.setenv("GOROOT", tg.path("home/go")+"/")
tg.run("env", "GOPATH")
tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go/")
}
func TestDefaultGOPATHGet(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", "")
tg.tempDir("home")
tg.setenv(homeEnvName(), tg.path("home"))
// warn for creating directory
tg.run("get", "-v", "github.com/golang/example/hello")
tg.grepStderr("created GOPATH="+regexp.QuoteMeta(tg.path("home/go"))+"; see 'go help gopath'", "did not create GOPATH")
// no warning if directory already exists
tg.must(os.RemoveAll(tg.path("home/go")))
tg.tempDir("home/go")
tg.run("get", "github.com/golang/example/hello")
tg.grepStderrNot(".", "expected no output on standard error")
// error if $HOME/go is a file
tg.must(os.RemoveAll(tg.path("home/go")))
tg.tempFile("home/go", "")
tg.runFail("get", "github.com/golang/example/hello")
tg.grepStderr(`mkdir .*[/\\]go: .*(not a directory|cannot find the path)`, "expected error because $HOME/go is a file")
}
func TestDefaultGOPATHPrintedSearchList(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", "")
tg.tempDir("home")
tg.setenv(homeEnvName(), tg.path("home"))
tg.runFail("install", "github.com/golang/example/hello")
tg.grepStderr(regexp.QuoteMeta(tg.path("home/go/src/github.com/golang/example/hello"))+`.*from \$GOPATH`, "expected default GOPATH")
}
// Issue 4186. go get cannot be used to download packages to $GOROOT.
// Test that without GOPATH set, go get should fail.
func TestGoGetIntoGOROOT(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src")
// Fails because GOROOT=GOPATH
tg.setenv("GOPATH", tg.path("."))
tg.setenv("GOROOT", tg.path("."))
tg.runFail("get", "-d", "github.com/golang/example/hello")
tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
// Fails because GOROOT=GOPATH after cleaning.
tg.setenv("GOPATH", tg.path(".")+"/")
tg.setenv("GOROOT", tg.path("."))
tg.runFail("get", "-d", "github.com/golang/example/hello")
tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
tg.setenv("GOPATH", tg.path("."))
tg.setenv("GOROOT", tg.path(".")+"/")
tg.runFail("get", "-d", "github.com/golang/example/hello")
tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
// Fails because GOROOT=$HOME/go so default GOPATH unset.
tg.tempDir("home/go")
tg.setenv(homeEnvName(), tg.path("home"))
tg.setenv("GOPATH", "")
tg.setenv("GOROOT", tg.path("home/go"))
tg.runFail("get", "-d", "github.com/golang/example/hello")
tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
tg.setenv(homeEnvName(), tg.path("home")+"/")
tg.setenv("GOPATH", "")
tg.setenv("GOROOT", tg.path("home/go"))
tg.runFail("get", "-d", "github.com/golang/example/hello")
tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
tg.setenv(homeEnvName(), tg.path("home"))
tg.setenv("GOPATH", "")
tg.setenv("GOROOT", tg.path("home/go")+"/")
tg.runFail("get", "-d", "github.com/golang/example/hello")
tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
}
func TestLdflagsArgumentsWithSpacesIssue3941(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("main.go", `package main
var extern string
func main() {
println(extern)
}`)
tg.run("run", "-ldflags", `-X "main.extern=hello world"`, tg.path("main.go"))
tg.grepStderr("^hello world", `ldflags -X "main.extern=hello world"' failed`)
}
func TestGoTestCpuprofileLeavesBinaryBehind(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.makeTempdir()
tg.cd(tg.path("."))
tg.run("test", "-cpuprofile", "errors.prof", "errors")
tg.wantExecutable("errors.test"+exeSuffix, "go test -cpuprofile did not create errors.test")
}
func TestGoTestCpuprofileDashOControlsBinaryLocation(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.makeTempdir()
tg.cd(tg.path("."))
tg.run("test", "-cpuprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
tg.wantExecutable("myerrors.test"+exeSuffix, "go test -cpuprofile -o myerrors.test did not create myerrors.test")
}
func TestGoTestMutexprofileLeavesBinaryBehind(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.makeTempdir()
tg.cd(tg.path("."))
tg.run("test", "-mutexprofile", "errors.prof", "errors")
tg.wantExecutable("errors.test"+exeSuffix, "go test -mutexprofile did not create errors.test")
}
func TestGoTestMutexprofileDashOControlsBinaryLocation(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.makeTempdir()
tg.cd(tg.path("."))
tg.run("test", "-mutexprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
tg.wantExecutable("myerrors.test"+exeSuffix, "go test -mutexprofile -o myerrors.test did not create myerrors.test")
}
func TestGoBuildNonMain(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("build", "-buildmode=exe", "-o", "not_main"+exeSuffix, "not_main")
tg.grepStderr("-buildmode=exe requires exactly one main package", "go build with -o and -buildmode=exe should on a non-main package should throw an error")
tg.mustNotExist("not_main" + exeSuffix)
}
func TestGoTestDashCDashOControlsBinaryLocation(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.run("test", "-c", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -c -o myerrors.test did not create myerrors.test")
}
func TestGoTestDashOWritesBinary(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.run("test", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
}
func TestGoTestDashIDashOWritesBinary(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
// don't let test -i overwrite runtime
tg.wantNotStale("runtime", "", "must be non-stale before test -i")
tg.run("test", "-v", "-i", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
tg.grepBothNot("PASS|FAIL", "test should not have run")
tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
}
// Issue 4568.
func TestSymlinksList(t *testing.T) {
testenv.MustHaveSymlink(t)
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.tempDir("src")
tg.must(os.Symlink(tg.path("."), tg.path("src/dir1")))
tg.tempFile("src/dir1/p.go", "package p")
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("src"))
tg.run("list", "-f", "{{.Root}}", "dir1")
if strings.TrimSpace(tg.getStdout()) != tg.path(".") {
t.Error("confused by symlinks")
}
}
// Issue 14054.
func TestSymlinksVendor(t *testing.T) {
testenv.MustHaveSymlink(t)
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.tempDir("gopath/src/dir1/vendor/v")
tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `v`\nfunc main(){}")
tg.tempFile("gopath/src/dir1/vendor/v/v.go", "package v")
tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
tg.setenv("GOPATH", tg.path("gopath"))
tg.cd(tg.path("symdir1"))
tg.run("list", "-f", "{{.Root}}", ".")
if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
t.Error("list confused by symlinks")
}
// All of these should succeed, not die in vendor-handling code.
tg.run("run", "p.go")
tg.run("build")
tg.run("install")
}
// Issue 15201.
func TestSymlinksVendor15201(t *testing.T) {
testenv.MustHaveSymlink(t)
tg := testgo(t)
defer tg.cleanup()
tg.tempDir("gopath/src/x/y/_vendor/src/x")
tg.must(os.Symlink("../../..", tg.path("gopath/src/x/y/_vendor/src/x/y")))
tg.tempFile("gopath/src/x/y/w/w.go", "package w\nimport \"x/y/z\"\n")
tg.must(os.Symlink("../_vendor/src", tg.path("gopath/src/x/y/w/vendor")))
tg.tempFile("gopath/src/x/y/z/z.go", "package z\n")
tg.setenv("GOPATH", tg.path("gopath/src/x/y/_vendor")+string(filepath.ListSeparator)+tg.path("gopath"))
tg.cd(tg.path("gopath/src"))
tg.run("list", "./...")
}
func TestSymlinksInternal(t *testing.T) {
testenv.MustHaveSymlink(t)
tg := testgo(t)
defer tg.cleanup()
tg.tempDir("gopath/src/dir1/internal/v")
tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `dir1/internal/v`\nfunc main(){}")
tg.tempFile("gopath/src/dir1/internal/v/v.go", "package v")
tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
tg.setenv("GOPATH", tg.path("gopath"))
tg.cd(tg.path("symdir1"))
tg.run("list", "-f", "{{.Root}}", ".")
if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
t.Error("list confused by symlinks")
}
// All of these should succeed, not die in internal-handling code.
tg.run("run", "p.go")
tg.run("build")
tg.run("install")
}
// Issue 4515.
func TestInstallWithTags(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("bin")
tg.tempFile("src/example/a/main.go", `package main
func main() {}`)
tg.tempFile("src/example/b/main.go", `// +build mytag
package main
func main() {}`)
tg.setenv("GOPATH", tg.path("."))
tg.run("install", "-tags", "mytag", "example/a", "example/b")
tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/a example/b did not install binaries")
tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/a example/b did not install binaries")
tg.must(os.Remove(tg.path("bin/a" + exeSuffix)))
tg.must(os.Remove(tg.path("bin/b" + exeSuffix)))
tg.run("install", "-tags", "mytag", "example/...")
tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/... did not install binaries")
tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/... did not install binaries")
tg.run("list", "-tags", "mytag", "example/b...")
if strings.TrimSpace(tg.getStdout()) != "example/b" {
t.Error("go list example/b did not find example/b")
}
}
// Issue 4773
func TestCaseCollisions(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src/example/a/pkg")
tg.tempDir("src/example/a/Pkg")
tg.tempDir("src/example/b")
tg.setenv("GOPATH", tg.path("."))
tg.tempFile("src/example/a/a.go", `package p
import (
_ "example/a/pkg"
_ "example/a/Pkg"
)`)
tg.tempFile("src/example/a/pkg/pkg.go", `package pkg`)
tg.tempFile("src/example/a/Pkg/pkg.go", `package pkg`)
tg.run("list", "-json", "example/a")
tg.grepStdout("case-insensitive import collision", "go list -json example/a did not report import collision")
tg.runFail("build", "example/a")
tg.grepStderr("case-insensitive import collision", "go build example/a did not report import collision")
tg.tempFile("src/example/b/file.go", `package b`)
tg.tempFile("src/example/b/FILE.go", `package b`)
f, err := os.Open(tg.path("src/example/b"))
tg.must(err)
names, err := f.Readdirnames(0)
tg.must(err)
tg.check(f.Close())
args := []string{"list"}
if len(names) == 2 {
// case-sensitive file system, let directory read find both files
args = append(args, "example/b")
} else {
// case-insensitive file system, list files explicitly on command line
args = append(args, tg.path("src/example/b/file.go"), tg.path("src/example/b/FILE.go"))
}
tg.runFail(args...)
tg.grepStderr("case-insensitive file name collision", "go list example/b did not report file name collision")
tg.runFail("list", "example/a/pkg", "example/a/Pkg")
tg.grepStderr("case-insensitive import collision", "go list example/a/pkg example/a/Pkg did not report import collision")
tg.run("list", "-json", "-e", "example/a/pkg", "example/a/Pkg")
tg.grepStdout("case-insensitive import collision", "go list -json -e example/a/pkg example/a/Pkg did not report import collision")
tg.runFail("build", "example/a/pkg", "example/a/Pkg")
tg.grepStderr("case-insensitive import collision", "go build example/a/pkg example/a/Pkg did not report import collision")
}
// Issue 17451, 17662.
func TestSymlinkWarning(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.tempDir("src/example/xx")
tg.tempDir("yy/zz")
tg.tempFile("yy/zz/zz.go", "package zz\n")
if err := os.Symlink(tg.path("yy"), tg.path("src/example/xx/yy")); err != nil {
t.Skipf("symlink failed: %v", err)
}
tg.run("list", "example/xx/z...")
tg.grepStdoutNot(".", "list should not have matched anything")
tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
tg.grepStderrNot("symlink", "list should not have reported symlink")
tg.run("list", "example/xx/...")
tg.grepStdoutNot(".", "list should not have matched anything")
tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
tg.grepStderr("ignoring symlink", "list should have reported symlink")
}
// Issue 8181.
func TestGoGetDashTIssue8181(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.run("get", "-v", "-t", "github.com/rsc/go-get-issue-8181/a", "github.com/rsc/go-get-issue-8181/b")
tg.run("list", "...")
tg.grepStdout("x/build/gerrit", "missing expected x/build/gerrit")
}
func TestIssue11307(t *testing.T) {
// go get -u was not working except in checkout directory
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.run("get", "github.com/rsc/go-get-issue-11307")
tg.run("get", "-u", "github.com/rsc/go-get-issue-11307") // was failing
}
func TestShadowingLogic(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
pwd := tg.pwd()
sep := string(filepath.ListSeparator)
tg.setenv("GOPATH", filepath.Join(pwd, "testdata", "shadow", "root1")+sep+filepath.Join(pwd, "testdata", "shadow", "root2"))
// The math in root1 is not "math" because the standard math is.
tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/math")
pwdForwardSlash := strings.Replace(pwd, string(os.PathSeparator), "/", -1)
if !strings.HasPrefix(pwdForwardSlash, "/") {
pwdForwardSlash = "/" + pwdForwardSlash
}
// The output will have makeImportValid applies, but we only
// bother to deal with characters we might reasonably see.
for _, r := range " :" {
pwdForwardSlash = strings.Replace(pwdForwardSlash, string(r), "_", -1)
}
want := "(_" + pwdForwardSlash + "/testdata/shadow/root1/src/math) (" + filepath.Join(runtime.GOROOT(), "src", "math") + ")"
if strings.TrimSpace(tg.getStdout()) != want {
t.Error("shadowed math is not shadowed; looking for", want)
}
// The foo in root1 is "foo".
tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/foo")
if strings.TrimSpace(tg.getStdout()) != "(foo) ()" {
t.Error("unshadowed foo is shadowed")
}
// The foo in root2 is not "foo" because the foo in root1 got there first.
tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root2/src/foo")
want = "(_" + pwdForwardSlash + "/testdata/shadow/root2/src/foo) (" + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo") + ")"
if strings.TrimSpace(tg.getStdout()) != want {
t.Error("shadowed foo is not shadowed; looking for", want)
}
// The error for go install should mention the conflicting directory.
tg.runFail("install", "./testdata/shadow/root2/src/foo")
want = "go install: no install location for " + filepath.Join(pwd, "testdata", "shadow", "root2", "src", "foo") + ": hidden by " + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo")
if strings.TrimSpace(tg.getStderr()) != want {
t.Error("wrong shadowed install error; looking for", want)
}
}
// Only succeeds if source order is preserved.
func TestSourceFileNameOrderPreserved(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "testdata/example1_test.go", "testdata/example2_test.go")
}
// Check that coverage analysis works at all.
// Don't worry about the exact numbers but require not 0.0%.
func checkCoverage(tg *testgoData, data string) {
tg.t.Helper()
if regexp.MustCompile(`[^0-9]0\.0%`).MatchString(data) {
tg.t.Error("some coverage results are 0.0%")
}
}
func TestCoverageRuns(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-short", "-coverpkg=strings", "strings", "regexp")
data := tg.getStdout() + tg.getStderr()
tg.run("test", "-short", "-cover", "strings", "math", "regexp")
data += tg.getStdout() + tg.getStderr()
checkCoverage(tg, data)
}
func TestCoverageDotImport(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "-coverpkg=coverdot1,coverdot2", "coverdot2")
data := tg.getStdout() + tg.getStderr()
checkCoverage(tg, data)
}
// Check that coverage analysis uses set mode.
// Also check that coverage profiles merge correctly.
func TestCoverageUsesSetMode(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.creatingTemp("testdata/cover.out")
tg.run("test", "-short", "-cover", "encoding/binary", "errors", "-coverprofile=testdata/cover.out")
data := tg.getStdout() + tg.getStderr()
if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
t.Error(err)
} else {
if !bytes.Contains(out, []byte("mode: set")) {
t.Error("missing mode: set")
}
if !bytes.Contains(out, []byte("errors.go")) {
t.Error("missing errors.go")
}
if !bytes.Contains(out, []byte("binary.go")) {
t.Error("missing binary.go")
}
if bytes.Count(out, []byte("mode: set")) != 1 {
t.Error("too many mode: set")
}
}
checkCoverage(tg, data)
}
func TestCoverageUsesAtomicModeForRace(t *testing.T) {
tooSlow(t)
if !canRace {
t.Skip("skipping because race detector not supported")
}
tg := testgo(t)
defer tg.cleanup()
tg.creatingTemp("testdata/cover.out")
tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
data := tg.getStdout() + tg.getStderr()
if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
t.Error(err)
} else {
if !bytes.Contains(out, []byte("mode: atomic")) {
t.Error("missing mode: atomic")
}
}
checkCoverage(tg, data)
}
func TestCoverageSyncAtomicImport(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "-short", "-cover", "-covermode=atomic", "-coverpkg=coverdep/p1", "coverdep")
}
func TestCoverageDepLoop(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
// coverdep2/p1's xtest imports coverdep2/p2 which imports coverdep2/p1.
// Make sure that coverage on coverdep2/p2 recompiles coverdep2/p2.
tg.run("test", "-short", "-cover", "coverdep2/p1")
tg.grepStdout("coverage: 100.0% of statements", "expected 100.0% coverage")
}
func TestCoverageImportMainLoop(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("test", "importmain/test")
tg.grepStderr("not an importable package", "did not detect import main")
tg.runFail("test", "-cover", "importmain/test")
tg.grepStderr("not an importable package", "did not detect import main")
}
func TestCoveragePattern(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
// If coverpkg=sleepy... expands by package loading
// (as opposed to pattern matching on deps)
// then it will try to load sleepybad, which does not compile,
// and the test command will fail.
tg.run("test", "-coverprofile="+tg.path("cover.out"), "-coverpkg=sleepy...", "-run=^$", "sleepy1")
}
func TestCoverageErrorLine(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.setenv("GOTMPDIR", tg.tempdir)
tg.runFail("test", "coverbad")
tg.grepStderr(`coverbad[\\/]p\.go:4`, "did not find coverbad/p.go:4")
if canCgo {
tg.grepStderr(`coverbad[\\/]p1\.go:6`, "did not find coverbad/p1.go:6")
}
tg.grepStderrNot(regexp.QuoteMeta(tg.tempdir), "found temporary directory in error")
stderr := tg.getStderr()
tg.runFail("test", "-cover", "coverbad")
stderr2 := tg.getStderr()
// It's OK that stderr2 drops the character position in the error,
// because of the //line directive (see golang.org/issue/22662).
stderr = strings.Replace(stderr, "p.go:4:2:", "p.go:4:", -1)
if stderr != stderr2 {
t.Logf("test -cover changed error messages:\nbefore:\n%s\n\nafter:\n%s", stderr, stderr2)
t.Skip("golang.org/issue/22660")
t.FailNow()
}
}
func TestTestBuildFailureOutput(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
// Doesn't build, -x output should not claim to run test.
tg.runFail("test", "-x", "coverbad")
tg.grepStderrNot(`[\\/]coverbad\.test( |$)`, "claimed to run test")
}
func TestCoverageFunc(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "-outputdir="+tg.tempdir, "-coverprofile=cover.out", "coverasm")
tg.run("tool", "cover", "-func="+tg.path("cover.out"))
tg.grepStdout(`\tg\t*100.0%`, "did not find g 100% covered")
tg.grepStdoutNot(`\tf\t*[0-9]`, "reported coverage for assembly function f")
}
// Issue 24588.
func TestCoverageDashC(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "-c", "-o", tg.path("coverdep"), "-coverprofile="+tg.path("no/such/dir/cover.out"), "coverdep")
tg.wantExecutable(tg.path("coverdep"), "go -test -c -coverprofile did not create executable")
}
func TestPluginNonMain(t *testing.T) {
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
pkg := filepath.Join(wd, "testdata", "testdep", "p2")
tg := testgo(t)
defer tg.cleanup()
tg.runFail("build", "-buildmode=plugin", pkg)
}
func TestTestEmpty(t *testing.T) {
if !canRace {
t.Skip("no race detector")
}
wd, _ := os.Getwd()
testdata := filepath.Join(wd, "testdata")
for _, dir := range []string{"pkg", "test", "xtest", "pkgtest", "pkgxtest", "pkgtestxtest", "testxtest"} {
t.Run(dir, func(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", testdata)
tg.cd(filepath.Join(testdata, "src/empty/"+dir))
tg.run("test", "-cover", "-coverpkg=.", "-race")
})
if testing.Short() {
break
}
}
}
func TestNoGoError(t *testing.T) {
wd, _ := os.Getwd()
testdata := filepath.Join(wd, "testdata")
for _, dir := range []string{"empty/test", "empty/xtest", "empty/testxtest", "exclude", "exclude/ignore", "exclude/empty"} {
t.Run(dir, func(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", testdata)
tg.cd(filepath.Join(testdata, "src"))
tg.runFail("build", "./"+dir)
var want string
if strings.Contains(dir, "test") {
want = "no non-test Go files in "
} else if dir == "exclude" {
want = "build constraints exclude all Go files in "
} else {
want = "no Go files in "
}
tg.grepStderr(want, "wrong reason for failure")
})
}
}
func TestTestRaceInstall(t *testing.T) {
if !canRace {
t.Skip("no race detector")
}
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.tempDir("pkg")
pkgdir := tg.path("pkg")
tg.run("install", "-race", "-pkgdir="+pkgdir, "std")
tg.run("test", "-race", "-pkgdir="+pkgdir, "-i", "-v", "empty/pkg")
if tg.getStderr() != "" {
t.Error("go test -i -race: rebuilds cached packages")
}
}
func TestBuildDryRunWithCgo(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("foo.go", `package main
/*
#include <limits.h>
*/
import "C"
func main() {
println(C.INT_MAX)
}`)
tg.run("build", "-n", tg.path("foo.go"))
tg.grepStderrNot(`os.Stat .* no such file or directory`, "unexpected stat of archive file")
}
func TestCoverageWithCgo(t *testing.T) {
tooSlow(t)
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
for _, dir := range []string{"cgocover", "cgocover2", "cgocover3", "cgocover4"} {
t.Run(dir, func(t *testing.T) {
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "-short", "-cover", dir)
data := tg.getStdout() + tg.getStderr()
checkCoverage(tg, data)
})
}
}
func TestCgoAsmError(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("build", "cgoasm")
tg.grepBoth("package using cgo has Go assembly file", "did not detect Go assembly file")
}
func TestCgoDependsOnSyscall(t *testing.T) {
if testing.Short() {
t.Skip("skipping test that removes $GOROOT/pkg/*_race in short mode")
}
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
if !canRace {
t.Skip("skipping because race detector not supported")
}
tg := testgo(t)
defer tg.cleanup()
files, err := filepath.Glob(filepath.Join(runtime.GOROOT(), "pkg", "*_race"))
tg.must(err)
for _, file := range files {
tg.check(os.RemoveAll(file))
}
tg.tempFile("src/foo/foo.go", `
package foo
//#include <stdio.h>
import "C"`)
tg.setenv("GOPATH", tg.path("."))
tg.run("build", "-race", "foo")
}
func TestCgoShowsFullPathNames(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/x/y/dirname/foo.go", `
package foo
import "C"
func f() {`)
tg.setenv("GOPATH", tg.path("."))
tg.runFail("build", "x/y/dirname")
tg.grepBoth("x/y/dirname", "error did not use full path")
}
func TestCgoHandlesWlORIGIN(t *testing.T) {
tooSlow(t)
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/origin/origin.go", `package origin
// #cgo !darwin LDFLAGS: -Wl,-rpath,$ORIGIN
// void f(void) {}
import "C"
func f() { C.f() }`)
tg.setenv("GOPATH", tg.path("."))
tg.run("build", "origin")
}
func TestCgoPkgConfig(t *testing.T) {
tooSlow(t)
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.run("env", "PKG_CONFIG")
pkgConfig := strings.TrimSpace(tg.getStdout())
if out, err := exec.Command(pkgConfig, "--atleast-pkgconfig-version", "0.24").CombinedOutput(); err != nil {
t.Skipf("%s --atleast-pkgconfig-version 0.24: %v\n%s", pkgConfig, err, out)
}
// OpenBSD's pkg-config is strict about whitespace and only
// supports backslash-escaped whitespace. It does not support
// quotes, which the normal freedesktop.org pkg-config does
// support. See http://man.openbsd.org/pkg-config.1
tg.tempFile("foo.pc", `
Name: foo
Description: The foo library
Version: 1.0.0
Cflags: -Dhello=10 -Dworld=+32 -DDEFINED_FROM_PKG_CONFIG=hello\ world
`)
tg.tempFile("foo.go", `package main
/*
#cgo pkg-config: foo
int value() {
return DEFINED_FROM_PKG_CONFIG;
}
*/
import "C"
import "os"
func main() {
if C.value() != 42 {
println("value() =", C.value(), "wanted 42")
os.Exit(1)
}
}
`)
tg.setenv("PKG_CONFIG_PATH", tg.path("."))
tg.run("run", tg.path("foo.go"))
}
// "go test -c -test.bench=XXX errors" should not hang.
// "go test -c" should also produce reproducible binaries.
// "go test -c" should also appear to write a new binary every time,
// even if it's really just updating the mtime on an existing up-to-date binary.
func TestIssue6480(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.makeTempdir()
tg.cd(tg.path("."))
tg.run("test", "-c", "-test.bench=XXX", "errors")
tg.run("test", "-c", "-o", "errors2.test", "errors")
data1, err := ioutil.ReadFile("errors.test" + exeSuffix)
tg.must(err)
data2, err := ioutil.ReadFile("errors2.test") // no exeSuffix because -o above doesn't have it
tg.must(err)
if !bytes.Equal(data1, data2) {
t.Fatalf("go test -c errors produced different binaries when run twice")
}
start := time.Now()
tg.run("test", "-x", "-c", "-test.bench=XXX", "errors")
tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
info, err := os.Stat("errors.test" + exeSuffix)
if err != nil {
t.Fatal(err)
}
start = truncateLike(start, info.ModTime())
if info.ModTime().Before(start) {
t.Fatalf("mtime of errors.test predates test -c command (%v < %v)", info.ModTime(), start)
}
start = time.Now()
tg.run("test", "-x", "-c", "-o", "errors2.test", "errors")
tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
info, err = os.Stat("errors2.test")
if err != nil {
t.Fatal(err)
}
start = truncateLike(start, info.ModTime())
if info.ModTime().Before(start) {
t.Fatalf("mtime of errors2.test predates test -c command (%v < %v)", info.ModTime(), start)
}
}
// truncateLike returns the result of truncating t to the apparent precision of p.
func truncateLike(t, p time.Time) time.Time {
nano := p.UnixNano()
d := 1 * time.Nanosecond
for nano%int64(d) == 0 && d < 1*time.Second {
d *= 10
}
for nano%int64(d) == 0 && d < 2*time.Second {
d *= 2
}
return t.Truncate(d)
}
// cmd/cgo: undefined reference when linking a C-library using gccgo
func TestIssue7573(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
if _, err := exec.LookPath("gccgo"); err != nil {
t.Skip("skipping because no gccgo compiler found")
}
t.Skip("golang.org/issue/22472")
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/cgoref/cgoref.go", `
package main
// #cgo LDFLAGS: -L alibpath -lalib
// void f(void) {}
import "C"
func main() { C.f() }`)
tg.setenv("GOPATH", tg.path("."))
tg.run("build", "-n", "-compiler", "gccgo", "cgoref")
tg.grepStderr(`gccgo.*\-L [^ ]*alibpath \-lalib`, `no Go-inline "#cgo LDFLAGS:" ("-L alibpath -lalib") passed to gccgo linking stage`)
}
func TestListTemplateContextFunction(t *testing.T) {
t.Parallel()
for _, tt := range []struct {
v string
want string
}{
{"GOARCH", runtime.GOARCH},
{"GOOS", runtime.GOOS},
{"GOROOT", filepath.Clean(runtime.GOROOT())},
{"GOPATH", os.Getenv("GOPATH")},
{"CgoEnabled", ""},
{"UseAllFiles", ""},
{"Compiler", ""},
{"BuildTags", ""},
{"ReleaseTags", ""},
{"InstallSuffix", ""},
} {
tt := tt
t.Run(tt.v, func(t *testing.T) {
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tmpl := "{{context." + tt.v + "}}"
tg.run("list", "-f", tmpl)
if tt.want == "" {
return
}
if got := strings.TrimSpace(tg.getStdout()); got != tt.want {
t.Errorf("go list -f %q: got %q; want %q", tmpl, got, tt.want)
}
})
}
}
// cmd/go: "go test" should fail if package does not build
func TestIssue7108(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("test", "notest")
}
// cmd/go: go test -a foo does not rebuild regexp.
func TestIssue6844(t *testing.T) {
if testing.Short() {
t.Skip("don't rebuild the standard library in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.creatingTemp("deps.test" + exeSuffix)
tg.run("test", "-x", "-a", "-c", "testdata/dep_test.go")
tg.grepStderr("regexp", "go test -x -a -c testdata/dep-test.go did not rebuild regexp")
}
func TestBuildDashIInstallsDependencies(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/x/y/foo/foo.go", `package foo
func F() {}`)
tg.tempFile("src/x/y/bar/bar.go", `package bar
import "x/y/foo"
func F() { foo.F() }`)
tg.setenv("GOPATH", tg.path("."))
// don't let build -i overwrite runtime
tg.wantNotStale("runtime", "", "must be non-stale before build -i")
checkbar := func(desc string) {
tg.run("build", "-v", "-i", "x/y/bar")
tg.grepBoth("x/y/foo", "first build -i "+desc+" did not build x/y/foo")
tg.run("build", "-v", "-i", "x/y/bar")
tg.grepBothNot("x/y/foo", "second build -i "+desc+" built x/y/foo")
}
checkbar("pkg")
tg.creatingTemp("bar" + exeSuffix)
tg.sleep()
tg.tempFile("src/x/y/foo/foo.go", `package foo
func F() { F() }`)
tg.tempFile("src/x/y/bar/bar.go", `package main
import "x/y/foo"
func main() { foo.F() }`)
checkbar("cmd")
}
func TestGoBuildInTestOnlyDirectoryFailsWithAGoodError(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.runFail("build", "./testdata/testonly")
tg.grepStderr("no non-test Go files in", "go build ./testdata/testonly produced unexpected error")
}
func TestGoTestDetectsTestOnlyImportCycles(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("test", "-c", "testcycle/p3")
tg.grepStderr("import cycle not allowed in test", "go test testcycle/p3 produced unexpected error")
tg.runFail("test", "-c", "testcycle/q1")
tg.grepStderr("import cycle not allowed in test", "go test testcycle/q1 produced unexpected error")
}
func TestGoTestFooTestWorks(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "testdata/standalone_test.go")
}
// Issue 22388
func TestGoTestMainWithWrongSignature(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.runFail("test", "testdata/standalone_main_wrong_test.go")
tg.grepStderr(`wrong signature for TestMain, must be: func TestMain\(m \*testing.M\)`, "detected wrong error message")
}
func TestGoTestMainAsNormalTest(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "testdata/standalone_main_normal_test.go")
tg.grepBoth(okPattern, "go test did not say ok")
}
func TestGoTestMainTwice(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOCACHE", tg.tempdir)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "-v", "multimain")
if strings.Count(tg.getStdout(), "notwithstanding") != 2 {
t.Fatal("tests did not run twice")
}
}
func TestGoTestFlagsAfterPackage(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "testdata/flag_test.go", "-v", "-args", "-v=7") // Two distinct -v flags.
tg.run("test", "-v", "testdata/flag_test.go", "-args", "-v=7") // Two distinct -v flags.
}
func TestGoTestXtestonlyWorks(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("clean", "-i", "xtestonly")
tg.run("test", "xtestonly")
}
func TestGoTestBuildsAnXtestContainingOnlyNonRunnableExamples(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-v", "./testdata/norunexample")
tg.grepStdout("File with non-runnable example was built.", "file with non-runnable example was not built")
}
func TestGoGenerateHandlesSimpleCommand(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping because windows has no echo command")
}
tg := testgo(t)
defer tg.cleanup()
tg.run("generate", "./testdata/generate/test1.go")
tg.grepStdout("Success", "go generate ./testdata/generate/test1.go generated wrong output")
}
func TestGoGenerateHandlesCommandAlias(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping because windows has no echo command")
}
tg := testgo(t)
defer tg.cleanup()
tg.run("generate", "./testdata/generate/test2.go")
tg.grepStdout("Now is the time for all good men", "go generate ./testdata/generate/test2.go generated wrong output")
}
func TestGoGenerateVariableSubstitution(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping because windows has no echo command")
}
tg := testgo(t)
defer tg.cleanup()
tg.run("generate", "./testdata/generate/test3.go")
tg.grepStdout(runtime.GOARCH+" test3.go:7 pabc xyzp/test3.go/123", "go generate ./testdata/generate/test3.go generated wrong output")
}
func TestGoGenerateRunFlag(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping because windows has no echo command")
}
tg := testgo(t)
defer tg.cleanup()
tg.run("generate", "-run", "y.s", "./testdata/generate/test4.go")
tg.grepStdout("yes", "go generate -run yes ./testdata/generate/test4.go did not select yes")
tg.grepStdoutNot("no", "go generate -run yes ./testdata/generate/test4.go selected no")
}
func TestGoGenerateEnv(t *testing.T) {
switch runtime.GOOS {
case "plan9", "windows":
t.Skipf("skipping because %s does not have the env command", runtime.GOOS)
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("env.go", "package main\n\n//go:generate env")
tg.run("generate", tg.path("env.go"))
for _, v := range []string{"GOARCH", "GOOS", "GOFILE", "GOLINE", "GOPACKAGE", "DOLLAR"} {
tg.grepStdout("^"+v+"=", "go generate environment missing "+v)
}
}
func TestGoGenerateXTestPkgName(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping because windows has no echo command")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("env_test.go", "package main_test\n\n//go:generate echo $GOPACKAGE")
tg.run("generate", tg.path("env_test.go"))
want := "main_test"
if got := strings.TrimSpace(tg.getStdout()); got != want {
t.Errorf("go generate in XTest file got package name %q; want %q", got, want)
}
}
func TestGoGenerateBadImports(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("skipping because windows has no echo command")
}
// This package has an invalid import causing an import cycle,
// but go generate is supposed to still run.
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("generate", "gencycle")
tg.grepStdout("hello world", "go generate gencycle did not run generator")
}
func TestGoGetCustomDomainWildcard(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.run("get", "-u", "rsc.io/pdf/...")
tg.wantExecutable(tg.path("bin/pdfpasswd"+exeSuffix), "did not build rsc/io/pdf/pdfpasswd")
}
func TestGoGetInternalWildcard(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
// used to fail with errors about internal packages
tg.run("get", "github.com/rsc/go-get-issue-11960/...")
}
func TestGoVetWithExternalTests(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("vet", "vetpkg")
tg.grepBoth("Printf", "go vet vetpkg did not find missing argument for Printf")
}
func TestGoVetWithTags(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("vet", "-tags", "tagtest", "vetpkg")
tg.grepBoth(`c\.go.*Printf`, "go vet vetpkg did not run scan tagged file")
}
func TestGoVetWithFlagsOn(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("vet", "-printf", "vetpkg")
tg.grepBoth("Printf", "go vet -printf vetpkg did not find missing argument for Printf")
}
func TestGoVetWithFlagsOff(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("vet", "-printf=false", "vetpkg")
}
// Issue 23395.
func TestGoVetWithOnlyTestFiles(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/p/p_test.go", "package p; import \"testing\"; func TestMe(*testing.T) {}")
tg.setenv("GOPATH", tg.path("."))
tg.run("vet", "p")
}
// Issue 24193.
func TestVetWithOnlyCgoFiles(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/p/p.go", "package p; import \"C\"; func F() {}")
tg.setenv("GOPATH", tg.path("."))
tg.run("vet", "p")
}
// Issue 9767, 19769.
func TestGoGetDotSlashDownload(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.tempDir("src/rsc.io")
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("src/rsc.io"))
tg.run("get", "./pprof_mac_fix")
}
// Issue 13037: Was not parsing <meta> tags in 404 served over HTTPS
func TestGoGetHTTPS404(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
switch runtime.GOOS {
case "darwin", "linux", "freebsd":
default:
t.Skipf("test case does not work on %s", runtime.GOOS)
}
tg := testgo(t)
defer tg.cleanup()
tg.tempDir("src")
tg.setenv("GOPATH", tg.path("."))
tg.run("get", "bazil.org/fuse/fs/fstestutil")
}
// Test that you cannot import a main package.
// See golang.org/issue/4210 and golang.org/issue/17475.
func TestImportMain(t *testing.T) {
tooSlow(t)
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
// Importing package main from that package main's test should work.
tg.tempFile("src/x/main.go", `package main
var X int
func main() {}`)
tg.tempFile("src/x/main_test.go", `package main_test
import xmain "x"
import "testing"
var _ = xmain.X
func TestFoo(t *testing.T) {}
`)
tg.setenv("GOPATH", tg.path("."))
tg.creatingTemp("x" + exeSuffix)
tg.run("build", "x")
tg.run("test", "x")
// Importing package main from another package should fail.
tg.tempFile("src/p1/p.go", `package p1
import xmain "x"
var _ = xmain.X
`)
tg.runFail("build", "p1")
tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
// ... even in that package's test.
tg.tempFile("src/p2/p.go", `package p2
`)
tg.tempFile("src/p2/p_test.go", `package p2
import xmain "x"
import "testing"
var _ = xmain.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "p2")
tg.runFail("test", "p2")
tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
// ... even if that package's test is an xtest.
tg.tempFile("src/p3/p.go", `package p
`)
tg.tempFile("src/p3/p_test.go", `package p_test
import xmain "x"
import "testing"
var _ = xmain.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "p3")
tg.runFail("test", "p3")
tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
// ... even if that package is a package main
tg.tempFile("src/p4/p.go", `package main
func main() {}
`)
tg.tempFile("src/p4/p_test.go", `package main
import xmain "x"
import "testing"
var _ = xmain.X
func TestFoo(t *testing.T) {}
`)
tg.creatingTemp("p4" + exeSuffix)
tg.run("build", "p4")
tg.runFail("test", "p4")
tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
// ... even if that package is a package main using an xtest.
tg.tempFile("src/p5/p.go", `package main
func main() {}
`)
tg.tempFile("src/p5/p_test.go", `package main_test
import xmain "x"
import "testing"
var _ = xmain.X
func TestFoo(t *testing.T) {}
`)
tg.creatingTemp("p5" + exeSuffix)
tg.run("build", "p5")
tg.runFail("test", "p5")
tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
}
// Test that you cannot use a local import in a package
// accessed by a non-local import (found in a GOPATH/GOROOT).
// See golang.org/issue/17475.
func TestImportLocal(t *testing.T) {
tooSlow(t)
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.tempFile("src/dir/x/x.go", `package x
var X int
`)
tg.setenv("GOPATH", tg.path("."))
tg.run("build", "dir/x")
// Ordinary import should work.
tg.tempFile("src/dir/p0/p.go", `package p0
import "dir/x"
var _ = x.X
`)
tg.run("build", "dir/p0")
// Relative import should not.
tg.tempFile("src/dir/p1/p.go", `package p1
import "../x"
var _ = x.X
`)
tg.runFail("build", "dir/p1")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in a test.
tg.tempFile("src/dir/p2/p.go", `package p2
`)
tg.tempFile("src/dir/p2/p_test.go", `package p2
import "../x"
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir/p2")
tg.runFail("test", "dir/p2")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in an xtest.
tg.tempFile("src/dir/p2/p_test.go", `package p2_test
import "../x"
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir/p2")
tg.runFail("test", "dir/p2")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// Relative import starting with ./ should not work either.
tg.tempFile("src/dir/d.go", `package dir
import "./x"
var _ = x.X
`)
tg.runFail("build", "dir")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in a test.
tg.tempFile("src/dir/d.go", `package dir
`)
tg.tempFile("src/dir/d_test.go", `package dir
import "./x"
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir")
tg.runFail("test", "dir")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in an xtest.
tg.tempFile("src/dir/d_test.go", `package dir_test
import "./x"
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir")
tg.runFail("test", "dir")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// Relative import plain ".." should not work.
tg.tempFile("src/dir/x/y/y.go", `package dir
import ".."
var _ = x.X
`)
tg.runFail("build", "dir/x/y")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in a test.
tg.tempFile("src/dir/x/y/y.go", `package y
`)
tg.tempFile("src/dir/x/y/y_test.go", `package y
import ".."
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir/x/y")
tg.runFail("test", "dir/x/y")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in an x test.
tg.tempFile("src/dir/x/y/y_test.go", `package y_test
import ".."
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir/x/y")
tg.runFail("test", "dir/x/y")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// Relative import "." should not work.
tg.tempFile("src/dir/x/xx.go", `package x
import "."
var _ = x.X
`)
tg.runFail("build", "dir/x")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in a test.
tg.tempFile("src/dir/x/xx.go", `package x
`)
tg.tempFile("src/dir/x/xx_test.go", `package x
import "."
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir/x")
tg.runFail("test", "dir/x")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
// ... even in an xtest.
tg.tempFile("src/dir/x/xx.go", `package x
`)
tg.tempFile("src/dir/x/xx_test.go", `package x_test
import "."
import "testing"
var _ = x.X
func TestFoo(t *testing.T) {}
`)
tg.run("build", "dir/x")
tg.runFail("test", "dir/x")
tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
}
func TestGoGetInsecure(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.failSSH()
const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
// Try go get -d of HTTP-only repo (should fail).
tg.runFail("get", "-d", repo)
// Try again with -insecure (should succeed).
tg.run("get", "-d", "-insecure", repo)
// Try updating without -insecure (should fail).
tg.runFail("get", "-d", "-u", "-f", repo)
}
func TestGoGetUpdateInsecure(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
const repo = "github.com/golang/example"
// Clone the repo via HTTP manually.
cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo))
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
}
// Update without -insecure should fail.
// Update with -insecure should succeed.
// We need -f to ignore import comments.
const pkg = repo + "/hello"
tg.runFail("get", "-d", "-u", "-f", pkg)
tg.run("get", "-d", "-u", "-f", "-insecure", pkg)
}
func TestGoGetInsecureCustomDomain(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
tg.runFail("get", "-d", repo)
tg.run("get", "-d", "-insecure", repo)
}
func TestGoRunDirs(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.cd("testdata/rundir")
tg.runFail("run", "x.go", "sub/sub.go")
tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output")
tg.runFail("run", "sub/sub.go", "x.go")
tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output")
}
func TestGoInstallPkgdir(t *testing.T) {
tooSlow(t)
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.makeTempdir()
pkg := tg.path(".")
tg.run("install", "-pkgdir", pkg, "sync")
tg.mustExist(filepath.Join(pkg, "sync.a"))
tg.mustNotExist(filepath.Join(pkg, "sync/atomic.a"))
tg.run("install", "-i", "-pkgdir", pkg, "sync")
tg.mustExist(filepath.Join(pkg, "sync.a"))
tg.mustExist(filepath.Join(pkg, "sync/atomic.a"))
}
func TestGoTestRaceInstallCgo(t *testing.T) {
if !canRace {
t.Skip("skipping because race detector not supported")
}
// golang.org/issue/10500.
// This used to install a race-enabled cgo.
tg := testgo(t)
defer tg.cleanup()
tg.run("tool", "-n", "cgo")
cgo := strings.TrimSpace(tg.stdout.String())
old, err := os.Stat(cgo)
tg.must(err)
tg.run("test", "-race", "-i", "runtime/race")
new, err := os.Stat(cgo)
tg.must(err)
if !new.ModTime().Equal(old.ModTime()) {
t.Fatalf("go test -i runtime/race reinstalled cmd/cgo")
}
}
func TestGoTestRaceFailures(t *testing.T) {
tooSlow(t)
if !canRace {
t.Skip("skipping because race detector not supported")
}
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "testrace")
tg.runFail("test", "-race", "testrace")
tg.grepStdout("FAIL: TestRace", "TestRace did not fail")
tg.grepBothNot("PASS", "something passed")
tg.runFail("test", "-race", "testrace", "-run", "XXX", "-bench", ".")
tg.grepStdout("FAIL: BenchmarkRace", "BenchmarkRace did not fail")
tg.grepBothNot("PASS", "something passed")
}
func TestGoTestImportErrorStack(t *testing.T) {
const out = `package testdep/p1 (test)
imports testdep/p2
imports testdep/p3: build constraints exclude all Go files `
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("test", "testdep/p1")
if !strings.Contains(tg.stderr.String(), out) {
t.Fatalf("did not give full import stack:\n\n%s", tg.stderr.String())
}
}
func TestGoGetUpdate(t *testing.T) {
// golang.org/issue/9224.
// The recursive updating was trying to walk to
// former dependencies, not current ones.
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
rewind := func() {
tg.run("get", "github.com/rsc/go-get-issue-9224-cmd")
cmd := exec.Command("git", "reset", "--hard", "HEAD~")
cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib")
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git: %v\n%s", err, out)
}
}
rewind()
tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd")
// Again with -d -u.
rewind()
tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd")
}
// Issue #20512.
func TestGoGetRace(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
if !canRace {
t.Skip("skipping because race detector not supported")
}
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.run("get", "-race", "github.com/rsc/go-get-issue-9224-cmd")
}
func TestGoGetDomainRoot(t *testing.T) {
// golang.org/issue/9357.
// go get foo.io (not foo.io/subdir) was not working consistently.
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
// go-get-issue-9357.appspot.com is running
// the code at github.com/rsc/go-get-issue-9357,
// a trivial Go on App Engine app that serves a
// <meta> tag for the domain root.
tg.run("get", "-d", "go-get-issue-9357.appspot.com")
tg.run("get", "go-get-issue-9357.appspot.com")
tg.run("get", "-u", "go-get-issue-9357.appspot.com")
tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
tg.run("get", "go-get-issue-9357.appspot.com")
tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
tg.run("get", "-u", "go-get-issue-9357.appspot.com")
}
func TestGoInstallShadowedGOPATH(t *testing.T) {
// golang.org/issue/3652.
// go get foo.io (not foo.io/subdir) was not working consistently.
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2"))
tg.tempDir("gopath1/src/test")
tg.tempDir("gopath2/src/test")
tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n")
tg.cd(tg.path("gopath2/src/test"))
tg.runFail("install")
tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error")
}
func TestGoBuildGOPATHOrder(t *testing.T) {
// golang.org/issue/14176#issuecomment-179895769
// golang.org/issue/14192
// -I arguments to compiler could end up not in GOPATH order,
// leading to unexpected import resolution in the compiler.
// This is still not a complete fix (see golang.org/issue/14271 and next test)
// but it is clearly OK and enough to fix both of the two reported
// instances of the underlying problem. It will have to do for now.
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("p1")+string(filepath.ListSeparator)+tg.path("p2"))
tg.tempFile("p1/src/foo/foo.go", "package foo\n")
tg.tempFile("p2/src/baz/baz.go", "package baz\n")
tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
tg.tempFile("p1/src/bar/bar.go", `
package bar
import _ "baz"
import _ "foo"
`)
tg.run("install", "-x", "bar")
}
func TestGoBuildGOPATHOrderBroken(t *testing.T) {
// This test is known not to work.
// See golang.org/issue/14271.
t.Skip("golang.org/issue/14271")
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.tempFile("p1/src/foo/foo.go", "package foo\n")
tg.tempFile("p2/src/baz/baz.go", "package baz\n")
tg.tempFile("p1/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/baz.a", "bad\n")
tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
tg.tempFile("p1/src/bar/bar.go", `
package bar
import _ "baz"
import _ "foo"
`)
colon := string(filepath.ListSeparator)
tg.setenv("GOPATH", tg.path("p1")+colon+tg.path("p2"))
tg.run("install", "-x", "bar")
tg.setenv("GOPATH", tg.path("p2")+colon+tg.path("p1"))
tg.run("install", "-x", "bar")
}
func TestIssue11709(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("run.go", `
package main
import "os"
func main() {
if os.Getenv("TERM") != "" {
os.Exit(1)
}
}`)
tg.unsetenv("TERM")
tg.run("run", tg.path("run.go"))
}
func TestIssue12096(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("test_test.go", `
package main
import ("os"; "testing")
func TestEnv(t *testing.T) {
if os.Getenv("TERM") != "" {
t.Fatal("TERM is set")
}
}`)
tg.unsetenv("TERM")
tg.run("test", tg.path("test_test.go"))
}
func TestGoBuildOutput(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.cd(tg.path("."))
nonExeSuffix := ".exe"
if exeSuffix == ".exe" {
nonExeSuffix = ""
}
tg.tempFile("x.go", "package main\nfunc main(){}\n")
tg.run("build", "x.go")
tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix)
tg.must(os.Remove(tg.path("x" + exeSuffix)))
tg.mustNotExist("x" + nonExeSuffix)
tg.run("build", "-o", "myprog", "x.go")
tg.mustNotExist("x")
tg.mustNotExist("x.exe")
tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog")
tg.mustNotExist("myprog.exe")
tg.tempFile("p.go", "package p\n")
tg.run("build", "p.go")
tg.mustNotExist("p")
tg.mustNotExist("p.a")
tg.mustNotExist("p.o")
tg.mustNotExist("p.exe")
tg.run("build", "-o", "p.a", "p.go")
tg.wantArchive("p.a")
tg.run("build", "cmd/gofmt")
tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix)
tg.must(os.Remove(tg.path("gofmt" + exeSuffix)))
tg.mustNotExist("gofmt" + nonExeSuffix)
tg.run("build", "-o", "mygofmt", "cmd/gofmt")
tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt")
tg.mustNotExist("mygofmt.exe")
tg.mustNotExist("gofmt")
tg.mustNotExist("gofmt.exe")
tg.run("build", "sync/atomic")
tg.mustNotExist("atomic")
tg.mustNotExist("atomic.exe")
tg.run("build", "-o", "myatomic.a", "sync/atomic")
tg.wantArchive("myatomic.a")
tg.mustNotExist("atomic")
tg.mustNotExist("atomic.a")
tg.mustNotExist("atomic.exe")
tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic")
tg.grepStderr("multiple packages", "did not reject -o with multiple packages")
}
func TestGoBuildARM(t *testing.T) {
if testing.Short() {
t.Skip("skipping cross-compile in short mode")
}
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.cd(tg.path("."))
tg.setenv("GOARCH", "arm")
tg.setenv("GOOS", "linux")
tg.setenv("GOARM", "5")
tg.tempFile("hello.go", `package main
func main() {}`)
tg.run("build", "hello.go")
tg.grepStderrNot("unable to find math.a", "did not build math.a correctly")
}
// For issue 14337.
func TestParallelTest(t *testing.T) {
tooSlow(t)
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.makeTempdir()
const testSrc = `package package_test
import (
"testing"
)
func TestTest(t *testing.T) {
}`
tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1))
tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1))
tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1))
tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1))
tg.setenv("GOPATH", tg.path("."))
tg.run("test", "-p=4", "p1", "p2", "p3", "p4")
}
func TestCgoConsistentResults(t *testing.T) {
tooSlow(t)
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
switch runtime.GOOS {
case "freebsd":
testenv.SkipFlaky(t, 15405)
case "solaris":
testenv.SkipFlaky(t, 13247)
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
exe1 := tg.path("cgotest1" + exeSuffix)
exe2 := tg.path("cgotest2" + exeSuffix)
tg.run("build", "-o", exe1, "cgotest")
tg.run("build", "-x", "-o", exe2, "cgotest")
b1, err := ioutil.ReadFile(exe1)
tg.must(err)
b2, err := ioutil.ReadFile(exe2)
tg.must(err)
if !tg.doGrepMatch(`-fdebug-prefix-map=\$WORK`, &tg.stderr) {
t.Skip("skipping because C compiler does not support -fdebug-prefix-map")
}
if !bytes.Equal(b1, b2) {
t.Error("building cgotest twice did not produce the same output")
}
}
// Issue 14444: go get -u .../ duplicate loads errors
func TestGoGetUpdateAllDoesNotTryToLoadDuplicates(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.run("get", "-u", ".../")
tg.grepStderrNot("duplicate loads of", "did not remove old packages from cache")
}
// Issue 17119 more duplicate load errors
func TestIssue17119(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("build", "dupload")
tg.grepBothNot("duplicate load|internal error", "internal error")
}
func TestFatalInBenchmarkCauseNonZeroExitStatus(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.runFail("test", "-run", "^$", "-bench", ".", "./testdata/src/benchfatal")
tg.grepBothNot("^ok", "test passed unexpectedly")
tg.grepBoth("FAIL.*benchfatal", "test did not run everything")
}
func TestBinaryOnlyPackages(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
tg.tempFile("src/p1/p1.go", `//go:binary-only-package
package p1
`)
tg.wantStale("p1", "missing or invalid binary-only package", "p1 is binary-only but has no binary, should be stale")
tg.runFail("install", "p1")
tg.grepStderr("missing or invalid binary-only package", "did not report attempt to compile binary-only package")
tg.tempFile("src/p1/p1.go", `
package p1
import "fmt"
func F(b bool) { fmt.Printf("hello from p1\n"); if b { F(false) } }
`)
tg.run("install", "p1")
os.Remove(tg.path("src/p1/p1.go"))
tg.mustNotExist(tg.path("src/p1/p1.go"))
tg.tempFile("src/p2/p2.go", `//go:binary-only-packages-are-not-great
package p2
import "p1"
func F() { p1.F(true) }
`)
tg.runFail("install", "p2")
tg.grepStderr("no Go files", "did not complain about missing sources")
tg.tempFile("src/p1/missing.go", `//go:binary-only-package
package p1
import _ "fmt"
func G()
`)
tg.wantNotStale("p1", "binary-only package", "should NOT want to rebuild p1 (first)")
tg.run("install", "-x", "p1") // no-op, up to date
tg.grepBothNot(`[\\/]compile`, "should not have run compiler")
tg.run("install", "p2") // does not rebuild p1 (or else p2 will fail)
tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
// changes to the non-source-code do not matter,
// and only one file needs the special comment.
tg.tempFile("src/p1/missing2.go", `
package p1
func H()
`)
tg.wantNotStale("p1", "binary-only package", "should NOT want to rebuild p1 (second)")
tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
tg.tempFile("src/p3/p3.go", `
package main
import (
"p1"
"p2"
)
func main() {
p1.F(false)
p2.F()
}
`)
tg.run("install", "p3")
tg.run("run", tg.path("src/p3/p3.go"))
tg.grepStdout("hello from p1", "did not see message from p1")
tg.tempFile("src/p4/p4.go", `package main`)
// The odd string split below avoids vet complaining about
// a // +build line appearing too late in this source file.
tg.tempFile("src/p4/p4not.go", `//go:binary-only-package
/`+`/ +build asdf
package main
`)
tg.run("list", "-f", "{{.BinaryOnly}}", "p4")
tg.grepStdout("false", "did not see BinaryOnly=false for p4")
}
// Issue 16050.
func TestAlwaysLinkSysoFiles(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src/syso")
tg.tempFile("src/syso/a.syso", ``)
tg.tempFile("src/syso/b.go", `package syso`)
tg.setenv("GOPATH", tg.path("."))
// We should see the .syso file regardless of the setting of
// CGO_ENABLED.
tg.setenv("CGO_ENABLED", "1")
tg.run("list", "-f", "{{.SysoFiles}}", "syso")
tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=1")
tg.setenv("CGO_ENABLED", "0")
tg.run("list", "-f", "{{.SysoFiles}}", "syso")
tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0")
}
// Issue 16120.
func TestGenerateUsesBuildContext(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("this test won't run under Windows")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempDir("src/gen")
tg.tempFile("src/gen/gen.go", "package gen\n//go:generate echo $GOOS $GOARCH\n")
tg.setenv("GOPATH", tg.path("."))
tg.setenv("GOOS", "linux")
tg.setenv("GOARCH", "amd64")
tg.run("generate", "gen")
tg.grepStdout("linux amd64", "unexpected GOOS/GOARCH combination")
tg.setenv("GOOS", "darwin")
tg.setenv("GOARCH", "386")
tg.run("generate", "gen")
tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination")
}
// Issue 14450: go get -u .../ tried to import not downloaded package
func TestGoGetUpdateWithWildcard(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("."))
const aPkgImportPath = "github.com/tmwh/go-get-issue-14450/a"
tg.run("get", aPkgImportPath)
tg.run("get", "-u", ".../")
tg.grepStderrNot("cannot find package", "did not update packages given wildcard path")
var expectedPkgPaths = []string{
"src/github.com/tmwh/go-get-issue-14450/b",
"src/github.com/tmwh/go-get-issue-14450-b-dependency/c",
"src/github.com/tmwh/go-get-issue-14450-b-dependency/d",
}
for _, importPath := range expectedPkgPaths {
_, err := os.Stat(tg.path(importPath))
tg.must(err)
}
const notExpectedPkgPath = "src/github.com/tmwh/go-get-issue-14450-c-dependency/e"
tg.mustNotExist(tg.path(notExpectedPkgPath))
}
func TestGoEnv(t *testing.T) {
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.setenv("GOOS", "freebsd") // to avoid invalid pair errors
tg.setenv("GOARCH", "arm")
tg.run("env", "GOARCH")
tg.grepStdout("^arm$", "GOARCH not honored")
tg.run("env", "GCCGO")
tg.grepStdout(".", "GCCGO unexpectedly empty")
tg.run("env", "CGO_CFLAGS")
tg.grepStdout(".", "default CGO_CFLAGS unexpectedly empty")
tg.setenv("CGO_CFLAGS", "-foobar")
tg.run("env", "CGO_CFLAGS")
tg.grepStdout("^-foobar$", "CGO_CFLAGS not honored")
tg.setenv("CC", "gcc -fmust -fgo -ffaster")
tg.run("env", "CC")
tg.grepStdout("gcc", "CC not found")
tg.run("env", "GOGCCFLAGS")
tg.grepStdout("-ffaster", "CC arguments not found")
}
const (
noMatchesPattern = `(?m)^ok.*\[no tests to run\]`
okPattern = `(?m)^ok`
)
func TestMatchesNoTests(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_test.go")
tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
}
func TestMatchesNoTestsDoesNotOverrideBuildFailure(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("test", "-run", "ThisWillNotMatch", "syntaxerror")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth("FAIL", "go test did not say FAIL")
}
func TestMatchesNoBenchmarksIsOK(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.run("test", "-run", "^$", "-bench", "ThisWillNotMatch", "testdata/standalone_benchmark_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth(okPattern, "go test did not say ok")
}
func TestMatchesOnlyExampleIsOK(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.run("test", "-run", "Example", "testdata/example1_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth(okPattern, "go test did not say ok")
}
func TestMatchesOnlyBenchmarkIsOK(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth(okPattern, "go test did not say ok")
}
func TestBenchmarkLabels(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "-run", "^$", "-bench", ".", "bench")
tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
tg.grepStdout(`(?m)^pkg: bench`, "go test did not say pkg: bench")
tg.grepBothNot(`(?s)pkg:.*pkg:`, "go test said pkg multiple times")
}
func TestBenchmarkLabelsOutsideGOPATH(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
tg.grepBothNot(`(?m)^pkg:`, "go test did say pkg:")
}
func TestMatchesOnlyTestIsOK(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
// TODO: tg.parallel()
tg.run("test", "-run", "Test", "testdata/standalone_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth(okPattern, "go test did not say ok")
}
func TestMatchesNoTestsWithSubtests(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_sub_test.go")
tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
}
func TestMatchesNoSubtestsMatch(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-run", "Test/ThisWillNotMatch", "testdata/standalone_sub_test.go")
tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
}
func TestMatchesNoSubtestsDoesNotOverrideFailure(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.runFail("test", "-run", "TestThatFails/ThisWillNotMatch", "testdata/standalone_fail_sub_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth("FAIL", "go test did not say FAIL")
}
func TestMatchesOnlySubtestIsOK(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-run", "Test/Sub", "testdata/standalone_sub_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth(okPattern, "go test did not say ok")
}
func TestMatchesNoSubtestsParallel(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-run", "Test/Sub/ThisWillNotMatch", "testdata/standalone_parallel_sub_test.go")
tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
}
func TestMatchesOnlySubtestParallelIsOK(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-run", "Test/Sub/Nested", "testdata/standalone_parallel_sub_test.go")
tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
tg.grepBoth(okPattern, "go test did not say ok")
}
// Issue 18845
func TestBenchTimeout(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-bench", ".", "-timeout", "750ms", "testdata/timeoutbench_test.go")
}
// Issue 19394
func TestWriteProfilesOnTimeout(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.tempDir("profiling")
tg.tempFile("profiling/timeouttest_test.go", `package timeouttest_test
import "testing"
import "time"
func TestSleep(t *testing.T) { time.Sleep(time.Second) }`)
tg.cd(tg.path("profiling"))
tg.runFail(
"test",
"-cpuprofile", tg.path("profiling/cpu.pprof"), "-memprofile", tg.path("profiling/mem.pprof"),
"-timeout", "1ms")
tg.mustHaveContent(tg.path("profiling/cpu.pprof"))
tg.mustHaveContent(tg.path("profiling/mem.pprof"))
}
func TestLinkXImportPathEscape(t *testing.T) {
// golang.org/issue/16710
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
exe := "./linkx" + exeSuffix
tg.creatingTemp(exe)
tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked", "my.pkg/main")
out, err := exec.Command(exe).CombinedOutput()
if err != nil {
tg.t.Fatal(err)
}
if string(out) != "linkXworked\n" {
tg.t.Log(string(out))
tg.t.Fatal(`incorrect output: expected "linkXworked\n"`)
}
}
// Issue 18044.
func TestLdBindNow(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("LD_BIND_NOW", "1")
tg.run("help")
}
// Issue 18225.
// This is really a cmd/asm issue but this is a convenient place to test it.
func TestConcurrentAsm(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
asm := `DATA ·constants<>+0x0(SB)/8,$0
GLOBL ·constants<>(SB),8,$8
`
tg.tempFile("go/src/p/a.s", asm)
tg.tempFile("go/src/p/b.s", asm)
tg.tempFile("go/src/p/p.go", `package p`)
tg.setenv("GOPATH", tg.path("go"))
tg.run("build", "p")
}
// Issue 18778.
func TestDotDotDotOutsideGOPATH(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("pkgs/a.go", `package x`)
tg.tempFile("pkgs/a_test.go", `package x_test
import "testing"
func TestX(t *testing.T) {}`)
tg.tempFile("pkgs/a/a.go", `package a`)
tg.tempFile("pkgs/a/a_test.go", `package a_test
import "testing"
func TestA(t *testing.T) {}`)
tg.cd(tg.path("pkgs"))
tg.run("build", "./...")
tg.run("test", "./...")
tg.run("list", "./...")
tg.grepStdout("pkgs$", "expected package not listed")
tg.grepStdout("pkgs/a", "expected package not listed")
}
// Issue 18975.
func TestFFLAGS(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("p/src/p/main.go", `package main
// #cgo FFLAGS: -no-such-fortran-flag
import "C"
func main() {}
`)
tg.tempFile("p/src/p/a.f", `! comment`)
tg.setenv("GOPATH", tg.path("p"))
// This should normally fail because we are passing an unknown flag,
// but issue #19080 points to Fortran compilers that succeed anyhow.
// To work either way we call doRun directly rather than run or runFail.
tg.doRun([]string{"build", "-x", "p"})
tg.grepStderr("no-such-fortran-flag", `missing expected "-no-such-fortran-flag"`)
}
// Issue 19198.
// This is really a cmd/link issue but this is a convenient place to test it.
func TestDuplicateGlobalAsmSymbols(t *testing.T) {
tooSlow(t)
if runtime.GOARCH != "386" && runtime.GOARCH != "amd64" {
t.Skipf("skipping test on %s", runtime.GOARCH)
}
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
asm := `
#include "textflag.h"
DATA sym<>+0x0(SB)/8,$0
GLOBL sym<>(SB),(NOPTR+RODATA),$8
TEXT ·Data(SB),NOSPLIT,$0
MOVB sym<>(SB), AX
MOVB AX, ret+0(FP)
RET
`
tg.tempFile("go/src/a/a.s", asm)
tg.tempFile("go/src/a/a.go", `package a; func Data() uint8`)
tg.tempFile("go/src/b/b.s", asm)
tg.tempFile("go/src/b/b.go", `package b; func Data() uint8`)
tg.tempFile("go/src/p/p.go", `
package main
import "a"
import "b"
import "C"
func main() {
_ = a.Data() + b.Data()
}
`)
tg.setenv("GOPATH", tg.path("go"))
exe := tg.path("p.exe")
tg.creatingTemp(exe)
tg.run("build", "-o", exe, "p")
}
func TestBuildTagsNoComma(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOPATH", tg.path("go"))
tg.run("build", "-tags", "tag1 tag2", "math")
tg.runFail("build", "-tags", "tag1,tag2", "math")
tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error")
}
func copyFile(src, dst string, perm os.FileMode) error {
sf, err := os.Open(src)
if err != nil {
return err
}
defer sf.Close()
df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
_, err = io.Copy(df, sf)
err2 := df.Close()
if err != nil {
return err
}
return err2
}
func TestExecutableGOROOT(t *testing.T) {
if runtime.GOOS == "openbsd" {
t.Skipf("test case does not work on %s, missing os.Executable", runtime.GOOS)
}
// Env with no GOROOT.
var env []string
for _, e := range os.Environ() {
if !strings.HasPrefix(e, "GOROOT=") {
env = append(env, e)
}
}
check := func(t *testing.T, exe, want string) {
cmd := exec.Command(exe, "env", "GOROOT")
cmd.Env = env
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("%s env GOROOT: %v, %s", exe, err, out)
}
goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
if err != nil {
t.Fatal(err)
}
want, err = filepath.EvalSymlinks(want)
if err != nil {
t.Fatal(err)
}
if !strings.EqualFold(goroot, want) {
t.Errorf("go env GOROOT:\nhave %s\nwant %s", goroot, want)
} else {
t.Logf("go env GOROOT: %s", goroot)
}
}
// Note: Must not call tg methods inside subtests: tg is attached to outer t.
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.tempDir("new/bin")
newGoTool := tg.path("new/bin/go" + exeSuffix)
tg.must(copyFile(tg.goTool(), newGoTool, 0775))
newRoot := tg.path("new")
t.Run("RelocatedExe", func(t *testing.T) {
// Should fall back to default location in binary,
// which is the GOROOT we used when building testgo.exe.
check(t, newGoTool, testGOROOT)
})
// If the binary is sitting in a bin dir next to ../pkg/tool, that counts as a GOROOT,
// so it should find the new tree.
tg.tempDir("new/pkg/tool")
t.Run("RelocatedTree", func(t *testing.T) {
check(t, newGoTool, newRoot)
})
tg.tempDir("other/bin")
symGoTool := tg.path("other/bin/go" + exeSuffix)
// Symlink into go tree should still find go tree.
t.Run("SymlinkedExe", func(t *testing.T) {
testenv.MustHaveSymlink(t)
if err := os.Symlink(newGoTool, symGoTool); err != nil {
t.Fatal(err)
}
check(t, symGoTool, newRoot)
})
tg.must(os.RemoveAll(tg.path("new/pkg")))
// Binaries built in the new tree should report the
// new tree when they call runtime.GOROOT.
t.Run("RuntimeGoroot", func(t *testing.T) {
// Build a working GOROOT the easy way, with symlinks.
testenv.MustHaveSymlink(t)
if err := os.Symlink(filepath.Join(testGOROOT, "src"), tg.path("new/src")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(testGOROOT, "pkg"), tg.path("new/pkg")); err != nil {
t.Fatal(err)
}
cmd := exec.Command(newGoTool, "run", "testdata/print_goroot.go")
cmd.Env = env
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("%s run testdata/print_goroot.go: %v, %s", newGoTool, err, out)
}
goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
if err != nil {
t.Fatal(err)
}
want, err := filepath.EvalSymlinks(tg.path("new"))
if err != nil {
t.Fatal(err)
}
if !strings.EqualFold(goroot, want) {
t.Errorf("go run testdata/print_goroot.go:\nhave %s\nwant %s", goroot, want)
} else {
t.Logf("go run testdata/print_goroot.go: %s", goroot)
}
})
}
func TestNeedVersion(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("goversion.go", `package main; func main() {}`)
path := tg.path("goversion.go")
tg.setenv("TESTGO_VERSION", "go1.testgo")
tg.runFail("run", path)
tg.grepStderr("compile", "does not match go tool version")
}
// Test that user can override default code generation flags.
func TestUserOverrideFlags(t *testing.T) {
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
if runtime.GOOS != "linux" {
// We are testing platform-independent code, so it's
// OK to skip cases that work differently.
t.Skipf("skipping on %s because test only works if c-archive implies -shared", runtime.GOOS)
}
tg := testgo(t)
defer tg.cleanup()
// Don't call tg.parallel, as creating override.h and override.a may
// confuse other tests.
tg.tempFile("override.go", `package main
import "C"
//export GoFunc
func GoFunc() {}
func main() {}`)
tg.creatingTemp("override.a")
tg.creatingTemp("override.h")
tg.run("build", "-x", "-buildmode=c-archive", "-gcflags=all=-shared=false", tg.path("override.go"))
tg.grepStderr("compile .*-shared .*-shared=false", "user can not override code generation flag")
}
func TestCgoFlagContainsSpace(t *testing.T) {
tooSlow(t)
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.cd(tg.path("."))
tg.tempFile("main.go", `package main
// #cgo CFLAGS: -I"c flags"
// #cgo LDFLAGS: -L"ld flags"
import "C"
func main() {}
`)
tg.run("run", "-x", "main.go")
tg.grepStderr(`"-I[^"]+c flags"`, "did not find quoted c flags")
tg.grepStderrNot(`"-I[^"]+c flags".*"-I[^"]+c flags"`, "found too many quoted c flags")
tg.grepStderr(`"-L[^"]+ld flags"`, "did not find quoted ld flags")
tg.grepStderrNot(`"-L[^"]+c flags".*"-L[^"]+c flags"`, "found too many quoted ld flags")
}
// Issue #20435.
func TestGoTestRaceCoverModeFailures(t *testing.T) {
tooSlow(t)
if !canRace {
t.Skip("skipping because race detector not supported")
}
tg := testgo(t)
tg.parallel()
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "testrace")
tg.runFail("test", "-race", "-covermode=set", "testrace")
tg.grepStderr(`-covermode must be "atomic", not "set", when -race is enabled`, "-race -covermode=set was allowed")
tg.grepBothNot("PASS", "something passed")
}
// Issue 9737: verify that GOARM and GO386 affect the computed build ID.
func TestBuildIDContainsArchModeEnv(t *testing.T) {
if testing.Short() {
t.Skip("skipping in short mode")
}
var tg *testgoData
testWith := func(before, after func()) func(*testing.T) {
return func(t *testing.T) {
tg = testgo(t)
defer tg.cleanup()
tg.tempFile("src/mycmd/x.go", `package main
func main() {}`)
tg.setenv("GOPATH", tg.path("."))
tg.cd(tg.path("src/mycmd"))
tg.setenv("GOOS", "linux")
before()
tg.run("install", "mycmd")
after()
tg.wantStale("mycmd", "stale dependency: runtime/internal/sys", "should be stale after environment variable change")
}
}
t.Run("386", testWith(func() {
tg.setenv("GOARCH", "386")
tg.setenv("GO386", "387")
}, func() {
tg.setenv("GO386", "sse2")
}))
t.Run("arm", testWith(func() {
tg.setenv("GOARCH", "arm")
tg.setenv("GOARM", "5")
}, func() {
tg.setenv("GOARM", "7")
}))
}
func TestTestRegexps(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "-cpu=1", "-run=X/Y", "-bench=X/Y", "-count=2", "-v", "testregexp")
var lines []string
for _, line := range strings.SplitAfter(tg.getStdout(), "\n") {
if strings.Contains(line, "=== RUN") || strings.Contains(line, "--- BENCH") || strings.Contains(line, "LOG") {
lines = append(lines, line)
}
}
// Important parts:
// TestX is run, twice
// TestX/Y is run, twice
// TestXX is run, twice
// TestZ is not run
// BenchmarkX is run but only with N=1, once
// BenchmarkXX is run but only with N=1, once
// BenchmarkX/Y is run in full, twice
want := `=== RUN TestX
=== RUN TestX/Y
x_test.go:6: LOG: X running
x_test.go:8: LOG: Y running
=== RUN TestXX
z_test.go:10: LOG: XX running
=== RUN TestX
=== RUN TestX/Y
x_test.go:6: LOG: X running
x_test.go:8: LOG: Y running
=== RUN TestXX
z_test.go:10: LOG: XX running
--- BENCH: BenchmarkX/Y
x_test.go:15: LOG: Y running N=1
x_test.go:15: LOG: Y running N=100
x_test.go:15: LOG: Y running N=10000
x_test.go:15: LOG: Y running N=1000000
x_test.go:15: LOG: Y running N=100000000
x_test.go:15: LOG: Y running N=2000000000
--- BENCH: BenchmarkX/Y
x_test.go:15: LOG: Y running N=1
x_test.go:15: LOG: Y running N=100
x_test.go:15: LOG: Y running N=10000
x_test.go:15: LOG: Y running N=1000000
x_test.go:15: LOG: Y running N=100000000
x_test.go:15: LOG: Y running N=2000000000
--- BENCH: BenchmarkX
x_test.go:13: LOG: X running N=1
--- BENCH: BenchmarkXX
z_test.go:18: LOG: XX running N=1
`
have := strings.Join(lines, "")
if have != want {
t.Errorf("reduced output:<<<\n%s>>> want:<<<\n%s>>>", have, want)
}
}
func TestListTests(t *testing.T) {
tooSlow(t)
var tg *testgoData
testWith := func(listName, expected string) func(*testing.T) {
return func(t *testing.T) {
tg = testgo(t)
defer tg.cleanup()
tg.run("test", "./testdata/src/testlist/...", fmt.Sprintf("-list=%s", listName))
tg.grepStdout(expected, fmt.Sprintf("-test.list=%s returned %q, expected %s", listName, tg.getStdout(), expected))
}
}
t.Run("Test", testWith("Test", "TestSimple"))
t.Run("Bench", testWith("Benchmark", "BenchmarkSimple"))
t.Run("Example1", testWith("Example", "ExampleSimple"))
t.Run("Example2", testWith("Example", "ExampleWithEmptyOutput"))
}
func TestBuildmodePIE(t *testing.T) {
if testing.Short() && testenv.Builder() == "" {
t.Skipf("skipping in -short mode on non-builder")
}
if runtime.Compiler == "gccgo" {
t.Skipf("skipping test because buildmode=pie is not supported on gccgo")
}
platform := fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)
switch platform {
case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x",
"android/amd64", "android/arm", "android/arm64", "android/386",
"freebsd/amd64":
case "darwin/amd64":
default:
t.Skipf("skipping test because buildmode=pie is not supported on %s", platform)
}
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("main.go", `package main; func main() { print("hello") }`)
src := tg.path("main.go")
obj := tg.path("main")
tg.run("build", "-buildmode=pie", "-o", obj, src)
switch runtime.GOOS {
case "linux", "android", "freebsd":
f, err := elf.Open(obj)
if err != nil {
t.Fatal(err)
}
defer f.Close()
if f.Type != elf.ET_DYN {
t.Errorf("PIE type must be ET_DYN, but %s", f.Type)
}
case "darwin":
f, err := macho.Open(obj)
if err != nil {
t.Fatal(err)
}
defer f.Close()
if f.Flags&macho.FlagDyldLink == 0 {
t.Error("PIE must have DyldLink flag, but not")
}
if f.Flags&macho.FlagPIE == 0 {
t.Error("PIE must have PIE flag, but not")
}
default:
panic("unreachable")
}
out, err := exec.Command(obj).CombinedOutput()
if err != nil {
t.Fatal(err)
}
if string(out) != "hello" {
t.Errorf("got %q; want %q", out, "hello")
}
}
func TestExecBuildX(t *testing.T) {
tooSlow(t)
if !canCgo {
t.Skip("skipping because cgo not enabled")
}
if runtime.GOOS == "plan9" || runtime.GOOS == "windows" {
t.Skipf("skipping because unix shell is not supported on %s", runtime.GOOS)
}
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOCACHE", "off")
tg.tempFile("main.go", `package main; import "C"; func main() { print("hello") }`)
src := tg.path("main.go")
obj := tg.path("main")
tg.run("build", "-x", "-o", obj, src)
sh := tg.path("test.sh")
err := ioutil.WriteFile(sh, []byte("set -e\n"+tg.getStderr()), 0666)
if err != nil {
t.Fatal(err)
}
out, err := exec.Command(obj).CombinedOutput()
if err != nil {
t.Fatal(err)
}
if string(out) != "hello" {
t.Fatalf("got %q; want %q", out, "hello")
}
err = os.Remove(obj)
if err != nil {
t.Fatal(err)
}
out, err = exec.Command("/usr/bin/env", "bash", "-x", sh).CombinedOutput()
if err != nil {
t.Fatalf("/bin/sh %s: %v\n%s", sh, err, out)
}
t.Logf("shell output:\n%s", out)
out, err = exec.Command(obj).CombinedOutput()
if err != nil {
t.Fatal(err)
}
if string(out) != "hello" {
t.Fatalf("got %q; want %q", out, "hello")
}
}
func TestParallelNumber(t *testing.T) {
tooSlow(t)
for _, n := range [...]string{"-1", "0"} {
t.Run(n, func(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.runFail("test", "-parallel", n, "testdata/standalone_parallel_sub_test.go")
tg.grepBoth("-parallel can only be given", "go test -parallel with N<1 did not error")
})
}
}
func TestWrongGOOSErrorBeforeLoadError(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.setenv("GOOS", "windwos")
tg.runFail("build", "exclude")
tg.grepStderr("unsupported GOOS/GOARCH pair", "GOOS=windwos go build exclude did not report 'unsupported GOOS/GOARCH pair'")
}
func TestUpxCompression(t *testing.T) {
if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
t.Skipf("skipping upx test on %s/%s", runtime.GOOS, runtime.GOARCH)
}
out, err := exec.Command("upx", "--version").CombinedOutput()
if err != nil {
t.Skip("skipping because upx is not available")
}
// upx --version prints `upx <version>` in the first line of output:
// upx 3.94
// [...]
re := regexp.MustCompile(`([[:digit:]]+)\.([[:digit:]]+)`)
upxVersion := re.FindStringSubmatch(string(out))
if len(upxVersion) != 3 {
t.Errorf("bad upx version string: %s", upxVersion)
}
major, err1 := strconv.Atoi(upxVersion[1])
minor, err2 := strconv.Atoi(upxVersion[2])
if err1 != nil || err2 != nil {
t.Errorf("bad upx version string: %s", upxVersion[0])
}
// Anything below 3.94 is known not to work with go binaries
if (major < 3) || (major == 3 && minor < 94) {
t.Skipf("skipping because upx version %v.%v is too old", major, minor)
}
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("main.go", `package main; import "fmt"; func main() { fmt.Print("hello upx") }`)
src := tg.path("main.go")
obj := tg.path("main")
tg.run("build", "-o", obj, src)
out, err = exec.Command("upx", obj).CombinedOutput()
if err != nil {
t.Logf("executing upx\n%s\n", out)
t.Fatalf("upx failed with %v", err)
}
out, err = exec.Command(obj).CombinedOutput()
if err != nil {
t.Logf("%s", out)
t.Fatalf("running compressed go binary failed with error %s", err)
}
if string(out) != "hello upx" {
t.Fatalf("bad output from compressed go binary:\ngot %q; want %q", out, "hello upx")
}
}
func TestGOTMPDIR(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.makeTempdir()
tg.setenv("GOTMPDIR", tg.tempdir)
tg.setenv("GOCACHE", "off")
// complex/x is a trivial non-main package.
tg.run("build", "-work", "-x", "complex/w")
tg.grepStderr("WORK="+regexp.QuoteMeta(tg.tempdir), "did not work in $GOTMPDIR")
}
func TestBuildCache(t *testing.T) {
tooSlow(t)
if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
t.Skip("GODEBUG gocacheverify")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.makeTempdir()
tg.setenv("GOCACHE", tg.tempdir)
// complex/w is a trivial non-main package.
// It imports nothing, so there should be no Deps.
tg.run("list", "-f={{join .Deps \" \"}}", "complex/w")
tg.grepStdoutNot(".+", "complex/w depends on unexpected packages")
tg.run("build", "-x", "complex/w")
tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler")
tg.run("build", "-x", "complex/w")
tg.grepStderrNot(`[\\/]compile|gccgo`, "ran compiler incorrectly")
tg.run("build", "-a", "-x", "complex/w")
tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler with -a")
// complex is a non-trivial main package.
// the link step should not be cached.
tg.run("build", "-o", os.DevNull, "-x", "complex")
tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
tg.run("build", "-o", os.DevNull, "-x", "complex")
tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
}
func TestCacheOutput(t *testing.T) {
// Test that command output is cached and replayed too.
if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
t.Skip("GODEBUG gocacheverify")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.makeTempdir()
tg.setenv("GOCACHE", tg.tempdir)
tg.run("build", "-gcflags=-m", "errors")
stdout1 := tg.getStdout()
stderr1 := tg.getStderr()
tg.run("build", "-gcflags=-m", "errors")
stdout2 := tg.getStdout()
stderr2 := tg.getStderr()
if stdout2 != stdout1 || stderr2 != stderr1 {
t.Errorf("cache did not reproduce output:\n\nstdout1:\n%s\n\nstdout2:\n%s\n\nstderr1:\n%s\n\nstderr2:\n%s",
stdout1, stdout2, stderr1, stderr2)
}
}
func TestCacheCoverage(t *testing.T) {
tooSlow(t)
if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
t.Skip("GODEBUG gocacheverify")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.makeTempdir()
tg.setenv("GOCACHE", tg.path("c1"))
tg.run("test", "-cover", "-short", "strings")
tg.run("test", "-cover", "-short", "math", "strings")
}
func TestIssue22588(t *testing.T) {
// Don't get confused by stderr coming from tools.
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
if _, err := os.Stat("/usr/bin/time"); err != nil {
t.Skip(err)
}
tg.run("list", "-f={{.Stale}}", "runtime")
tg.run("list", "-toolexec=/usr/bin/time", "-f={{.Stale}}", "runtime")
tg.grepStdout("false", "incorrectly reported runtime as stale")
}
func TestIssue22531(t *testing.T) {
tooSlow(t)
if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
t.Skip("GODEBUG gocacheverify")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", tg.tempdir)
tg.setenv("GOCACHE", tg.path("cache"))
tg.tempFile("src/m/main.go", "package main /* c1 */; func main() {}\n")
tg.run("install", "-x", "m")
tg.run("list", "-f", "{{.Stale}}", "m")
tg.grepStdout("false", "reported m as stale after install")
tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
// The link action ID did not include the full main build ID,
// even though the full main build ID is written into the
// eventual binary. That caused the following install to
// be a no-op, thinking the gofmt binary was up-to-date,
// even though .Stale could see it was not.
tg.tempFile("src/m/main.go", "package main /* c2 */; func main() {}\n")
tg.run("install", "-x", "m")
tg.run("list", "-f", "{{.Stale}}", "m")
tg.grepStdout("false", "reported m as stale after reinstall")
tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
}
func TestIssue22596(t *testing.T) {
tooSlow(t)
if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
t.Skip("GODEBUG gocacheverify")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOCACHE", tg.path("cache"))
tg.tempFile("gopath1/src/p/p.go", "package p; func F(){}\n")
tg.tempFile("gopath2/src/p/p.go", "package p; func F(){}\n")
tg.setenv("GOPATH", tg.path("gopath1"))
tg.run("list", "-f={{.Target}}", "p")
target1 := strings.TrimSpace(tg.getStdout())
tg.run("install", "p")
tg.wantNotStale("p", "", "p stale after install")
tg.setenv("GOPATH", tg.path("gopath2"))
tg.run("list", "-f={{.Target}}", "p")
target2 := strings.TrimSpace(tg.getStdout())
tg.must(os.MkdirAll(filepath.Dir(target2), 0777))
tg.must(copyFile(target1, target2, 0666))
tg.wantStale("p", "build ID mismatch", "p not stale after copy from gopath1")
tg.run("install", "p")
tg.wantNotStale("p", "", "p stale after install2")
}
func TestTestCache(t *testing.T) {
tooSlow(t)
if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
t.Skip("GODEBUG gocacheverify")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", tg.tempdir)
tg.setenv("GOCACHE", tg.path("cache"))
// timeout here should not affect result being cached
// or being retrieved later.
tg.run("test", "-x", "-timeout=10s", "errors")
tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler")
tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
tg.grepStderr(`errors\.test`, "did not run test")
tg.run("test", "-x", "errors")
tg.grepStdout(`ok \terrors\t\(cached\)`, "did not report cached result")
tg.grepStderrNot(`[\\/]compile|gccgo`, "incorrectly ran compiler")
tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly ran linker")
tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
tg.grepStderrNot("DO NOT USE", "poisoned action status leaked")
// Even very low timeouts do not disqualify cached entries.
tg.run("test", "-timeout=1ns", "-x", "errors")
tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
tg.run("clean", "-testcache")
tg.run("test", "-x", "errors")
tg.grepStderr(`errors\.test`, "did not run test")
// The -p=1 in the commands below just makes the -x output easier to read.
t.Log("\n\nINITIAL\n\n")
tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\nvar X = 1\n")
tg.tempFile("src/t/t1/t1_test.go", "package t\nimport \"testing\"\nfunc Test1(*testing.T) {}\n")
tg.tempFile("src/t/t2/t2_test.go", "package t\nimport _ \"p1\"\nimport \"testing\"\nfunc Test2(*testing.T) {}\n")
tg.tempFile("src/t/t3/t3_test.go", "package t\nimport \"p1\"\nimport \"testing\"\nfunc Test3(t *testing.T) {t.Log(p1.X)}\n")
tg.tempFile("src/t/t4/t4_test.go", "package t\nimport \"p2\"\nimport \"testing\"\nfunc Test4(t *testing.T) {t.Log(p2.X)}")
tg.run("test", "-x", "-v", "-short", "t/...")
t.Log("\n\nREPEAT\n\n")
tg.run("test", "-x", "-v", "-short", "t/...")
tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
tg.grepStderrNot(`[\\/]compile|gccgo`, "incorrectly ran compiler")
tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly ran linker")
tg.grepStderrNot(`p[0-9]\.test`, "incorrectly ran test")
t.Log("\n\nCOMMENT\n\n")
// Changing the program text without affecting the compiled package
// should result in the package being rebuilt but nothing more.
tg.tempFile("src/p1/p1.go", "package p1\nvar X = 01\n")
tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
tg.grepStderrNot(`([\\/]compile|gccgo).*t[0-9]_test\.go`, "incorrectly ran compiler")
tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly ran linker")
tg.grepStderrNot(`t[0-9]\.test.*test\.short`, "incorrectly ran test")
t.Log("\n\nCHANGE\n\n")
// Changing the actual package should have limited effects.
tg.tempFile("src/p1/p1.go", "package p1\nvar X = 02\n")
tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
// p2 should have been rebuilt.
tg.grepStderr(`([\\/]compile|gccgo).*p2.go`, "did not recompile p2")
// t1 does not import anything, should not have been rebuilt.
tg.grepStderrNot(`([\\/]compile|gccgo).*t1_test.go`, "incorrectly recompiled t1")
tg.grepStderrNot(`([\\/]link|gccgo).*t1_test`, "incorrectly relinked t1_test")
tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t/t1")
// t2 imports p1 and must be rebuilt and relinked,
// but the change should not have any effect on the test binary,
// so the test should not have been rerun.
tg.grepStderr(`([\\/]compile|gccgo).*t2_test.go`, "did not recompile t2")
tg.grepStderr(`([\\/]link|gccgo).*t2\.test`, "did not relink t2_test")
tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t/t2")
// t3 imports p1, and changing X changes t3's test binary.
tg.grepStderr(`([\\/]compile|gccgo).*t3_test.go`, "did not recompile t3")
tg.grepStderr(`([\\/]link|gccgo).*t3\.test`, "did not relink t3_test")
tg.grepStderr(`t3\.test.*-test.short`, "did not rerun t3_test")
tg.grepStdoutNot(`ok \tt/t3\t\(cached\)`, "reported cached t3_test result")
// t4 imports p2, but p2 did not change, so t4 should be relinked, not recompiled,
// and not rerun.
tg.grepStderrNot(`([\\/]compile|gccgo).*t4_test.go`, "incorrectly recompiled t4")
tg.grepStderr(`([\\/]link|gccgo).*t4\.test`, "did not relink t4_test")
tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t/t4")
}
func TestTestCacheInputs(t *testing.T) {
tooSlow(t)
if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
t.Skip("GODEBUG gocacheverify")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.setenv("GOCACHE", tg.path("cache"))
defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"))
tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("x"), 0644))
old := time.Now().Add(-1 * time.Minute)
tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
info, err := os.Stat(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
if err != nil {
t.Fatal(err)
}
t.Logf("file.txt: old=%v, info.ModTime=%v", old, info.ModTime()) // help debug when Chtimes lies about succeeding
tg.setenv("TESTKEY", "x")
tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), []byte("#!/bin/sh\nexit 0\n"), 0755))
tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old, old))
tg.run("test", "testcache")
tg.run("test", "testcache")
tg.grepStdout(`\(cached\)`, "did not cache")
tg.setenv("TESTKEY", "y")
tg.run("test", "testcache")
tg.grepStdoutNot(`\(cached\)`, "did not notice env var change")
tg.run("test", "testcache")
tg.grepStdout(`\(cached\)`, "did not cache")
tg.run("test", "testcache", "-run=FileSize")
tg.run("test", "testcache", "-run=FileSize")
tg.grepStdout(`\(cached\)`, "did not cache")
tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxx"), 0644))
tg.run("test", "testcache", "-run=FileSize")
tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
tg.run("test", "testcache", "-run=FileSize")
tg.grepStdout(`\(cached\)`, "did not cache")
tg.run("test", "testcache", "-run=Chdir")
tg.run("test", "testcache", "-run=Chdir")
tg.grepStdout(`\(cached\)`, "did not cache")
tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxxxx"), 0644))
tg.run("test", "testcache", "-run=Chdir")
tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
tg.run("test", "testcache", "-run=Chdir")
tg.grepStdout(`\(cached\)`, "did not cache")
tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
tg.run("test", "testcache", "-run=FileContent")
tg.run("test", "testcache", "-run=FileContent")
tg.grepStdout(`\(cached\)`, "did not cache")
tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("yyy"), 0644))
old2 := old.Add(10 * time.Second)
tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old2, old2))
tg.run("test", "testcache", "-run=FileContent")
tg.grepStdoutNot(`\(cached\)`, "did not notice file content change")
tg.run("test", "testcache", "-run=FileContent")
tg.grepStdout(`\(cached\)`, "did not cache")
tg.run("test", "testcache", "-run=DirList")
tg.run("test", "testcache", "-run=DirList")
tg.grepStdout(`\(cached\)`, "did not cache")
tg.must(os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt")))
tg.run("test", "testcache", "-run=DirList")
tg.grepStdoutNot(`\(cached\)`, "did not notice directory change")
tg.run("test", "testcache", "-run=DirList")
tg.grepStdout(`\(cached\)`, "did not cache")
tg.tempFile("file.txt", "")
tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"), []byte(`package testcache
import (
"os"
"testing"
)
func TestExternalFile(t *testing.T) {
os.Open(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
_, err := os.Stat(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
if err != nil {
t.Fatal(err)
}
}
`), 0666))
defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"))
tg.run("test", "testcache", "-run=ExternalFile")
tg.run("test", "testcache", "-run=ExternalFile")
tg.grepStdout(`\(cached\)`, "did not cache")
tg.must(os.Remove(filepath.Join(tg.tempdir, "file.txt")))
tg.run("test", "testcache", "-run=ExternalFile")
tg.grepStdout(`\(cached\)`, "did not cache")
switch runtime.GOOS {
case "nacl", "plan9", "windows":
// no shell scripts
default:
tg.run("test", "testcache", "-run=Exec")
tg.run("test", "testcache", "-run=Exec")
tg.grepStdout(`\(cached\)`, "did not cache")
tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old2, old2))
tg.run("test", "testcache", "-run=Exec")
tg.grepStdoutNot(`\(cached\)`, "did not notice script change")
tg.run("test", "testcache", "-run=Exec")
tg.grepStdout(`\(cached\)`, "did not cache")
}
}
func TestNoCache(t *testing.T) {
switch runtime.GOOS {
case "windows":
t.Skipf("no unwritable directories on %s", runtime.GOOS)
}
if os.Getuid() == 0 {
t.Skip("skipping test because running as root")
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("triv.go", `package main; func main() {}`)
tg.must(os.MkdirAll(tg.path("unwritable"), 0555))
home := "HOME"
if runtime.GOOS == "plan9" {
home = "home"
}
tg.setenv(home, tg.path(filepath.Join("unwritable", "home")))
tg.unsetenv("GOCACHE")
tg.run("build", "-o", tg.path("triv"), tg.path("triv.go"))
tg.grepStderr("disabling cache", "did not disable cache")
}
func TestTestVet(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("p1_test.go", `
package p
import "testing"
func Test(t *testing.T) {
t.Logf("%d") // oops
}
`)
tg.runFail("test", tg.path("p1_test.go"))
tg.grepStderr(`Logf format %d`, "did not diagnose bad Logf")
tg.run("test", "-vet=off", tg.path("p1_test.go"))
tg.grepStdout(`^ok`, "did not print test summary")
tg.tempFile("p1.go", `
package p
import "fmt"
func F() {
fmt.Printf("%d") // oops
}
`)
tg.runFail("test", tg.path("p1.go"))
tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
tg.run("test", "-x", "-vet=shift", tg.path("p1.go"))
tg.grepStderr(`[\\/]vet.*-shift`, "did not run vet with -shift")
tg.grepStdout(`\[no test files\]`, "did not print test summary")
tg.run("test", "-vet=off", tg.path("p1.go"))
tg.grepStdout(`\[no test files\]`, "did not print test summary")
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.run("test", "vetcycle") // must not fail; #22890
tg.runFail("test", "vetfail/...")
tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
tg.grepStdout(`ok\s+vetfail/p2`, "did not run vetfail/p2")
}
func TestTestVetRebuild(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
// golang.org/issue/23701.
// b_test imports b with augmented method from export_test.go.
// b_test also imports a, which imports b.
// Must not accidentally see un-augmented b propagate through a to b_test.
tg.tempFile("src/a/a.go", `package a
import "b"
type Type struct{}
func (*Type) M() b.T {return 0}
`)
tg.tempFile("src/b/b.go", `package b
type T int
type I interface {M() T}
`)
tg.tempFile("src/b/export_test.go", `package b
func (*T) Method() *T { return nil }
`)
tg.tempFile("src/b/b_test.go", `package b_test
import (
"testing"
"a"
. "b"
)
func TestBroken(t *testing.T) {
x := new(T)
x.Method()
_ = new(a.Type)
}
`)
tg.setenv("GOPATH", tg.path("."))
tg.run("test", "b")
tg.run("vet", "b")
}
func TestInstallDeps(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOPATH", tg.tempdir)
tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\n")
tg.tempFile("src/main1/main.go", "package main\nimport _ \"p2\"\nfunc main() {}\n")
tg.run("list", "-f={{.Target}}", "p1")
p1 := strings.TrimSpace(tg.getStdout())
tg.run("list", "-f={{.Target}}", "p2")
p2 := strings.TrimSpace(tg.getStdout())
tg.run("list", "-f={{.Target}}", "main1")
main1 := strings.TrimSpace(tg.getStdout())
tg.run("install", "main1")
tg.mustExist(main1)
tg.mustNotExist(p2)
tg.mustNotExist(p1)
tg.run("install", "p2")
tg.mustExist(p2)
tg.mustNotExist(p1)
// don't let install -i overwrite runtime
tg.wantNotStale("runtime", "", "must be non-stale before install -i")
tg.run("install", "-i", "main1")
tg.mustExist(p1)
tg.must(os.Remove(p1))
tg.run("install", "-i", "p2")
tg.mustExist(p1)
}
func TestFmtLoadErrors(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
tg.runFail("fmt", "does-not-exist")
tg.run("fmt", "-n", "exclude")
}
func TestRelativePkgdir(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.makeTempdir()
tg.setenv("GOCACHE", "off")
tg.cd(tg.tempdir)
tg.run("build", "-i", "-pkgdir=.", "runtime")
}
func TestGcflagsPatterns(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.setenv("GOPATH", "")
tg.setenv("GOCACHE", "off")
tg.run("build", "-n", "-v", "-gcflags= \t\r\n -e", "fmt")
tg.grepStderr("^# fmt", "did not rebuild fmt")
tg.grepStderrNot("^# reflect", "incorrectly rebuilt reflect")
tg.run("build", "-n", "-v", "-gcflags=-e", "fmt", "reflect")
tg.grepStderr("^# fmt", "did not rebuild fmt")
tg.grepStderr("^# reflect", "did not rebuild reflect")
tg.grepStderrNot("^# runtime", "incorrectly rebuilt runtime")
tg.run("build", "-n", "-x", "-v", "-gcflags= \t\r\n reflect \t\r\n = \t\r\n -N", "fmt")
tg.grepStderr("^# fmt", "did not rebuild fmt")
tg.grepStderr("^# reflect", "did not rebuild reflect")
tg.grepStderr("compile.* -N .*-p reflect", "did not build reflect with -N flag")
tg.grepStderrNot("compile.* -N .*-p fmt", "incorrectly built fmt with -N flag")
tg.run("test", "-c", "-n", "-gcflags=-N", "-ldflags=-X=x.y=z", "strings")
tg.grepStderr("compile.* -N .*compare_test.go", "did not compile strings_test package with -N flag")
tg.grepStderr("link.* -X=x.y=z", "did not link strings.test binary with -X flag")
tg.run("test", "-c", "-n", "-gcflags=strings=-N", "-ldflags=strings=-X=x.y=z", "strings")
tg.grepStderr("compile.* -N .*compare_test.go", "did not compile strings_test package with -N flag")
tg.grepStderr("link.* -X=x.y=z", "did not link strings.test binary with -X flag")
}
func TestGoTestMinusN(t *testing.T) {
// Intent here is to verify that 'go test -n' works without crashing.
// This reuses flag_test.go, but really any test would do.
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "testdata/flag_test.go", "-n", "-args", "-v=7")
}
func TestGoTestJSON(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.makeTempdir()
tg.setenv("GOCACHE", tg.tempdir)
tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
// It would be nice to test that the output is interlaced
// but it seems to be impossible to do that in a short test
// that isn't also flaky. Just check that we get JSON output.
tg.run("test", "-json", "-short", "-v", "errors", "empty/pkg", "skipper")
tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
tg.grepStdout(`"Action":"run"`, "did not see JSON output")
tg.grepStdout(`"Action":"output","Package":"empty/pkg","Output":".*no test files`, "did not see no test files print")
tg.grepStdout(`"Action":"skip","Package":"empty/pkg"`, "did not see skip")
tg.grepStdout(`"Action":"output","Package":"skipper","Test":"Test","Output":"--- SKIP:`, "did not see SKIP output")
tg.grepStdout(`"Action":"skip","Package":"skipper","Test":"Test"`, "did not see skip result for Test")
tg.run("test", "-json", "-short", "-v", "errors")
tg.grepStdout(`"Action":"output","Package":"errors","Output":".*\(cached\)`, "did not see no cached output")
tg.run("test", "-json", "-bench=NONE", "-short", "-v", "errors")
tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
tg.grepStdout(`"Action":"run"`, "did not see JSON output")
tg.run("test", "-o", tg.path("errors.test.exe"), "-c", "errors")
tg.run("tool", "test2json", "-p", "errors", tg.path("errors.test.exe"), "-test.v", "-test.short")
tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
tg.grepStdout(`"Action":"run"`, "did not see JSON output")
tg.grepStdout(`\{"Action":"pass","Package":"errors"\}`, "did not see final pass")
}
func TestFailFast(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tests := []struct {
run string
failfast bool
nfail int
}{
{"TestFailingA", true, 1},
{"TestFailing[AB]", true, 1},
{"TestFailing[AB]", false, 2},
// mix with non-failing tests:
{"TestA|TestFailing[AB]", true, 1},
{"TestA|TestFailing[AB]", false, 2},
// mix with parallel tests:
{"TestFailingB|TestParallelFailingA", true, 2},
{"TestFailingB|TestParallelFailingA", false, 2},
{"TestFailingB|TestParallelFailing[AB]", true, 3},
{"TestFailingB|TestParallelFailing[AB]", false, 3},
// mix with parallel sub-tests
{"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", true, 3},
{"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", false, 5},
{"TestParallelFailingSubtestsA", true, 1},
// only parallels:
{"TestParallelFailing[AB]", false, 2},
// non-parallel subtests:
{"TestFailingSubtestsA", true, 1},
{"TestFailingSubtestsA", false, 2},
}
for _, tt := range tests {
t.Run(tt.run, func(t *testing.T) {
tg.runFail("test", "./testdata/src/failfast_test.go", "-run="+tt.run, "-failfast="+strconv.FormatBool(tt.failfast))
nfail := strings.Count(tg.getStdout(), "FAIL - ")
if nfail != tt.nfail {
t.Errorf("go test -run=%s -failfast=%t printed %d FAILs, want %d", tt.run, tt.failfast, nfail, tt.nfail)
}
})
}
}
// Issue 22986.
func TestImportPath(t *testing.T) {
tooSlow(t)
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/a/a.go", `
package main
import (
"log"
p "a/p-1.0"
)
func main() {
if !p.V {
log.Fatal("false")
}
}`)
tg.tempFile("src/a/a_test.go", `
package main_test
import (
p "a/p-1.0"
"testing"
)
func TestV(t *testing.T) {
if !p.V {
t.Fatal("false")
}
}`)
tg.tempFile("src/a/p-1.0/p.go", `
package p
var V = true
func init() {}
`)
tg.setenv("GOPATH", tg.path("."))
tg.run("build", "-o", tg.path("a.exe"), "a")
tg.run("test", "a")
}
// Issue 23150.
func TestCpuprofileTwice(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("prof/src/x/x_test.go", `
package x_test
import (
"testing"
"time"
)
func TestSleep(t *testing.T) { time.Sleep(10 * time.Millisecond) }`)
tg.setenv("GOPATH", tg.path("prof"))
bin := tg.path("x.test")
out := tg.path("cpu.out")
tg.run("test", "-o="+bin, "-cpuprofile="+out, "x")
tg.must(os.Remove(out))
tg.run("test", "-o="+bin, "-cpuprofile="+out, "x")
tg.mustExist(out)
}
// Issue 23694.
func TestAtomicCoverpkgAll(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/x/x.go", `package x; import _ "sync/atomic"; func F() {}`)
tg.tempFile("src/x/x_test.go", `package x; import "testing"; func TestF(t *testing.T) { F() }`)
tg.setenv("GOPATH", tg.path("."))
tg.run("test", "-coverpkg=all", "-covermode=atomic", "x")
if canRace {
tg.run("test", "-coverpkg=all", "-race", "x")
}
}
// Issue 23882.
func TestCoverpkgAllRuntime(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/x/x.go", `package x; import _ "runtime"; func F() {}`)
tg.tempFile("src/x/x_test.go", `package x; import "testing"; func TestF(t *testing.T) { F() }`)
tg.setenv("GOPATH", tg.path("."))
tg.run("test", "-coverpkg=all", "x")
if canRace {
tg.run("test", "-coverpkg=all", "-race", "x")
}
}
func TestBadCommandLines(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("src/x/x.go", "package x\n")
tg.setenv("GOPATH", tg.path("."))
tg.run("build", "x")
tg.tempFile("src/x/@y.go", "package x\n")
tg.runFail("build", "x")
tg.grepStderr("invalid input file name \"@y.go\"", "did not reject @y.go")
tg.must(os.Remove(tg.path("src/x/@y.go")))
tg.tempFile("src/x/-y.go", "package x\n")
tg.runFail("build", "x")
tg.grepStderr("invalid input file name \"-y.go\"", "did not reject -y.go")
tg.must(os.Remove(tg.path("src/x/-y.go")))
tg.runFail("build", "-gcflags=all=@x", "x")
tg.grepStderr("invalid command-line argument @x in command", "did not reject @x during exec")
tg.tempFile("src/@x/x.go", "package x\n")
tg.setenv("GOPATH", tg.path("."))
tg.runFail("build", "@x")
tg.grepStderr("invalid input directory name \"@x\"", "did not reject @x directory")
tg.tempFile("src/@x/y/y.go", "package y\n")
tg.setenv("GOPATH", tg.path("."))
tg.runFail("build", "@x/y")
tg.grepStderr("invalid import path \"@x/y\"", "did not reject @x/y import path")
tg.tempFile("src/-x/x.go", "package x\n")
tg.setenv("GOPATH", tg.path("."))
tg.runFail("build", "--", "-x")
tg.grepStderr("invalid input directory name \"-x\"", "did not reject -x directory")
tg.tempFile("src/-x/y/y.go", "package y\n")
tg.setenv("GOPATH", tg.path("."))
tg.runFail("build", "--", "-x/y")
tg.grepStderr("invalid import path \"-x/y\"", "did not reject -x/y import path")
}
func TestBadCgoDirectives(t *testing.T) {
if !canCgo {
t.Skip("no cgo")
}
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("src/x/x.go", "package x\n")
tg.setenv("GOPATH", tg.path("."))
tg.tempFile("src/x/x.go", `package x
//go:cgo_ldflag "-fplugin=foo.so"
import "C"
`)
tg.runFail("build", "x")
tg.grepStderr("//go:cgo_ldflag .* only allowed in cgo-generated code", "did not reject //go:cgo_ldflag directive")
tg.must(os.Remove(tg.path("src/x/x.go")))
tg.runFail("build", "x")
tg.grepStderr("no Go files", "did not report missing source code")
tg.tempFile("src/x/_cgo_yy.go", `package x
//go:cgo_ldflag "-fplugin=foo.so"
import "C"
`)
tg.runFail("build", "x")
tg.grepStderr("no Go files", "did not report missing source code") // _* files are ignored...
tg.runFail("build", tg.path("src/x/_cgo_yy.go")) // ... but if forced, the comment is rejected
// Actually, today there is a separate issue that _ files named
// on the command-line are ignored. Once that is fixed,
// we want to see the cgo_ldflag error.
tg.grepStderr("//go:cgo_ldflag only allowed in cgo-generated code|no Go files", "did not reject //go:cgo_ldflag directive")
tg.must(os.Remove(tg.path("src/x/_cgo_yy.go")))
tg.tempFile("src/x/x.go", "package x\n")
tg.tempFile("src/x/y.go", `package x
// #cgo CFLAGS: -fplugin=foo.so
import "C"
`)
tg.runFail("build", "x")
tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
tg.tempFile("src/x/y.go", `package x
// #cgo CFLAGS: -Ibar -fplugin=foo.so
import "C"
`)
tg.runFail("build", "x")
tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
tg.tempFile("src/x/y.go", `package x
// #cgo pkg-config: -foo
import "C"
`)
tg.runFail("build", "x")
tg.grepStderr("invalid pkg-config package name: -foo", "did not reject pkg-config: -foo")
tg.tempFile("src/x/y.go", `package x
// #cgo pkg-config: @foo
import "C"
`)
tg.runFail("build", "x")
tg.grepStderr("invalid pkg-config package name: @foo", "did not reject pkg-config: -foo")
tg.tempFile("src/x/y.go", `package x
// #cgo CFLAGS: @foo
import "C"
`)
tg.runFail("build", "x")
tg.grepStderr("invalid flag in #cgo CFLAGS: @foo", "did not reject @foo flag")
tg.tempFile("src/x/y.go", `package x
// #cgo CFLAGS: -D
import "C"
`)
tg.runFail("build", "x")
tg.grepStderr("invalid flag in #cgo CFLAGS: -D without argument", "did not reject trailing -I flag")
// Note that -I @foo is allowed because we rewrite it into -I /path/to/src/@foo
// before the check is applied. There's no such rewrite for -D.
tg.tempFile("src/x/y.go", `package x
// #cgo CFLAGS: -D @foo
import "C"
`)
tg.runFail("build", "x")
tg.grepStderr("invalid flag in #cgo CFLAGS: -D @foo", "did not reject -D @foo flag")
tg.tempFile("src/x/y.go", `package x
// #cgo CFLAGS: -D@foo
import "C"
`)
tg.runFail("build", "x")
tg.grepStderr("invalid flag in #cgo CFLAGS: -D@foo", "did not reject -D@foo flag")
tg.setenv("CGO_CFLAGS", "-D@foo")
tg.tempFile("src/x/y.go", `package x
import "C"
`)
tg.run("build", "-n", "x")
tg.grepStderr("-D@foo", "did not find -D@foo in commands")
}
func TestTwoPkgConfigs(t *testing.T) {
if !canCgo {
t.Skip("no cgo")
}
if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
t.Skipf("no shell scripts on %s", runtime.GOOS)
}
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/x/a.go", `package x
// #cgo pkg-config: --static a
import "C"
`)
tg.tempFile("src/x/b.go", `package x
// #cgo pkg-config: --static a
import "C"
`)
tg.tempFile("pkg-config.sh", `#!/bin/sh
echo $* >>`+tg.path("pkg-config.out"))
tg.must(os.Chmod(tg.path("pkg-config.sh"), 0755))
tg.setenv("GOPATH", tg.path("."))
tg.setenv("PKG_CONFIG", tg.path("pkg-config.sh"))
tg.run("build", "x")
out, err := ioutil.ReadFile(tg.path("pkg-config.out"))
tg.must(err)
out = bytes.TrimSpace(out)
want := "--cflags --static --static -- a a\n--libs --static --static -- a a"
if !bytes.Equal(out, []byte(want)) {
t.Errorf("got %q want %q", out, want)
}
}
// Issue 23982
func TestFilepathUnderCwdFormat(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.run("test", "-x", "-cover", "log")
tg.grepStderrNot(`\.log\.cover\.go`, "-x output should contain correctly formatted filepath under cwd")
}
// Issue 24396.
func TestDontReportRemoveOfEmptyDir(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.parallel()
tg.tempFile("src/a/a.go", `package a`)
tg.setenv("GOPATH", tg.path("."))
tg.run("install", "-x", "a")
tg.run("install", "-x", "a")
// The second install should have printed only a WORK= line,
// nothing else.
if bytes.Count(tg.stdout.Bytes(), []byte{'\n'})+bytes.Count(tg.stderr.Bytes(), []byte{'\n'}) > 1 {
t.Error("unnecessary output when installing installed package")
}
}
// Issue 23264.
func TestNoRelativeTmpdir(t *testing.T) {
tg := testgo(t)
defer tg.cleanup()
tg.tempFile("src/a/a.go", `package a`)
tg.cd(tg.path("."))
tg.must(os.Mkdir("tmp", 0777))
tg.setenv("GOCACHE", "off")
tg.setenv("GOPATH", tg.path("."))
tg.setenv("GOTMPDIR", "tmp")
tg.runFail("build", "a")
tg.grepStderr("relative tmpdir", "wrong error")
if runtime.GOOS != "windows" && runtime.GOOS != "plan9" {
tg.unsetenv("GOTMPDIR")
tg.setenv("TMPDIR", "tmp")
tg.runFail("build", "a")
tg.grepStderr("relative tmpdir", "wrong error")
}
}
| [
"\"GO_GCFLAGS\"",
"\"HOME\"",
"\"CCACHE_DIR\"",
"\"GOCACHE\"",
"\"PATH\"",
"\"GOPATH\"",
"\"TERM\"",
"\"TERM\"",
"\"GODEBUG\"",
"\"GODEBUG\"",
"\"GODEBUG\"",
"\"GODEBUG\"",
"\"GODEBUG\"",
"\"GODEBUG\"",
"\"GODEBUG\""
]
| []
| [
"GO_GCFLAGS",
"CCACHE_DIR",
"GOPATH",
"TERM",
"GOCACHE",
"GODEBUG",
"HOME",
"PATH"
]
| [] | ["GO_GCFLAGS", "CCACHE_DIR", "GOPATH", "TERM", "GOCACHE", "GODEBUG", "HOME", "PATH"] | go | 8 | 0 | |
api/utility.go | package api
import (
"encoding/json"
"fmt"
"math/rand"
"net/http"
"os"
"time"
mailjet "github.com/mailjet/mailjet-apiv3-go"
)
//Key pass values to send email
var key = os.Getenv("SMTP_KEY")
var pass = os.Getenv("SMTP_PASS")
//SendResponse is use to send the given data as a response
func SendResponse(w http.ResponseWriter, data interface{}, code int) {
b, _ := json.Marshal(data)
w.WriteHeader(code)
w.Write(b)
return
}
//Generates the unique ID for interview
func generateID() int {
rand.Seed(time.Now().UnixNano())
min := 1
max := 100
return rand.Intn(max-min+1) + min
}
var from = &mailjet.RecipientV31{
Email: "[email protected]",
Name: "Yashi Gupta",
}
var client = mailjet.NewMailjetClient(key, pass)
//SendEmail function is used to send notification Email
func SendEmail(RecipientEmail string, RecipientName string, Body string) bool {
messagesInfo := []mailjet.InfoMessagesV31{
mailjet.InfoMessagesV31{
From: from,
To: &mailjet.RecipientsV31{
mailjet.RecipientV31{
Email: RecipientEmail,
Name: RecipientName,
},
},
Subject: "Interview Scheduled",
TextPart: "You have an Interview Scheduled " + Body,
HTMLPart: ``,
},
}
messages := mailjet.MessagesV31{Info: messagesInfo}
res, err := client.SendMailV31(&messages)
if err != nil {
fmt.Println("error while sending mail", err)
return false
}
fmt.Println(res.ResultsV31)
return true
}
// func RequestParamCheck(){
// }
| [
"\"SMTP_KEY\"",
"\"SMTP_PASS\""
]
| []
| [
"SMTP_KEY",
"SMTP_PASS"
]
| [] | ["SMTP_KEY", "SMTP_PASS"] | go | 2 | 0 | |
pwnlib/tubes/ssh.py | from __future__ import absolute_import
from __future__ import division
import inspect
import logging
import os
import re
import shutil
import six
import string
import sys
import tarfile
import tempfile
import threading
import time
import types
from pwnlib import term
from pwnlib.context import context
from pwnlib.log import Logger
from pwnlib.log import getLogger
from pwnlib.term import text
from pwnlib.timeout import Timeout
from pwnlib.tubes.sock import sock
from pwnlib.util import hashes
from pwnlib.util import misc
from pwnlib.util import safeeval
from pwnlib.util.sh_string import sh_string
# Kill the warning line:
# No handlers could be found for logger "paramiko.transport"
paramiko_log = logging.getLogger("paramiko.transport")
h = logging.StreamHandler(open('/dev/null','w+'))
h.setFormatter(logging.Formatter())
paramiko_log.addHandler(h)
class ssh_channel(sock):
#: Parent :class:`ssh` object
parent = None
#: Remote host
host = None
#: Return code, or :const:`None` if the process has not returned
#: Use :meth:`poll` to check.
returncode = None
#: :const:`True` if a tty was allocated for this channel
tty = False
#: Environment specified for the remote process, or :const:`None`
#: if the default environment was used
env = None
#: Command specified for the constructor
process = None
def __init__(self, parent, process = None, tty = False, wd = None, env = None, raw = True, *args, **kwargs):
super(ssh_channel, self).__init__(*args, **kwargs)
# keep the parent from being garbage collected in some cases
self.parent = parent
self.returncode = None
self.host = parent.host
self.tty = tty
self.env = env
self.process = process
if isinstance(wd, six.text_type):
wd = wd.encode('utf-8')
self.cwd = wd or b'.'
env = env or {}
msg = 'Opening new channel: %r' % (process or 'shell')
if isinstance(process, (list, tuple)):
process = b' '.join((lambda x:x.encode('utf-8') if isinstance(x, six.text_type) else x)(sh_string(s)) for s in process)
if isinstance(process, six.text_type):
process = process.encode('utf-8')
if process and wd:
process = b'cd ' + sh_string(wd) + b' >/dev/null 2>&1;' + process
if process and env:
for name, value in env.items():
if not re.match('^[a-zA-Z_][a-zA-Z0-9_]*$', name):
self.error('run(): Invalid environment key %r' % name)
export = 'export %s=%s;' % (name, sh_string(value))
if isinstance(export, six.text_type):
export = export.encode('utf-8')
process = export + process
if process and tty:
if raw:
process = b'stty raw -ctlecho -echo; ' + process
else:
process = b'stty -ctlecho -echo; ' + process
# If this object is enabled for DEBUG-level logging, don't hide
# anything about the command that's actually executed.
if process and self.isEnabledFor(logging.DEBUG):
msg = 'Opening new channel: %r' % ((process,) or 'shell')
with self.waitfor(msg) as h:
import paramiko
try:
self.sock = parent.transport.open_session()
except paramiko.ChannelException as e:
if e.args == (1, 'Administratively prohibited'):
self.error("Too many sessions open! Use ssh_channel.close() or 'with'!")
raise e
if self.tty:
self.sock.get_pty('xterm', term.width, term.height)
def resizer():
if self.sock:
try:
self.sock.resize_pty(term.width, term.height)
except paramiko.ssh_exception.SSHException:
pass
self.resizer = resizer
term.term.on_winch.append(self.resizer)
else:
self.resizer = None
# Put stderr on stdout. This might not always be desirable,
# but our API does not support multiple streams
self.sock.set_combine_stderr(True)
self.settimeout(self.timeout)
if process:
self.sock.exec_command(process)
else:
self.sock.invoke_shell()
h.success()
def kill(self):
"""kill()
Kills the process.
"""
self.close()
def recvall(self, timeout = sock.forever):
# We subclass tubes.sock which sets self.sock to None.
#
# However, we need to wait for the return value to propagate,
# which may not happen by the time .close() is called by tube.recvall()
tmp_sock = self.sock
tmp_close = self.close
self.close = lambda: None
timeout = self.maximum if self.timeout is self.forever else self.timeout
data = super(ssh_channel, self).recvall(timeout)
# Restore self.sock to be able to call wait()
self.close = tmp_close
self.sock = tmp_sock
self.wait()
self.close()
# Again set self.sock to None
self.sock = None
return data
def wait(self):
return self.poll(block=True)
def poll(self, block=False):
"""poll() -> int
Poll the exit code of the process. Will return None, if the
process has not yet finished and the exit code otherwise.
"""
if self.returncode == None and self.sock \
and (block or self.sock.exit_status_ready()):
while not self.sock.status_event.is_set():
self.sock.status_event.wait(0.05)
self.returncode = self.sock.recv_exit_status()
return self.returncode
def can_recv_raw(self, timeout):
with self.countdown(timeout):
while self.countdown_active():
if self.sock.recv_ready():
return True
time.sleep(min(self.timeout, 0.05))
return False
def interactive(self, prompt = term.text.bold_red('$') + ' '):
"""interactive(prompt = pwnlib.term.text.bold_red('$') + ' ')
If not in TTY-mode, this does exactly the same as
meth:`pwnlib.tubes.tube.tube.interactive`, otherwise
it does mostly the same.
An SSH connection in TTY-mode will typically supply its own prompt,
thus the prompt argument is ignored in this case.
We also have a few SSH-specific hacks that will ideally be removed
once the :mod:`pwnlib.term` is more mature.
"""
# If we are only executing a regular old shell, we need to handle
# control codes (specifically Ctrl+C).
#
# Otherwise, we can just punt to the default implementation of interactive()
if self.process is not None:
return super(ssh_channel, self).interactive(prompt)
self.info('Switching to interactive mode')
# We would like a cursor, please!
term.term.show_cursor()
event = threading.Event()
def recv_thread(event):
while not event.is_set():
try:
cur = self.recv(timeout = 0.05)
cur = cur.replace(b'\r\n',b'\n')
cur = cur.replace(b'\r',b'')
if cur == None:
continue
elif cur == b'\a':
# Ugly hack until term unstands bell characters
continue
stdout = sys.stdout
if not term.term_mode:
stdout = getattr(stdout, 'buffer', stdout)
stdout.write(cur)
stdout.flush()
except EOFError:
self.info('Got EOF while reading in interactive')
event.set()
break
t = context.Thread(target = recv_thread, args = (event,))
t.daemon = True
t.start()
while not event.is_set():
if term.term_mode:
try:
data = term.key.getraw(0.1)
except KeyboardInterrupt:
data = [3] # This is ctrl-c
except IOError:
if not event.is_set():
raise
else:
stdin = getattr(sys.stdin, 'buffer', sys.stdin)
data = stdin.read(1)
if not data:
event.set()
else:
data = [six.byte2int(data)]
if data:
try:
self.send(b''.join(six.int2byte(c) for c in data))
except EOFError:
event.set()
self.info('Got EOF while sending in interactive')
while t.is_alive():
t.join(timeout = 0.1)
# Restore
term.term.hide_cursor()
def close(self):
self.poll()
while self.resizer in term.term.on_winch:
term.term.on_winch.remove(self.resizer)
super(ssh_channel, self).close()
def spawn_process(self, *args, **kwargs):
self.error("Cannot use spawn_process on an SSH channel.""")
def _close_msg(self):
self.info('Closed SSH channel with %s' % self.host)
class ssh_process(ssh_channel):
#: Working directory
cwd = None
#: PID of the process
#: Only valid when instantiated through :meth:`ssh.process`
pid = None
#: Executable of the procesks
#: Only valid when instantiated through :meth:`ssh.process`
executable = None
#: Arguments passed to the process
#: Only valid when instantiated through :meth:`ssh.process`
argv = None
def libs(self):
"""libs() -> dict
Returns a dictionary mapping the address of each loaded library in the
process's address space.
If ``/proc/$PID/maps`` cannot be opened, the output of ldd is used
verbatim, which may be different than the actual addresses if ASLR
is enabled.
"""
maps = self.parent.libs(self.executable)
maps_raw = self.parent.cat('/proc/%d/maps' % self.pid)
for lib in maps:
remote_path = lib.split(self.parent.host)[-1]
for line in maps_raw.splitlines():
if line.endswith(remote_path):
address = line.split('-')[0]
maps[lib] = int(address, 16)
break
return maps
@property
def libc(self):
"""libc() -> ELF
Returns an ELF for the libc for the current process.
If possible, it is adjusted to the correct address
automatically.
"""
from pwnlib.elf import ELF
for lib, address in self.libs().items():
if 'libc.so' in lib:
e = ELF(lib)
e.address = address
return e
@property
def elf(self):
"""elf() -> pwnlib.elf.elf.ELF
Returns an ELF file for the executable that launched the process.
"""
import pwnlib.elf.elf
libs = self.parent.libs(self.executable)
for lib in libs:
# Cannot just check "executable in lib", see issue #1047
if lib.endswith(self.executable):
return pwnlib.elf.elf.ELF(lib)
@property
def corefile(self):
import pwnlib.elf.corefile
finder = pwnlib.elf.corefile.CorefileFinder(self)
if not finder.core_path:
self.error("Could not find core file for pid %i" % self.pid)
return pwnlib.elf.corefile.Corefile(finder.core_path)
def getenv(self, variable, **kwargs):
"""Retrieve the address of an environment variable in the remote process.
"""
argv0 = self.argv[0]
script = ';'.join(('from ctypes import *',
'import os',
'libc = CDLL("libc.so.6")',
'print(os.path.realpath(%r))' % self.executable,
'print(libc.getenv(%r))' % variable,))
try:
with context.local(log_level='error'):
python = self.parent.which('python')
if not python:
self.error("Python is not installed on the remote system.")
io = self.parent.process([argv0,'-c', script.strip()],
executable=python,
env=self.env,
**kwargs)
path = io.recvline()
address = int(io.recvline())
address -= len(python)
address += len(path)
return int(address) & context.mask
except:
self.exception("Could not look up environment variable %r" % variable)
def _close_msg(self):
# If we never completely started up, just use the parent implementation
if self.executable is None:
return super(ssh_process, self)._close_msg()
self.info('Stopped remote process %r on %s (pid %i)' \
% (os.path.basename(self.executable),
self.host,
self.pid))
class ssh_connecter(sock):
def __init__(self, parent, host, port, *a, **kw):
super(ssh_connecter, self).__init__(*a, **kw)
# keep the parent from being garbage collected in some cases
self.parent = parent
self.host = parent.host
self.rhost = host
self.rport = port
msg = 'Connecting to %s:%d via SSH to %s' % (self.rhost, self.rport, self.host)
with self.waitfor(msg) as h:
try:
self.sock = parent.transport.open_channel('direct-tcpip', (host, port), ('127.0.0.1', 0))
except Exception as e:
self.exception(e.message)
raise
try:
# Iterate all layers of proxying to get to base-level Socket object
curr = self.sock.get_transport().sock
while getattr(curr, "get_transport", None):
curr = curr.get_transport().sock
sockname = curr.getsockname()
self.lhost = sockname[0]
self.lport = sockname[1]
except Exception as e:
self.exception("Could not find base-level Socket object.")
raise e
h.success()
def spawn_process(self, *args, **kwargs):
self.error("Cannot use spawn_process on an SSH channel.""")
def _close_msg(self):
self.info("Closed remote connection to %s:%d via SSH connection to %s" % (self.rhost, self.rport, self.host))
class ssh_listener(sock):
def __init__(self, parent, bind_address, port, *a, **kw):
super(ssh_listener, self).__init__(*a, **kw)
# keep the parent from being garbage collected in some cases
self.parent = parent
self.host = parent.host
try:
self.port = parent.transport.request_port_forward(bind_address, port)
except Exception:
h.failure('Failed create a port forwarding')
raise
def accepter():
msg = 'Waiting on port %d via SSH to %s' % (self.port, self.host)
h = self.waitfor(msg)
try:
self.sock = parent.transport.accept()
parent.transport.cancel_port_forward(bind_address, self.port)
except Exception:
self.sock = None
h.failure()
self.exception('Failed to get a connection')
return
self.rhost, self.rport = self.sock.origin_addr
h.success('Got connection from %s:%d' % (self.rhost, self.rport))
self._accepter = context.Thread(target = accepter)
self._accepter.daemon = True
self._accepter.start()
def _close_msg(self):
self.info("Closed remote connection to %s:%d via SSH listener on port %d via %s" % (self.rhost, self.rport, self.port, self.host))
def spawn_process(self, *args, **kwargs):
self.error("Cannot use spawn_process on an SSH channel.""")
def wait_for_connection(self):
"""Blocks until a connection has been established."""
_ = self.sock
return self
def __getattr__(self, key):
if key == 'sock':
while self._accepter.is_alive():
self._accepter.join(timeout = 0.1)
return self.sock
else:
return getattr(super(ssh_listener, self), key)
class ssh(Timeout, Logger):
#: Remote host name (``str``)
host = None
#: Remote port (``int``)
port = None
#: Working directory (``str``)
cwd = None
#: Enable caching of SSH downloads (``bool``)
cache = True
#: Paramiko SSHClient which backs this object
client = None
#: Paramiko SFTPClient object which is used for file transfers.
#: Set to :const:`None` to disable ``sftp``.
sftp = None
#: PID of the remote ``sshd`` process servicing this connection.
pid = None
def __init__(self, user, host, port = 22, password = None, key = None,
keyfile = None, proxy_command = None, proxy_sock = None,
level = None, cache = True, ssh_agent = False, *a, **kw):
"""Creates a new ssh connection.
Arguments:
user(str): The username to log in with
host(str): The hostname to connect to
port(int): The port to connect to
password(str): Try to authenticate using this password
key(str): Try to authenticate using this private key. The string should be the actual private key.
keyfile(str): Try to authenticate using this private key. The string should be a filename.
proxy_command(str): Use this as a proxy command. It has approximately the same semantics as ProxyCommand from ssh(1).
proxy_sock(str): Use this socket instead of connecting to the host.
timeout: Timeout, in seconds
level: Log level
cache: Cache downloaded files (by hash/size/timestamp)
ssh_agent: If :const:`True`, enable usage of keys via ssh-agent
NOTE: The proxy_command and proxy_sock arguments is only available if a
fairly new version of paramiko is used.
Example proxying:
>>> s1 = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> r1 = s1.remote('localhost', 22)
>>> s2 = ssh(host='example.pwnme',
... user='travis',
... password='demopass',
... proxy_sock=r1.sock)
>>> r2 = s2.remote('localhost', 22) # and so on...
>>> for x in r2, s2, r1, s1: x.close()
"""
super(ssh, self).__init__(*a, **kw)
Logger.__init__(self)
if level is not None:
self.setLevel(level)
self.host = host
self.port = port
self.user = user
self.password = password
self.key = key
self.keyfile = keyfile
self._cachedir = os.path.join(tempfile.gettempdir(), 'pwntools-ssh-cache')
self.cwd = '.'
self.cache = cache
# Deferred attributes
self._platform_info = {}
self._aslr = None
self._aslr_ulimit = None
misc.mkdir_p(self._cachedir)
# This is a dirty hack to make my Yubikey shut up.
# If anybody has a problem with this, please open a bug and I'll
# figure out a better workaround.
if not ssh_agent:
os.environ.pop('SSH_AUTH_SOCK', None)
import paramiko
# Make a basic attempt to parse the ssh_config file
try:
config_file = os.path.expanduser('~/.ssh/config')
if os.path.exists(config_file):
ssh_config = paramiko.SSHConfig()
ssh_config.parse(open(config_file))
host_config = ssh_config.lookup(host)
if 'hostname' in host_config:
self.host = host = host_config['hostname']
if not keyfile and 'identityfile' in host_config:
keyfile = host_config['identityfile'][0]
if keyfile.lower() == 'none':
keyfile = None
except Exception as e:
self.debug("An error occurred while parsing ~/.ssh/config:\n%s" % e)
keyfiles = [os.path.expanduser(keyfile)] if keyfile else []
msg = 'Connecting to %s on port %d' % (host, port)
with self.waitfor(msg) as h:
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
known_hosts = os.path.expanduser('~/.ssh/known_hosts')
if os.path.exists(known_hosts):
self.client.load_host_keys(known_hosts)
has_proxy = (proxy_sock or proxy_command) and True
if has_proxy:
if 'ProxyCommand' not in dir(paramiko):
self.error('This version of paramiko does not support proxies.')
if proxy_sock and proxy_command:
self.error('Cannot have both a proxy command and a proxy sock')
if proxy_command:
proxy_sock = paramiko.ProxyCommand(proxy_command)
self.client.connect(host, port, user, password, key, keyfiles, self.timeout, compress = True, sock = proxy_sock)
else:
self.client.connect(host, port, user, password, key, keyfiles, self.timeout, compress = True)
self.transport = self.client.get_transport()
self.transport.use_compression(True)
h.success()
self._tried_sftp = False
with context.local(log_level='error'):
def getppid():
print(os.getppid())
try:
self.pid = int(self.process('false', preexec_fn=getppid).recvall())
except Exception:
self.pid = None
try:
self.info_once(self.checksec())
except Exception:
self.warn_once("Couldn't check security settings on %r" % self.host)
@property
def sftp(self):
if not self._tried_sftp:
try:
self._sftp = self.transport.open_sftp_client()
except Exception:
self._sftp = None
self._tried_sftp = True
return self._sftp
@sftp.setter
def sftp(self, value):
self._sftp = value
self._tried_sftp = True
def __enter__(self, *a):
return self
def __exit__(self, *a, **kw):
self.close()
def shell(self, shell = None, tty = True, timeout = Timeout.default):
"""shell(shell = None, tty = True, timeout = Timeout.default) -> ssh_channel
Open a new channel with a shell inside.
Arguments:
shell(str): Path to the shell program to run.
If :const:`None`, uses the default shell for the logged in user.
tty(bool): If :const:`True`, then a TTY is requested on the remote server.
Returns:
Return a :class:`pwnlib.tubes.ssh.ssh_channel` object.
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> sh = s.shell('/bin/sh')
>>> sh.sendline(b'echo Hello; exit')
>>> print(b'Hello' in sh.recvall())
True
"""
return self.run(shell, tty, timeout = timeout)
def process(self, argv=None, executable=None, tty=True, cwd=None, env=None, timeout=Timeout.default, run=True,
stdin=0, stdout=1, stderr=2, preexec_fn=None, preexec_args=(), raw=True, aslr=None, setuid=None,
shell=False):
r"""
Executes a process on the remote server, in the same fashion
as pwnlib.tubes.process.process.
To achieve this, a Python script is created to call ``os.execve``
with the appropriate arguments.
As an added bonus, the ``ssh_channel`` object returned has a
``pid`` property for the process pid.
Arguments:
argv(list):
List of arguments to pass into the process
executable(str):
Path to the executable to run.
If :const:`None`, ``argv[0]`` is used.
tty(bool):
Request a `tty` from the server. This usually fixes buffering problems
by causing `libc` to write data immediately rather than buffering it.
However, this disables interpretation of control codes (e.g. Ctrl+C)
and breaks `.shutdown`.
cwd(str):
Working directory. If :const:`None`, uses the working directory specified
on :attr:`cwd` or set via :meth:`set_working_directory`.
env(dict):
Environment variables to set in the child. If :const:`None`, inherits the
default environment.
timeout(int):
Timeout to set on the `tube` created to interact with the process.
run(bool):
Set to :const:`True` to run the program (default).
If :const:`False`, returns the path to an executable Python script on the
remote server which, when executed, will do it.
stdin(int, str):
If an integer, replace stdin with the numbered file descriptor.
If a string, a open a file with the specified path and replace
stdin with its file descriptor. May also be one of ``sys.stdin``,
``sys.stdout``, ``sys.stderr``. If :const:`None`, the file descriptor is closed.
stdout(int, str):
See ``stdin``.
stderr(int, str):
See ``stdin``.
preexec_fn(callable):
Function which is executed on the remote side before execve().
This **MUST** be a self-contained function -- it must perform
all of its own imports, and cannot refer to variables outside
its scope.
preexec_args(object):
Argument passed to ``preexec_fn``.
This **MUST** only consist of native Python objects.
raw(bool):
If :const:`True`, disable TTY control code interpretation.
aslr(bool):
See :class:`pwnlib.tubes.process.process` for more information.
setuid(bool):
See :class:`pwnlib.tubes.process.process` for more information.
shell(bool):
Pass the command-line arguments to the shell.
Returns:
A new SSH channel, or a path to a script if ``run=False``.
Notes:
Requires Python on the remote server.
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> sh = s.process('/bin/sh', env={'PS1':''})
>>> sh.sendline(b'echo Hello; exit')
>>> sh.recvall()
b'Hello\n'
>>> s.process(['/bin/echo', b'\xff']).recvall()
b'\xff\n'
>>> s.process(['readlink', '/proc/self/exe']).recvall()
b'/bin/readlink\n'
>>> s.process(['LOLOLOL', '/proc/self/exe'], executable='readlink').recvall()
b'/bin/readlink\n'
>>> s.process(['LOLOLOL\x00', '/proc/self/cmdline'], executable='cat').recvall()
b'LOLOLOL\x00/proc/self/cmdline\x00'
>>> sh = s.process(executable='/bin/sh')
>>> str(sh.pid).encode() in s.pidof('sh') # doctest: +SKIP
True
>>> s.process(['pwd'], cwd='/tmp').recvall()
b'/tmp\n'
>>> p = s.process(['python','-c','import os; print(os.read(2, 1024))'], stderr=0)
>>> p.send(b'hello')
>>> p.recv()
b'hello\n'
>>> s.process(['/bin/echo', 'hello']).recvall()
b'hello\n'
>>> s.process(['/bin/echo', 'hello'], stdout='/dev/null').recvall()
b''
>>> s.process(['/usr/bin/env'], env={}).recvall()
b''
>>> s.process('/usr/bin/env', env={'A':'B'}).recvall()
b'A=B\n'
>>> s.process('false', preexec_fn=1234)
Traceback (most recent call last):
...
PwnlibException: preexec_fn must be a function
>>> s.process('false', preexec_fn=lambda: 1234)
Traceback (most recent call last):
...
PwnlibException: preexec_fn cannot be a lambda
>>> def uses_globals():
... foo = bar
>>> print(s.process('false', preexec_fn=uses_globals).recvall().strip().decode()) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
NameError: global name 'bar' is not defined
>>> s.process('echo hello', shell=True).recvall()
b'hello\n'
"""
if not argv and not executable:
self.error("Must specify argv or executable")
argv = argv or []
aslr = aslr if aslr is not None else context.aslr
if isinstance(argv, (six.text_type, six.binary_type)):
argv = [argv]
if not isinstance(argv, (list, tuple)):
self.error('argv must be a list or tuple')
if not all(isinstance(arg, (six.text_type, six.binary_type)) for arg in argv):
self.error("argv must be strings or bytes: %r" % argv)
if shell:
if len(argv) != 1:
self.error('Cannot provide more than 1 argument if shell=True')
argv = ['/bin/sh', '-c'] + argv
# Create a duplicate so we can modify it
argv = list(argv or [])
# Python doesn't like when an arg in argv contains '\x00'
# -> execve() arg 2 must contain only strings
for i, oarg in enumerate(argv):
if isinstance(oarg, six.text_type):
arg = oarg.encode('utf-8')
else:
arg = oarg
if b'\x00' in arg[:-1]:
self.error('Inappropriate nulls in argv[%i]: %r' % (i, oarg))
argv[i] = arg.rstrip(b'\x00')
# Python also doesn't like when envp contains '\x00'
env2 = {}
if env and hasattr(env, 'items'):
for k, v in env.items():
if isinstance(k, six.text_type):
k = k.encode('utf-8')
if isinstance(v, six.text_type):
v = v.encode('utf-8')
if b'\x00' in k[:-1]:
self.error('Inappropriate nulls in environment key %r' % k)
if b'\x00' in v[:-1]:
self.error('Inappropriate nulls in environment value %r=%r' % (k, v))
env2[k.rstrip(b'\x00')] = v.rstrip(b'\x00')
env = env2 or env
executable = executable or argv[0]
cwd = cwd or self.cwd
# Validate, since failures on the remote side will suck.
if not isinstance(executable, (six.text_type, six.binary_type)):
self.error("executable / argv[0] must be a string: %r" % executable)
if env is not None and not isinstance(env, dict) and env != os.environ:
self.error("env must be a dict: %r" % env)
# Allow passing in sys.stdin/stdout/stderr objects
handles = {sys.stdin: 0, sys.stdout:1, sys.stderr:2}
stdin = handles.get(stdin, stdin)
stdout = handles.get(stdout, stdout)
stderr = handles.get(stderr, stderr)
# Allow the user to provide a self-contained function to run
def func(): pass
func = preexec_fn or func
func_args = preexec_args
if not isinstance(func, types.FunctionType):
self.error("preexec_fn must be a function")
func_name = func.__name__
if func_name == (lambda: 0).__name__:
self.error("preexec_fn cannot be a lambda")
func_src = inspect.getsource(func).strip()
setuid = True if setuid is None else bool(setuid)
script = r"""
#!/usr/bin/env python2
import os, sys, ctypes, resource, platform, stat
from collections import OrderedDict
exe = %(executable)r
argv = %(argv)r
env = %(env)r
os.chdir(%(cwd)r)
if env is not None:
os.environ.clear()
os.environ.update(env)
else:
env = os.environ
def is_exe(path):
return os.path.isfile(path) and os.access(path, os.X_OK)
PATH = os.environ.get('PATH','').split(os.pathsep)
if os.path.sep not in exe and not is_exe(exe):
for path in PATH:
test_path = os.path.join(path, exe)
if is_exe(test_path):
exe = test_path
break
if not is_exe(exe):
sys.stderr.write('3\n')
sys.stderr.write("{} is not executable or does not exist in $PATH: {}".format(exe,PATH))
sys.exit(-1)
if not %(setuid)r:
PR_SET_NO_NEW_PRIVS = 38
result = ctypes.CDLL('libc.so.6').prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)
if result != 0:
sys.stdout.write('3\n')
sys.stdout.write("Could not disable setuid: prctl(PR_SET_NO_NEW_PRIVS) failed")
sys.exit(-1)
try:
PR_SET_PTRACER = 0x59616d61
PR_SET_PTRACER_ANY = -1
ctypes.CDLL('libc.so.6').prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0)
except Exception:
pass
# Determine what UID the process will execute as
# This is used for locating apport core dumps
suid = os.getuid()
sgid = os.getgid()
st = os.stat(exe)
if %(setuid)r:
if (st.st_mode & stat.S_ISUID):
suid = st.st_uid
if (st.st_mode & stat.S_ISGID):
sgid = st.st_gid
if sys.argv[-1] == 'check':
sys.stdout.write("1\n")
sys.stdout.write(str(os.getpid()) + "\n")
sys.stdout.write(str(os.getuid()) + "\n")
sys.stdout.write(str(os.getgid()) + "\n")
sys.stdout.write(str(suid) + "\n")
sys.stdout.write(str(sgid) + "\n")
sys.stdout.write(os.path.realpath(exe) + '\x00')
sys.stdout.flush()
for fd, newfd in {0: %(stdin)r, 1: %(stdout)r, 2:%(stderr)r}.items():
if newfd is None:
close(fd)
elif isinstance(newfd, str):
os.close(fd)
os.open(newfd, os.O_RDONLY if fd == 0 else (os.O_RDWR|os.O_CREAT))
elif isinstance(newfd, int) and newfd != fd:
os.dup2(fd, newfd)
if not %(aslr)r:
if platform.system().lower() == 'linux' and %(setuid)r is not True:
ADDR_NO_RANDOMIZE = 0x0040000
ctypes.CDLL('libc.so.6').personality(ADDR_NO_RANDOMIZE)
resource.setrlimit(resource.RLIMIT_STACK, (-1, -1))
# Attempt to dump ALL core file regions
try:
with open('/proc/self/coredump_filter', 'w') as core_filter:
core_filter.write('0x3f\n')
except Exception:
pass
# Assume that the user would prefer to have core dumps.
try:
resource.setrlimit(resource.RLIMIT_CORE, (-1, -1))
except Exception:
pass
%(func_src)s
apply(%(func_name)s, %(func_args)r)
os.execve(exe, argv, env)
""" % locals()
script = script.strip()
self.debug("Created execve script:\n" + script)
if not run:
with context.local(log_level='error'):
tmpfile = self.mktemp('-t', 'pwnlib-execve-XXXXXXXXXX')
self.chmod('+x', tmpfile)
self.info("Uploading execve script to %r" % tmpfile)
self.upload_data(script, tmpfile)
return tmpfile
if self.isEnabledFor(logging.DEBUG):
execve_repr = "execve(%r, %s, %s)" % (executable,
argv,
'os.environ'
if (env in (None, os.environ))
else env)
# Avoid spamming the screen
if self.isEnabledFor(logging.DEBUG) and len(execve_repr) > 512:
execve_repr = execve_repr[:512] + '...'
else:
execve_repr = repr(executable)
msg = 'Starting remote process %s on %s' % (execve_repr, self.host)
with self.progress(msg) as h:
script = 'for py in python2.7 python2 python; do test -x "$(which $py 2>&1)" && exec $py -c %s check; done; echo 2' % sh_string(script)
with context.local(log_level='error'):
python = ssh_process(self, script, tty=True, raw=True, level=self.level, timeout=self.timeout)
try:
result = safeeval.const(python.recvline())
except Exception:
h.failure("Process creation failed")
self.warn_once('Could not find a Python2 interpreter on %s\n' % self.host \
+ "Use ssh.run() instead of ssh.process()")
return None
# If an error occurred, try to grab as much output
# as we can.
if result != 1:
error_message = python.recvrepeat(timeout=1)
if result == 0:
self.error("%r does not exist or is not executable" % executable)
elif result == 3:
self.error(error_message)
elif result == 2:
self.error("python is not installed on the remote system %r" % self.host)
elif result != 1:
h.failure("something bad happened:\n%s" % error_message)
python.pid = safeeval.const(python.recvline())
python.uid = safeeval.const(python.recvline())
python.gid = safeeval.const(python.recvline())
python.suid = safeeval.const(python.recvline())
python.sgid = safeeval.const(python.recvline())
python.argv = argv
python.executable = python.recvuntil(b'\x00')[:-1]
h.success('pid %i' % python.pid)
if aslr == False and setuid and (python.uid != python.suid or python.gid != python.sgid):
effect = "partial" if self.aslr_ulimit else "no"
message = "Specfied aslr=False on setuid binary %s\n" % python.executable
message += "This will have %s effect. Add setuid=False to disable ASLR for debugging.\n" % effect
if self.aslr_ulimit:
message += "Unlimited stack size should de-randomize shared libraries."
self.warn_once(message)
elif not aslr:
self.warn_once("ASLR is disabled for %r!" % python.executable)
return python
def which(self, program):
"""which(program) -> str
Minor modification to just directly invoking ``which`` on the remote
system which adds the current working directory to the end of ``$PATH``.
"""
# If name is a path, do not attempt to resolve it.
if os.path.sep in program:
return program
result = self.run('export PATH=$PATH:$PWD; which %s' % program).recvall().strip().decode()
if ('/%s' % program) not in result:
return None
return result
def system(self, process, tty = True, wd = None, env = None, timeout = None, raw = True):
r"""system(process, tty = True, wd = None, env = None, timeout = Timeout.default, raw = True) -> ssh_channel
Open a new channel with a specific process inside. If `tty` is True,
then a TTY is requested on the remote server.
If `raw` is True, terminal control codes are ignored and input is not
echoed back.
Return a :class:`pwnlib.tubes.ssh.ssh_channel` object.
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> py = s.run('python -i')
>>> _ = py.recvuntil(b'>>> ')
>>> py.sendline(b'print(2+2)')
>>> py.sendline(b'exit')
>>> print(repr(py.recvline()))
b'4\n'
"""
if wd is None:
wd = self.cwd
if timeout is None:
timeout = self.timeout
return ssh_channel(self, process, tty, wd, env, timeout = timeout, level = self.level, raw = raw)
#: Backward compatibility. Use :meth:`system`
run = system
def getenv(self, variable, **kwargs):
"""Retrieve the address of an environment variable on the remote
system.
Note:
The exact address will differ based on what other environment
variables are set, as well as argv[0]. In order to ensure that
the path is *exactly* the same, it is recommended to invoke the
process with ``argv=[]``.
"""
script = '''
from ctypes import *; libc = CDLL('libc.so.6'); print(libc.getenv(%r))
''' % variable
with context.local(log_level='error'):
python = self.which('python')
if not python:
self.error("Python is not installed on the remote system.")
io = self.process(['','-c', script.strip()], executable=python, **kwargs)
result = io.recvall()
try:
return int(result) & context.mask
except ValueError:
self.exception("Could not look up environment variable %r" % variable)
def run_to_end(self, process, tty = False, wd = None, env = None):
r"""run_to_end(process, tty = False, timeout = Timeout.default, env = None) -> str
Run a command on the remote server and return a tuple with
(data, exit_status). If `tty` is True, then the command is run inside
a TTY on the remote server.
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> print(s.run_to_end('echo Hello; exit 17'))
(b'Hello\n', 17)
"""
with context.local(log_level = 'ERROR'):
c = self.run(process, tty, wd = wd, timeout = Timeout.default)
data = c.recvall()
retcode = c.wait()
c.close()
return data, retcode
def connect_remote(self, host, port, timeout = Timeout.default):
r"""connect_remote(host, port, timeout = Timeout.default) -> ssh_connecter
Connects to a host through an SSH connection. This is equivalent to
using the ``-L`` flag on ``ssh``.
Returns a :class:`pwnlib.tubes.ssh.ssh_connecter` object.
Examples:
>>> from pwn import *
>>> l = listen()
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> a = s.connect_remote(s.host, l.lport)
>>> b = l.wait_for_connection()
>>> a.sendline(b'Hello')
>>> print(repr(b.recvline()))
b'Hello\n'
"""
return ssh_connecter(self, host, port, timeout, level=self.level)
remote = connect_remote
def listen_remote(self, port = 0, bind_address = '', timeout = Timeout.default):
r"""listen_remote(port = 0, bind_address = '', timeout = Timeout.default) -> ssh_connecter
Listens remotely through an SSH connection. This is equivalent to
using the ``-R`` flag on ``ssh``.
Returns a :class:`pwnlib.tubes.ssh.ssh_listener` object.
Examples:
>>> from pwn import *
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> l = s.listen_remote()
>>> a = remote(s.host, l.port)
>>> b = l.wait_for_connection()
>>> a.sendline(b'Hello')
>>> print(repr(b.recvline()))
b'Hello\n'
"""
return ssh_listener(self, bind_address, port, timeout, level=self.level)
listen = listen_remote
def __getitem__(self, attr):
"""Permits indexed access to run commands over SSH
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> print(repr(s['echo hello']))
b'hello'
"""
return self.__getattr__(attr)()
def __call__(self, attr):
"""Permits function-style access to run commands over SSH
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> print(repr(s('echo hello')))
b'hello'
"""
return self.__getattr__(attr)()
def __getattr__(self, attr):
"""Permits member access to run commands over SSH
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> s.echo('hello')
b'hello'
>>> s.whoami()
b'travis'
>>> s.echo(['huh','yay','args'])
b'huh yay args'
"""
bad_attrs = [
'trait_names', # ipython tab-complete
]
if attr in self.__dict__ \
or attr in bad_attrs \
or attr.startswith('_'):
raise AttributeError
def runner(*args):
if len(args) == 1 and isinstance(args[0], (list, tuple)):
command = [attr] + args[0]
else:
command = ' '.join((attr,) + args)
return self.run(command).recvall().strip()
return runner
def connected(self):
"""Returns True if we are connected.
Example:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> s.connected()
True
>>> s.close()
>>> s.connected()
False
"""
return bool(self.client and self.client.get_transport().is_active())
def close(self):
"""Close the connection."""
if self.client:
self.client.close()
self.client = None
self.info("Closed connection to %r" % self.host)
def _libs_remote(self, remote):
"""Return a dictionary of the libraries used by a remote file."""
escaped_remote = sh_string(remote)
cmd = ''.join([
'(',
'ulimit -s unlimited;',
'ldd %s > /dev/null &&' % escaped_remote,
'(',
'LD_TRACE_LOADED_OBJECTS=1 %s||' % escaped_remote,
'ldd %s' % escaped_remote,
'))',
' 2>/dev/null'
])
data, status = self.run_to_end(cmd)
if status != 0:
self.error('Unable to find libraries for %r' % remote)
return {}
return misc.parse_ldd_output(context._decode(data))
def _get_fingerprint(self, remote):
cmd = '(sha256 || sha256sum || openssl sha256) 2>/dev/null < '
cmd = cmd + sh_string(remote)
data, status = self.run_to_end(cmd)
if status != 0:
return None
# OpenSSL outputs in the format of...
# (stdin)= e3b0c4429...
data = data.replace(b'(stdin)= ',b'')
# sha256 and sha256sum outputs in the format of...
# e3b0c442... -
data = data.replace(b'-',b'').strip()
if not isinstance(data, str):
data = data.decode('ascii')
return data
def _get_cachefile(self, fingerprint):
return os.path.join(self._cachedir, fingerprint)
def _verify_local_fingerprint(self, fingerprint):
if not set(fingerprint).issubset(string.hexdigits) or \
len(fingerprint) != 64:
self.error('Invalid fingerprint %r' % fingerprint)
return False
local = self._get_cachefile(fingerprint)
if not os.path.isfile(local):
return False
if hashes.sha256filehex(local) == fingerprint:
return True
else:
os.unlink(local)
return False
def _download_raw(self, remote, local, h):
def update(has, total):
h.status("%s/%s" % (misc.size(has), misc.size(total)))
if self.sftp:
try:
self.sftp.get(remote, local, update)
return
except IOError:
pass
cmd = 'wc -c < ' + sh_string(remote)
total, exitcode = self.run_to_end(cmd)
if exitcode != 0:
h.failure("%r does not exist or is not accessible" % remote)
return
total = int(total)
with context.local(log_level = 'ERROR'):
cmd = 'cat < ' + sh_string(remote)
c = self.run(cmd)
data = b''
while True:
try:
data += c.recv()
except EOFError:
break
update(len(data), total)
result = c.wait()
if result != 0:
h.failure('Could not download file %r (%r)' % (remote, result))
return
with open(local, 'wb') as fd:
fd.write(data)
def _download_to_cache(self, remote, p):
with context.local(log_level='error'):
remote = self.readlink('-f',remote)
if not hasattr(remote, 'encode'):
remote = remote.decode('utf-8')
fingerprint = self._get_fingerprint(remote)
if fingerprint is None:
local = os.path.normpath(remote)
local = os.path.basename(local)
local += time.strftime('-%Y-%m-%d-%H:%M:%S')
local = os.path.join(self._cachedir, local)
self._download_raw(remote, local, p)
return local
local = self._get_cachefile(fingerprint)
if self.cache and self._verify_local_fingerprint(fingerprint):
p.success('Found %r in ssh cache' % remote)
else:
self._download_raw(remote, local, p)
if not self._verify_local_fingerprint(fingerprint):
p.failure('Could not download file %r' % remote)
return local
def download_data(self, remote):
"""Downloads a file from the remote server and returns it as a string.
Arguments:
remote(str): The remote filename to download.
Examples:
>>> with open('/tmp/bar','w+') as f:
... _ = f.write('Hello, world')
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass',
... cache=False)
>>> s.download_data('/tmp/bar')
b'Hello, world'
>>> s._sftp = None
>>> s._tried_sftp = True
>>> s.download_data('/tmp/bar')
b'Hello, world'
"""
with self.progress('Downloading %r' % remote) as p:
with open(self._download_to_cache(remote, p), 'rb') as fd:
return fd.read()
def download_file(self, remote, local = None):
"""Downloads a file from the remote server.
The file is cached in /tmp/pwntools-ssh-cache using a hash of the file, so
calling the function twice has little overhead.
Arguments:
remote(str): The remote filename to download
local(str): The local filename to save it to. Default is to infer it from the remote filename.
"""
if not local:
local = os.path.basename(os.path.normpath(remote))
if os.path.basename(remote) == remote:
remote = os.path.join(self.cwd, remote)
with self.progress('Downloading %r to %r' % (remote, local)) as p:
local_tmp = self._download_to_cache(remote, p)
# Check to see if an identical copy of the file already exists
if not os.path.exists(local) or hashes.sha256filehex(local_tmp) != hashes.sha256filehex(local):
shutil.copy2(local_tmp, local)
def download_dir(self, remote=None, local=None):
"""Recursively downloads a directory from the remote server
Arguments:
local: Local directory
remote: Remote directory
"""
remote = remote or self.cwd
if self.sftp:
remote = str(self.sftp.normalize(remote))
else:
with context.local(log_level='error'):
remote = self.system('readlink -f ' + sh_string(remote))
basename = os.path.basename(remote)
local = local or '.'
local = os.path.expanduser(local)
self.info("Downloading %r to %r" % (basename,local))
with context.local(log_level='error'):
remote_tar = self.mktemp()
cmd = 'tar -C %s -czf %s %s' % \
(sh_string(dirname),
sh_string(remote_tar),
sh_string(basename))
tar = self.system(cmd)
if 0 != tar.wait():
self.error("Could not create remote tar")
local_tar = tempfile.NamedTemporaryFile(suffix='.tar.gz')
self.download_file(remote_tar, local_tar.name)
tar = tarfile.open(local_tar.name)
tar.extractall(local)
def upload_data(self, data, remote):
"""Uploads some data into a file on the remote server.
Arguments:
data(str): The data to upload.
remote(str): The filename to upload it to.
Example:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> s.upload_data(b'Hello, world', '/tmp/upload_foo')
>>> print(open('/tmp/upload_foo').read())
Hello, world
>>> s._sftp = False
>>> s._tried_sftp = True
>>> s.upload_data(b'Hello, world', '/tmp/upload_bar')
>>> print(open('/tmp/upload_bar').read())
Hello, world
"""
data = context._encode(data)
# If a relative path was provided, prepend the cwd
if os.path.normpath(remote) == os.path.basename(remote):
remote = os.path.join(self.cwd, remote)
if self.sftp:
with tempfile.NamedTemporaryFile() as f:
f.write(data)
f.flush()
self.sftp.put(f.name, remote)
return
with context.local(log_level = 'ERROR'):
cmd = 'cat > ' + sh_string(remote)
s = self.run(cmd, tty=False)
s.send(data)
s.shutdown('send')
data = s.recvall()
result = s.wait()
if result != 0:
self.error("Could not upload file %r (%r)\n%s" % (remote, result, data))
def upload_file(self, filename, remote = None):
"""Uploads a file to the remote server. Returns the remote filename.
Arguments:
filename(str): The local filename to download
remote(str): The remote filename to save it to. Default is to infer it from the local filename."""
if remote == None:
remote = os.path.normpath(filename)
remote = os.path.basename(remote)
remote = os.path.join(self.cwd, remote)
with open(filename, 'rb') as fd:
data = fd.read()
self.info("Uploading %r to %r" % (filename,remote))
self.upload_data(data, remote)
return remote
def upload_dir(self, local, remote=None):
"""Recursively uploads a directory onto the remote server
Arguments:
local: Local directory
remote: Remote directory
"""
remote = remote or self.cwd
local = os.path.expanduser(local)
dirname = os.path.dirname(local)
basename = os.path.basename(local)
if not os.path.isdir(local):
self.error("%r is not a directory" % local)
msg = "Uploading %r to %r" % (basename,remote)
with self.waitfor(msg):
# Generate a tarfile with everything inside of it
local_tar = tempfile.mktemp()
with tarfile.open(local_tar, 'w:gz') as tar:
tar.add(local, basename)
# Upload and extract it
with context.local(log_level='error'):
remote_tar = self.mktemp('--suffix=.tar.gz')
self.upload_file(local_tar, remote_tar)
untar = self.run('cd %s && tar -xzf %s' % (remote, remote_tar))
message = untar.recvrepeat(2)
if untar.wait() != 0:
self.error("Could not untar %r on the remote end\n%s" % (remote_tar, message))
def upload(self, file_or_directory, remote=None):
"""upload(file_or_directory, remote=None)
Upload a file or directory to the remote host.
Arguments:
file_or_directory(str): Path to the file or directory to download.
remote(str): Local path to store the data.
By default, uses the working directory.
"""
if isinstance(file_or_directory, str):
file_or_directory = os.path.expanduser(file_or_directory)
file_or_directory = os.path.expandvars(file_or_directory)
if os.path.isfile(file_or_directory):
return self.upload_file(file_or_directory, remote)
if os.path.isdir(file_or_directory):
return self.upload_dir(file_or_directory, remote)
self.error('%r does not exist' % file_or_directory)
def download(self, file_or_directory, local=None):
"""download(file_or_directory, local=None)
Download a file or directory from the remote host.
Arguments:
file_or_directory(str): Path to the file or directory to download.
local(str): Local path to store the data.
By default, uses the current directory.
"""
if not self.sftp:
self.error("Cannot determine remote file type without SFTP")
with self.system('test -d ' + sh_string(file_or_directory)) as io:
is_dir = io.wait()
if 0 == is_dir:
self.download_dir(file_or_directory, local)
else:
self.download_file(file_or_directory, local)
put = upload
get = download
def unlink(self, file):
"""unlink(file)
Delete the file on the remote host
Arguments:
file(str): Path to the file
"""
if not self.sftp:
self.error("unlink() is only supported if SFTP is supported")
return self.sftp.unlink(file)
def libs(self, remote, directory = None):
"""Downloads the libraries referred to by a file.
This is done by running ldd on the remote server, parsing the output
and downloading the relevant files.
The directory argument specified where to download the files. This defaults
to './$HOSTNAME' where $HOSTNAME is the hostname of the remote server."""
libs = self._libs_remote(remote)
remote = context._decode(self.readlink('-f',remote).strip())
libs[remote] = 0
if directory == None:
directory = self.host
directory = os.path.realpath(directory)
res = {}
seen = set()
for lib, addr in libs.items():
local = os.path.realpath(os.path.join(directory, '.' + os.path.sep + lib))
if not local.startswith(directory):
self.warning('This seems fishy: %r' % lib)
continue
misc.mkdir_p(os.path.dirname(local))
if lib not in seen:
self.download_file(lib, local)
seen.add(lib)
res[local] = addr
return res
def interactive(self, shell=None):
"""Create an interactive session.
This is a simple wrapper for creating a new
:class:`pwnlib.tubes.ssh.ssh_channel` object and calling
:meth:`pwnlib.tubes.ssh.ssh_channel.interactive` on it."""
s = self.shell(shell)
if self.cwd != '.':
cmd = 'cd ' + sh_string(self.cwd)
s.sendline(cmd)
s.interactive()
s.close()
def set_working_directory(self, wd = None, symlink = False):
"""Sets the working directory in which future commands will
be run (via ssh.run) and to which files will be uploaded/downloaded
from if no path is provided
Note:
This uses ``mktemp -d`` under the covers, sets permissions
on the directory to ``0700``. This means that setuid binaries
will **not** be able to access files created in this directory.
In order to work around this, we also ``chmod +x`` the directory.
Arguments:
wd(string): Working directory. Default is to auto-generate a directory
based on the result of running 'mktemp -d' on the remote machine.
symlink(bool,str): Create symlinks in the new directory.
The default value, ``False``, implies that no symlinks should be
created.
A string value is treated as a path that should be symlinked.
It is passed directly to the shell on the remote end for expansion,
so wildcards work.
Any other value is treated as a boolean, where ``True`` indicates
that all files in the "old" working directory should be symlinked.
Examples:
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> cwd = s.set_working_directory()
>>> s.ls()
b''
>>> s.pwd() == cwd
True
>>> s = ssh(host='example.pwnme',
... user='travis',
... password='demopass')
>>> homedir = s.pwd()
>>> _=s.touch('foo')
>>> _=s.set_working_directory()
>>> assert s.ls() == b''
>>> _=s.set_working_directory(homedir)
>>> assert b'foo' in s.ls().split()
>>> _=s.set_working_directory(symlink=True)
>>> assert b'foo' in s.ls().split()
>>> assert homedir != s.pwd()
>>> symlink=os.path.join(homedir,b'*')
>>> _=s.set_working_directory(symlink=symlink)
>>> assert b'foo' in s.ls().split()
>>> assert homedir != s.pwd()
"""
status = 0
if symlink and not isinstance(symlink, (six.binary_type, six.text_type)):
symlink = os.path.join(self.pwd(), b'*')
if not hasattr(symlink, 'encode') and hasattr(symlink, 'decode'):
symlink = symlink.decode('utf-8')
if not wd:
wd, status = self.run_to_end('x=$(mktemp -d) && cd $x && chmod +x . && echo $PWD', wd='.')
wd = wd.strip()
if status:
self.error("Could not generate a temporary directory (%i)\n%s" % (status, wd))
else:
cmd = b'ls ' + sh_string(wd)
_, status = self.run_to_end(cmd, wd = '.')
if status:
self.error("%r does not appear to exist" % wd)
self.cwd = wd
if not isinstance(wd, str):
self.cwd = wd.decode('utf-8')
self.info("Working directory: %r" % self.cwd)
if symlink:
self.ln('-s', symlink, '.')
return wd
def write(self, path, data):
"""Wrapper around upload_data to match :func:`pwnlib.util.misc.write`"""
return self.upload_data(data, path)
def read(self, path):
"""Wrapper around download_data to match :func:`pwnlib.util.misc.read`"""
return self.download_data(path)
def _init_remote_platform_info(self):
r"""Fills _platform_info, e.g.:
::
{'distro': 'Ubuntu\n',
'distro_ver': '14.04\n',
'machine': 'x86_64',
'node': 'pwnable.kr',
'processor': 'x86_64',
'release': '3.11.0-12-generic',
'system': 'linux',
'version': '#19-ubuntu smp wed oct 9 16:20:46 utc 2013'}
"""
if self._platform_info:
return
def preexec():
import platform
print('\n'.join(platform.uname()))
with context.quiet:
with self.process('true', preexec_fn=preexec) as io:
self._platform_info = {
'system': io.recvline().lower().strip().decode(),
'node': io.recvline().lower().strip().decode(),
'release': io.recvline().lower().strip().decode(),
'version': io.recvline().lower().strip().decode(),
'machine': io.recvline().lower().strip().decode(),
'processor': io.recvline().lower().strip().decode(),
'distro': 'Unknown',
'distro_ver': ''
}
try:
if not self.which('lsb_release'):
return
with self.process(['lsb_release', '-irs']) as io:
self._platform_info.update({
'distro': io.recvline().strip().decode(),
'distro_ver': io.recvline().strip().decode()
})
except Exception:
pass
@property
def os(self):
""":class:`str`: Operating System of the remote machine."""
try:
self._init_remote_platform_info()
with context.local(os=self._platform_info['system']):
return context.os
except Exception:
return "Unknown"
@property
def arch(self):
""":class:`str`: CPU Architecture of the remote machine."""
try:
self._init_remote_platform_info()
with context.local(arch=self._platform_info['machine']):
return context.arch
except Exception:
return "Unknown"
@property
def bits(self):
""":class:`str`: Pointer size of the remote machine."""
try:
with context.local():
context.clear()
context.arch = self.arch
return context.bits
except Exception:
return context.bits
@property
def version(self):
""":class:`tuple`: Kernel version of the remote machine."""
try:
self._init_remote_platform_info()
vers = self._platform_info['release']
# 3.11.0-12-generic
expr = r'([0-9]+\.?)+'
vers = re.search(expr, vers).group()
return tuple(map(int, vers.split('.')))
except Exception:
return (0,0,0)
@property
def distro(self):
""":class:`tuple`: Linux distribution name and release."""
try:
self._init_remote_platform_info()
return (self._platform_info['distro'], self._platform_info['distro_ver'])
except Exception:
return ("Unknown", "Unknown")
@property
def aslr(self):
""":class:`bool`: Whether ASLR is enabled on the system.
Example:
>>> s = ssh("travis", "example.pwnme")
>>> s.aslr
True
"""
if self._aslr is None:
if self.os != 'linux':
self.warn_once("Only Linux is supported for ASLR checks.")
self._aslr = False
else:
with context.quiet:
rvs = self.read('/proc/sys/kernel/randomize_va_space')
self._aslr = not rvs.startswith(b'0')
return self._aslr
@property
def aslr_ulimit(self):
""":class:`bool`: Whether the entropy of 32-bit processes can be reduced with ulimit."""
import pwnlib.elf.elf
import pwnlib.shellcraft
if self._aslr_ulimit is not None:
return self._aslr_ulimit
# This test must run a 32-bit binary, fix the architecture
arch = {
'amd64': 'i386',
'aarch64': 'arm'
}.get(self.arch, self.arch)
with context.local(arch=arch, bits=32, os=self.os, aslr=True):
with context.quiet:
try:
sc = pwnlib.shellcraft.cat('/proc/self/maps') \
+ pwnlib.shellcraft.exit(0)
elf = pwnlib.elf.elf.ELF.from_assembly(sc, shared=True)
except Exception:
self.warn_once("Can't determine ulimit ASLR status")
self._aslr_ulimit = False
return self._aslr_ulimit
def preexec():
import resource
try:
resource.setrlimit(resource.RLIMIT_STACK, (-1, -1))
except Exception:
pass
# Move to a new temporary directory
cwd = self.cwd
tmp = self.set_working_directory()
try:
self.upload(elf.path, './aslr-test')
except IOError:
self.warn_once("Couldn't check ASLR ulimit trick")
self._aslr_ulimit = False
return False
self.process(['chmod', '+x', './aslr-test']).wait()
maps = self.process(['./aslr-test'], preexec_fn=preexec).recvall()
# Move back to the old directory
self.cwd = cwd
# Clean up the files
self.process(['rm', '-rf', tmp]).wait()
# Check for 555555000 (1/3 of the address space for PAE)
# and for 40000000 (1/3 of the address space with 3BG barrier)
self._aslr_ulimit = bool(b'55555000' in maps or b'40000000' in maps)
return self._aslr_ulimit
def _checksec_cache(self, value=None):
path = self._get_cachefile('%s-%s' % (self.host, self.port))
if value is not None:
with open(path, 'w+') as f:
f.write(value)
elif os.path.exists(path):
with open(path, 'r+') as f:
return f.read()
def checksec(self, banner=True):
"""checksec()
Prints a helpful message about the remote system.
Arguments:
banner(bool): Whether to print the path to the ELF binary.
"""
cached = self._checksec_cache()
if cached:
return cached
red = text.red
green = text.green
yellow = text.yellow
res = [
"%s@%s:" % (self.user, self.host),
"Distro".ljust(10) + ' '.join(self.distro),
"OS:".ljust(10) + self.os,
"Arch:".ljust(10) + self.arch,
"Version:".ljust(10) + '.'.join(map(str, self.version)),
"ASLR:".ljust(10) + {
True: green("Enabled"),
False: red("Disabled")
}[self.aslr]
]
if self.aslr_ulimit:
res += [ "Note:".ljust(10) + red("Susceptible to ASLR ulimit trick (CVE-2016-3672)")]
cached = '\n'.join(res)
self._checksec_cache(cached)
return cached
| []
| []
| [
"PATH"
]
| [] | ["PATH"] | python | 1 | 0 | |
core/services/keystore/keys/vrfkey/crypto_test.go | package vrfkey
import (
"math/big"
"testing"
bm "github.com/GoPlugin/Plugin/core/utils/big_math"
"github.com/stretchr/testify/assert"
)
func TestVRF_IsSquare(t *testing.T) {
assert.True(t, IsSquare(bm.Four))
minusOneModP := bm.I().Sub(FieldSize, bm.One)
assert.False(t, IsSquare(minusOneModP))
}
func TestVRF_SquareRoot(t *testing.T) {
assert.Equal(t, bm.Two, SquareRoot(bm.Four))
}
func TestVRF_YSquared(t *testing.T) {
assert.Equal(t, bm.Add(bm.Mul(bm.Two, bm.Mul(bm.Two, bm.Two)), bm.Seven), YSquared(bm.Two)) // 2³+7
}
func TestVRF_IsCurveXOrdinate(t *testing.T) {
assert.True(t, IsCurveXOrdinate(big.NewInt(1)))
assert.False(t, IsCurveXOrdinate(big.NewInt(5)))
}
| []
| []
| []
| [] | [] | go | null | null | null |
manage.py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
SMARTCHART = '''
_____ ___ ___ ___ _____ _____ _____ _ _ ___ _____ _____
/ ___/ / |/ | / | | _ \ |_ _| / ___| | | | | / | | _ \ |_ _|
| |___ / /| /| | / /| | | |_| | | | | | | |_| | / /| | | |_| | | |
\___ \ / / |__/ | | / / | | | _ / | | | | | _ | / / | | | _ / | |
___| | / / | | / / | | | | \ \ | | | |___ | | | | / / | | | | \ \ | |
/_____/ /_/ |_| /_/ |_| |_| \_\ |_| \_____| |_| |_| /_/ |_| |_| \_\ |_|
www.smartchart.cn version: 5.2
'''
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'smartcharts.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
print(SMARTCHART)
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
conda/cli/activate.py | from __future__ import print_function, division, absolute_import
import os
import sys
from os.path import isdir, join, abspath
import errno
from conda.cli.common import find_prefix_name
import conda.config
import conda.install
def help():
# sys.argv[1] will be ..checkenv in activate if an environment is already
# activated
if sys.argv[1] in ('..activate', '..checkenv'):
sys.exit("""Usage: source activate ENV
adds the 'bin' directory of the environment ENV to the front of PATH.
ENV may either refer to just the name of the environment, or the full
prefix path.""")
else: # ..deactivate
sys.exit("""Usage: source deactivate
removes the 'bin' directory of the environment activated with 'source
activate' from PATH. """)
def prefix_from_arg(arg):
if os.sep in arg:
return abspath(arg)
prefix = find_prefix_name(arg)
if prefix is None:
sys.exit('Error: could not find environment: %s' % arg)
return prefix
def binpath_from_arg(arg):
path = join(prefix_from_arg(arg), 'bin')
if not isdir(path):
sys.exit("Error: no such directory: %s" % path)
return path
def main():
if '-h' in sys.argv or '--help' in sys.argv:
help()
if sys.argv[1] == '..activate':
if len(sys.argv) == 2:
sys.exit("Error: no environment provided.")
elif len(sys.argv) == 3:
binpath = binpath_from_arg(sys.argv[2])
else:
sys.exit("Error: did not expect more than one argument")
paths = [binpath]
sys.stderr.write("prepending %s to PATH\n" % binpath)
elif sys.argv[1] == '..deactivate':
if len(sys.argv) != 2:
sys.exit("Error: too many arguments.")
try:
binpath = binpath_from_arg(os.getenv('CONDA_DEFAULT_ENV', 'root'))
except SystemExit:
print(os.environ['PATH'])
raise
paths = []
sys.stderr.write("discarding %s from PATH\n" % binpath)
elif sys.argv[1] == '..activateroot':
if len(sys.argv) != 2:
sys.exit("Error: too many arguments.")
if 'CONDA_DEFAULT_ENV' not in os.environ:
sys.exit("Error: No environment to deactivate")
try:
binpath = binpath_from_arg(os.getenv('CONDA_DEFAULT_ENV'))
rootpath = binpath_from_arg(conda.config.root_env_name)
except SystemExit:
print(os.environ['PATH'])
raise
# deactivate is the same as activate root (except without setting
# CONDA_DEFAULT_ENV or PS1). XXX: The user might want to put the root
# env back somewhere in the middle of the PATH, not at the beginning.
if rootpath not in os.getenv('PATH').split(os.pathsep):
paths = [rootpath]
else:
paths = []
sys.stderr.write("discarding %s from PATH\n" % binpath)
elif sys.argv[1] == '..checkenv':
if len(sys.argv) < 3:
sys.exit("Error: no environment provided.")
if len(sys.argv) > 3:
sys.exit("Error: did not expect more than one argument.")
binpath = binpath_from_arg(sys.argv[2])
# Make sure an env always has the conda symlink
try:
conda.install.symlink_conda(join(binpath, '..'), conda.config.root_dir)
except (IOError, OSError) as e:
if e.errno == errno.EPERM or e.errno == errno.EACCES:
sys.exit("Cannot activate environment {}, do not have write access to write conda symlink".format(sys.argv[2]))
raise
sys.exit(0)
else:
# This means there is a bug in main.py
raise ValueError("unexpected command")
for path in os.getenv('PATH').split(os.pathsep):
if path != binpath:
paths.append(path)
print(os.pathsep.join(paths))
if __name__ == '__main__':
main()
| []
| []
| [
"CONDA_DEFAULT_ENV",
"PATH"
]
| [] | ["CONDA_DEFAULT_ENV", "PATH"] | python | 2 | 0 | |
opentelemetry-sdk/src/opentelemetry/sdk/trace/export/in_memory_span_exporter.py | # Copyright 2019, OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import threading
import typing
from .. import Span
from . import SpanExporter, SpanExportResult
class InMemorySpanExporter(SpanExporter):
"""Implementation of :class:`.SpanExporter` that stores spans in memory.
This class can be used for testing purposes. It stores the exported spans
in a list in memory that can be retrieved using the
:func:`.get_finished_spans` method.
"""
def __init__(self):
self._finished_spans = []
self._stopped = False
self._lock = threading.Lock()
def clear(self):
"""Clear list of collected spans."""
with self._lock:
self._finished_spans.clear()
def get_finished_spans(self):
"""Get list of collected spans."""
with self._lock:
return tuple(self._finished_spans)
def export(self, spans: typing.Sequence[Span]) -> SpanExportResult:
"""Stores a list of spans in memory."""
if self._stopped:
return SpanExportResult.FAILED_NOT_RETRYABLE
with self._lock:
self._finished_spans.extend(spans)
return SpanExportResult.SUCCESS
def shutdown(self):
"""Shut downs the exporter.
Calls to export after the exporter has been shut down will fail.
"""
self._stopped = True
| []
| []
| []
| [] | [] | python | null | null | null |
test.py | from bsm import Manager, Episode, EpisodeGroup
from dotenv import load_dotenv
import os
load_dotenv()
ID = os.environ.get("ID")
TOKEN = os.environ.get("TOKEN")
manager = Manager(ID, TOKEN)
print(manager.test_api())
ep = Episode(**{'title': "test upload"})
res = manager.post_episode(ep, 'testfile.mp3', None)
print(res)
| []
| []
| [
"TOKEN",
"ID"
]
| [] | ["TOKEN", "ID"] | python | 2 | 0 | |
cmd/server/shared/zoekt.go | package shared
import (
"fmt"
"os"
"path/filepath"
)
func maybeZoektProcFile() []string {
// Zoekt is alreay configured
if os.Getenv("ZOEKT_HOST") != "" {
return nil
}
if os.Getenv("INDEXED_SEARCH_SERVERS") != "" {
return nil
}
defaultHost := "127.0.0.1:3070"
SetDefaultEnv("INDEXED_SEARCH_SERVERS", defaultHost)
frontendInternalHost := os.Getenv("SRC_FRONTEND_INTERNAL")
indexDir := filepath.Join(DataDir, "zoekt/index")
debugFlag := ""
if verbose {
debugFlag = "-debug"
}
return []string{
fmt.Sprintf("zoekt-indexserver: env GOGC=50 HOSTNAME=%s zoekt-sourcegraph-indexserver -sourcegraph_url http://%s -index %s -interval 1m -listen 127.0.0.1:6072 -cpu_fraction 0.25 %s", defaultHost, frontendInternalHost, indexDir, debugFlag),
fmt.Sprintf("zoekt-webserver: env GOGC=50 zoekt-webserver -rpc -pprof -listen %s -index %s", defaultHost, indexDir),
}
}
| [
"\"ZOEKT_HOST\"",
"\"INDEXED_SEARCH_SERVERS\"",
"\"SRC_FRONTEND_INTERNAL\""
]
| []
| [
"ZOEKT_HOST",
"INDEXED_SEARCH_SERVERS",
"SRC_FRONTEND_INTERNAL"
]
| [] | ["ZOEKT_HOST", "INDEXED_SEARCH_SERVERS", "SRC_FRONTEND_INTERNAL"] | go | 3 | 0 | |
cartoview/wsgi.py | """
WSGI config for cartoview project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
from django.core.wsgi import get_wsgi_application
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cartoview.settings")
os.environ["DJANGO_SETTINGS_MODULE"] = "cartoview.settings"
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
| []
| []
| [
"DJANGO_SETTINGS_MODULE"
]
| [] | ["DJANGO_SETTINGS_MODULE"] | python | 1 | 0 | |
sdk/go/common/workspace/plugins.go | // Copyright 2016-2018, Pulumi Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package workspace
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"time"
"github.com/blang/semver"
"github.com/cheggaaa/pb"
"github.com/djherbis/times"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v2/go/common/diag/colors"
"github.com/pulumi/pulumi/sdk/v2/go/common/util/archive"
"github.com/pulumi/pulumi/sdk/v2/go/common/util/contract"
"github.com/pulumi/pulumi/sdk/v2/go/common/util/fsutil"
"github.com/pulumi/pulumi/sdk/v2/go/common/util/httputil"
"github.com/pulumi/pulumi/sdk/v2/go/common/util/logging"
"github.com/pulumi/pulumi/sdk/v2/go/common/version"
"github.com/pulumi/pulumi/sdk/v2/nodejs/npm"
"github.com/pulumi/pulumi/sdk/v2/python"
)
const (
windowsGOOS = "windows"
)
var (
enableLegacyPluginBehavior = os.Getenv("PULUMI_ENABLE_LEGACY_PLUGIN_SEARCH") != ""
)
// MissingError is returned by functions that attempt to load plugins if a plugin can't be located.
type MissingError struct {
// Info contains information about the plugin that was not found.
Info PluginInfo
}
// NewMissingError allocates a new error indicating the given plugin info was not found.
func NewMissingError(info PluginInfo) error {
return &MissingError{
Info: info,
}
}
func (err *MissingError) Error() string {
if err.Info.Version != nil {
return fmt.Sprintf("no %[1]s plugin '%[2]s-v%[3]s' found in the workspace or on your $PATH, "+
"install the plugin using `pulumi plugin install %[1]s %[2]s v%[3]s`",
err.Info.Kind, err.Info.Name, err.Info.Version)
}
return fmt.Sprintf("no %s plugin '%s' found in the workspace or on your $PATH",
err.Info.Kind, err.Info.String())
}
// PluginInfo provides basic information about a plugin. Each plugin gets installed into a system-wide
// location, by default `~/.pulumi/plugins/<kind>-<name>-<version>/`. A plugin may contain multiple files,
// however the primary loadable executable must be named `pulumi-<kind>-<name>`.
type PluginInfo struct {
Name string // the simple name of the plugin.
Path string // the path that a plugin was loaded from.
Kind PluginKind // the kind of the plugin (language, resource, etc).
Version *semver.Version // the plugin's semantic version, if present.
Size int64 // the size of the plugin, in bytes.
InstallTime time.Time // the time the plugin was installed.
LastUsedTime time.Time // the last time the plugin was used.
ServerURL string // an optional server to use when downloading this plugin.
PluginDir string // if set, will be used as the root plugin dir instead of ~/.pulumi/plugins.
}
// Dir gets the expected plugin directory for this plugin.
func (info PluginInfo) Dir() string {
dir := fmt.Sprintf("%s-%s", info.Kind, info.Name)
if info.Version != nil {
dir = fmt.Sprintf("%s-v%s", dir, info.Version.String())
}
return dir
}
// File gets the expected filename for this plugin.
func (info PluginInfo) File() string {
return info.FilePrefix() + info.FileSuffix()
}
// FilePrefix gets the expected default file prefix for the plugin.
func (info PluginInfo) FilePrefix() string {
return fmt.Sprintf("pulumi-%s-%s", info.Kind, info.Name)
}
// FileSuffix returns the suffix for the plugin (if any).
func (info PluginInfo) FileSuffix() string {
if runtime.GOOS == windowsGOOS {
return ".exe"
}
return ""
}
// DirPath returns the directory where this plugin should be installed.
func (info PluginInfo) DirPath() (string, error) {
var err error
dir := info.PluginDir
if dir == "" {
dir, err = GetPluginDir()
if err != nil {
return "", err
}
}
return filepath.Join(dir, info.Dir()), nil
}
// LockFilePath returns the full path to the plugin's lock file used during installation
// to prevent concurrent installs.
func (info PluginInfo) LockFilePath() (string, error) {
dir, err := info.DirPath()
if err != nil {
return "", err
}
return fmt.Sprintf("%s.lock", dir), nil
}
// PartialFilePath returns the full path to the plugin's partial file used during installation
// to indicate installation of the plugin hasn't completed yet.
func (info PluginInfo) PartialFilePath() (string, error) {
dir, err := info.DirPath()
if err != nil {
return "", err
}
return fmt.Sprintf("%s.partial", dir), nil
}
// FilePath returns the full path where this plugin's primary executable should be installed.
func (info PluginInfo) FilePath() (string, error) {
dir, err := info.DirPath()
if err != nil {
return "", err
}
return filepath.Join(dir, info.File()), nil
}
// Delete removes the plugin from the cache. It also deletes any supporting files in the cache, which includes
// any files that contain the same prefix as the plugin itself.
func (info PluginInfo) Delete() error {
dir, err := info.DirPath()
if err != nil {
return err
}
if err := os.RemoveAll(dir); err != nil {
return err
}
// Attempt to delete any leftover .partial or .lock files.
// Don't fail the operation if we can't delete these.
contract.IgnoreError(os.Remove(fmt.Sprintf("%s.partial", dir)))
contract.IgnoreError(os.Remove(fmt.Sprintf("%s.lock", dir)))
return nil
}
// SetFileMetadata adds extra metadata from the given file, representing this plugin's directory.
func (info *PluginInfo) SetFileMetadata(path string) error {
// Get the file info.
file, err := os.Stat(path)
if err != nil {
return err
}
// Next, get the size from the directory (or, if there is none, just the file).
size, err := getPluginSize(path)
if err != nil {
return errors.Wrapf(err, "getting plugin dir %s size", path)
}
info.Size = size
// Next get the access times from the plugin binary itself.
tinfo := times.Get(file)
if tinfo.HasBirthTime() {
info.InstallTime = tinfo.BirthTime()
}
info.LastUsedTime = tinfo.AccessTime()
return nil
}
// Download fetches an io.ReadCloser for this plugin and also returns the size of the response (if known).
func (info PluginInfo) Download() (io.ReadCloser, int64, error) {
// Figure out the OS/ARCH pair for the download URL.
var os string
switch runtime.GOOS {
case "darwin", "linux", "windows":
os = runtime.GOOS
default:
return nil, -1, errors.Errorf("unsupported plugin OS: %s", runtime.GOOS)
}
var arch string
switch runtime.GOARCH {
case "amd64":
arch = runtime.GOARCH
default:
return nil, -1, errors.Errorf("unsupported plugin architecture: %s", runtime.GOARCH)
}
// If the plugin has a server, associated with it, download from there. Otherwise use the "default" location, which
// is hosted by Pulumi.
serverURL := info.ServerURL
if serverURL == "" {
serverURL = "https://get.pulumi.com/releases/plugins"
}
serverURL = strings.TrimSuffix(serverURL, "/")
logging.V(1).Infof("%s downloading from %s", info.Name, serverURL)
// URL escape the path value to ensure we have the correct path for S3/CloudFront.
endpoint := fmt.Sprintf("%s/%s",
serverURL,
url.QueryEscape(fmt.Sprintf("pulumi-%s-%s-v%s-%s-%s.tar.gz", info.Kind, info.Name, info.Version, os, arch)))
logging.V(9).Infof("full plugin download url: %s", endpoint)
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return nil, -1, err
}
userAgent := fmt.Sprintf("pulumi-cli/1 (%s; %s)", version.Version, runtime.GOOS)
req.Header.Set("User-Agent", userAgent)
logging.V(9).Infof("plugin install request headers: %v", req.Header)
resp, err := httputil.DoWithRetry(req, http.DefaultClient)
if err != nil {
return nil, -1, err
}
logging.V(9).Infof("plugin install response headers: %v", resp.Header)
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, -1, errors.Errorf("%d HTTP error fetching plugin from %s", resp.StatusCode, endpoint)
}
return resp.Body, resp.ContentLength, nil
}
// installLock acquires a file lock used to prevent concurrent installs.
func (info PluginInfo) installLock() (unlock func(), err error) {
finalDir, err := info.DirPath()
if err != nil {
return nil, err
}
lockFilePath := fmt.Sprintf("%s.lock", finalDir)
if err := os.MkdirAll(filepath.Dir(lockFilePath), 0700); err != nil {
return nil, errors.Wrap(err, "creating plugin root")
}
mutex := fsutil.NewFileMutex(lockFilePath)
if err := mutex.Lock(); err != nil {
return nil, err
}
return func() {
contract.IgnoreError(mutex.Unlock())
}, nil
}
// Install installs a plugin's tarball into the cache. It validates that plugin names are in the expected format.
// Previous versions of Pulumi extracted the tarball to a temp directory first, and then renamed the temp directory
// to the final directory. The rename operation fails often enough on Windows due to aggressive virus scanners opening
// files in the temp directory. To address this, we now extract the tarball directly into the final directory, and use
// file locks to prevent concurrent installs.
// Each plugin has its own file lock, with the same name as the plugin directory, with a `.lock` suffix.
// During installation an empty file with a `.partial` suffix is created, indicating that installation is in-progress.
// The `.partial` file is deleted when installation is complete, indicating that the plugin has finished installing.
// If a failure occurs during installation, the `.partial` file will remain, indicating the plugin wasn't fully
// installed. The next time the plugin is installed, the old installation directory will be removed and replaced with
// a fresh install.
func (info PluginInfo) Install(tarball io.ReadCloser) error {
defer contract.IgnoreClose(tarball)
// Fetch the directory into which we will expand this tarball.
finalDir, err := info.DirPath()
if err != nil {
return err
}
// Create a file lock file at <pluginsdir>/<kind>-<name>-<version>.lock.
unlock, err := info.installLock()
if err != nil {
return err
}
defer unlock()
// Cleanup any temp dirs from failed installations of this plugin from previous versions of Pulumi.
if err := cleanupTempDirs(finalDir); err != nil {
// We don't want to fail the installation if there was an error cleaning up these old temp dirs.
// Instead, log the error and continue on.
logging.V(5).Infof("Install: Error cleaning up temp dirs: %s", err.Error())
}
// Get the partial file path (e.g. <pluginsdir>/<kind>-<name>-<version>.partial).
partialFilePath, err := info.PartialFilePath()
if err != nil {
return err
}
// Check whether the directory exists while we were waiting on the lock.
_, finalDirStatErr := os.Stat(finalDir)
if finalDirStatErr == nil {
_, partialFileStatErr := os.Stat(partialFilePath)
if partialFileStatErr != nil {
if os.IsNotExist(partialFileStatErr) {
// finalDir exists and there's no partial file, so the plugin is already installed.
return nil
}
return partialFileStatErr
}
// The partial file exists, meaning a previous attempt at installing the plugin failed.
// Delete finalDir so we can try installing again. There's no need to delete the partial
// file since we'd just be recreating it again below anyway.
if err := os.RemoveAll(finalDir); err != nil {
return err
}
} else if !os.IsNotExist(finalDirStatErr) {
return finalDirStatErr
}
// Create an empty partial file to indicate installation is in-progress.
if err := ioutil.WriteFile(partialFilePath, nil, 0600); err != nil {
return err
}
// Create the final directory.
if err := os.MkdirAll(finalDir, 0700); err != nil {
return err
}
// Uncompress the plugin.
tarballBytes, err := ioutil.ReadAll(tarball)
if err != nil {
return err
}
if err := archive.UnTGZ(tarballBytes, finalDir); err != nil {
return err
}
// Even though we deferred closing the tarball at the beginning of this function, go ahead and explicitly close
// it now since we're finished extracting it, to prevent subsequent output from being displayed oddly with
// the progress bar.
contract.IgnoreClose(tarball)
// Install dependencies, if needed.
proj, err := LoadPluginProject(filepath.Join(finalDir, "PulumiPlugin.yaml"))
if err != nil && !os.IsNotExist(err) {
return errors.Wrap(err, "loading PulumiPlugin.yaml")
}
if proj != nil {
runtime := strings.ToLower(proj.Runtime.Name())
// For now, we only do this for Node.js and Python. For Go, the expectation is the binary is
// already built. For .NET, similarly, a single self-contained binary could be used, but
// otherwise `dotnet run` will implicitly run `dotnet restore`.
// TODO[pulumi/pulumi#1334]: move to the language plugins so we don't have to hard code here.
switch runtime {
case "nodejs":
var b bytes.Buffer
if _, err := npm.Install(finalDir, &b, &b); err != nil {
os.Stderr.Write(b.Bytes())
return errors.Wrap(err, "installing plugin dependencies")
}
case "python":
if err := python.InstallDependencies(finalDir, "venv", false /*showOutput*/); err != nil {
return errors.Wrap(err, "installing plugin dependencies")
}
}
}
// Installation is complete. Remove the partial file.
return os.Remove(partialFilePath)
}
// cleanupTempDirs cleans up leftover temp dirs from failed installs with previous versions of Pulumi.
func cleanupTempDirs(finalDir string) error {
dir := filepath.Dir(finalDir)
infos, err := ioutil.ReadDir(dir)
if err != nil {
return err
}
for _, info := range infos {
// Temp dirs have a suffix of `.tmpXXXXXX` (where `XXXXXX`) is a random number,
// from ioutil.TempFile.
if info.IsDir() && installingPluginRegexp.MatchString(info.Name()) {
path := filepath.Join(dir, info.Name())
if err := os.RemoveAll(path); err != nil {
return errors.Wrapf(err, "cleaning up temp dir %s", path)
}
}
}
return nil
}
func (info PluginInfo) String() string {
var version string
if v := info.Version; v != nil {
version = fmt.Sprintf("-%s", v)
}
return info.Name + version
}
// PluginKind represents a kind of a plugin that may be dynamically loaded and used by Pulumi.
type PluginKind string
const (
// AnalyzerPlugin is a plugin that can be used as a resource analyzer.
AnalyzerPlugin PluginKind = "analyzer"
// LanguagePlugin is a plugin that can be used as a language host.
LanguagePlugin PluginKind = "language"
// ResourcePlugin is a plugin that can be used as a resource provider for custom CRUD operations.
ResourcePlugin PluginKind = "resource"
)
// IsPluginKind returns true if k is a valid plugin kind, and false otherwise.
func IsPluginKind(k string) bool {
switch PluginKind(k) {
case AnalyzerPlugin, LanguagePlugin, ResourcePlugin:
return true
default:
return false
}
}
// HasPlugin returns true if the given plugin exists.
func HasPlugin(plug PluginInfo) bool {
dir, err := plug.DirPath()
if err == nil {
_, err := os.Stat(dir)
if err == nil {
partialFilePath, err := plug.PartialFilePath()
if err == nil {
if _, err := os.Stat(partialFilePath); os.IsNotExist(err) {
return true
}
}
}
}
return false
}
// HasPluginGTE returns true if the given plugin exists at the given version number or greater.
func HasPluginGTE(plug PluginInfo) (bool, error) {
// If an exact match, return true right away.
if HasPlugin(plug) {
return true, nil
}
// Otherwise, load up the list of plugins and find one with the same name/type and >= version.
plugs, err := GetPlugins()
if err != nil {
return false, err
}
// If we're not doing the legacy plugin behavior and we've been asked for a specific version, do the same plugin
// search that we'd do at runtime. This ensures that `pulumi plugin install` works the same way that the runtime
// loader does, to minimize confusion when a user has to install new plugins.
if !enableLegacyPluginBehavior && plug.Version != nil {
requestedVersion := semver.MustParseRange(plug.Version.String())
_, err := SelectCompatiblePlugin(plugs, plug.Kind, plug.Name, requestedVersion)
return err == nil, err
}
for _, p := range plugs {
if p.Name == plug.Name &&
p.Kind == plug.Kind &&
(p.Version != nil && plug.Version != nil && p.Version.GTE(*plug.Version)) {
return true, nil
}
}
return false, nil
}
// GetPolicyDir returns the directory in which an organization's Policy Packs on the current machine are managed.
func GetPolicyDir(orgName string) (string, error) {
return GetPulumiPath(PolicyDir, orgName)
}
// GetPolicyPath finds a PolicyPack by its name version, as well as a bool marked true if the path
// already exists and is a directory.
func GetPolicyPath(orgName, name, version string) (string, bool, error) {
policiesDir, err := GetPolicyDir(orgName)
if err != nil {
return "", false, err
}
policyPackPath := path.Join(policiesDir, fmt.Sprintf("pulumi-analyzer-%s-v%s", name, version))
file, err := os.Stat(policyPackPath)
if err == nil && file.IsDir() {
// PolicyPack exists. Return.
return policyPackPath, true, nil
} else if err != nil && !os.IsNotExist(err) {
// Error trying to inspect PolicyPack FS entry. Return error.
return "", false, err
}
// Not found. Return empty path.
return policyPackPath, false, nil
}
// GetPluginDir returns the directory in which plugins on the current machine are managed.
func GetPluginDir() (string, error) {
return GetPulumiPath(PluginDir)
}
// GetPlugins returns a list of installed plugins.
func GetPlugins() ([]PluginInfo, error) {
// To get the list of plugins, simply scan the directory in the usual place.
dir, err := GetPluginDir()
if err != nil {
return nil, err
}
return getPlugins(dir)
}
func getPlugins(dir string) ([]PluginInfo, error) {
files, err := ioutil.ReadDir(dir)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
// Now read the file infos and create the plugin infos.
var plugins []PluginInfo
for _, file := range files {
// Skip anything that doesn't look like a plugin.
if kind, name, version, ok := tryPlugin(file); ok {
plugin := PluginInfo{
Name: name,
Kind: kind,
Version: &version,
}
path := filepath.Join(dir, file.Name())
if _, err := os.Stat(fmt.Sprintf("%s.partial", path)); err == nil {
// Skip it if the partial file exists, meaning the plugin is not fully installed.
continue
} else if !os.IsNotExist(err) {
return nil, err
}
if err = plugin.SetFileMetadata(path); err != nil {
return nil, err
}
plugins = append(plugins, plugin)
}
}
return plugins, nil
}
// GetPluginPath finds a plugin's path by its kind, name, and optional version. It will match the latest version that
// is >= the version specified. If no version is supplied, the latest plugin for that given kind/name pair is loaded,
// using standard semver sorting rules. A plugin may be overridden entirely by placing it on your $PATH.
func GetPluginPath(kind PluginKind, name string, version *semver.Version) (string, string, error) {
// If we have a version of the plugin on its $PATH, use it. This supports development scenarios.
filename := (&PluginInfo{Kind: kind, Name: name, Version: version}).FilePrefix()
if path, err := exec.LookPath(filename); err == nil {
logging.V(6).Infof("GetPluginPath(%s, %s, %v): found on $PATH %s", kind, name, version, path)
return "", path, nil
}
// At some point in the future, language plugins will be located in the plugin cache, just like regular plugins
// (see pulumi/pulumi#956 for some of the reasons why this isn't the case today). For now, they ship next to the
// `pulumi` binary. While we encourage this folder to be on the $PATH (and so the check above would have found
// the language plugin) it's possible someone is running `pulumi` with an explicit path on the command line or
// has done symlink magic such that `pulumi` is on the path, but the language plugins are not. So, if possible,
// look next to the instance of `pulumi` that is running to find this language plugin.
if kind == LanguagePlugin {
exePath, exeErr := os.Executable()
if exeErr == nil {
fullPath, fullErr := filepath.EvalSymlinks(exePath)
if fullErr == nil {
for _, ext := range getCandidateExtensions() {
candidate := filepath.Join(filepath.Dir(fullPath), filename+ext)
// Let's see if the file is executable. On Windows, os.Stat() returns a mode of "-rw-rw-rw" so on
// on windows we just trust the fact that the .exe can actually be launched.
if stat, err := os.Stat(candidate); err == nil &&
(stat.Mode()&0100 != 0 || runtime.GOOS == windowsGOOS) {
logging.V(6).Infof("GetPluginPath(%s, %s, %v): found next to current executable %s",
kind, name, version, candidate)
return "", candidate, nil
}
}
}
}
}
// Otherwise, check the plugin cache.
plugins, err := GetPlugins()
if err != nil {
return "", "", errors.Wrapf(err, "loading plugin list")
}
var match *PluginInfo
if !enableLegacyPluginBehavior && version != nil {
logging.V(6).Infof("GetPluginPath(%s, %s, %s): enabling new plugin behavior", kind, name, version)
candidate, err := SelectCompatiblePlugin(plugins, kind, name, semver.MustParseRange(version.String()))
if err != nil {
return "", "", NewMissingError(PluginInfo{
Name: name,
Kind: kind,
Version: version,
})
}
match = &candidate
} else {
for _, cur := range plugins {
// Since the value of cur changes as we iterate, we can't save a pointer to it. So let's have a local that
// we can take a pointer to if this plugin is the best match yet.
plugin := cur
if plugin.Kind == kind && plugin.Name == name {
// Always pick the most recent version of the plugin available. Even if this is an exact match, we
// keep on searching just in case there's a newer version available.
var m *PluginInfo
if match == nil && version == nil {
m = &plugin // no existing match, no version spec, take it.
} else if match != nil &&
(match.Version == nil || (plugin.Version != nil && plugin.Version.GT(*match.Version))) {
m = &plugin // existing match, but this plugin is newer, prefer it.
} else if version != nil && plugin.Version != nil && plugin.Version.GTE(*version) {
m = &plugin // this plugin is >= the version being requested, use it.
}
if m != nil {
match = m
logging.V(6).Infof("GetPluginPath(%s, %s, %s): found candidate (#%s)",
kind, name, version, match.Version)
}
}
}
}
if match != nil {
matchDir, err := match.DirPath()
if err != nil {
return "", "", err
}
matchPath, err := match.FilePath()
if err != nil {
return "", "", err
}
logging.V(6).Infof("GetPluginPath(%s, %s, %v): found in cache at %s", kind, name, version, matchPath)
return matchDir, matchPath, nil
}
return "", "", nil
}
// SortedPluginInfo is a wrapper around PluginInfo that allows for sorting by version.
type SortedPluginInfo []PluginInfo
func (sp SortedPluginInfo) Len() int { return len(sp) }
func (sp SortedPluginInfo) Less(i, j int) bool {
iVersion := sp[i].Version
jVersion := sp[j].Version
switch {
case iVersion == nil && jVersion == nil:
return false
case iVersion == nil:
return true
case jVersion == nil:
return false
default:
return iVersion.LT(*jVersion)
}
}
func (sp SortedPluginInfo) Swap(i, j int) { sp[i], sp[j] = sp[j], sp[i] }
// SelectCompatiblePlugin selects a plugin from the list of plugins with the given kind and name that sastisfies the
// requested semver range. It returns the highest version plugin that satisfies the requested constraints, or an error
// if no such plugin could be found.
//
// If there exist plugins in the plugin list that don't have a version, SelectCompatiblePlugin will select them if there
// are no other compatible plugins available.
func SelectCompatiblePlugin(
plugins []PluginInfo, kind PluginKind, name string, requested semver.Range) (PluginInfo, error) {
logging.V(7).Infof("SelectCompatiblePlugin(..., %s): beginning", name)
var bestMatch PluginInfo
var hasMatch bool
// Before iterating over the list of plugins, sort the list of plugins by version in ascending order. This ensures
// that we can do a single pass over the plugin list, from lowest version to greatest version, and be confident that
// the best match that we find at the end is the greatest possible compatible version for the requested plugin.
//
// Plugins without versions are treated as having the lowest version. Ties between plugins without versions are
// resolved arbitrarily.
sort.Sort(SortedPluginInfo(plugins))
for _, plugin := range plugins {
switch {
case plugin.Kind != kind || plugin.Name != name:
// Not the plugin we're looking for.
case !hasMatch && plugin.Version == nil:
// This is the plugin we're looking for, but it doesn't have a version. We haven't seen anything better yet,
// so take it.
logging.V(7).Infof(
"SelectCompatiblePlugin(..., %s): best plugin %s: no version and no other candidates",
name, plugin.String())
hasMatch = true
bestMatch = plugin
case plugin.Version == nil:
// This is a rare case - we've already seen a version-less plugin and we're seeing another here. Ignore this
// one and defer to the one we previously selected.
logging.V(7).Infof("SelectCompatiblePlugin(..., %s): skipping plugin %s: no version", name, plugin.String())
case requested(*plugin.Version):
// This plugin is compatible with the requested semver range. Save it as the best match and continue.
logging.V(7).Infof("SelectCompatiblePlugin(..., %s): best plugin %s: semver match", name, plugin.String())
hasMatch = true
bestMatch = plugin
default:
logging.V(7).Infof(
"SelectCompatiblePlugin(..., %s): skipping plugin %s: semver mismatch", name, plugin.String())
}
}
if !hasMatch {
logging.V(7).Infof("SelectCompatiblePlugin(..., %s): failed to find match", name)
return PluginInfo{}, errors.New("failed to locate compatible plugin")
}
logging.V(7).Infof("SelectCompatiblePlugin(..., %s): selecting plugin '%s': best match ", name, bestMatch.String())
return bestMatch, nil
}
// ReadCloserProgressBar displays a progress bar for the given closer and returns a wrapper closer to manipulate it.
func ReadCloserProgressBar(
closer io.ReadCloser, size int64, message string, colorization colors.Colorization) io.ReadCloser {
if size == -1 {
return closer
}
// If we know the length of the download, show a progress bar.
bar := pb.New(int(size))
bar.Prefix(colorization.Colorize(colors.SpecUnimportant + message + ":"))
bar.Postfix(colorization.Colorize(colors.Reset))
bar.SetMaxWidth(80)
bar.SetUnits(pb.U_BYTES)
bar.Start()
return &barCloser{
bar: bar,
readCloser: bar.NewProxyReader(closer),
}
}
// getCandidateExtensions returns a set of file extensions (including the dot seprator) which should be used when
// probing for an executable file.
func getCandidateExtensions() []string {
if runtime.GOOS == windowsGOOS {
return []string{".exe", ".cmd"}
}
return []string{""}
}
// pluginRegexp matches plugin directory names: pulumi-KIND-NAME-VERSION.
var pluginRegexp = regexp.MustCompile(
"^(?P<Kind>[a-z]+)-" + // KIND
"(?P<Name>[a-zA-Z0-9-]*[a-zA-Z0-9])-" + // NAME
"v(?P<Version>.*)$") // VERSION
// installingPluginRegexp matches the name of temporary folders. Previous versions of Pulumi first extracted
// plugins to a temporary folder with a suffix of `.tmpXXXXXX` (where `XXXXXX`) is a random number, from
// ioutil.TempFile. We should ignore these folders.
var installingPluginRegexp = regexp.MustCompile(`\.tmp[0-9]+$`)
// tryPlugin returns true if a file is a plugin, and extracts information about it.
func tryPlugin(file os.FileInfo) (PluginKind, string, semver.Version, bool) {
// Only directories contain plugins.
if !file.IsDir() {
logging.V(11).Infof("skipping file in plugin directory: %s", file.Name())
return "", "", semver.Version{}, false
}
// Ignore plugins which are being installed
if installingPluginRegexp.MatchString(file.Name()) {
logging.V(11).Infof("skipping plugin %s which is being installed", file.Name())
return "", "", semver.Version{}, false
}
// Filenames must match the plugin regexp.
match := pluginRegexp.FindStringSubmatch(file.Name())
if len(match) != len(pluginRegexp.SubexpNames()) {
logging.V(11).Infof("skipping plugin %s with missing capture groups: expect=%d, actual=%d",
file.Name(), len(pluginRegexp.SubexpNames()), len(match))
return "", "", semver.Version{}, false
}
var kind PluginKind
var name string
var version *semver.Version
for i, group := range pluginRegexp.SubexpNames() {
v := match[i]
switch group {
case "Kind":
// Skip invalid kinds.
if IsPluginKind(v) {
kind = PluginKind(v)
} else {
logging.V(11).Infof("skipping invalid plugin kind: %s", v)
}
case "Name":
name = v
case "Version":
// Skip invalid versions.
ver, err := semver.ParseTolerant(v)
if err == nil {
version = &ver
} else {
logging.V(11).Infof("skipping invalid plugin version: %s", v)
}
}
}
// If anything was missing or invalid, skip this plugin.
if kind == "" || name == "" || version == nil {
logging.V(11).Infof("skipping plugin with missing information: kind=%s, name=%s, version=%v",
kind, name, version)
return "", "", semver.Version{}, false
}
return kind, name, *version, true
}
// getPluginSize recursively computes how much space is devoted to a given plugin.
func getPluginSize(path string) (int64, error) {
file, err := os.Stat(path)
if err != nil {
return 0, nil
}
size := int64(0)
if file.IsDir() {
subs, err := ioutil.ReadDir(path)
if err != nil {
return 0, err
}
for _, child := range subs {
add, err := getPluginSize(filepath.Join(path, child.Name()))
if err != nil {
return 0, err
}
size += add
}
} else {
size += file.Size()
}
return size, nil
}
type barCloser struct {
bar *pb.ProgressBar
readCloser io.ReadCloser
}
func (bc *barCloser) Read(dest []byte) (int, error) {
return bc.readCloser.Read(dest)
}
func (bc *barCloser) Close() error {
bc.bar.Finish()
return bc.readCloser.Close()
}
| [
"\"PULUMI_ENABLE_LEGACY_PLUGIN_SEARCH\""
]
| []
| [
"PULUMI_ENABLE_LEGACY_PLUGIN_SEARCH"
]
| [] | ["PULUMI_ENABLE_LEGACY_PLUGIN_SEARCH"] | go | 1 | 0 | |
dags/ethereumetl_airflow/build_parse_dag.py | from __future__ import print_function
import json
import logging
import os
import time
from datetime import datetime, timedelta
from glob import glob
from airflow import models
from airflow.contrib.operators.bigquery_operator import BigQueryOperator
from airflow.operators.python_operator import PythonOperator
from airflow.operators.sensors import ExternalTaskSensor
from airflow.operators.email_operator import EmailOperator
from google.api_core.exceptions import Conflict
from google.cloud import bigquery
from eth_utils import event_abi_to_log_topic, function_abi_to_4byte_selector
from google.cloud.bigquery import TimePartitioning
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
dags_folder = os.environ.get('DAGS_FOLDER', '/home/airflow/gcs/dags')
def build_parse_dag(
dag_id,
dataset_folder,
parse_destination_dataset_project_id,
notification_emails=None,
parse_start_date=datetime(2018, 7, 1),
schedule_interval='0 0 * * *',
enabled=True,
parse_all_partitions=True
):
if not enabled:
logging.info('enabled is False, the DAG will not be built.')
return None
logging.info('parse_all_partitions is {}'.format(parse_all_partitions))
SOURCE_PROJECT_ID = 'bigquery-public-data'
SOURCE_DATASET_NAME = 'crypto_ethereum'
environment = {
'source_project_id': SOURCE_PROJECT_ID,
'source_dataset_name': SOURCE_DATASET_NAME
}
default_dag_args = {
'depends_on_past': False,
'start_date': parse_start_date,
'email_on_failure': True,
'email_on_retry': False,
'retries': 5,
'retry_delay': timedelta(minutes=5)
}
if notification_emails and len(notification_emails) > 0:
default_dag_args['email'] = [email.strip() for email in notification_emails.split(',')]
dag = models.DAG(
dag_id,
catchup=False,
schedule_interval=schedule_interval,
default_args=default_dag_args)
def create_task_and_add_to_dag(task_config):
dataset_name = 'ethereum_' + task_config['table']['dataset_name']
table_name = task_config['table']['table_name']
table_description = task_config['table']['table_description']
schema = task_config['table']['schema']
parser = task_config['parser']
parser_type = parser.get('type', 'log')
abi = json.dumps(parser['abi'])
columns = [c.get('name') for c in schema]
def parse_task(ds, **kwargs):
template_context = kwargs.copy()
template_context['ds'] = ds
template_context['params'] = environment
template_context['params']['table_name'] = table_name
template_context['params']['columns'] = columns
template_context['params']['parser'] = parser
template_context['params']['abi'] = abi
if parser_type == 'log':
template_context['params']['event_topic'] = abi_to_event_topic(parser['abi'])
elif parser_type == 'trace':
template_context['params']['method_selector'] = abi_to_method_selector(parser['abi'])
template_context['params']['struct_fields'] = create_struct_string_from_schema(schema)
template_context['params']['parse_all_partitions'] = parse_all_partitions
client = bigquery.Client()
# # # Create a temporary table
dataset_name_temp = 'parse_temp'
create_dataset(client, dataset_name_temp)
temp_table_name = 'temp_{table_name}_{milliseconds}'\
.format(table_name=table_name, milliseconds=int(round(time.time() * 1000)))
temp_table_ref = client.dataset(dataset_name_temp).table(temp_table_name)
temp_table = bigquery.Table(temp_table_ref, schema=read_bigquery_schema_from_dict(schema, parser_type))
temp_table.description = table_description
temp_table.time_partitioning = TimePartitioning(field='block_timestamp')
logging.info('Creating table: ' + json.dumps(temp_table.to_api_repr()))
temp_table = client.create_table(temp_table)
assert temp_table.table_id == temp_table_name
# # # Query to temporary table
job_config = bigquery.QueryJobConfig()
job_config.priority = bigquery.QueryPriority.INTERACTIVE
job_config.destination = temp_table_ref
sql_template = get_parse_sql_template(parser_type)
sql = kwargs['task'].render_template('', sql_template, template_context)
logging.info(sql)
query_job = client.query(sql, location='US', job_config=job_config)
submit_bigquery_job(query_job, job_config)
assert query_job.state == 'DONE'
# # # Copy / merge to destination
if parse_all_partitions:
# Copy temporary table to destination
copy_job_config = bigquery.CopyJobConfig()
copy_job_config.write_disposition = 'WRITE_TRUNCATE'
dest_table_ref = client.dataset(dataset_name, project=parse_destination_dataset_project_id).table(table_name)
copy_job = client.copy_table(temp_table_ref, dest_table_ref, location='US', job_config=copy_job_config)
submit_bigquery_job(copy_job, copy_job_config)
assert copy_job.state == 'DONE'
# Need to do update description as copy above won't repect the description in case destination table
# already exists
table = client.get_table(dest_table_ref)
table.description = table_description
table = client.update_table(table, ["description"])
assert table.description == table_description
else:
# Merge
# https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#merge_statement
merge_job_config = bigquery.QueryJobConfig()
# Finishes faster, query limit for concurrent interactive queries is 50
merge_job_config.priority = bigquery.QueryPriority.INTERACTIVE
merge_sql_template = get_merge_table_sql_template()
merge_template_context = template_context.copy()
merge_template_context['params']['source_table'] = temp_table_name
merge_template_context['params']['destination_dataset_project_id'] = parse_destination_dataset_project_id
merge_template_context['params']['destination_dataset_name'] = dataset_name
merge_template_context['params']['dataset_name_temp'] = dataset_name_temp
merge_template_context['params']['columns'] = columns
merge_sql = kwargs['task'].render_template('', merge_sql_template, merge_template_context)
print('Merge sql:')
print(merge_sql)
merge_job = client.query(merge_sql, location='US', job_config=merge_job_config)
submit_bigquery_job(merge_job, merge_job_config)
assert merge_job.state == 'DONE'
# Delete temp table
client.delete_table(temp_table_ref)
parsing_operator = PythonOperator(
task_id=table_name,
python_callable=parse_task,
provide_context=True,
execution_timeout=timedelta(minutes=60),
dag=dag
)
return parsing_operator
wait_for_ethereum_load_dag_task = ExternalTaskSensor(
task_id='wait_for_ethereum_load_dag',
external_dag_id='ethereum_load_dag',
external_task_id='verify_logs_have_latest',
dag=dag)
files = get_list_of_json_files(dataset_folder)
logging.info('files')
logging.info(files)
all_parse_tasks = []
for f in files:
task_config = read_json_file(f)
task = create_task_and_add_to_dag(task_config)
wait_for_ethereum_load_dag_task >> task
all_parse_tasks.append(task)
if notification_emails and len(notification_emails) > 0:
send_email_task = EmailOperator(
task_id='send_email',
to=[email.strip() for email in notification_emails.split(',')],
subject='Ethereum ETL Airflow Parse DAG Succeeded',
html_content='Ethereum ETL Airflow Parse DAG Succeeded',
dag=dag
)
for task in all_parse_tasks:
task >> send_email_task
return dag
def abi_to_event_topic(abi):
return '0x' + event_abi_to_log_topic(abi).hex()
def abi_to_method_selector(abi):
return '0x' + function_abi_to_4byte_selector(abi).hex()
def get_list_of_json_files(dataset_folder):
logging.info('get_list_of_json_files')
logging.info(dataset_folder)
logging.info(os.path.join(dataset_folder, '*.json'))
return [f for f in glob(os.path.join(dataset_folder, '*.json'))]
def get_parse_sql_template(parser_type):
return get_parse_logs_sql_template() if parser_type == 'log' else get_parse_traces_sql_template()
def get_parse_logs_sql_template():
filepath = os.path.join(dags_folder, 'resources/stages/parse/sqls/parse_logs.sql')
with open(filepath) as file_handle:
content = file_handle.read()
return content
def get_parse_traces_sql_template():
filepath = os.path.join(dags_folder, 'resources/stages/parse/sqls/parse_traces.sql')
with open(filepath) as file_handle:
content = file_handle.read()
return content
def get_merge_table_sql_template():
filepath = os.path.join(dags_folder, 'resources/stages/parse/sqls/merge_table.sql')
with open(filepath) as file_handle:
content = file_handle.read()
return content
def read_json_file(filepath):
with open(filepath) as file_handle:
content = file_handle.read()
return json.loads(content)
def create_struct_string_from_schema(schema):
return ', '.join(['`' + f.get('name') + '` ' + f.get('type') for f in schema])
def read_bigquery_schema_from_dict(schema, parser_type):
result = [
bigquery.SchemaField(
name='block_timestamp',
field_type='TIMESTAMP',
mode='REQUIRED',
description='Timestamp of the block where this event was emitted'),
bigquery.SchemaField(
name='block_number',
field_type='INTEGER',
mode='REQUIRED',
description='The block number where this event was emitted'),
bigquery.SchemaField(
name='transaction_hash',
field_type='STRING',
mode='REQUIRED',
description='Hash of the transactions in which this event was emitted')
]
if parser_type == 'log':
result.append(bigquery.SchemaField(
name='log_index',
field_type='INTEGER',
mode='REQUIRED',
description='Integer of the log index position in the block of this event'))
elif parser_type == 'trace':
result.append(bigquery.SchemaField(
name='trace_address',
field_type='STRING',
description='Comma separated list of trace address in call tree'))
for field in schema:
result.append(bigquery.SchemaField(
name=field.get('name'),
field_type=field.get('type', 'STRING'),
mode=field.get('mode', 'NULLABLE'),
description=field.get('description')))
return result
def submit_bigquery_job(job, configuration):
try:
logging.info('Creating a job: ' + json.dumps(configuration.to_api_repr()))
result = job.result()
logging.info(result)
assert job.errors is None or len(job.errors) == 0
return result
except Exception:
logging.info(job.errors)
raise
def create_dataset(client, dataset_name):
dataset = client.dataset(dataset_name)
try:
logging.info('Creating new dataset ...')
dataset = client.create_dataset(dataset)
logging.info('New dataset created: ' + dataset_name)
except Conflict as error:
logging.info('Dataset already exists')
return dataset
| []
| []
| [
"DAGS_FOLDER"
]
| [] | ["DAGS_FOLDER"] | python | 1 | 0 | |
pkg/controller/windowsmachineconfig/windows/windows.go | package windows
import (
"os"
"github.com/openshift/windows-machine-config-bootstrapper/tools/windows-node-installer/pkg/types"
wkl "github.com/openshift/windows-machine-config-operator/pkg/controller/wellknownlocations"
"github.com/pkg/errors"
logf "sigs.k8s.io/controller-runtime/pkg/log"
)
const (
// remoteDir is the remote temporary directory created on the Windows VM
remoteDir = "C:\\Temp\\"
// winTemp is the default Windows temporary directory
winTemp = "C:\\Windows\\Temp\\"
// wgetIgnoreCertCmd is the remote location of the wget-ignore-cert.ps1 script
wgetIgnoreCertCmd = remoteDir + "wget-ignore-cert.ps1"
)
var log = logf.Log.WithName("windows")
// Windows is a wrapper for the WindowsVM interface.
type Windows struct {
types.WindowsVM
}
// New returns a new instance of windows struct
func New(vm types.WindowsVM) *Windows {
return &Windows{vm}
}
// Configure prepares the Windows VM for the bootstrapper and then runs it
func (vm *Windows) Configure() error {
// Create the temp directory
_, _, err := vm.Run(mkdirCmd(remoteDir), false)
if err != nil {
return errors.Wrapf(err, "unable to create remote directory %v", remoteDir)
}
if err := vm.CopyFile(wkl.IgnoreWgetPowerShellPath, remoteDir); err != nil {
return errors.Wrapf(err, "error while copying powershell script")
}
return vm.runBootstrapper()
}
// runBootstrapper copies the bootstrapper and runs the code on the remote Windows VM
func (vm *Windows) runBootstrapper() error {
if err := vm.CopyFile(wkl.WmcbPath, remoteDir); err != nil {
return errors.Wrap(err, "error while copying wmcb binary")
}
err := vm.initializeBootstrapperFiles()
if err != nil {
return errors.Wrap(err, "error initializing bootstrapper files")
}
wmcbInitializeCmd := remoteDir + "\\wmcb.exe initialize-kubelet --ignition-file " + winTemp +
"worker.ign --kubelet-path " + winTemp + "kubelet.exe"
stdout, stderr, err := vm.Run(wmcbInitializeCmd, true)
if err != nil {
return errors.Wrap(err, "error running bootstrapper")
}
if len(stderr) > 0 {
log.Info(stderr, "err", "bootstrapper initialization failed")
}
log.V(5).Info("stdout from wmcb", "stdout", stdout)
return nil
}
// initializeTestBootstrapperFiles initializes the files required for initialize-kubelet
func (vm *Windows) initializeBootstrapperFiles() error {
err := vm.CopyFile(wkl.KubeletPath, winTemp)
if err != nil {
return errors.Wrapf(err, "unable to copy kubelet.exe to %s", winTemp)
}
// TODO: As of now, getting cluster address from the environment var, remove it.
// Download the worker ignition to C:\Windows\Temp\ using the script that ignores the server cert
// Jira story: https://issues.redhat.com/browse/WINC-274
ClusterAddress := os.Getenv("CLUSTER_ADDR")
ignitionFileDownloadCmd := wgetIgnoreCertCmd + " -server https://api-int." +
ClusterAddress + ":22623/config/worker" + " -output " + winTemp + "worker.ign"
stdout, stderr, err := vm.Run(ignitionFileDownloadCmd, true)
if err != nil {
return errors.Wrap(err, "unable to download worker.ign")
}
log.V(5).Info("stderr associated with the ignition file download", "stderr", stderr)
if len(stderr) > 0 {
log.Info(stderr, "err", "error while downloading the ignition file from cluster")
}
log.V(5).Info("stdout associated with the ignition file download", "stdout", stdout)
return nil
}
// mkdirCmd returns the Windows command to create a directory if it does not exists
func mkdirCmd(dirName string) string {
return "if not exist " + dirName + " mkdir " + dirName
}
| [
"\"CLUSTER_ADDR\""
]
| []
| [
"CLUSTER_ADDR"
]
| [] | ["CLUSTER_ADDR"] | go | 1 | 0 | |
plato/config.py | """
Reading runtime parameters from a standard configuration file (which is easier
to work on than JSON).
"""
import argparse
import logging
import os
import random
import sqlite3
from collections import OrderedDict, namedtuple
import yaml
from yamlinclude import YamlIncludeConstructor
class Config:
"""
Retrieving configuration parameters by parsing a configuration file
using the YAML configuration file parser.
"""
_instance = None
def __new__(cls):
if cls._instance is None:
parser = argparse.ArgumentParser()
parser.add_argument('-i',
'--id',
type=str,
help='Unique client ID.')
parser.add_argument('-p',
'--port',
type=str,
help='The port number for running a server.')
parser.add_argument('-c',
'--config',
type=str,
default='./config.yml',
help='Federated learning configuration file.')
parser.add_argument('-s',
'--server',
type=str,
default=None,
help='The server hostname and port number.')
parser.add_argument(
'-d',
'--download',
action='store_true',
help='Download the dataset to prepare for a training session.')
parser.add_argument('-l',
'--log',
type=str,
default='info',
help='Log messages level.')
args = parser.parse_args()
Config.args = args
if Config.args.id is not None:
Config.args.id = int(args.id)
if Config.args.port is not None:
Config.args.port = int(args.port)
numeric_level = getattr(logging, args.log.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError(f'Invalid log level: {args.log}')
logging.basicConfig(
format='[%(levelname)s][%(asctime)s]: %(message)s',
datefmt='%H:%M:%S')
root_logger = logging.getLogger()
root_logger.setLevel(numeric_level)
cls._instance = super(Config, cls).__new__(cls)
if 'config_file' in os.environ:
filename = os.environ['config_file']
else:
filename = args.config
YamlIncludeConstructor.add_to_loader_class(
loader_class=yaml.SafeLoader, base_dir='./configs')
if os.path.isfile(filename):
with open(filename, 'r', encoding="utf8") as config_file:
config = yaml.load(config_file, Loader=yaml.SafeLoader)
else:
# if the configuration file does not exist, use a default one
config = Config.default_config()
Config.clients = Config.namedtuple_from_dict(config['clients'])
Config.server = Config.namedtuple_from_dict(config['server'])
Config.data = Config.namedtuple_from_dict(config['data'])
Config.trainer = Config.namedtuple_from_dict(config['trainer'])
Config.algorithm = Config.namedtuple_from_dict(config['algorithm'])
if Config.args.server is not None:
Config.server = Config.server._replace(
address=args.server.split(':')[0])
Config.server = Config.server._replace(
port=args.server.split(':')[1])
if Config.args.download:
Config.clients = Config.clients._replace(total_clients=1)
Config.clients = Config.clients._replace(per_round=1)
if 'results' in config:
Config.results = Config.namedtuple_from_dict(config['results'])
if hasattr(Config().results, 'results_dir'):
Config.result_dir = Config.results.results_dir
else:
datasource = Config.data.datasource
model = Config.trainer.model_name
server_type = Config.algorithm.type
Config.result_dir = f'./results/{datasource}/{model}/{server_type}/'
if 'model' in config:
Config.model = Config.namedtuple_from_dict(config['model'])
if hasattr(Config().trainer, 'max_concurrency'):
# Using a temporary SQLite database to limit the maximum number of concurrent
# trainers
Config.sql_connection = sqlite3.connect(
"/tmp/running_trainers.sqlitedb")
Config().cursor = Config.sql_connection.cursor()
# Customizable dictionary of global parameters
Config.params: dict = {}
# A run ID is unique to each client in an experiment
Config.params['run_id'] = os.getpid()
# Pretrained models
Config.params['model_dir'] = "./models/pretrained/"
Config.params['pretrained_model_dir'] = "./models/pretrained/"
return cls._instance
@staticmethod
def namedtuple_from_dict(obj):
"""Creates a named tuple from a dictionary."""
if isinstance(obj, dict):
fields = sorted(obj.keys())
namedtuple_type = namedtuple(typename='Config',
field_names=fields,
rename=True)
field_value_pairs = OrderedDict(
(str(field), Config.namedtuple_from_dict(obj[field]))
for field in fields)
try:
return namedtuple_type(**field_value_pairs)
except TypeError:
# Cannot create namedtuple instance so fallback to dict (invalid attribute names)
return dict(**field_value_pairs)
elif isinstance(obj, (list, set, tuple, frozenset)):
return [Config.namedtuple_from_dict(item) for item in obj]
else:
return obj
@staticmethod
def is_edge_server() -> bool:
"""Returns whether the current instance is an edge server in cross-silo FL."""
return Config().args.port is not None
@staticmethod
def is_central_server() -> bool:
"""Returns whether the current instance is a central server in cross-silo FL."""
return hasattr(Config().algorithm,
'cross_silo') and Config().args.port is None
@staticmethod
def device() -> str:
"""Returns the device to be used for training."""
device = 'cpu'
if hasattr(Config().trainer, 'use_mindspore'):
pass
elif hasattr(Config().trainer, 'use_tensorflow'):
import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
if len(gpus) > 0:
device = 'GPU'
tf.config.experimental.set_visible_devices(
gpus[random.randint(0,
len(gpus) - 1)], 'GPU')
else:
import torch
if torch.cuda.is_available() and torch.cuda.device_count() > 0:
if hasattr(Config().trainer,
'parallelized') and Config().trainer.parallelized:
device = 'cuda'
else:
device = 'cuda:' + str(
random.randint(0,
torch.cuda.device_count() - 1))
return device
@staticmethod
def is_parallel() -> bool:
"""Check if the hardware and OS support data parallelism."""
import torch
return hasattr(Config().trainer, 'parallelized') and Config(
).trainer.parallelized and torch.cuda.is_available(
) and torch.distributed.is_available(
) and torch.cuda.device_count() > 1
@staticmethod
def default_config() -> dict:
''' Supply a default configuration when the configuration file is missing. '''
config = {}
config['clients'] = {}
config['clients']['type'] = 'simple'
config['clients']['total_clients'] = 1
config['clients']['per_round'] = 1
config['clients']['do_test'] = False
config['server'] = {}
config['server']['address'] = '127.0.0.1'
config['server']['port'] = 8000
config['server']['disable_clients'] = True
config['data'] = {}
config['data']['datasource'] = 'MNIST'
config['data']['data_path'] = './data'
config['data']['partition_size'] = 20000
config['data']['sampler'] = 'iid'
config['data']['random_seed'] = 1
config['trainer'] = {}
config['trainer']['type'] = 'basic'
config['trainer']['rounds'] = 5
config['trainer']['parallelized'] = False
config['trainer']['target_accuracy'] = 0.94
config['trainer']['epochs'] = 5
config['trainer']['batch_size'] = 32
config['trainer']['optimizer'] = 'SGD'
config['trainer']['learning_rate'] = 0.01
config['trainer']['momentum'] = 0.9
config['trainer']['weight_decay'] = 0.0
config['trainer']['model_name'] = 'lenet5'
config['algorithm'] = {}
config['algorithm']['type'] = 'fedavg'
return config
@staticmethod
def store() -> None:
""" Saving the current run-time configuration to a file. """
data = {}
data['clients'] = Config.clients._asdict()
data['server'] = Config.server._asdict()
data['data'] = Config.data._asdict()
data['trainer'] = Config.trainer._asdict()
data['algorithm'] = Config.algorithm._asdict()
with open(Config.args.config, "w", encoding="utf8") as out:
yaml.dump(data, out, default_flow_style=False)
| []
| []
| [
"config_file"
]
| [] | ["config_file"] | python | 1 | 0 | |
go/libraries/doltcore/sqle/altertests/common_test.go | // Copyright 2021 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package altertests
import (
"context"
"fmt"
"io"
"os"
"testing"
"time"
"github.com/dolthub/go-mysql-server/sql"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/dolthub/dolt/go/libraries/doltcore/doltdb"
"github.com/dolthub/dolt/go/libraries/doltcore/dtestutils"
"github.com/dolthub/dolt/go/libraries/doltcore/env"
"github.com/dolthub/dolt/go/libraries/doltcore/sqle"
"github.com/dolthub/dolt/go/libraries/doltcore/table/editor"
)
type ModifyTypeTest struct {
FromType string
ToType string
InsertValues string
SelectRes []interface{}
ExpectedErr bool
}
func RunModifyTypeTests(t *testing.T, tests []ModifyTypeTest) {
for _, test := range tests {
name := fmt.Sprintf("%s -> %s: %s", test.FromType, test.ToType, test.InsertValues)
if len(name) > 200 {
name = name[:200]
}
t.Run(name, func(t *testing.T) {
t.Parallel()
ctx := context.Background()
dEnv := dtestutils.CreateTestEnv()
root, err := dEnv.WorkingRoot(ctx)
require.NoError(t, err)
root, err = executeModify(t, ctx, dEnv, root, fmt.Sprintf("CREATE TABLE test(pk BIGINT PRIMARY KEY, v1 %s);", test.FromType))
require.NoError(t, err)
root, err = executeModify(t, ctx, dEnv, root, fmt.Sprintf("INSERT INTO test VALUES %s;", test.InsertValues))
require.NoError(t, err)
root, err = executeModify(t, ctx, dEnv, root, fmt.Sprintf("ALTER TABLE test MODIFY v1 %s;", test.ToType))
if test.ExpectedErr {
assert.Error(t, err)
return
}
require.NoError(t, err)
res, err := executeSelect(t, ctx, dEnv, root, "SELECT v1 FROM test ORDER BY pk;")
require.NoError(t, err)
assert.Equal(t, test.SelectRes, res)
})
}
}
func SkipByDefaultInCI(t *testing.T) {
if os.Getenv("CI") != "" && os.Getenv("DOLT_TEST_RUN_NON_RACE_TESTS") == "" {
t.Skip()
}
}
func widenValue(v interface{}) interface{} {
switch x := v.(type) {
case int:
return int64(x)
case int8:
return int64(x)
case int16:
return int64(x)
case int32:
return int64(x)
case uint:
return uint64(x)
case uint8:
return uint64(x)
case uint16:
return uint64(x)
case uint32:
return uint64(x)
case float32:
return float64(x)
default:
return v
}
}
func parseTime(timestampLayout bool, value string) time.Time {
var t time.Time
var err error
if timestampLayout {
t, err = time.Parse("2006-01-02 15:04:05.999999", value)
} else {
t, err = time.Parse("2006-01-02", value)
}
if err != nil {
panic(err)
}
return t.UTC()
}
func executeSelect(t *testing.T, ctx context.Context, dEnv *env.DoltEnv, root *doltdb.RootValue, query string) ([]interface{}, error) {
var err error
opts := editor.Options{Deaf: dEnv.DbEaFactory(), Tempdir: dEnv.TempTableFilesDir()}
db := sqle.NewDatabase("dolt", dEnv.DbData(), opts)
engine, sqlCtx, err := sqle.NewTestEngine(t, dEnv, ctx, db, root)
if err != nil {
return nil, err
}
_, iter, err := engine.Query(sqlCtx, query)
if err != nil {
return nil, err
}
var vals []interface{}
var r sql.Row
for r, err = iter.Next(sqlCtx); err == nil; r, err = iter.Next(sqlCtx) {
if len(r) == 1 {
// widen the values since we're testing values rather than types
vals = append(vals, widenValue(r[0]))
} else if len(r) > 1 {
return nil, fmt.Errorf("expected return of single value from select: %q", query)
} else { // no values
vals = append(vals, nil)
}
}
if err != io.EOF {
return nil, err
}
return vals, nil
}
func executeModify(t *testing.T, ctx context.Context, dEnv *env.DoltEnv, root *doltdb.RootValue, query string) (*doltdb.RootValue, error) {
opts := editor.Options{Deaf: dEnv.DbEaFactory(), Tempdir: dEnv.TempTableFilesDir()}
db := sqle.NewDatabase("dolt", dEnv.DbData(), opts)
engine, sqlCtx, err := sqle.NewTestEngine(t, dEnv, ctx, db, root)
if err != nil {
return nil, err
}
_, iter, err := engine.Query(sqlCtx, query)
if err != nil {
return nil, err
}
for {
_, err := iter.Next(sqlCtx)
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
}
err = iter.Close(sqlCtx)
if err != nil {
return nil, err
}
return db.GetRoot(sqlCtx)
}
| [
"\"CI\"",
"\"DOLT_TEST_RUN_NON_RACE_TESTS\""
]
| []
| [
"DOLT_TEST_RUN_NON_RACE_TESTS",
"CI"
]
| [] | ["DOLT_TEST_RUN_NON_RACE_TESTS", "CI"] | go | 2 | 0 | |
runtests.py | import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_summernote.test_settings'
test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, test_dir)
from django.test.utils import get_runner
from django.conf import settings
import django
if django.VERSION >= (1, 7):
django.setup()
def runtests():
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True)
failures = test_runner.run_tests(['django_summernote'])
sys.exit(bool(failures))
if __name__ == '__main__':
runtests()
| []
| []
| [
"DJANGO_SETTINGS_MODULE"
]
| [] | ["DJANGO_SETTINGS_MODULE"] | python | 1 | 0 | |
airflow/executors/celery_executor.py | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import subprocess
import time
import os
from celery import Celery
from celery import states as celery_states
from airflow.config_templates.default_celery import DEFAULT_CELERY_CONFIG
from airflow.exceptions import AirflowException
from airflow.executors.base_executor import BaseExecutor
from airflow import configuration
from airflow.utils.log.logging_mixin import LoggingMixin
from airflow.utils.module_loading import import_string
'''
To start the celery worker, run the command:
airflow worker
'''
if configuration.conf.has_option('celery', 'celery_config_options'):
celery_configuration = import_string(
configuration.conf.get('celery', 'celery_config_options')
)
else:
celery_configuration = DEFAULT_CELERY_CONFIG
app = Celery(
configuration.conf.get('celery', 'CELERY_APP_NAME'),
config_source=celery_configuration)
@app.task
def execute_command(command):
log = LoggingMixin().log
log.info("Executing command in Celery: %s", command)
env = os.environ.copy()
try:
subprocess.check_call(command, shell=True, stderr=subprocess.STDOUT,
close_fds=True, env=env)
except subprocess.CalledProcessError as e:
log.exception('execute_command encountered a CalledProcessError')
log.error(e.output)
raise AirflowException('Celery command failed')
class CeleryExecutor(BaseExecutor):
"""
CeleryExecutor is recommended for production use of Airflow. It allows
distributing the execution of task instances to multiple worker nodes.
Celery is a simple, flexible and reliable distributed system to process
vast amounts of messages, while providing operations with the tools
required to maintain such a system.
"""
def start(self):
self.tasks = {}
self.last_state = {}
def execute_async(self, key, command,
queue=DEFAULT_CELERY_CONFIG['task_default_queue'],
executor_config=None):
self.log.info("[celery] queuing {key} through celery, "
"queue={queue}".format(**locals()))
self.tasks[key] = execute_command.apply_async(
args=[command], queue=queue)
self.last_state[key] = celery_states.PENDING
def sync(self):
self.log.debug("Inquiring about %s celery task(s)", len(self.tasks))
for key, task in list(self.tasks.items()):
try:
state = task.state
if self.last_state[key] != state:
if state == celery_states.SUCCESS:
self.success(key)
del self.tasks[key]
del self.last_state[key]
elif state == celery_states.FAILURE:
self.fail(key)
del self.tasks[key]
del self.last_state[key]
elif state == celery_states.REVOKED:
self.fail(key)
del self.tasks[key]
del self.last_state[key]
else:
self.log.info("Unexpected state: %s", state)
self.last_state[key] = state
except Exception as e:
self.log.error("Error syncing the celery executor, ignoring it:")
self.log.exception(e)
def end(self, synchronous=False):
if synchronous:
while any([
task.state not in celery_states.READY_STATES
for task in self.tasks.values()]):
time.sleep(5)
self.sync()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
django_project/testdj/manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testdj.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
| []
| []
| []
| [] | [] | python | 0 | 0 | |
src/test/java/AlertAPI01.java |
import com.aut.BaseClass;
import com.aut.DatabaseFactory;
import com.aut.EncryptionServiceImpl;
import com.aut.HttpMethodsFactory;
import com.thoughtworks.gauge.Step;
import io.restassured.path.json.JsonPath;
import org.junit.Assert;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class AlertAPI01 extends BaseClass {
@Step("User Enter Alert Search API </api/><version></alerts/search>")
public void enter_api(String arg0, String arg1, String arg2) {
this.api = System.getenv("URI") + arg0 + arg1 + arg2;
System.out.println("API: " + api);
}
@Step("User Call Alert Search API")
public void call_the_api() {
Map<String, String> header = new HashMap();
header.put("headername", "Authorization");
header.put("headervalue", "bearer " + LogInAPISteps.token);
this.response = HttpMethodsFactory.getMethod(this.api, header);
this.setJsonPath(new JsonPath(this.response.getBody().asString()));
}
public void get_db_data(String id) throws SQLException, ClassNotFoundException {
String sql = "select sent_alert_details.id as sentalertid,person.id as grampaid, sent_alert_details.status as status,sent_alert_details.alert_message_body as alertbody ,sent_alert_details.alert_message_subject as alertsubject,person.first_name fname,person.last_name lname from main.user_alert_details join main.sent_alert_details on sent_alert_details.id=user_alert_details.sent_alert_details_id join main.person on person.id=sent_alert_details.grampa_id and user_alert_details.id=" + EncryptionServiceImpl.decryptToLong(id) + "";
System.out.println(sql);
setResults(DatabaseFactory.getDBData(sql));
Assert.assertEquals("No record found. ID:" + EncryptionServiceImpl.decryptToLong(id), true, getResults().next());
getResults().previous();
}
@Step("Validate Alert Content")
public void validate_alert_content() throws SQLException, ClassNotFoundException {
for (int i = 1; i <= getJsonPath().getList("content.alerts").size(); i++) {
int count = 0;
String val = Integer.toString(i - 1);
String userid = getJsonPath().getString("content.alerts[" + val + "].id");
String sentalertid = getJsonPath().getString("content.alerts[" + val + "].sentAlertDetail.id");
String status = getJsonPath().getString("content.alerts[" + val + "].sentAlertDetail.status");
String alertbody = getJsonPath().getString("content.alerts[" + val + "].sentAlertDetail.alertMessageBody");
String alertsubject = getJsonPath().getString("content.alerts[" + val + "].sentAlertDetail.alertMessageSubject");
String grampaid = getJsonPath().getString("content.alerts[" + val + "].sentAlertDetail.grampa.id");
String grampaname = getJsonPath().getString("content.alerts[" + val + "].sentAlertDetail.grampa.elderName");
get_db_data(userid);
while (getResults().next()) {
count++;
Assert.assertEquals(getResults().getString("sentalertid"), EncryptionServiceImpl.decryptToLong(sentalertid).toString());
Assert.assertEquals(getResults().getString("status"), status);
Assert.assertEquals(getResults().getString("alertbody"), alertbody);
Assert.assertEquals(getResults().getString("alertsubject"), alertsubject);
Assert.assertEquals(getResults().getString("grampaid"), EncryptionServiceImpl.decryptToLong(grampaid).toString());
Assert.assertEquals(getResults().getString("fname") + " " + getResults().getString("lname"), grampaname);
}
Assert.assertEquals("Data miss match API:DB", 1, count);
}
}
}
| [
"\"URI\""
]
| []
| [
"URI"
]
| [] | ["URI"] | java | 1 | 0 | |
5_Linked_Lists/4.py | # https://www.hackerrank.com/challenges/find-the-merge-point-of-two-joined-linked-lists/problem
#!/bin/python3
import math
import os
import random
import re
import sys
class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = SinglyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
self.tail = node
def print_singly_linked_list(node, sep, fptr):
while node:
fptr.write(str(node.data))
node = node.next
if node:
fptr.write(sep)
# Complete the findMergeNode function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def findMergeNode(head1, head2):
while(head1.next!=None):
t=head1
head1=head1.next
t.next=None
while(head2.next!=None): head2=head2.next
return head2.data
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
tests = int(input())
for tests_itr in range(tests):
index = int(input())
llist1_count = int(input())
llist1 = SinglyLinkedList()
for _ in range(llist1_count):
llist1_item = int(input())
llist1.insert_node(llist1_item)
llist2_count = int(input())
llist2 = SinglyLinkedList()
for _ in range(llist2_count):
llist2_item = int(input())
llist2.insert_node(llist2_item)
ptr1 = llist1.head;
ptr2 = llist2.head;
for i in range(llist1_count):
if i < index:
ptr1 = ptr1.next
for i in range(llist2_count):
if i != llist2_count-1:
ptr2 = ptr2.next
ptr2.next = ptr1
result = findMergeNode(llist1.head, llist2.head)
fptr.write(str(result) + '\n')
fptr.close() | []
| []
| [
"OUTPUT_PATH"
]
| [] | ["OUTPUT_PATH"] | python | 1 | 0 | |
config/config_test.go | package config
import (
"io/ioutil"
"os"
"reflect"
"testing"
"github.com/stretchr/testify/suite"
"goyave.dev/goyave/v3/helper/filesystem"
)
type ConfigTestSuite struct {
suite.Suite
previousEnv string
}
func (suite *ConfigTestSuite) SetupSuite() {
suite.previousEnv = os.Getenv("GOYAVE_ENV")
}
func (suite *ConfigTestSuite) SetupTest() {
os.Setenv("GOYAVE_ENV", "test")
Clear()
if err := Load(); err != nil {
suite.FailNow(err.Error())
}
}
func (suite *ConfigTestSuite) TestIsLoaded() {
suite.True(IsLoaded())
}
func (suite *ConfigTestSuite) TestReadConfigFile() {
obj, err := readConfigFile("config.test.json")
suite.Nil(err)
suite.NotEmpty(obj)
suite.Equal("root level content", obj["rootLevel"])
cat, ok := obj["app"]
suite.True(ok)
catObj, ok := cat.(map[string]interface{})
suite.True(ok)
suite.Equal("test", catObj["environment"])
_, ok = catObj["name"]
suite.False(ok)
// Error
err = ioutil.WriteFile("test-forbidden.json", []byte("{\"app\":\"test\"}"), 0111)
if err != nil {
panic(err)
}
defer filesystem.Delete("test-forbidden.json")
obj, err = readConfigFile("test-forbidden.json")
suite.NotNil(err)
if err != nil {
suite.Equal("open test-forbidden.json: permission denied", err.Error())
}
suite.Empty(obj)
}
func (suite *ConfigTestSuite) TestLoadDefaults() {
src := object{
"rootLevel": &Entry{"root level content", []interface{}{}, reflect.String, false},
"app": object{
"environment": &Entry{"test", []interface{}{}, reflect.String, false},
},
"auth": object{
"basic": object{
"username": &Entry{"test username", []interface{}{}, reflect.String, false},
"password": &Entry{"test password", []interface{}{}, reflect.String, false},
},
},
}
dst := object{}
loadDefaults(src, dst)
e, ok := dst["rootLevel"]
suite.True(ok)
entry, ok := e.(*Entry)
suite.True(ok)
suite.Equal("root level content", entry.Value)
suite.Equal(reflect.String, entry.Type)
suite.Equal([]interface{}{}, entry.AuthorizedValues)
suite.NotSame(src["rootLevel"], dst["rootLevel"])
e, ok = dst["app"]
suite.True(ok)
app, ok := e.(object)
suite.True(ok)
e, ok = app["environment"]
suite.True(ok)
suite.Equal("test", e.(*Entry).Value)
e, ok = dst["auth"]
suite.True(ok)
auth, ok := e.(object)
suite.True(ok)
e, ok = auth["basic"]
suite.True(ok)
basic, ok := e.(object)
suite.True(ok)
e, ok = basic["username"]
suite.True(ok)
entry, ok = e.(*Entry)
suite.True(ok)
suite.Equal("test username", entry.Value)
suite.Equal(reflect.String, entry.Type)
suite.Equal([]interface{}{}, entry.AuthorizedValues)
e, ok = basic["password"]
suite.True(ok)
entry, ok = e.(*Entry)
suite.True(ok)
suite.Equal("test password", entry.Value)
suite.Equal(reflect.String, entry.Type)
suite.Equal([]interface{}{}, entry.AuthorizedValues)
}
func (suite *ConfigTestSuite) TestLoadDefaultsWithSlice() {
slice := []string{"val1", "val2"}
src := object{
"rootLevel": &Entry{slice, []interface{}{}, reflect.String, true},
}
dst := object{}
loadDefaults(src, dst)
e, ok := dst["rootLevel"]
suite.True(ok)
entry, ok := e.(*Entry)
suite.True(ok)
cpy, ok := entry.Value.([]string)
suite.True(ok)
suite.NotSame(cpy, slice)
suite.Equal(slice, cpy)
}
func (suite *ConfigTestSuite) TestOverride() {
src := object{
"rootLevel": "root level content",
"app": map[string]interface{}{
"environment": "test",
},
"auth": map[string]interface{}{
"basic": map[string]interface{}{
"username": "test username",
"password": "test password",
"deepcategory": map[string]interface{}{
"deepentry": 1,
},
},
},
}
dst := object{
"app": object{
"name": &Entry{"default name", []interface{}{}, reflect.String, false},
"environment": &Entry{"default env", []interface{}{}, reflect.String, false},
},
}
suite.Nil(override(src, dst))
e, ok := dst["rootLevel"]
suite.True(ok)
entry, ok := e.(*Entry)
suite.True(ok)
suite.Equal("root level content", entry.Value)
suite.Equal(reflect.String, entry.Type)
suite.Equal([]interface{}{}, entry.AuthorizedValues)
e, ok = dst["app"]
suite.True(ok)
app, ok := e.(object)
suite.True(ok)
e, ok = app["name"]
suite.True(ok)
suite.Equal("default name", e.(*Entry).Value)
e, ok = app["environment"]
suite.True(ok)
suite.Equal("test", e.(*Entry).Value)
e, ok = dst["auth"]
suite.True(ok)
auth, ok := e.(object)
suite.True(ok)
e, ok = auth["basic"]
suite.True(ok)
basic, ok := e.(object)
suite.True(ok)
e, ok = basic["username"]
suite.True(ok)
entry, ok = e.(*Entry)
suite.True(ok)
suite.Equal("test username", entry.Value)
suite.Equal(reflect.String, entry.Type)
suite.Equal([]interface{}{}, entry.AuthorizedValues)
e, ok = basic["password"]
suite.True(ok)
entry, ok = e.(*Entry)
suite.True(ok)
suite.Equal("test password", entry.Value)
suite.Equal(reflect.String, entry.Type)
suite.Equal([]interface{}{}, entry.AuthorizedValues)
e, ok = basic["deepcategory"]
suite.True(ok)
deepCategory, ok := e.(object)
suite.True(ok)
e, ok = deepCategory["deepentry"]
suite.True(ok)
entry, ok = e.(*Entry)
suite.True(ok)
suite.Equal(1, entry.Value)
suite.Equal(reflect.Int, entry.Type)
suite.Equal([]interface{}{}, entry.AuthorizedValues)
}
func (suite *ConfigTestSuite) TestOverrideConflict() {
// conflict override entry with category (depth == 0)
src := object{
"rootLevel": map[string]interface{}{
"environment": "test",
},
}
dst := object{
"rootLevel": &Entry{"root level content", []interface{}{}, reflect.String, false},
}
err := override(src, dst)
suite.NotNil(err)
if err != nil {
suite.Equal("Invalid config:\n\t- Cannot override entry \"rootLevel\" with a category", err.Error())
}
// conflict override entry with category (depth > 0)
src = object{
"app": map[string]interface{}{
"environment": map[string]interface{}{
"prod": false,
},
},
}
dst = object{
"app": object{
"environment": &Entry{"default env", []interface{}{}, reflect.String, false},
},
}
err = override(src, dst)
suite.NotNil(err)
if err != nil {
suite.Equal("Invalid config:\n\t- Cannot override entry \"environment\" with a category", err.Error())
}
// conflict override category with entry (depth == 0)
src = object{
"app": "test",
}
dst = object{
"app": object{
"name": &Entry{"default name", []interface{}{}, reflect.String, false},
"environment": &Entry{"default env", []interface{}{}, reflect.String, false},
},
}
err = override(src, dst)
suite.NotNil(err)
if err != nil {
suite.Equal("Invalid config:\n\t- Cannot override category \"app\" with an entry", err.Error())
}
// conflict override category with entry (depth > 0)
src = object{
"app": map[string]interface{}{
"environments": "test",
},
}
dst = object{
"app": object{
"name": &Entry{"default name", []interface{}{}, reflect.String, false},
"environments": object{
"prod": &Entry{false, []interface{}{}, reflect.Bool, false},
},
},
}
err = override(src, dst)
suite.NotNil(err)
if err != nil {
suite.Equal("Invalid config:\n\t- Cannot override category \"environments\" with an entry", err.Error())
}
}
func (suite *ConfigTestSuite) TestLoad() {
Clear()
err := Load()
suite.Nil(err)
suite.Equal(configDefaults["server"], config["server"])
suite.Equal(configDefaults["database"], config["database"])
suite.NotEqual(configDefaults["app"], config["app"])
defaultAppCategory := configDefaults["app"].(object)
appCategory := config["app"].(object)
suite.Equal(defaultAppCategory["name"], appCategory["name"])
suite.Equal(defaultAppCategory["debug"], appCategory["debug"])
suite.Equal(defaultAppCategory["defaultLanguage"], appCategory["defaultLanguage"])
suite.Equal(defaultAppCategory["name"], appCategory["name"])
// readConfigFile error
Clear()
err = ioutil.WriteFile("config.forbidden.json", []byte("{\"app\":\"test\"}"), 0111)
if err != nil {
panic(err)
}
defer filesystem.Delete("config.forbidden.json")
if e := os.Setenv("GOYAVE_ENV", "forbidden"); e != nil {
panic(e)
}
err = Load()
if e := os.Setenv("GOYAVE_ENV", "test"); e != nil {
panic(e)
}
suite.NotNil(err)
if err != nil {
suite.Equal("open config.forbidden.json: permission denied", err.Error())
}
suite.Nil(config)
suite.False(IsLoaded())
// override error
Clear()
configDefaults["rootLevel"] = object{}
err = Load()
delete(configDefaults, "rootLevel")
suite.NotNil(err)
if err != nil {
suite.Equal("Invalid config:\n\t- Cannot override category \"rootLevel\" with an entry", err.Error())
}
suite.Nil(config)
suite.False(IsLoaded())
// validation error
Clear()
configDefaults["rootLevel"] = &Entry{42, []interface{}{}, reflect.Int, false}
err = Load()
delete(configDefaults, "rootLevel")
suite.NotNil(err)
if err != nil {
suite.Equal("Invalid config:\n\t- \"rootLevel\" type must be int", err.Error())
}
suite.Nil(config)
suite.False(IsLoaded())
}
func (suite *ConfigTestSuite) TestLoadFrom() {
Clear()
err := LoadFrom("../resources/custom_config.json")
suite.Nil(err)
suite.Equal(configDefaults["server"], config["server"])
suite.Equal(configDefaults["database"], config["database"])
suite.Equal(configDefaults["app"], config["app"])
e, ok := config["custom-entry"]
suite.True(ok)
entry, ok := e.(*Entry)
suite.True(ok)
suite.Equal("value", entry.Value)
}
func (suite *ConfigTestSuite) TestCreateMissingCategories() {
config := object{}
created := createMissingCategories(config, "category.entry")
e, ok := config["category"]
suite.True(ok)
category, ok := e.(object)
suite.True(ok)
_, ok = category["entry"]
suite.False(ok)
suite.Equal(category, created)
// Depth
config = object{}
created = createMissingCategories(config, "category.subcategory.entry")
e, ok = config["category"]
suite.True(ok)
category, ok = e.(object)
suite.True(ok)
e, ok = category["subcategory"]
suite.True(ok)
subcategory, ok := e.(object)
suite.True(ok)
_, ok = subcategory["entry"]
suite.False(ok)
suite.Equal(subcategory, created)
// With partial existence
config = object{
"category": object{},
}
created = createMissingCategories(config, "category.subcategory.entry")
e, ok = config["category"]
suite.True(ok)
category, ok = e.(object)
suite.True(ok)
e, ok = category["subcategory"]
suite.True(ok)
subcategory, ok = e.(object)
suite.True(ok)
_, ok = subcategory["entry"]
suite.False(ok)
suite.Equal(subcategory, created)
config = object{}
created = createMissingCategories(config, "entry")
suite.Equal(config, created)
_, ok = config["entry"]
suite.False(ok)
}
func (suite *ConfigTestSuite) TestSet() {
suite.Equal("root level content", Get("rootLevel"))
Set("rootLevel", "root level content override")
suite.Equal("root level content override", Get("rootLevel"))
suite.Equal("test", Get("app.environment"))
Set("app.environment", "test_override")
suite.Equal("test_override", Get("app.environment"))
Set("newEntry", "test_new_entry")
e, ok := config["newEntry"]
suite.True(ok)
entry, ok := e.(*Entry)
suite.True(ok)
if ok {
suite.Equal("test_new_entry", entry.Value)
suite.Equal(entry.Type, reflect.String)
suite.False(entry.IsSlice)
suite.Equal([]interface{}{}, entry.AuthorizedValues)
}
suite.Panics(func() { // empty key not allowed
Set("", "")
})
// Slice
config["stringslice"] = &Entry{nil, []interface{}{}, reflect.String, true}
Set("stringslice", []string{"val1", "val2"})
suite.Equal([]string{"val1", "val2"}, config["stringslice"].(*Entry).Value)
// Trying to convert an entry to a category
config["app"].(object)["category"] = object{"entry": &Entry{"value", []interface{}{}, reflect.String, false}}
suite.Panics(func() {
Set("app.category.entry.error", "override")
})
suite.Panics(func() {
Set("rootLevel.error", "override")
})
// Trying to replace a category
config["app"].(object)["category"] = object{"entry": &Entry{"value", []interface{}{}, reflect.String, false}}
suite.Panics(func() {
Set("app.category", "not a category")
})
suite.Panics(func() {
Set("app", "not a category")
})
// Config not loaded
Clear()
suite.Panics(func() {
Set("app.name", "config not loaded")
})
}
func (suite *ConfigTestSuite) TestWalk() {
config := object{
"rootLevel": &Entry{"root level content", []interface{}{}, reflect.String, false},
"app": object{
"environment": &Entry{"test", []interface{}{}, reflect.String, false},
},
}
category, entryKey, exists := walk(config, "app.environment")
suite.True(exists)
suite.Equal("environment", entryKey)
suite.Equal(config["app"], category)
category, entryKey, exists = walk(config, "category.subcategory.entry")
suite.False(exists)
suite.Equal("entry", entryKey)
n, ok := config["category"]
suite.True(ok)
newCat, ok := n.(object)
suite.True(ok)
s, ok := newCat["subcategory"]
suite.True(ok)
subCat, ok := s.(object)
suite.True(ok)
suite.Equal(subCat, category)
_, ok = subCat["entry"]
suite.False(ok)
category, entryKey, exists = walk(config, "category.subcategory.other")
suite.False(exists)
suite.Equal("other", entryKey)
n, ok = config["category"]
suite.True(ok)
newCat, ok = n.(object)
suite.True(ok)
s, ok = newCat["subcategory"]
suite.True(ok)
subCat, ok = s.(object)
suite.True(ok)
suite.Equal(subCat, category)
_, ok = subCat["other"]
suite.False(ok)
// Trying to convert an entry to a category
suite.Panics(func() {
walk(config, "app.environment.error")
})
suite.Panics(func() {
walk(config, "rootLevel.error")
})
// Trying to replace a category
suite.Panics(func() {
walk(config, "category.subcategory")
})
suite.Panics(func() {
walk(config, "app")
})
// Path ending with a dot
suite.Panics(func() {
walk(config, "paniccategory.subcategory.")
})
// Check nothing has been created
_, ok = config["paniccategory"]
suite.False(ok)
suite.Panics(func() { // empty key not allowed
walk(config, "")
})
}
func (suite *ConfigTestSuite) TestSetCreateCategories() {
// Entirely new categories
Set("rootCategory.subCategory.entry", "new")
suite.Equal("new", Get("rootCategory.subCategory.entry"))
rootCategory, ok := config["rootCategory"]
rootCategoryObj, okTA := rootCategory.(object)
suite.True(ok)
suite.True(okTA)
subCategory, ok := rootCategoryObj["subCategory"]
subCategoryObj, okTA := subCategory.(object)
suite.True(ok)
suite.True(okTA)
e, ok := subCategoryObj["entry"]
entry, okTA := e.(*Entry)
suite.True(ok)
suite.True(okTA)
suite.Equal("new", entry.Value)
// With a category that already exists
Set("app.subCategory.entry", "new")
suite.Equal("new", Get("app.subCategory.entry"))
appCategory, ok := config["app"]
appCategoryObj, okTA := appCategory.(object)
suite.True(ok)
suite.True(okTA)
subCategory, ok = appCategoryObj["subCategory"]
subCategoryObj, okTA = subCategory.(object)
suite.True(ok)
suite.True(okTA)
e, ok = subCategoryObj["entry"]
entry, okTA = e.(*Entry)
suite.True(ok)
suite.True(okTA)
suite.Equal("new", entry.Value)
}
func (suite *ConfigTestSuite) TestSetValidation() {
previous := Get("app.name")
suite.Panics(func() {
Set("app.name", 1)
})
suite.Equal(previous, Get("app.name"))
// Works with float64 without decimals
Set("server.port", 8080.0)
suite.Equal(8080, Get("server.port"))
}
func (suite *ConfigTestSuite) TestUnset() {
suite.Equal("root level content", Get("rootLevel"))
Set("rootLevel", nil)
val, ok := get("rootLevel")
suite.False(ok)
suite.Nil(val)
}
func (suite *ConfigTestSuite) TestGet() {
suite.Equal("goyave", Get("app.name"))
suite.Panics(func() {
Get("missingKey")
})
suite.Panics(func() {
Get("app.missingKey")
})
suite.Panics(func() {
Get("app") // Cannot get a category
})
suite.Panics(func() {
Get("server.tls.cert") // Value is nil, so considered unset
})
suite.Equal("goyave", GetString("app.name"))
suite.Panics(func() {
GetString("missingKey")
})
suite.Panics(func() {
GetString("app.debug") // Not a string
})
suite.Equal(true, GetBool("app.debug"))
suite.Panics(func() {
GetBool("missingKey")
})
suite.Panics(func() {
GetBool("app.name") // Not a bool
})
suite.Equal(8080, GetInt("server.port"))
suite.Panics(func() {
GetInt("missingKey")
})
suite.Panics(func() {
GetInt("app.name") // Not an int
})
Set("testFloat", 1.42)
suite.Equal(1.42, GetFloat("testFloat"))
suite.Panics(func() {
GetFloat("missingKey")
})
suite.Panics(func() {
GetFloat("app.name") // Not a float
})
}
func (suite *ConfigTestSuite) TestGetSlice() {
Set("stringslice", []string{"val1", "val2"})
suite.Equal([]string{"val1", "val2"}, GetStringSlice("stringslice"))
suite.Panics(func() {
GetStringSlice("missingKey")
})
suite.Panics(func() {
GetStringSlice("app.name") // Not a string slice
})
Set("boolslice", []bool{true, false})
suite.Equal([]bool{true, false}, GetBoolSlice("boolslice"))
suite.Panics(func() {
GetBoolSlice("missingKey")
})
suite.Panics(func() {
GetBoolSlice("app.name") // Not a bool slice
})
Set("intslice", []int{1, 2})
suite.Equal([]int{1, 2}, GetIntSlice("intslice"))
suite.Panics(func() {
GetIntSlice("missingKey")
})
suite.Panics(func() {
GetIntSlice("app.name") // Not an int slice
})
Set("floatslice", []float64{1.2, 2.3})
suite.Equal([]float64{1.2, 2.3}, GetFloatSlice("floatslice"))
suite.Panics(func() {
GetFloatSlice("missingKey")
})
suite.Panics(func() {
GetFloatSlice("app.name") // Not a float slice
})
}
func (suite *ConfigTestSuite) TestLowLevelGet() {
val, ok := get("rootLevel")
suite.True(ok)
suite.Equal("root level content", val)
val, ok = get("app")
suite.False(ok)
suite.Nil(val)
val, ok = get("app.environment")
suite.True(ok)
suite.Equal("test", val)
val, ok = get("app.notakey")
suite.False(ok)
suite.Nil(val)
// Existing but unset value (nil)
val, ok = get("server.tls.cert")
suite.False(ok)
suite.Nil(val)
// Ensure getting a category is not possible
config["app"].(object)["test"] = object{"this": &Entry{"that", []interface{}{}, reflect.String, false}}
val, ok = get("app.test")
suite.False(ok)
suite.Nil(val)
val, ok = get("app.test.this")
suite.True(ok)
suite.Equal("that", val)
// Path ending with a dot
val, ok = get("app.test.")
suite.False(ok)
suite.Nil(val)
// Config not loaded
Clear()
suite.Panics(func() {
get("app.name")
})
}
func (suite *ConfigTestSuite) TestHas() {
suite.False(Has("not_a_config_entry"))
suite.True(Has("rootLevel"))
suite.True(Has("app.name"))
}
func (suite *ConfigTestSuite) TestGetEnv() {
os.Setenv("GOYAVE_ENV", "localhost")
suite.Equal("config.json", getConfigFilePath())
os.Setenv("GOYAVE_ENV", "test")
suite.Equal("config.test.json", getConfigFilePath())
os.Setenv("GOYAVE_ENV", "production")
suite.Equal("config.production.json", getConfigFilePath())
os.Setenv("GOYAVE_ENV", "test")
}
func (suite *ConfigTestSuite) TestTryIntConversion() {
e := &Entry{1.42, []interface{}{}, reflect.Int, false}
suite.False(e.tryIntConversion(reflect.Float64))
e.Value = float64(2)
suite.True(e.tryIntConversion(reflect.Float64))
suite.Equal(2, e.Value)
}
func (suite *ConfigTestSuite) TestValidateEntryWithConversion() {
e := &Entry{1.42, []interface{}{}, reflect.Int, false}
category := object{"number": e}
err := category.validate("")
suite.NotNil(err)
suite.Equal("\n\t- \"number\" type must be int", err.Error())
e.Value = float64(2)
err = category.validate("")
suite.Nil(err)
suite.Equal(2, category["number"].(*Entry).Value)
}
func (suite *ConfigTestSuite) TestValidateEntry() {
// Unset (no validation needed)
e := &Entry{nil, []interface{}{}, reflect.String, false}
err := e.validate("entry")
suite.Nil(err)
e = &Entry{nil, []interface{}{"val1", "val2"}, reflect.String, false}
err = e.validate("entry")
suite.Nil(err)
// Wrong type
e = &Entry{1, []interface{}{}, reflect.String, false}
err = e.validate("entry")
suite.NotNil(err)
if err != nil {
suite.Equal("\"entry\" type must be string", err.Error())
}
// Int conversion
e = &Entry{1.0, []interface{}{}, reflect.Int, false}
err = e.validate("entry")
suite.Nil(err)
suite.Equal(1, e.Value)
e = &Entry{1.42, []interface{}{}, reflect.Int, false}
err = e.validate("entry")
suite.NotNil(err)
if err != nil {
suite.Equal("\"entry\" type must be int", err.Error())
}
// Authorized values
e = &Entry{1.42, []interface{}{1.2, 1.3, 2.4, 42.1, 1.4200000001}, reflect.Float64, false}
err = e.validate("entry")
suite.NotNil(err)
if err != nil {
suite.Equal("\"entry\" must have one of the following values: [1.2 1.3 2.4 42.1 1.4200000001]", err.Error())
}
e = &Entry{"test", []interface{}{"val1", "val2"}, reflect.String, false}
err = e.validate("entry")
suite.NotNil(err)
if err != nil {
suite.Equal("\"entry\" must have one of the following values: [val1 val2]", err.Error())
}
// Everything's fine
e = &Entry{"val1", []interface{}{"val1", "val2"}, reflect.String, false}
err = e.validate("entry")
suite.Nil(err)
e = &Entry{1.42, []interface{}{1.2, 1.3, 2.4, 42.1, 1.4200000001, 1.42}, reflect.Float64, false}
err = e.validate("entry")
suite.Nil(err)
// From environment variable
e = &Entry{"${TEST_VAR}", []interface{}{}, reflect.Float64, false}
os.Setenv("TEST_VAR", "2..")
defer os.Unsetenv("TEST_VAR")
err = e.validate("entry")
suite.NotNil(err)
if err != nil {
suite.Equal("\"entry\" could not be converted to float64 from environment variable \"TEST_VAR\" of value \"2..\"", err.Error())
}
suite.Equal("${TEST_VAR}", e.Value)
}
func (suite *ConfigTestSuite) TestValidateObject() {
config := object{
"rootLevel": &Entry{"root level content", []interface{}{}, reflect.Bool, false},
"app": object{
"environment": &Entry{true, []interface{}{}, reflect.String, false},
"subcategory": object{
"entry": &Entry{666, []interface{}{1, 2, 3}, reflect.Int, false},
},
},
}
err := config.validate("")
suite.NotNil(err)
if err != nil {
message := []string{"\n\t- \"rootLevel\" type must be bool",
"\n\t- \"app.environment\" type must be string",
"\n\t- \"app.subcategory.entry\" must have one of the following values: [1 2 3]"}
// Maps are unordered, use a slice to make sure all messages are there
for _, m := range message {
suite.Contains(err.Error(), m)
}
}
config = object{
"rootLevel": &Entry{"root level content", []interface{}{}, reflect.String, false},
"app": object{
"environment": &Entry{"local", []interface{}{}, reflect.String, false},
"subcategory": object{
"entry": &Entry{2, []interface{}{1, 2, 3}, reflect.Int, false},
},
},
}
err = config.validate("")
suite.Nil(err)
}
func (suite *ConfigTestSuite) TestRegister() {
entry := Entry{"value", []interface{}{"value", "other value"}, reflect.String, false}
Register("rootLevel", entry)
newEntry, ok := configDefaults["rootLevel"]
suite.True(ok)
suite.Equal(&entry, newEntry)
suite.NotSame(&entry, newEntry)
delete(configDefaults, "rootLevel")
// Entry already exists and matches -> do nothing
appCategory := configDefaults["app"].(object)
entry = Entry{"goyave", []interface{}{}, reflect.String, false}
current := appCategory["name"]
Register("app.name", entry)
newEntry, ok = appCategory["name"]
suite.True(ok)
suite.Same(current, newEntry)
suite.NotSame(&entry, newEntry)
// Entry already exists but doesn't match -> panic
// Value doesn't match
entry = Entry{"not goyave", []interface{}{}, reflect.String, false}
current = appCategory["name"]
suite.Panics(func() {
Register("app.name", entry)
})
newEntry, ok = appCategory["name"]
suite.True(ok)
suite.Same(current, newEntry)
suite.Equal("goyave", newEntry.(*Entry).Value)
// Type doesn't match
entry = Entry{"goyave", []interface{}{}, reflect.Int, false}
current = appCategory["name"]
suite.Panics(func() {
Register("app.name", entry)
})
newEntry, ok = appCategory["name"]
suite.True(ok)
suite.Same(current, newEntry)
suite.Equal(reflect.String, newEntry.(*Entry).Type)
// Required values don't match
entry = Entry{"goyave", []interface{}{"app", "thing"}, reflect.String, false}
current = appCategory["name"]
suite.Panics(func() {
Register("app.name", entry)
})
newEntry, ok = appCategory["name"]
suite.True(ok)
suite.Same(current, newEntry)
suite.Equal([]interface{}{}, newEntry.(*Entry).AuthorizedValues)
}
func (suite *ConfigTestSuite) TestTryEnvVarConversion() {
entry := &Entry{"${TEST_VAR}", []interface{}{}, reflect.String, false}
err := entry.tryEnvVarConversion("entry")
suite.NotNil(err)
if err != nil {
suite.Equal("\"entry\": \"TEST_VAR\" environment variable is not set", err.Error())
}
suite.Equal("${TEST_VAR}", entry.Value)
os.Setenv("TEST_VAR", "")
defer os.Unsetenv("TEST_VAR")
err = entry.tryEnvVarConversion("entry")
suite.Nil(err)
suite.Equal("", entry.Value)
entry.Value = "${TEST_VAR}"
os.Setenv("TEST_VAR", "env var value")
err = entry.tryEnvVarConversion("entry")
suite.Nil(err)
suite.Equal("env var value", entry.Value)
// Int conversion
entry = &Entry{"${TEST_VAR}", []interface{}{}, reflect.Int, false}
os.Setenv("TEST_VAR", "29")
err = entry.tryEnvVarConversion("entry")
suite.Nil(err)
suite.Equal(29, entry.Value)
entry.Value = "${TEST_VAR}"
os.Setenv("TEST_VAR", "2.9")
err = entry.tryEnvVarConversion("entry")
suite.NotNil(err)
if err != nil {
suite.Equal("\"entry\" could not be converted to int from environment variable \"TEST_VAR\" of value \"2.9\"", err.Error())
}
suite.Equal("${TEST_VAR}", entry.Value)
// Float conversion
entry = &Entry{"${TEST_VAR}", []interface{}{}, reflect.Float64, false}
os.Setenv("TEST_VAR", "2.9")
err = entry.tryEnvVarConversion("entry")
suite.Nil(err)
suite.Equal(2.9, entry.Value)
entry.Value = "${TEST_VAR}"
os.Setenv("TEST_VAR", "2..")
err = entry.tryEnvVarConversion("entry")
suite.NotNil(err)
if err != nil {
suite.Equal("\"entry\" could not be converted to float64 from environment variable \"TEST_VAR\" of value \"2..\"", err.Error())
}
suite.Equal("${TEST_VAR}", entry.Value)
// Bool conversion
entry = &Entry{"${TEST_VAR}", []interface{}{}, reflect.Bool, false}
os.Setenv("TEST_VAR", "true")
err = entry.tryEnvVarConversion("entry")
suite.Nil(err)
suite.Equal(true, entry.Value)
entry.Value = "${TEST_VAR}"
os.Setenv("TEST_VAR", "no")
err = entry.tryEnvVarConversion("entry")
suite.NotNil(err)
if err != nil {
suite.Equal("\"entry\" could not be converted to bool from environment variable \"TEST_VAR\" of value \"no\"", err.Error())
}
suite.Equal("${TEST_VAR}", entry.Value)
// Empty name edge case
entry = &Entry{"${}", []interface{}{}, reflect.Bool, false}
err = entry.tryEnvVarConversion("entry")
suite.NotNil(err)
if err != nil {
suite.Equal("\"entry\": \"\" environment variable is not set", err.Error())
}
suite.Equal("${}", entry.Value)
}
func (suite *ConfigTestSuite) TestSlice() {
entry := Entry{[]string{"val1", "val2"}, []interface{}{}, reflect.String, false}
suite.NotNil(entry.validate("slice"))
entry = Entry{[]string{"val1", "val2"}, []interface{}{}, reflect.String, true}
suite.Nil(entry.validate("slice"))
entry.Value = []int{4, 5}
err := entry.validate("slice")
suite.NotNil(err)
if err != nil {
suite.Equal("\"slice\" must be a slice of string", err.Error())
}
entry = Entry{[]interface{}{"val1", 1, 2.3}, []interface{}{}, reflect.Interface, true}
suite.Nil(entry.validate("slice"))
entry = Entry{[]interface{}{"val1", 1, 2.3}, []interface{}{"val1", 1, 2.3, true}, reflect.Interface, true}
suite.Nil(entry.validate("slice"))
entry = Entry{[]interface{}{"val1", 1, 'c'}, []interface{}{"val1", 1, 2.3, true}, reflect.Interface, true}
err = entry.validate("slice")
suite.NotNil(err)
if err != nil {
suite.Equal("\"slice\" elements must have one of the following values: [val1 1 2.3 true]", err.Error())
}
}
func (suite *ConfigTestSuite) TestSliceIntConversion() {
entry := Entry{[]float64{1, 2}, []interface{}{}, reflect.Int, true}
suite.Nil(entry.validate("slice"))
suite.Equal([]int{1, 2}, entry.Value)
entry = Entry{[]float64{1, 2.5}, []interface{}{}, reflect.Int, true}
suite.NotNil(entry.validate("slice"))
suite.Equal([]float64{1, 2.5}, entry.Value)
}
func (suite *ConfigTestSuite) TestMakeEntryFromValue() {
entry := makeEntryFromValue(1)
suite.Equal(1, entry.Value)
suite.Equal(entry.Type, reflect.Int)
suite.False(entry.IsSlice)
suite.Equal([]interface{}{}, entry.AuthorizedValues)
entry = makeEntryFromValue([]string{"1", "2"})
suite.Equal([]string{"1", "2"}, entry.Value)
suite.Equal(entry.Type, reflect.String)
suite.True(entry.IsSlice)
suite.Equal([]interface{}{}, entry.AuthorizedValues)
}
func (suite *ConfigTestSuite) TestLoadJSON() {
json := `
{
"app": {
"name": "loaded from json"
}
}`
suite.Nil(LoadJSON(json))
suite.Equal("loaded from json", Get("app.name"))
Clear()
json = `
{
"app": {
"name": 4
}
}`
err := LoadJSON(json)
suite.NotNil(err)
suite.Contains(err.Error(), "Invalid config")
json = `{`
err = LoadJSON(json)
suite.NotNil(err)
suite.Contains(err.Error(), "EOF")
}
func (suite *ConfigTestSuite) TearDownAllSuite() {
config = map[string]interface{}{}
os.Setenv("GOYAVE_ENV", suite.previousEnv)
}
func TestConfigTestSuite(t *testing.T) {
suite.Run(t, new(ConfigTestSuite))
}
| [
"\"GOYAVE_ENV\""
]
| []
| [
"GOYAVE_ENV"
]
| [] | ["GOYAVE_ENV"] | go | 1 | 0 | |
workshop/src/test/java/com/saucedemo/exercises/SanityTest.java | package com.saucedemo.exercises;
import com.saucelabs.saucebindings.SauceSession;
import org.junit.After;
import org.junit.Test;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class SanityTest {
RemoteWebDriver driver;
@Test
public void functionalWorks() {
driver = new SauceSession().start();
assertNotNull("Register for your free sauce account https://saucelabs.com/sign-up", driver);
}
@Test
public void visualWorks() throws MalformedURLException {
MutableCapabilities capabilities = new MutableCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "chrome");
capabilities.setCapability(CapabilityType.BROWSER_VERSION, "latest");
capabilities.setCapability(CapabilityType.PLATFORM_NAME, "Windows 10");
MutableCapabilities sauceOptions = new MutableCapabilities();
sauceOptions.setCapability("username", System.getenv("SAUCE_USERNAME"));
sauceOptions.setCapability("accesskey", System.getenv("SAUCE_ACCESS_KEY"));
capabilities.setCapability("sauce:options", sauceOptions);
MutableCapabilities visualOptions = new MutableCapabilities();
visualOptions.setCapability("apiKey", System.getenv("SCREENER_API_KEY"));
visualOptions.setCapability("projectName", "java-sanity");
visualOptions.setCapability("viewportSize", "1280x1024");
visualOptions.setCapability("failOnNewStates", false);
capabilities.setCapability("sauce:visual", visualOptions);
URL url = new URL("https://hub.screener.io/wd/hub");
driver = new RemoteWebDriver(url, capabilities);
driver.get("https://saucedemo.com");
((JavascriptExecutor)driver).executeScript("/*@visual.init*/", "Simple visual test");
((JavascriptExecutor)driver).executeScript("/*@visual.snapshot*/", "Home");
Map<String, Object> response = (Map<String, Object>) ((JavascriptExecutor)driver).executeScript("/*@visual.end*/");
assertNull(response.get("message"));
}
@After
public void tearDown() {
if(driver != null){
driver.quit();
}
}
}
| [
"\"SAUCE_USERNAME\"",
"\"SAUCE_ACCESS_KEY\"",
"\"SCREENER_API_KEY\""
]
| []
| [
"SAUCE_USERNAME",
"SAUCE_ACCESS_KEY",
"SCREENER_API_KEY"
]
| [] | ["SAUCE_USERNAME", "SAUCE_ACCESS_KEY", "SCREENER_API_KEY"] | java | 3 | 0 | |
tests/settings.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'django-admin-interface'
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'admin_interface',
'colorfield',
]
if django.VERSION < (1, 9):
# ONLY if django version < 1.9
INSTALLED_APPS += [
'flat',
]
if django.VERSION < (2, 0):
# ONLY if django version < 2.0
INSTALLED_APPS += [
'flat_responsive',
]
INSTALLED_APPS += [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.messages',
'django.contrib.sessions',
]
if django.VERSION < (2, 0):
MIDDLEWARE_CLASSES = [
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware'
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
]
else:
MIDDLEWARE = [
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
]
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.request',
]
},
},]
database_engine = os.environ.get('DATABASE_ENGINE', 'sqlite')
database_config = {
'sqlite': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
# 'mysql': {
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME': 'admin_interface',
# 'USER': 'mysql',
# 'PASSWORD': 'mysql',
# 'HOST': '',
# 'PORT': '',
# },
'postgres': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'admin_interface',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': '',
'PORT': '',
}
}
github_workflow = os.environ.get('GITHUB_WORKFLOW')
if github_workflow:
database_config['postgres']['NAME'] = 'postgres'
database_config['postgres']['HOST'] = '127.0.0.1'
database_config['postgres']['PORT'] = '5432'
DATABASES = {
'default': database_config.get(database_engine),
}
USE_I18N = True
LANGUAGES = (
('en', 'English', ),
('it', 'Italian', ),
)
LANGUAGE_CODE = 'en'
ROOT_URLCONF = 'tests.urls'
MEDIA_ROOT = os.path.join(BASE_DIR, 'admin_interface/public/media/')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'admin_interface/public/static/')
STATIC_URL = '/static/'
| []
| []
| [
"GITHUB_WORKFLOW",
"DATABASE_ENGINE"
]
| [] | ["GITHUB_WORKFLOW", "DATABASE_ENGINE"] | python | 2 | 0 | |
pyfastnoisesimd/helpers.py | import pyfastnoisesimd.extension as ext
import concurrent.futures as cf
import numpy as np
from enum import Enum
_MIN_CHUNK_SIZE = 8192
def empty_aligned(shape, dtype=np.float32, n_byte=ext.SIMD_ALIGNMENT):
"""
Provides an memory-aligned array for use with SIMD accelerated instructions.
Should be used to build
Adapted from: https://github.com/hgomersall/pyFFTW/blob/master/pyfftw/utils.pxi
Args:
shape: a sequence (typically a tuple) of array axes.
dtype: NumPy data type of the underlying array. Note FastNoiseSIMD supports
only `np.float32`. Seg faults may occur if this is changed.
n_byte: byte alignment. Should always use the `pyfastnoisesimd.extension.SIMD_ALIGNMENT`
value or seg faults may occur.
"""
dtype = np.dtype(dtype)
itemsize = dtype.itemsize
if not isinstance(shape, (int, np.integer)):
array_length = 1
for each_dimension in shape:
array_length *= each_dimension
else:
array_length = shape
# Allocate a new array that will contain the aligned data
buffer = np.empty(array_length * itemsize + n_byte, dtype='int8')
offset = (n_byte - buffer.ctypes.data) % n_byte
aligned = buffer[offset:offset-n_byte].view(dtype).reshape(shape)
return aligned
def full_aligned(shape, fill, dtype=np.float32, n_byte=ext.SIMD_ALIGNMENT):
"""
As per `empty_aligned`, but returns an array initialized to a constant value.
Args:
shape: a sequence (typically a tuple) of array axes.
fill: the value to fill each array element with.
dtype: NumPy data type of the underlying array. Note FastNoiseSIMD supports
only `np.float32`. Seg faults may occur if this is changed.
n_byte: byte alignment. Should always use the `pyfastnoisesimd.extension.SIMD_ALIGNMENT`
value or seg faults may occur.
"""
aligned = empty_aligned(shape, dtype=dtype, n_byte=n_byte)
aligned.fill(fill)
return aligned
def empty_coords(length, dtype=np.float32, n_byte=ext.SIMD_ALIGNMENT):
"""
"""
dtype = np.dtype(dtype)
itemsize = dtype.itemsize
# We need to expand length to be a multiple of the vector size
vect_len = max(ext.SIMD_ALIGNMENT // itemsize, 1)
aligned_len = int(vect_len*np.ceil(length/vect_len))
shape = (3, aligned_len)
coords = empty_aligned(shape)
# Lots of trouble with passing sliced views out, with over-running the
# array and seg-faulting on an invalid write.
# return coords[:,:length]
return coords
def check_alignment(array):
"""
Verifies that an array is aligned correctly for the supported SIMD level.
Args:
array: numpy.ndarray
Returns:
truth: bool
"""
return ((ext.SIMD_ALIGNMENT - array.ctypes.data) % ext.SIMD_ALIGNMENT) == 0
def check_coords(array):
"""
Verifies that an array is aligned correctly for the supported SIMD level.
Args:
array: numpy.ndarray
Returns:
truth: bool
"""
# print(' Array shape: ', array.shape)
# if array.base is not None:
# print(' Base shape: ', array.base.shape)
base = array if array.base is None else array.base
# print(' Check alignment: ', check_alignment(array))
# print(' Base alignment error: ', (array.shape[1]*array.dtype.itemsize)%ext.SIMD_ALIGNMENT)
return check_alignment(array) \
and (array.shape[1] * array.dtype.itemsize) % ext.SIMD_ALIGNMENT == 0 == 0
def aligned_chunks(array, n_chunks, axis=0):
"""
An generator that divides an array into chunks that have memory
addresses compatible with SIMD vector length.
Args:
array: numpy.ndarray
the array to chunk
n_chunks: int
the desired number of chunks, the returned number _may_ be less.
axis: int
the axis to chunk on, similar to `numpy` axis commanes.
Returns
chunk: numpy.ndarray
start: Tuple[int]
the start indices of the chunk, in the `array`.
"""
block_size = 1
if array.ndim > axis + 1:
block_size = np.product(array.shape[axis:])
# print(f'Got blocksize of {block_size}')
vect_len = max(ext.SIMD_ALIGNMENT // array.dtype.itemsize, 1)
if block_size % vect_len == 0:
# Iterate at-will, the underlying blocks have the correct shape
slice_size = int(np.ceil(array.shape[axis] / n_chunks))
else:
# Round slice_size up to nearest vect_len
slice_size = int(vect_len*np.ceil(array.shape[axis] / n_chunks /vect_len))
# print('Slice size: ', slice_size)
offset = 0
chunk_index = 0
while(chunk_index < n_chunks):
# Dynamic slicing is pretty clumsy, unfortunately:
# https://stackoverflow.com/questions/24398708/slicing-a-numpy-array-along-a-dynamically-specified-axis#47859801
# so just use some nested conditions.
if axis == 0:
if array.ndim == 1:
chunk = array[offset:offset+slice_size]
else:
chunk = array[offset:offset+slice_size, ...]
elif axis == 1:
if array.ndim == 2:
chunk = array[:, offset:offset+slice_size]
else:
chunk = array[:, offset:offset+slice_size, ...]
elif axis == 2:
chunk = array[:, :, offset:offset+slice_size]
# print(f'Chunk has memory addr: {chunk.ctypes.data}, remain: {chunk.ctypes.data%ext.SIMD_ALIGNMENT}')
yield chunk, offset
offset += slice_size
chunk_index += 1
def num_virtual_cores():
"""
Detects the number of virtual cores on a system without importing
``multiprocessing``. Borrowed from NumExpr 2.6.
"""
import os, subprocess
# Linux, Unix and MacOS
if hasattr(os, 'sysconf'):
if 'SC_NPROCESSORS_ONLN' in os.sysconf_names:
# Linux & Unix:
ncpus = os.sysconf('SC_NPROCESSORS_ONLN')
if isinstance(ncpus, int) and ncpus > 0:
return ncpus
else: # OSX:
return int(subprocess.check_output(['sysctl', '-n', 'hw.ncpu']))
# Windows
if 'NUMBER_OF_PROCESSORS' in os.environ:
ncpus = int(os.environ['NUMBER_OF_PROCESSORS'])
if ncpus > 0:
return ncpus
else:
return 1
# TODO: need method for ARM7/8
return 1 # Default
class NoiseType(Enum):
"""
The class of noise generated.
Enums: ``{Value, ValueFractal, Perlin, PerlinFractal, Simplex, SimplexFractal, WhiteNoise, Cellular, Cubic, CubicFractal}``
"""
Value = 0
ValueFractal = 1
Perlin = 2
PerlinFractal = 3
Simplex = 4
SimplexFractal = 5
WhiteNoise = 6
Cellular = 7
Cubic = 8
CubicFractal = 9
class FractalType(Enum):
"""
Enum: Fractal noise types also have an additional fractal type.
Values: ``{FBM, Billow, RigidMulti}``"""
FBM = 0
Billow = 1
RigidMulti = 2
class PerturbType(Enum):
"""
Enum: The enumerator for the class of Perturbation.
Values: ``{NoPeturb, Gradient, GradientFractal, Normalise, Gradient_Normalise, GradientFractal_Normalise}``
"""
NoPerturb = 0
Gradient = 1
GradientFractal = 2
Normalise = 3
Gradient_Normalise = 4
GradientFractal_Normalise = 5
class CellularDistanceFunction(Enum):
"""
Enum: The distance function for cellular noise.
Values: ``{Euclidean, Manhattan, Natural}``"""
Euclidean = 0
Manhattan = 1
Natural = 2
class CellularReturnType(Enum):
"""
Enum: The functional filter to apply to the distance function to generate the
return from cellular noise.
Values: ``{CellValue, Distance, Distance2, Distance2Add, Distance2Sub, Distance2Mul, Distance2Div, NoiseLookup, Distance2Cave}``
"""
CellValue = 0
Distance = 1
Distance2 = 2
Distance2Add = 3
Distance2Sub = 4
Distance2Mul = 5
Distance2Div = 6
NoiseLookup = 7
Distance2Cave = 8
class FractalClass(object):
"""
Holds properties related to noise types that include fractal octaves.
Do not instantiate this class separately from `Noise`.
"""
def __init__(self, fns):
self._fns = fns
self._octaves = 3
self._lacunarity = 2.0
self._gain = 0.5
self._fractalType = FractalType.FBM
@property
def fractalType(self) -> FractalType:
"""
The type of fractal for fractal NoiseTypes.
Default: ``FractalType.FBM``"""
return self._fractalType
@fractalType.setter
def fractalType(self, new):
if isinstance(new, FractalType):
pass
elif isinstance(new, int):
new = FractalType(int)
elif isinstance(new, str):
new = FractalType[new]
else:
raise TypeError('Unparsable type for fractalType: {}'.format(type(new)))
self._fractalType = new
self._fns.SetFractalType(new.value)
@property
def octaves(self) -> int:
"""
Octave count for all fractal noise types, i.e. the number of
log-scaled frequency levels of noise to apply. Generally ``3`` is
sufficient for small textures/sprites (256x256 pixels), use larger
values for larger textures/sprites.
Default: ``3``
"""
return self._octaves
@octaves.setter
def octaves(self, new):
self._octaves = int(new)
self._fns.SetFractalOctaves(int(new))
@property
def lacunarity(self) -> float:
"""
Octave lacunarity for all fractal noise types.
Default: ``2.0``
"""
return self._lacunarity
@lacunarity.setter
def lacunarity(self, new):
self._lacunarity = float(new)
self._fns.SetFractalLacunarity(float(new))
@property
def gain(self) -> float:
"""
Octave gain for all fractal noise types. Reflects the ratio
of the underlying noise to that of the fractal. Values > 0.5 up-weight
the fractal.
Default: ``0.5``
"""
return self._gain
@gain.setter
def gain(self, new):
self._gain = float(new)
self._fns.SetFractalGain(float(new))
class CellularClass(object):
"""
Holds properties related to `NoiseType.Cellular`.
Do not instantiate this class separately from ``Noise``.
"""
def __init__(self, fns):
self._fns = fns
self._returnType = CellularReturnType.Distance
self._distanceFunc = CellularDistanceFunction.Euclidean
self._noiseLookupType = NoiseType.Simplex
self._lookupFrequency = 0.2
self._jitter = 0.45
self._distanceIndices = (0.0, 1.0)
@property
def returnType(self):
"""
The return type for cellular (cubic Voronoi) noise.
Default: ``CellularReturnType.Distance``
"""
return self._returnType
@returnType.setter
def returnType(self, new):
if isinstance(new, CellularReturnType):
pass
elif isinstance(new, int):
new = CellularReturnType(int)
elif isinstance(new, str):
new = CellularReturnType[new]
else:
raise TypeError('Unparsable type for returnType: {}'.format(type(new)))
self._returnType = new
self._fns.SetCellularReturnType(new.value)
@property
def distanceFunc(self):
return self._distanceFunc
@distanceFunc.setter
def distanceFunc(self, new):
"""
The distance function for cellular (cubic Voronoi) noise.
Default: ``CellularDistanceFunction.Euclidean``
"""
if isinstance(new, CellularDistanceFunction):
pass
elif isinstance(new, int):
new = CellularDistanceFunction(int)
elif isinstance(new, str):
new = CellularDistanceFunction[new]
else:
raise TypeError('Unparsable type for distanceFunc: {}'.format(type(new)))
self._distanceFunc = new
self._fns.SetCellularDistanceFunction(new.value)
@property
def noiseLookupType(self) -> NoiseType:
"""
Sets the type of noise used if cellular return type.
Default: `NoiseType.Simplex`
"""
return self._noiseLookupType
@noiseLookupType.setter
def noiseLookupType(self, new):
if isinstance(new, NoiseType):
pass
elif isinstance(new, int):
new = NoiseType(int)
elif isinstance(new, str):
new = NoiseType[new]
else:
raise TypeError('Unparsable type for noiseLookupType: {}'.format(type(new)))
self._noiseLookupType = new
self._fns.SetCellularNoiseLookupType(new.value)
@property
def lookupFrequency(self):
"""
Relative frequency on the cellular noise lookup return type.
Default: ``0.2``
"""
return self._lookupFrequency
@lookupFrequency.setter
def lookupFrequency(self, new):
self._lookupFrequency = float(new)
self._fns.SetCellularNoiseLookupFrequency(float(new))
@property
def jitter(self):
"""
The maximum distance a cellular point can move from it's grid
position. The value is relative to the cubic cell spacing of ``1.0``.
Setting ``jitter > 0.5`` can generate wrapping artifacts.
Default: ``0.45``
"""
return self._jitter
@jitter.setter
def jitter(self, new):
self._jitter = float(new)
self._fns.SetCellularJitter(float(new))
@property
def distanceIndices(self) -> tuple:
"""
Sets the two distance indices used for ``distance2X`` return types
Default: ``(0, 1)``
.. note: * index0 should be lower than index1
* Both indices must be ``>= 0``
* index1 must be ``< 4``
"""
return self._distanceIndices
@distanceIndices.setter
def distanceIndices(self, new):
if not hasattr(new, '__len__') or len(new) != 2:
raise ValueError( 'distanceIndices must be a length 2 array/list/tuple' )
new = list(new)
if new[0] < 0:
new[0] = 0
if new[1] < 0:
new[0] = 0
if new[1] >= 4:
new[1] = 3
if new[0] >= new[1]:
new[0] = new[1]-1
self._distanceIndices = new
return self._fns.SetCellularDistance2Indices(*new)
class PerturbClass(object):
"""
Holds properties related to the perturbation applied to noise.
Do not instantiate this class separately from ``Noise``.
"""
def __init__(self, fns):
self._fns = fns
self._perturbType = PerturbType.NoPerturb
self._amp = 1.0
self._frequency = 0.5
self._octaves = 3
self._lacunarity = 2.0
self._gain = 2.0
self._normaliseLength = 1.0
@property
def perturbType(self) -> PerturbType:
"""
The class of perturbation.
Default: ``PerturbType.NoPeturb``
"""
return self._perturbType
@perturbType.setter
def perturbType(self, new):
if isinstance(new, PerturbType):
pass
elif isinstance(new, int):
new = PerturbType(int)
elif isinstance(new, str):
new = PerturbType[new]
else:
raise TypeError('Unparsable type for perturbType: {}'.format(type(new)))
self._perturbType = new
return self._fns.SetPerturbType(new.value)
@property
def amp(self) -> float:
"""
The maximum distance the input position can be perturbed. The
reasonable values of ``amp`` before artifacts are apparent increase with
decreased ``frequency``. The default value of ``1.0`` is quite high.
Default: ``1.0``
"""
return self._amp
@amp.setter
def amp(self, new):
self._amp = float(new)
return self._fns.SetPerturbAmp(float(new))
@property
def frequency(self) -> float:
"""
The relative frequency for the perturbation gradient.
Default: ``0.5``
"""
return self._frequency
@frequency.setter
def frequency(self, new):
self._frequency = float(new)
return self._fns.SetPerturbFrequency(float(new))
@property
def octaves(self) -> int:
"""
The octave count for fractal perturbation types, i.e. the number of
log-scaled frequency levels of noise to apply. Generally ``3`` is
sufficient for small textures/sprites (256x256 pixels), use larger values for
larger textures/sprites.
Default: ``3``
"""
return self._octaves
@octaves.setter
def octaves(self, new):
self._octaves = int(new)
return self._fns.SetPerturbFractalOctaves(int(new))
@property
def lacunarity(self) -> float:
"""
The octave lacunarity (gap-fill) for fractal perturbation types.
Lacunarity increases the fineness of fractals. The appearance of
graininess in fractal noise occurs when lacunarity is too high for
the given frequency.
Default: ``2.0``
"""
return self._lacunarity
@lacunarity.setter
def lacunarity(self, new):
self._lacunarity = float(new)
return self._fns.SetPerturbFractalLacunarity(float(new))
@property
def gain(self) -> float:
"""
The octave gain for fractal perturbation types. Reflects the ratio
of the underlying noise to that of the fractal. Values > 0.5 up-weight
the fractal.
Default: ``0.5``
"""
return self._gain
@gain.setter
def gain(self, new):
self._gain = float(new)
return self._fns.SetPerturbFractalGain(float(new))
@property
def normaliseLength(self) -> float:
"""
The length for vectors after perturb normalising
Default: ``1.0``
"""
return self._normaliseLength
@normaliseLength.setter
def normaliseLength(self, new):
self._normaliseLength = float(new)
return self._fns.SetPerturbNormaliseLength(float(new))
def _chunk_noise_grid(fns, chunk, chunkStart, chunkAxis, start=[0,0,0]):
"""
For use by ``concurrent.futures`` to multi-thread ``Noise.genAsGrid()`` calls.
"""
dataPtr = chunk.__array_interface__['data'][0]
# print( 'pointer: {:X}, start: {}, shape: {}'.format(dataPtr, chunkStart, chunk.shape) )
if chunkAxis == 0:
fns.FillNoiseSet(chunk, chunkStart+start[0], start[1], start[2], *chunk.shape)
elif chunkAxis == 1:
fns.FillNoiseSet(chunk, start[0], chunkStart+start[1], start[2], *chunk.shape)
else:
fns.FillNoiseSet(chunk, start[0], start[1], chunkStart+start[2], *chunk.shape)
class Noise(object):
"""
``Noise`` encapsulates the C++ SIMD class ``FNSObject`` and enables get/set
of all relative properties via Python properties.
Args:
seed: The random number (int32) that seeds the random-number generator
If ``seed == None`` a random integer is generated as the seed.
numWorkers: The number of threads used for parallel noise generation.
If ``numWorkers == None``, the default applied by
`concurrent.futures.ThreadPoolExecutor` is used.
"""
def __init__(self, seed: int=None, numWorkers: int=None):
self._fns = ext.FNS()
if numWorkers is not None:
self._num_workers = int(numWorkers)
else:
self._num_workers = num_virtual_cores()
self._asyncExecutor = cf.ThreadPoolExecutor(max_workers = self._num_workers)
# Sub-classed object handles
self.fractal = FractalClass(self._fns)
self.cell = CellularClass(self._fns)
self.perturb = PerturbClass(self._fns)
if bool(seed):
self.seed = seed # calls setter
else:
self.seed = np.random.randint(-2147483648, 2147483647)
# Syncronizers for property getters should use the default values as
# stated in `FastNoiseSIMD.h`
self._noiseType = NoiseType.Simplex
self._frequency = 0.01
self._axesScales = (1.0, 1.0, 1.0)
@property
def numWorkers(self) -> int:
"""
Sets the maximum number of thread workers that will be used for
generating noise. Generally should be the number of physical CPU cores
on the machine.
Default: Number of virtual cores on machine.
"""
return self._num_workers
@numWorkers.setter
def numWorkers(self, N_workers) -> int:
N_workers = int(N_workers)
if N_workers <= 0:
raise ValueError('numWorkers must be greater than 0')
self._num_workers = N_workers
self._asyncExecutor = cf.ThreadPoolExecutor(max_workers = N_workers)
@property
def seed(self) -> int:
"""
The random-number seed used for generation of noise.
Default: ``numpy.random.randint()``
"""
return self._fns.GetSeed()
@seed.setter
def seed(self, new):
return self._fns.SetSeed(int(np.int32(new)))
@property
def frequency(self) -> float:
"""
The frequency of the noise, lower values result in larger noise features.
Default: ``0.01``
"""
return self._frequency
@frequency.setter
def frequency(self, new):
self._frequency = float(new)
return self._fns.SetFrequency(float(new))
@property
def noiseType(self) -> NoiseType:
"""
The class of noise.
Default: ``NoiseType.Simplex``
"""
return self._noiseType
@noiseType.setter
def noiseType(self, new):
if isinstance(new, NoiseType):
pass
elif isinstance(new, int):
new = NoiseType(int)
elif isinstance(new, str):
new = NoiseType[new]
else:
raise TypeError('Unparsable type for noiseType: {}'.format(type(new)))
self._noiseType = new
return self._fns.SetNoiseType(new.value)
@property
def axesScales(self) -> tuple:
"""
Sets the FastNoiseSIMD axes scales, which allows for non-square
voxels. Indirectly affects `frequency` by changing the voxel pitch.
Default: ``(1.0, 1.0, 1.0)``
"""
return self._axesScales
@axesScales.setter
def axesScales(self, new: tuple):
if not hasattr(new, '__len__') or len(new) != 3:
raise ValueError( 'axesScales must be a length 3 array/list/tuple' )
self._axesScales = new
return self._fns.SetAxesScales(*new)
def genAsGrid(self, shape=[1,1024,1024], start=[0,0,0]) -> np.ndarray:
"""
Generates noise according to the set properties along a rectilinear
(evenly-spaced) grid.
Args:
shape: Tuple[int]
the shape of the output noise volume.
start: Tuple[int]
the starting coordinates for generation of the grid.
I.e. the coordinates are essentially `start: start + shape`
Example::
import numpy as np
import pyfastnoisesimd as fns
noise = fns.Noise()
result = noise.genFromGrid(shape=[256,256,256], start=[0,0,0])
nextResult = noise.genFromGrid(shape=[256,256,256], start=[256,0,0])
"""
if isinstance(shape, (int, np.integer)):
shape = (shape,)
# There is a minimum array size before we bother to turn on futures.
size = np.product(shape)
# size needs to be evenly divisible by ext.SIMD_ALINGMENT
if np.remainder(size, ext.SIMD_ALIGNMENT/np.dtype(np.float32).itemsize) != 0.0:
raise ValueError('The size of the array (in bytes) must be evenly divisible by the SIMD vector length')
result = empty_aligned(shape)
# Shape could be 1 or 2D, so we need to expand it with singleton
# dimensions for the FillNoiseSet call
if len(start) == 1:
start = [start[0], 0, 0]
elif len(start) == 2:
start = [start[0], start[1], 1]
else:
start = list(start)
start_zero = start[0]
if self._num_workers <= 1 or size < _MIN_CHUNK_SIZE:
# print('Grid single-threaded')
if len(shape) == 1:
shape = (*shape, 1, 1)
elif len(shape) == 2:
shape = (*shape, 1)
else:
shape = shape
self._fns.FillNoiseSet(result, *start, *shape)
return result
# else run in threaded mode.
n_chunks = np.minimum(self._num_workers, shape[0])
# print(f'genAsGrid using {n_chunks} chunks')
# print('Grid multi-threaded')
workers = []
for I, (chunk, consumed) in enumerate(aligned_chunks(result, n_chunks, axis=0)):
# print(f'{I}: Got chunk of shape {chunk.shape} with {consumed} consumed')
if len(chunk.shape) == 1:
chunk_shape = (*chunk.shape, 1, 1)
elif len(chunk.shape) == 2:
chunk_shape = (*chunk.shape, 1)
else:
chunk_shape = chunk.shape
start[0] = start_zero + consumed
# print('len start: ', len(start), ', len shape: ', len(chunk_shape))
peon = self._asyncExecutor.submit(self._fns.FillNoiseSet,
chunk, *start, *chunk_shape)
workers.append(peon)
for peon in workers:
peon.result()
# For memory management we have to tell NumPy it's ok to free the memory
# region when it is dereferenced.
# self._fns._OwnSplitArray(noise)
return result
def genFromCoords(self, coords: np.ndarray) -> np.ndarray:
"""
Generate noise from supplied coordinates, rather than a rectilinear grid.
Useful for complicated shapes, such as tesselated surfaces.
Args:
coords: 3-D coords as generated by ``fns.empty_coords()``
and filled with relevant values by the user.
Returns:
noise: a shape (N,) array of the generated noise values.
Example::
import numpy as np
import pyfastnoisesimd as fns
numCoords = 256
coords = fns.empty_coords(3,numCoords)
# <Set the coordinate values, it is a (3, numCoords) array
coords[0,:] = np.linspace(-np.pi, np.pi, numCoords)
coords[1,:] = np.linspace(-1.0, 1.0, numCoords)
coords[2,:] = np.zeros(numCoords)
noise = fns.Noise()
result = noise.genFromCoords(coords)
"""
if not isinstance(coords, np.ndarray):
raise TypeError('`coords` must be of type `np.ndarray`, not type: ', type(coords))
if coords.ndim != 2:
raise ValueError('`coords` must be a 2D array')
shape = coords.shape
if shape[0] != 3:
raise ValueError('`coords.shape[0]` must equal 3')
if not check_alignment(coords):
raise ValueError('Memory alignment of `coords` is not valid')
if coords.dtype != np.float32:
raise ValueError('`coords` must be of dtype `np.float32`')
if np.remainder(coords.shape[1], ext.SIMD_ALIGNMENT/np.dtype(np.float32).itemsize) != 0.0:
raise ValueError('The number of coordinates must be evenly divisible by the SIMD vector length')
itemsize = coords.dtype.itemsize
result = empty_aligned(shape[1])
if self._num_workers <= 1 or shape[1] < _MIN_CHUNK_SIZE:
self._fns.NoiseFromCoords(result,
coords[0,:], coords[1,:], coords[2,:], shape[1], 0)
return result
n_chunks = np.minimum(self._num_workers,
shape[1] * itemsize / ext.SIMD_ALIGNMENT)
workers = []
# for I, ((result_chunk, r_offset), (coord_chunk, offset)) in enumerate(zip(
# aligned_chunks(result, self._num_workers, axis=0),
# aligned_chunks(coords, self._num_workers, axis=1))):
for I, (result_chunk, offset) in enumerate(
aligned_chunks(result, self._num_workers, axis=0)):
# aligned_size = int(vect_len*np.ceil(result_chunk.size/vect_len))
# print(f' {I}: Got chunk of length {result_chunk.size}, AlignedSize would be: {aligned_size}')
# print(' Offset: ', offset, ', offset error: ', offset % 8)
# zPtr = (coords[0,:].ctypes.data + offset) % 8
# yPtr = (coords[1,:].ctypes.data + offset) % 8
# xPtr = (coords[2,:].ctypes.data + offset) % 8
# print(f' Pointer alignment: {zPtr, yPtr, xPtr}')
# peon = self._asyncExecutor.submit(self._fns.NoiseFromCoords, result,
# coords[0,:], coords[1,:], coords[2,:], aligned_size, offset)
peon = self._asyncExecutor.submit(self._fns.NoiseFromCoords, result,
coords[0,:], coords[1,:], coords[2,:], result_chunk.size, offset)
workers.append(peon)
for peon in workers:
peon.result()
return result
| []
| []
| [
"NUMBER_OF_PROCESSORS"
]
| [] | ["NUMBER_OF_PROCESSORS"] | python | 1 | 0 | |
cmd/server/main.go | // Copyright 2018 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.
package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/cardonator/ofac"
"github.com/moov-io/base/admin"
moovhttp "github.com/moov-io/base/http"
"github.com/moov-io/base/http/bind"
"github.com/go-kit/kit/log"
"github.com/gorilla/mux"
"github.com/mattn/go-sqlite3"
)
var (
httpAddr = flag.String("http.addr", bind.HTTP("ofac"), "HTTP listen address")
adminAddr = flag.String("admin.addr", bind.Admin("ofac"), "Admin HTTP listen address")
flagLogFormat = flag.String("log.format", "", "Format for log lines (Options: json, plain")
ofacDataRefreshInterval = 12 * time.Hour
)
func main() {
flag.Parse()
var logger log.Logger
if strings.ToLower(*flagLogFormat) == "json" {
logger = log.NewJSONLogger(os.Stderr)
} else {
logger = log.NewLogfmtLogger(os.Stderr)
}
logger = log.With(logger, "ts", log.DefaultTimestampUTC)
logger = log.With(logger, "caller", log.DefaultCaller)
logger.Log("startup", fmt.Sprintf("Starting ofac server version %s", ofac.Version))
// Channel for errors
errs := make(chan error)
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
errs <- fmt.Errorf("%s", <-c)
}()
// Setup SQLite database
if sqliteVersion, _, _ := sqlite3.Version(); sqliteVersion != "" {
logger.Log("main", fmt.Sprintf("sqlite version %s", sqliteVersion))
}
db, err := createSqliteConnection(logger, getSqlitePath())
if err != nil {
logger.Log("main", err)
os.Exit(1)
}
if err := migrate(logger, db); err != nil {
logger.Log("main", err)
os.Exit(1)
}
defer func() {
if err := db.Close(); err != nil {
logger.Log("main", err)
}
}()
// Setup business HTTP routes
router := mux.NewRouter()
moovhttp.AddCORSHandler(router)
addPingRoute(router)
// Start business HTTP server
readTimeout, _ := time.ParseDuration("30s")
writTimeout, _ := time.ParseDuration("30s")
idleTimeout, _ := time.ParseDuration("60s")
serve := &http.Server{
Addr: *httpAddr,
Handler: router,
TLSConfig: &tls.Config{
InsecureSkipVerify: false,
PreferServerCipherSuites: true,
MinVersion: tls.VersionTLS12,
},
ReadTimeout: readTimeout,
WriteTimeout: writTimeout,
IdleTimeout: idleTimeout,
}
shutdownServer := func() {
if err := serve.Shutdown(context.TODO()); err != nil {
logger.Log("shutdown", err)
}
}
// Start Admin server (with Prometheus metrics)
adminServer := admin.NewServer(*adminAddr)
go func() {
logger.Log("admin", fmt.Sprintf("listening on %s", adminServer.BindAddr()))
if err := adminServer.Listen(); err != nil {
err = fmt.Errorf("problem starting admin http: %v", err)
logger.Log("admin", err)
errs <- err
}
}()
defer adminServer.Shutdown()
// Setup download repository
downloadRepo := &sqliteDownloadRepository{db, logger}
defer downloadRepo.close()
// Start our searcher (and downloader)
searcher := &searcher{
logger: logger,
}
if stats, err := searcher.refreshData(); err != nil {
logger.Log("main", fmt.Sprintf("ERROR: failed to download/parse initial sanctions lists data: %v", err))
os.Exit(1)
} else {
downloadRepo.recordStats(stats)
logger.Log("main", fmt.Sprintf("OFAC data refreshed - Addresses=%d AltNames=%d SDNs=%d DeniedPersons=%d SectoralSanctions=%d ELs=%d",
stats.Addresses, stats.Alts, stats.SDNs, stats.DeniedPersons, stats.SectoralSanctions, stats.BISEntities))
}
// Setup Watch and Webhook database wrapper
watchRepo := &sqliteWatchRepository{db, logger}
defer watchRepo.close()
webhookRepo := &sqliteWebhookRepository{db}
defer webhookRepo.close()
// Setup company / customer repositories
companyRepo := &sqliteCompanyRepository{db}
defer companyRepo.close()
custRepo := &sqliteCustomerRepository{db}
defer custRepo.close()
// Setup periodic download and re-search
updates := make(chan *downloadStats)
ofacDataRefreshInterval = getOFACRefreshInterval(logger, os.Getenv("OFAC_DATA_REFRESH"))
go searcher.periodicDataRefresh(ofacDataRefreshInterval, downloadRepo, updates)
go searcher.spawnResearching(logger, companyRepo, custRepo, watchRepo, webhookRepo, updates)
// Add manual OFAC data refresh endpoint
adminServer.AddHandler(manualRefreshPath, manualRefreshHandler(logger, searcher, downloadRepo))
// Add searcher for HTTP routes
addCompanyRoutes(logger, router, searcher, companyRepo, watchRepo)
addCustomerRoutes(logger, router, searcher, custRepo, watchRepo)
addSDNRoutes(logger, router, searcher)
addSearchRoutes(logger, router, searcher)
addDownloadRoutes(logger, router, downloadRepo)
// Start business logic HTTP server
go func() {
logger.Log("transport", "HTTP", "addr", *httpAddr)
errs <- serve.ListenAndServe()
// TODO(adam): support TLS
// func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error
}()
// Block/Wait for an error
if err := <-errs; err != nil {
shutdownServer()
logger.Log("exit", err)
}
}
func addPingRoute(r *mux.Router) {
r.Methods("GET").Path("/ping").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
moovhttp.SetAccessControlAllowHeaders(w, r.Header.Get("Origin"))
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
w.Write([]byte("PONG"))
})
}
// env is the value from an environmental variable
func getOFACRefreshInterval(logger log.Logger, env string) time.Duration {
if env != "" {
dur, _ := time.ParseDuration(env)
if dur > 0 {
if logger != nil {
logger.Log("main", fmt.Sprintf("Setting OFAC data refresh interval to %v", dur))
}
return dur
}
}
return ofacDataRefreshInterval
}
| [
"\"OFAC_DATA_REFRESH\""
]
| []
| [
"OFAC_DATA_REFRESH"
]
| [] | ["OFAC_DATA_REFRESH"] | go | 1 | 0 | |
crawler/packages/oxford_api/settings.py | # settings.py
from dotenv import load_dotenv
import os
# explicitly providing path to '.env'
from pathlib import Path # Python 3.6+ only
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
# settings.py
APP_ID = os.getenv("APP_ID")
APP_KEY = os.getenv("APP_KEY")
| []
| []
| [
"APP_ID",
"APP_KEY"
]
| [] | ["APP_ID", "APP_KEY"] | python | 2 | 0 | |
athenabot/database.go | package athenabot
import (
"cloud.google.com/go/firestore"
"context"
"os"
)
func gcloudProject() string {
return os.Getenv("GCLOUD_PROJECT")
}
func writeSeenIssues(ctx context.Context, seenIssues []Issue) error {
client, err := firestore.NewClient(ctx, gcloudProject())
if err != nil {
return err
}
defer client.Close()
issuesCollection := client.Collection("seenIssues")
batch := client.Batch()
for _, issue := range seenIssues {
issueDoc := issuesCollection.Doc(issue.Id)
batch = batch.Set(issueDoc, map[string]interface{}{
"title": issue.Title,
"number": issue.Number,
"repoOwner": "kubernetes",
"repo": "kubernetes",
"url": issue.Url,
})
}
_, err = batch.Commit(ctx)
return err
}
| [
"\"GCLOUD_PROJECT\""
]
| []
| [
"GCLOUD_PROJECT"
]
| [] | ["GCLOUD_PROJECT"] | go | 1 | 0 | |
cmd/shimesaba/main.go | package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"os/signal"
"strings"
"syscall"
"github.com/aws/aws-lambda-go/lambda"
"github.com/handlename/ssmwrap"
"github.com/mashiike/shimesaba"
"github.com/mashiike/shimesaba/internal/logger"
)
type stringSlice []string
func (i *stringSlice) String() string {
return fmt.Sprintf("%v", *i)
}
func (i *stringSlice) Set(v string) error {
if strings.ContainsRune(v, ',') {
*i = append(*i, strings.Split(v, ",")...)
} else {
*i = append(*i, v)
}
return nil
}
var (
Version = "current"
mackerelAPIKey string
debug bool
dryRun bool
backfill uint
configFiles stringSlice
)
func main() {
paths := strings.Split(os.Getenv("SSMWRAP_PATHS"), ",")
if len(paths) == 0 {
err := ssmwrap.Export(ssmwrap.ExportOptions{
Paths: paths,
Retries: 3,
})
if err != nil {
logger.Setup(os.Stderr, "info")
log.Printf("[error] ssmwrap.Export failed: %s\n", err)
os.Exit(1)
}
}
flag.Var(&configFiles, "config", "config file path, can set multiple")
flag.StringVar(&mackerelAPIKey, "mackerel-apikey", "", "for access mackerel API")
flag.BoolVar(&debug, "debug", false, "output debug log")
flag.BoolVar(&dryRun, "dry-run", false, "report output stdout and not put mackerel")
flag.UintVar(&backfill, "backfill", 3, "generate report before n point")
flag.VisitAll(envToFlag)
flag.Parse()
minLevel := "info"
if debug {
minLevel = "debug"
}
logger.Setup(os.Stderr, minLevel)
if backfill == 0 {
log.Println("[error] backfill count must positive avlue")
os.Exit(1)
}
cfg := shimesaba.NewDefaultConfig()
if err := cfg.Load(configFiles...); err != nil {
log.Println("[error]", err)
os.Exit(1)
}
if err := cfg.ValidateVersion(Version); err != nil {
log.Println("[error]", err)
os.Exit(1)
}
app, err := shimesaba.New(mackerelAPIKey, cfg)
if err != nil {
log.Println("[error]", err)
os.Exit(1)
}
if strings.HasPrefix(os.Getenv("AWS_EXECUTION_ENV"), "AWS_Lambda") ||
os.Getenv("AWS_LAMBDA_RUNTIME_API") != "" {
lambda.Start(lambdaHandler(app))
return
}
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP)
defer cancel()
if err := app.Run(ctx, shimesaba.DryRunOption(dryRun), shimesaba.BackfillOption(int(backfill))); err != nil {
log.Println("[error]", err)
os.Exit(1)
}
}
func lambdaHandler(app *shimesaba.App) func(context.Context) error {
return func(ctx context.Context) error {
return app.Run(ctx, shimesaba.DryRunOption(dryRun), shimesaba.BackfillOption(int(backfill)))
}
}
func envToFlag(f *flag.Flag) {
name := strings.ToUpper(strings.Replace(f.Name, "-", "_", -1))
if s, ok := os.LookupEnv(name); ok {
f.Value.Set(s)
}
}
| [
"\"SSMWRAP_PATHS\"",
"\"AWS_EXECUTION_ENV\"",
"\"AWS_LAMBDA_RUNTIME_API\""
]
| []
| [
"AWS_EXECUTION_ENV",
"AWS_LAMBDA_RUNTIME_API",
"SSMWRAP_PATHS"
]
| [] | ["AWS_EXECUTION_ENV", "AWS_LAMBDA_RUNTIME_API", "SSMWRAP_PATHS"] | go | 3 | 0 | |
Django-Projects/djangoprojects/manage.py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoprojects.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
test/e2e/autoscaling/cluster_size_autoscaling.go | /*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package autoscaling
import (
"context"
"fmt"
"io/ioutil"
"math"
"net/http"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
v1 "k8s.io/api/core/v1"
policyv1 "k8s.io/api/policy/v1"
schedulingv1 "k8s.io/api/scheduling/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/uuid"
"k8s.io/apimachinery/pkg/util/wait"
clientset "k8s.io/client-go/kubernetes"
"k8s.io/klog/v2"
"k8s.io/kubernetes/test/e2e/framework"
e2emanifest "k8s.io/kubernetes/test/e2e/framework/manifest"
e2enetwork "k8s.io/kubernetes/test/e2e/framework/network"
e2enode "k8s.io/kubernetes/test/e2e/framework/node"
e2epv "k8s.io/kubernetes/test/e2e/framework/pv"
e2erc "k8s.io/kubernetes/test/e2e/framework/rc"
e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
"k8s.io/kubernetes/test/e2e/scheduling"
testutils "k8s.io/kubernetes/test/utils"
imageutils "k8s.io/kubernetes/test/utils/image"
"github.com/onsi/ginkgo"
)
const (
defaultTimeout = 3 * time.Minute
resizeTimeout = 5 * time.Minute
manualResizeTimeout = 6 * time.Minute
scaleUpTimeout = 5 * time.Minute
scaleUpTriggerTimeout = 2 * time.Minute
scaleDownTimeout = 20 * time.Minute
podTimeout = 2 * time.Minute
nodesRecoverTimeout = 5 * time.Minute
rcCreationRetryTimeout = 4 * time.Minute
rcCreationRetryDelay = 20 * time.Second
makeSchedulableTimeout = 10 * time.Minute
makeSchedulableDelay = 20 * time.Second
freshStatusLimit = 20 * time.Second
gkeUpdateTimeout = 15 * time.Minute
gkeNodepoolNameKey = "cloud.google.com/gke-nodepool"
disabledTaint = "DisabledForAutoscalingTest"
criticalAddonsOnlyTaint = "CriticalAddonsOnly"
newNodesForScaledownTests = 2
unhealthyClusterThreshold = 4
caNoScaleUpStatus = "NoActivity"
caOngoingScaleUpStatus = "InProgress"
timestampFormat = "2006-01-02 15:04:05 -0700 MST"
expendablePriorityClassName = "expendable-priority"
highPriorityClassName = "high-priority"
gpuLabel = "cloud.google.com/gke-accelerator"
)
var _ = SIGDescribe("Cluster size autoscaling [Slow]", func() {
f := framework.NewDefaultFramework("autoscaling")
var c clientset.Interface
var nodeCount int
var memAllocatableMb int
var originalSizes map[string]int
ginkgo.BeforeEach(func() {
c = f.ClientSet
e2eskipper.SkipUnlessProviderIs("gce", "gke")
originalSizes = make(map[string]int)
sum := 0
for _, mig := range strings.Split(framework.TestContext.CloudConfig.NodeInstanceGroup, ",") {
size, err := framework.GroupSize(mig)
framework.ExpectNoError(err)
ginkgo.By(fmt.Sprintf("Initial size of %s: %d", mig, size))
originalSizes[mig] = size
sum += size
}
// Give instances time to spin up
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, sum, scaleUpTimeout))
nodes, err := e2enode.GetReadySchedulableNodes(f.ClientSet)
framework.ExpectNoError(err)
nodeCount = len(nodes.Items)
ginkgo.By(fmt.Sprintf("Initial number of schedulable nodes: %v", nodeCount))
framework.ExpectNotEqual(nodeCount, 0)
mem := nodes.Items[0].Status.Allocatable[v1.ResourceMemory]
memAllocatableMb = int((&mem).Value() / 1024 / 1024)
framework.ExpectEqual(nodeCount, sum)
if framework.ProviderIs("gke") {
val, err := isAutoscalerEnabled(5)
framework.ExpectNoError(err)
if !val {
err = enableAutoscaler("default-pool", 3, 5)
framework.ExpectNoError(err)
}
}
})
ginkgo.AfterEach(func() {
e2eskipper.SkipUnlessProviderIs("gce", "gke")
ginkgo.By(fmt.Sprintf("Restoring initial size of the cluster"))
setMigSizes(originalSizes)
expectedNodes := 0
for _, size := range originalSizes {
expectedNodes += size
}
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, expectedNodes, scaleDownTimeout))
nodes, err := c.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
framework.ExpectNoError(err)
s := time.Now()
makeSchedulableLoop:
for start := time.Now(); time.Since(start) < makeSchedulableTimeout; time.Sleep(makeSchedulableDelay) {
for _, n := range nodes.Items {
err = makeNodeSchedulable(c, &n, true)
switch err.(type) {
case CriticalAddonsOnlyError:
continue makeSchedulableLoop
default:
framework.ExpectNoError(err)
}
}
break
}
klog.Infof("Made nodes schedulable again in %v", time.Since(s).String())
})
ginkgo.It("shouldn't increase cluster size if pending pod is too large [Feature:ClusterSizeAutoscalingScaleUp]", func() {
ginkgo.By("Creating unschedulable pod")
ReserveMemory(f, "memory-reservation", 1, int(1.1*float64(memAllocatableMb)), false, defaultTimeout)
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
ginkgo.By("Waiting for scale up hoping it won't happen")
// Verify that the appropriate event was generated
eventFound := false
EventsLoop:
for start := time.Now(); time.Since(start) < scaleUpTimeout; time.Sleep(20 * time.Second) {
ginkgo.By("Waiting for NotTriggerScaleUp event")
events, err := f.ClientSet.CoreV1().Events(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{})
framework.ExpectNoError(err)
for _, e := range events.Items {
if e.InvolvedObject.Kind == "Pod" && e.Reason == "NotTriggerScaleUp" {
ginkgo.By("NotTriggerScaleUp event found")
eventFound = true
break EventsLoop
}
}
}
framework.ExpectEqual(eventFound, true)
// Verify that cluster size is not changed
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size <= nodeCount }, time.Second))
})
simpleScaleUpTest := func(unready int) {
ReserveMemory(f, "memory-reservation", 100, nodeCount*memAllocatableMb, false, 1*time.Second)
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
// Verify that cluster size is increased
framework.ExpectNoError(WaitForClusterSizeFuncWithUnready(f.ClientSet,
func(size int) bool { return size >= nodeCount+1 }, scaleUpTimeout, unready))
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
}
ginkgo.It("should increase cluster size if pending pods are small [Feature:ClusterSizeAutoscalingScaleUp]",
func() { simpleScaleUpTest(0) })
gpuType := os.Getenv("TESTED_GPU_TYPE")
ginkgo.It(fmt.Sprintf("Should scale up GPU pool from 0 [GpuType:%s] [Feature:ClusterSizeAutoscalingGpu]", gpuType), func() {
e2eskipper.SkipUnlessProviderIs("gke")
if gpuType == "" {
framework.Failf("TEST_GPU_TYPE not defined")
return
}
const gpuPoolName = "gpu-pool"
addGpuNodePool(gpuPoolName, gpuType, 1, 0)
defer deleteNodePool(gpuPoolName)
installNvidiaDriversDaemonSet(f)
ginkgo.By("Enable autoscaler")
framework.ExpectNoError(enableAutoscaler(gpuPoolName, 0, 1))
defer disableAutoscaler(gpuPoolName, 0, 1)
framework.ExpectEqual(len(getPoolNodes(f, gpuPoolName)), 0)
ginkgo.By("Schedule a pod which requires GPU")
framework.ExpectNoError(ScheduleAnySingleGpuPod(f, "gpu-pod-rc"))
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "gpu-pod-rc")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == nodeCount+1 }, scaleUpTimeout))
framework.ExpectEqual(len(getPoolNodes(f, gpuPoolName)), 1)
})
ginkgo.It(fmt.Sprintf("Should scale up GPU pool from 1 [GpuType:%s] [Feature:ClusterSizeAutoscalingGpu]", gpuType), func() {
e2eskipper.SkipUnlessProviderIs("gke")
if gpuType == "" {
framework.Failf("TEST_GPU_TYPE not defined")
return
}
const gpuPoolName = "gpu-pool"
addGpuNodePool(gpuPoolName, gpuType, 1, 1)
defer deleteNodePool(gpuPoolName)
installNvidiaDriversDaemonSet(f)
ginkgo.By("Schedule a single pod which requires GPU")
framework.ExpectNoError(ScheduleAnySingleGpuPod(f, "gpu-pod-rc"))
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "gpu-pod-rc")
ginkgo.By("Enable autoscaler")
framework.ExpectNoError(enableAutoscaler(gpuPoolName, 0, 2))
defer disableAutoscaler(gpuPoolName, 0, 2)
framework.ExpectEqual(len(getPoolNodes(f, gpuPoolName)), 1)
ginkgo.By("Scale GPU deployment")
e2erc.ScaleRC(f.ClientSet, f.ScalesGetter, f.Namespace.Name, "gpu-pod-rc", 2, true)
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == nodeCount+2 }, scaleUpTimeout))
framework.ExpectEqual(len(getPoolNodes(f, gpuPoolName)), 2)
})
ginkgo.It(fmt.Sprintf("Should not scale GPU pool up if pod does not require GPUs [GpuType:%s] [Feature:ClusterSizeAutoscalingGpu]", gpuType), func() {
e2eskipper.SkipUnlessProviderIs("gke")
if gpuType == "" {
framework.Failf("TEST_GPU_TYPE not defined")
return
}
const gpuPoolName = "gpu-pool"
addGpuNodePool(gpuPoolName, gpuType, 1, 0)
defer deleteNodePool(gpuPoolName)
installNvidiaDriversDaemonSet(f)
ginkgo.By("Enable autoscaler")
framework.ExpectNoError(enableAutoscaler(gpuPoolName, 0, 1))
defer disableAutoscaler(gpuPoolName, 0, 1)
framework.ExpectEqual(len(getPoolNodes(f, gpuPoolName)), 0)
ginkgo.By("Schedule bunch of pods beyond point of filling default pool but do not request any GPUs")
ReserveMemory(f, "memory-reservation", 100, nodeCount*memAllocatableMb, false, 1*time.Second)
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
// Verify that cluster size is increased
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size >= nodeCount+1 }, scaleUpTimeout))
// Expect gpu pool to stay intact
framework.ExpectEqual(len(getPoolNodes(f, gpuPoolName)), 0)
})
ginkgo.It(fmt.Sprintf("Should scale down GPU pool from 1 [GpuType:%s] [Feature:ClusterSizeAutoscalingGpu]", gpuType), func() {
e2eskipper.SkipUnlessProviderIs("gke")
if gpuType == "" {
framework.Failf("TEST_GPU_TYPE not defined")
return
}
const gpuPoolName = "gpu-pool"
addGpuNodePool(gpuPoolName, gpuType, 1, 1)
defer deleteNodePool(gpuPoolName)
installNvidiaDriversDaemonSet(f)
ginkgo.By("Schedule a single pod which requires GPU")
framework.ExpectNoError(ScheduleAnySingleGpuPod(f, "gpu-pod-rc"))
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "gpu-pod-rc")
ginkgo.By("Enable autoscaler")
framework.ExpectNoError(enableAutoscaler(gpuPoolName, 0, 1))
defer disableAutoscaler(gpuPoolName, 0, 1)
framework.ExpectEqual(len(getPoolNodes(f, gpuPoolName)), 1)
ginkgo.By("Remove the only POD requiring GPU")
e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "gpu-pod-rc")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == nodeCount }, scaleDownTimeout))
framework.ExpectEqual(len(getPoolNodes(f, gpuPoolName)), 0)
})
ginkgo.It("should increase cluster size if pending pods are small and one node is broken [Feature:ClusterSizeAutoscalingScaleUp]",
func() {
e2enetwork.TestUnderTemporaryNetworkFailure(c, "default", getAnyNode(c), func() { simpleScaleUpTest(1) })
})
ginkgo.It("shouldn't trigger additional scale-ups during processing scale-up [Feature:ClusterSizeAutoscalingScaleUp]", func() {
// Wait for the situation to stabilize - CA should be running and have up-to-date node readiness info.
status, err := waitForScaleUpStatus(c, func(s *scaleUpStatus) bool {
return s.ready == s.target && s.ready <= nodeCount
}, scaleUpTriggerTimeout)
framework.ExpectNoError(err)
unmanagedNodes := nodeCount - status.ready
ginkgo.By("Schedule more pods than can fit and wait for cluster to scale-up")
ReserveMemory(f, "memory-reservation", 100, nodeCount*memAllocatableMb, false, 1*time.Second)
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
status, err = waitForScaleUpStatus(c, func(s *scaleUpStatus) bool {
return s.status == caOngoingScaleUpStatus
}, scaleUpTriggerTimeout)
framework.ExpectNoError(err)
target := status.target
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
ginkgo.By("Expect no more scale-up to be happening after all pods are scheduled")
// wait for a while until scale-up finishes; we cannot read CA status immediately
// after pods are scheduled as status config map is updated by CA once every loop iteration
status, err = waitForScaleUpStatus(c, func(s *scaleUpStatus) bool {
return s.status == caNoScaleUpStatus
}, 2*freshStatusLimit)
framework.ExpectNoError(err)
if status.target != target {
klog.Warningf("Final number of nodes (%v) does not match initial scale-up target (%v).", status.target, target)
}
framework.ExpectEqual(status.timestamp.Add(freshStatusLimit).Before(time.Now()), false)
framework.ExpectEqual(status.status, caNoScaleUpStatus)
framework.ExpectEqual(status.ready, status.target)
nodes, err := e2enode.GetReadySchedulableNodes(f.ClientSet)
framework.ExpectNoError(err)
framework.ExpectEqual(len(nodes.Items), status.target+unmanagedNodes)
})
ginkgo.It("should increase cluster size if pending pods are small and there is another node pool that is not autoscaled [Feature:ClusterSizeAutoscalingScaleUp]", func() {
e2eskipper.SkipUnlessProviderIs("gke")
ginkgo.By("Creating new node-pool with n1-standard-4 machines")
const extraPoolName = "extra-pool"
addNodePool(extraPoolName, "n1-standard-4", 1)
defer deleteNodePool(extraPoolName)
extraNodes := getPoolInitialSize(extraPoolName)
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+extraNodes, resizeTimeout))
// We wait for nodes to become schedulable to make sure the new nodes
// will be returned by getPoolNodes below.
framework.ExpectNoError(framework.WaitForAllNodesSchedulable(c, resizeTimeout))
klog.Infof("Not enabling cluster autoscaler for the node pool (on purpose).")
ginkgo.By("Getting memory available on new nodes, so we can account for it when creating RC")
nodes := getPoolNodes(f, extraPoolName)
framework.ExpectEqual(len(nodes), extraNodes)
extraMemMb := 0
for _, node := range nodes {
mem := node.Status.Allocatable[v1.ResourceMemory]
extraMemMb += int((&mem).Value() / 1024 / 1024)
}
ginkgo.By("Reserving 0.1x more memory than the cluster holds to trigger scale up")
totalMemoryReservation := int(1.1 * float64(nodeCount*memAllocatableMb+extraMemMb))
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
ReserveMemory(f, "memory-reservation", 100, totalMemoryReservation, false, defaultTimeout)
// Verify, that cluster size is increased
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size >= nodeCount+extraNodes+1 }, scaleUpTimeout))
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
})
ginkgo.It("should disable node pool autoscaling [Feature:ClusterSizeAutoscalingScaleUp]", func() {
e2eskipper.SkipUnlessProviderIs("gke")
ginkgo.By("Creating new node-pool with n1-standard-4 machines")
const extraPoolName = "extra-pool"
addNodePool(extraPoolName, "n1-standard-4", 1)
defer deleteNodePool(extraPoolName)
extraNodes := getPoolInitialSize(extraPoolName)
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+extraNodes, resizeTimeout))
framework.ExpectNoError(enableAutoscaler(extraPoolName, 1, 2))
framework.ExpectNoError(disableAutoscaler(extraPoolName, 1, 2))
})
ginkgo.It("should increase cluster size if pods are pending due to host port conflict [Feature:ClusterSizeAutoscalingScaleUp]", func() {
scheduling.CreateHostPortPods(f, "host-port", nodeCount+2, false)
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "host-port")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size >= nodeCount+2 }, scaleUpTimeout))
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
})
ginkgo.It("should increase cluster size if pods are pending due to pod anti-affinity [Feature:ClusterSizeAutoscalingScaleUp]", func() {
pods := nodeCount
newPods := 2
labels := map[string]string{
"anti-affinity": "yes",
}
ginkgo.By("starting a pod with anti-affinity on each node")
framework.ExpectNoError(runAntiAffinityPods(f, f.Namespace.Name, pods, "some-pod", labels, labels))
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "some-pod")
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
ginkgo.By("scheduling extra pods with anti-affinity to existing ones")
framework.ExpectNoError(runAntiAffinityPods(f, f.Namespace.Name, newPods, "extra-pod", labels, labels))
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "extra-pod")
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+newPods, scaleUpTimeout))
})
ginkgo.It("should increase cluster size if pod requesting EmptyDir volume is pending [Feature:ClusterSizeAutoscalingScaleUp]", func() {
ginkgo.By("creating pods")
pods := nodeCount
newPods := 1
labels := map[string]string{
"anti-affinity": "yes",
}
framework.ExpectNoError(runAntiAffinityPods(f, f.Namespace.Name, pods, "some-pod", labels, labels))
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "some-pod")
ginkgo.By("waiting for all pods before triggering scale up")
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
ginkgo.By("creating a pod requesting EmptyDir")
framework.ExpectNoError(runVolumeAntiAffinityPods(f, f.Namespace.Name, newPods, "extra-pod", labels, labels, emptyDirVolumes))
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "extra-pod")
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+newPods, scaleUpTimeout))
})
ginkgo.It("should increase cluster size if pod requesting volume is pending [Feature:ClusterSizeAutoscalingScaleUp]", func() {
e2eskipper.SkipUnlessProviderIs("gce", "gke")
volumeLabels := labels.Set{
e2epv.VolumeSelectorKey: f.Namespace.Name,
}
selector := metav1.SetAsLabelSelector(volumeLabels)
ginkgo.By("creating volume & pvc")
diskName, err := e2epv.CreatePDWithRetry()
framework.ExpectNoError(err)
pvConfig := e2epv.PersistentVolumeConfig{
NamePrefix: "gce-",
Labels: volumeLabels,
PVSource: v1.PersistentVolumeSource{
GCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{
PDName: diskName,
FSType: "ext3",
ReadOnly: false,
},
},
Prebind: nil,
}
emptyStorageClass := ""
pvcConfig := e2epv.PersistentVolumeClaimConfig{
Selector: selector,
StorageClassName: &emptyStorageClass,
}
pv, pvc, err := e2epv.CreatePVPVC(c, pvConfig, pvcConfig, f.Namespace.Name, false)
framework.ExpectNoError(err)
framework.ExpectNoError(e2epv.WaitOnPVandPVC(c, f.Timeouts, f.Namespace.Name, pv, pvc))
defer func() {
errs := e2epv.PVPVCCleanup(c, f.Namespace.Name, pv, pvc)
if len(errs) > 0 {
framework.Failf("failed to delete PVC and/or PV. Errors: %v", utilerrors.NewAggregate(errs))
}
pv, pvc = nil, nil
if diskName != "" {
framework.ExpectNoError(e2epv.DeletePDWithRetry(diskName))
}
}()
ginkgo.By("creating pods")
pods := nodeCount
labels := map[string]string{
"anti-affinity": "yes",
}
framework.ExpectNoError(runAntiAffinityPods(f, f.Namespace.Name, pods, "some-pod", labels, labels))
defer func() {
e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "some-pod")
klog.Infof("RC and pods not using volume deleted")
}()
ginkgo.By("waiting for all pods before triggering scale up")
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
ginkgo.By("creating a pod requesting PVC")
pvcPodName := "pvc-pod"
newPods := 1
volumes := buildVolumes(pv, pvc)
framework.ExpectNoError(runVolumeAntiAffinityPods(f, f.Namespace.Name, newPods, pvcPodName, labels, labels, volumes))
defer func() {
e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, pvcPodName)
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
}()
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+newPods, scaleUpTimeout))
})
ginkgo.It("should add node to the particular mig [Feature:ClusterSizeAutoscalingScaleUp]", func() {
labelKey := "cluster-autoscaling-test.special-node"
labelValue := "true"
ginkgo.By("Finding the smallest MIG")
minMig := ""
minSize := nodeCount
for mig, size := range originalSizes {
if size <= minSize {
minMig = mig
minSize = size
}
}
if minSize == 0 {
newSizes := make(map[string]int)
for mig, size := range originalSizes {
newSizes[mig] = size
}
newSizes[minMig] = 1
setMigSizes(newSizes)
}
removeLabels := func(nodesToClean sets.String) {
ginkgo.By("Removing labels from nodes")
for node := range nodesToClean {
framework.RemoveLabelOffNode(c, node, labelKey)
}
}
nodes, err := framework.GetGroupNodes(minMig)
framework.ExpectNoError(err)
nodesSet := sets.NewString(nodes...)
defer removeLabels(nodesSet)
ginkgo.By(fmt.Sprintf("Annotating nodes of the smallest MIG(%s): %v", minMig, nodes))
for node := range nodesSet {
framework.AddOrUpdateLabelOnNode(c, node, labelKey, labelValue)
}
err = scheduling.CreateNodeSelectorPods(f, "node-selector", minSize+1, map[string]string{labelKey: labelValue}, false)
framework.ExpectNoError(err)
ginkgo.By("Waiting for new node to appear and annotating it")
framework.WaitForGroupSize(minMig, int32(minSize+1))
// Verify that cluster size is increased
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size >= nodeCount+1 }, scaleUpTimeout))
newNodes, err := framework.GetGroupNodes(minMig)
framework.ExpectNoError(err)
newNodesSet := sets.NewString(newNodes...)
newNodesSet.Delete(nodes...)
if len(newNodesSet) > 1 {
ginkgo.By(fmt.Sprintf("Spotted following new nodes in %s: %v", minMig, newNodesSet))
klog.Infof("Usually only 1 new node is expected, investigating")
klog.Infof("Kubectl:%s\n", framework.RunKubectlOrDie(f.Namespace.Name, "get", "nodes", "-o", "json"))
if output, err := exec.Command("gcloud", "compute", "instances", "list",
"--project="+framework.TestContext.CloudConfig.ProjectID,
"--zone="+framework.TestContext.CloudConfig.Zone).Output(); err == nil {
klog.Infof("Gcloud compute instances list: %s", output)
} else {
klog.Errorf("Failed to get instances list: %v", err)
}
for newNode := range newNodesSet {
if output, err := execCmd("gcloud", "compute", "instances", "describe",
newNode,
"--project="+framework.TestContext.CloudConfig.ProjectID,
"--zone="+framework.TestContext.CloudConfig.Zone).Output(); err == nil {
klog.Infof("Gcloud compute instances describe: %s", output)
} else {
klog.Errorf("Failed to get instances describe: %v", err)
}
}
// TODO: possibly remove broken node from newNodesSet to prevent removeLabel from crashing.
// However at this moment we DO WANT it to crash so that we don't check all test runs for the
// rare behavior, but only the broken ones.
}
ginkgo.By(fmt.Sprintf("New nodes: %v\n", newNodesSet))
registeredNodes := sets.NewString()
for nodeName := range newNodesSet {
node, err := f.ClientSet.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})
if err == nil && node != nil {
registeredNodes.Insert(nodeName)
} else {
klog.Errorf("Failed to get node %v: %v", nodeName, err)
}
}
ginkgo.By(fmt.Sprintf("Setting labels for registered new nodes: %v", registeredNodes.List()))
for node := range registeredNodes {
framework.AddOrUpdateLabelOnNode(c, node, labelKey, labelValue)
}
defer removeLabels(registeredNodes)
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
framework.ExpectNoError(e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "node-selector"))
})
ginkgo.It("should scale up correct target pool [Feature:ClusterSizeAutoscalingScaleUp]", func() {
e2eskipper.SkipUnlessProviderIs("gke")
ginkgo.By("Creating new node-pool with n1-standard-4 machines")
const extraPoolName = "extra-pool"
addNodePool(extraPoolName, "n1-standard-4", 1)
defer deleteNodePool(extraPoolName)
extraNodes := getPoolInitialSize(extraPoolName)
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+extraNodes, resizeTimeout))
framework.ExpectNoError(enableAutoscaler(extraPoolName, 1, 2))
defer disableAutoscaler(extraPoolName, 1, 2)
extraPods := extraNodes + 1
totalMemoryReservation := int(float64(extraPods) * 1.5 * float64(memAllocatableMb))
ginkgo.By(fmt.Sprintf("Creating rc with %v pods too big to fit default-pool but fitting extra-pool", extraPods))
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
ReserveMemory(f, "memory-reservation", extraPods, totalMemoryReservation, false, defaultTimeout)
// Apparently GKE master is restarted couple minutes after the node pool is added
// resetting all the timers in scale down code. Adding 5 extra minutes to workaround
// this issue.
// TODO: Remove the extra time when GKE restart is fixed.
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+extraNodes+1, scaleUpTimeout+5*time.Minute))
})
simpleScaleDownTest := func(unready int) {
cleanup, err := addKubeSystemPdbs(f)
defer cleanup()
framework.ExpectNoError(err)
ginkgo.By("Manually increase cluster size")
increasedSize := 0
newSizes := make(map[string]int)
for key, val := range originalSizes {
newSizes[key] = val + 2 + unready
increasedSize += val + 2 + unready
}
setMigSizes(newSizes)
framework.ExpectNoError(WaitForClusterSizeFuncWithUnready(f.ClientSet,
func(size int) bool { return size >= increasedSize }, manualResizeTimeout, unready))
ginkgo.By("Some node should be removed")
framework.ExpectNoError(WaitForClusterSizeFuncWithUnready(f.ClientSet,
func(size int) bool { return size < increasedSize }, scaleDownTimeout, unready))
}
ginkgo.It("should correctly scale down after a node is not needed [Feature:ClusterSizeAutoscalingScaleDown]",
func() { simpleScaleDownTest(0) })
ginkgo.It("should correctly scale down after a node is not needed and one node is broken [Feature:ClusterSizeAutoscalingScaleDown]",
func() {
e2eskipper.SkipUnlessSSHKeyPresent()
e2enetwork.TestUnderTemporaryNetworkFailure(c, "default", getAnyNode(c), func() { simpleScaleDownTest(1) })
})
ginkgo.It("should correctly scale down after a node is not needed when there is non autoscaled pool[Feature:ClusterSizeAutoscalingScaleDown]", func() {
e2eskipper.SkipUnlessProviderIs("gke")
increasedSize := manuallyIncreaseClusterSize(f, originalSizes)
const extraPoolName = "extra-pool"
addNodePool(extraPoolName, "n1-standard-1", 3)
defer deleteNodePool(extraPoolName)
extraNodes := getPoolInitialSize(extraPoolName)
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size >= increasedSize+extraNodes }, scaleUpTimeout))
ginkgo.By("Some node should be removed")
// Apparently GKE master is restarted couple minutes after the node pool is added
// resetting all the timers in scale down code. Adding 10 extra minutes to workaround
// this issue.
// TODO: Remove the extra time when GKE restart is fixed.
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size < increasedSize+extraNodes }, scaleDownTimeout+10*time.Minute))
})
ginkgo.It("should be able to scale down when rescheduling a pod is required and pdb allows for it[Feature:ClusterSizeAutoscalingScaleDown]", func() {
runDrainTest(f, originalSizes, f.Namespace.Name, 1, 1, func(increasedSize int) {
ginkgo.By("Some node should be removed")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size < increasedSize }, scaleDownTimeout))
})
})
ginkgo.It("shouldn't be able to scale down when rescheduling a pod is required, but pdb doesn't allow drain[Feature:ClusterSizeAutoscalingScaleDown]", func() {
runDrainTest(f, originalSizes, f.Namespace.Name, 1, 0, func(increasedSize int) {
ginkgo.By("No nodes should be removed")
time.Sleep(scaleDownTimeout)
nodes, err := e2enode.GetReadySchedulableNodes(f.ClientSet)
framework.ExpectNoError(err)
framework.ExpectEqual(len(nodes.Items), increasedSize)
})
})
ginkgo.It("should be able to scale down by draining multiple pods one by one as dictated by pdb[Feature:ClusterSizeAutoscalingScaleDown]", func() {
runDrainTest(f, originalSizes, f.Namespace.Name, 2, 1, func(increasedSize int) {
ginkgo.By("Some node should be removed")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size < increasedSize }, scaleDownTimeout))
})
})
ginkgo.It("should be able to scale down by draining system pods with pdb[Feature:ClusterSizeAutoscalingScaleDown]", func() {
runDrainTest(f, originalSizes, "kube-system", 2, 1, func(increasedSize int) {
ginkgo.By("Some node should be removed")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size < increasedSize }, scaleDownTimeout))
})
})
ginkgo.It("Should be able to scale a node group up from 0[Feature:ClusterSizeAutoscalingScaleUp]", func() {
// Provider-specific setup
if framework.ProviderIs("gke") {
// GKE-specific setup
ginkgo.By("Add a new node pool with 0 nodes and min size 0")
const extraPoolName = "extra-pool"
addNodePool(extraPoolName, "n1-standard-4", 0)
defer deleteNodePool(extraPoolName)
framework.ExpectNoError(enableAutoscaler(extraPoolName, 0, 1))
defer disableAutoscaler(extraPoolName, 0, 1)
} else {
// on GCE, run only if there are already at least 2 node groups
e2eskipper.SkipUnlessAtLeast(len(originalSizes), 2, "At least 2 node groups are needed for scale-to-0 tests")
ginkgo.By("Manually scale smallest node group to 0")
minMig := ""
minSize := nodeCount
for mig, size := range originalSizes {
if size <= minSize {
minMig = mig
minSize = size
}
}
framework.ExpectNoError(framework.ResizeGroup(minMig, int32(0)))
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount-minSize, resizeTimeout))
}
ginkgo.By("Make remaining nodes unschedulable")
nodes, err := f.ClientSet.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{FieldSelector: fields.Set{
"spec.unschedulable": "false",
}.AsSelector().String()})
framework.ExpectNoError(err)
for _, node := range nodes.Items {
err = makeNodeUnschedulable(f.ClientSet, &node)
defer func(n v1.Node) {
makeNodeSchedulable(f.ClientSet, &n, false)
}(node)
framework.ExpectNoError(err)
}
ginkgo.By("Run a scale-up test")
ReserveMemory(f, "memory-reservation", 1, 100, false, 1*time.Second)
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
// Verify that cluster size is increased
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size >= len(nodes.Items)+1 }, scaleUpTimeout))
framework.ExpectNoError(waitForAllCaPodsReadyInNamespace(f, c))
})
// Scale to 0 test is split into two functions (for GKE & GCE.)
// The reason for it is that scenario is exactly the same,
// but setup & verification use different APIs.
//
// Scenario:
// (GKE only) add an extra node pool with size 1 & enable autoscaling for it
// (GCE only) find the smallest MIG & resize it to 1
// manually drain the single node from this node pool/MIG
// wait for cluster size to decrease
// verify the targeted node pool/MIG is of size 0
gkeScaleToZero := func() {
// GKE-specific setup
ginkgo.By("Add a new node pool with size 1 and min size 0")
const extraPoolName = "extra-pool"
addNodePool(extraPoolName, "n1-standard-4", 1)
defer deleteNodePool(extraPoolName)
extraNodes := getPoolInitialSize(extraPoolName)
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount+extraNodes, resizeTimeout))
framework.ExpectNoError(enableAutoscaler(extraPoolName, 0, 1))
defer disableAutoscaler(extraPoolName, 0, 1)
ngNodes := getPoolNodes(f, extraPoolName)
framework.ExpectEqual(len(ngNodes), extraNodes)
for _, node := range ngNodes {
ginkgo.By(fmt.Sprintf("Target node for scale-down: %s", node.Name))
}
for _, node := range ngNodes {
drainNode(f, node)
}
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size <= nodeCount }, scaleDownTimeout))
// GKE-specific check
newSize := getPoolSize(f, extraPoolName)
framework.ExpectEqual(newSize, 0)
}
gceScaleToZero := func() {
// non-GKE only
ginkgo.By("Find smallest node group and manually scale it to a single node")
minMig := ""
minSize := nodeCount
for mig, size := range originalSizes {
if size <= minSize {
minMig = mig
minSize = size
}
}
framework.ExpectNoError(framework.ResizeGroup(minMig, int32(1)))
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, nodeCount-minSize+1, resizeTimeout))
ngNodes, err := framework.GetGroupNodes(minMig)
framework.ExpectNoError(err)
framework.ExpectEqual(len(ngNodes) == 1, true)
node, err := f.ClientSet.CoreV1().Nodes().Get(context.TODO(), ngNodes[0], metav1.GetOptions{})
ginkgo.By(fmt.Sprintf("Target node for scale-down: %s", node.Name))
framework.ExpectNoError(err)
// this part is identical
drainNode(f, node)
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size < nodeCount-minSize+1 }, scaleDownTimeout))
// non-GKE only
newSize, err := framework.GroupSize(minMig)
framework.ExpectNoError(err)
framework.ExpectEqual(newSize, 0)
}
ginkgo.It("Should be able to scale a node group down to 0[Feature:ClusterSizeAutoscalingScaleDown]", func() {
if framework.ProviderIs("gke") { // In GKE, we can just add a node pool
gkeScaleToZero()
} else if len(originalSizes) >= 2 {
gceScaleToZero()
} else {
e2eskipper.Skipf("At least 2 node groups are needed for scale-to-0 tests")
}
})
ginkgo.It("Shouldn't perform scale up operation and should list unhealthy status if most of the cluster is broken[Feature:ClusterSizeAutoscalingScaleUp]", func() {
e2eskipper.SkipUnlessSSHKeyPresent()
clusterSize := nodeCount
for clusterSize < unhealthyClusterThreshold+1 {
clusterSize = manuallyIncreaseClusterSize(f, originalSizes)
}
// If new nodes are disconnected too soon, they'll be considered not started
// instead of unready, and cluster won't be considered unhealthy.
//
// More precisely, Cluster Autoscaler compares last transition time of
// several readiness conditions to node create time. If it's within
// 2 minutes, it'll assume node is just starting and not unhealthy.
//
// Nodes become ready in less than 1 minute after being created,
// so waiting extra 2 minutes before breaking them (which triggers
// readiness condition transition) should be sufficient, while
// making no assumptions about minimal node startup time.
time.Sleep(2 * time.Minute)
ginkgo.By("Block network connectivity to some nodes to simulate unhealthy cluster")
nodesToBreakCount := int(math.Ceil(math.Max(float64(unhealthyClusterThreshold), 0.5*float64(clusterSize))))
nodes, err := f.ClientSet.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{FieldSelector: fields.Set{
"spec.unschedulable": "false",
}.AsSelector().String()})
framework.ExpectNoError(err)
framework.ExpectEqual(nodesToBreakCount <= len(nodes.Items), true)
nodesToBreak := nodes.Items[:nodesToBreakCount]
// TestUnderTemporaryNetworkFailure only removes connectivity to a single node,
// and accepts func() callback. This is expanding the loop to recursive call
// to avoid duplicating TestUnderTemporaryNetworkFailure
var testFunction func()
testFunction = func() {
if len(nodesToBreak) > 0 {
ntb := &nodesToBreak[0]
nodesToBreak = nodesToBreak[1:]
e2enetwork.TestUnderTemporaryNetworkFailure(c, "default", ntb, testFunction)
} else {
ReserveMemory(f, "memory-reservation", 100, nodeCount*memAllocatableMb, false, defaultTimeout)
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, "memory-reservation")
time.Sleep(scaleUpTimeout)
currentNodes, err := e2enode.GetReadySchedulableNodes(f.ClientSet)
framework.ExpectNoError(err)
framework.Logf("Currently available nodes: %v, nodes available at the start of test: %v, disabled nodes: %v", len(currentNodes.Items), len(nodes.Items), nodesToBreakCount)
framework.ExpectEqual(len(currentNodes.Items), len(nodes.Items)-nodesToBreakCount)
status, err := getClusterwideStatus(c)
framework.Logf("Clusterwide status: %v", status)
framework.ExpectNoError(err)
framework.ExpectEqual(status, "Unhealthy")
}
}
testFunction()
// Give nodes time to recover from network failure
framework.ExpectNoError(e2enode.WaitForReadyNodes(c, len(nodes.Items), nodesRecoverTimeout))
})
ginkgo.It("shouldn't scale up when expendable pod is created [Feature:ClusterSizeAutoscalingScaleUp]", func() {
defer createPriorityClasses(f)()
// Create nodesCountAfterResize+1 pods allocating 0.7 allocatable on present nodes. One more node will have to be created.
cleanupFunc := ReserveMemoryWithPriority(f, "memory-reservation", nodeCount+1, int(float64(nodeCount+1)*float64(0.7)*float64(memAllocatableMb)), false, time.Second, expendablePriorityClassName)
defer cleanupFunc()
ginkgo.By(fmt.Sprintf("Waiting for scale up hoping it won't happen, sleep for %s", scaleUpTimeout.String()))
time.Sleep(scaleUpTimeout)
// Verify that cluster size is not changed
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == nodeCount }, time.Second))
})
ginkgo.It("should scale up when non expendable pod is created [Feature:ClusterSizeAutoscalingScaleUp]", func() {
defer createPriorityClasses(f)()
// Create nodesCountAfterResize+1 pods allocating 0.7 allocatable on present nodes. One more node will have to be created.
cleanupFunc := ReserveMemoryWithPriority(f, "memory-reservation", nodeCount+1, int(float64(nodeCount+1)*float64(0.7)*float64(memAllocatableMb)), true, scaleUpTimeout, highPriorityClassName)
defer cleanupFunc()
// Verify that cluster size is not changed
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size > nodeCount }, time.Second))
})
ginkgo.It("shouldn't scale up when expendable pod is preempted [Feature:ClusterSizeAutoscalingScaleUp]", func() {
defer createPriorityClasses(f)()
// Create nodesCountAfterResize pods allocating 0.7 allocatable on present nodes - one pod per node.
cleanupFunc1 := ReserveMemoryWithPriority(f, "memory-reservation1", nodeCount, int(float64(nodeCount)*float64(0.7)*float64(memAllocatableMb)), true, defaultTimeout, expendablePriorityClassName)
defer cleanupFunc1()
// Create nodesCountAfterResize pods allocating 0.7 allocatable on present nodes - one pod per node. Pods created here should preempt pods created above.
cleanupFunc2 := ReserveMemoryWithPriority(f, "memory-reservation2", nodeCount, int(float64(nodeCount)*float64(0.7)*float64(memAllocatableMb)), true, defaultTimeout, highPriorityClassName)
defer cleanupFunc2()
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == nodeCount }, time.Second))
})
ginkgo.It("should scale down when expendable pod is running [Feature:ClusterSizeAutoscalingScaleDown]", func() {
defer createPriorityClasses(f)()
increasedSize := manuallyIncreaseClusterSize(f, originalSizes)
// Create increasedSize pods allocating 0.7 allocatable on present nodes - one pod per node.
cleanupFunc := ReserveMemoryWithPriority(f, "memory-reservation", increasedSize, int(float64(increasedSize)*float64(0.7)*float64(memAllocatableMb)), true, scaleUpTimeout, expendablePriorityClassName)
defer cleanupFunc()
ginkgo.By("Waiting for scale down")
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == nodeCount }, scaleDownTimeout))
})
ginkgo.It("shouldn't scale down when non expendable pod is running [Feature:ClusterSizeAutoscalingScaleDown]", func() {
defer createPriorityClasses(f)()
increasedSize := manuallyIncreaseClusterSize(f, originalSizes)
// Create increasedSize pods allocating 0.7 allocatable on present nodes - one pod per node.
cleanupFunc := ReserveMemoryWithPriority(f, "memory-reservation", increasedSize, int(float64(increasedSize)*float64(0.7)*float64(memAllocatableMb)), true, scaleUpTimeout, highPriorityClassName)
defer cleanupFunc()
ginkgo.By(fmt.Sprintf("Waiting for scale down hoping it won't happen, sleep for %s", scaleDownTimeout.String()))
time.Sleep(scaleDownTimeout)
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet,
func(size int) bool { return size == increasedSize }, time.Second))
})
})
func installNvidiaDriversDaemonSet(f *framework.Framework) {
ginkgo.By("Add daemonset which installs nvidia drivers")
dsYamlURL := "https://raw.githubusercontent.com/GoogleCloudPlatform/container-engine-accelerators/master/daemonset.yaml"
framework.Logf("Using %v", dsYamlURL)
// Creates the DaemonSet that installs Nvidia Drivers.
ds, err := e2emanifest.DaemonSetFromURL(dsYamlURL)
framework.ExpectNoError(err)
ds.Namespace = f.Namespace.Name
_, err = f.ClientSet.AppsV1().DaemonSets(f.Namespace.Name).Create(context.TODO(), ds, metav1.CreateOptions{})
framework.ExpectNoError(err, "failed to create nvidia-driver-installer daemonset")
}
func execCmd(args ...string) *exec.Cmd {
klog.Infof("Executing: %s", strings.Join(args, " "))
return exec.Command(args[0], args[1:]...)
}
func runDrainTest(f *framework.Framework, migSizes map[string]int, namespace string, podsPerNode, pdbSize int, verifyFunction func(int)) {
increasedSize := manuallyIncreaseClusterSize(f, migSizes)
nodes, err := f.ClientSet.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{FieldSelector: fields.Set{
"spec.unschedulable": "false",
}.AsSelector().String()})
framework.ExpectNoError(err)
numPods := len(nodes.Items) * podsPerNode
testID := string(uuid.NewUUID()) // So that we can label and find pods
labelMap := map[string]string{"test_id": testID}
framework.ExpectNoError(runReplicatedPodOnEachNode(f, nodes.Items, namespace, podsPerNode, "reschedulable-pods", labelMap, 0))
defer e2erc.DeleteRCAndWaitForGC(f.ClientSet, namespace, "reschedulable-pods")
ginkgo.By("Create a PodDisruptionBudget")
minAvailable := intstr.FromInt(numPods - pdbSize)
pdb := &policyv1.PodDisruptionBudget{
ObjectMeta: metav1.ObjectMeta{
Name: "test_pdb",
Namespace: namespace,
},
Spec: policyv1.PodDisruptionBudgetSpec{
Selector: &metav1.LabelSelector{MatchLabels: labelMap},
MinAvailable: &minAvailable,
},
}
_, err = f.ClientSet.PolicyV1().PodDisruptionBudgets(namespace).Create(context.TODO(), pdb, metav1.CreateOptions{})
defer func() {
f.ClientSet.PolicyV1().PodDisruptionBudgets(namespace).Delete(context.TODO(), pdb.Name, metav1.DeleteOptions{})
}()
framework.ExpectNoError(err)
verifyFunction(increasedSize)
}
func getGkeAPIEndpoint() string {
gkeAPIEndpoint := os.Getenv("CLOUDSDK_API_ENDPOINT_OVERRIDES_CONTAINER")
if gkeAPIEndpoint == "" {
gkeAPIEndpoint = "https://test-container.sandbox.googleapis.com"
}
if strings.HasSuffix(gkeAPIEndpoint, "/") {
gkeAPIEndpoint = gkeAPIEndpoint[:len(gkeAPIEndpoint)-1]
}
return gkeAPIEndpoint
}
func getGKEURL(apiVersion string, suffix string) string {
out, err := execCmd("gcloud", "auth", "print-access-token").Output()
framework.ExpectNoError(err)
token := strings.Replace(string(out), "\n", "", -1)
return fmt.Sprintf("%s/%s/%s?access_token=%s",
getGkeAPIEndpoint(),
apiVersion,
suffix,
token)
}
func getGKEClusterURL(apiVersion string) string {
if isRegionalCluster() {
// TODO(bskiba): Use locations API for all clusters once it's graduated to v1.
return getGKEURL(apiVersion, fmt.Sprintf("projects/%s/locations/%s/clusters/%s",
framework.TestContext.CloudConfig.ProjectID,
framework.TestContext.CloudConfig.Region,
framework.TestContext.CloudConfig.Cluster))
}
return getGKEURL(apiVersion, fmt.Sprintf("projects/%s/zones/%s/clusters/%s",
framework.TestContext.CloudConfig.ProjectID,
framework.TestContext.CloudConfig.Zone,
framework.TestContext.CloudConfig.Cluster))
}
func getCluster(apiVersion string) (string, error) {
resp, err := http.Get(getGKEClusterURL(apiVersion))
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("error: %s %s", resp.Status, body)
}
return string(body), nil
}
func isAutoscalerEnabled(expectedMaxNodeCountInTargetPool int) (bool, error) {
apiVersion := "v1"
if isRegionalCluster() {
apiVersion = "v1beta1"
}
strBody, err := getCluster(apiVersion)
if err != nil {
return false, err
}
if strings.Contains(strBody, "\"maxNodeCount\": "+strconv.Itoa(expectedMaxNodeCountInTargetPool)) {
return true, nil
}
return false, nil
}
func getClusterLocation() string {
if isRegionalCluster() {
return "--region=" + framework.TestContext.CloudConfig.Region
}
return "--zone=" + framework.TestContext.CloudConfig.Zone
}
func getGcloudCommandFromTrack(commandTrack string, args []string) []string {
command := []string{"gcloud"}
if commandTrack == "beta" || commandTrack == "alpha" {
command = append(command, commandTrack)
}
command = append(command, args...)
command = append(command, getClusterLocation())
command = append(command, "--project="+framework.TestContext.CloudConfig.ProjectID)
return command
}
func getGcloudCommand(args []string) []string {
track := ""
if isRegionalCluster() {
track = "beta"
}
return getGcloudCommandFromTrack(track, args)
}
func isRegionalCluster() bool {
// TODO(bskiba): Use an appropriate indicator that the cluster is regional.
return framework.TestContext.CloudConfig.MultiZone
}
func enableAutoscaler(nodePool string, minCount, maxCount int) error {
klog.Infof("Using gcloud to enable autoscaling for pool %s", nodePool)
args := []string{"container", "clusters", "update", framework.TestContext.CloudConfig.Cluster,
"--enable-autoscaling",
"--min-nodes=" + strconv.Itoa(minCount),
"--max-nodes=" + strconv.Itoa(maxCount),
"--node-pool=" + nodePool}
output, err := execCmd(getGcloudCommand(args)...).CombinedOutput()
if err != nil {
klog.Errorf("Failed config update result: %s", output)
return fmt.Errorf("Failed to enable autoscaling: %v", err)
}
klog.Infof("Config update result: %s", output)
var finalErr error
for startTime := time.Now(); startTime.Add(gkeUpdateTimeout).After(time.Now()); time.Sleep(30 * time.Second) {
val, err := isAutoscalerEnabled(maxCount)
if err == nil && val {
return nil
}
finalErr = err
}
return fmt.Errorf("autoscaler not enabled, last error: %v", finalErr)
}
func disableAutoscaler(nodePool string, minCount, maxCount int) error {
klog.Infof("Using gcloud to disable autoscaling for pool %s", nodePool)
args := []string{"container", "clusters", "update", framework.TestContext.CloudConfig.Cluster,
"--no-enable-autoscaling",
"--node-pool=" + nodePool}
output, err := execCmd(getGcloudCommand(args)...).CombinedOutput()
if err != nil {
klog.Errorf("Failed config update result: %s", output)
return fmt.Errorf("Failed to disable autoscaling: %v", err)
}
klog.Infof("Config update result: %s", output)
var finalErr error
for startTime := time.Now(); startTime.Add(gkeUpdateTimeout).After(time.Now()); time.Sleep(30 * time.Second) {
val, err := isAutoscalerEnabled(maxCount)
if err == nil && !val {
return nil
}
finalErr = err
}
return fmt.Errorf("autoscaler still enabled, last error: %v", finalErr)
}
func addNodePool(name string, machineType string, numNodes int) {
args := []string{"container", "node-pools", "create", name, "--quiet",
"--machine-type=" + machineType,
"--num-nodes=" + strconv.Itoa(numNodes),
"--cluster=" + framework.TestContext.CloudConfig.Cluster}
output, err := execCmd(getGcloudCommand(args)...).CombinedOutput()
klog.Infof("Creating node-pool %s: %s", name, output)
framework.ExpectNoError(err, string(output))
}
func addGpuNodePool(name string, gpuType string, gpuCount int, numNodes int) {
args := []string{"beta", "container", "node-pools", "create", name, "--quiet",
"--accelerator", "type=" + gpuType + ",count=" + strconv.Itoa(gpuCount),
"--num-nodes=" + strconv.Itoa(numNodes),
"--cluster=" + framework.TestContext.CloudConfig.Cluster}
output, err := execCmd(getGcloudCommand(args)...).CombinedOutput()
klog.Infof("Creating node-pool %s: %s", name, output)
framework.ExpectNoError(err, string(output))
}
func deleteNodePool(name string) {
klog.Infof("Deleting node pool %s", name)
args := []string{"container", "node-pools", "delete", name, "--quiet",
"--cluster=" + framework.TestContext.CloudConfig.Cluster}
err := wait.ExponentialBackoff(
wait.Backoff{Duration: 1 * time.Minute, Factor: float64(3), Steps: 3},
func() (bool, error) {
output, err := execCmd(getGcloudCommand(args)...).CombinedOutput()
if err != nil {
klog.Warningf("Error deleting nodegroup - error:%v, output: %s", err, output)
return false, nil
}
klog.Infof("Node-pool deletion output: %s", output)
return true, nil
})
framework.ExpectNoError(err)
}
func getPoolNodes(f *framework.Framework, poolName string) []*v1.Node {
nodes := make([]*v1.Node, 0, 1)
nodeList, err := e2enode.GetReadyNodesIncludingTainted(f.ClientSet)
if err != nil {
framework.Logf("Unexpected error occurred: %v", err)
}
framework.ExpectNoErrorWithOffset(0, err)
for _, node := range nodeList.Items {
if node.Labels[gkeNodepoolNameKey] == poolName {
nodes = append(nodes, &node)
}
}
return nodes
}
// getPoolInitialSize returns the initial size of the node pool taking into
// account that it may span multiple zones. In that case, node pool consists of
// multiple migs all containing initialNodeCount nodes.
func getPoolInitialSize(poolName string) int {
// get initial node count
args := []string{"container", "node-pools", "describe", poolName, "--quiet",
"--cluster=" + framework.TestContext.CloudConfig.Cluster,
"--format=value(initialNodeCount)"}
output, err := execCmd(getGcloudCommand(args)...).CombinedOutput()
klog.Infof("Node-pool initial size: %s", output)
framework.ExpectNoError(err, string(output))
fields := strings.Fields(string(output))
framework.ExpectEqual(len(fields), 1)
size, err := strconv.ParseInt(fields[0], 10, 64)
framework.ExpectNoError(err)
// get number of node pools
args = []string{"container", "node-pools", "describe", poolName, "--quiet",
"--cluster=" + framework.TestContext.CloudConfig.Cluster,
"--format=value(instanceGroupUrls)"}
output, err = execCmd(getGcloudCommand(args)...).CombinedOutput()
framework.ExpectNoError(err, string(output))
nodeGroupCount := len(strings.Split(string(output), ";"))
return int(size) * nodeGroupCount
}
func getPoolSize(f *framework.Framework, poolName string) int {
size := 0
nodeList, err := e2enode.GetReadySchedulableNodes(f.ClientSet)
framework.ExpectNoError(err)
for _, node := range nodeList.Items {
if node.Labels[gkeNodepoolNameKey] == poolName {
size++
}
}
return size
}
func reserveMemory(f *framework.Framework, id string, replicas, megabytes int, expectRunning bool, timeout time.Duration, selector map[string]string, tolerations []v1.Toleration, priorityClassName string) func() error {
ginkgo.By(fmt.Sprintf("Running RC which reserves %v MB of memory", megabytes))
request := int64(1024 * 1024 * megabytes / replicas)
config := &testutils.RCConfig{
Client: f.ClientSet,
Name: id,
Namespace: f.Namespace.Name,
Timeout: timeout,
Image: imageutils.GetPauseImageName(),
Replicas: replicas,
MemRequest: request,
NodeSelector: selector,
Tolerations: tolerations,
PriorityClassName: priorityClassName,
}
for start := time.Now(); time.Since(start) < rcCreationRetryTimeout; time.Sleep(rcCreationRetryDelay) {
err := e2erc.RunRC(*config)
if err != nil && strings.Contains(err.Error(), "Error creating replication controller") {
klog.Warningf("Failed to create memory reservation: %v", err)
continue
}
if expectRunning {
framework.ExpectNoError(err)
}
return func() error {
return e2erc.DeleteRCAndWaitForGC(f.ClientSet, f.Namespace.Name, id)
}
}
framework.Failf("Failed to reserve memory within timeout")
return nil
}
// ReserveMemoryWithPriority creates a replication controller with pods with priority that, in summation,
// request the specified amount of memory.
func ReserveMemoryWithPriority(f *framework.Framework, id string, replicas, megabytes int, expectRunning bool, timeout time.Duration, priorityClassName string) func() error {
return reserveMemory(f, id, replicas, megabytes, expectRunning, timeout, nil, nil, priorityClassName)
}
// ReserveMemoryWithSelectorAndTolerations creates a replication controller with pods with node selector that, in summation,
// request the specified amount of memory.
func ReserveMemoryWithSelectorAndTolerations(f *framework.Framework, id string, replicas, megabytes int, expectRunning bool, timeout time.Duration, selector map[string]string, tolerations []v1.Toleration) func() error {
return reserveMemory(f, id, replicas, megabytes, expectRunning, timeout, selector, tolerations, "")
}
// ReserveMemory creates a replication controller with pods that, in summation,
// request the specified amount of memory.
func ReserveMemory(f *framework.Framework, id string, replicas, megabytes int, expectRunning bool, timeout time.Duration) func() error {
return reserveMemory(f, id, replicas, megabytes, expectRunning, timeout, nil, nil, "")
}
// WaitForClusterSizeFunc waits until the cluster size matches the given function.
func WaitForClusterSizeFunc(c clientset.Interface, sizeFunc func(int) bool, timeout time.Duration) error {
return WaitForClusterSizeFuncWithUnready(c, sizeFunc, timeout, 0)
}
// WaitForClusterSizeFuncWithUnready waits until the cluster size matches the given function and assumes some unready nodes.
func WaitForClusterSizeFuncWithUnready(c clientset.Interface, sizeFunc func(int) bool, timeout time.Duration, expectedUnready int) error {
for start := time.Now(); time.Since(start) < timeout; time.Sleep(20 * time.Second) {
nodes, err := c.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{FieldSelector: fields.Set{
"spec.unschedulable": "false",
}.AsSelector().String()})
if err != nil {
klog.Warningf("Failed to list nodes: %v", err)
continue
}
numNodes := len(nodes.Items)
// Filter out not-ready nodes.
e2enode.Filter(nodes, func(node v1.Node) bool {
return e2enode.IsConditionSetAsExpected(&node, v1.NodeReady, true)
})
numReady := len(nodes.Items)
if numNodes == numReady+expectedUnready && sizeFunc(numNodes) {
klog.Infof("Cluster has reached the desired size")
return nil
}
klog.Infof("Waiting for cluster with func, current size %d, not ready nodes %d", numNodes, numNodes-numReady)
}
return fmt.Errorf("timeout waiting %v for appropriate cluster size", timeout)
}
func waitForCaPodsReadyInNamespace(f *framework.Framework, c clientset.Interface, tolerateUnreadyCount int) error {
var notready []string
for start := time.Now(); time.Now().Before(start.Add(scaleUpTimeout)); time.Sleep(20 * time.Second) {
pods, err := c.CoreV1().Pods(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{})
if err != nil {
return fmt.Errorf("failed to get pods: %v", err)
}
notready = make([]string, 0)
for _, pod := range pods.Items {
ready := false
for _, c := range pod.Status.Conditions {
if c.Type == v1.PodReady && c.Status == v1.ConditionTrue {
ready = true
}
}
// Failed pods in this context generally mean that they have been
// double scheduled onto a node, but then failed a constraint check.
if pod.Status.Phase == v1.PodFailed {
klog.Warningf("Pod has failed: %v", pod)
}
if !ready && pod.Status.Phase != v1.PodFailed {
notready = append(notready, pod.Name)
}
}
if len(notready) <= tolerateUnreadyCount {
klog.Infof("sufficient number of pods ready. Tolerating %d unready", tolerateUnreadyCount)
return nil
}
klog.Infof("Too many pods are not ready yet: %v", notready)
}
klog.Info("Timeout on waiting for pods being ready")
klog.Info(framework.RunKubectlOrDie(f.Namespace.Name, "get", "pods", "-o", "json", "--all-namespaces"))
klog.Info(framework.RunKubectlOrDie(f.Namespace.Name, "get", "nodes", "-o", "json"))
// Some pods are still not running.
return fmt.Errorf("Too many pods are still not running: %v", notready)
}
func waitForAllCaPodsReadyInNamespace(f *framework.Framework, c clientset.Interface) error {
return waitForCaPodsReadyInNamespace(f, c, 0)
}
func getAnyNode(c clientset.Interface) *v1.Node {
nodes, err := c.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{FieldSelector: fields.Set{
"spec.unschedulable": "false",
}.AsSelector().String()})
if err != nil {
klog.Errorf("Failed to get node list: %v", err)
return nil
}
if len(nodes.Items) == 0 {
klog.Errorf("No nodes")
return nil
}
return &nodes.Items[0]
}
func setMigSizes(sizes map[string]int) bool {
madeChanges := false
for mig, desiredSize := range sizes {
currentSize, err := framework.GroupSize(mig)
framework.ExpectNoError(err)
if desiredSize != currentSize {
ginkgo.By(fmt.Sprintf("Setting size of %s to %d", mig, desiredSize))
err = framework.ResizeGroup(mig, int32(desiredSize))
framework.ExpectNoError(err)
madeChanges = true
}
}
return madeChanges
}
func drainNode(f *framework.Framework, node *v1.Node) {
ginkgo.By("Make the single node unschedulable")
makeNodeUnschedulable(f.ClientSet, node)
ginkgo.By("Manually drain the single node")
podOpts := metav1.ListOptions{FieldSelector: fields.OneTermEqualSelector("spec.nodeName", node.Name).String()}
pods, err := f.ClientSet.CoreV1().Pods(metav1.NamespaceAll).List(context.TODO(), podOpts)
framework.ExpectNoError(err)
for _, pod := range pods.Items {
err = f.ClientSet.CoreV1().Pods(pod.Namespace).Delete(context.TODO(), pod.Name, *metav1.NewDeleteOptions(0))
framework.ExpectNoError(err)
}
}
func makeNodeUnschedulable(c clientset.Interface, node *v1.Node) error {
ginkgo.By(fmt.Sprintf("Taint node %s", node.Name))
for j := 0; j < 3; j++ {
freshNode, err := c.CoreV1().Nodes().Get(context.TODO(), node.Name, metav1.GetOptions{})
if err != nil {
return err
}
for _, taint := range freshNode.Spec.Taints {
if taint.Key == disabledTaint {
return nil
}
}
freshNode.Spec.Taints = append(freshNode.Spec.Taints, v1.Taint{
Key: disabledTaint,
Value: "DisabledForTest",
Effect: v1.TaintEffectNoSchedule,
})
_, err = c.CoreV1().Nodes().Update(context.TODO(), freshNode, metav1.UpdateOptions{})
if err == nil {
return nil
}
if !apierrors.IsConflict(err) {
return err
}
klog.Warningf("Got 409 conflict when trying to taint node, retries left: %v", 3-j)
}
return fmt.Errorf("Failed to taint node in allowed number of retries")
}
// CriticalAddonsOnlyError implements the `error` interface, and signifies the
// presence of the `CriticalAddonsOnly` taint on the node.
type CriticalAddonsOnlyError struct{}
func (CriticalAddonsOnlyError) Error() string {
return fmt.Sprintf("CriticalAddonsOnly taint found on node")
}
func makeNodeSchedulable(c clientset.Interface, node *v1.Node, failOnCriticalAddonsOnly bool) error {
ginkgo.By(fmt.Sprintf("Remove taint from node %s", node.Name))
for j := 0; j < 3; j++ {
freshNode, err := c.CoreV1().Nodes().Get(context.TODO(), node.Name, metav1.GetOptions{})
if err != nil {
return err
}
var newTaints []v1.Taint
for _, taint := range freshNode.Spec.Taints {
if failOnCriticalAddonsOnly && taint.Key == criticalAddonsOnlyTaint {
return CriticalAddonsOnlyError{}
}
if taint.Key != disabledTaint {
newTaints = append(newTaints, taint)
}
}
if len(newTaints) == len(freshNode.Spec.Taints) {
return nil
}
freshNode.Spec.Taints = newTaints
_, err = c.CoreV1().Nodes().Update(context.TODO(), freshNode, metav1.UpdateOptions{})
if err == nil {
return nil
}
if !apierrors.IsConflict(err) {
return err
}
klog.Warningf("Got 409 conflict when trying to taint node, retries left: %v", 3-j)
}
return fmt.Errorf("Failed to remove taint from node in allowed number of retries")
}
// ScheduleAnySingleGpuPod schedules a pod which requires single GPU of any type
func ScheduleAnySingleGpuPod(f *framework.Framework, id string) error {
return ScheduleGpuPod(f, id, "", 1)
}
// ScheduleGpuPod schedules a pod which requires a given number of gpus of given type
func ScheduleGpuPod(f *framework.Framework, id string, gpuType string, gpuLimit int64) error {
config := &testutils.RCConfig{
Client: f.ClientSet,
Name: id,
Namespace: f.Namespace.Name,
Timeout: 3 * scaleUpTimeout, // spinning up GPU node is slow
Image: imageutils.GetPauseImageName(),
Replicas: 1,
GpuLimit: gpuLimit,
Labels: map[string]string{"requires-gpu": "yes"},
}
if gpuType != "" {
config.NodeSelector = map[string]string{gpuLabel: gpuType}
}
err := e2erc.RunRC(*config)
if err != nil {
return err
}
return nil
}
// Create an RC running a given number of pods with anti-affinity
func runAntiAffinityPods(f *framework.Framework, namespace string, pods int, id string, podLabels, antiAffinityLabels map[string]string) error {
config := &testutils.RCConfig{
Affinity: buildAntiAffinity(antiAffinityLabels),
Client: f.ClientSet,
Name: id,
Namespace: namespace,
Timeout: scaleUpTimeout,
Image: imageutils.GetPauseImageName(),
Replicas: pods,
Labels: podLabels,
}
err := e2erc.RunRC(*config)
if err != nil {
return err
}
_, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Get(context.TODO(), id, metav1.GetOptions{})
if err != nil {
return err
}
return nil
}
func runVolumeAntiAffinityPods(f *framework.Framework, namespace string, pods int, id string, podLabels, antiAffinityLabels map[string]string, volumes []v1.Volume) error {
config := &testutils.RCConfig{
Affinity: buildAntiAffinity(antiAffinityLabels),
Volumes: volumes,
Client: f.ClientSet,
Name: id,
Namespace: namespace,
Timeout: scaleUpTimeout,
Image: imageutils.GetPauseImageName(),
Replicas: pods,
Labels: podLabels,
}
err := e2erc.RunRC(*config)
if err != nil {
return err
}
_, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Get(context.TODO(), id, metav1.GetOptions{})
if err != nil {
return err
}
return nil
}
var emptyDirVolumes = []v1.Volume{
{
Name: "empty-volume",
VolumeSource: v1.VolumeSource{
EmptyDir: &v1.EmptyDirVolumeSource{},
},
},
}
func buildVolumes(pv *v1.PersistentVolume, pvc *v1.PersistentVolumeClaim) []v1.Volume {
return []v1.Volume{
{
Name: pv.Name,
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: pvc.Name,
ReadOnly: false,
},
},
},
}
}
func buildAntiAffinity(labels map[string]string) *v1.Affinity {
return &v1.Affinity{
PodAntiAffinity: &v1.PodAntiAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: []v1.PodAffinityTerm{
{
LabelSelector: &metav1.LabelSelector{
MatchLabels: labels,
},
TopologyKey: "kubernetes.io/hostname",
},
},
},
}
}
// Create an RC running a given number of pods on each node without adding any constraint forcing
// such pod distribution. This is meant to create a bunch of underutilized (but not unused) nodes
// with pods that can be rescheduled on different nodes.
// This is achieved using the following method:
// 1. disable scheduling on each node
// 2. create an empty RC
// 3. for each node:
// 3a. enable scheduling on that node
// 3b. increase number of replicas in RC by podsPerNode
func runReplicatedPodOnEachNode(f *framework.Framework, nodes []v1.Node, namespace string, podsPerNode int, id string, labels map[string]string, memRequest int64) error {
ginkgo.By("Run a pod on each node")
for _, node := range nodes {
err := makeNodeUnschedulable(f.ClientSet, &node)
defer func(n v1.Node) {
makeNodeSchedulable(f.ClientSet, &n, false)
}(node)
if err != nil {
return err
}
}
config := &testutils.RCConfig{
Client: f.ClientSet,
Name: id,
Namespace: namespace,
Timeout: defaultTimeout,
Image: imageutils.GetPauseImageName(),
Replicas: 0,
Labels: labels,
MemRequest: memRequest,
}
err := e2erc.RunRC(*config)
if err != nil {
return err
}
rc, err := f.ClientSet.CoreV1().ReplicationControllers(namespace).Get(context.TODO(), id, metav1.GetOptions{})
if err != nil {
return err
}
for i, node := range nodes {
err = makeNodeSchedulable(f.ClientSet, &node, false)
if err != nil {
return err
}
// Update replicas count, to create new pods that will be allocated on node
// (we retry 409 errors in case rc reference got out of sync)
for j := 0; j < 3; j++ {
*rc.Spec.Replicas = int32((i + 1) * podsPerNode)
rc, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Update(context.TODO(), rc, metav1.UpdateOptions{})
if err == nil {
break
}
if !apierrors.IsConflict(err) {
return err
}
klog.Warningf("Got 409 conflict when trying to scale RC, retries left: %v", 3-j)
rc, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Get(context.TODO(), id, metav1.GetOptions{})
if err != nil {
return err
}
}
err = wait.PollImmediate(5*time.Second, podTimeout, func() (bool, error) {
rc, err = f.ClientSet.CoreV1().ReplicationControllers(namespace).Get(context.TODO(), id, metav1.GetOptions{})
if err != nil || rc.Status.ReadyReplicas < int32((i+1)*podsPerNode) {
return false, nil
}
return true, nil
})
if err != nil {
return fmt.Errorf("failed to coerce RC into spawning a pod on node %s within timeout", node.Name)
}
err = makeNodeUnschedulable(f.ClientSet, &node)
if err != nil {
return err
}
}
return nil
}
// Increase cluster size by newNodesForScaledownTests to create some unused nodes
// that can be later removed by cluster autoscaler.
func manuallyIncreaseClusterSize(f *framework.Framework, originalSizes map[string]int) int {
ginkgo.By("Manually increase cluster size")
increasedSize := 0
newSizes := make(map[string]int)
for key, val := range originalSizes {
newSizes[key] = val + newNodesForScaledownTests
increasedSize += val + newNodesForScaledownTests
}
setMigSizes(newSizes)
checkClusterSize := func(size int) bool {
if size >= increasedSize {
return true
}
resized := setMigSizes(newSizes)
if resized {
klog.Warning("Unexpected node group size while waiting for cluster resize. Setting size to target again.")
}
return false
}
framework.ExpectNoError(WaitForClusterSizeFunc(f.ClientSet, checkClusterSize, manualResizeTimeout))
return increasedSize
}
// Try to get clusterwide health from CA status configmap.
// Status configmap is not parsing-friendly, so evil regexpery follows.
func getClusterwideStatus(c clientset.Interface) (string, error) {
configMap, err := c.CoreV1().ConfigMaps("kube-system").Get(context.TODO(), "cluster-autoscaler-status", metav1.GetOptions{})
if err != nil {
return "", err
}
status, ok := configMap.Data["status"]
if !ok {
return "", fmt.Errorf("Status information not found in configmap")
}
matcher, err := regexp.Compile("Cluster-wide:\\s*\n\\s*Health:\\s*([A-Za-z]+)")
if err != nil {
return "", err
}
result := matcher.FindStringSubmatch(status)
if len(result) < 2 {
return "", fmt.Errorf("Failed to parse CA status configmap, raw status: %v", status)
}
return result[1], nil
}
type scaleUpStatus struct {
status string
ready int
target int
timestamp time.Time
}
// Try to get timestamp from status.
// Status configmap is not parsing-friendly, so evil regexpery follows.
func getStatusTimestamp(status string) (time.Time, error) {
timestampMatcher, err := regexp.Compile("Cluster-autoscaler status at \\s*([0-9\\-]+ [0-9]+:[0-9]+:[0-9]+\\.[0-9]+ \\+[0-9]+ [A-Za-z]+)")
if err != nil {
return time.Time{}, err
}
timestampMatch := timestampMatcher.FindStringSubmatch(status)
if len(timestampMatch) < 2 {
return time.Time{}, fmt.Errorf("Failed to parse CA status timestamp, raw status: %v", status)
}
timestamp, err := time.Parse(timestampFormat, timestampMatch[1])
if err != nil {
return time.Time{}, err
}
return timestamp, nil
}
// Try to get scaleup statuses of all node groups.
// Status configmap is not parsing-friendly, so evil regexpery follows.
func getScaleUpStatus(c clientset.Interface) (*scaleUpStatus, error) {
configMap, err := c.CoreV1().ConfigMaps("kube-system").Get(context.TODO(), "cluster-autoscaler-status", metav1.GetOptions{})
if err != nil {
return nil, err
}
status, ok := configMap.Data["status"]
if !ok {
return nil, fmt.Errorf("Status information not found in configmap")
}
timestamp, err := getStatusTimestamp(status)
if err != nil {
return nil, err
}
matcher, err := regexp.Compile("s*ScaleUp:\\s*([A-Za-z]+)\\s*\\(ready=([0-9]+)\\s*cloudProviderTarget=([0-9]+)\\s*\\)")
if err != nil {
return nil, err
}
matches := matcher.FindAllStringSubmatch(status, -1)
if len(matches) < 1 {
return nil, fmt.Errorf("Failed to parse CA status configmap, raw status: %v", status)
}
result := scaleUpStatus{
status: caNoScaleUpStatus,
ready: 0,
target: 0,
timestamp: timestamp,
}
for _, match := range matches {
if match[1] == caOngoingScaleUpStatus {
result.status = caOngoingScaleUpStatus
}
newReady, err := strconv.Atoi(match[2])
if err != nil {
return nil, err
}
result.ready += newReady
newTarget, err := strconv.Atoi(match[3])
if err != nil {
return nil, err
}
result.target += newTarget
}
klog.Infof("Cluster-Autoscaler scale-up status: %v (%v, %v)", result.status, result.ready, result.target)
return &result, nil
}
func waitForScaleUpStatus(c clientset.Interface, cond func(s *scaleUpStatus) bool, timeout time.Duration) (*scaleUpStatus, error) {
var finalErr error
var status *scaleUpStatus
err := wait.PollImmediate(5*time.Second, timeout, func() (bool, error) {
status, finalErr = getScaleUpStatus(c)
if finalErr != nil {
return false, nil
}
if status.timestamp.Add(freshStatusLimit).Before(time.Now()) {
// stale status
finalErr = fmt.Errorf("Status too old")
return false, nil
}
return cond(status), nil
})
if err != nil {
err = fmt.Errorf("Failed to find expected scale up status: %v, last status: %v, final err: %v", err, status, finalErr)
}
return status, err
}
// This is a temporary fix to allow CA to migrate some kube-system pods
// TODO: Remove this when the PDB is added for some of those components
func addKubeSystemPdbs(f *framework.Framework) (func(), error) {
ginkgo.By("Create PodDisruptionBudgets for kube-system components, so they can be migrated if required")
var newPdbs []string
cleanup := func() {
var finalErr error
for _, newPdbName := range newPdbs {
ginkgo.By(fmt.Sprintf("Delete PodDisruptionBudget %v", newPdbName))
err := f.ClientSet.PolicyV1().PodDisruptionBudgets("kube-system").Delete(context.TODO(), newPdbName, metav1.DeleteOptions{})
if err != nil {
// log error, but attempt to remove other pdbs
klog.Errorf("Failed to delete PodDisruptionBudget %v, err: %v", newPdbName, err)
finalErr = err
}
}
if finalErr != nil {
framework.Failf("Error during PodDisruptionBudget cleanup: %v", finalErr)
}
}
type pdbInfo struct {
label string
minAvailable int
}
pdbsToAdd := []pdbInfo{
{label: "kube-dns", minAvailable: 1},
{label: "kube-dns-autoscaler", minAvailable: 0},
{label: "metrics-server", minAvailable: 0},
{label: "kubernetes-dashboard", minAvailable: 0},
{label: "glbc", minAvailable: 0},
}
for _, pdbData := range pdbsToAdd {
ginkgo.By(fmt.Sprintf("Create PodDisruptionBudget for %v", pdbData.label))
labelMap := map[string]string{"k8s-app": pdbData.label}
pdbName := fmt.Sprintf("test-pdb-for-%v", pdbData.label)
minAvailable := intstr.FromInt(pdbData.minAvailable)
pdb := &policyv1.PodDisruptionBudget{
ObjectMeta: metav1.ObjectMeta{
Name: pdbName,
Namespace: "kube-system",
},
Spec: policyv1.PodDisruptionBudgetSpec{
Selector: &metav1.LabelSelector{MatchLabels: labelMap},
MinAvailable: &minAvailable,
},
}
_, err := f.ClientSet.PolicyV1().PodDisruptionBudgets("kube-system").Create(context.TODO(), pdb, metav1.CreateOptions{})
newPdbs = append(newPdbs, pdbName)
if err != nil {
return cleanup, err
}
}
return cleanup, nil
}
func createPriorityClasses(f *framework.Framework) func() {
priorityClasses := map[string]int32{
expendablePriorityClassName: -15,
highPriorityClassName: 1000,
}
for className, priority := range priorityClasses {
_, err := f.ClientSet.SchedulingV1().PriorityClasses().Create(context.TODO(), &schedulingv1.PriorityClass{ObjectMeta: metav1.ObjectMeta{Name: className}, Value: priority}, metav1.CreateOptions{})
if err != nil {
klog.Errorf("Error creating priority class: %v", err)
}
framework.ExpectEqual(err == nil || apierrors.IsAlreadyExists(err), true)
}
return func() {
for className := range priorityClasses {
err := f.ClientSet.SchedulingV1().PriorityClasses().Delete(context.TODO(), className, metav1.DeleteOptions{})
if err != nil {
klog.Errorf("Error deleting priority class: %v", err)
}
}
}
}
| [
"\"TESTED_GPU_TYPE\"",
"\"CLOUDSDK_API_ENDPOINT_OVERRIDES_CONTAINER\""
]
| []
| [
"CLOUDSDK_API_ENDPOINT_OVERRIDES_CONTAINER",
"TESTED_GPU_TYPE"
]
| [] | ["CLOUDSDK_API_ENDPOINT_OVERRIDES_CONTAINER", "TESTED_GPU_TYPE"] | go | 2 | 0 | |
rlang/src/main/java/org/apache/zeppelin/r/ZeppelinR.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.zeppelin.r;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.environment.EnvironmentUtils;
import org.apache.commons.io.IOUtils;
import org.apache.zeppelin.r.SparkRBackend;
import org.apache.zeppelin.interpreter.InterpreterException;
import org.apache.zeppelin.interpreter.InterpreterOutput;
import org.apache.zeppelin.interpreter.util.ProcessLauncher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* R repl interaction
*/
public class ZeppelinR {
private static Logger LOGGER = LoggerFactory.getLogger(ZeppelinR.class);
private RInterpreter rInterpreter;
private RProcessLogOutputStream processOutputStream;
static Map<Integer, ZeppelinR> zeppelinR = Collections.synchronizedMap(new HashMap());
private RProcessLauncher rProcessLauncher;
/**
* Request to R repl
*/
private Request rRequestObject = null;
private Integer rRequestNotifier = new Integer(0);
/**
* Response from R repl
*/
private Object rResponseValue = null;
private boolean rResponseError = false;
private Integer rResponseNotifier = new Integer(0);
public ZeppelinR(RInterpreter rInterpreter) {
this.rInterpreter = rInterpreter;
}
/**
* Start R repl
* @throws IOException
*/
public void open() throws IOException, InterpreterException {
String rCmdPath = rInterpreter.getProperty("zeppelin.R.cmd", "R");
String sparkRLibPath;
if (System.getenv("SPARK_HOME") != null) {
// local or yarn-client mode when SPARK_HOME is specified
sparkRLibPath = System.getenv("SPARK_HOME") + "/R/lib";
} else if (System.getenv("ZEPPELIN_HOME") != null){
// embedded mode when SPARK_HOME is not specified or for native R support
String interpreter = "r";
if (rInterpreter.isSparkSupported()) {
interpreter = "spark";
}
sparkRLibPath = System.getenv("ZEPPELIN_HOME") + "/interpreter/" + interpreter + "/R/lib";
// workaround to make sparkr work without SPARK_HOME
System.setProperty("spark.test.home", System.getenv("ZEPPELIN_HOME") + "/interpreter/" + interpreter);
} else {
// yarn-cluster mode
sparkRLibPath = "sparkr";
}
if (!new File(sparkRLibPath).exists()) {
throw new InterpreterException(String.format("sparkRLib %s doesn't exist", sparkRLibPath));
}
File scriptFile = File.createTempFile("zeppelin_sparkr-", ".R");
FileOutputStream out = null;
InputStream in = null;
try {
out = new FileOutputStream(scriptFile);
in = getClass().getClassLoader().getResourceAsStream("R/zeppelin_sparkr.R");
IOUtils.copy(in, out);
} catch (IOException e) {
throw new InterpreterException(e);
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
}
zeppelinR.put(hashCode(), this);
String timeout = rInterpreter.getProperty("spark.r.backendConnectionTimeout", "6000");
CommandLine cmd = CommandLine.parse(rCmdPath);
cmd.addArgument("--no-save");
cmd.addArgument("--no-restore");
cmd.addArgument("-f");
cmd.addArgument(scriptFile.getAbsolutePath());
cmd.addArgument("--args");
cmd.addArgument(Integer.toString(hashCode()));
cmd.addArgument(Integer.toString(SparkRBackend.get().port()));
cmd.addArgument(sparkRLibPath);
cmd.addArgument(rInterpreter.sparkVersion() + "");
cmd.addArgument(timeout);
cmd.addArgument(rInterpreter.isSparkSupported() + "");
if (rInterpreter.isSecretSupported()) {
cmd.addArgument(SparkRBackend.get().socketSecret());
}
// dump out the R command to facilitate manually running it, e.g. for fault diagnosis purposes
LOGGER.info("R Command: " + cmd.toString());
processOutputStream = new RProcessLogOutputStream(rInterpreter);
Map env = EnvironmentUtils.getProcEnvironment();
rProcessLauncher = new RProcessLauncher(cmd, env, processOutputStream);
rProcessLauncher.launch();
rProcessLauncher.waitForReady(30 * 1000);
if (!rProcessLauncher.isRunning()) {
if (rProcessLauncher.isLaunchTimeout()) {
throw new IOException("Launch r process is time out.\n" +
rProcessLauncher.getErrorMessage());
} else {
throw new IOException("Fail to launch r process.\n" +
rProcessLauncher.getErrorMessage());
}
}
// flush output
eval("cat('')");
}
public void setInterpreterOutput(InterpreterOutput out) {
processOutputStream.setInterpreterOutput(out);
}
/**
* Request object
*
* type : "eval", "set", "get"
* stmt : statement to evaluate when type is "eval"
* key when type is "set" or "get"
* value : value object when type is "put"
*/
public static class Request {
String type;
String stmt;
Object value;
public Request(String type, String stmt, Object value) {
this.type = type;
this.stmt = stmt;
this.value = value;
}
public String getType() {
return type;
}
public String getStmt() {
return stmt;
}
public Object getValue() {
return value;
}
}
/**
* Evaluate expression
* @param expr
* @return
*/
public Object eval(String expr) throws InterpreterException {
synchronized (this) {
rRequestObject = new Request("eval", expr, null);
return request();
}
}
/**
* assign value to key
* @param key
* @param value
*/
public void set(String key, Object value) throws InterpreterException {
synchronized (this) {
rRequestObject = new Request("set", key, value);
request();
}
}
/**
* get value of key
* @param key
* @return
*/
public Object get(String key) throws InterpreterException {
synchronized (this) {
rRequestObject = new Request("get", key, null);
return request();
}
}
/**
* get value of key, as a string
* @param key
* @return
*/
public String getS0(String key) throws InterpreterException {
synchronized (this) {
rRequestObject = new Request("getS", key, null);
return (String) request();
}
}
private boolean isRProcessInitialized() {
return rProcessLauncher != null && rProcessLauncher.isRunning();
}
/**
* Send request to r repl and return response
* @return responseValue
*/
private Object request() throws RuntimeException {
if (!isRProcessInitialized()) {
throw new RuntimeException("r repl is not running");
}
rResponseValue = null;
synchronized (rRequestNotifier) {
rRequestNotifier.notify();
}
Object respValue = null;
synchronized (rResponseNotifier) {
while (rResponseValue == null && isRProcessInitialized()) {
try {
rResponseNotifier.wait(1000);
} catch (InterruptedException e) {
LOGGER.error(e.getMessage(), e);
}
}
respValue = rResponseValue;
rResponseValue = null;
}
if (rResponseError) {
throw new RuntimeException(respValue.toString());
} else {
return respValue;
}
}
/**
* invoked by src/main/resources/R/zeppelin_sparkr.R
* @return
*/
public Request getRequest() {
synchronized (rRequestNotifier) {
while (rRequestObject == null) {
try {
rRequestNotifier.wait(1000);
} catch (InterruptedException e) {
LOGGER.error(e.getMessage(), e);
}
}
Request req = rRequestObject;
rRequestObject = null;
return req;
}
}
/**
* invoked by src/main/resources/R/zeppelin_sparkr.R
* @param value
* @param error
*/
public void setResponse(Object value, boolean error) {
synchronized (rResponseNotifier) {
rResponseValue = value;
rResponseError = error;
rResponseNotifier.notify();
}
}
/**
* invoked by src/main/resources/R/zeppelin_sparkr.R
*/
public void onScriptInitialized() {
rProcessLauncher.initialized();
}
/**
* Terminate this R repl
*/
public void close() {
if (rProcessLauncher != null) {
rProcessLauncher.stop();
}
zeppelinR.remove(hashCode());
}
/**
* Get instance
* This method will be invoded from zeppelin_sparkr.R
* @param hashcode
* @return
*/
public static ZeppelinR getZeppelinR(int hashcode) {
return zeppelinR.get(hashcode);
}
class RProcessLauncher extends ProcessLauncher {
public RProcessLauncher(CommandLine commandLine,
Map<String, String> envs,
ProcessLogOutputStream processLogOutput) {
super(commandLine, envs, processLogOutput);
}
@Override
public void waitForReady(int timeout) {
long startTime = System.currentTimeMillis();
synchronized (this) {
while (state == State.LAUNCHED) {
LOGGER.info("Waiting for R process initialized");
try {
wait(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if ((System.currentTimeMillis() - startTime) > timeout) {
onTimeout();
break;
}
}
}
}
public void initialized() {
synchronized (this) {
this.state = State.RUNNING;
notify();
}
}
}
public static class RProcessLogOutputStream extends ProcessLauncher.ProcessLogOutputStream {
private InterpreterOutput interpreterOutput;
private RInterpreter rInterpreter;
public RProcessLogOutputStream(RInterpreter rInterpreter) {
this.rInterpreter = rInterpreter;
}
/**
* Redirect r process output to interpreter output.
* @param interpreterOutput
*/
public void setInterpreterOutput(InterpreterOutput interpreterOutput) {
this.interpreterOutput = interpreterOutput;
}
@Override
protected void processLine(String s, int i) {
super.processLine(s, i);
if (s.contains("Java SparkR backend might have failed") // spark 2.x
|| s.contains("Execution halted")) { // spark 1.x
rInterpreter.getRbackendDead().set(true);
}
if (interpreterOutput != null) {
try {
interpreterOutput.write(s);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public void close() throws IOException {
super.close();
if (interpreterOutput != null) {
interpreterOutput.close();
}
}
}
}
| [
"\"SPARK_HOME\"",
"\"SPARK_HOME\"",
"\"ZEPPELIN_HOME\"",
"\"ZEPPELIN_HOME\"",
"\"ZEPPELIN_HOME\""
]
| []
| [
"ZEPPELIN_HOME",
"SPARK_HOME"
]
| [] | ["ZEPPELIN_HOME", "SPARK_HOME"] | java | 2 | 0 | |
commands/server/main.go | // Run the rickover server.
//
// All of the project defaults are used. There is one authenticated user for
// basic auth, the user is "test" and the password is "hymanrickover". You will
// want to copy this binary and add your own authentication scheme.
package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/kevinburke/handlers"
"github.com/kevinburke/rickover/config"
"github.com/kevinburke/rickover/metrics"
"github.com/kevinburke/rickover/models/db"
"github.com/kevinburke/rickover/server"
"github.com/kevinburke/rickover/setup"
)
func configure(ctx context.Context) (http.Handler, error) {
dbConns, err := config.GetInt("PG_SERVER_POOL_SIZE")
if err != nil {
log.Printf("Error getting database pool size: %s. Defaulting to 10", err)
dbConns = 10
}
if err = setup.DB(ctx, db.DefaultConnection, dbConns); err != nil {
return nil, err
}
go metrics.Run(ctx, metrics.LibratoConfig{
Namespace: "rickover.server",
Source: "web",
Email: os.Getenv("LIBRATO_EMAIL_ACCOUNT"),
})
go setup.MeasureActiveQueries(ctx, 5*time.Second)
// If you run this in production, change this user.
server.AddUser("test", "hymanrickover")
return server.Get(server.Config{Auth: server.DefaultAuthorizer}), nil
}
func main() {
flag.Parse()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
s, err := configure(ctx)
if err != nil {
log.Fatal(err)
}
port := os.Getenv("PORT")
if port == "" {
port = "9090"
}
log.Printf("Listening on port %s\n", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), handlers.Log(s)))
}
| [
"\"LIBRATO_EMAIL_ACCOUNT\"",
"\"PORT\""
]
| []
| [
"PORT",
"LIBRATO_EMAIL_ACCOUNT"
]
| [] | ["PORT", "LIBRATO_EMAIL_ACCOUNT"] | go | 2 | 0 | |
python/paddle/fluid/tests/unittests/dist_mnist_gradient_merge_raw_optimizer.py | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import paddle
import paddle.nn as nn
import paddle.fluid as fluid
import paddle.distributed.fleet as fleet
import numpy as np
from test_dist_base import TestDistRunnerBase, runtime_main
from dist_mnist import cnn_model
class TestDistMnistGradientMergeRawOptimizer(TestDistRunnerBase):
def get_model(self, batch_size=2, single_device=False):
paddle.enable_static()
paddle.seed(1)
np.random.seed(1)
assert fluid.core.globals()['FLAGS_apply_pass_to_program']
strategy = fleet.DistributedStrategy()
build_strategy = paddle.static.BuildStrategy()
settings = {
"fuse_relu_depthwise_conv": True,
"fuse_bn_act_ops": True,
"fuse_bn_add_act_ops": True,
"fuse_elewise_add_act_ops": True,
"fuse_all_optimizer_ops": True,
"enable_addto": True,
"enable_inplace": True,
}
for k, v in settings.items():
setattr(build_strategy, k, v)
strategy.build_strategy = build_strategy
strategy.gradient_merge = True
avg = os.environ['enable_gm_avg'] == "True"
strategy.gradient_merge_configs = {
"k_steps": 2,
"avg": avg,
}
strategy.without_graph_optimization = True
fleet.init(is_collective=True, strategy=strategy)
image = paddle.static.data(name='image',
shape=[None, 1, 28, 28],
dtype="float32")
label = paddle.static.data(name='label', shape=[None, 1], dtype='int64')
predict = cnn_model(image)
acc = paddle.metric.accuracy(predict, label)
loss_fn = nn.CrossEntropyLoss(use_softmax=False)
cost = loss_fn(predict, label)
test_program = paddle.static.default_main_program().clone(for_test=True)
optimizer = paddle.optimizer.Adam(learning_rate=1e-3)
if single_device:
optimizer = fluid.optimizer.GradientMergeOptimizer(
optimizer,
k_steps=strategy.gradient_merge_configs["k_steps"],
avg=strategy.gradient_merge_configs["avg"])
world_size = 1
else:
optimizer = fleet.distributed_optimizer(optimizer)
world_size = fleet.world_size()
optimizer.minimize(cost)
if world_size > 1:
assert paddle.static.default_main_program().num_blocks == 2
gm_block = paddle.static.default_main_program().block(1)
start_allreduce_idx = None
for i, op in enumerate(gm_block.ops):
if op.type == "c_allreduce_sum":
start_allreduce_idx = i
break
# the magic number 1 below means skip the c_sync_calc_stream op
if avg:
assert start_allreduce_idx > 1
else:
assert start_allreduce_idx == 1
train_reader = paddle.batch(paddle.dataset.mnist.test(),
batch_size=batch_size)
test_reader = paddle.batch(paddle.dataset.mnist.test(),
batch_size=batch_size)
return test_program, cost, train_reader, test_reader, acc, predict
if __name__ == "__main__":
runtime_main(TestDistMnistGradientMergeRawOptimizer)
| []
| []
| [
"enable_gm_avg"
]
| [] | ["enable_gm_avg"] | python | 1 | 0 | |
src/control/cmd/daos_agent/start.go | //
// (C) Copyright 2020-2022 Intel Corporation.
//
// SPDX-License-Identifier: BSD-2-Clause-Patent
//
package main
import (
"context"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/daos-stack/daos/src/control/drpc"
"github.com/daos-stack/daos/src/control/lib/hardware/hwprov"
"github.com/daos-stack/daos/src/control/lib/netdetect"
)
const (
agentSockName = "daos_agent.sock"
)
type startCmd struct {
logCmd
configCmd
ctlInvokerCmd
}
func (cmd *startCmd) Execute(_ []string) error {
cmd.log.Debugf("Starting %s (pid %d)", versionString(), os.Getpid())
startedAt := time.Now()
ctx, shutdown := context.WithCancel(context.Background())
defer shutdown()
sockPath := filepath.Join(cmd.cfg.RuntimeDir, agentSockName)
cmd.log.Debugf("Full socket path is now: %s", sockPath)
drpcServer, err := drpc.NewDomainSocketServer(ctx, cmd.log, sockPath)
if err != nil {
cmd.log.Errorf("Unable to create socket server: %v", err)
return err
}
aicEnabled := (os.Getenv("DAOS_AGENT_DISABLE_CACHE") != "true")
if !aicEnabled {
cmd.log.Debugf("GetAttachInfo agent caching has been disabled\n")
}
ficEnabled := (os.Getenv("DAOS_AGENT_DISABLE_OFI_CACHE") != "true")
if !ficEnabled {
cmd.log.Debugf("Local fabric interface caching has been disabled\n")
}
hwprovFini, err := hwprov.Init(cmd.log)
if err != nil {
return err
}
defer hwprovFini()
netCtx, err := netdetect.Init(context.Background())
defer netdetect.CleanUp(netCtx)
if err != nil {
cmd.log.Errorf("Unable to initialize netdetect services")
return err
}
numaAware := netdetect.HasNUMA(netCtx)
if !numaAware {
cmd.log.Debugf("This system is not NUMA aware. Any devices found are reported as NUMA node 0.")
}
procmon := NewProcMon(cmd.log, cmd.ctlInvoker, cmd.cfg.SystemName)
procmon.startMonitoring(ctx)
fabricCache := newLocalFabricCache(cmd.log, ficEnabled)
if len(cmd.cfg.FabricInterfaces) > 0 {
// Cache is required to use user-defined fabric interfaces
fabricCache.enabled.SetTrue()
nf := NUMAFabricFromConfig(cmd.log, cmd.cfg.FabricInterfaces)
fabricCache.Cache(ctx, nf)
}
drpcServer.RegisterRPCModule(NewSecurityModule(cmd.log, cmd.cfg.TransportConfig))
drpcServer.RegisterRPCModule(&mgmtModule{
log: cmd.log,
sys: cmd.cfg.SystemName,
ctlInvoker: cmd.ctlInvoker,
attachInfo: newAttachInfoCache(cmd.log, aicEnabled),
fabricInfo: fabricCache,
numaAware: numaAware,
netCtx: netCtx,
monitor: procmon,
})
err = drpcServer.Start()
if err != nil {
cmd.log.Errorf("Unable to start socket server on %s: %v", sockPath, err)
return err
}
cmd.log.Debugf("startup complete in %s", time.Since(startedAt))
cmd.log.Infof("%s (pid %d) listening on %s", versionString(), os.Getpid(), sockPath)
// Setup signal handlers so we can block till we get SIGINT or SIGTERM
signals := make(chan os.Signal)
finish := make(chan struct{})
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM, syscall.SIGPIPE)
// Anonymous goroutine to wait on the signals channel and tell the
// program to finish when it receives a signal. Since we notify on
// SIGINT and SIGTERM we should only catch these on a kill or ctrl+c
// SIGPIPE is caught and logged to avoid killing the agent.
// The syntax looks odd but <- Channel means wait on any input on the
// channel.
var shutdownRcvd time.Time
go func() {
sig := <-signals
switch sig {
case syscall.SIGPIPE:
cmd.log.Infof("Signal received. Caught non-fatal %s; continuing", sig)
default:
shutdownRcvd = time.Now()
cmd.log.Infof("Signal received. Caught %s; shutting down", sig)
close(finish)
}
}()
<-finish
drpcServer.Shutdown()
cmd.log.Debugf("shutdown complete in %s", time.Since(shutdownRcvd))
return nil
}
| [
"\"DAOS_AGENT_DISABLE_CACHE\"",
"\"DAOS_AGENT_DISABLE_OFI_CACHE\""
]
| []
| [
"DAOS_AGENT_DISABLE_CACHE",
"DAOS_AGENT_DISABLE_OFI_CACHE"
]
| [] | ["DAOS_AGENT_DISABLE_CACHE", "DAOS_AGENT_DISABLE_OFI_CACHE"] | go | 2 | 0 | |
backend/project/asgi.py | """
ASGI config for project project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
django_asgi_app = get_asgi_application()
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from app.routing import websocket_urlpatterns
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(websocket_urlpatterns)
),
}) | []
| []
| []
| [] | [] | python | 0 | 0 | |
ml_data/config.py | import os
APP_DIR = os.path.dirname(__file__)
ROOT_DIR = os.path.dirname(APP_DIR)
DATA_DIR = os.path.join(ROOT_DIR, 'data')
celery_cfg = {
'broker': os.environ.get('CELERY_BROKER'),
'backend': os.environ.get('CELERY_BACKEND')
}
rest_cfg = {
'address': os.environ.get('APP_ADDRESS'),
'port': os.environ.get('PORT')
}
| []
| []
| [
"PORT",
"APP_ADDRESS",
"CELERY_BROKER",
"CELERY_BACKEND"
]
| [] | ["PORT", "APP_ADDRESS", "CELERY_BROKER", "CELERY_BACKEND"] | python | 4 | 0 | |
cmd/watchmantest/main.go | // Copyright 2020 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.
// watchmantest is a cli tool used for testing the Moov Sanction Search service.
//
// With no arguments the contaier runs tests against the production API.
// This tool requires an OAuth token provided by github.com/moov-io/api written
// to the local disk, but running apitest first will write this token.
//
// This tool can be used to query with custom searches:
// $ go install ./cmd/watchmantest
// $ watchmantest -local moh
// 2019/02/14 23:37:44.432334 main.go:44: Starting moov/watchmantest v0.4.1-dev
// 2019/02/14 23:37:44.432366 main.go:60: [INFO] using http://localhost:8084 for address
// 2019/02/14 23:37:44.434534 main.go:76: [SUCCESS] ping
// 2019/02/14 23:37:44.435204 main.go:83: [SUCCESS] last download was: 3h45m58s ago
// 2019/02/14 23:37:44.440230 main.go:96: [SUCCESS] name search passed, query="moh"
// 2019/02/14 23:37:44.441506 main.go:104: [SUCCESS] added customer=24032 watch
// 2019/02/14 23:37:44.445473 main.go:118: [SUCCESS] alt name search passed
// 2019/02/14 23:37:44.449367 main.go:123: [SUCCESS] address search passed
//
// watchmantest is not a stable tool. Please contact Moov developers if you intend to use this tool,
// otherwise we might change the tool (or remove it) without notice.
package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
"os"
"time"
"github.com/moov-io/watchman"
moov "github.com/moov-io/watchman/client"
"github.com/moov-io/watchman/cmd/internal"
"github.com/antihax/optional"
)
var (
flagApiAddress = flag.String("address", internal.DefaultApiAddress, "Moov API address")
flagLocal = flag.Bool("local", false, "Use local HTTP addresses")
flagWebhook = flag.String("webhook", "https://moov.io/watchman", "Secure HTTP address for webhooks")
flagRequestID = flag.String("request-id", "", "Override what is set for the X-Request-ID HTTP header")
)
func main() {
flag.Parse()
log.SetFlags(log.Ldate | log.Ltime | log.LUTC | log.Lmicroseconds | log.Lshortfile)
log.Printf("Starting moov/watchmantest %s", watchman.Version)
conf := internal.Config(*flagApiAddress, *flagLocal)
log.Printf("[INFO] using %s for address", conf.BasePath)
// Read OAuth token and set on conf
if v := os.Getenv("OAUTH_TOKEN"); v != "" {
conf.AddDefaultHeader("Authorization", fmt.Sprintf("Bearer %s", v))
} else {
if local := *flagLocal; !local {
log.Fatal("[FAILURE] no OAuth token provided (try adding -local for http://localhost requests)")
}
}
// Setup API client
api, ctx := moov.NewAPIClient(conf), context.TODO()
// Ping
if err := ping(ctx, api); err != nil {
log.Fatal("[FAILURE] ping Sanction Search")
} else {
log.Println("[SUCCESS] ping")
}
// Check downloads
if when, err := latestDownload(ctx, api); err != nil || when.IsZero() {
log.Fatalf("[FAILURE] downloads: %v", err)
} else {
log.Printf("[SUCCESS] last download was: %v ago", time.Since(when).Truncate(1*time.Second))
}
query := "alh" // string that matches a lot of records
if v := flag.Arg(0); v != "" {
query = v
}
// Search queries
sdn, err := searchByName(ctx, api, query)
if err != nil {
log.Fatalf("[FAILURE] problem searching SDNs: %v", err)
} else {
log.Printf("[SUCCESS] name search passed, query=%q", query)
}
// Add watch on the SDN
if sdn.SdnType == moov.SDNTYPE_INDIVIDUAL {
if err := addCustomerWatch(ctx, api, sdn.EntityID, *flagWebhook); err != nil {
log.Fatalf("[FAILURE] problem adding customer watch: %v", err)
} else {
log.Printf("[SUCCESS] added customer=%s watch", sdn.EntityID)
}
} else {
if err := addCompanyWatch(ctx, api, sdn.EntityID, *flagWebhook); err != nil {
log.Fatalf("[FAILURE] problem adding company watch: %v", err)
} else {
log.Printf("[SUCCESS] added company=%s watch", sdn.EntityID)
}
}
// Load alt names and addresses
if err := searchByAltName(ctx, api, query); err != nil {
log.Fatalf("[FAILURE] problem searching Alt Names: %v", err)
} else {
log.Println("[SUCCESS] alt name search passed")
}
if err := searchByAddress(ctx, api, "St"); err != nil {
log.Fatalf("[FAILURE] problem searching addresses: %v", err)
} else {
log.Println("[SUCCESS] address search passed")
}
// Lookup UI values
if err := getUIValues(ctx, api); err != nil {
log.Fatalf("[FAILURE] problem looking up UI values: %v", err)
} else {
log.Println("[SUCCESS] UI values lookup passed")
}
}
func ping(ctx context.Context, api *moov.APIClient) error {
resp, err := api.WatchmanApi.Ping(ctx)
if err != nil {
return err
}
resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return fmt.Errorf("ping error (stats code: %d): %v", resp.StatusCode, err)
}
return nil
}
func latestDownload(ctx context.Context, api *moov.APIClient) (time.Time, error) {
opts := &moov.GetLatestDownloadsOpts{
Limit: optional.NewInt32(1),
XRequestID: optional.NewString(*flagRequestID),
}
downloads, resp, err := api.WatchmanApi.GetLatestDownloads(ctx, opts)
if err != nil {
return time.Time{}, err
}
resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return time.Time{}, fmt.Errorf("download error (stats code: %d): %v", resp.StatusCode, err)
}
if len(downloads) == 0 {
return time.Time{}, errors.New("empty downloads response")
}
return downloads[0].Timestamp, nil
}
| [
"\"OAUTH_TOKEN\""
]
| []
| [
"OAUTH_TOKEN"
]
| [] | ["OAUTH_TOKEN"] | go | 1 | 0 | |
sample-operators/tomcat-operator/src/test/java/io/javaoperatorsdk/operator/sample/TomcatOperatorE2E.java | package io.javaoperatorsdk.operator.sample;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.client.*;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.extended.run.RunConfigBuilder;
import io.javaoperatorsdk.operator.Operator;
import io.javaoperatorsdk.operator.config.runtime.DefaultConfigurationService;
import static java.util.concurrent.TimeUnit.*;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
public class TomcatOperatorE2E {
final static String TEST_NS = "tomcat-test";
final static Logger log = LoggerFactory.getLogger(TomcatOperatorE2E.class);
@Test
public void test() {
Config config = new ConfigBuilder().withNamespace(null).build();
KubernetesClient client = new DefaultKubernetesClient(config);
// Use this if you want to run the test without deploying the Operator to Kubernetes
if ("true".equals(System.getenv("RUN_OPERATOR_IN_TEST"))) {
Operator operator = new Operator(client, DefaultConfigurationService.instance());
operator.register(new TomcatReconciler(client));
operator.register(new WebappReconciler(client));
operator.start();
}
Tomcat tomcat = new Tomcat();
tomcat.setMetadata(new ObjectMetaBuilder()
.withName("test-tomcat1")
.withNamespace(TEST_NS)
.build());
tomcat.setSpec(new TomcatSpec());
tomcat.getSpec().setReplicas(3);
tomcat.getSpec().setVersion(9);
Webapp webapp1 = new Webapp();
webapp1.setMetadata(new ObjectMetaBuilder()
.withName("test-webapp1")
.withNamespace(TEST_NS)
.build());
webapp1.setSpec(new WebappSpec());
webapp1.getSpec().setContextPath("webapp1");
webapp1.getSpec().setTomcat(tomcat.getMetadata().getName());
webapp1.getSpec().setUrl("http://tomcat.apache.org/tomcat-7.0-doc/appdev/sample/sample.war");
var tomcatClient = client.customResources(Tomcat.class);
var webappClient = client.customResources(Webapp.class);
Namespace testNs = new NamespaceBuilder().withMetadata(
new ObjectMetaBuilder().withName(TEST_NS).build()).build();
if (testNs != null) {
// We perform a pre-run cleanup instead of a post-run cleanup. This is to help with debugging
// test results when running against a persistent cluster. The test namespace would stay
// after the test run so we can check what's there, but it would be cleaned up during the next
// test run.
log.info("Cleanup: deleting test namespace {}", TEST_NS);
client.namespaces().delete(testNs);
await().atMost(5, MINUTES)
.until(() -> client.namespaces().withName("tomcat-test").get() == null);
}
log.info("Creating test namespace {}", TEST_NS);
client.namespaces().create(testNs);
log.info("Creating test Tomcat object: {}", tomcat);
tomcatClient.inNamespace(TEST_NS).create(tomcat);
log.info("Creating test Webapp object: {}", webapp1);
webappClient.inNamespace(TEST_NS).create(webapp1);
log.info("Waiting 5 minutes for Tomcat and Webapp CR statuses to be updated");
await().atMost(5, MINUTES).untilAsserted(() -> {
Tomcat updatedTomcat =
tomcatClient.inNamespace(TEST_NS).withName(tomcat.getMetadata().getName()).get();
Webapp updatedWebapp =
webappClient.inNamespace(TEST_NS).withName(webapp1.getMetadata().getName()).get();
assertThat(updatedTomcat.getStatus(), is(notNullValue()));
assertThat(updatedTomcat.getStatus().getReadyReplicas(), equalTo(3));
assertThat(updatedWebapp.getStatus(), is(notNullValue()));
assertThat(updatedWebapp.getStatus().getDeployedArtifact(), is(notNullValue()));
});
String url =
"http://" + tomcat.getMetadata().getName() + "/" + webapp1.getSpec().getContextPath() + "/";
log.info("Starting curl Pod and waiting 5 minutes for GET of {} to return 200", url);
await("wait-for-webapp").atMost(6, MINUTES).untilAsserted(() -> {
try {
log.info("Starting curl Pod to test if webapp was deployed correctly");
Pod curlPod = client.run().inNamespace(TEST_NS)
.withRunConfig(new RunConfigBuilder()
.withArgs("-s", "-o", "/dev/null", "-w", "%{http_code}", url)
.withName("curl")
.withImage("curlimages/curl:7.78.0")
.withRestartPolicy("Never")
.build())
.done();
log.info("Waiting for curl Pod to finish running");
await("wait-for-curl-pod-run").atMost(2, MINUTES)
.until(() -> {
String phase =
client.pods().inNamespace(TEST_NS).withName("curl").get().getStatus().getPhase();
return phase.equals("Succeeded") || phase.equals("Failed");
});
String curlOutput =
client.pods().inNamespace(TEST_NS).withName(curlPod.getMetadata().getName()).getLog();
log.info("Output from curl: '{}'", curlOutput);
assertThat(curlOutput, equalTo("200"));
} catch (KubernetesClientException ex) {
throw new AssertionError(ex);
} finally {
log.info("Deleting curl Pod");
client.pods().inNamespace(TEST_NS).withName("curl").delete();
await("wait-for-curl-pod-stop").atMost(1, MINUTES)
.until(() -> client.pods().inNamespace(TEST_NS).withName("curl").get() == null);
}
});
}
}
| [
"\"RUN_OPERATOR_IN_TEST\""
]
| []
| [
"RUN_OPERATOR_IN_TEST"
]
| [] | ["RUN_OPERATOR_IN_TEST"] | java | 1 | 0 | |
core/celery.py | # Django Celery
# https://pypi.org/project/django-celery/
import os
CELERY_BROKER_URL = os.environ.get('CLOUDAMQP_URL')
CELERY_IMPORTS = ('main.tasks',)
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = "Asia/Calcutta"
| []
| []
| [
"CLOUDAMQP_URL"
]
| [] | ["CLOUDAMQP_URL"] | python | 1 | 0 | |
src/cmd/services/m3coordinator/downsample/downsampler_test.go | // Copyright (c) 2018 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//nolint: dupl
package downsample
import (
"bytes"
"fmt"
"os"
"strings"
"testing"
"time"
"github.com/m3db/m3/src/aggregator/client"
clusterclient "github.com/m3db/m3/src/cluster/client"
"github.com/m3db/m3/src/cluster/kv/mem"
dbclient "github.com/m3db/m3/src/dbnode/client"
"github.com/m3db/m3/src/metrics/aggregation"
"github.com/m3db/m3/src/metrics/generated/proto/metricpb"
"github.com/m3db/m3/src/metrics/generated/proto/rulepb"
"github.com/m3db/m3/src/metrics/matcher"
"github.com/m3db/m3/src/metrics/metadata"
"github.com/m3db/m3/src/metrics/metric/id"
"github.com/m3db/m3/src/metrics/metric/unaggregated"
"github.com/m3db/m3/src/metrics/policy"
"github.com/m3db/m3/src/metrics/rules"
ruleskv "github.com/m3db/m3/src/metrics/rules/store/kv"
"github.com/m3db/m3/src/metrics/rules/view"
"github.com/m3db/m3/src/metrics/transformation"
"github.com/m3db/m3/src/query/models"
"github.com/m3db/m3/src/query/storage"
"github.com/m3db/m3/src/query/storage/m3"
"github.com/m3db/m3/src/query/storage/m3/storagemetadata"
"github.com/m3db/m3/src/query/storage/mock"
"github.com/m3db/m3/src/query/ts"
"github.com/m3db/m3/src/x/clock"
"github.com/m3db/m3/src/x/ident"
"github.com/m3db/m3/src/x/instrument"
xio "github.com/m3db/m3/src/x/io"
"github.com/m3db/m3/src/x/pool"
"github.com/m3db/m3/src/x/serialize"
xtest "github.com/m3db/m3/src/x/test"
xtime "github.com/m3db/m3/src/x/time"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
)
var (
testAggregationType = aggregation.Sum
testAggregationStoragePolicies = []policy.StoragePolicy{
policy.MustParseStoragePolicy("2s:1d"),
}
)
const (
nameTag = "__name__"
)
func TestDownsamplerAggregationWithAutoMappingRulesFromNamespacesWatcher(t *testing.T) {
t.Parallel()
ctrl := xtest.NewController(t)
defer ctrl.Finish()
gaugeMetrics, _ := testGaugeMetrics(testGaugeMetricsOptions{})
require.Equal(t, 1, len(gaugeMetrics))
gaugeMetric := gaugeMetrics[0]
numSamples := len(gaugeMetric.samples)
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: gaugeMetrics,
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: gaugeMetric.tags,
// NB(nate): Automapping rules generated from cluster namespaces currently
// hardcode 'Last' as the aggregation type. As such, expect value to be the last value
// in the sample.
values: []expectedValue{{value: gaugeMetric.samples[numSamples-1]}},
},
},
},
})
require.False(t, testDownsampler.downsampler.Enabled())
origStagedMetadata := originalStagedMetadata(t, testDownsampler)
session := dbclient.NewMockSession(ctrl)
setAggregatedNamespaces(t, testDownsampler, session, m3.AggregatedClusterNamespaceDefinition{
NamespaceID: ident.StringID("2s:1d"),
Resolution: 2 * time.Second,
Retention: 24 * time.Hour,
Session: session,
})
waitForStagedMetadataUpdate(t, testDownsampler, origStagedMetadata)
require.True(t, testDownsampler.downsampler.Enabled())
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationDownsamplesRawMetricWithRollupRule(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42},
{value: 64, offset: 1 * time.Second},
},
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
RollupRules: []RollupRuleConfiguration{
{
Filter: fmt.Sprintf(
"%s:http_requests app:* status_code:* endpoint:*",
nameTag),
Transforms: []TransformConfiguration{
{
Transform: &TransformOperationConfiguration{
Type: transformation.PerSecond,
},
},
{
Rollup: &RollupOperationConfiguration{
MetricName: "http_requests_by_status_code",
GroupBy: []string{"app", "status_code", "endpoint"},
Aggregations: []aggregation.Type{aggregation.Sum},
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
// aggregated rollup metric
{
tags: map[string]string{
nameTag: "http_requests_by_status_code",
string(rollupTagName): string(rollupTagValue),
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
values: []expectedValue{{value: 22}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
// raw aggregated metric
{
tags: gaugeMetric.tags,
values: []expectedValue{{value: 42}, {value: 64}},
},
},
},
})
// Setup auto-mapping rules.
require.False(t, testDownsampler.downsampler.Enabled())
origStagedMetadata := originalStagedMetadata(t, testDownsampler)
ctrl := xtest.NewController(t)
defer ctrl.Finish()
session := dbclient.NewMockSession(ctrl)
setAggregatedNamespaces(t, testDownsampler, session, m3.AggregatedClusterNamespaceDefinition{
NamespaceID: ident.StringID("1s:30d"),
Resolution: res,
Retention: ret,
Session: session,
})
waitForStagedMetadataUpdate(t, testDownsampler, origStagedMetadata)
require.True(t, testDownsampler.downsampler.Enabled())
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerEmptyGroupBy(t *testing.T) {
t.Parallel()
requestMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "http_requests",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42},
{value: 64, offset: 1 * time.Second},
},
}
errorMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "http_errors",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 43},
{value: 65, offset: 1 * time.Second},
},
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
RollupRules: []RollupRuleConfiguration{
{
Filter: fmt.Sprintf("%s:http_*", nameTag),
Transforms: []TransformConfiguration{
{
Transform: &TransformOperationConfiguration{
Type: transformation.PerSecond,
},
},
{
Rollup: &RollupOperationConfiguration{
MetricName: "http_all",
GroupBy: []string{},
Aggregations: []aggregation.Type{aggregation.Sum},
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{requestMetric, errorMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
// aggregated rollup metric
{
tags: map[string]string{
nameTag: "http_all",
string(rollupTagName): string(rollupTagValue),
},
values: []expectedValue{{value: 22 * 2}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
// raw aggregated metric
{
tags: requestMetric.tags,
values: []expectedValue{{value: 42}, {value: 64}},
},
{
tags: errorMetric.tags,
values: []expectedValue{{value: 43}, {value: 65}},
},
},
},
})
// Setup auto-mapping rules.
require.False(t, testDownsampler.downsampler.Enabled())
origStagedMetadata := originalStagedMetadata(t, testDownsampler)
ctrl := xtest.NewController(t)
defer ctrl.Finish()
session := dbclient.NewMockSession(ctrl)
setAggregatedNamespaces(t, testDownsampler, session, m3.AggregatedClusterNamespaceDefinition{
NamespaceID: ident.StringID("1s:30d"),
Resolution: res,
Retention: ret,
Session: session,
})
waitForStagedMetadataUpdate(t, testDownsampler, origStagedMetadata)
require.True(t, testDownsampler.downsampler.Enabled())
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationDoesNotDownsampleRawMetricWithRollupRulesWithoutRollup(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42},
{value: 64, offset: 1 * time.Second},
},
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
RollupRules: []RollupRuleConfiguration{
{
Filter: fmt.Sprintf(
"%s:http_requests app:* status_code:* endpoint:*",
nameTag),
Transforms: []TransformConfiguration{
{
Aggregate: &AggregateOperationConfiguration{
Type: aggregation.Sum,
},
},
{
Transform: &TransformOperationConfiguration{
Type: transformation.Add,
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
// mapped metric
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
values: []expectedValue{{value: 42}, {value: 106, offset: 1 * time.Second}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
},
},
})
// Setup auto-mapping rules.
require.False(t, testDownsampler.downsampler.Enabled())
origStagedMetadata := originalStagedMetadata(t, testDownsampler)
ctrl := xtest.NewController(t)
defer ctrl.Finish()
session := dbclient.NewMockSession(ctrl)
setAggregatedNamespaces(t, testDownsampler, session, m3.AggregatedClusterNamespaceDefinition{
NamespaceID: ident.StringID("1s:30d"),
Resolution: res,
Retention: ret,
Session: session,
})
waitForStagedMetadataUpdate(t, testDownsampler, origStagedMetadata)
require.True(t, testDownsampler.downsampler.Enabled())
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationToggleEnabled(t *testing.T) {
t.Parallel()
ctrl := xtest.NewController(t)
defer ctrl.Finish()
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{})
require.False(t, testDownsampler.downsampler.Enabled())
// Add an aggregated namespace and expect downsampler to be enabled.
session := dbclient.NewMockSession(ctrl)
setAggregatedNamespaces(t, testDownsampler, session, m3.AggregatedClusterNamespaceDefinition{
NamespaceID: ident.StringID("2s:1d"),
Resolution: 2 * time.Second,
Retention: 24 * time.Hour,
Session: session,
})
waitForEnabledUpdate(t, &testDownsampler, false)
require.True(t, testDownsampler.downsampler.Enabled())
// Set just an unaggregated namespace and expect downsampler to be disabled.
clusters, err := m3.NewClusters(m3.UnaggregatedClusterNamespaceDefinition{
NamespaceID: ident.StringID("default"),
Retention: 48 * time.Hour,
Session: session,
})
require.NoError(t, err)
require.NoError(t,
testDownsampler.opts.ClusterNamespacesWatcher.Update(clusters.ClusterNamespaces()))
waitForEnabledUpdate(t, &testDownsampler, true)
require.False(t, testDownsampler.downsampler.Enabled())
}
func TestDownsamplerAggregationWithRulesStore(t *testing.T) {
t.Parallel()
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{})
rulesStore := testDownsampler.rulesStore
// Create rules
nss, err := rulesStore.ReadNamespaces()
require.NoError(t, err)
_, err = nss.AddNamespace("default", testUpdateMetadata())
require.NoError(t, err)
rule := view.MappingRule{
ID: "mappingrule",
Name: "mappingrule",
Filter: "app:test*",
AggregationID: aggregation.MustCompressTypes(testAggregationType),
StoragePolicies: testAggregationStoragePolicies,
}
rs := rules.NewEmptyRuleSet("default", testUpdateMetadata())
_, err = rs.AddMappingRule(rule, testUpdateMetadata())
require.NoError(t, err)
err = rulesStore.WriteAll(nss, rs)
require.NoError(t, err)
logger := testDownsampler.instrumentOpts.Logger().
With(zap.String("test", t.Name()))
// Wait for mapping rule to appear
logger.Info("waiting for mapping rules to propagate")
matcher := testDownsampler.matcher
testMatchID := newTestID(t, map[string]string{
"__name__": "foo",
"app": "test123",
})
for {
now := time.Now().UnixNano()
res := matcher.ForwardMatch(testMatchID, now, now+1)
results := res.ForExistingIDAt(now)
if !results.IsDefault() {
break
}
time.Sleep(100 * time.Millisecond)
}
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRules(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "foo_metric",
"app": "nginx_edge",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "app:nginx*",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: gaugeMetric.tags,
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithAutoMappingRulesAndRulesConfigMappingRulesAndDropRule(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "foo_metric",
"app": "nginx_edge",
"env": "staging",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
expectDropPolicyApplied: true,
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
autoMappingRules: []m3.ClusterNamespaceOptions{
m3.NewClusterNamespaceOptions(
storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Retention: 2 * time.Hour,
Resolution: 1 * time.Second,
},
nil,
),
m3.NewClusterNamespaceOptions(
storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Retention: 12 * time.Hour,
Resolution: 5 * time.Second,
},
nil,
),
},
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "env:staging",
Drop: true,
},
{
Filter: "app:nginx*",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 10 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
allowFilter: &testDownsamplerOptionsExpectAllowFilter{
attributes: []storagemetadata.Attributes{
{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 10 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
writes: []testExpectedWrite{
{
tags: gaugeMetric.tags,
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 10 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRulesPartialReplaceAutoMappingRuleFromNamespacesWatcher(t *testing.T) {
t.Parallel()
ctrl := xtest.NewController(t)
defer ctrl.Finish()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "foo_metric",
"app": "nginx_edge",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0, offset: 1 * time.Millisecond},
},
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "app:nginx*",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 2 * time.Second,
Retention: 24 * time.Hour,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
// Expect the max to be used and override the default auto
// mapping rule for the storage policy 2s:24h.
{
tags: gaugeMetric.tags,
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 2 * time.Second,
Retention: 24 * time.Hour,
},
},
// Expect last to still be used for the storage
// policy 4s:48h.
{
tags: gaugeMetric.tags,
// NB(nate): Automapping rules generated from cluster namespaces currently
// hardcode 'Last' as the aggregation type. As such, expect value to be the last value
// in the sample.
values: []expectedValue{{value: 0}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 4 * time.Second,
Retention: 48 * time.Hour,
},
},
},
},
})
origStagedMetadata := originalStagedMetadata(t, testDownsampler)
session := dbclient.NewMockSession(ctrl)
setAggregatedNamespaces(t, testDownsampler, session, m3.AggregatedClusterNamespaceDefinition{
NamespaceID: ident.StringID("2s:24h"),
Resolution: 2 * time.Second,
Retention: 24 * time.Hour,
Session: session,
}, m3.AggregatedClusterNamespaceDefinition{
NamespaceID: ident.StringID("4s:48h"),
Resolution: 4 * time.Second,
Retention: 48 * time.Hour,
Session: session,
})
waitForStagedMetadataUpdate(t, testDownsampler, origStagedMetadata)
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRulesReplaceAutoMappingRuleFromNamespacesWatcher(t *testing.T) {
t.Parallel()
ctrl := xtest.NewController(t)
defer ctrl.Finish()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "foo_metric",
"app": "nginx_edge",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "app:nginx*",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 2 * time.Second,
Retention: 24 * time.Hour,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
// Expect the max to be used and override the default auto
// mapping rule for the storage policy 2s:24h.
{
tags: gaugeMetric.tags,
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 2 * time.Second,
Retention: 24 * time.Hour,
},
},
},
},
})
origStagedMetadata := originalStagedMetadata(t, testDownsampler)
session := dbclient.NewMockSession(ctrl)
setAggregatedNamespaces(t, testDownsampler, session, m3.AggregatedClusterNamespaceDefinition{
NamespaceID: ident.StringID("2s:24h"),
Resolution: 2 * time.Second,
Retention: 24 * time.Hour,
Session: session,
})
waitForStagedMetadataUpdate(t, testDownsampler, origStagedMetadata)
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRulesNoNameTag(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
"app": "nginx_edge",
"endpoint": "health",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
identTag: "endpoint",
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "app:nginx*",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: gaugeMetric.tags,
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRulesTypeFilter(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
"app": "nginx_edge",
"endpoint": "health",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
identTag: "endpoint",
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "__m3_type__:counter",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
},
sampleAppenderOpts: &SampleAppenderOptions{
SeriesAttributes: ts.SeriesAttributes{M3Type: ts.M3MetricTypeCounter},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
"app": "nginx_edge",
"endpoint": "health",
},
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
//nolint:dupl
func TestDownsamplerAggregationWithRulesConfigMappingRulesTypePromFilter(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
"app": "nginx_edge",
"endpoint": "health",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
identTag: "endpoint",
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "__m3_prom_type__:counter",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
},
sampleAppenderOpts: &SampleAppenderOptions{
SeriesAttributes: ts.SeriesAttributes{PromType: ts.PromMetricTypeCounter},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
"app": "nginx_edge",
"endpoint": "health",
},
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRulesTypeFilterNoMatch(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
"app": "nginx_edge",
"endpoint": "health",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
identTag: "endpoint",
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "__m3_type__:counter",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
},
sampleAppenderOpts: &SampleAppenderOptions{
SeriesAttributes: ts.SeriesAttributes{M3Type: ts.M3MetricTypeGauge},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
//nolint:dupl
func TestDownsamplerAggregationWithRulesConfigMappingRulesPromTypeFilterNoMatch(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
"app": "nginx_edge",
"endpoint": "health",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
identTag: "endpoint",
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "__m3_prom_type__:counter",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
},
sampleAppenderOpts: &SampleAppenderOptions{
SeriesAttributes: ts.SeriesAttributes{PromType: ts.PromMetricTypeGauge},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRulesAggregationType(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
"__g0__": "nginx_edge",
"__g1__": "health",
"__option_id_scheme__": "graphite",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
tags := []Tag{{Name: "__m3_graphite_aggregation__"}}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
identTag: "__g2__",
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "__m3_type__:gauge",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
Tags: tags,
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
"__g0__": "nginx_edge",
"__g1__": "health",
"__g2__": "upper",
},
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRulesMultipleAggregationType(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
"__g0__": "nginx_edge",
"__g1__": "health",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
tags := []Tag{{Name: "__m3_graphite_aggregation__"}}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
identTag: "__g2__",
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "__m3_type__:gauge",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
Tags: tags,
},
{
Filter: "__m3_type__:gauge",
Aggregations: []aggregation.Type{aggregation.Sum},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
Tags: tags,
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
"__g0__": "nginx_edge",
"__g1__": "health",
"__g2__": "upper",
},
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
{
tags: map[string]string{
"__g0__": "nginx_edge",
"__g1__": "health",
"__g2__": "sum",
},
values: []expectedValue{{value: 60}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRulesGraphitePrefixAndAggregationTags(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
"__g0__": "nginx_edge",
"__g1__": "health",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
tags := []Tag{
{Name: "__m3_graphite_aggregation__"},
{Name: "__m3_graphite_prefix__", Value: "stats.counter"},
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
identTag: "__g4__",
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "__m3_type__:gauge",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
Tags: tags,
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
"__g0__": "stats",
"__g1__": "counter",
"__g2__": "nginx_edge",
"__g3__": "health",
"__g4__": "upper",
},
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRulesGraphitePrefixTag(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
"__g0__": "nginx_edge",
"__g1__": "health",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
tags := []Tag{
{Name: "__m3_graphite_prefix__", Value: "stats.counter"},
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
identTag: "__g3__",
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "__m3_type__:gauge",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
Tags: tags,
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
"__g0__": "stats",
"__g1__": "counter",
"__g2__": "nginx_edge",
"__g3__": "health",
},
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRulesPromQuantileTag(t *testing.T) {
t.Parallel()
timerMetric := testTimerMetric{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"endpoint": "health",
},
timedSamples: []testTimerMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
tags := []Tag{
{Name: "__m3_prom_summary__"},
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "__m3_type__:timer",
Aggregations: []aggregation.Type{aggregation.P50},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
Tags: tags,
},
},
},
sampleAppenderOpts: &SampleAppenderOptions{
SeriesAttributes: ts.SeriesAttributes{M3Type: ts.M3MetricTypeTimer},
},
ingest: &testDownsamplerOptionsIngest{
timerMetrics: []testTimerMetric{timerMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"endpoint": "health",
"agg": ".p50",
"quantile": "0.5",
},
values: []expectedValue{{value: 10}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRulesPromQuantileTagIgnored(t *testing.T) {
t.Parallel()
timerMetric := testTimerMetric{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"endpoint": "health",
},
timedSamples: []testTimerMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
tags := []Tag{
{Name: "__m3_prom_summary__"},
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "__m3_type__:timer",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
Tags: tags,
},
},
},
sampleAppenderOpts: &SampleAppenderOptions{
SeriesAttributes: ts.SeriesAttributes{M3Type: ts.M3MetricTypeTimer},
},
ingest: &testDownsamplerOptionsIngest{
timerMetrics: []testTimerMetric{timerMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"endpoint": "health",
"agg": ".upper",
},
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRulesAugmentTag(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
"app": "nginx_edge",
"endpoint": "health",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
tags := []Tag{
{Name: "datacenter", Value: "abc"},
}
//nolint:dupl
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
identTag: "app",
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "app:nginx*",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
Tags: tags,
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
"app": "nginx_edge",
"endpoint": "health",
"datacenter": "abc",
},
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigMappingRulesWithDropTSTag(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "foo_metric",
"app": "nginx_edge",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 15}, {value: 10}, {value: 30}, {value: 5}, {value: 0},
},
}
counterMetric := testCounterMetric{
tags: map[string]string{
nameTag: "counter0",
"app": "testapp",
"foo": "bar",
},
timedSamples: []testCounterMetricTimedSample{
{value: 1}, {value: 2}, {value: 3},
},
expectDropTimestamp: true,
}
tags := []Tag{
{Name: "__m3_drop_timestamp__", Value: ""},
}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "app:nginx*",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
{
Filter: "app:testapp",
Aggregations: []aggregation.Type{aggregation.Sum},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
Tags: tags,
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
counterMetrics: []testCounterMetric{counterMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: gaugeMetric.tags,
values: []expectedValue{{value: 30}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
{
tags: counterMetric.tags,
values: []expectedValue{{value: 6}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigRollupRulesNoNameTag(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42},
{value: 64, offset: 1 * time.Second},
},
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
identTag: "endpoint",
rulesConfig: &RulesConfiguration{
RollupRules: []RollupRuleConfiguration{
{
Filter: fmt.Sprintf(
"%s:http_requests app:* status_code:* endpoint:*",
nameTag),
Transforms: []TransformConfiguration{
{
Transform: &TransformOperationConfiguration{
Type: transformation.PerSecond,
},
},
{
Rollup: &RollupOperationConfiguration{
MetricName: "http_requests_by_status_code",
GroupBy: []string{"app", "status_code", "endpoint"},
Aggregations: []aggregation.Type{aggregation.Sum},
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigRollupRulesPerSecondSum(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42},
{value: 64, offset: 1 * time.Second},
},
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
RollupRules: []RollupRuleConfiguration{
{
Filter: fmt.Sprintf(
"%s:http_requests app:* status_code:* endpoint:*",
nameTag),
Transforms: []TransformConfiguration{
{
Transform: &TransformOperationConfiguration{
Type: transformation.PerSecond,
},
},
{
Rollup: &RollupOperationConfiguration{
MetricName: "http_requests_by_status_code",
GroupBy: []string{"app", "status_code", "endpoint"},
Aggregations: []aggregation.Type{aggregation.Sum},
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_requests_by_status_code",
string(rollupTagName): string(rollupTagValue),
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
values: []expectedValue{{value: 22}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigRollupRulesAugmentTags(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42},
{value: 64, offset: 1 * time.Second},
},
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
RollupRules: []RollupRuleConfiguration{
{
Filter: fmt.Sprintf(
"%s:http_requests app:* status_code:* endpoint:*",
nameTag),
Transforms: []TransformConfiguration{
{
Transform: &TransformOperationConfiguration{
Type: transformation.PerSecond,
},
},
{
Rollup: &RollupOperationConfiguration{
MetricName: "http_requests_by_status_code",
GroupBy: []string{"app", "status_code", "endpoint"},
Aggregations: []aggregation.Type{aggregation.Sum},
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
Tags: []Tag{
{
Name: "__rollup_type__",
Value: "counter",
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_requests_by_status_code",
string(rollupTagName): string(rollupTagValue),
"__rollup_type__": "counter",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
values: []expectedValue{{value: 22}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
// TestDownsamplerAggregationWithRulesConfigRollupRulesAggregateTransformNoRollup
// tests that rollup rules can be used to actually simply transform values
// without the need for an explicit rollup step.
func TestDownsamplerAggregationWithRulesConfigRollupRulesAggregateTransformNoRollup(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42},
{value: 64},
},
}
res := 5 * time.Second
ret := 30 * 24 * time.Hour
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
RollupRules: []RollupRuleConfiguration{
{
Filter: fmt.Sprintf(
"%s:http_requests app:* status_code:* endpoint:*",
nameTag),
Transforms: []TransformConfiguration{
{
Aggregate: &AggregateOperationConfiguration{
Type: aggregation.Sum,
},
},
{
Transform: &TransformOperationConfiguration{
Type: transformation.Add,
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value",
},
values: []expectedValue{{value: 106}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigRollupRulesIncreaseAdd(t *testing.T) {
t.Parallel()
// nolint:dupl
gaugeMetrics := []testGaugeMetric{
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value_1",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42, offset: 1 * time.Second}, // +42
{value: 12, offset: 2 * time.Second}, // +12 - simulate a reset (should count as a 0)
{value: 33, offset: 3 * time.Second}, // +21
},
},
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value_2",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 13, offset: 1 * time.Second}, // +13
{value: 27, offset: 2 * time.Second}, // +14
{value: 42, offset: 3 * time.Second}, // +15
},
},
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
RollupRules: []RollupRuleConfiguration{
{
Filter: fmt.Sprintf(
"%s:http_requests app:* status_code:* endpoint:*",
nameTag),
Transforms: []TransformConfiguration{
{
Transform: &TransformOperationConfiguration{
Type: transformation.Increase,
},
},
{
Rollup: &RollupOperationConfiguration{
MetricName: "http_requests_by_status_code",
GroupBy: []string{"app", "status_code", "endpoint"},
Aggregations: []aggregation.Type{aggregation.Sum},
},
},
{
Transform: &TransformOperationConfiguration{
Type: transformation.Add,
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: gaugeMetrics,
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_requests_by_status_code",
string(rollupTagName): string(rollupTagValue),
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
values: []expectedValue{
{value: 55},
{value: 69, offset: 1 * time.Second},
{value: 105, offset: 2 * time.Second},
},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigRollupRuleAndDropPolicy(t *testing.T) {
t.Parallel()
gaugeMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42},
{value: 64, offset: 1 * time.Second},
},
expectDropPolicyApplied: true,
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
filter := fmt.Sprintf("%s:http_requests app:* status_code:* endpoint:*", nameTag)
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: filter,
Drop: true,
},
},
RollupRules: []RollupRuleConfiguration{
{
Filter: filter,
Transforms: []TransformConfiguration{
{
Transform: &TransformOperationConfiguration{
Type: transformation.PerSecond,
},
},
{
Rollup: &RollupOperationConfiguration{
MetricName: "http_requests_by_status_code",
GroupBy: []string{"app", "status_code", "endpoint"},
Aggregations: []aggregation.Type{aggregation.Sum},
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_requests_by_status_code",
string(rollupTagName): string(rollupTagValue),
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
values: []expectedValue{{value: 22}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigRollupRuleAndDropPolicyAndDropTimestamp(t *testing.T) {
t.Parallel()
gaugeMetrics := []testGaugeMetric{
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value_1",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42}, // +42 (should not be accounted since is a reset)
// Explicit no value.
{value: 12, offset: 2 * time.Second}, // +12 - simulate a reset (should not be accounted)
},
expectDropTimestamp: true,
expectDropPolicyApplied: true,
},
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value_2",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 13},
{value: 27, offset: 2 * time.Second}, // +14
},
expectDropTimestamp: true,
expectDropPolicyApplied: true,
},
}
tags := []Tag{
{Name: "__m3_drop_timestamp__", Value: ""},
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
filter := fmt.Sprintf("%s:http_requests app:* status_code:* endpoint:*", nameTag)
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: filter,
Drop: true,
Tags: tags,
},
},
RollupRules: []RollupRuleConfiguration{
{
Filter: filter,
Transforms: []TransformConfiguration{
{
Rollup: &RollupOperationConfiguration{
MetricName: "http_requests_by_status_code",
GroupBy: []string{"app", "status_code", "endpoint"},
Aggregations: []aggregation.Type{aggregation.Sum},
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: gaugeMetrics,
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_requests_by_status_code",
string(rollupTagName): string(rollupTagValue),
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
values: []expectedValue{{value: 94}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigRollupRuleUntimedRollups(t *testing.T) {
t.Parallel()
gaugeMetrics := []testGaugeMetric{
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value_1",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42},
{value: 12, offset: 2 * time.Second},
},
expectDropTimestamp: true,
},
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value_2",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 13},
{value: 27, offset: 2 * time.Second},
},
expectDropTimestamp: true,
},
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
filter := fmt.Sprintf("%s:http_requests app:* status_code:* endpoint:*", nameTag)
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
untimedRollups: true,
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "app:nginx*",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
RollupRules: []RollupRuleConfiguration{
{
Filter: filter,
Transforms: []TransformConfiguration{
{
Rollup: &RollupOperationConfiguration{
MetricName: "http_requests_by_status_code",
GroupBy: []string{"app", "status_code", "endpoint"},
Aggregations: []aggregation.Type{aggregation.Sum},
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: gaugeMetrics,
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_requests_by_status_code",
string(rollupTagName): string(rollupTagValue),
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
values: []expectedValue{{value: 94}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigRollupRuleUntimedRollupsWaitForOffset(t *testing.T) {
t.Parallel()
gaugeMetrics := []testGaugeMetric{
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value_1",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42},
},
expectDropPolicyApplied: true,
expectDropTimestamp: true,
},
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value_2",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 12, offset: 2 * time.Second},
},
expectDropPolicyApplied: true,
expectDropTimestamp: true,
},
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value_3",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 13},
},
expectDropPolicyApplied: true,
expectDropTimestamp: true,
},
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
filter := fmt.Sprintf("%s:http_requests app:* status_code:* endpoint:*", nameTag)
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
waitForOffset: true,
untimedRollups: true,
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: filter,
Drop: true,
},
},
RollupRules: []RollupRuleConfiguration{
{
Filter: filter,
Transforms: []TransformConfiguration{
{
Rollup: &RollupOperationConfiguration{
MetricName: "http_requests_by_status_code",
GroupBy: []string{"app", "status_code", "endpoint"},
Aggregations: []aggregation.Type{aggregation.Sum},
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: gaugeMetrics,
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_requests_by_status_code",
string(rollupTagName): string(rollupTagValue),
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
values: []expectedValue{{value: 42}, {value: 25}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigRollupRuleRollupLaterUntimedRollups(t *testing.T) {
t.Parallel()
gaugeMetrics := []testGaugeMetric{
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value_1",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42},
{value: 12, offset: 2 * time.Second},
},
expectDropTimestamp: true,
},
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value_2",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 13},
{value: 27, offset: 2 * time.Second},
},
expectDropTimestamp: true,
},
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
filter := fmt.Sprintf("%s:http_requests app:* status_code:* endpoint:*", nameTag)
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
untimedRollups: true,
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "app:nginx*",
Aggregations: []aggregation.Type{aggregation.Max},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 1 * time.Second,
Retention: 30 * 24 * time.Hour,
},
},
},
},
RollupRules: []RollupRuleConfiguration{
{
Filter: filter,
Transforms: []TransformConfiguration{
{
Transform: &TransformOperationConfiguration{
Type: transformation.Add,
},
},
{
Rollup: &RollupOperationConfiguration{
MetricName: "http_requests_by_status_code",
GroupBy: []string{"app", "status_code", "endpoint"},
Aggregations: []aggregation.Type{aggregation.Sum},
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: gaugeMetrics,
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_requests_by_status_code",
string(rollupTagName): string(rollupTagValue),
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
values: []expectedValue{{value: 39}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigRollupRulesExcludeByLastMean(t *testing.T) {
t.Parallel()
gaugeMetrics := []testGaugeMetric{
{
tags: map[string]string{
nameTag: "http_request_latency_max_gauge",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"instance": "not_rolled_up_instance_1",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42},
},
},
{
tags: map[string]string{
nameTag: "http_request_latency_max_gauge",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"instance": "not_rolled_up_instance_2",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 13},
},
},
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
RollupRules: []RollupRuleConfiguration{
{
Filter: fmt.Sprintf(
"%s:http_request_latency_max_gauge app:* status_code:* endpoint:*",
nameTag),
Transforms: []TransformConfiguration{
{
Aggregate: &AggregateOperationConfiguration{
Type: aggregation.Last,
},
},
{
Rollup: &RollupOperationConfiguration{
MetricName: "{{ .MetricName }}:mean_without_instance",
ExcludeBy: []string{"instance"},
Aggregations: []aggregation.Type{aggregation.Mean},
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: gaugeMetrics,
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_request_latency_max_gauge:mean_without_instance",
string(rollupTagName): string(rollupTagValue),
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
values: []expectedValue{
{value: 27.5},
},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRulesConfigRollupRulesExcludeByIncreaseSumAdd(t *testing.T) {
t.Parallel()
// nolint:dupl
gaugeMetrics := []testGaugeMetric{
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"instance": "not_rolled_up_instance_1",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42, offset: 1 * time.Second}, // +42
{value: 12, offset: 2 * time.Second}, // +12 - simulate a reset (should count as a 0)
{value: 33, offset: 3 * time.Second}, // +21
},
},
{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"instance": "not_rolled_up_instance_2",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 13, offset: 1 * time.Second}, // +13
{value: 27, offset: 2 * time.Second}, // +14
{value: 42, offset: 3 * time.Second}, // +15
},
},
}
res := 1 * time.Second
ret := 30 * 24 * time.Hour
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
RollupRules: []RollupRuleConfiguration{
{
Filter: fmt.Sprintf(
"%s:http_requests app:* status_code:* endpoint:*",
nameTag),
Transforms: []TransformConfiguration{
{
Transform: &TransformOperationConfiguration{
Type: transformation.Increase,
},
},
{
Rollup: &RollupOperationConfiguration{
MetricName: "{{ .MetricName }}:sum_without_instance",
ExcludeBy: []string{"instance"},
Aggregations: []aggregation.Type{aggregation.Sum},
},
},
{
Transform: &TransformOperationConfiguration{
Type: transformation.Add,
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: gaugeMetrics,
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_requests:sum_without_instance",
string(rollupTagName): string(rollupTagValue),
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
values: []expectedValue{
{value: 55},
{value: 69, offset: 1 * time.Second},
{value: 105, offset: 2 * time.Second},
},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithTimedSamples(t *testing.T) {
counterMetrics, counterMetricsExpect := testCounterMetrics(testCounterMetricsOptions{
timedSamples: true,
})
gaugeMetrics, gaugeMetricsExpect := testGaugeMetrics(testGaugeMetricsOptions{
timedSamples: true,
})
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
ingest: &testDownsamplerOptionsIngest{
counterMetrics: counterMetrics,
gaugeMetrics: gaugeMetrics,
},
expect: &testDownsamplerOptionsExpect{
writes: append(counterMetricsExpect, gaugeMetricsExpect...),
},
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "__name__:*",
Aggregations: []aggregation.Type{testAggregationType},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 2 * time.Second,
Retention: 24 * time.Hour,
},
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithOverrideRules(t *testing.T) {
counterMetrics, counterMetricsExpect := testCounterMetrics(testCounterMetricsOptions{})
counterMetricsExpect[0].values = []expectedValue{{value: 2}}
gaugeMetrics, gaugeMetricsExpect := testGaugeMetrics(testGaugeMetricsOptions{})
gaugeMetricsExpect[0].values = []expectedValue{{value: 5}}
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
sampleAppenderOpts: &SampleAppenderOptions{
Override: true,
OverrideRules: SamplesAppenderOverrideRules{
MappingRules: []AutoMappingRule{
{
Aggregations: []aggregation.Type{aggregation.Mean},
Policies: []policy.StoragePolicy{
policy.MustParseStoragePolicy("4s:1d"),
},
},
},
},
},
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "__name__:*",
Aggregations: []aggregation.Type{testAggregationType},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 2 * time.Second,
Retention: 24 * time.Hour,
},
},
},
},
},
ingest: &testDownsamplerOptionsIngest{
counterMetrics: counterMetrics,
gaugeMetrics: gaugeMetrics,
},
expect: &testDownsamplerOptionsExpect{
writes: append(counterMetricsExpect, gaugeMetricsExpect...),
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func TestDownsamplerAggregationWithRemoteAggregatorClient(t *testing.T) {
ctrl := xtest.NewController(t)
defer ctrl.Finish()
// Create mock client
remoteClientMock := client.NewMockClient(ctrl)
remoteClientMock.EXPECT().Init().Return(nil)
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
MappingRules: []MappingRuleConfiguration{
{
Filter: "__name__:*",
Aggregations: []aggregation.Type{testAggregationType},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: 2 * time.Second,
Retention: 24 * time.Hour,
},
},
},
},
},
remoteClientMock: remoteClientMock,
})
// Test expected output
testDownsamplerRemoteAggregation(t, testDownsampler)
}
func TestDownsamplerWithOverrideNamespace(t *testing.T) {
overrideNamespaceTag := "override_namespace_tag"
gaugeMetric := testGaugeMetric{
tags: map[string]string{
nameTag: "http_requests",
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
"not_rolled_up": "not_rolled_up_value",
// Set namespace tags on ingested metrics.
// The test demonstrates that overrideNamespaceTag is respected, meaning setting
// values on defaultNamespaceTag won't affect aggregation.
defaultNamespaceTag: "namespace_ignored",
},
timedSamples: []testGaugeMetricTimedSample{
{value: 42},
{value: 64, offset: 5 * time.Second},
},
}
res := 5 * time.Second
ret := 30 * 24 * time.Hour
testDownsampler := newTestDownsampler(t, testDownsamplerOptions{
rulesConfig: &RulesConfiguration{
RollupRules: []RollupRuleConfiguration{
{
Filter: fmt.Sprintf(
"%s:http_requests app:* status_code:* endpoint:*",
nameTag),
Transforms: []TransformConfiguration{
{
Transform: &TransformOperationConfiguration{
Type: transformation.PerSecond,
},
},
{
Rollup: &RollupOperationConfiguration{
MetricName: "http_requests_by_status_code",
GroupBy: []string{"app", "status_code", "endpoint"},
Aggregations: []aggregation.Type{aggregation.Sum},
},
},
},
StoragePolicies: []StoragePolicyConfiguration{
{
Resolution: res,
Retention: ret,
},
},
},
},
},
matcherConfig: MatcherConfiguration{NamespaceTag: overrideNamespaceTag},
ingest: &testDownsamplerOptionsIngest{
gaugeMetrics: []testGaugeMetric{gaugeMetric},
},
expect: &testDownsamplerOptionsExpect{
writes: []testExpectedWrite{
{
tags: map[string]string{
nameTag: "http_requests_by_status_code",
string(rollupTagName): string(rollupTagValue),
"app": "nginx_edge",
"status_code": "500",
"endpoint": "/foo/bar",
},
values: []expectedValue{{value: 4.4}},
attributes: &storagemetadata.Attributes{
MetricsType: storagemetadata.AggregatedMetricsType,
Resolution: res,
Retention: ret,
},
},
},
},
})
// Test expected output
testDownsamplerAggregation(t, testDownsampler)
}
func originalStagedMetadata(t *testing.T, testDownsampler testDownsampler) []metricpb.StagedMetadatas {
ds, ok := testDownsampler.downsampler.(*downsampler)
require.True(t, ok)
origStagedMetadata := ds.metricsAppenderOpts.defaultStagedMetadatasProtos
return origStagedMetadata
}
func waitForStagedMetadataUpdate(t *testing.T, testDownsampler testDownsampler, origStagedMetadata []metricpb.StagedMetadatas) {
ds, ok := testDownsampler.downsampler.(*downsampler)
require.True(t, ok)
require.True(t, clock.WaitUntil(func() bool {
ds.RLock()
defer ds.RUnlock()
return !assert.ObjectsAreEqual(origStagedMetadata, ds.metricsAppenderOpts.defaultStagedMetadatasProtos)
}, time.Second))
}
func waitForEnabledUpdate(t *testing.T, testDownsampler *testDownsampler, current bool) {
ds, ok := testDownsampler.downsampler.(*downsampler)
require.True(t, ok)
require.True(t, clock.WaitUntil(func() bool {
ds.RLock()
defer ds.RUnlock()
return current != ds.enabled
}, time.Second))
}
type testExpectedWrite struct {
tags map[string]string
values []expectedValue // use values for multi expected values
valueAllowedError float64 // use for allowing for slightly inexact values due to timing, etc
attributes *storagemetadata.Attributes
}
type expectedValue struct {
offset time.Duration
value float64
}
type testCounterMetric struct {
tags map[string]string
samples []int64
timedSamples []testCounterMetricTimedSample
expectDropPolicyApplied bool
expectDropTimestamp bool
}
type testCounterMetricTimedSample struct {
time xtime.UnixNano
offset time.Duration
value int64
}
type testGaugeMetric struct {
tags map[string]string
samples []float64
timedSamples []testGaugeMetricTimedSample
expectDropPolicyApplied bool
expectDropTimestamp bool
}
type testGaugeMetricTimedSample struct {
time xtime.UnixNano
offset time.Duration
value float64
}
type testTimerMetric struct {
tags map[string]string
samples []float64
timedSamples []testTimerMetricTimedSample
expectDropPolicyApplied bool
expectDropTimestamp bool
}
type testTimerMetricTimedSample struct {
time xtime.UnixNano
offset time.Duration
value float64
}
type testCounterMetricsOptions struct {
timedSamples bool
}
func testCounterMetrics(opts testCounterMetricsOptions) (
[]testCounterMetric,
[]testExpectedWrite,
) {
metric := testCounterMetric{
tags: map[string]string{nameTag: "counter0", "app": "testapp", "foo": "bar"},
samples: []int64{1, 2, 3},
}
if opts.timedSamples {
metric.samples = nil
metric.timedSamples = []testCounterMetricTimedSample{
{value: 1}, {value: 2}, {value: 3},
}
}
write := testExpectedWrite{
tags: metric.tags,
values: []expectedValue{{value: 6}},
}
return []testCounterMetric{metric}, []testExpectedWrite{write}
}
type testGaugeMetricsOptions struct {
timedSamples bool
}
func testGaugeMetrics(opts testGaugeMetricsOptions) ([]testGaugeMetric, []testExpectedWrite) {
metric := testGaugeMetric{
tags: map[string]string{nameTag: "gauge0", "app": "testapp", "qux": "qaz"},
samples: []float64{4, 5, 6},
}
if opts.timedSamples {
metric.samples = nil
metric.timedSamples = []testGaugeMetricTimedSample{
{value: 4},
{value: 5},
{value: 6, offset: 1 * time.Nanosecond},
}
}
write := testExpectedWrite{
tags: metric.tags,
values: []expectedValue{{value: 15}},
}
return []testGaugeMetric{metric}, []testExpectedWrite{write}
}
func testDownsamplerAggregation(
t *testing.T,
testDownsampler testDownsampler,
) {
testOpts := testDownsampler.testOpts
logger := testDownsampler.instrumentOpts.Logger().
With(zap.String("test", t.Name()))
counterMetrics, counterMetricsExpect := testCounterMetrics(testCounterMetricsOptions{})
gaugeMetrics, gaugeMetricsExpect := testGaugeMetrics(testGaugeMetricsOptions{})
expectedWrites := append(counterMetricsExpect, gaugeMetricsExpect...)
// Allow overrides
var (
allowFilter *testDownsamplerOptionsExpectAllowFilter
timerMetrics []testTimerMetric
)
if ingest := testOpts.ingest; ingest != nil {
counterMetrics = ingest.counterMetrics
gaugeMetrics = ingest.gaugeMetrics
timerMetrics = ingest.timerMetrics
}
if expect := testOpts.expect; expect != nil {
expectedWrites = expect.writes
allowFilter = expect.allowFilter
}
// Ingest points
testDownsamplerAggregationIngest(t, testDownsampler,
counterMetrics, gaugeMetrics, timerMetrics)
// Wait for writes
logger.Info("wait for test metrics to appear")
logWritesAccumulated := os.Getenv("TEST_LOG_WRITES_ACCUMULATED") == "true"
logWritesAccumulatedTicker := time.NewTicker(time.Second)
logWritesMatch := os.Getenv("TEST_LOG_WRITES_MATCH") == "true"
logWritesMatchTicker := time.NewTicker(time.Second)
identTag := nameTag
if len(testDownsampler.testOpts.identTag) > 0 {
identTag = testDownsampler.testOpts.identTag
}
CheckAllWritesArrivedLoop:
for {
allWrites := testDownsampler.storage.Writes()
if logWritesAccumulated {
select {
case <-logWritesAccumulatedTicker.C:
logger.Info("logging accmulated writes",
zap.Int("numAllWrites", len(allWrites)))
for _, write := range allWrites {
logger.Info("accumulated write",
zap.ByteString("tags", write.Tags().ID()),
zap.Any("datapoints", write.Datapoints()),
zap.Any("attributes", write.Attributes()))
}
default:
}
}
for _, expectedWrite := range expectedWrites {
name := expectedWrite.tags[identTag]
attrs := expectedWrite.attributes
writesForNameAndAttrs, _ := findWrites(allWrites, name, identTag, attrs)
if len(writesForNameAndAttrs) != len(expectedWrite.values) {
if logWritesMatch {
select {
case <-logWritesMatchTicker.C:
logger.Info("continuing wait for accumulated writes",
zap.String("name", name),
zap.Any("attributes", attrs),
zap.Int("numWritesForNameAndAttrs", len(writesForNameAndAttrs)),
zap.Int("numExpectedWriteValues", len(expectedWrite.values)),
)
default:
}
}
time.Sleep(100 * time.Millisecond)
continue CheckAllWritesArrivedLoop
}
}
break
}
// Verify writes
logger.Info("verify test metrics")
allWrites := testDownsampler.storage.Writes()
if logWritesAccumulated {
logger.Info("logging accmulated writes to verify",
zap.Int("numAllWrites", len(allWrites)))
for _, write := range allWrites {
logger.Info("accumulated write",
zap.ByteString("tags", write.Tags().ID()),
zap.Any("datapoints", write.Datapoints()))
}
}
for _, expectedWrite := range expectedWrites {
name := expectedWrite.tags[identTag]
expectedValues := expectedWrite.values
allowedError := expectedWrite.valueAllowedError
writesForNameAndAttrs, found := findWrites(allWrites, name, identTag, expectedWrite.attributes)
require.True(t, found)
require.Equal(t, len(expectedValues), len(writesForNameAndAttrs))
for i, expectedValue := range expectedValues {
write := writesForNameAndAttrs[i]
assert.Equal(t, expectedWrite.tags, tagsToStringMap(write.Tags()))
require.Equal(t, 1, len(write.Datapoints()))
actualValue := write.Datapoints()[0].Value
if allowedError == 0 {
// Exact match value.
assert.Equal(t, expectedValue.value, actualValue)
} else {
// Fuzzy match value.
lower := expectedValue.value - allowedError
upper := expectedValue.value + allowedError
withinBounds := (lower <= actualValue) && (actualValue <= upper)
msg := fmt.Sprintf("expected within: lower=%f, upper=%f, actual=%f",
lower, upper, actualValue)
assert.True(t, withinBounds, msg)
}
if expectedOffset := expectedValue.offset; expectedOffset > 0 {
// Check if distance between datapoints as expected (use
// absolute offset from first write).
firstTimestamp := writesForNameAndAttrs[0].Datapoints()[0].Timestamp
actualOffset := write.Datapoints()[0].Timestamp.Sub(firstTimestamp)
assert.Equal(t, expectedOffset, actualOffset)
}
if attrs := expectedWrite.attributes; attrs != nil {
assert.Equal(t, *attrs, write.Attributes())
}
}
}
if allowFilter == nil {
return // No allow filter checking required.
}
for _, write := range testDownsampler.storage.Writes() {
attrs := write.Attributes()
foundMatchingAttribute := false
for _, allowed := range allowFilter.attributes {
if allowed == attrs {
foundMatchingAttribute = true
break
}
}
assert.True(t, foundMatchingAttribute,
fmt.Sprintf("attribute not allowed: allowed=%v, actual=%v",
allowFilter.attributes, attrs))
}
}
func testDownsamplerRemoteAggregation(
t *testing.T,
testDownsampler testDownsampler,
) {
testOpts := testDownsampler.testOpts
expectTestCounterMetrics, _ := testCounterMetrics(testCounterMetricsOptions{})
testCounterMetrics, _ := testCounterMetrics(testCounterMetricsOptions{})
expectTestGaugeMetrics, _ := testGaugeMetrics(testGaugeMetricsOptions{})
testGaugeMetrics, _ := testGaugeMetrics(testGaugeMetricsOptions{})
remoteClientMock := testOpts.remoteClientMock
require.NotNil(t, remoteClientMock)
// Expect ingestion
checkedCounterSamples := 0
remoteClientMock.EXPECT().
WriteUntimedCounter(gomock.Any(), gomock.Any()).
AnyTimes().
Do(func(counter unaggregated.Counter,
metadatas metadata.StagedMetadatas,
) error {
for _, c := range expectTestCounterMetrics {
if !strings.Contains(counter.ID.String(), c.tags[nameTag]) {
continue
}
var remainingSamples []int64
found := false
for _, s := range c.samples {
if !found && s == counter.Value {
found = true
} else {
remainingSamples = append(remainingSamples, s)
}
}
c.samples = remainingSamples
if found {
checkedCounterSamples++
}
break
}
return nil
})
checkedGaugeSamples := 0
remoteClientMock.EXPECT().
WriteUntimedGauge(gomock.Any(), gomock.Any()).
AnyTimes().
Do(func(gauge unaggregated.Gauge,
metadatas metadata.StagedMetadatas,
) error {
for _, g := range expectTestGaugeMetrics {
if !strings.Contains(gauge.ID.String(), g.tags[nameTag]) {
continue
}
var remainingSamples []float64
found := false
for _, s := range g.samples {
if !found && s == gauge.Value {
found = true
} else {
remainingSamples = append(remainingSamples, s)
}
}
g.samples = remainingSamples
if found {
checkedGaugeSamples++
}
break
}
return nil
})
// Ingest points
testDownsamplerAggregationIngest(t, testDownsampler,
testCounterMetrics, testGaugeMetrics, []testTimerMetric{})
// Ensure we checked counters and gauges
samplesCounters := 0
for _, c := range testCounterMetrics {
samplesCounters += len(c.samples)
}
samplesGauges := 0
for _, c := range testGaugeMetrics {
samplesGauges += len(c.samples)
}
require.Equal(t, samplesCounters, checkedCounterSamples)
require.Equal(t, samplesGauges, checkedGaugeSamples)
}
func testDownsamplerAggregationIngest(
t *testing.T,
testDownsampler testDownsampler,
testCounterMetrics []testCounterMetric,
testGaugeMetrics []testGaugeMetric,
testTimerMetrics []testTimerMetric,
) {
downsampler := testDownsampler.downsampler
testOpts := testDownsampler.testOpts
logger := testDownsampler.instrumentOpts.Logger().
With(zap.String("test", t.Name()))
logger.Info("write test metrics")
appender, err := downsampler.NewMetricsAppender()
require.NoError(t, err)
defer appender.Finalize()
var opts SampleAppenderOptions
if testOpts.sampleAppenderOpts != nil {
opts = *testOpts.sampleAppenderOpts
}
// make the current timestamp predictable:
now := time.Now().Truncate(time.Microsecond)
xNow := xtime.ToUnixNano(now)
for _, metric := range testCounterMetrics {
appender.NextMetric()
for name, value := range metric.tags {
appender.AddTag([]byte(name), []byte(value))
}
samplesAppenderResult, err := appender.SamplesAppender(opts)
require.NoError(t, err)
require.Equal(t, metric.expectDropPolicyApplied,
samplesAppenderResult.IsDropPolicyApplied)
require.Equal(t, metric.expectDropTimestamp,
samplesAppenderResult.ShouldDropTimestamp)
samplesAppender := samplesAppenderResult.SamplesAppender
for _, sample := range metric.samples {
err = samplesAppender.AppendUntimedCounterSample(xtime.Now(), sample, nil)
require.NoError(t, err)
}
for _, sample := range metric.timedSamples {
if sample.time.IsZero() {
sample.time = xNow // Allow empty time to mean "now"
}
if sample.offset > 0 {
sample.time = sample.time.Add(sample.offset)
}
if testOpts.waitForOffset {
time.Sleep(sample.offset)
}
if samplesAppenderResult.ShouldDropTimestamp {
err = samplesAppender.AppendUntimedCounterSample(sample.time, sample.value, nil)
} else {
err = samplesAppender.AppendCounterSample(sample.time, sample.value, nil)
}
require.NoError(t, err)
}
}
for _, metric := range testGaugeMetrics {
appender.NextMetric()
for name, value := range metric.tags {
appender.AddTag([]byte(name), []byte(value))
}
samplesAppenderResult, err := appender.SamplesAppender(opts)
require.NoError(t, err)
require.Equal(t, metric.expectDropPolicyApplied,
samplesAppenderResult.IsDropPolicyApplied)
require.Equal(t, metric.expectDropTimestamp,
samplesAppenderResult.ShouldDropTimestamp)
samplesAppender := samplesAppenderResult.SamplesAppender
for _, sample := range metric.samples {
err = samplesAppender.AppendUntimedGaugeSample(xtime.Now(), sample, nil)
require.NoError(t, err)
}
for _, sample := range metric.timedSamples {
if sample.time.IsZero() {
sample.time = xNow // Allow empty time to mean "now"
}
if sample.offset > 0 {
sample.time = sample.time.Add(sample.offset)
}
if testOpts.waitForOffset {
time.Sleep(sample.offset)
}
if samplesAppenderResult.ShouldDropTimestamp {
err = samplesAppender.AppendUntimedGaugeSample(sample.time, sample.value, nil)
} else {
err = samplesAppender.AppendGaugeSample(sample.time, sample.value, nil)
}
require.NoError(t, err)
}
}
//nolint:dupl
for _, metric := range testTimerMetrics {
appender.NextMetric()
for name, value := range metric.tags {
appender.AddTag([]byte(name), []byte(value))
}
samplesAppenderResult, err := appender.SamplesAppender(opts)
require.NoError(t, err)
require.Equal(t, metric.expectDropPolicyApplied,
samplesAppenderResult.IsDropPolicyApplied)
require.Equal(t, metric.expectDropTimestamp,
samplesAppenderResult.ShouldDropTimestamp)
samplesAppender := samplesAppenderResult.SamplesAppender
for _, sample := range metric.samples {
err = samplesAppender.AppendUntimedTimerSample(xtime.Now(), sample, nil)
require.NoError(t, err)
}
for _, sample := range metric.timedSamples {
if sample.time.IsZero() {
sample.time = xtime.ToUnixNano(now) // Allow empty time to mean "now"
}
if sample.offset > 0 {
sample.time = sample.time.Add(sample.offset)
}
if testOpts.waitForOffset {
time.Sleep(sample.offset)
}
if samplesAppenderResult.ShouldDropTimestamp {
err = samplesAppender.AppendUntimedTimerSample(sample.time, sample.value, nil)
} else {
err = samplesAppender.AppendTimerSample(sample.time, sample.value, nil)
}
require.NoError(t, err)
}
}
}
func setAggregatedNamespaces(
t *testing.T,
testDownsampler testDownsampler,
session dbclient.Session,
namespaces ...m3.AggregatedClusterNamespaceDefinition,
) {
clusters, err := m3.NewClusters(m3.UnaggregatedClusterNamespaceDefinition{
NamespaceID: ident.StringID("default"),
Retention: 48 * time.Hour,
Session: session,
}, namespaces...)
require.NoError(t, err)
require.NoError(t, testDownsampler.opts.ClusterNamespacesWatcher.Update(clusters.ClusterNamespaces()))
}
func tagsToStringMap(tags models.Tags) map[string]string {
stringMap := make(map[string]string, tags.Len())
for _, t := range tags.Tags {
stringMap[string(t.Name)] = string(t.Value)
}
return stringMap
}
type testDownsampler struct {
opts DownsamplerOptions
testOpts testDownsamplerOptions
downsampler Downsampler
matcher matcher.Matcher
storage mock.Storage
rulesStore rules.Store
instrumentOpts instrument.Options
}
type testDownsamplerOptions struct {
clockOpts clock.Options
instrumentOpts instrument.Options
identTag string
untimedRollups bool
waitForOffset bool
// Options for the test
autoMappingRules []m3.ClusterNamespaceOptions
sampleAppenderOpts *SampleAppenderOptions
remoteClientMock *client.MockClient
rulesConfig *RulesConfiguration
matcherConfig MatcherConfiguration
// Test ingest and expectations overrides
ingest *testDownsamplerOptionsIngest
expect *testDownsamplerOptionsExpect
}
type testDownsamplerOptionsIngest struct {
counterMetrics []testCounterMetric
gaugeMetrics []testGaugeMetric
timerMetrics []testTimerMetric
}
type testDownsamplerOptionsExpect struct {
writes []testExpectedWrite
allowFilter *testDownsamplerOptionsExpectAllowFilter
}
type testDownsamplerOptionsExpectAllowFilter struct {
attributes []storagemetadata.Attributes
}
func newTestDownsampler(t *testing.T, opts testDownsamplerOptions) testDownsampler {
if opts.expect == nil {
opts.expect = &testDownsamplerOptionsExpect{}
}
storage := mock.NewMockStorage()
rulesKVStore := mem.NewStore()
clockOpts := clock.NewOptions()
if opts.clockOpts != nil {
clockOpts = opts.clockOpts
}
// Use a test instrument options by default to get the debug logs on by default.
instrumentOpts := instrument.NewTestOptions(t)
if opts.instrumentOpts != nil {
instrumentOpts = opts.instrumentOpts
}
matcherOpts := matcher.NewOptions()
// Initialize the namespaces
_, err := rulesKVStore.Set(matcherOpts.NamespacesKey(), &rulepb.Namespaces{})
require.NoError(t, err)
rulesetKeyFmt := matcherOpts.RuleSetKeyFn()([]byte("%s"))
rulesStoreOpts := ruleskv.NewStoreOptions(matcherOpts.NamespacesKey(),
rulesetKeyFmt, nil)
rulesStore := ruleskv.NewStore(rulesKVStore, rulesStoreOpts)
tagEncoderOptions := serialize.NewTagEncoderOptions()
tagDecoderOptions := serialize.NewTagDecoderOptions(serialize.TagDecoderOptionsConfig{})
tagEncoderPoolOptions := pool.NewObjectPoolOptions().
SetSize(2).
SetInstrumentOptions(instrumentOpts.
SetMetricsScope(instrumentOpts.MetricsScope().
SubScope("tag-encoder-pool")))
tagDecoderPoolOptions := pool.NewObjectPoolOptions().
SetSize(2).
SetInstrumentOptions(instrumentOpts.
SetMetricsScope(instrumentOpts.MetricsScope().
SubScope("tag-decoder-pool")))
metricsAppenderPoolOptions := pool.NewObjectPoolOptions().
SetSize(2).
SetInstrumentOptions(instrumentOpts.
SetMetricsScope(instrumentOpts.MetricsScope().
SubScope("metrics-appender-pool")))
cfg := Configuration{
BufferPastLimits: []BufferPastLimitConfiguration{
{Resolution: 0, BufferPast: 500 * time.Millisecond},
},
}
if opts.remoteClientMock != nil {
// Optionally set an override to use remote aggregation
// with a mock client
cfg.RemoteAggregator = &RemoteAggregatorConfiguration{
clientOverride: opts.remoteClientMock,
}
}
if opts.rulesConfig != nil {
cfg.Rules = opts.rulesConfig
}
cfg.Matcher = opts.matcherConfig
cfg.UntimedRollups = opts.untimedRollups
instance, err := cfg.NewDownsampler(DownsamplerOptions{
Storage: storage,
ClusterClient: clusterclient.NewMockClient(gomock.NewController(t)),
RulesKVStore: rulesKVStore,
ClusterNamespacesWatcher: m3.NewClusterNamespacesWatcher(),
ClockOptions: clockOpts,
InstrumentOptions: instrumentOpts,
TagEncoderOptions: tagEncoderOptions,
TagDecoderOptions: tagDecoderOptions,
TagEncoderPoolOptions: tagEncoderPoolOptions,
TagDecoderPoolOptions: tagDecoderPoolOptions,
MetricsAppenderPoolOptions: metricsAppenderPoolOptions,
RWOptions: xio.NewOptions(),
TagOptions: models.NewTagOptions(),
})
require.NoError(t, err)
if len(opts.autoMappingRules) > 0 {
// Simulate the automapping rules being injected into the downsampler.
ctrl := gomock.NewController(t)
var mockNamespaces m3.ClusterNamespaces
for _, r := range opts.autoMappingRules {
n := m3.NewMockClusterNamespace(ctrl)
n.EXPECT().
Options().
Return(r).
AnyTimes()
mockNamespaces = append(mockNamespaces, n)
}
instance.(*downsampler).OnUpdate(mockNamespaces)
}
downcast, ok := instance.(*downsampler)
require.True(t, ok)
return testDownsampler{
opts: downcast.opts,
testOpts: opts,
downsampler: instance,
matcher: downcast.agg.matcher,
storage: storage,
rulesStore: rulesStore,
instrumentOpts: instrumentOpts,
}
}
func newTestID(t *testing.T, tags map[string]string) id.ID {
tagEncoderPool := serialize.NewTagEncoderPool(serialize.NewTagEncoderOptions(),
pool.NewObjectPoolOptions().SetSize(1))
tagEncoderPool.Init()
tagsIter := newTags()
for name, value := range tags {
tagsIter.append([]byte(name), []byte(value))
}
tagEncoder := tagEncoderPool.Get()
err := tagEncoder.Encode(tagsIter)
require.NoError(t, err)
data, ok := tagEncoder.Data()
require.True(t, ok)
size := 1
tagDecoderPool := serialize.NewTagDecoderPool(
serialize.NewTagDecoderOptions(serialize.TagDecoderOptionsConfig{
CheckBytesWrapperPoolSize: &size,
}),
pool.NewObjectPoolOptions().SetSize(size))
tagDecoderPool.Init()
tagDecoder := tagDecoderPool.Get()
iter := serialize.NewMetricTagsIterator(tagDecoder, nil)
iter.Reset(data.Bytes())
return iter
}
func findWrites(
writes []*storage.WriteQuery,
name, identTag string,
optionalMatchAttrs *storagemetadata.Attributes,
) ([]*storage.WriteQuery, bool) {
var results []*storage.WriteQuery
for _, w := range writes {
if t, ok := w.Tags().Get([]byte(identTag)); ok {
if !bytes.Equal(t, []byte(name)) {
// Does not match name.
continue
}
if optionalMatchAttrs != nil && w.Attributes() != *optionalMatchAttrs {
// Tried to match attributes and not matched.
continue
}
// Matches name and all optional lookups.
results = append(results, w)
}
}
return results, len(results) > 0
}
func testUpdateMetadata() rules.UpdateMetadata {
return rules.NewRuleSetUpdateHelper(0).NewUpdateMetadata(time.Now().UnixNano(), "test")
}
| [
"\"TEST_LOG_WRITES_ACCUMULATED\"",
"\"TEST_LOG_WRITES_MATCH\""
]
| []
| [
"TEST_LOG_WRITES_ACCUMULATED",
"TEST_LOG_WRITES_MATCH"
]
| [] | ["TEST_LOG_WRITES_ACCUMULATED", "TEST_LOG_WRITES_MATCH"] | go | 2 | 0 | |
src/controller/cmd/controller/main.go | package main
import (
"context"
"runtime"
"os"
stub "github.com/sap/infrabox/src/controller/pkg/stub"
sdk "github.com/operator-framework/operator-sdk/pkg/sdk"
k8sutil "github.com/operator-framework/operator-sdk/pkg/util/k8sutil"
sdkVersion "github.com/operator-framework/operator-sdk/version"
"github.com/sirupsen/logrus"
)
func printVersion() {
logrus.Infof("Go Version: %s", runtime.Version())
logrus.Infof("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH)
logrus.Infof("operator-sdk Version: %v", sdkVersion.Version)
}
func main() {
printVersion()
resource := "core.infrabox.net/v1alpha1"
namespace, err := k8sutil.GetWatchNamespace()
if err != nil {
logrus.Fatalf("Failed to get watch namespace: %v", err)
}
kind := os.Getenv("WATCH_KIND")
if len(kind) == 0 {
logrus.Fatalf("WATCH_KIND not set")
}
resyncPeriod := 5
sdk.Watch(resource, kind, namespace, resyncPeriod)
sdk.Handle(stub.NewHandler())
sdk.Run(context.TODO())
}
| [
"\"WATCH_KIND\""
]
| []
| [
"WATCH_KIND"
]
| [] | ["WATCH_KIND"] | go | 1 | 0 | |
api_ai/api.py | import os
import requests
import json
from . import logger
from .models import Intent, Entity
class ApiAi(object):
"""Interface for making and recieving API-AI requests.
Use the developer access token for managing entities and intents and the client access token for making queries.
"""
def __init__(self, dev_token=None, client_token=None):
self._dev_token = dev_token or os.getenv('DEV_ACCESS_TOKEN')
self._client_token = client_token or os.getenv('CLIENT_ACCESS_TOKEN')
self.versioning = '20161213'
self.base_url = 'https://api.api.ai/v1/'
if self._dev_token is None:
logger.warn(json.dumps("""No API.AI Developer Access Token set.
You will not be able to register or retrieve resources from API.AI"""))
if self._client_token is None:
logger.warn(json.dumps("""No API.AI Client Access Token set. You will be able to query the agent"""))
@property
def _dev_header(self):
return {'Authorization': 'Bearer {}'.format(self._dev_token),
'Content-Type': 'application/json'}
@property
def _client_header(self):
return {'Authorization': 'Bearer {}'.format(self._client_token),
'Content-Type': 'application/json; charset=utf-8'}
def _intent_uri(self, intent_id=''):
if intent_id != '':
intent_id = '/' + intent_id
return '{}intents{}?v={}'.format(self.base_url, intent_id, self.versioning)
def _entity_uri(self, entity_id=''):
if entity_id != '':
entity_id = '/' + entity_id
return '{}entities{}?v={}'.format(self.base_url, entity_id, self.versioning)
@property
def _query_uri(self):
return '{}query?v={}'.format(self.base_url, self.versioning)
def _get(self, endpoint):
response = requests.get(endpoint, headers=self._dev_header)
response.raise_for_status
logger.debug('Response from {}: {}'.format(endpoint, response))
return response.json()
def _post(self, endpoint, data):
response = requests.post(endpoint, headers=self._dev_header, data=data)
response.raise_for_status
return response.json()
def _put(self, endpoint, data):
response = requests.put(endpoint, headers=self._dev_header, data=data)
response.raise_for_status
return response.json()
## Intents ##
@property
def agent_intents(self):
"""Returns a list of intent json objects"""
endpoint = self._intent_uri()
intents = self._get(endpoint) # should be list of dicts
if isinstance(intents, dict): # if error: intents = {status: {error}}
raise Exception(intents['status'])
return [Intent(intent_json=i) for i in intents]
def get_intent(self, intent_id):
"""Returns the intent object with the given intent_id"""
endpoint = self._intent_uri(intent_id=intent_id)
return self._get(endpoint)
def post_intent(self, intent_json):
"""Sends post request to create a new intent"""
endpoint = self._intent_uri()
return self._post(endpoint, data=intent_json)
def put_intent(self, intent_id, intent_json):
"""Send a put request to update the intent with intent_id"""
endpoint = self._intent_uri(intent_id)
return self._put(endpoint, intent_json)
## Entities ##
@property
def agent_entities(self):
"""Returns a list of intent json objects"""
endpoint = self._entity_uri()
entities = self._get(endpoint) # should be list of dicts
if isinstance(entities, dict): # error: entities = {status: {error}}
raise Exception(entities['status'])
return [Entity(entity_json=i) for i in entities if isinstance(i, dict)]
def get_entity(self, entity_id):
endpoint = self._entity_uri(entity_id=entity_id)
return self._get(endpoint)
def post_entity(self, entity_json):
endpoint = self._entity_uri()
return self._post(endpoint, data=entity_json)
def put_entity(self, entity_id, entity_json):
endpoint = self._entity_uri(entity_id)
return self._put(endpoint, data=entity_json)
## Querying ##
def post_query(self, query, sessionID=None):
data = {
'query': query,
'sessionId': sessionID or '123',
'lang': 'en',
'contexts': [],
}
data = json.dumps(data)
response = requests.post(self._query_uri,
headers=self._client_header, data=data)
response.raise_for_status
return response
| []
| []
| [
"DEV_ACCESS_TOKEN",
"CLIENT_ACCESS_TOKEN"
]
| [] | ["DEV_ACCESS_TOKEN", "CLIENT_ACCESS_TOKEN"] | python | 2 | 0 | |
app.go | // ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
// 🤖 Github Repository: https://github.com/gofiber/fiber
// 📌 API Documentation: https://docs.gofiber.io
// Package fiber
// Fiber is an Express inspired web framework built on top of Fasthttp,
// the fastest HTTP engine for Go. Designed to ease things up for fast
// development with zero memory allocation and performance in mind.
package fiber
import (
"bufio"
"fmt"
"net"
"net/http"
"net/http/httputil"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"time"
"github.com/gofiber/fiber/v2/internal/colorable"
"github.com/gofiber/fiber/v2/internal/isatty"
"github.com/gofiber/fiber/v2/utils"
"github.com/valyala/fasthttp"
)
// Version of current fiber package
const Version = "2.0.5"
// Map is a shortcut for map[string]interface{}, useful for JSON returns
type Map map[string]interface{}
// Handler defines a function to serve HTTP requests.
type Handler = func(*Ctx) error
// ErrorHandler defines a function that will process all errors
// returned from any handlers in the stack
// cfg := fiber.Config{}
// cfg.ErrorHandler = func(c *Ctx, err error) error {
// code := StatusInternalServerError
// if e, ok := err.(*Error); ok {
// code = e.Code
// }
// c.Set(HeaderContentType, MIMETextPlainCharsetUTF8)
// return c.Status(code).SendString(err.Error())
// }
// app := fiber.New(cfg)
type ErrorHandler = func(*Ctx, error) error
// Error represents an error that occurred while handling a request.
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
}
// App denotes the Fiber application.
type App struct {
mutex sync.Mutex
// Route stack divided by HTTP methods
stack [][]*Route
// Route stack divided by HTTP methods and route prefixes
treeStack []map[string][]*Route
// Amount of registered routes
routesCount int
// Amount of registered handlers
handlerCount int
// Ctx pool
pool sync.Pool
// Fasthttp server
server *fasthttp.Server
// App config
config Config
}
// Config is a struct holding the server settings.
type Config struct {
// When set to true, this will spawn multiple Go processes listening on the same port.
//
// Default: false
Prefork bool `json:"prefork"`
// Enables the "Server: value" HTTP header.
//
// Default: ""
ServerHeader string `json:"server_header"`
// When set to true, the router treats "/foo" and "/foo/" as different.
// By default this is disabled and both "/foo" and "/foo/" will execute the same handler.
//
// Default: false
StrictRouting bool `json:"strict_routing"`
// When set to true, enables case sensitive routing.
// E.g. "/FoO" and "/foo" are treated as different routes.
// By default this is disabled and both "/FoO" and "/foo" will execute the same handler.
//
// Default: false
CaseSensitive bool `json:"case_sensitive"`
// When set to true, this relinquishes the 0-allocation promise in certain
// cases in order to access the handler values (e.g. request bodies) in an
// immutable fashion so that these values are available even if you return
// from handler.
//
// Default: false
Immutable bool `json:"immutable"`
// When set to true, converts all encoded characters in the route back
// before setting the path for the context, so that the routing can also
// work with urlencoded special characters.
//
// Default: false
UnescapePath bool `json:"unescape_path"`
// Enable or disable ETag header generation, since both weak and strong etags are generated
// using the same hashing method (CRC-32). Weak ETags are the default when enabled.
//
// Default: false
ETag bool `json:"etag"`
// Max body size that the server accepts.
// Default: 4 * 1024 * 1024
BodyLimit int `json:"body_limit"`
// Maximum number of concurrent connections.
//
// Default: 256 * 1024
Concurrency int `json:"concurrency"`
// Views is the interface that wraps the Render function.
//
// Default: nil
Views Views `json:"-"`
// The amount of time allowed to read the full request including body.
// It is reset after the request handler has returned.
// The connection's read deadline is reset when the connection opens.
//
// Default: unlimited
ReadTimeout time.Duration `json:"read_timeout"`
// The maximum duration before timing out writes of the response.
// It is reset after the request handler has returned.
//
// Default: unlimited
WriteTimeout time.Duration `json:"write_timeout"`
// The maximum amount of time to wait for the next request when keep-alive is enabled.
// If IdleTimeout is zero, the value of ReadTimeout is used.
//
// Default: unlimited
IdleTimeout time.Duration `json:"idle_timeout"`
// Per-connection buffer size for requests' reading.
// This also limits the maximum header size.
// Increase this buffer if your clients send multi-KB RequestURIs
// and/or multi-KB headers (for example, BIG cookies).
//
// Default: 4096
ReadBufferSize int `json:"read_buffer_size"`
// Per-connection buffer size for responses' writing.
//
// Default: 4096
WriteBufferSize int `json:"write_buffer_size"`
// CompressedFileSuffix adds suffix to the original file name and
// tries saving the resulting compressed file under the new file name.
//
// Default: ".fiber.gz"
CompressedFileSuffix string `json:"compressed_file_suffix"`
// ProxyHeader will enable c.IP() to return the value of the given header key
// By default c.IP() will return the Remote IP from the TCP connection
// This property can be useful if you are behind a load balancer: X-Forwarded-*
// NOTE: headers are easily spoofed and the detected IP addresses are unreliable.
//
// Default: ""
ProxyHeader string `json:"proxy_header"`
// GETOnly rejects all non-GET requests if set to true.
// This option is useful as anti-DoS protection for servers
// accepting only GET requests. The request size is limited
// by ReadBufferSize if GETOnly is set.
//
// Default: false
GETOnly bool `json:"get_only"`
// ErrorHandler is executed when an error is returned from fiber.Handler.
//
// Default: DefaultErrorHandler
ErrorHandler ErrorHandler `json:"-"`
// When set to true, disables keep-alive connections.
// The server will close incoming connections after sending the first response to client.
//
// Default: false
DisableKeepalive bool `json:"disable_keepalive"`
// When set to true, causes the default date header to be excluded from the response.
//
// Default: false
DisableDefaultDate bool `json:"disable_default_date"`
// When set to true, causes the default Content-Type header to be excluded from the response.
//
// Default: false
DisableDefaultContentType bool `json:"disable_default_content_type"`
// When set to true, disables header normalization.
// By default all header names are normalized: conteNT-tYPE -> Content-Type.
//
// Default: false
DisableHeaderNormalizing bool `json:"disable_header_normalizing"`
// When set to true, it will not print out the «Fiber» ASCII art and listening address.
//
// Default: false
DisableStartupMessage bool `json:"disable_startup_message"`
// FEATURE: v2.2.x
// The router executes the same handler by default if StrictRouting or CaseSensitive is disabled.
// Enabling RedirectFixedPath will change this behaviour into a client redirect to the original route path.
// Using the status code 301 for GET requests and 308 for all other request methods.
//
// Default: false
// RedirectFixedPath bool
}
// Static defines configuration options when defining static assets.
type Static struct {
// When set to true, the server tries minimizing CPU usage by caching compressed files.
// This works differently than the github.com/gofiber/compression middleware.
// Optional. Default value false
Compress bool `json:"compress"`
// When set to true, enables byte range requests.
// Optional. Default value false
ByteRange bool `json:"byte_range"`
// When set to true, enables directory browsing.
// Optional. Default value false.
Browse bool `json:"browse"`
// The name of the index file for serving a directory.
// Optional. Default value "index.html".
Index string `json:"index"`
}
// Default Config values
const (
DefaultBodyLimit = 4 * 1024 * 1024
DefaultConcurrency = 256 * 1024
DefaultReadBufferSize = 4096
DefaultWriteBufferSize = 4096
DefaultCompressedFileSuffix = ".fiber.gz"
)
// Default ErrorHandler that process return errors from handlers
var DefaultErrorHandler = func(c *Ctx, err error) error {
code := StatusInternalServerError
if e, ok := err.(*Error); ok {
code = e.Code
}
c.Set(HeaderContentType, MIMETextPlainCharsetUTF8)
return c.Status(code).SendString(err.Error())
}
// New creates a new Fiber named instance.
// app := fiber.New()
// You can pass optional configuration options by passing a Config struct:
// app := fiber.New(fiber.Config{
// Prefork: true,
// ServerHeader: "Fiber",
// })
func New(config ...Config) *App {
// Create a new app
app := &App{
// Create router stack
stack: make([][]*Route, len(intMethod)),
treeStack: make([]map[string][]*Route, len(intMethod)),
// Create Ctx pool
pool: sync.Pool{
New: func() interface{} {
return new(Ctx)
},
},
// Create config
config: Config{},
}
// Override config if provided
if len(config) > 0 {
app.config = config[0]
}
// Override default values
if app.config.BodyLimit <= 0 {
app.config.BodyLimit = DefaultBodyLimit
}
if app.config.Concurrency <= 0 {
app.config.Concurrency = DefaultConcurrency
}
if app.config.ReadBufferSize <= 0 {
app.config.ReadBufferSize = DefaultReadBufferSize
}
if app.config.WriteBufferSize <= 0 {
app.config.WriteBufferSize = DefaultWriteBufferSize
}
if app.config.CompressedFileSuffix == "" {
app.config.CompressedFileSuffix = DefaultCompressedFileSuffix
}
if app.config.Immutable {
getBytes, getString = getBytesImmutable, getStringImmutable
}
if app.config.ErrorHandler == nil {
app.config.ErrorHandler = DefaultErrorHandler
}
// Init app
app.init()
// Return app
return app
}
// Mount attaches another app instance as a subrouter along a routing path.
// It's very useful to split up a large API as many independent routers and
// compose them as a single service using Mount.
func (app *App) Mount(prefix string, fiber *App) Router {
stack := fiber.Stack()
for m := range stack {
for r := range stack[m] {
route := app.copyRoute(stack[m][r])
app.addRoute(route.Method, app.addPrefixToRoute(prefix, route))
}
}
return app
}
// Use registers a middleware route that will match requests
// with the provided prefix (which is optional and defaults to "/").
//
// app.Use(func(c *fiber.Ctx) error {
// return c.Next()
// })
// app.Use("/api", func(c *fiber.Ctx) error {
// return c.Next()
// })
// app.Use("/api", handler, func(c *fiber.Ctx) error {
// return c.Next()
// })
//
// This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...
func (app *App) Use(args ...interface{}) Router {
var prefix string
var handlers []Handler
for i := 0; i < len(args); i++ {
switch arg := args[i].(type) {
case string:
prefix = arg
case Handler:
handlers = append(handlers, arg)
default:
panic(fmt.Sprintf("use: invalid handler %v\n", reflect.TypeOf(arg)))
}
}
app.register(methodUse, prefix, handlers...)
return app
}
// Get registers a route for GET methods that requests a representation
// of the specified resource. Requests using GET should only retrieve data.
func (app *App) Get(path string, handlers ...Handler) Router {
return app.Add(MethodHead, path, handlers...).Add(MethodGet, path, handlers...)
}
// Head registers a route for HEAD methods that asks for a response identical
// to that of a GET request, but without the response body.
func (app *App) Head(path string, handlers ...Handler) Router {
return app.Add(MethodHead, path, handlers...)
}
// Post registers a route for POST methods that is used to submit an entity to the
// specified resource, often causing a change in state or side effects on the server.
func (app *App) Post(path string, handlers ...Handler) Router {
return app.Add(MethodPost, path, handlers...)
}
// Put registers a route for PUT methods that replaces all current representations
// of the target resource with the request payload.
func (app *App) Put(path string, handlers ...Handler) Router {
return app.Add(MethodPut, path, handlers...)
}
// Delete registers a route for DELETE methods that deletes the specified resource.
func (app *App) Delete(path string, handlers ...Handler) Router {
return app.Add(MethodDelete, path, handlers...)
}
// Connect registers a route for CONNECT methods that establishes a tunnel to the
// server identified by the target resource.
func (app *App) Connect(path string, handlers ...Handler) Router {
return app.Add(MethodConnect, path, handlers...)
}
// Options registers a route for OPTIONS methods that is used to describe the
// communication options for the target resource.
func (app *App) Options(path string, handlers ...Handler) Router {
return app.Add(MethodOptions, path, handlers...)
}
// Trace registers a route for TRACE methods that performs a message loop-back
// test along the path to the target resource.
func (app *App) Trace(path string, handlers ...Handler) Router {
return app.Add(MethodTrace, path, handlers...)
}
// Patch registers a route for PATCH methods that is used to apply partial
// modifications to a resource.
func (app *App) Patch(path string, handlers ...Handler) Router {
return app.Add(MethodPatch, path, handlers...)
}
// Add allows you to specify a HTTP method to register a route
func (app *App) Add(method, path string, handlers ...Handler) Router {
return app.register(method, path, handlers...)
}
// Static will create a file server serving static files
func (app *App) Static(prefix, root string, config ...Static) Router {
return app.registerStatic(prefix, root, config...)
}
// All will register the handler on all HTTP methods
func (app *App) All(path string, handlers ...Handler) Router {
for _, method := range intMethod {
_ = app.Add(method, path, handlers...)
}
return app
}
// Group is used for Routes with common prefix to define a new sub-router with optional middleware.
// api := app.Group("/api")
// api.Get("/users", handler)
func (app *App) Group(prefix string, handlers ...Handler) Router {
if len(handlers) > 0 {
app.register(methodUse, prefix, handlers...)
}
return &Group{prefix: prefix, app: app}
}
// Error makes it compatible with the `error` interface.
func (e *Error) Error() string {
return e.Message
}
// NewError creates a new Error instance with an optional message
func NewError(code int, message ...string) *Error {
e := &Error{
Code: code,
}
if len(message) > 0 {
e.Message = message[0]
} else {
e.Message = utils.StatusMessage(code)
}
return e
}
// Listener can be used to pass a custom listener.
func (app *App) Listener(ln net.Listener) error {
// Prefork is supported for custom listeners
if app.config.Prefork {
addr, tls := lnMetadata(ln)
return app.prefork(addr, tls)
}
// Print startup message
if !app.config.DisableStartupMessage {
app.startupMessage(ln.Addr().String(), false, "")
}
// TODO: Detect TLS
return app.server.Serve(ln)
}
// Listen serves HTTP requests from the given addr.
//
// app.Listen(":8080")
// app.Listen("127.0.0.1:8080")
func (app *App) Listen(addr string) error {
// Start prefork
if app.config.Prefork {
return app.prefork(addr, nil)
}
// Setup listener
ln, err := net.Listen("tcp4", addr)
if err != nil {
return err
}
// Print startup message
if !app.config.DisableStartupMessage {
app.startupMessage(ln.Addr().String(), false, "")
}
// Start listening
return app.server.Serve(ln)
}
// Config returns the app config as value ( read-only ).
func (app *App) Config() Config {
return app.config
}
// Handler returns the server handler.
func (app *App) Handler() fasthttp.RequestHandler {
return app.handler
}
// Stack returns the raw router stack.
func (app *App) Stack() [][]*Route {
return app.stack
}
// Shutdown gracefully shuts down the server without interrupting any active connections.
// Shutdown works by first closing all open listeners and then waiting indefinitely for all connections to return to idle and then shut down.
//
// Make sure the program doesn't exit and waits instead for Shutdown to return.
//
// Shutdown does not close keepalive connections so its recommended to set ReadTimeout to something else than 0.
func (app *App) Shutdown() error {
app.mutex.Lock()
defer app.mutex.Unlock()
if app.server == nil {
return fmt.Errorf("shutdown: server is not running")
}
return app.server.Shutdown()
}
// Server returns the underlying fasthttp server
func (app *App) Server() *fasthttp.Server {
return app.server
}
// Test is used for internal debugging by passing a *http.Request.
// Timeout is optional and defaults to 1s, -1 will disable it completely.
func (app *App) Test(req *http.Request, msTimeout ...int) (resp *http.Response, err error) {
// Set timeout
timeout := 1000
if len(msTimeout) > 0 {
timeout = msTimeout[0]
}
// Add Content-Length if not provided with body
if req.Body != http.NoBody && req.Header.Get(HeaderContentLength) == "" {
req.Header.Add(HeaderContentLength, strconv.FormatInt(req.ContentLength, 10))
}
// Dump raw http request
dump, err := httputil.DumpRequest(req, true)
if err != nil {
return nil, err
}
// Create test connection
conn := new(testConn)
// Write raw http request
if _, err = conn.r.Write(dump); err != nil {
return nil, err
}
// Serve conn to server
channel := make(chan error)
go func() {
channel <- app.server.ServeConn(conn)
}()
// Wait for callback
if timeout >= 0 {
// With timeout
select {
case err = <-channel:
case <-time.After(time.Duration(timeout) * time.Millisecond):
return nil, fmt.Errorf("test: timeout error %vms", timeout)
}
} else {
// Without timeout
err = <-channel
}
// Check for errors
if err != nil && err != fasthttp.ErrGetOnly {
return nil, err
}
// Read response
buffer := bufio.NewReader(&conn.w)
// Convert raw http response to *http.Response
return http.ReadResponse(buffer, req)
}
type disableLogger struct{}
func (dl *disableLogger) Printf(format string, args ...interface{}) {
// fmt.Println(fmt.Sprintf(format, args...))
}
func (app *App) init() *App {
// lock application
app.mutex.Lock()
// Only load templates if an view engine is specified
if app.config.Views != nil {
if err := app.config.Views.Load(); err != nil {
fmt.Printf("views: %v\n", err)
}
}
// create fasthttp server
app.server = &fasthttp.Server{
Logger: &disableLogger{},
LogAllErrors: false,
ErrorHandler: func(fctx *fasthttp.RequestCtx, err error) {
c := app.AcquireCtx(fctx)
if _, ok := err.(*fasthttp.ErrSmallBuffer); ok {
err = ErrRequestHeaderFieldsTooLarge
} else if netErr, ok := err.(*net.OpError); ok && netErr.Timeout() {
err = ErrRequestTimeout
} else if err == fasthttp.ErrBodyTooLarge {
err = ErrRequestEntityTooLarge
} else if err == fasthttp.ErrGetOnly {
err = ErrMethodNotAllowed
} else if strings.Contains(err.Error(), "timeout") {
err = ErrRequestTimeout
} else {
err = ErrBadRequest
}
if catch := app.config.ErrorHandler(c, err); catch != nil {
_ = c.SendStatus(StatusInternalServerError)
}
app.ReleaseCtx(c)
},
}
// fasthttp server settings
app.server.Handler = app.handler
app.server.Name = app.config.ServerHeader
app.server.Concurrency = app.config.Concurrency
app.server.NoDefaultDate = app.config.DisableDefaultDate
app.server.NoDefaultContentType = app.config.DisableDefaultContentType
app.server.DisableHeaderNamesNormalizing = app.config.DisableHeaderNormalizing
app.server.DisableKeepalive = app.config.DisableKeepalive
app.server.MaxRequestBodySize = app.config.BodyLimit
app.server.NoDefaultServerHeader = app.config.ServerHeader == ""
app.server.ReadTimeout = app.config.ReadTimeout
app.server.WriteTimeout = app.config.WriteTimeout
app.server.IdleTimeout = app.config.IdleTimeout
app.server.ReadBufferSize = app.config.ReadBufferSize
app.server.WriteBufferSize = app.config.WriteBufferSize
app.server.GetOnly = app.config.GETOnly
// unlock application
app.mutex.Unlock()
return app
}
func (app *App) startupMessage(addr string, tls bool, pids string) {
// ignore child processes
if IsChild() {
return
}
var logo string
logo += "\n%s"
logo += " ┌───────────────────────────────────────────────────┐\n"
logo += " │ %s │\n"
logo += " │ %s │\n"
logo += " │ │\n"
logo += " │ Handlers %s Threads %s │\n"
logo += " │ Prefork .%s PID ....%s │\n"
logo += " └───────────────────────────────────────────────────┘"
logo += "%s\n\n"
const (
cBlack = "\u001b[90m"
// cRed = "\u001b[91m"
cCyan = "\u001b[96m"
// cGreen = "\u001b[92m"
// cYellow = "\u001b[93m"
// cBlue = "\u001b[94m"
// cMagenta = "\u001b[95m"
// cWhite = "\u001b[97m"
cReset = "\u001b[0m"
)
value := func(s string, width int) string {
pad := width - len(s)
str := ""
for i := 0; i < pad; i++ {
str += "."
}
if s == "Disabled" {
str += " " + s
} else {
str += fmt.Sprintf(" %s%s%s", cCyan, s, cBlack)
}
return str
}
center := func(s string, width int) string {
pad := strconv.Itoa((width - len(s)) / 2)
str := fmt.Sprintf("%"+pad+"s", " ")
str += s
str += fmt.Sprintf("%"+pad+"s", " ")
if len(str) < width {
str += " "
}
return str
}
centerValue := func(s string, width int) string {
pad := strconv.Itoa((width - len(s)) / 2)
str := fmt.Sprintf("%"+pad+"s", " ")
str += fmt.Sprintf("%s%s%s", cCyan, s, cBlack)
str += fmt.Sprintf("%"+pad+"s", " ")
if len(str)-10 < width {
str += " "
}
return str
}
host, port := parseAddr(addr)
if host == "" || host == "0.0.0.0" {
host = "127.0.0.1"
}
addr = "http://" + host + ":" + port
if tls {
addr = "https://" + host + ":" + port
}
isPrefork := "Disabled"
if app.config.Prefork {
isPrefork = "Enabled"
}
out := colorable.NewColorableStdout()
if os.Getenv("TERM") == "dumb" || (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())) {
out = colorable.NewNonColorable(os.Stdout)
}
_, _ = fmt.Fprintf(out, logo,
cBlack,
centerValue(" Fiber v"+Version, 49),
center(addr, 49),
value(strconv.Itoa(app.handlerCount), 14), value(strconv.Itoa(runtime.NumCPU()), 14),
value(isPrefork, 14), value(strconv.Itoa(os.Getpid()), 14),
cReset,
)
}
| [
"\"TERM\""
]
| []
| [
"TERM"
]
| [] | ["TERM"] | go | 1 | 0 | |
vendor/k8s.io/apiextensions-apiserver/pkg/client/clientset/internalclientset/scheme/register.go | /*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package scheme
import (
os "os"
apiextensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/install"
announced "k8s.io/apimachinery/pkg/apimachinery/announced"
registered "k8s.io/apimachinery/pkg/apimachinery/registered"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
schema "k8s.io/apimachinery/pkg/runtime/schema"
serializer "k8s.io/apimachinery/pkg/runtime/serializer"
)
var Scheme = runtime.NewScheme()
var Codecs = serializer.NewCodecFactory(Scheme)
var ParameterCodec = runtime.NewParameterCodec(Scheme)
var Registry = registered.NewOrDie(os.Getenv("KUBE_API_VERSIONS"))
var GroupFactoryRegistry = make(announced.APIGroupFactoryRegistry)
func init() {
v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"})
Install(GroupFactoryRegistry, Registry, Scheme)
}
// Install registers the API group and adds types to a scheme
func Install(groupFactoryRegistry announced.APIGroupFactoryRegistry, registry *registered.APIRegistrationManager, scheme *runtime.Scheme) {
apiextensions.Install(groupFactoryRegistry, registry, scheme)
}
| [
"\"KUBE_API_VERSIONS\""
]
| []
| [
"KUBE_API_VERSIONS"
]
| [] | ["KUBE_API_VERSIONS"] | go | 1 | 0 | |
lib/webports/util.py | # Copyright 2014 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import fcntl
import hashlib
import os
import shutil
import subprocess
import sys
# Allow use of this module even if termcolor is missing. There are many
# standalone python scripts in build_tools that can be run directly without
# PYTHONPATH set (i.e. not via build/python_wrapper that adds this path.
# TODO(sbc): we should probably just assume that all the module dependencies
# are present.
try:
import termcolor
except ImportError:
termcolor = None
from webports import error, paths
GS_URL = 'http://storage.googleapis.com/'
GS_BUCKET = 'webports'
GS_MIRROR_URL = '%s%s/mirror' % (GS_URL, GS_BUCKET)
# Require the latest version of the NaCl SDK. webports is built
# and tested against the pepper_canary release. To build aginst older
# versions of the SDK use the one of the pepper_XX branches (or use
# --skip-sdk-version-check).
MIN_SDK_VERSION = 49
arch_to_pkgarch = {
'x86_64': 'x86-64',
'i686': 'i686',
'arm': 'arm',
'pnacl': 'pnacl',
'emscripten': 'emscripten',
'le32': 'le32'
}
# Inverse of arch_to_pkgarch
pkgarch_to_arch = {v: k for k, v in arch_to_pkgarch.items()}
LOG_ERROR = 0
LOG_WARN = 1
LOG_INFO = 2
LOG_VERBOSE = 3
LOG_TRACE = 4
ELF_MAGIC = '\x7fELF'
PEXE_MAGIC = 'PEXE'
log_level = LOG_INFO
color_mode = 'auto'
def colorize(message, color):
if termcolor and colorize.enabled:
return termcolor.colored(message, color)
else:
return message
def check_stdout_for_color_support():
if color_mode == 'auto':
colorize.enabled = sys.stdout.isatty()
def is_elf_file(filename):
if os.path.islink(filename):
return False
with open(filename) as f:
header = f.read(4)
return header == ELF_MAGIC
def is_pexe_file(filename):
if os.path.islink(filename):
return False
with open(filename) as f:
header = f.read(4)
return header == PEXE_MAGIC
def memoize(f):
"""Memoization decorator for functions taking one or more arguments."""
class Memo(dict):
def __init__(self, f):
super(Memo, self).__init__()
self.f = f
def __call__(self, *args):
return self[args]
def __missing__(self, key):
ret = self[key] = self.f(*key)
return ret
return Memo(f)
def set_verbose(enabled):
if enabled:
set_log_level(LOG_VERBOSE)
else:
set_log_level(LOG_INFO)
def set_log_level(verbosity):
global log_level
log_level = verbosity
def log(message, verbosity=LOG_INFO):
"""Log a message to the console (stdout)."""
if log_level < verbosity:
return
sys.stdout.write(str(message) + '\n')
sys.stdout.flush()
def log_heading(message, suffix=''):
"""Log a colored/highlighted message with optional suffix."""
if colorize.enabled:
log(colorize(message, 'green') + suffix)
else:
if log_level > LOG_WARN:
# When running in verbose mode make sure heading standout
log('###################################################################')
log(message + suffix)
log('###################################################################')
else:
log(message + suffix)
def warn(message):
log('warning: ' + message, LOG_WARN)
def trace(message):
log(message, LOG_TRACE)
def log_verbose(message):
log(message, LOG_VERBOSE)
def find_in_path(command_name):
"""Search user's PATH for a given executable.
Returns:
Full path to executable.
"""
extensions = ('',)
if not os.path.splitext(command_name)[1] and os.name == 'nt':
extensions = ('.bat', '.com', '.exe')
for path in os.environ.get('PATH', '').split(os.pathsep):
for ext in extensions:
full_name = os.path.join(path, command_name + ext)
if os.path.exists(full_name) and os.path.isfile(full_name):
return full_name
raise error.Error('command not found: %s' % command_name)
def download_file(filename, url):
"""Download a file from a given URL.
Args:
filename: the name of the file to download the URL to.
url: then URL to fetch.
"""
temp_filename = filename + '.partial'
# Ensure curl is in user's PATH
find_in_path('curl')
curl_cmd = ['curl', '--fail', '--location', '--stderr', '-', '-o',
temp_filename]
if hasattr(sys.stdout, 'fileno') and os.isatty(sys.stdout.fileno()):
# Add --progress-bar but only if stdout is a TTY device.
curl_cmd.append('--progress-bar')
else:
# otherwise suppress status output, since curl always assumes its
# talking to a TTY and writes \r and \b characters. But add
# --show-error so that when curl fails it at least prints something.
curl_cmd += ['--silent', '--show-error']
curl_cmd.append(url)
if log_level > LOG_WARN:
log('Downloading: %s [%s]' % (url, filename))
else:
log('Downloading: %s' % url.replace(GS_URL, ''))
try:
subprocess.check_call(curl_cmd)
except subprocess.CalledProcessError as e:
raise error.Error('Error downloading file: %s' % str(e))
os.rename(temp_filename, filename)
def check_stamp(filename, contents=None):
"""Check that a given stamp file is up-to-date.
Returns: False is the file does not exists or is older that that given
comparison file, or does not contain the given contents. True otherwise.
"""
if not os.path.exists(filename):
return False
if contents is not None:
with open(filename) as f:
if not f.read().startswith(contents):
return False
return True
@memoize
def get_sdk_root():
"""Returns the root of the currently configured Native Client SDK."""
root = os.environ.get('NACL_SDK_ROOT')
if root is None:
local_sdk_root = os.path.join(paths.OUT_DIR, 'nacl_sdk')
if os.path.exists(local_sdk_root):
root = local_sdk_root
else:
raise error.Error('$NACL_SDK_ROOT not set')
if sys.platform == "cygwin":
root = root.replace('\\', '/')
return root
@memoize
def get_emscripten_root():
emscripten = os.environ.get('EMSCRIPTEN')
if emscripten is None:
local_root = os.path.join(paths.OUT_DIR, 'emsdk', 'emscripten')
if os.path.exists(local_root):
emscripten = local_root
else:
raise error.Error('$EMSCRIPTEN not set and %s does not exist.' %
local_root)
if not os.path.isdir(emscripten):
raise error.Error('$EMSCRIPTEN environment variable does not point'
' to a directory: %s' % emscripten)
return emscripten
def setup_emscripten():
if 'EMSCRIPTEN' in os.environ:
return
local_root = get_emscripten_root()
os.environ['EMSCRIPTEN'] = local_root
os.environ['EM_CONFIG'] = os.path.join(
os.path.dirname(local_root), '.emscripten')
try:
find_in_path('node')
except error.Error:
node_bin = os.path.join(paths.OUT_DIR, 'node', 'bin')
if not os.path.isdir(node_bin):
raise error.Error(
'node not found in path and default path not found: %s' % node_bin)
os.environ['PATH'] += ':' + node_bin
find_in_path('node')
@memoize
def get_sdk_version():
"""Returns the version (as a string) of the current SDK."""
getos = os.path.join(get_sdk_root(), 'tools', 'getos.py')
version = subprocess.check_output([getos, '--sdk-version']).strip()
return version
def check_sdk_version(version):
"""Returns True if the currently configured SDK is 'version' or above."""
return int(get_sdk_version()) >= int(version)
@memoize
def get_sdk_revision():
"""Returns the revision of the currently configured Native Client SDK."""
getos = os.path.join(get_sdk_root(), 'tools', 'getos.py')
version = subprocess.check_output([getos, '--sdk-revision']).strip()
return int(version)
@memoize
def get_platform():
"""Returns the current platform name according getos.py."""
getos = os.path.join(get_sdk_root(), 'tools', 'getos.py')
platform = subprocess.check_output([getos]).strip()
return platform
@memoize
def get_toolchain_root(config):
"""Returns the toolchain folder for a given NaCl toolchain."""
if config.toolchain == 'emscripten':
return get_emscripten_root()
platform = get_platform()
if config.toolchain in ('pnacl', 'clang-newlib'):
tc_dir = os.path.join('%s_pnacl' % platform)
else:
tc_arch = {'arm': 'arm', 'i686': 'x86', 'x86_64': 'x86'}[config.arch]
tc_dir = '%s_%s_%s' % (platform, tc_arch, config.libc)
return os.path.join(get_sdk_root(), 'toolchain', tc_dir)
@memoize
def get_install_root(config):
"""Returns the install location given a build configuration."""
tc_dir = get_toolchain_root(config)
if config.toolchain == 'emscripten':
return os.path.join(tc_dir, 'system', 'local')
if config.toolchain == 'pnacl':
tc_dir = os.path.join(tc_dir, 'le32-nacl')
else:
tc_dir = os.path.join(tc_dir, '%s-nacl' % config.arch)
return os.path.join(tc_dir, 'usr')
@memoize
def get_install_stamp_root(config):
"""Returns the installation metadata folder for the give configuration."""
tc_root = get_install_root(config)
return os.path.join(tc_root, 'var', 'lib', 'npkg')
@memoize
def get_strip(config):
tc_dir = get_toolchain_root(config)
if config.toolchain == 'pnacl':
strip = os.path.join(tc_dir, 'bin', 'pnacl-strip')
else:
strip = os.path.join(tc_dir, 'bin', '%s-nacl-strip' % config.arch)
assert os.path.exists(strip), 'strip executable not found: %s' % strip
return strip
def get_install_stamp(package_name, config):
"""Returns the filename of the install stamp for for a given package.
This file is written at install time and contains metadata
about the installed package.
"""
root = get_install_stamp_root(config)
return os.path.join(root, package_name + '.info')
def get_list_file(package_name, config):
"""Returns the filename of the list of installed files for a given package.
This file is written at install time.
"""
root = get_install_stamp_root(config)
return os.path.join(root, package_name + '.list')
def is_installed(package_name, config, stamp_content=None):
"""Returns True if the given package is installed."""
stamp = get_install_stamp(package_name, config)
result = check_stamp(stamp, stamp_content)
return result
def check_sdk_root():
"""Check validity of NACL_SDK_ROOT."""
root = get_sdk_root()
if not os.path.isdir(root):
raise error.Error('$NACL_SDK_ROOT does not exist: %s' % root)
landmark = os.path.join(root, 'tools', 'getos.py')
if not os.path.exists(landmark):
raise error.Error("$NACL_SDK_ROOT (%s) doesn't look right. "
"Couldn't find landmark file (%s)" % (root, landmark))
if not check_sdk_version(MIN_SDK_VERSION):
raise error.Error(
'This version of webports requires at least version %s of\n'
'the NaCl SDK. The version in $NACL_SDK_ROOT is %s. If you want\n'
'to use webports with an older version of the SDK please checkout\n'
'one of the pepper_XX branches (or run with\n'
'--skip-sdk-version-check).' % (MIN_SDK_VERSION, get_sdk_version()))
def hash_file(filename):
"""Return the SHA1 (in hex format) of the contents of the given file."""
block_size = 100 * 1024
sha1 = hashlib.sha1()
with open(filename) as f:
while True:
data = f.read(block_size)
if not data:
break
sha1.update(data)
return sha1.hexdigest()
class HashVerificationError(error.Error):
pass
def verify_hash(filename, sha1):
"""Return True if the sha1 of the given file match the sha1 passed in."""
file_sha1 = hash_file(filename)
if sha1 != file_sha1:
raise HashVerificationError(
'verification failed: %s\nExpected: %s\nActual: %s' %
(filename, sha1, file_sha1))
def remove_tree(directory):
"""Recursively remove a directory and its contents."""
if not os.path.exists(directory):
return
if not os.path.isdir(directory):
raise error.Error('RemoveTree: not a directory: %s', directory)
shutil.rmtree(directory)
def rel_path(filename):
"""Return a pathname relative to the root the webports src tree.
This is used mostly to make output more readable when printing filenames."""
return os.path.relpath(filename, paths.NACLPORTS_ROOT)
def makedirs(directory):
if os.path.isdir(directory):
return
if os.path.exists(directory):
raise error.Error('mkdir: File exists and is not a directory: %s' %
directory)
trace("mkdir: %s" % directory)
os.makedirs(directory)
class DirLock(object):
"""Per-directory flock()-based context manager
This class will raise an exception if another process already holds the
lock for the given directory.
"""
def __init__(self, lock_dir):
if not os.path.exists(lock_dir):
makedirs(lock_dir)
self.file_name = os.path.join(lock_dir, 'webports.lock')
self.fd = open(self.file_name, 'w')
def __enter__(self):
try:
fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except Exception:
raise error.Error("Unable to acquire lock (%s): Is webports already "
"running?" % self.file_name)
def __exit__(self, exc_type, exc_val, exc_tb):
os.remove(self.file_name)
self.fd.close()
class BuildLock(DirLock):
"""Lock used when building a package (essentially a lock on OUT_DIR)"""
def __init__(self):
super(BuildLock, self).__init__(paths.OUT_DIR)
class InstallLock(DirLock):
"""Lock used when installing/uninstalling package"""
def __init__(self, config):
root = get_install_root(config)
super(InstallLock, self).__init__(root)
check_stdout_for_color_support()
| []
| []
| [
"NACL_SDK_ROOT",
"PATH",
"EMSCRIPTEN",
"EM_CONFIG"
]
| [] | ["NACL_SDK_ROOT", "PATH", "EMSCRIPTEN", "EM_CONFIG"] | python | 4 | 0 | |
openshift/gitops/manifests/configs/auth/base/merge_oauth_identity_providers.py | #!/usr/bin/env python
import json
import os
import sys
cluster_oauth = os.environ.get('CLUSTER_OAUTH_LOCATION', '/config/cluster-oauth.yaml')
gitops_oauth = os.environ.get('GITOPS_OAUTH_LOCATION', '/config/gitops-oauth.yaml')
gitops_idenity_providers = []
cluster_identity_providers = []
def read_json_file(filename):
with open(filename) as json_file:
return json.load(json_file)
def merge_identity_provider(cluster_identity_providers, gitops_provider):
for identity_provider_idx in range(len(cluster_identity_providers)):
if gitops_provider['name'] == cluster_identity_providers[identity_provider_idx]['name']:
cluster_identity_providers[identity_provider_idx] = gitops_provider
return
cluster_identity_providers.append(gitops_provider)
if not os.path.exists(cluster_oauth):
print("Cannot locate Cluster OAuth")
sys.exit(1)
if not os.path.exists(gitops_oauth):
print("GitOps Configuration File Not Found. Exiting")
sys.exit(0)
cluster_oauth_file = read_json_file(cluster_oauth)
gitops_oauth_file = read_json_file(gitops_oauth)
if 'identityProviders' in cluster_oauth_file['spec']:
cluster_identity_providers = cluster_oauth_file['spec']['identityProviders']
if 'identityProviders' in gitops_oauth_file['spec']:
gitops_identity_providers = gitops_oauth_file['spec']['identityProviders']
if len(gitops_identity_providers) > 0:
for gitops_identity_provider in gitops_identity_providers:
merge_identity_provider(cluster_identity_providers, gitops_identity_provider)
if len(cluster_identity_providers):
cluster_oauth_file['spec']['identityProviders'] = cluster_identity_providers
with open(cluster_oauth, 'w') as outfile:
json.dump(cluster_oauth_file, outfile)
| []
| []
| [
"CLUSTER_OAUTH_LOCATION",
"GITOPS_OAUTH_LOCATION"
]
| [] | ["CLUSTER_OAUTH_LOCATION", "GITOPS_OAUTH_LOCATION"] | python | 2 | 0 | |
cmd/kubeops/main.go | package main
import (
"context"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"syscall"
"time"
"github.com/gorilla/mux"
"github.com/heptiolabs/healthcheck"
"github.com/kubeapps/kubeapps/cmd/kubeops/internal/handler"
"github.com/kubeapps/kubeapps/pkg/agent"
appRepoHandler "github.com/kubeapps/kubeapps/pkg/apprepo"
"github.com/kubeapps/kubeapps/pkg/auth"
log "github.com/sirupsen/logrus"
"github.com/spf13/pflag"
"github.com/urfave/negroni"
"k8s.io/helm/pkg/helm/environment"
)
var (
settings environment.EnvSettings
assetsvcURL string
helmDriverArg string
userAgentComment string
listLimit int
timeout int64
)
func init() {
settings.AddFlags(pflag.CommandLine)
pflag.StringVar(&assetsvcURL, "assetsvc-url", "https://kubeapps-internal-assetsvc:8080", "URL to the internal assetsvc")
pflag.StringVar(&helmDriverArg, "helm-driver", "", "which Helm driver type to use")
pflag.IntVar(&listLimit, "list-max", 256, "maximum number of releases to fetch")
pflag.StringVar(&userAgentComment, "user-agent-comment", "", "UserAgent comment used during outbound requests")
// Default timeout from https://github.com/helm/helm/blob/b0b0accdfc84e154b3d48ec334cd5b4f9b345667/cmd/helm/install.go#L216
pflag.Int64Var(&timeout, "timeout", 300, "Timeout to perform release operations (install, upgrade, rollback, delete)")
}
func main() {
pflag.Parse()
settings.Init(pflag.CommandLine)
options := handler.Options{
ListLimit: listLimit,
Timeout: timeout,
}
storageForDriver := agent.StorageForSecrets
if helmDriverArg != "" {
var err error
storageForDriver, err = agent.ParseDriverType(helmDriverArg)
if err != nil {
panic(err)
}
}
withHandlerConfig := handler.WithHandlerConfig(storageForDriver, options)
r := mux.NewRouter()
// Healthcheck
// TODO: add app specific health and readiness checks as per https://github.com/heptiolabs/healthcheck
health := healthcheck.NewHandler()
r.Handle("/live", health)
r.Handle("/ready", health)
// Routes
// Auth not necessary here with Helm 3 because it's done by Kubernetes.
addRoute := handler.AddRouteWith(r.PathPrefix("/v1").Subrouter(), withHandlerConfig)
addRoute("GET", "/releases", handler.ListAllReleases)
addRoute("GET", "/namespaces/{namespace}/releases", handler.ListReleases)
addRoute("POST", "/namespaces/{namespace}/releases", handler.CreateRelease)
addRoute("GET", "/namespaces/{namespace}/releases/{releaseName}", handler.GetRelease)
addRoute("PUT", "/namespaces/{namespace}/releases/{releaseName}", handler.OperateRelease)
addRoute("DELETE", "/namespaces/{namespace}/releases/{releaseName}", handler.DeleteRelease)
// Backend routes unrelated to kubeops functionality.
appreposHandler, err := appRepoHandler.NewAppRepositoriesHandler(os.Getenv("POD_NAMESPACE"))
if err != nil {
log.Fatalf("Unable to create app repositories handler: %+v", err)
}
backendAPIv1 := r.PathPrefix("/backend/v1").Subrouter()
backendAPIv1.Methods("POST").Path("/apprepositories").Handler(negroni.New(
negroni.WrapFunc(appreposHandler.Create),
))
// assetsvc reverse proxy
authGate := auth.AuthGate()
parsedAssetsvcURL, err := url.Parse(assetsvcURL)
if err != nil {
log.Fatalf("Unable to parse the assetsvc URL: %v", err)
}
assetsvcProxy := httputil.NewSingleHostReverseProxy(parsedAssetsvcURL)
assetsvcPrefix := "/assetsvc"
assetsvcRouter := r.PathPrefix(assetsvcPrefix).Subrouter()
// Logos don't require authentication so bypass that step
assetsvcRouter.Methods("GET").Path("/v1/assets/{repo}/{id}/logo").Handler(negroni.New(
negroni.Wrap(http.StripPrefix(assetsvcPrefix, assetsvcProxy)),
))
assetsvcRouter.Methods("GET").Handler(negroni.New(
authGate,
negroni.Wrap(http.StripPrefix(assetsvcPrefix, assetsvcProxy)),
))
n := negroni.Classic()
n.UseHandler(r)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
addr := ":" + port
srv := &http.Server{
Addr: addr,
Handler: n,
}
go func() {
log.WithFields(log.Fields{"addr": addr}).Info("Started Kubeops")
err := srv.ListenAndServe()
if err != nil {
log.Info(err)
}
}()
// Catch SIGINT and SIGTERM
// Set up channel on which to send signal notifications.
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
log.Debug("Set system to get notified on signals")
s := <-c
log.Infof("Received signal: %v. Waiting for existing requests to finish", s)
// Set a timeout value high enough to let k8s terminationGracePeriodSeconds to act
// accordingly and send a SIGKILL if needed
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3600)
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
srv.Shutdown(ctx)
log.Info("All requests have been served. Exiting")
os.Exit(0)
}
| [
"\"POD_NAMESPACE\"",
"\"PORT\""
]
| []
| [
"POD_NAMESPACE",
"PORT"
]
| [] | ["POD_NAMESPACE", "PORT"] | go | 2 | 0 | |
vendor/github.com/kubernetes-incubator/service-catalog/vendor/github.com/coreos/go-systemd/daemon/sdnotify.go | // Copyright 2014 Docker, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code forked from Docker project
package daemon
import (
"net"
"os"
)
// SdNotify sends a message to the init daemon. It is common to ignore the error.
// If `unsetEnvironment` is true, the environment variable `NOTIFY_SOCKET`
// will be unconditionally unset.
//
// It returns one of the following:
// (false, nil) - notification not supported (i.e. NOTIFY_SOCKET is unset)
// (false, err) - notification supported, but failure happened (e.g. error connecting to NOTIFY_SOCKET or while sending data)
// (true, nil) - notification supported, data has been sent
func SdNotify(unsetEnvironment bool, state string) (sent bool, err error) {
socketAddr := &net.UnixAddr{
Name: os.Getenv("NOTIFY_SOCKET"),
Net: "unixgram",
}
// NOTIFY_SOCKET not set
if socketAddr.Name == "" {
return false, nil
}
if unsetEnvironment {
err = os.Unsetenv("NOTIFY_SOCKET")
}
if err != nil {
return false, err
}
conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr)
// Error connecting to NOTIFY_SOCKET
if err != nil {
return false, err
}
defer conn.Close()
_, err = conn.Write([]byte(state))
// Error sending the message
if err != nil {
return false, err
}
return true, nil
}
| [
"\"NOTIFY_SOCKET\""
]
| []
| [
"NOTIFY_SOCKET"
]
| [] | ["NOTIFY_SOCKET"] | go | 1 | 0 | |
cmd/fpga_crihook/main.go | // Copyright 2018 Intel Corporation. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/intel/intel-device-plugins-for-kubernetes/pkg/fpga"
"github.com/intel/intel-device-plugins-for-kubernetes/pkg/fpga/bitstream"
"github.com/pkg/errors"
utilsexec "k8s.io/utils/exec"
)
const (
fpgaBitStreamDirectory = "/srv/intel.com/fpga"
configJSON = "config.json"
fpgaRegionEnvPrefix = "FPGA_REGION_"
fpgaAfuEnvPrefix = "FPGA_AFU_"
annotationName = "com.intel.fpga.mode"
annotationValue = "fpga.intel.com/region"
)
// Stdin defines structure for standard JSONed input of the OCI platform hook
type Stdin struct {
Annotations struct {
ComIntelFpgaMode string `json:"com.intel.fpga.mode"`
} `json:"annotations"`
Bundle string `json:"bundle"`
}
// Config defines structure of OCI hook configuration
type Config struct {
Process struct {
Env []string `json:"env"`
} `json:"process"`
Linux struct {
Devices []Device `json:"devices"`
} `json:"linux"`
}
// Device defines structure for Config.Linux.Devices entries
type Device struct {
// these fields are set by the hook
name string
processed bool
// these are set by JSON decoder
Path string `json:"path"`
Type string `json:"type"`
Major int `json:"major"`
Minor int `json:"minor"`
UID int `json:"uid"`
Gid int `json:"gid"`
}
func (dev *Device) getName() string {
if len(dev.name) == 0 {
dev.name = filepath.Base(dev.Path)
}
return dev.name
}
func decodeJSONStream(reader io.Reader, dest interface{}) error {
decoder := json.NewDecoder(reader)
err := decoder.Decode(&dest)
return errors.WithStack(err)
}
type hookEnv struct {
bitstreamDir string
config string
execer utilsexec.Interface
}
type fpgaParams struct {
region string
afu string
portDevice string
}
func newHookEnv(bitstreamDir string, config string, execer utilsexec.Interface) *hookEnv {
return &hookEnv{
bitstreamDir: bitstreamDir,
config: config,
execer: execer,
}
}
func (he *hookEnv) getConfig(stdinJ *Stdin) (*Config, error) {
configPath := filepath.Join(stdinJ.Bundle, he.config)
configFile, err := os.Open(configPath)
if err != nil {
return nil, errors.WithStack(err)
}
defer configFile.Close()
var config Config
err = decodeJSONStream(configFile, &config)
if err != nil {
return nil, errors.WithMessage(err, "can't decode "+configPath)
}
if len(config.Process.Env) == 0 {
return nil, errors.Errorf("%s: process.env is empty", configPath)
}
if len(config.Linux.Devices) == 0 {
return nil, errors.Errorf("%s: linux.devices is empty", configPath)
}
return &config, nil
}
func (he *hookEnv) getFPGAParams(config *Config) ([]fpgaParams, error) {
// parse FPGA_REGION_N and FPGA_AFU_N environment variables
regionEnv := make(map[string]string)
afuEnv := make(map[string]string)
for _, env := range config.Process.Env {
splitted := strings.SplitN(env, "=", 2)
if strings.HasPrefix(splitted[0], fpgaRegionEnvPrefix) {
num := strings.Split(splitted[0], fpgaRegionEnvPrefix)[1]
regionEnv[num] = fpga.CanonizeID(splitted[1])
} else if strings.HasPrefix(splitted[0], fpgaAfuEnvPrefix) {
num := strings.Split(splitted[0], fpgaAfuEnvPrefix)[1]
afuEnv[num] = fpga.CanonizeID(splitted[1])
}
}
if len(regionEnv) == 0 {
return nil, errors.Errorf("No %s* environment variables are set", fpgaRegionEnvPrefix)
}
if len(afuEnv) == 0 {
return nil, errors.Errorf("No %s* environment variables are set", fpgaAfuEnvPrefix)
}
if len(afuEnv) != len(regionEnv) {
return nil, errors.Errorf("Environment variables %s* and %s* don't match", fpgaRegionEnvPrefix, fpgaAfuEnvPrefix)
}
params := []fpgaParams{}
for num, region := range regionEnv {
afu, ok := afuEnv[num]
if !ok {
return nil, errors.Errorf("Environment variable %s%s is not set", fpgaAfuEnvPrefix, num)
}
// Find a device suitable for the region/interface id
found := false
for _, dev := range config.Linux.Devices {
deviceName := dev.getName()
// skip non-FPGA devices
if !fpga.IsFpgaPort(deviceName) {
continue
}
// skip already processed devices
if dev.processed {
continue
}
port, err := fpga.NewPort(deviceName)
if err != nil {
return nil, err
}
if interfaceUUID := port.GetInterfaceUUID(); interfaceUUID == region {
params = append(params,
fpgaParams{
afu: afu,
region: interfaceUUID,
portDevice: deviceName,
},
)
dev.processed = true
found = true
break
}
}
if !found {
return nil, errors.Errorf("can't find appropriate device for region %s", region)
}
}
return params, nil
}
func getStdin(reader io.Reader) (*Stdin, error) {
var stdinJ Stdin
err := decodeJSONStream(reader, &stdinJ)
if err != nil {
return nil, err
}
// Check if device plugin annotation is set
if stdinJ.Annotations.ComIntelFpgaMode == "" {
return nil, fmt.Errorf("annotation %s is not set", annotationName)
}
// Check if device plugin annotation is set
if stdinJ.Annotations.ComIntelFpgaMode != annotationValue {
return nil, fmt.Errorf("annotation %s has incorrect value '%s'", annotationName, stdinJ.Annotations.ComIntelFpgaMode)
}
if stdinJ.Bundle == "" {
return nil, errors.New("'bundle' field is not set in the stdin JSON")
}
if _, err := os.Stat(stdinJ.Bundle); err != nil {
return nil, fmt.Errorf("bundle directory %s: stat error: %+v", stdinJ.Bundle, err)
}
return &stdinJ, nil
}
func (he *hookEnv) process(reader io.Reader) error {
stdin, err := getStdin(reader)
if err != nil {
return err
}
config, err := he.getConfig(stdin)
if err != nil {
return err
}
paramslist, err := he.getFPGAParams(config)
if err != nil {
return errors.WithMessage(err, "couldn't get FPGA region, AFU and device node")
}
for _, params := range paramslist {
port, err := fpga.NewPort(params.portDevice)
if err != nil {
return err
}
programmedAfu := port.GetAcceleratorTypeUUID()
if programmedAfu == params.afu {
// Afu is already programmed
return nil
}
bitstream, err := bitstream.GetFPGABitstream(he.bitstreamDir, params.region, params.afu)
if err != nil {
return err
}
defer bitstream.Close()
err = port.PR(bitstream, false)
if err != nil {
return err
}
programmedAfu = port.GetAcceleratorTypeUUID()
if programmedAfu != bitstream.AcceleratorTypeUUID() {
return errors.Errorf("programmed function %s instead of %s", programmedAfu, bitstream.AcceleratorTypeUUID())
}
}
return nil
}
func main() {
if os.Getenv("PATH") == "" { // runc doesn't set PATH when runs hooks
os.Setenv("PATH", "/sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin")
}
he := newHookEnv(fpgaBitStreamDirectory, configJSON, utilsexec.New())
if err := he.process(os.Stdin); err != nil {
fmt.Printf("%+v\n", err)
os.Exit(1)
}
}
| [
"\"PATH\""
]
| []
| [
"PATH"
]
| [] | ["PATH"] | go | 1 | 0 | |
azure-vote/azure-vote/main.py | import os
import socket
import redis
from flask import Flask, request, render_template
app = Flask(__name__)
# Load configurations from environment or config file
app.config.from_pyfile('config_file.cfg')
if ("VOTE1VALUE" in os.environ and os.environ['VOTE1VALUE']):
button1 = os.environ['VOTE1VALUE']
else:
button1 = app.config['VOTE1VALUE']
if ("VOTE2VALUE" in os.environ and os.environ['VOTE2VALUE']):
button2 = os.environ['VOTE2VALUE']
else:
button2 = app.config['VOTE2VALUE']
if ("TITLE" in os.environ and os.environ['TITLE']):
title = os.environ['TITLE']
else:
title = app.config['TITLE']
# Redis configurations
redis_server = os.environ['REDIS']
title2 = app.config['TITLE']
# Redis Connection
try:
if "REDIS_PWD" in os.environ:
r = redis.StrictRedis(host=redis_server,
port=6379,
password=os.environ['REDIS_PWD'])
else:
r = redis.Redis(redis_server)
r.ping()
except redis.ConnectionError:
exit('Failed to connect to Redis, terminating.')
# Change title to host name to demo NLB
if app.config['SHOWHOST'] == "true":
title = socket.gethostname()
# Init Redis
if not r.get(button1):
r.set(button1, 0)
if not r.get(button2):
r.set(button2, 0)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
# Get current values
vote1 = r.get(button1).decode('utf-8')
vote2 = r.get(button2).decode('utf-8')
# Return index with values
return render_template("index.html", value1=int(vote1), value2=int(vote2), button1=button1, button2=button2, title=title, title2=title2)
elif request.method == 'POST':
if request.form['vote'] == 'reset':
# Empty table and return results
r.set(button1, 0)
r.set(button2, 0)
vote1 = r.get(button1).decode('utf-8')
vote2 = r.get(button2).decode('utf-8')
return render_template("index.html", value1=int(vote1), value2=int(vote2), button1=button1, button2=button2, title=title, title2=title2)
else:
# Insert vote result into DB
vote = request.form['vote']
r.incr(vote, 1)
# Get current values
vote1 = r.get(button1).decode('utf-8')
vote2 = r.get(button2).decode('utf-8')
# Return results
return render_template("index.html", value1=int(vote1), value2=int(vote2), button1=button1, button2=button2, title=title, title2=title2)
if __name__ == "__main__":
app.run()
| []
| []
| [
"REDIS",
"TITLE",
"VOTE1VALUE",
"VOTE2VALUE",
"REDIS_PWD"
]
| [] | ["REDIS", "TITLE", "VOTE1VALUE", "VOTE2VALUE", "REDIS_PWD"] | python | 5 | 0 | |
tests/conftest.py | #
# Copyright 2017, Alexander Shorin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import datetime
import os
import pytest
import setuptools
from setuptools_changelog.changelog import ChangeLog
@pytest.fixture()
def distribution():
return setuptools.Distribution({
'author': 'John Doe',
'author_email': '[email protected]',
'description': 'long story short',
'install_requires': ['test==1.2.3'],
'keywords': ['foo', 'bar', 'baz'],
'license': 'BSD',
'long_description': 'long story long',
'name': 'simple',
'url': 'https://example.com',
'version': '0.0.0',
})
@pytest.fixture()
def make_changelog(distribution): # pylint: disable=redefined-outer-name
command = ChangeLog(distribution)
command.major_changes_types = {
'breaking': 'Breaking Changes'
}
command.minor_changes_types = {
'feature': 'New Features'
}
command.patch_changes_types = {
'bug': 'Bug Fixes'
}
def _make_changelog(**kwargs):
for key, value in kwargs.items():
assert hasattr(command, key)
setattr(command, key, value)
command.finalize_options()
return command
return _make_changelog
@pytest.fixture(scope='session')
def major_changes():
return os.path.join(os.path.dirname(__file__), 'major')
@pytest.fixture(scope='session')
def minor_changes():
return os.path.join(os.path.dirname(__file__), 'minor')
@pytest.fixture(scope='session')
def patch_changes():
return os.path.join(os.path.dirname(__file__), 'patch')
@pytest.fixture(scope='session')
def no_changes():
return os.path.join(os.path.dirname(__file__), 'empty')
@pytest.fixture(scope='session')
def today():
return datetime.datetime.now().date()
| []
| []
| []
| [] | [] | python | null | null | null |
netbox/client/dcim/dcim_device_types_create_responses.go | // Code generated by go-swagger; DO NOT EDIT.
// Copyright 2020 The go-netbox Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package dcim
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/netbox-community/go-netbox/netbox/models"
)
// DcimDeviceTypesCreateReader is a Reader for the DcimDeviceTypesCreate structure.
type DcimDeviceTypesCreateReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *DcimDeviceTypesCreateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 201:
result := NewDcimDeviceTypesCreateCreated()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
}
}
// NewDcimDeviceTypesCreateCreated creates a DcimDeviceTypesCreateCreated with default headers values
func NewDcimDeviceTypesCreateCreated() *DcimDeviceTypesCreateCreated {
return &DcimDeviceTypesCreateCreated{}
}
/*DcimDeviceTypesCreateCreated handles this case with default header values.
DcimDeviceTypesCreateCreated dcim device types create created
*/
type DcimDeviceTypesCreateCreated struct {
Payload *models.DeviceType
}
func (o *DcimDeviceTypesCreateCreated) Error() string {
return fmt.Sprintf("[POST /dcim/device-types/][%d] dcimDeviceTypesCreateCreated %+v", 201, o.Payload)
}
func (o *DcimDeviceTypesCreateCreated) GetPayload() *models.DeviceType {
return o.Payload
}
func (o *DcimDeviceTypesCreateCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.DeviceType)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
| []
| []
| []
| [] | [] | go | null | null | null |
goagen/codegen/workspace_test.go | package codegen_test
import (
"fmt"
"go/build"
"io/ioutil"
"os"
"path/filepath"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/shogo82148/goa-v1/goagen/codegen"
)
func abs(elems ...string) string {
r, err := filepath.Abs(filepath.Join(append([]string{""}, elems...)...))
if err != nil {
panic("abs: " + err.Error())
}
return r
}
// TODO: @shogo82148 GO111MODULE doesn't work correctly
var _ = Describe("Workspace", func() {
Describe("WorkspaceFor", func() {
oldGOPATH := build.Default.GOPATH
xx := abs("xx")
BeforeEach(func() {
os.Setenv("GOPATH", xx)
})
AfterEach(func() {
os.Setenv("GOPATH", oldGOPATH)
})
var (
err error
gopath string
)
Context("with GOMOD", func() {
var (
f *os.File
)
BeforeEach(func() {
f, err = os.OpenFile("go.mod", os.O_CREATE, 0755)
Ω(err).ShouldNot(HaveOccurred())
Ω(f.Close()).ShouldNot(HaveOccurred())
})
AfterEach(func() {
Ω(os.RemoveAll("go.mod")).ShouldNot(HaveOccurred())
})
Context("with GO111MODULE=auto", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Unsetenv("GO111MODULE")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a GOPATH mode workspace", func() {
workspace, err := codegen.WorkspaceFor(abs("", "xx", "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(workspace.Path).To(Equal(xx))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return a Module mode workspace", func() {
abs, err := filepath.Abs(".")
Ω(err).ShouldNot(HaveOccurred())
workspace, err := codegen.WorkspaceFor(abs)
Ω(err).ShouldNot(HaveOccurred())
Expect(workspace.Path).To(Equal(abs))
})
})
})
Context("with GO111MODULE=on", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Setenv("GO111MODULE", "on")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a Module mode workspace", func() {
abs, err := filepath.Abs(".")
Ω(err).ShouldNot(HaveOccurred())
workspace, err := codegen.WorkspaceFor(abs)
Ω(err).ShouldNot(HaveOccurred())
Expect(workspace.Path).To(Equal(abs))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return a Module mode workspace", func() {
abs, err := filepath.Abs(".")
Ω(err).ShouldNot(HaveOccurred())
workspace, err := codegen.WorkspaceFor(abs)
Ω(err).ShouldNot(HaveOccurred())
Expect(workspace.Path).To(Equal(abs))
})
})
})
Context("with GO111MODULE=off", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Setenv("GO111MODULE", "off")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a GOPATH mode workspace", func() {
workspace, err := codegen.WorkspaceFor(abs("", "xx", "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(workspace.Path).To(Equal(xx))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return an error", func() {
_, err := codegen.WorkspaceFor(abs("", "bar", "xx", "42"))
Ω(err).Should(Equal(fmt.Errorf(`Go source file "%s" not in Go workspace, adjust GOPATH %s or use modules`, abs("", "bar", "xx", "42"), gopath)))
})
})
})
})
Context("with no GOMOD", func() {
Context("with GO111MODULE=auto", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Unsetenv("GO111MODULE")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a GOPATH mode workspace", func() {
workspace, err := codegen.WorkspaceFor(abs("xx", "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(workspace.Path).To(Equal(abs("xx")))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return an error", func() {
_, err := codegen.WorkspaceFor(abs("bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
// Ω(err).Should(Equal(fmt.Errorf(`Go source file "%s" not in Go workspace, adjust GOPATH %s or use modules`, abs("bar", "xx", "42"), gopath)))
})
})
})
Context("with GO111MODULE=on", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Setenv("GO111MODULE", "on")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should not return an error", func() {
_, err := codegen.WorkspaceFor(abs("bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should not return an error", func() {
_, err := codegen.WorkspaceFor(abs("bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
})
})
})
Context("with GO111MODULE=off", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Setenv("GO111MODULE", "off")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a GOPATH mode workspace", func() {
workspace, err := codegen.WorkspaceFor(abs("xx", "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(workspace.Path).To(Equal(abs("xx")))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return an error", func() {
_, err := codegen.WorkspaceFor(abs("bar", "xx", "42"))
Ω(err).Should(Equal(fmt.Errorf(`Go source file "%s" not in Go workspace, adjust GOPATH %s or use modules`, abs("bar", "xx", "42"), gopath)))
})
})
})
})
})
Describe("PackageFor", func() {
oldGOPATH := build.Default.GOPATH
BeforeEach(func() {
os.Setenv("GOPATH", abs("xx"))
})
AfterEach(func() {
os.Setenv("GOPATH", oldGOPATH)
})
var (
err error
gopath string
)
Context("with GOMOD", func() {
var (
f *os.File
)
BeforeEach(func() {
f, err = os.OpenFile("go.mod", os.O_CREATE, 0755)
Ω(err).ShouldNot(HaveOccurred())
Ω(f.Close()).ShouldNot(HaveOccurred())
})
AfterEach(func() {
Ω(os.RemoveAll("go.mod")).ShouldNot(HaveOccurred())
})
Context("with GO111MODULE=auto", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Unsetenv("GO111MODULE")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a GOPATH mode package", func() {
pkg, err := codegen.PackageFor(abs("xx", "src", "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(pkg.Path).To(Equal("bar/xx"))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return a Module mode package", func() {
ab, err := filepath.Abs(".")
Ω(err).ShouldNot(HaveOccurred())
pkg, err := codegen.PackageFor(abs(ab, "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(pkg.Path).To(Equal("bar/xx"))
})
})
})
Context("with GO111MODULE=on", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Setenv("GO111MODULE", "on")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a Module mode package", func() {
ab, err := filepath.Abs(".")
Ω(err).ShouldNot(HaveOccurred())
pkg, err := codegen.PackageFor(abs(ab, "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(pkg.Path).To(Equal("bar/xx"))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return a Module mode package", func() {
ab, err := filepath.Abs(".")
Ω(err).ShouldNot(HaveOccurred())
pkg, err := codegen.PackageFor(abs(ab, "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(pkg.Path).To(Equal("bar/xx"))
})
})
})
Context("with GO111MODULE=off", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Setenv("GO111MODULE", "off")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a GOPATH mode package", func() {
pkg, err := codegen.PackageFor(abs("xx", "src", "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(pkg.Path).To(Equal("bar/xx"))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return an error", func() {
_, err := codegen.PackageFor(abs("bar", "xx", "42"))
Ω(err).Should(Equal(fmt.Errorf(`Go source file "%s" not in Go workspace, adjust GOPATH %s or use modules`, abs("bar", "xx", "42"), gopath)))
})
})
})
})
Context("with no GOMOD", func() {
Context("with GO111MODULE=auto", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Unsetenv("GO111MODULE")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a GOPATH mode package", func() {
pkg, err := codegen.PackageFor(abs("xx", "src", "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(pkg.Path).To(Equal("bar/xx"))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return an error", func() {
_, err := codegen.PackageFor(abs("bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
// Ω(err).Should(Equal(fmt.Errorf(`Go source file "%s" not in Go workspace, adjust GOPATH %s or use modules`, abs("bar", "xx", "42"), gopath)))
})
})
})
Context("with GO111MODULE=on", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Setenv("GO111MODULE", "on")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return an error", func() {
_, err := codegen.PackageFor(abs("bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
// Ω(err).Should(Equal(fmt.Errorf(`Go source file "%s" not in Go workspace, adjust GOPATH %s or use modules`, abs("bar", "xx", "42"), abs("xx"))))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return an error", func() {
_, err := codegen.PackageFor(abs("bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
// Ω(err).Should(Equal(fmt.Errorf(`Go source file "%s" not in Go workspace, adjust GOPATH %s or use modules`, abs("bar", "xx", "42"), gopath)))
})
})
})
Context("with GO111MODULE=off", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Setenv("GO111MODULE", "off")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a GOPATH mode package", func() {
pkg, err := codegen.PackageFor(abs("xx", "src", "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(pkg.Path).To(Equal("bar/xx"))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return an error", func() {
_, err := codegen.PackageFor(abs("bar", "xx", "42"))
Ω(err).Should(Equal(fmt.Errorf(`Go source file "%s" not in Go workspace, adjust GOPATH %s or use modules`, abs("bar", "xx", "42"), gopath)))
})
})
})
})
})
Describe("Package.Abs", func() {
var (
err error
gopath string
f *os.File
oldGOPATH = build.Default.GOPATH
oldGO111MODULE = os.Getenv("GO111MODULE")
)
BeforeEach(func() {
os.Setenv("GOPATH", "/xx")
f, err = os.OpenFile("go.mod", os.O_CREATE, 0755)
Ω(err).ShouldNot(HaveOccurred())
Ω(f.Close()).ShouldNot(HaveOccurred())
os.Unsetenv("GO111MODULE")
})
AfterEach(func() {
os.Setenv("GOPATH", oldGOPATH)
Ω(os.RemoveAll("go.mod")).ShouldNot(HaveOccurred())
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return the absolute path to the GOPATH directory", func() {
pkg, err := codegen.PackageFor(abs("xx", "src", "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(pkg.Abs()).To(Equal(abs("xx", "src", "bar", "xx")))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return the absolute path to the Module directory", func() {
ab, err := filepath.Abs(".")
Ω(err).ShouldNot(HaveOccurred())
pkg, err := codegen.PackageFor(abs(ab, "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(pkg.Abs()).To(Equal(abs(ab, "bar", "xx")))
})
})
})
Describe("PackagePath", func() {
oldGOPATH := build.Default.GOPATH
BeforeEach(func() {
os.Setenv("GOPATH", abs("xx"))
})
AfterEach(func() {
os.Setenv("GOPATH", oldGOPATH)
})
var (
err error
gopath string
)
Context("with GOMOD", func() {
var (
f *os.File
)
BeforeEach(func() {
f, err = os.OpenFile("go.mod", os.O_CREATE, 0755)
Ω(err).ShouldNot(HaveOccurred())
Ω(f.Close()).ShouldNot(HaveOccurred())
})
AfterEach(func() {
Ω(os.RemoveAll("go.mod")).ShouldNot(HaveOccurred())
})
Context("with GO111MODULE=auto", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Unsetenv("GO111MODULE")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a GOPATH mode package path", func() {
p, err := codegen.PackagePath(abs("xx", "src", "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(p).To(Equal("bar/xx/42"))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return a Module mode package path", func() {
ab, err := filepath.Abs(".")
Ω(err).ShouldNot(HaveOccurred())
p, err := codegen.PackagePath(abs(ab, "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(p).To(Equal("bar/xx/42"))
})
})
})
Context("with GO111MODULE=on", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Setenv("GO111MODULE", "on")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a Module mode package path", func() {
ab, err := filepath.Abs(".")
Ω(err).ShouldNot(HaveOccurred())
p, err := codegen.PackagePath(abs(ab, "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(p).To(Equal("bar/xx/42"))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return a Module mode package path", func() {
ab, err := filepath.Abs(".")
Ω(err).ShouldNot(HaveOccurred())
p, err := codegen.PackagePath(abs(ab, "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(p).To(Equal("bar/xx/42"))
})
})
})
Context("with GO111MODULE=off", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Setenv("GO111MODULE", "off")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a GOPATH mode package path", func() {
p, err := codegen.PackagePath(abs("xx", "src", "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(p).To(Equal("bar/xx/42"))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return an error", func() {
_, err := codegen.PackagePath(abs("bar", "xx", "42"))
Ω(err).Should(Equal(fmt.Errorf("%s does not contain a Go package", abs("bar", "xx", "42"))))
})
})
})
})
Context("with no GOMOD", func() {
Context("with GO111MODULE=auto", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Unsetenv("GO111MODULE")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a GOPATH mode package path", func() {
p, err := codegen.PackagePath(abs("xx", "src", "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(p).To(Equal("bar/xx/42"))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return an error", func() {
_, err := codegen.PackagePath(abs("bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
// Ω(err).Should(Equal(fmt.Errorf("%s does not contain a Go package", abs("bar", "xx", "42"))))
})
})
})
Context("with GO111MODULE=on", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Setenv("GO111MODULE", "on")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return an error", func() {
_, err := codegen.PackagePath(abs("bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
// Ω(err).Should(Equal(fmt.Errorf("%s does not contain a Go package", abs("bar", "xx", "42"))))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return an error", func() {
_, err := codegen.PackagePath(abs("bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
// Ω(err).Should(Equal(fmt.Errorf("%s does not contain a Go package", abs("bar", "xx", "42"))))
})
})
})
Context("with GO111MODULE=off", func() {
oldGO111MODULE := os.Getenv("GO111MODULE")
BeforeEach(func() {
os.Setenv("GO111MODULE", "off")
})
AfterEach(func() {
os.Setenv("GO111MODULE", oldGO111MODULE)
})
Context("inside GOPATH", func() {
It("should return a GOPATH mode package path", func() {
p, err := codegen.PackagePath(abs("xx", "src", "bar", "xx", "42"))
Ω(err).ShouldNot(HaveOccurred())
Expect(p).To(Equal("bar/xx/42"))
})
})
Context("outside GOPATH", func() {
BeforeEach(func() {
gopath, err = ioutil.TempDir(".", "go")
Ω(err).ShouldNot(HaveOccurred())
os.Setenv("GOPATH", gopath)
})
AfterEach(func() {
Ω(os.RemoveAll(gopath)).ShouldNot(HaveOccurred())
})
It("should return an error", func() {
_, err := codegen.PackagePath(abs("bar", "xx", "42"))
Ω(err).Should(Equal(fmt.Errorf("%s does not contain a Go package", abs("bar", "xx", "42"))))
})
})
})
})
})
})
| [
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\"",
"\"GO111MODULE\""
]
| []
| [
"GO111MODULE"
]
| [] | ["GO111MODULE"] | go | 1 | 0 | |
Validation/Performance/scripts/cmsBenchmark.py | #!/usr/bin/env python
"""
Usage: ./cmsBenchmark.py [options]
Options:
--cpu=... specify the core on which to run the performance suite
--cores=... specify the number of cores of the machine (can be used with 0 to stop cmsScimark from running on the other cores)
-n ..., --numevts specify the number of events for each tests/each candle/each step
--candle=... specify the candle to run instead of all the 7 candles of the suite
--step=... specify the step to run instead of all steps of the suite
--repeat=... specify the number of times to re-run the whole suite
-h, --help show this help
-d show debugging information
Legal entries for individual candles (--candle option):
HiggsZZ4LM190
MinBias
SingleElectronE1000
SingleMuMinusPt10
SinglePiMinusE1000
TTbar
QCD_80_120
Legal entries for specific tests (--step option):
GEN
SIM
DIGI
L1
DIGI2RAW
HLT
RAW2DIGI
RECO
and combinations of steps like:
GEN-SIM
L1-DIGI2RAW-HLT
DIGI2RAW-RAW2DIGI
and sequences of steps or combinations of steps like:
GEN-SIM,DIGI,L1-DIGI2RAW-RAW2DIGI,RECO
Note: when the necessary pre-steps are omitted, cmsPerfSuite.py will take care of it.
Examples:
./cmsBenchmark.py
This will run with the default options --cpu=1, --cores=4, --numevts=100, --step=GEN-SIM,DIGI,RECO --repeat=1 (Note: all results will be reported in a directory called Run1).
OR
./cmsBenchmark.py --cpu=2
This will run the test on core cpu2.
OR
./cmsBenchmark.py --cpu=0,1 --cores=8 -n 200
This will run the suite with 200 events for all tests/candles/step, on cores cpu0 and cpu1 simulataneously, while running the cmsScimark benchmarks on the other 6 cores.
OR
./cmsBenchmark.py --cores=8 --repeat=10 --candle QCD_80_120
This will run the performance tests only on candle QCD_80_120, running 100 evts for all steps, and it will repeat these tests 10 times, saving the results in 10 separate directories (each called RunN, with N=1,..,10) to check for systematic/statistical uncertainties. Note that by default --repeat=1, so all results will be in a directory called Run1.
OR
./cmsBenchmark.py --step=GEN-SIM,DIGI,RECO
This will run the performance tests only for the steps "GEN,SIM" (at once), "DIGI" and "RECO" taking care of running the necessary intermediate steps to make sure all steps can be run.
"""
from __future__ import print_function
import os
#Get some environment variables to use
cmssw_base=os.environ["CMSSW_BASE"]
cmssw_release_base=os.environ["CMSSW_RELEASE_BASE"]
cmssw_version=os.environ["CMSSW_VERSION"]
host=os.environ["HOST"]
user=os.environ["USER"]
#Performance suites script used:
Script="cmsPerfSuite.py"
#Options handling
import getopt
import sys
def usage():
print(__doc__)
def main(argv):
#Some default values:
#Number of cpu cores on the machine
coresOption="4"
cores=" --cores=4"
#Cpu core(s) on which the suite is run:
cpuOption=(1) #not necessary to use tuple for single cpu, but for type consistency use ().
cpu=" --cpu=1"
#Number of events per test (per candle/per step):
numevtsOption="100"
numevts=" --timesize=100"
#default benchmark does not run igprof nor valgrind
igprofevts=" --igprof=0"
valgrindevts=" --valgrind=0"
#Default option for candle is "" since, usually all 7 candles of the suite will be run!
candleOption=""
candle=""
#Default option for step is ["GEN,SIM","DIGI","RECO"] since we don't need to profile all steps of the suite
stepOption="GEN-SIM,DIGI,RECO"
step=" --step="+stepOption
#Default option for repeat
repeatOption=1 #Use integer here since it will be used directly in the script
#Let's check the command line arguments
try:
opts, args = getopt.getopt(argv, "n:hd", ["cpu=","cores=","numevts=","candle=","step=","repeat=","help"])
except getopt.GetoptError:
print("This argument option is not accepted")
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt == '-d':
global _debug
_debug = 1
elif opt == "--cpu":
cpuOption=arg
cpus=cpuOption.split(",")
cpu=" --cpu="+cpuOption
elif opt == "--cores":
coresOption = arg
elif opt in ("-n", "--numevts"):
numevtsOption = arg
numevts=" --timesize="+arg
elif opt == "--candle":
candleOption = arg
candle=" --candle="+arg
elif opt == "--step":
stepOption = arg
steps=stepOption.split(",")
elif opt == "--repeat":
repeatOption = int(arg)
#Case with no arguments (using defaults)
if opts == []:
print("No arguments given, so DEFAULT test will be run:")
#Print a time stamp at the beginning:
import time
date=time.ctime()
path=os.path.abspath(".")
print("CMS Benchmarking started running at %s on %s in directory %s, run by user %s" % (date,host,path,user))
#showtags=os.popen4("showtags -r")[1].read()
#print showtags
#For the log:
print("This machine (%s) is assumed to have %s cores, and the suite will be run on cpu(s) %s" %(host,coresOption,cpuOption))
print("%s events per test will be run" % numevtsOption)
if candleOption !="":
print("Running only %s candle, instead of all the candles in the performance suite" % candleOption)
if stepOption != "":
print("Profiling only the following steps: %s" % stepOption)
step=" --step="+stepOption
#This "unpacking" of the steps is better done in cmsPerfSuite.py or the cmsSimPyRelVal.py (.pl for now)
#steps=stepOption.split(",")
#cmsPerfSuiteSteps=[]
#for step in steps:
# newstep=reduce(lambda a,b:a+","+b,step.split("-"))
# cmsPerfSuiteSteps.append(newstep)
if repeatOption !=1:
print("The benchmarking will be repeated %s times" % repeatOption)
#Now let's play!
for repetition in range(repeatOption):
mkdircdcmd="mkdir Run"+str(repetition+1)+";cd Run"+str(repetition+1)
#mkdircdstdout=os.popen4(mkdircmd)[1].read()
#if mkdirstdout:
# print mkdirstdout,
#print "Here we'd launch cmsPerfSuite.py!"
PerfSuitecmd="cmsPerfSuite.py" + cpu + cores + numevts + igprofevts + valgrindevts + candle + step + ">& cmsPerfSuiteRun" + str(repetition + 1) + ".log"
launchcmd=mkdircdcmd+";"+PerfSuitecmd
print(launchcmd)
sys.stdout.flush()
#Obsolete popen4-> subprocess.Popen
#launchcmdstdout=os.popen4(launchcmd)[1].read()
launchcmdstdout=Popen(launchcmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT).stdout.read()
print(launchcmdstdout)
if __name__ == "__main__":
main(sys.argv[1:])
| []
| []
| [
"HOST",
"CMSSW_BASE",
"CMSSW_RELEASE_BASE",
"USER",
"CMSSW_VERSION"
]
| [] | ["HOST", "CMSSW_BASE", "CMSSW_RELEASE_BASE", "USER", "CMSSW_VERSION"] | python | 5 | 0 | |
examples/notes/create/createANote/main.go | package main
import (
"fmt"
"os"
"go.m3o.com"
"go.m3o.com/notes"
)
func main() {
client := m3o.New(os.Getenv("M3O_API_TOKEN"))
rsp, err := client.Notes.Create(¬es.CreateRequest{
Title: "New Note",
Text: "This is my note",
})
fmt.Println(rsp, err)
}
| [
"\"M3O_API_TOKEN\""
]
| []
| [
"M3O_API_TOKEN"
]
| [] | ["M3O_API_TOKEN"] | go | 1 | 0 | |
dashboard/settings.py | import os
from collections import OrderedDict
from datetime import timedelta
import raven
import raven.contrib.celery
from django.utils.translation import gettext_lazy as _
__version__ = '0.0.0'
"""
Django settings for dashboard project.
Generated by 'django-admin startproject' using Django 2.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SETTINGS_PATH = os.path.normpath(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# The routine validate_keys_are_changed is run in production and will prevent the default keys to be used.
SECRET_KEY: str = os.environ.get('SECRET_KEY', '_dzlo^9d#ox6!7c9rju@=u8+4^sprqocy3s*l*ejc2yr34@&98')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG', False)
if DEBUG:
print('Django debugging is enabled.')
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost,127.0.0.1,::1').split(',')
# Application definition
INSTALLED_APPS = [
# Constance
'constance',
'constance.backends.database',
# Jet
'jet.dashboard',
'jet',
'nested_admin',
# Import Export
'import_export',
# Standard Django
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
# Periodic tasks
'django_celery_beat',
# Web Security Map (todo: minimize the subset)
# The reason (model) why it's included is in the comments.
'websecmap.app', # Job
'websecmap.organizations', # Url
'websecmap.scanners', # Endpoint, EndpointGenericScan, UrlGenericScan
'websecmap.reporting', # Various reporting functions (might be not needed)
'websecmap.map', # because some scanners are intertwined with map configurations. That needs to go.
'websecmap.pro', # some model inlines
# Custom Apps
# These apps overwrite whatever is declared above, for example the user information.
# Yet, it does not overwrite management commands.
'dashboard.internet_nl_dashboard',
# Two factor auth
'django_otp',
'django_otp.plugins.otp_static',
'django_otp.plugins.otp_totp',
'two_factor',
# Javascript and CSS compression:
'compressor',
# Django activity stream
# https://django-activity-stream.readthedocs.io/en/latest/installation.html
'django.contrib.sites',
'actstream',
]
# django activity stream wants a site-id:
SITE_ID = 1
try:
# hack to disable django_uwsgi app as it currently conflicts with compressor
# https://github.com/django-compressor/django-compressor/issues/881
if not os.environ.get('COMPRESS', False):
import django_uwsgi # NOQA
INSTALLED_APPS += ['django_uwsgi', ]
except ImportError:
# only configure uwsgi app if installed (ie: production environment)
pass
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
# Two factor Auth
'django_otp.middleware.OTPMiddleware',
]
ROOT_URLCONF = 'dashboard.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR + '/',
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'constance.context_processors.config',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'dashboard.internet_nl_dashboard.context_processors.template_settings_processor',
],
},
},
]
WSGI_APPLICATION = 'dashboard.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASE_OPTIONS = {
'mysql': {'init_command': "SET character_set_connection=utf8,"
"collation_connection=utf8_unicode_ci,"
"sql_mode='STRICT_ALL_TABLES';"},
}
DB_ENGINE = os.environ.get('DB_ENGINE', 'mysql')
DATABASE_ENGINES = {
'mysql': 'dashboard.app.backends.mysql',
}
DATABASES_SETTINGS = {
# persisten local database used during development (runserver)
'dev': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.environ.get('DB_NAME', 'db.sqlite3'),
},
# sqlite memory database for running tests without
'test': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.environ.get('DB_NAME', 'db.sqlite3'),
},
# for production get database settings from environment (eg: docker)
'production': {
'ENGINE': DATABASE_ENGINES.get(DB_ENGINE, 'django.db.backends.' + DB_ENGINE),
'NAME': os.environ.get('DB_NAME', 'dashboard'),
'USER': os.environ.get('DB_USER', 'dashboard'),
'PASSWORD': os.environ.get('DB_PASSWORD', 'dashboard'),
'HOST': os.environ.get('DB_HOST', 'mysql'),
'OPTIONS': DATABASE_OPTIONS.get(os.environ.get('DB_ENGINE', 'mysql'), {})
}
}
# allow database to be selected through environment variables
DATABASE = os.environ.get('DJANGO_DATABASE', 'dev')
DATABASES = {'default': DATABASES_SETTINGS[DATABASE]}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOCALE_PATHS = ['locale']
LANGUAGE_COOKIE_NAME = 'dashboard_language'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
# Absolute path to aggregate to and serve static file from.
if DEBUG:
STATIC_ROOT = 'static'
else:
STATIC_ROOT = os.environ.get('STATIC_ROOT', '/srv/dashboard/static/') # noqa
MEDIA_ROOT = os.environ.get('MEDIA_ROOT', os.path.abspath(os.path.dirname(__file__)) + '/uploads/')
UPLOAD_ROOT: str = os.environ.get('MEDIA_ROOT', os.path.abspath(os.path.dirname(__file__)) + '/uploads/')
# Two factor auth
LOGIN_URL = "two_factor:login"
LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = LOGIN_URL
TWO_FACTOR_QR_FACTORY = 'qrcode.image.pil.PilImage'
# 6 supports google authenticator
TWO_FACTOR_TOTP_DIGITS = 6
TWO_FACTOR_PATCH_ADMIN = True
# Encrypted fields
# Note that this key is not stored in the database, that would be a security risk.
# The key can be generated with the following routine:
# https://cryptography.io/en/latest/fernet/
# from cryptography.fernet import Fernet
# Fernet.generate_key()
# Make sure you remove the b' and ' from the string, so you're working with a string.
# For example: b'JjvHNnFMfEaGd7Y0SAHBRNZYGGpNs7ydEp-ixmKSvkQ=' becomes
# JjvHNnFMfEaGd7Y0SAHBRNZYGGpNs7ydEp-ixmKSvkQ=
# Also note that on the production server a different key is required, otherwise the server will not start.
# See dashboard_prdserver for more details.
# The routine validate_keys_are_changed is run in production and will prevent the default keys to be used.
IMPORTED_FIELD_ENCRYPTION_KEY: str = os.environ.get('FIELD_ENCRYPTION_KEY',
"JjvHNnFMfEaGd7Y0SAHBRNZYGGpNs7ydEp-ixmKSvkQ=")
# The encryption key under ENV variables can only be stored as a string. This means we'll have to parse it to bytes.
FIELD_ENCRYPTION_KEY: bytes = IMPORTED_FIELD_ENCRYPTION_KEY.encode()
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler', # sys.stdout
'formatter': 'color',
},
},
'formatters': {
'debug': {
'format': '%(asctime)s\t%(levelname)-8s - %(filename)-20s:%(lineno)-4s - '
'%(funcName)20s() - %(message)s',
},
'color': {
'()': 'colorlog.ColoredFormatter',
'format': '%(log_color)s%(asctime)s\t%(levelname)-8s - '
'%(message)s',
'datefmt': '%Y-%m-%d %H:%M',
'log_colors': {
'DEBUG': 'green',
'INFO': 'white',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
},
}
},
'loggers': {
# Used when there is no log defined or loaded. Disabled given we always use __package__ to log.
# Would you enable it, all logging messages will be logged twice.
# '': {
# 'handlers': ['console'],
# 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
# },
# Default Django logging, we expect django to work, and therefore only show INFO messages.
# It can be smart to sometimes want to see what's going on here, but not all the time.
# https://docs.djangoproject.com/en/2.1/topics/logging/#django-s-logging-extensions
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
},
'celery.app.trace': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
},
# We expect to be able to debug websecmap all of the time.
'dashboard': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
},
'websecmap': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
},
'test': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
},
},
}
# settings to get WebSecMap to work:
# Celery 4.0 settings
# Pickle can work, but you need to use certificates to communicate (to verify the right origin)
# It's preferable not to use pickle, yet it's overly convenient as the normal serializer can not
# even serialize dicts.
# http://docs.celeryproject.org/en/latest/userguide/configuration.html
CELERY_accept_content = ['pickle', 'yaml']
CELERY_task_serializer = 'pickle'
CELERY_result_serializer = 'pickle'
# Celery config
CELERY_BROKER_URL = os.environ.get('BROKER', 'redis://localhost:6379/0')
ENABLE_UTC = True
# Any data transfered with pickle needs to be over tls... you can inject arbitrary objects with
# this stuff... message signing makes it a bit better, not perfect as it peels the onion.
# this stuff... message signing makes it a bit better, not perfect as it peels the onion.
# see: https://blog.nelhage.com/2011/03/exploiting-pickle/
# Yet pickle is the only convenient way of transporting objects without having to lean in all kinds
# of directions to get the job done. Intermediate tables to store results could be an option.
CELERY_ACCEPT_CONTENT = ['pickle']
CELERY_TASK_SERIALIZER = 'pickle'
CELERY_RESULT_SERIALIZER = 'pickle'
CELERY_TIMEZONE = 'UTC'
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
CELERY_BROKER_CONNECTION_MAX_RETRIES = 1
CELERY_BROKER_CONNECTION_RETRY = False
CELERY_RESULT_EXPIRES = timedelta(hours=4)
# Use the value of 2 for celery prefetch multiplier. Previous was 1. The
# assumption is that 1 will block a worker thread until the current (rate
# limited) task is completed. When using 2 (or higher) the assumption is that
# celery will drop further rate limited task from the internal worker queue and
# fetch other tasks tasks that could be executed (spooling other rate limited
# tasks through in the process but to no hard except for a slight drop in
# overall throughput/performance). A to high value for the prefetch multiplier
# might result in high priority tasks not being picked up as Celery does not
# seem to do prioritisation in worker queues but only on the broker
# queues. The value of 2 is currently selected because it higher than 1,
# behaviour needs to be observed to decide if raising this results in
# further improvements without impacting the priority feature.
CELERY_WORKER_PREFETCH_MULTIPLIER = 2
# numer of tasks to be executed in parallel by celery
CELERY_WORKER_CONCURRENCY = 10
# Workers will scale up and scale down depending on the number of tasks
# available. To prevent workers from scaling down while still doing work,
# the ACKS_LATE setting is used. This insures that a task is removed from
# the task queue after the task is performed. This might result in some
# issues where tasks that don't finish or crash keep being executed:
# thus for tasks that are not programmed perfectly it will raise a number
# of repeated exceptions which will need to be debugged.
CELERY_ACKS_LATE = True
# Settings for statsd metrics collection. Statsd defaults over UDP port 8125.
# https://django-statsd.readthedocs.io/en/latest/#celery-signals-integration
STATSD_HOST = os.environ.get('STATSD_HOST', '127.0.0.1')
STATSD_PREFIX = 'dashboard'
# register hooks for selery tasks
STATSD_CELERY_SIGNALS = True
# send database query metric (in production, in development we have debug toolbar for this)
if not DEBUG:
STATSD_PATCHES = ['django_statsd.patches.db', ]
TOOLS = {
'organizations': {
'import_data_dir': '',
},
}
OUTPUT_DIR = os.environ.get('OUTPUT_DIR', os.path.abspath(os.path.dirname(__file__)) + '/')
VENDOR_DIR = os.environ.get('VENDOR_DIR', os.path.abspath(os.path.dirname(__file__) + '/../vendor/') + '/')
if DEBUG:
# too many sql variables....
DATA_UPLOAD_MAX_NUMBER_FIELDS = 10000
# Compression
# Django-compressor is used to compress css and js files in production
# During development this is disabled as it does not provide any feature there
# Django-compressor configuration defaults take care of this.
# https://django-compressor.readthedocs.io/en/latest/usage/
# which plugins to use to find static files
STATICFILES_FINDERS = (
# default static files finders
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# other finders..
'compressor.finders.CompressorFinder',
)
COMPRESS_CSS_FILTERS = ['compressor.filters.cssmin.CSSCompressorFilter']
# Slimit doesn't work with vue. Tried two versions. Had to rewrite some other stuff.
# Now using the default, so not explicitly adding that to the settings
# COMPRESS_JS_FILTERS = ['compressor.filters.jsmin.JSMinFilter']
# Brotli compress storage gives some issues.
# This creates the original compressed and a gzipped compressed file.
COMPRESS_STORAGE = (
'compressor.storage.GzipCompressorFileStorage'
)
# Enable static file (js/css) compression when not running debug
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_OFFLINE
COMPRESS_OFFLINE = not DEBUG
# https://django-compressor.readthedocs.io/en/latest/settings/#django.conf.settings.COMPRESS_ENABLED
# Enabled when debug is off by default.
# Constance settings:
CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend'
CONSTANCE_CONFIG = {
'SCAN_AT_ALL': (
True,
'This quickly enables or disabled all scans. Note that scans in the scan queue will still be processed.',
bool
),
'DASHBOARD_MAXIMUM_DOMAINS_PER_SPREADSHEET': (
10000,
'The maximum amount of domains that can be imported via a spreadsheet at one time. '
'In normal use cases these limits will not be reached.',
int
),
'DASHBOARD_MAXIMUM_LISTS_PER_SPREADSHEET': (
200,
'The maximum amount of lists that can be imported via a spreadsheet at one time. '
'In normal usec ases these limits will not be reached.',
int
),
'DASHBOARD_MAXIMUM_DOMAINS_PER_LIST': (
# The average list is about 300. 90DEV is 600. One exception of 13.000.
10000,
'The maximum amount of domains that can be in a list. There will be no crash when somebody imports more '
'via a spreadsheet: it will be added but the list will refuse to scan and show a warning.'
'In normal use cases these limits will not be reached.',
int
),
'INTERNET_NL_API_USERNAME': (
'dummy',
'Username for the internet.nl API. You can request one via the contact '
'options on their site, https://internet.nl.',
str),
'INTERNET_NL_API_PASSWORD': (
'',
'Password for the internet.nl API',
str
),
'INTERNET_NL_API_URL': ('https://batch.internet.nl/api/batch/v2',
'The internet address for the Internet.nl API installation. Defaults to a version from '
'2020.', str),
'INTERNET_NL_MAXIMUM_URLS': (1000, 'The maximum amount of domains per scan.', int),
}
CONSTANCE_CONFIG_FIELDSETS = OrderedDict([
('DASHBOARD', ('DASHBOARD_MAXIMUM_DOMAINS_PER_LIST',
'DASHBOARD_MAXIMUM_DOMAINS_PER_SPREADSHEET',
'DASHBOARD_MAXIMUM_LISTS_PER_SPREADSHEET')),
('Internet.nl Scans', ('INTERNET_NL_API_USERNAME', 'INTERNET_NL_API_PASSWORD', 'INTERNET_NL_API_URL',
'INTERNET_NL_MAXIMUM_URLS'))
])
# the try-except makes sure autofix doesn't move the import to the top of the file.
# Loaded here, otherwise: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
try:
from websecmap.scanners.constance import add_scanner_fields, add_scanner_fieldsets # NOQA
CONSTANCE_CONFIG = add_scanner_fields(CONSTANCE_CONFIG)
CONSTANCE_CONFIG_FIELDSETS = add_scanner_fieldsets(CONSTANCE_CONFIG_FIELDSETS)
except ImportError:
pass
JET_SIDE_MENU_ITEMS = [
{'label': _('👤 User'), 'items': [
{'name': 'auth.user'},
{'name': 'internet_nl_dashboard.account'},
{'name': 'otp_totp.totpdevice'},
]},
{'label': _('📘 Dashboard'), 'items': [
{'name': 'constance.config', 'label': '🎛️ Config'},
{'name': 'internet_nl_dashboard.urllist', 'label': "Domain lists"},
{'name': 'internet_nl_dashboard.uploadlog', 'label': 'Uploads'},
]},
{'label': _('🔬 Scan'), 'items': [
{'name': 'internet_nl_dashboard.accountinternetnlscan'},
{'name': 'internet_nl_dashboard.accountinternetnlscanlog'},
{'name': 'scanners.internetnlv2scan', 'label': 'Internet.nl Scans Tasks'},
{'name': 'scanners.internetnlv2statelog', 'label': 'Internet.nl Scans Log'},
]},
{'label': _('💽 Data'), 'items': [
{'name': 'organizations.url', 'label': 'Urls'},
{'name': 'scanners.endpoint', 'label': 'Endpoints'},
{'name': 'scanners.endpointgenericscan', 'label': 'Endpoint Scans'},
]},
{'label': _('📊 Report'), 'items': [
{'name': 'reporting.urlreport', 'label': 'Url Reports'},
{'name': 'internet_nl_dashboard.urllistreport', 'label': 'Full Reports'}
]},
{'label': _('🕒 Periodic Tasks'), 'items': [
{'name': 'django_celery_beat.periodictask'},
{'name': 'django_celery_beat.crontabschedule'},
{'name': 'app.job'},
]},
{'label': _('✨ Activity'), 'items': [
{'name': 'actstream.action'},
]},
]
JET_SIDE_MENU_COMPACT = True
# Allows to see all details of websecmap.
# Loaded here, otherwise: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
# try:
# from websecmap.jet import websecmap_menu_items # NOQA
# JET_SIDE_MENU_ITEMS += websecmap_menu_items()
# except ImportError:
# pass
# Security options
if not DEBUG:
SESSION_COOKIE_SECURE = True # insecure by default
SESSION_COOKIE_SAMESITE = 'Lax'
SESSION_COOKIE_AGE = 1209600 # two weeks, could be longer
CSRF_COOKIE_SECURE = True # insecure by default
# if sentry DSN is provided register raven to emit events on exceptions
SENTRY_DSN = os.environ.get('SENTRY_DSN')
if SENTRY_DSN:
INSTALLED_APPS += ('raven.contrib.django.raven_compat',)
RAVEN_CONFIG = {
'dsn': SENTRY_DSN,
'release': __version__,
}
# add sentry ID to request for inclusion in templates
# https://docs.sentry.io/clients/python/integrations/django/#message-references
MIDDLEWARE.insert(0, 'raven.contrib.django.raven_compat.middleware.SentryResponseErrorIdMiddleware')
# Celery specific handlers
client = raven.Client(SENTRY_DSN)
raven.contrib.celery.register_logger_signal(client)
raven.contrib.celery.register_signal(client)
# Copied from internet.nl
# Supported languages.
# NOTE: Make sure that a DNS record for each language exists.
# More information can be found in the README file.
LANGUAGES = sorted([
('nl', 'Dutch'),
('en', 'English'),
], key=lambda x: x[0])
# email settings...
if DEBUG:
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# As there are sanity checks, these settings need to be present during debugging too.
EMAIL_HOST = ''
EMAIL_PORT = ''
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
EMAIL_USE_SSL = False
else:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# todo: get these settings from internet.nl
EMAIL_HOST = ''
EMAIL_PORT = ''
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
EMAIL_USE_SSL = False
if DEBUG:
# 25 megs for importing reports from live situations
DATA_UPLOAD_MAX_MEMORY_SIZE = 26214400
| []
| []
| [
"BROKER",
"DB_HOST",
"DB_NAME",
"SECRET_KEY",
"STATSD_HOST",
"SENTRY_DSN",
"VENDOR_DIR",
"DB_USER",
"OUTPUT_DIR",
"ALLOWED_HOSTS",
"DB_ENGINE",
"STATIC_ROOT",
"DJANGO_LOG_LEVEL",
"DJANGO_DATABASE",
"FIELD_ENCRYPTION_KEY",
"COMPRESS",
"DB_PASSWORD",
"MEDIA_ROOT",
"DEBUG"
]
| [] | ["BROKER", "DB_HOST", "DB_NAME", "SECRET_KEY", "STATSD_HOST", "SENTRY_DSN", "VENDOR_DIR", "DB_USER", "OUTPUT_DIR", "ALLOWED_HOSTS", "DB_ENGINE", "STATIC_ROOT", "DJANGO_LOG_LEVEL", "DJANGO_DATABASE", "FIELD_ENCRYPTION_KEY", "COMPRESS", "DB_PASSWORD", "MEDIA_ROOT", "DEBUG"] | python | 19 | 0 | |
Lib/os2knixpath.py | # Module 'os2knixpath' -- common operations on OS/2 pathnames
"""Common pathname manipulations, OS/2 libc version.
Instead of importing this module directly, import os and refer to this
module as os.path.
"""
import os
import stat
from genericpath import *
from ntpath import (expanduser, expandvars, isabs, islink, splitdrive,
splitext, split)
__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
"basename","dirname","commonprefix","getsize","getmtime",
"getatime","getctime", "islink","exists","lexists","isdir","isfile",
"ismount","expanduser","expandvars","normpath","abspath",
"curdir","pardir","sep","pathsep","defpath","altsep",
"extsep","devnull","realpath","supports_unicode_filenames","relpath",
"samefile","sameopenfile","samestat", "commonpath", "splitunc"]
# strings representing various path-related bits and pieces
curdir = '.'
pardir = '..'
extsep = '.'
sep = '/'
altsep = '\\'
pathsep = ';'
defpath = '.;' + (os.environ['UNIXROOT'] + '\\usr\\bin' if 'UNIXROOT' in os.environ else 'C:\\bin')
devnull = 'nul'
# Normalize the case of a pathname and map slashes to backslashes.
# Other normalizations (such as optimizing '../' away) are not done
# (this is done by normpath).
def normcase(s):
"""Normalize case of pathname.
Makes all characters lowercase and all altseps into seps."""
return s.replace(altsep, sep).lower()
# Join two (or more) paths.
def join(a, *p):
"""Join two or more pathname components, inserting sep as needed.
Also replaces all altsep chars with sep in the returned string
to make it consistent."""
path = a
for b in p:
if isabs(b):
path = b
elif path == '' or path[-1:] in '/\\:':
path = path + b
else:
path = path + '/' + b
return path.replace(altsep, sep)
# Parse UNC paths
def splitunc(p):
"""Split a pathname into UNC mount point and relative path specifiers.
Return a 2-tuple (unc, rest); either part may be empty.
If unc is not empty, it has the form '//host/mount' (or similar
using backslashes). unc+rest is always the input path.
Paths containing drive letters never have an UNC part.
"""
if p[1:2] == ':':
return '', p # Drive letter present
firstTwo = p[0:2]
if firstTwo == '/' * 2 or firstTwo == '\\' * 2:
# is a UNC path:
# vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
# \\machine\mountpoint\directories...
# directory ^^^^^^^^^^^^^^^
normp = normcase(p)
index = normp.find('/', 2)
if index == -1:
##raise RuntimeError, 'illegal UNC path: "' + p + '"'
return ("", p)
index = normp.find('/', index + 1)
if index == -1:
index = len(p)
return p[:index], p[index:]
return '', p
# Return the tail (basename) part of a path.
def basename(p):
"""Returns the final component of a pathname"""
return split(p)[1]
# Return the head (dirname) part of a path.
def dirname(p):
"""Returns the directory component of a pathname"""
return split(p)[0]
# Is a path a directory?
# Is a path a mount point? Either a root (with or without drive letter)
# or an UNC path with at most a / or \ after the mount point.
def ismount(path):
"""Test whether a path is a mount point (defined as root of drive)"""
unc, rest = splitunc(path)
if unc:
return rest in ("", "/", "\\")
p = splitdrive(path)[1]
return len(p) == 1 and p[0] in '/\\'
# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
def normpath(path):
"""Normalize path, eliminating double slashes, etc."""
path = path.replace('\\', '/')
prefix, path = splitdrive(path)
while path[:1] == '/':
prefix = prefix + '/'
path = path[1:]
comps = path.split('/')
i = 0
while i < len(comps):
if comps[i] == '.':
del comps[i]
elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
del comps[i-1:i+1]
i = i - 1
elif comps[i] == '' and i > 0 and comps[i-1] != '':
del comps[i]
else:
i = i + 1
# If the path is now empty, substitute '.'
if not prefix and not comps:
comps.append('.')
return prefix + '/'.join(comps)
# Return an absolute path.
def abspath(path):
"""Return the absolute version of a path"""
if not isabs(path):
path = join(os.getcwd(), path)
return normpath(path)
# Return a canonical path (i.e. the absolute location of a file on the
# filesystem).
def realpath(filename):
"""Return the canonical path of the specified filename, eliminating any
symbolic links encountered in the path."""
if isabs(filename):
bits = ['/'] + filename.split('/')[1:]
else:
bits = [''] + filename.split('/')
for i in range(2, len(bits)+1):
component = join(*bits[0:i])
# Resolve symbolic links.
if islink(component):
resolved = _resolve_link(component)
if resolved is None:
# Infinite loop -- return original component + rest of the path
return abspath(join(*([component] + bits[i:])))
else:
newpath = join(*([resolved] + bits[i:]))
return realpath(newpath)
return abspath(filename)
def _resolve_link(path):
"""Internal helper function. Takes a path and follows symlinks
until we either arrive at something that isn't a symlink, or
encounter a path we've seen before (meaning that there's a loop).
"""
paths_seen = []
while islink(path):
if path in paths_seen:
# Already seen this path, so we must have a symlink loop
return None
paths_seen.append(path)
# Resolve where the link points to
resolved = os.readlink(path)
if not isabs(resolved):
dir = dirname(path)
path = normpath(join(dir, resolved))
else:
path = normpath(resolved)
return path
# Is a path a symbolic link?
# This will always return false on systems where os.lstat doesn't exist.
def islink(path):
"""Test whether a path is a symbolic link"""
try:
st = os.lstat(path)
except (os.error, AttributeError):
return False
return stat.S_ISLNK(st.st_mode)
# Being true for dangling symbolic links is also useful.
def lexists(path):
"""Test whether a path exists. Returns True for broken symbolic links"""
try:
st = os.lstat(path)
except os.error:
return False
return True
# Are two filenames really pointing to the same file?
def samefile(f1, f2):
"""Test whether two pathnames reference the same actual file"""
s1 = os.stat(f1)
s2 = os.stat(f2)
return samestat(s1, s2)
# Are two open files really referencing the same file?
# (Not necessarily the same file descriptor!)
def sameopenfile(fp1, fp2):
"""Test whether two open file objects reference the same file"""
s1 = os.fstat(fp1)
s2 = os.fstat(fp2)
return samestat(s1, s2)
# Are two stat buffers (obtained from stat, fstat or lstat)
# describing the same file?
def samestat(s1, s2):
"""Test whether two stat buffers reference the same file"""
return s1.st_ino == s2.st_ino and \
s1.st_dev == s2.st_dev
supports_unicode_filenames = False
def relpath(path, start=curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = abspath(start).split(sep)
path_list = abspath(path).split(sep)
# Remove empty components after trailing slashes
if (start_list[-1] == ''):
start_list.pop()
if (path_list[-1] == ''):
path_list.pop()
if start_list[0].lower() != path_list[0].lower():
unc_path, rest = splitunc(path)
unc_start, rest = splitunc(start)
if bool(unc_path) ^ bool(unc_start):
raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
% (path, start))
else:
raise ValueError("path is on drive %s, start on drive %s"
% (path_list[0], start_list[0]))
# Work out how much of the filepath is shared by start and path.
for i in range(min(len(start_list), len(path_list))):
if start_list[i].lower() != path_list[i].lower():
break
else:
i += 1
rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list)
# Return the longest common sub-path of the sequence of paths given as input.
# The function is case-insensitive and 'separator-insensitive', i.e. if the
# only difference between two paths is the use of '\' versus '/' as separator,
# they are deemed to be equal.
#
# However, the returned path will have the standard '\' separator (even if the
# given paths had the alternative '/' separator) and will have the case of the
# first path given in the sequence. Additionally, any trailing separator is
# stripped from the returned path.
def commonpath(paths):
"""Given a sequence of path names, returns the longest common sub-path."""
if not paths:
raise ValueError('commonpath() arg is an empty sequence')
paths = tuple(map(os.fspath, paths))
if isinstance(paths[0], bytes):
sep = b'\\'
altsep = b'/'
curdir = b'.'
else:
sep = '\\'
altsep = '/'
curdir = '.'
try:
drivesplits = [splitdrive(p.replace(altsep, sep).lower()) for p in paths]
split_paths = [p.split(sep) for d, p in drivesplits]
try:
isabs, = set(p[:1] == sep for d, p in drivesplits)
except ValueError:
raise ValueError("Can't mix absolute and relative paths") from None
# Check that all drive letters or UNC paths match. The check is made only
# now otherwise type errors for mixing strings and bytes would not be
# caught.
if len(set(d for d, p in drivesplits)) != 1:
raise ValueError("Paths don't have the same drive")
drive, path = splitdrive(paths[0].replace(altsep, sep))
common = path.split(sep)
common = [c for c in common if c and c != curdir]
split_paths = [[c for c in s if c and c != curdir] for s in split_paths]
s1 = min(split_paths)
s2 = max(split_paths)
for i, c in enumerate(s1):
if c != s2[i]:
common = common[:i]
break
else:
common = common[:len(s1)]
prefix = drive + sep if isabs else drive
return prefix + sep.join(common)
except (TypeError, AttributeError):
genericpath._check_arg_types('commonpath', *paths)
raise
| []
| []
| [
"UNIXROOT"
]
| [] | ["UNIXROOT"] | python | 1 | 0 | |
python/pyspark/sql/streaming.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
import json
from py4j.java_gateway import java_import
from pyspark import since, keyword_only
from pyspark.sql.column import _to_seq
from pyspark.sql.readwriter import OptionUtils, to_str
from pyspark.sql.types import StructType, StructField, StringType
from pyspark.sql.utils import ForeachBatchFunction, StreamingQueryException
__all__ = ["StreamingQuery", "StreamingQueryManager", "DataStreamReader", "DataStreamWriter"]
class StreamingQuery(object):
"""
A handle to a query that is executing continuously in the background as new data arrives.
All these methods are thread-safe.
.. versionadded:: 2.0.0
Notes
-----
This API is evolving.
"""
def __init__(self, jsq):
self._jsq = jsq
@property
@since(2.0)
def id(self):
"""Returns the unique id of this query that persists across restarts from checkpoint data.
That is, this id is generated when a query is started for the first time, and
will be the same every time it is restarted from checkpoint data.
There can only be one query with the same id active in a Spark cluster.
Also see, `runId`.
"""
return self._jsq.id().toString()
@property
@since(2.1)
def runId(self):
"""Returns the unique id of this query that does not persist across restarts. That is, every
query that is started (or restarted from checkpoint) will have a different runId.
"""
return self._jsq.runId().toString()
@property
@since(2.0)
def name(self):
"""Returns the user-specified name of the query, or null if not specified.
This name can be specified in the `org.apache.spark.sql.streaming.DataStreamWriter`
as `dataframe.writeStream.queryName("query").start()`.
This name, if set, must be unique across all active queries.
"""
return self._jsq.name()
@property
@since(2.0)
def isActive(self):
"""Whether this streaming query is currently active or not.
"""
return self._jsq.isActive()
@since(2.0)
def awaitTermination(self, timeout=None):
"""Waits for the termination of `this` query, either by :func:`query.stop()` or by an
exception. If the query has terminated with an exception, then the exception will be thrown.
If `timeout` is set, it returns whether the query has terminated or not within the
`timeout` seconds.
If the query has terminated, then all subsequent calls to this method will either return
immediately (if the query was terminated by :func:`stop()`), or throw the exception
immediately (if the query has terminated with exception).
throws :class:`StreamingQueryException`, if `this` query has terminated with an exception
"""
if timeout is not None:
if not isinstance(timeout, (int, float)) or timeout < 0:
raise ValueError("timeout must be a positive integer or float. Got %s" % timeout)
return self._jsq.awaitTermination(int(timeout * 1000))
else:
return self._jsq.awaitTermination()
@property
@since(2.1)
def status(self):
"""
Returns the current status of the query.
"""
return json.loads(self._jsq.status().json())
@property
@since(2.1)
def recentProgress(self):
"""Returns an array of the most recent [[StreamingQueryProgress]] updates for this query.
The number of progress updates retained for each stream is configured by Spark session
configuration `spark.sql.streaming.numRecentProgressUpdates`.
"""
return [json.loads(p.json()) for p in self._jsq.recentProgress()]
@property
def lastProgress(self):
"""
Returns the most recent :class:`StreamingQueryProgress` update of this streaming query or
None if there were no progress updates
.. versionadded:: 2.1.0
Returns
-------
dict
"""
lastProgress = self._jsq.lastProgress()
if lastProgress:
return json.loads(lastProgress.json())
else:
return None
def processAllAvailable(self):
"""Blocks until all available data in the source has been processed and committed to the
sink. This method is intended for testing.
.. versionadded:: 2.0.0
Notes
-----
In the case of continually arriving data, this method may block forever.
Additionally, this method is only guaranteed to block until data that has been
synchronously appended data to a stream source prior to invocation.
(i.e. `getOffset` must immediately reflect the addition).
"""
return self._jsq.processAllAvailable()
@since(2.0)
def stop(self):
"""Stop this streaming query.
"""
self._jsq.stop()
def explain(self, extended=False):
"""Prints the (logical and physical) plans to the console for debugging purpose.
.. versionadded:: 2.1.0
Parameters
----------
extended : bool, optional
default ``False``. If ``False``, prints only the physical plan.
Examples
--------
>>> sq = sdf.writeStream.format('memory').queryName('query_explain').start()
>>> sq.processAllAvailable() # Wait a bit to generate the runtime plans.
>>> sq.explain()
== Physical Plan ==
...
>>> sq.explain(True)
== Parsed Logical Plan ==
...
== Analyzed Logical Plan ==
...
== Optimized Logical Plan ==
...
== Physical Plan ==
...
>>> sq.stop()
"""
# Cannot call `_jsq.explain(...)` because it will print in the JVM process.
# We should print it in the Python process.
print(self._jsq.explainInternal(extended))
def exception(self):
"""
.. versionadded:: 2.1.0
Returns
-------
:class:`StreamingQueryException`
the StreamingQueryException if the query was terminated by an exception, or None.
"""
if self._jsq.exception().isDefined():
je = self._jsq.exception().get()
msg = je.toString().split(': ', 1)[1] # Drop the Java StreamingQueryException type info
stackTrace = '\n\t at '.join(map(lambda x: x.toString(), je.getStackTrace()))
return StreamingQueryException(msg, stackTrace, je.getCause())
else:
return None
class StreamingQueryManager(object):
"""A class to manage all the :class:`StreamingQuery` StreamingQueries active.
.. versionadded:: 2.0.0
Notes
-----
This API is evolving.
"""
def __init__(self, jsqm):
self._jsqm = jsqm
@property
def active(self):
"""Returns a list of active queries associated with this SQLContext
.. versionadded:: 2.0.0
Examples
--------
>>> sq = sdf.writeStream.format('memory').queryName('this_query').start()
>>> sqm = spark.streams
>>> # get the list of active streaming queries
>>> [q.name for q in sqm.active]
['this_query']
>>> sq.stop()
"""
return [StreamingQuery(jsq) for jsq in self._jsqm.active()]
def get(self, id):
"""Returns an active query from this SQLContext or throws exception if an active query
with this name doesn't exist.
.. versionadded:: 2.0.0
Examples
--------
>>> sq = sdf.writeStream.format('memory').queryName('this_query').start()
>>> sq.name
'this_query'
>>> sq = spark.streams.get(sq.id)
>>> sq.isActive
True
>>> sq = sqlContext.streams.get(sq.id)
>>> sq.isActive
True
>>> sq.stop()
"""
return StreamingQuery(self._jsqm.get(id))
@since(2.0)
def awaitAnyTermination(self, timeout=None):
"""Wait until any of the queries on the associated SQLContext has terminated since the
creation of the context, or since :func:`resetTerminated()` was called. If any query was
terminated with an exception, then the exception will be thrown.
If `timeout` is set, it returns whether the query has terminated or not within the
`timeout` seconds.
If a query has terminated, then subsequent calls to :func:`awaitAnyTermination()` will
either return immediately (if the query was terminated by :func:`query.stop()`),
or throw the exception immediately (if the query was terminated with exception). Use
:func:`resetTerminated()` to clear past terminations and wait for new terminations.
In the case where multiple queries have terminated since :func:`resetTermination()`
was called, if any query has terminated with exception, then :func:`awaitAnyTermination()`
will throw any of the exception. For correctly documenting exceptions across multiple
queries, users need to stop all of them after any of them terminates with exception, and
then check the `query.exception()` for each query.
throws :class:`StreamingQueryException`, if `this` query has terminated with an exception
"""
if timeout is not None:
if not isinstance(timeout, (int, float)) or timeout < 0:
raise ValueError("timeout must be a positive integer or float. Got %s" % timeout)
return self._jsqm.awaitAnyTermination(int(timeout * 1000))
else:
return self._jsqm.awaitAnyTermination()
def resetTerminated(self):
"""Forget about past terminated queries so that :func:`awaitAnyTermination()` can be used
again to wait for new terminations.
.. versionadded:: 2.0.0
Examples
--------
>>> spark.streams.resetTerminated()
"""
self._jsqm.resetTerminated()
class DataStreamReader(OptionUtils):
"""
Interface used to load a streaming :class:`DataFrame <pyspark.sql.DataFrame>` from external
storage systems (e.g. file systems, key-value stores, etc).
Use :attr:`SparkSession.readStream <pyspark.sql.SparkSession.readStream>` to access this.
.. versionadded:: 2.0.0
Notes
-----
This API is evolving.
"""
def __init__(self, spark):
self._jreader = spark._ssql_ctx.readStream()
self._spark = spark
def _df(self, jdf):
from pyspark.sql.dataframe import DataFrame
return DataFrame(jdf, self._spark)
def format(self, source):
"""Specifies the input data source format.
.. versionadded:: 2.0.0
Parameters
----------
source : str
name of the data source, e.g. 'json', 'parquet'.
Notes
-----
This API is evolving.
Examples
--------
>>> s = spark.readStream.format("text")
"""
self._jreader = self._jreader.format(source)
return self
def schema(self, schema):
"""Specifies the input schema.
Some data sources (e.g. JSON) can infer the input schema automatically from data.
By specifying the schema here, the underlying data source can skip the schema
inference step, and thus speed up data loading.
.. versionadded:: 2.0.0
Parameters
----------
schema : :class:`pyspark.sql.types.StructType` or str
a :class:`pyspark.sql.types.StructType` object or a DDL-formatted string
(For example ``col0 INT, col1 DOUBLE``).
Notes
-----
This API is evolving.
Examples
--------
>>> s = spark.readStream.schema(sdf_schema)
>>> s = spark.readStream.schema("col0 INT, col1 DOUBLE")
"""
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
if isinstance(schema, StructType):
jschema = spark._jsparkSession.parseDataType(schema.json())
self._jreader = self._jreader.schema(jschema)
elif isinstance(schema, str):
self._jreader = self._jreader.schema(schema)
else:
raise TypeError("schema should be StructType or string")
return self
def option(self, key, value):
"""Adds an input option for the underlying data source.
.. versionadded:: 2.0.0
Notes
-----
This API is evolving.
Examples
--------
>>> s = spark.readStream.option("x", 1)
"""
self._jreader = self._jreader.option(key, to_str(value))
return self
def options(self, **options):
"""Adds input options for the underlying data source.
.. versionadded:: 2.0.0
Notes
-----
This API is evolving.
Examples
--------
>>> s = spark.readStream.options(x="1", y=2)
"""
for k in options:
self._jreader = self._jreader.option(k, to_str(options[k]))
return self
def load(self, path=None, format=None, schema=None, **options):
"""Loads a data stream from a data source and returns it as a
:class:`DataFrame <pyspark.sql.DataFrame>`.
.. versionadded:: 2.0.0
Parameters
----------
path : str, optional
optional string for file-system backed data sources.
format : str, optional
optional string for format of the data source. Default to 'parquet'.
schema : :class:`pyspark.sql.types.StructType` or str, optional
optional :class:`pyspark.sql.types.StructType` for the input schema
or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).
**options : dict
all other string options
Notes
-----
This API is evolving.
Examples
--------
>>> json_sdf = spark.readStream.format("json") \\
... .schema(sdf_schema) \\
... .load(tempfile.mkdtemp())
>>> json_sdf.isStreaming
True
>>> json_sdf.schema == sdf_schema
True
"""
if format is not None:
self.format(format)
if schema is not None:
self.schema(schema)
self.options(**options)
if path is not None:
if type(path) != str or len(path.strip()) == 0:
raise ValueError("If the path is provided for stream, it needs to be a " +
"non-empty string. List of paths are not supported.")
return self._df(self._jreader.load(path))
else:
return self._df(self._jreader.load())
def json(self, path, schema=None, primitivesAsString=None, prefersDecimal=None,
allowComments=None, allowUnquotedFieldNames=None, allowSingleQuotes=None,
allowNumericLeadingZero=None, allowBackslashEscapingAnyCharacter=None,
mode=None, columnNameOfCorruptRecord=None, dateFormat=None, timestampFormat=None,
multiLine=None, allowUnquotedControlChars=None, lineSep=None, locale=None,
dropFieldIfAllNull=None, encoding=None, pathGlobFilter=None,
recursiveFileLookup=None, allowNonNumericNumbers=None):
"""
Loads a JSON file stream and returns the results as a :class:`DataFrame`.
`JSON Lines <http://jsonlines.org/>`_ (newline-delimited JSON) is supported by default.
For JSON (one record per file), set the ``multiLine`` parameter to ``true``.
If the ``schema`` parameter is not specified, this function goes
through the input once to determine the input schema.
.. versionadded:: 2.0.0
Parameters
----------
path : str
string represents path to the JSON dataset,
or RDD of Strings storing JSON objects.
schema : :class:`pyspark.sql.types.StructType` or str, optional
an optional :class:`pyspark.sql.types.StructType` for the input schema
or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).
Other Parameters
----------------
Extra options
For the extra options, refer to
`Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-json.html#data-source-option>`_ # noqa
in the version you use.
Notes
-----
This API is evolving.
Examples
--------
>>> json_sdf = spark.readStream.json(tempfile.mkdtemp(), schema = sdf_schema)
>>> json_sdf.isStreaming
True
>>> json_sdf.schema == sdf_schema
True
"""
self._set_opts(
schema=schema, primitivesAsString=primitivesAsString, prefersDecimal=prefersDecimal,
allowComments=allowComments, allowUnquotedFieldNames=allowUnquotedFieldNames,
allowSingleQuotes=allowSingleQuotes, allowNumericLeadingZero=allowNumericLeadingZero,
allowBackslashEscapingAnyCharacter=allowBackslashEscapingAnyCharacter,
mode=mode, columnNameOfCorruptRecord=columnNameOfCorruptRecord, dateFormat=dateFormat,
timestampFormat=timestampFormat, multiLine=multiLine,
allowUnquotedControlChars=allowUnquotedControlChars, lineSep=lineSep, locale=locale,
dropFieldIfAllNull=dropFieldIfAllNull, encoding=encoding,
pathGlobFilter=pathGlobFilter, recursiveFileLookup=recursiveFileLookup,
allowNonNumericNumbers=allowNonNumericNumbers)
if isinstance(path, str):
return self._df(self._jreader.json(path))
else:
raise TypeError("path can be only a single string")
def orc(self, path, mergeSchema=None, pathGlobFilter=None, recursiveFileLookup=None):
"""Loads a ORC file stream, returning the result as a :class:`DataFrame`.
.. versionadded:: 2.3.0
Other Parameters
----------------
Extra options
For the extra options, refer to
`Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-orc.html#data-source-option>`_ # noqa
in the version you use.
Examples
--------
>>> orc_sdf = spark.readStream.schema(sdf_schema).orc(tempfile.mkdtemp())
>>> orc_sdf.isStreaming
True
>>> orc_sdf.schema == sdf_schema
True
"""
self._set_opts(mergeSchema=mergeSchema, pathGlobFilter=pathGlobFilter,
recursiveFileLookup=recursiveFileLookup)
if isinstance(path, str):
return self._df(self._jreader.orc(path))
else:
raise TypeError("path can be only a single string")
def parquet(self, path, mergeSchema=None, pathGlobFilter=None, recursiveFileLookup=None,
datetimeRebaseMode=None, int96RebaseMode=None):
"""
Loads a Parquet file stream, returning the result as a :class:`DataFrame`.
.. versionadded:: 2.0.0
Parameters
----------
path : str
the path in any Hadoop supported file system
Other Parameters
----------------
Extra options
For the extra options, refer to
`Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-parquet.html#data-source-option>`_. # noqa
in the version you use.
Examples
--------
>>> parquet_sdf = spark.readStream.schema(sdf_schema).parquet(tempfile.mkdtemp())
>>> parquet_sdf.isStreaming
True
>>> parquet_sdf.schema == sdf_schema
True
"""
self._set_opts(mergeSchema=mergeSchema, pathGlobFilter=pathGlobFilter,
recursiveFileLookup=recursiveFileLookup,
datetimeRebaseMode=datetimeRebaseMode, int96RebaseMode=int96RebaseMode)
if isinstance(path, str):
return self._df(self._jreader.parquet(path))
else:
raise TypeError("path can be only a single string")
def text(self, path, wholetext=False, lineSep=None, pathGlobFilter=None,
recursiveFileLookup=None):
"""
Loads a text file stream and returns a :class:`DataFrame` whose schema starts with a
string column named "value", and followed by partitioned columns if there
are any.
The text files must be encoded as UTF-8.
By default, each line in the text file is a new row in the resulting DataFrame.
.. versionadded:: 2.0.0
Parameters
----------
paths : str or list
string, or list of strings, for input path(s).
Other Parameters
----------------
Extra options
For the extra options, refer to
`Data Source Option <https://spark.apache.org/docs/latest/sql-data-sources-text.html#data-source-option>`_ # noqa
in the version you use.
Notes
-----
This API is evolving.
Examples
--------
>>> text_sdf = spark.readStream.text(tempfile.mkdtemp())
>>> text_sdf.isStreaming
True
>>> "value" in str(text_sdf.schema)
True
"""
self._set_opts(
wholetext=wholetext, lineSep=lineSep, pathGlobFilter=pathGlobFilter,
recursiveFileLookup=recursiveFileLookup)
if isinstance(path, str):
return self._df(self._jreader.text(path))
else:
raise TypeError("path can be only a single string")
def csv(self, path, schema=None, sep=None, encoding=None, quote=None, escape=None,
comment=None, header=None, inferSchema=None, ignoreLeadingWhiteSpace=None,
ignoreTrailingWhiteSpace=None, nullValue=None, nanValue=None, positiveInf=None,
negativeInf=None, dateFormat=None, timestampFormat=None, maxColumns=None,
maxCharsPerColumn=None, maxMalformedLogPerPartition=None, mode=None,
columnNameOfCorruptRecord=None, multiLine=None, charToEscapeQuoteEscaping=None,
enforceSchema=None, emptyValue=None, locale=None, lineSep=None,
pathGlobFilter=None, recursiveFileLookup=None, unescapedQuoteHandling=None):
r"""Loads a CSV file stream and returns the result as a :class:`DataFrame`.
This function will go through the input once to determine the input schema if
``inferSchema`` is enabled. To avoid going through the entire data once, disable
``inferSchema`` option or specify the schema explicitly using ``schema``.
Parameters
----------
path : str or list
string, or list of strings, for input path(s).
schema : :class:`pyspark.sql.types.StructType` or str, optional
an optional :class:`pyspark.sql.types.StructType` for the input schema
or a DDL-formatted string (For example ``col0 INT, col1 DOUBLE``).
sep : str, optional
sets a separator (one or more characters) for each field and value. If None is
set, it uses the default value, ``,``.
encoding : str, optional
decodes the CSV files by the given encoding type. If None is set,
it uses the default value, ``UTF-8``.
quote : str, optional sets a single character used for escaping quoted values where the
separator can be part of the value. If None is set, it uses the default
value, ``"``. If you would like to turn off quotations, you need to set an
empty string.
escape : str, optional
sets a single character used for escaping quotes inside an already
quoted value. If None is set, it uses the default value, ``\``.
comment : str, optional
sets a single character used for skipping lines beginning with this
character. By default (None), it is disabled.
header : str or bool, optional
uses the first line as names of columns. If None is set, it uses the
default value, ``false``.
inferSchema : str or bool, optional
infers the input schema automatically from data. It requires one extra
pass over the data. If None is set, it uses the default value, ``false``.
enforceSchema : str or bool, optional
If it is set to ``true``, the specified or inferred schema will be
forcibly applied to datasource files, and headers in CSV files will be
ignored. If the option is set to ``false``, the schema will be
validated against all headers in CSV files or the first header in RDD
if the ``header`` option is set to ``true``. Field names in the schema
and column names in CSV headers are checked by their positions
taking into account ``spark.sql.caseSensitive``. If None is set,
``true`` is used by default. Though the default value is ``true``,
it is recommended to disable the ``enforceSchema`` option
to avoid incorrect results.
ignoreLeadingWhiteSpace : str or bool, optional
a flag indicating whether or not leading whitespaces from
values being read should be skipped. If None is set, it
uses the default value, ``false``.
ignoreTrailingWhiteSpace : str or bool, optional
a flag indicating whether or not trailing whitespaces from
values being read should be skipped. If None is set, it
uses the default value, ``false``.
nullValue : str, optional
sets the string representation of a null value. If None is set, it uses
the default value, empty string. Since 2.0.1, this ``nullValue`` param
applies to all supported types including the string type.
nanValue : str, optional
sets the string representation of a non-number value. If None is set, it
uses the default value, ``NaN``.
positiveInf : str, optional
sets the string representation of a positive infinity value. If None
is set, it uses the default value, ``Inf``.
negativeInf : str, optional
sets the string representation of a negative infinity value. If None
is set, it uses the default value, ``Inf``.
dateFormat : str, optional
sets the string that indicates a date format. Custom date formats
follow the formats at
`datetime pattern <https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html>`_. # noqa
This applies to date type. If None is set, it uses the
default value, ``yyyy-MM-dd``.
timestampFormat : str, optional
sets the string that indicates a timestamp format.
Custom date formats follow the formats at
`datetime pattern <https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html>`_. # noqa
This applies to timestamp type. If None is set, it uses the
default value, ``yyyy-MM-dd'T'HH:mm:ss[.SSS][XXX]``.
maxColumns : str or int, optional
defines a hard limit of how many columns a record can have. If None is
set, it uses the default value, ``20480``.
maxCharsPerColumn : str or int, optional
defines the maximum number of characters allowed for any given
value being read. If None is set, it uses the default value,
``-1`` meaning unlimited length.
maxMalformedLogPerPartition : str or int, optional
this parameter is no longer used since Spark 2.2.0.
If specified, it is ignored.
mode : str, optional
allows a mode for dealing with corrupt records during parsing. If None is
set, it uses the default value, ``PERMISSIVE``.
* ``PERMISSIVE``: when it meets a corrupted record, puts the malformed string \
into a field configured by ``columnNameOfCorruptRecord``, and sets malformed \
fields to ``null``. To keep corrupt records, an user can set a string type \
field named ``columnNameOfCorruptRecord`` in an user-defined schema. If a \
schema does not have the field, it drops corrupt records during parsing. \
A record with less/more tokens than schema is not a corrupted record to CSV. \
When it meets a record having fewer tokens than the length of the schema, \
sets ``null`` to extra fields. When the record has more tokens than the \
length of the schema, it drops extra tokens.
* ``DROPMALFORMED``: ignores the whole corrupted records.
* ``FAILFAST``: throws an exception when it meets corrupted records.
columnNameOfCorruptRecord : str, optional
allows renaming the new field having malformed string
created by ``PERMISSIVE`` mode. This overrides
``spark.sql.columnNameOfCorruptRecord``. If None is set,
it uses the value specified in
``spark.sql.columnNameOfCorruptRecord``.
multiLine : str or bool, optional
parse one record, which may span multiple lines. If None is
set, it uses the default value, ``false``.
charToEscapeQuoteEscaping : str, optional
sets a single character used for escaping the escape for
the quote character. If None is set, the default value is
escape character when escape and quote characters are
different, ``\0`` otherwise.
emptyValue : str, optional
sets the string representation of an empty value. If None is set, it uses
the default value, empty string.
locale : str, optional
sets a locale as language tag in IETF BCP 47 format. If None is set,
it uses the default value, ``en-US``. For instance, ``locale`` is used while
parsing dates and timestamps.
lineSep : str, optional
defines the line separator that should be used for parsing. If None is
set, it covers all ``\\r``, ``\\r\\n`` and ``\\n``.
Maximum length is 1 character.
pathGlobFilter : str or bool, optional
an optional glob pattern to only include files with paths matching
the pattern. The syntax follows `org.apache.hadoop.fs.GlobFilter`.
It does not change the behavior of
`partition discovery <https://spark.apache.org/docs/latest/sql-data-sources-parquet.html#partition-discovery>`_. # noqa
recursiveFileLookup : str or bool, optional
recursively scan a directory for files. Using this option disables
`partition discovery <https://spark.apache.org/docs/latest/sql-data-sources-parquet.html#partition-discovery>`_. # noqa
unescapedQuoteHandling : str, optional
defines how the CsvParser will handle values with unescaped quotes. If None is
set, it uses the default value, ``STOP_AT_DELIMITER``.
* ``STOP_AT_CLOSING_QUOTE``: If unescaped quotes are found in the input, accumulate
the quote character and proceed parsing the value as a quoted value, until a closing
quote is found.
* ``BACK_TO_DELIMITER``: If unescaped quotes are found in the input, consider the value
as an unquoted value. This will make the parser accumulate all characters of the current
parsed value until the delimiter is found. If no delimiter is found in the value, the
parser will continue accumulating characters from the input until a delimiter or line
ending is found.
* ``STOP_AT_DELIMITER``: If unescaped quotes are found in the input, consider the value
as an unquoted value. This will make the parser accumulate all characters until the
delimiter or a line ending is found in the input.
* ``SKIP_VALUE``: If unescaped quotes are found in the input, the content parsed
for the given value will be skipped and the value set in nullValue will be produced
instead.
* ``RAISE_ERROR``: If unescaped quotes are found in the input, a TextParsingException
will be thrown.
.. versionadded:: 2.0.0
Notes
-----
This API is evolving.
Examples
--------
>>> csv_sdf = spark.readStream.csv(tempfile.mkdtemp(), schema = sdf_schema)
>>> csv_sdf.isStreaming
True
>>> csv_sdf.schema == sdf_schema
True
"""
self._set_opts(
schema=schema, sep=sep, encoding=encoding, quote=quote, escape=escape, comment=comment,
header=header, inferSchema=inferSchema, ignoreLeadingWhiteSpace=ignoreLeadingWhiteSpace,
ignoreTrailingWhiteSpace=ignoreTrailingWhiteSpace, nullValue=nullValue,
nanValue=nanValue, positiveInf=positiveInf, negativeInf=negativeInf,
dateFormat=dateFormat, timestampFormat=timestampFormat, maxColumns=maxColumns,
maxCharsPerColumn=maxCharsPerColumn,
maxMalformedLogPerPartition=maxMalformedLogPerPartition, mode=mode,
columnNameOfCorruptRecord=columnNameOfCorruptRecord, multiLine=multiLine,
charToEscapeQuoteEscaping=charToEscapeQuoteEscaping, enforceSchema=enforceSchema,
emptyValue=emptyValue, locale=locale, lineSep=lineSep,
pathGlobFilter=pathGlobFilter, recursiveFileLookup=recursiveFileLookup,
unescapedQuoteHandling=unescapedQuoteHandling)
if isinstance(path, str):
return self._df(self._jreader.csv(path))
else:
raise TypeError("path can be only a single string")
def table(self, tableName):
"""Define a Streaming DataFrame on a Table. The DataSource corresponding to the table should
support streaming mode.
.. versionadded:: 3.1.0
Parameters
----------
tableName : str
string, for the name of the table.
Returns
--------
:class:`DataFrame`
Notes
-----
This API is evolving.
Examples
--------
>>> spark.readStream.table('input_table') # doctest: +SKIP
"""
if isinstance(tableName, str):
return self._df(self._jreader.table(tableName))
else:
raise TypeError("tableName can be only a single string")
class DataStreamWriter(object):
"""
Interface used to write a streaming :class:`DataFrame <pyspark.sql.DataFrame>` to external
storage systems (e.g. file systems, key-value stores, etc).
Use :attr:`DataFrame.writeStream <pyspark.sql.DataFrame.writeStream>`
to access this.
.. versionadded:: 2.0.0
Notes
-----
This API is evolving.
"""
def __init__(self, df):
self._df = df
self._spark = df.sql_ctx
self._jwrite = df._jdf.writeStream()
def _sq(self, jsq):
from pyspark.sql.streaming import StreamingQuery
return StreamingQuery(jsq)
def outputMode(self, outputMode):
"""Specifies how data of a streaming DataFrame/Dataset is written to a streaming sink.
.. versionadded:: 2.0.0
Options include:
* `append`: Only the new rows in the streaming DataFrame/Dataset will be written to
the sink
* `complete`: All the rows in the streaming DataFrame/Dataset will be written to the sink
every time these are some updates
* `update`: only the rows that were updated in the streaming DataFrame/Dataset will be
written to the sink every time there are some updates. If the query doesn't contain
aggregations, it will be equivalent to `append` mode.
Notes
-----
This API is evolving.
Examples
--------
>>> writer = sdf.writeStream.outputMode('append')
"""
if not outputMode or type(outputMode) != str or len(outputMode.strip()) == 0:
raise ValueError('The output mode must be a non-empty string. Got: %s' % outputMode)
self._jwrite = self._jwrite.outputMode(outputMode)
return self
def format(self, source):
"""Specifies the underlying output data source.
.. versionadded:: 2.0.0
Parameters
----------
source : str
string, name of the data source, which for now can be 'parquet'.
Notes
-----
This API is evolving.
Examples
--------
>>> writer = sdf.writeStream.format('json')
"""
self._jwrite = self._jwrite.format(source)
return self
def option(self, key, value):
"""Adds an output option for the underlying data source.
.. versionadded:: 2.0.0
Notes
-----
This API is evolving.
"""
self._jwrite = self._jwrite.option(key, to_str(value))
return self
def options(self, **options):
"""Adds output options for the underlying data source.
.. versionadded:: 2.0.0
Notes
-----
This API is evolving.
"""
for k in options:
self._jwrite = self._jwrite.option(k, to_str(options[k]))
return self
def partitionBy(self, *cols):
"""Partitions the output by the given columns on the file system.
If specified, the output is laid out on the file system similar
to Hive's partitioning scheme.
.. versionadded:: 2.0.0
Parameters
----------
cols : str or list
name of columns
Notes
-----
This API is evolving.
"""
if len(cols) == 1 and isinstance(cols[0], (list, tuple)):
cols = cols[0]
self._jwrite = self._jwrite.partitionBy(_to_seq(self._spark._sc, cols))
return self
def queryName(self, queryName):
"""Specifies the name of the :class:`StreamingQuery` that can be started with
:func:`start`. This name must be unique among all the currently active queries
in the associated SparkSession.
.. versionadded:: 2.0.0
Parameters
----------
queryName : str
unique name for the query
Notes
-----
This API is evolving.
Examples
--------
>>> writer = sdf.writeStream.queryName('streaming_query')
"""
if not queryName or type(queryName) != str or len(queryName.strip()) == 0:
raise ValueError('The queryName must be a non-empty string. Got: %s' % queryName)
self._jwrite = self._jwrite.queryName(queryName)
return self
@keyword_only
def trigger(self, *, processingTime=None, once=None, continuous=None):
"""Set the trigger for the stream query. If this is not set it will run the query as fast
as possible, which is equivalent to setting the trigger to ``processingTime='0 seconds'``.
.. versionadded:: 2.0.0
Parameters
----------
processingTime : str, optional
a processing time interval as a string, e.g. '5 seconds', '1 minute'.
Set a trigger that runs a microbatch query periodically based on the
processing time. Only one trigger can be set.
once : bool, optional
if set to True, set a trigger that processes only one batch of data in a
streaming query then terminates the query. Only one trigger can be set.
continuous : str, optional
a time interval as a string, e.g. '5 seconds', '1 minute'.
Set a trigger that runs a continuous query with a given checkpoint
interval. Only one trigger can be set.
Notes
-----
This API is evolving.
Examples
--------
>>> # trigger the query for execution every 5 seconds
>>> writer = sdf.writeStream.trigger(processingTime='5 seconds')
>>> # trigger the query for just once batch of data
>>> writer = sdf.writeStream.trigger(once=True)
>>> # trigger the query for execution every 5 seconds
>>> writer = sdf.writeStream.trigger(continuous='5 seconds')
"""
params = [processingTime, once, continuous]
if params.count(None) == 3:
raise ValueError('No trigger provided')
elif params.count(None) < 2:
raise ValueError('Multiple triggers not allowed.')
jTrigger = None
if processingTime is not None:
if type(processingTime) != str or len(processingTime.strip()) == 0:
raise ValueError('Value for processingTime must be a non empty string. Got: %s' %
processingTime)
interval = processingTime.strip()
jTrigger = self._spark._sc._jvm.org.apache.spark.sql.streaming.Trigger.ProcessingTime(
interval)
elif once is not None:
if once is not True:
raise ValueError('Value for once must be True. Got: %s' % once)
jTrigger = self._spark._sc._jvm.org.apache.spark.sql.streaming.Trigger.Once()
else:
if type(continuous) != str or len(continuous.strip()) == 0:
raise ValueError('Value for continuous must be a non empty string. Got: %s' %
continuous)
interval = continuous.strip()
jTrigger = self._spark._sc._jvm.org.apache.spark.sql.streaming.Trigger.Continuous(
interval)
self._jwrite = self._jwrite.trigger(jTrigger)
return self
def foreach(self, f):
"""
Sets the output of the streaming query to be processed using the provided writer ``f``.
This is often used to write the output of a streaming query to arbitrary storage systems.
The processing logic can be specified in two ways.
#. A **function** that takes a row as input.
This is a simple way to express your processing logic. Note that this does
not allow you to deduplicate generated data when failures cause reprocessing of
some input data. That would require you to specify the processing logic in the next
way.
#. An **object** with a ``process`` method and optional ``open`` and ``close`` methods.
The object can have the following methods.
* ``open(partition_id, epoch_id)``: *Optional* method that initializes the processing
(for example, open a connection, start a transaction, etc). Additionally, you can
use the `partition_id` and `epoch_id` to deduplicate regenerated data
(discussed later).
* ``process(row)``: *Non-optional* method that processes each :class:`Row`.
* ``close(error)``: *Optional* method that finalizes and cleans up (for example,
close connection, commit transaction, etc.) after all rows have been processed.
The object will be used by Spark in the following way.
* A single copy of this object is responsible of all the data generated by a
single task in a query. In other words, one instance is responsible for
processing one partition of the data generated in a distributed manner.
* This object must be serializable because each task will get a fresh
serialized-deserialized copy of the provided object. Hence, it is strongly
recommended that any initialization for writing data (e.g. opening a
connection or starting a transaction) is done after the `open(...)`
method has been called, which signifies that the task is ready to generate data.
* The lifecycle of the methods are as follows.
For each partition with ``partition_id``:
... For each batch/epoch of streaming data with ``epoch_id``:
....... Method ``open(partitionId, epochId)`` is called.
....... If ``open(...)`` returns true, for each row in the partition and
batch/epoch, method ``process(row)`` is called.
....... Method ``close(errorOrNull)`` is called with error (if any) seen while
processing rows.
Important points to note:
* The `partitionId` and `epochId` can be used to deduplicate generated data when
failures cause reprocessing of some input data. This depends on the execution
mode of the query. If the streaming query is being executed in the micro-batch
mode, then every partition represented by a unique tuple (partition_id, epoch_id)
is guaranteed to have the same data. Hence, (partition_id, epoch_id) can be used
to deduplicate and/or transactionally commit data and achieve exactly-once
guarantees. However, if the streaming query is being executed in the continuous
mode, then this guarantee does not hold and therefore should not be used for
deduplication.
* The ``close()`` method (if exists) will be called if `open()` method exists and
returns successfully (irrespective of the return value), except if the Python
crashes in the middle.
.. versionadded:: 2.4.0
Notes
-----
This API is evolving.
Examples
--------
>>> # Print every row using a function
>>> def print_row(row):
... print(row)
...
>>> writer = sdf.writeStream.foreach(print_row)
>>> # Print every row using a object with process() method
>>> class RowPrinter:
... def open(self, partition_id, epoch_id):
... print("Opened %d, %d" % (partition_id, epoch_id))
... return True
... def process(self, row):
... print(row)
... def close(self, error):
... print("Closed with error: %s" % str(error))
...
>>> writer = sdf.writeStream.foreach(RowPrinter())
"""
from pyspark.rdd import _wrap_function
from pyspark.serializers import PickleSerializer, AutoBatchedSerializer
from pyspark.taskcontext import TaskContext
if callable(f):
# The provided object is a callable function that is supposed to be called on each row.
# Construct a function that takes an iterator and calls the provided function on each
# row.
def func_without_process(_, iterator):
for x in iterator:
f(x)
return iter([])
func = func_without_process
else:
# The provided object is not a callable function. Then it is expected to have a
# 'process(row)' method, and optional 'open(partition_id, epoch_id)' and
# 'close(error)' methods.
if not hasattr(f, 'process'):
raise AttributeError("Provided object does not have a 'process' method")
if not callable(getattr(f, 'process')):
raise TypeError("Attribute 'process' in provided object is not callable")
def doesMethodExist(method_name):
exists = hasattr(f, method_name)
if exists and not callable(getattr(f, method_name)):
raise TypeError(
"Attribute '%s' in provided object is not callable" % method_name)
return exists
open_exists = doesMethodExist('open')
close_exists = doesMethodExist('close')
def func_with_open_process_close(partition_id, iterator):
epoch_id = TaskContext.get().getLocalProperty('streaming.sql.batchId')
if epoch_id:
epoch_id = int(epoch_id)
else:
raise RuntimeError("Could not get batch id from TaskContext")
# Check if the data should be processed
should_process = True
if open_exists:
should_process = f.open(partition_id, epoch_id)
error = None
try:
if should_process:
for x in iterator:
f.process(x)
except Exception as ex:
error = ex
finally:
if close_exists:
f.close(error)
if error:
raise error
return iter([])
func = func_with_open_process_close
serializer = AutoBatchedSerializer(PickleSerializer())
wrapped_func = _wrap_function(self._spark._sc, func, serializer, serializer)
jForeachWriter = \
self._spark._sc._jvm.org.apache.spark.sql.execution.python.PythonForeachWriter(
wrapped_func, self._df._jdf.schema())
self._jwrite.foreach(jForeachWriter)
return self
def foreachBatch(self, func):
"""
Sets the output of the streaming query to be processed using the provided
function. This is supported only the in the micro-batch execution modes (that is, when the
trigger is not continuous). In every micro-batch, the provided function will be called in
every micro-batch with (i) the output rows as a DataFrame and (ii) the batch identifier.
The batchId can be used deduplicate and transactionally write the output
(that is, the provided Dataset) to external systems. The output DataFrame is guaranteed
to exactly same for the same batchId (assuming all operations are deterministic in the
query).
.. versionadded:: 2.4.0
Notes
-----
This API is evolving.
Examples
--------
>>> def func(batch_df, batch_id):
... batch_df.collect()
...
>>> writer = sdf.writeStream.foreachBatch(func)
"""
from pyspark.java_gateway import ensure_callback_server_started
gw = self._spark._sc._gateway
java_import(gw.jvm, "org.apache.spark.sql.execution.streaming.sources.*")
wrapped_func = ForeachBatchFunction(self._spark, func)
gw.jvm.PythonForeachBatchHelper.callForeachBatch(self._jwrite, wrapped_func)
ensure_callback_server_started(gw)
return self
def start(self, path=None, format=None, outputMode=None, partitionBy=None, queryName=None,
**options):
"""Streams the contents of the :class:`DataFrame` to a data source.
The data source is specified by the ``format`` and a set of ``options``.
If ``format`` is not specified, the default data source configured by
``spark.sql.sources.default`` will be used.
.. versionadded:: 2.0.0
Parameters
----------
path : str, optional
the path in a Hadoop supported file system
format : str, optional
the format used to save
outputMode : str, optional
specifies how data of a streaming DataFrame/Dataset is written to a
streaming sink.
* `append`: Only the new rows in the streaming DataFrame/Dataset will be written to the
sink
* `complete`: All the rows in the streaming DataFrame/Dataset will be written to the
sink every time these are some updates
* `update`: only the rows that were updated in the streaming DataFrame/Dataset will be
written to the sink every time there are some updates. If the query doesn't contain
aggregations, it will be equivalent to `append` mode.
partitionBy : str or list, optional
names of partitioning columns
queryName : str, optional
unique name for the query
**options : dict
All other string options. You may want to provide a `checkpointLocation`
for most streams, however it is not required for a `memory` stream.
Notes
-----
This API is evolving.
Examples
--------
>>> sq = sdf.writeStream.format('memory').queryName('this_query').start()
>>> sq.isActive
True
>>> sq.name
'this_query'
>>> sq.stop()
>>> sq.isActive
False
>>> sq = sdf.writeStream.trigger(processingTime='5 seconds').start(
... queryName='that_query', outputMode="append", format='memory')
>>> sq.name
'that_query'
>>> sq.isActive
True
>>> sq.stop()
"""
self.options(**options)
if outputMode is not None:
self.outputMode(outputMode)
if partitionBy is not None:
self.partitionBy(partitionBy)
if format is not None:
self.format(format)
if queryName is not None:
self.queryName(queryName)
if path is None:
return self._sq(self._jwrite.start())
else:
return self._sq(self._jwrite.start(path))
def toTable(self, tableName, format=None, outputMode=None, partitionBy=None, queryName=None,
**options):
"""
Starts the execution of the streaming query, which will continually output results to the
given table as new data arrives.
The returned :class:`StreamingQuery` object can be used to interact with the stream.
.. versionadded:: 3.1.0
Parameters
----------
tableName : str
string, for the name of the table.
format : str, optional
the format used to save.
outputMode : str, optional
specifies how data of a streaming DataFrame/Dataset is written to a
streaming sink.
* `append`: Only the new rows in the streaming DataFrame/Dataset will be written to the
sink
* `complete`: All the rows in the streaming DataFrame/Dataset will be written to the
sink every time these are some updates
* `update`: only the rows that were updated in the streaming DataFrame/Dataset will be
written to the sink every time there are some updates. If the query doesn't contain
aggregations, it will be equivalent to `append` mode.
partitionBy : str or list, optional
names of partitioning columns
queryName : str, optional
unique name for the query
**options : dict
All other string options. You may want to provide a `checkpointLocation`.
Notes
-----
This API is evolving.
For v1 table, partitioning columns provided by `partitionBy` will be respected no matter
the table exists or not. A new table will be created if the table not exists.
For v2 table, `partitionBy` will be ignored if the table already exists. `partitionBy` will
be respected only if the v2 table does not exist. Besides, the v2 table created by this API
lacks some functionalities (e.g., customized properties, options, and serde info). If you
need them, please create the v2 table manually before the execution to avoid creating a
table with incomplete information.
Examples
--------
>>> sdf.writeStream.format('parquet').queryName('query').toTable('output_table')
... # doctest: +SKIP
>>> sdf.writeStream.trigger(processingTime='5 seconds').toTable(
... 'output_table',
... queryName='that_query',
... outputMode="append",
... format='parquet',
... checkpointLocation='/tmp/checkpoint') # doctest: +SKIP
"""
self.options(**options)
if outputMode is not None:
self.outputMode(outputMode)
if partitionBy is not None:
self.partitionBy(partitionBy)
if format is not None:
self.format(format)
if queryName is not None:
self.queryName(queryName)
return self._sq(self._jwrite.toTable(tableName))
def _test():
import doctest
import os
import tempfile
from pyspark.sql import SparkSession, SQLContext
import pyspark.sql.streaming
os.chdir(os.environ["SPARK_HOME"])
globs = pyspark.sql.streaming.__dict__.copy()
try:
spark = SparkSession.builder.getOrCreate()
except py4j.protocol.Py4JError: # noqa: F821
spark = SparkSession(sc) # noqa: F821
globs['tempfile'] = tempfile
globs['os'] = os
globs['spark'] = spark
globs['sqlContext'] = SQLContext.getOrCreate(spark.sparkContext)
globs['sdf'] = \
spark.readStream.format('text').load('python/test_support/sql/streaming')
globs['sdf_schema'] = StructType([StructField("data", StringType(), True)])
globs['df'] = \
globs['spark'].readStream.format('text').load('python/test_support/sql/streaming')
(failure_count, test_count) = doctest.testmod(
pyspark.sql.streaming, globs=globs,
optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE | doctest.REPORT_NDIFF)
globs['spark'].stop()
if failure_count:
sys.exit(-1)
if __name__ == "__main__":
_test()
| []
| []
| [
"SPARK_HOME"
]
| [] | ["SPARK_HOME"] | python | 1 | 0 | |
src/main/java/org/jenkinsci/plugins/initpipeline/InitPipeline.java | package org.jenkinsci.plugins.initpipeline;
/**
* initPipeline developed to extend git-plugin and handle the notifyCommit?url=URL commithook
* when the repo string passed is NOT known in Jenkins jobs and doesn't match any existing job
* This plugin catches the same /git/notifyCommit?url=URL commithook as git-plugin by
* extending the Listener in hudson.plugins.git.GitStatus.Listener, running parallel coding and
* then catching and handling the case of unknown repos and creating the job in Jenkins
* This done by calling out to an external executable to
* configure and instantiate a pipeline build and then kick it off for a first run
*/
/**
* this software is licensed under the MIT open source license
* see https://opensource.org/licenses/MIT
*/
import hudson.Extension;
import hudson.Util;
import hudson.model.*;
import hudson.plugins.git.BranchSpec;
import hudson.plugins.git.GitSCM;
import hudson.plugins.git.extensions.impl.IgnoreNotifyCommit;
import hudson.scm.SCM;
import hudson.security.ACL;
import hudson.triggers.SCMTrigger;
import jdk.nashorn.internal.runtime.options.LoggingOption;
import jenkins.model.Jenkins;
import jenkins.triggers.SCMTriggerItem;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.jgit.transport.URIish;
import org.kohsuke.stapler.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
// jgit
import org.eclipse.jgit.api.FetchCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.transport.FetchResult;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.api.ListBranchCommand.ListMode;
import org.eclipse.jgit.revwalk.*;
// jsch
import com.jcraft.jsch.HostKey;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* This page was originally gitplugin/gitstatus.java in the git-plugin code
* initPipeline extends the original git plugin listener and handles the
* !urlFound and !scmFound cases
*/
@Extension
@SuppressWarnings("unused") // Jenkins extension
// Extend the git-plugin Listener and catch the /git/notifyCommit?url=URL in parallel
public class InitPipeline extends hudson.plugins.git.GitStatus.Listener {
public String getDisplayName() {
return "Git";
}
public String getSearchUrl() {
return getUrlName();
}
public String getIconFileName() {
// TODO
return null;
}
public String getUrlName() {
return "git";
}
private String lastURL = ""; // Required query parameter
private static String notifyUrl = "";
// clearly capture and use url string sent to class outside of
// doNotifyCommit method
private String debugEnabled = "false";
// enables process-tracking messages to jenkins.log
private String lastBranches = null; // Optional query parameter
private String lastSHA1 = null; // Optional query parameter
private List<ParameterValue> lastBuildParameters = null;
private static List<ParameterValue> lastStaticBuildParameters = null;
// remove *** when no longer used
private String haveEnvVars = null;
@Override
public String toString() {
StringBuilder s = new StringBuilder();
s.append("URL: ");
s.append(lastURL);
if (lastSHA1 != null) {
s.append(" SHA1: ");
s.append(lastSHA1);
}
if (lastBranches != null) {
s.append(" Branches: ");
s.append(lastBranches);
}
if (lastBuildParameters != null && !lastBuildParameters.isEmpty()) {
s.append(" Parameters: ");
for (ParameterValue buildParameter : lastBuildParameters) {
s.append(buildParameter.getName());
s.append("='");
s.append(buildParameter.getValue());
s.append("',");
}
s.delete(s.length() - 1, s.length());
}
if (lastStaticBuildParameters != null && !lastStaticBuildParameters.isEmpty()) {
s.append(" More parameters: ");
for (ParameterValue buildParameter : lastStaticBuildParameters) {
s.append(buildParameter.getName());
s.append("='");
s.append(buildParameter.getValue());
s.append("',");
}
s.delete(s.length() - 1, s.length());
}
return s.toString();
}
public HttpResponse doNotifyCommit(HttpServletRequest request, @QueryParameter(required=true) String url,
@QueryParameter(required=false) String branches,
@QueryParameter(required=false) String sha1) throws ServletException, IOException {
lastURL = url;
notifyUrl = url; // isolate url string passed
lastBranches = branches;
lastSHA1 = sha1;
lastBuildParameters = null;
lastStaticBuildParameters = null;
URIish uri;
List<ParameterValue> buildParameters = new ArrayList<ParameterValue>();
try {
uri = new URIish(url);
} catch (URISyntaxException e) {
return HttpResponses.error(SC_BAD_REQUEST, new Exception("Illegal URL: " + url, e));
}
String capture_me = "";
final Map<String, String[]> parameterMap = request.getParameterMap();
for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
if (!(entry.getKey().equals("url")))
capture_me = entry.getKey();
if (!(entry.getKey().equals("url")) && !(entry.getKey().equals("branches")) && !(entry.getKey().equals("sha1")))
if (entry.getValue()[0] != null)
buildParameters.add(new StringParameterValue(entry.getKey(), entry.getValue()[0]));
}
lastBuildParameters = buildParameters;
branches = Util.fixEmptyAndTrim(branches);
String[] branchesArray;
if (branches == null) {
branchesArray = new String[0];
} else {
branchesArray = branches.split(",");
}
final List<hudson.plugins.git.GitStatus.ResponseContributor> contributors = new ArrayList<hudson.plugins.git.GitStatus.ResponseContributor>();
Jenkins jenkins = Jenkins.getInstance();
if (jenkins == null) {
return HttpResponses.error(SC_BAD_REQUEST, new Exception("Jenkins.getInstance() null for : " + url));
}
for (hudson.plugins.git.GitStatus.Listener listener : jenkins.getExtensionList(hudson.plugins.git.GitStatus.Listener.class)) {
contributors.addAll(listener.onNotifyCommit(uri, sha1, buildParameters, branchesArray));
}
return new HttpResponse() {
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node)
throws IOException, ServletException {
rsp.setStatus(SC_OK);
rsp.setContentType("text/plain");
for (hudson.plugins.git.GitStatus.ResponseContributor c : contributors) {
c.addHeaders(req, rsp);
}
PrintWriter w = rsp.getWriter();
for (hudson.plugins.git.GitStatus.ResponseContributor c : contributors) {
c.writeBody(req, rsp, w);
}
}
};
}
public static boolean looselyMatches(URIish lhs, URIish rhs) {
return StringUtils.equals(lhs.getHost(),rhs.getHost())
&& StringUtils.equals(normalizePath(lhs.getPath()), normalizePath(rhs.getPath()));
}
private static String normalizePath(String path) {
if (path.startsWith("/")) path=path.substring(1);
if (path.endsWith("/")) path=path.substring(0,path.length()-1);
if (path.endsWith(".git")) path=path.substring(0,path.length()-4);
return path;
}
@Override
public List<hudson.plugins.git.GitStatus.ResponseContributor> onNotifyCommit(URIish uri, String sha1, List<ParameterValue> buildParameters, String... branches) {
/**
* Untouched code...
*/
// log
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Received notification for uri = " + uri + " ; sha1 = " + sha1 + " ; branches = " + Arrays.toString(branches));
}
lastStaticBuildParameters = null;
List<ParameterValue> allBuildParameters = new ArrayList<ParameterValue>(buildParameters);
List<hudson.plugins.git.GitStatus.ResponseContributor> result = new ArrayList<hudson.plugins.git.GitStatus.ResponseContributor>();
// run in high privilege to see all the projects anonymous users don't see.
// this is safe because when we actually schedule a build, it's a build that can
// happen at some random time anyway.
SecurityContext old = ACL.impersonate(ACL.SYSTEM);
try {
boolean scmFound = false,
urlFound = false;
Jenkins jenkins = Jenkins.getInstance();
if (jenkins == null) {
LOGGER.severe("Jenkins.getInstance() is null in CicdDiscover.onNotifyCommit");
return result;
}
for (final Item project : Jenkins.getInstance().getAllItems()) {
SCMTriggerItem scmTriggerItem = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(project);
if (scmTriggerItem == null) {
continue;
}
SCMS:
for (SCM scm : scmTriggerItem.getSCMs()) {
if (!(scm instanceof GitSCM)) {
continue;
}
GitSCM git = (GitSCM) scm;
// here's the first "exists" case
scmFound = true;
for (RemoteConfig repository : git.getRepositories()) {
boolean repositoryMatches = false,
branchMatches = false;
URIish matchedURL = null;
for (URIish remoteURL : repository.getURIs()) {
if (looselyMatches(uri, remoteURL)) {
repositoryMatches = true;
matchedURL = remoteURL;
break;
}
}
if (!repositoryMatches || git.getExtensions().get(IgnoreNotifyCommit.class) != null) {
continue;
}
SCMTrigger trigger = scmTriggerItem.getSCMTrigger();
if (trigger == null || trigger.isIgnorePostCommitHooks()) {
LOGGER.info("no trigger, or post-commit hooks disabled, on " + project.getFullDisplayName());
continue;
}
boolean branchFound = false,
parametrizedBranchSpec = false;
if (branches.length == 0) {
branchFound = true;
} else {
OUT:
for (BranchSpec branchSpec : git.getBranches()) {
if (branchSpec.getName().contains("$")) {
// If the branchspec is parametrized, always run the polling
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Branch Spec is parametrized for " + project.getFullDisplayName() + ". ");
}
branchFound = true;
parametrizedBranchSpec = true;
} else {
for (String branch : branches) {
if (branchSpec.matches(repository.getName() + "/" + branch)) {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Branch Spec " + branchSpec + " matches modified branch "
+ branch + " for " + project.getFullDisplayName() + ". ");
}
branchFound = true;
break OUT;
}
}
}
}
}
if (!branchFound) continue;
urlFound = true;
if (!(project instanceof AbstractProject && ((AbstractProject) project).isDisabled())) {
//JENKINS-30178 Add default parameters defined in the job
if (project instanceof Job) {
Set<String> buildParametersNames = new HashSet<String>();
for (ParameterValue parameterValue : allBuildParameters) {
buildParametersNames.add(parameterValue.getName());
}
List<ParameterValue> jobParametersValues = getDefaultParametersValues((Job) project);
for (ParameterValue defaultParameterValue : jobParametersValues) {
if (!buildParametersNames.contains(defaultParameterValue.getName())) {
allBuildParameters.add(defaultParameterValue);
}
}
}
if (!parametrizedBranchSpec && isNotEmpty(sha1)) {
/* If SHA1 and not a parameterized branch spec, then schedule build.
* NOTE: This is SCHEDULING THE BUILD, not triggering polling of the repo.
* If no SHA1 or the branch spec is parameterized, it will only poll.
*/
LOGGER.info("Scheduling " + project.getFullDisplayName() + " to build commit " + sha1);
/**
* Dropping the job scheduling section
* Cases where the job exists should log but not act for InitPipeline...
*/
/*
scmTriggerItem.scheduleBuild2(scmTriggerItem.getQuietPeriod(),
new CauseAction(new CommitHookCause(sha1)),
new RevisionParameterAction(sha1, matchedURL), new ParametersAction(allBuildParameters));
result.add(new ScheduledResponseContributor(project));
*/
} else {
/* Poll the repository for changes
* NOTE: This is not scheduling the build, just polling for changes
* If the polling detects changes, it will schedule the build
*/
LOGGER.info(" CICD Discover:: NOT Triggering the polling of " + project.getFullDisplayName());
/**
* Dropping the job scheduling section
* Cases where the job exists should log but not act for InitPipeline...
*/
/*
trigger.run();
result.add(new PollingScheduledResponseContributor(project));
*/
break SCMS; // no need to trigger the same project twice, so do not consider other GitSCMs in it
}
}
break;
}
}
}
/**
* END Gitstatus.java mostly unmodified
* NEW CODE starts...
*/
if (!scmFound) {
result.add(new MessageResponseContributor("initPipeline:: repository: " + uri.toString() + " - START"));
notifyUrl = uri.toString();
// call prelims
LOGGER.log(Level.INFO, "initPipeline:: onNotifyCommit !scmFound: - START init Pipeline...");
/**
* ...am I in debug mode or no?
*/
checkDebug(); // if /var/lib/jenkins/plugins/.initpipeline.debug exists, enable debug
// sets global haveEnvVars if completely successful from getEnvVars()
if (debugEnabled == "true") {
result.add(new MessageResponseContributor("initPipeline:: " + uri.toString() + ": debug verbose logging enabled to Jenkins controller"));
} else {
result.add(new MessageResponseContributor("initPipeline:: " + uri.toString() + ": terse logging, no debug"));
}
/**
* drop out of java to /var/lib/jenkins/scripts/initPipeline executable...
*/
instantiatePipeline();
} else if (!urlFound) {
result.add(new MessageResponseContributor("initPipeline:: repository: " + uri.toString() + " - START"));
notifyUrl = uri.toString();
// call prelims
LOGGER.log(Level.INFO, "initPipeline:: onNotifyCommit !urlFound: - START Cicd Discover...");
/**
* ...am I in debug mode or no?
*/
checkDebug(); // if /var/lib/jenkins/plugins/.cicd-discover.debug exists, enable debug
// sets global haveEnvVars if completely successful
if (debugEnabled == "true") {
result.add(new MessageResponseContributor("initPipeline:: " + uri.toString() + ": debug verbose logging enabled to Jenkins controller"));
} else {
result.add(new MessageResponseContributor("initPipeline:: " + uri.toString() + ": terse logging, no debug"));
}
/**
* drop out of java to /var/lib/jenkins/scripts/initPipeline executable...
*/
instantiatePipeline();
}
LOGGER.log(Level.INFO, "initPipeline:: onNotifyCommit COMPLETE init pipeline execution");
result.add(new MessageResponseContributor("initPipeline:: repository: " + uri.toString() + " - COMPLETED"));
lastStaticBuildParameters = allBuildParameters;
return result;
} finally {
SecurityContextHolder.setContext(old);
}
}
/**
* START of Gitstatus.java legacy methods
* This code from lines 452 through to 590 (or so...)
* is directly from Gitstatus.java, unaltered
*/
public static class CommitHookCause extends Cause {
public final String sha1;
public CommitHookCause(String sha1) {
this.sha1 = sha1;
}
@Override
public String getShortDescription() {
return "commit notification " + sha1;
}
}
public static class MessageResponseContributor extends hudson.plugins.git.GitStatus.ResponseContributor {
/**
* The message.
*/
private final String msg;
/**
* Constructor.
*
* @param msg the message.
*/
public MessageResponseContributor(String msg) {
this.msg = msg;
}
/**
* {@inheritDoc}
*/
@Override
public void writeBody(PrintWriter w) {
w.println(msg);
}
}
private static class ScheduledResponseContributor extends hudson.plugins.git.GitStatus.ResponseContributor {
/**
* The project
*/
private final Item project;
/**
* Constructor.
*
* @param project the project.
*/
public ScheduledResponseContributor(Item project) {
this.project = project;
}
/**
* {@inheritDoc}
*/
@Override
public void addHeaders(StaplerRequest req, StaplerResponse rsp) {
rsp.addHeader("Triggered", project.getAbsoluteUrl());
}
/**
* {@inheritDoc}
*/
@Override
public void writeBody(PrintWriter w) {
w.println("Scheduled " + project.getFullDisplayName());
}
}
private static class PollingScheduledResponseContributor extends hudson.plugins.git.GitStatus.ResponseContributor {
/**
* The project
*/
private final Item project;
/**
* Constructor.
*
* @param project the project.
*/
public PollingScheduledResponseContributor(Item project) {
this.project = project;
}
/**
* {@inheritDoc}
*/
@Override
public void addHeaders(StaplerRequest req, StaplerResponse rsp) {
rsp.addHeader("Triggered", project.getAbsoluteUrl());
}
/**
* {@inheritDoc}
*/
@Override
public void writeBody(PrintWriter w) {
w.println("Scheduled polling of " + project.getFullDisplayName());
}
}
private static final Logger LOGGER = Logger.getLogger(InitPipeline.class.getName());
private ArrayList<ParameterValue> getDefaultParametersValues(Job<?,?> job) {
ArrayList<ParameterValue> defValues;
ParametersDefinitionProperty paramDefProp = job.getProperty(ParametersDefinitionProperty.class);
if (paramDefProp != null) {
List <ParameterDefinition> parameterDefinition = paramDefProp.getParameterDefinitions();
defValues = new ArrayList<ParameterValue>(parameterDefinition.size());
} else {
defValues = new ArrayList<ParameterValue>();
return defValues;
}
/* Scan for all parameter with an associated default values */
for (ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions()) {
ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();
if (defaultValue != null) {
defValues.add(defaultValue);
}
}
return defValues;
}
/**
* END GitStaatus.java original code
*/
/**
* NEW CODE
* InstantiatePipeline()
*/
private void instantiatePipeline() {
// Using jenkinsHome from /etc/sysconfig/jenkins, explicitly exporting JENKINS_HOME
String jenkinsHome = System.getenv("JENKINS_HOME");
// arg is notifyUrl, call is to initpipeline which does the heavy lifting
ProcessBuilder newpipe = new ProcessBuilder(jenkinsHome + "/scripts/" + "initpipeline", notifyUrl);
Process process;
InputStream is;
try {
process = newpipe.start();
is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader isbr = new BufferedReader(isr);
String idline;
// from this we should retrieve output
try {
while ((idline = isbr.readLine()) != null) {
if (debugEnabled == "true") {
LOGGER.log(Level.INFO, "initPipeline:: instantiatePipeline: idline: " + idline);
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
if (debugEnabled == "true") {
LOGGER.log(Level.INFO, "InitPipeline:: instanciatePipeline: completed initpipeline call");
}
}
/**
* checks for /var/lib/jenkins/plugins/.cicd-discover.debug file present
* if present, enables debug flag, which sends added logging to jenkins.log
*/
private void checkDebug() {
// set up file name
String jen_home = System.getenv("JENKINS_HOME");
String debugFile = jen_home + "/plugins/.initpipeline.debug";
// verify the file
File f = new File(debugFile);
if (f.exists()) {
LOGGER.log(Level.INFO, "initPipeline:: checkDebug: found file at " + debugFile + " ...enabling debug messages");
debugEnabled = "true";
} else {
debugEnabled = "false";
}
}
}
| [
"\"JENKINS_HOME\"",
"\"JENKINS_HOME\""
]
| []
| [
"JENKINS_HOME"
]
| [] | ["JENKINS_HOME"] | java | 1 | 0 | |
serenata_toolbox/chamber_of_deputies/presences_dataset.py | import os
import urllib
import xml.etree.ElementTree as ET
import socket
import time
import pandas as pd
from serenata_toolbox.datasets.helpers import (
save_to_csv,
translate_column,
xml_extract_datetime,
xml_extract_text,
)
class PresencesDataset:
URL = (
'http://www.camara.leg.br/SitCamaraWS/sessoesreunioes.asmx/ListarPresencasParlamentar'
'?dataIni={}'
'&dataFim={}'
'&numMatriculaParlamentar={}'
)
"""
:param sleep_interval: (integer) the amount of seconds to sleep between requests
"""
def __init__(self, sleep_interval=2):
self.sleep_interval = sleep_interval
def fetch(self, deputies, start_date, end_date):
"""
:param deputies: (pandas.DataFrame) a dataframe with deputies data
:param date_start: (str) date in the format dd/mm/yyyy
:param date_end: (str) date in the format dd/mm/yyyy
"""
if os.environ.get('DEBUG') == '1':
print("Fetching data for {} deputies from {} -> {}".format(len(deputies), start_date, end_date))
records = self._all_presences(deputies, start_date, end_date)
df = pd.DataFrame(records, columns=(
'term',
'congressperson_document',
'congressperson_name',
'party',
'state',
'date',
'present_on_day',
'justification',
'session',
'presence'
))
return self._translate(df)
def _all_presences(self, deputies, start_date, end_date):
error_count = 0
for i, deputy in deputies.iterrows():
if os.environ.get('DEBUG') == '1':
print(i, deputy.congressperson_name, deputy.congressperson_document)
url = self.URL.format(start_date, end_date, deputy.congressperson_document)
xml = self._try_fetch_xml(10, url)
if xml is None:
error_count += 1
else:
root = ET.ElementTree(file=xml).getroot()
for presence in self._parse_deputy_presences(root):
yield presence
time.sleep(self.sleep_interval)
if os.environ.get('DEBUG') == '1':
print("\nErrored fetching", error_count, "deputy presences")
def _try_fetch_xml(self, attempts, url):
while attempts > 0:
try:
return urllib.request.urlopen(url, data=None, timeout=10)
except urllib.error.HTTPError as err:
print("HTTP Error", err.code, "when loading URL", url)
# 500 seems to be the error code for "no data found for the
# params provided"
if err.code == 500:
print("SKIP")
return None
time.sleep(self.sleep_interval / 2)
attempts -= 1
if attempts > 0:
print("Trying again", attempts)
else:
print("FAIL")
except socket.error as socketerror:
print("Socket error:", socketerror)
time.sleep(self.sleep_interval * 10)
attempts -= 1
if attempts > 0:
print("Trying again", attempts)
else:
print("FAIL")
@staticmethod
def _parse_deputy_presences(root):
term = xml_extract_text(root, 'legislatura')
congressperson_document = xml_extract_text(root, 'carteiraParlamentar')
# Please note that this name contains the party and state
congressperson_name = xml_extract_text(root, 'nomeParlamentar')
party = xml_extract_text(root, 'siglaPartido')
state = xml_extract_text(root, 'siglaUF')
for day in root.findall('.//dia'):
date = xml_extract_datetime(day, 'data')
present_on_day = xml_extract_text(day, 'frequencianoDia')
justification = xml_extract_text(day, 'justificativa')
for session in day.findall('.//sessao'):
yield (
term,
congressperson_document,
congressperson_name,
party,
state,
date,
present_on_day,
justification,
xml_extract_text(session, 'descricao'),
xml_extract_text(session, 'frequencia')
)
@staticmethod
def _translate(df):
translate_column(df, 'presence', {
'Presença': 'Present',
'Ausência': 'Absent',
})
translate_column(df, 'present_on_day', {
'Presença (~)': 'Present (~)',
'Presença': 'Present',
'Ausência': 'Absent',
'Ausência justificada': 'Justified absence',
})
translate_column(df, 'justification', {
'': '',
'Atendimento a Obrigação Político-Partidária':
'Attending to Political-Party Obligation',
'Ausência Justificada':
'Justified absence',
'Decisão da Mesa':
'Board decision',
'Licença para Tratamento de Saúde':
'Health Care Leave',
'Missão Autorizada':
'Authorized Mission',
'Presença Eletrônica Aferida no Painel':
'Electronic Presence Measured on the Panel'
})
return df
def fetch_presences(data_dir, deputies, date_start, date_end):
"""
:param data_dir: (str) directory in which the output file will be saved
:param deputies: (pandas.DataFrame) a dataframe with deputies data
:param date_start: (str) a date in the format dd/mm/yyyy
:param date_end: (str) a date in the format dd/mm/yyyy
"""
presences = PresencesDataset()
df = presences.fetch(deputies, date_start, date_end)
save_to_csv(df, data_dir, "presences")
print("Presence records:", len(df))
print("Records of deputies present on a session:", len(df[df.presence == 'Present']))
print("Records of deputies absent from a session:", len(df[df.presence == 'Absent']))
return df
| []
| []
| [
"DEBUG"
]
| [] | ["DEBUG"] | python | 1 | 0 | |
internal/testing/cmdtest/cmdtest.go | // Copyright 2019 The Go Cloud Development Kit Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// The cmdtest package simplifies testing of command-line interfaces. It
// provides a simple, cross-platform, shell-like language to express command
// execution. It can compare actual output with the expected output, and can
// also update a file with new "golden" output that is deemed correct.
//
// Start using cmdtest by writing a test file with commands and expected output,
// giving it the extension ".ct". All test files in the same directory make up a
// test suite. See the TestSuite documentation for the syntax of test files.
//
// To test, first read the suite:
//
// ts, err := cmdtest.Read("testdata")
//
// Then configure the resulting TestSuite by adding commands or enabling
// debugging features. Lastly, call TestSuite.Run with false to compare
// or true to update. Typically, this boolean will be the value of a flag:
//
// var update = flag.Bool("update", false, "update test files with results")
// ...
// err := ts.Run(*update)
package cmdtest
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"sync"
"testing"
"github.com/google/go-cmp/cmp"
)
// A TestSuite contains a set of test files, each of which may contain multiple
// test cases. Use Read to build a TestSuite from all the test files in a
// directory. Then configure it and call Run.
//
// Format of a test file:
//
// Before the first line starting with a '$', empty lines and lines beginning with
// "#" are ignored.
//
// A sequence of consecutive lines starting with '$' begin a test case. These lines
// are commands to execute. See below for the valid commands.
//
// Lines following the '$' lines are command output (merged stdout and stderr).
// Output is always treated literally. After the command output there should be a
// blank line. Between that blank line and the next '$' line, empty lines and lines
// beginning with '#' are ignored. (Because of these rules, cmdtest cannot
// distinguish trailing blank lines in the output.)
//
// Syntax of a line beginning with '$': A sequence of space-separated words (no
// quoting is supported). The first word is the command, the rest are its args.
// If the next-to-last word is '<', the last word is interpreted as a file and
// becomes the standard input to the command. None of the built-in commands (see
// below) support input redirection, but commands defined with Program do.
//
// By default, commands are expected to succeed, and the test will fail
// otherwise. However, commands that are expected to fail can be marked
// with a " --> FAIL" suffix.
//
// The cases of a test file are executed in order, starting in a freshly
// created temporary directory.
//
// The built-in commands (initial contents of the Commands map) are:
//
// cd DIR
// cat FILE
// mkdir DIR
// setenv VAR VALUE
// echo ARG1 ARG2 ...
// echof FILE ARG1 ARG2 ...
//
// These all have their usual Unix shell meaning, except for echof, which writes its
// arguments to a file (output redirection is not supported). All file and directory
// arguments must refer to the current directory; that is, they cannot contain
// slashes.
//
// cmdtest does its own environment variable substitution, using the syntax
// "${VAR}". Test execution inherits the full environment of the test binary
// caller (typically, your shell). The environment variable ROOTDIR is set to
// the temporary directory created to run the test file.
type TestSuite struct {
// If non-nil, this function is called for each test. It is passed the root
// directory after it has been made the current directory.
Setup func(string) error
// The commands that can be executed (that is, whose names can occur as the
// first word of a command line).
Commands map[string]CommandFunc
// If true, don't delete the temporary root directories for each test file,
// and print out their names for debugging.
KeepRootDirs bool
files []*testFile
}
type testFile struct {
suite *TestSuite
filename string // full filename of the test file
cases []*testCase
suffix []string // non-output lines after last case
}
type testCase struct {
before []string // lines before the commands
startLine int // line of first command
// The list of commands to execute.
commands []string
// The stdout and stderr, merged and split into lines.
gotOutput []string // from execution
wantOutput []string // from file
}
// CommandFunc is the signature of a command function. The function takes the
// subsequent words on the command line (so that arg[0] is the first argument),
// as well as the name of a file to use for input redirection. It returns the
// command's output.
type CommandFunc func(args []string, inputFile string) ([]byte, error)
// Read reads all the files in dir with extension ".ct" and returns a TestSuite
// containing them. See the TestSuite documentation for syntax.
func Read(dir string) (*TestSuite, error) {
filenames, err := filepath.Glob(filepath.Join(dir, "*.ct"))
if err != nil {
return nil, err
}
ts := &TestSuite{
Commands: map[string]CommandFunc{
"cat": fixedArgBuiltin(1, catCmd),
"cd": fixedArgBuiltin(1, cdCmd),
"echo": echoCmd,
"echof": echofCmd,
"mkdir": fixedArgBuiltin(1, mkdirCmd),
"setenv": fixedArgBuiltin(2, setenvCmd),
},
}
for _, fn := range filenames {
tf, err := readFile(fn)
if err != nil {
return nil, err
}
tf.suite = ts
ts.files = append(ts.files, tf)
}
return ts, nil
}
func readFile(filename string) (*testFile, error) {
// parse states
const (
beforeFirstCommand = iota
inCommands
inOutput
)
tf := &testFile{
filename: filename,
}
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
var tc *testCase
lineno := 0
var prefix []string
state := beforeFirstCommand
for scanner.Scan() {
lineno++
line := scanner.Text()
isCommand := strings.HasPrefix(line, "$")
switch state {
case beforeFirstCommand:
if isCommand {
tc = &testCase{startLine: lineno, before: prefix}
tc.addCommandLine(line)
state = inCommands
} else {
line = strings.TrimSpace(line)
if line == "" || line[0] == '#' {
prefix = append(prefix, line)
} else {
return nil, fmt.Errorf("%s:%d: bad line %q (should begin with '#')", filename, lineno, line)
}
}
case inCommands:
if isCommand {
tc.addCommandLine(line)
} else { // End of commands marks the start of the output.
tc.wantOutput = append(tc.wantOutput, line)
state = inOutput
}
case inOutput:
if isCommand { // A command marks the end of the output.
prefix = tf.addCase(tc)
tc = &testCase{startLine: lineno, before: prefix}
tc.addCommandLine(line)
state = inCommands
} else {
tc.wantOutput = append(tc.wantOutput, line)
}
default:
panic("bad state")
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
if tc != nil {
tf.suffix = tf.addCase(tc)
}
return tf, nil
}
func (tc *testCase) addCommandLine(line string) {
tc.commands = append(tc.commands, strings.TrimSpace(line[1:]))
}
// addCase first splits the collected output for tc into the actual command
// output, and a suffix consisting of blank lines and comments. It then adds tc
// to the cases of tf, and returns the suffix.
func (tf *testFile) addCase(tc *testCase) []string {
// Trim the suffix of output that consists solely of blank lines and comments,
// and return it.
var i int
for i = len(tc.wantOutput) - 1; i >= 0; i-- {
if tc.wantOutput[i] != "" && tc.wantOutput[i][0] != '#' {
break
}
}
i++
// i is the index of the first line to ignore.
keep, suffix := tc.wantOutput[:i], tc.wantOutput[i:]
if len(keep) == 0 {
keep = nil
}
tc.wantOutput = keep
tf.cases = append(tf.cases, tc)
return suffix
}
// Run runs the commands in each file in the test suite. Each file runs in a
// separate subtest.
//
// If update is false, it compares their output with the output in the file,
// line by line.
//
// If update is true, it writes the output back to the file, overwriting the
// previous output.
//
// Before comparing/updating, occurrences of the root directory in the output
// are replaced by ${ROOTDIR}.
func (ts *TestSuite) Run(t *testing.T, update bool) {
if update {
ts.update(t)
} else {
ts.compare(t)
}
}
// compare runs a subtest for each file in the test suite. See Run.
func (ts *TestSuite) compare(t *testing.T) {
for _, tf := range ts.files {
t.Run(strings.TrimSuffix(tf.filename, ".ct"), func(t *testing.T) {
if s := tf.compare(t.Logf); s != "" {
t.Error(s)
}
})
}
}
var noopLogger = func(_ string, _ ...interface{}) {}
// compareReturningError is similar to compare, but it returns
// errors/differences in an error. It is used in tests for this package.
func (ts *TestSuite) compareReturningError() error {
var ss []string
for _, tf := range ts.files {
if s := tf.compare(noopLogger); s != "" {
ss = append(ss, s)
}
}
if len(ss) > 0 {
return errors.New(strings.Join(ss, ""))
}
return nil
}
func (tf *testFile) compare(log func(string, ...interface{})) string {
if err := tf.execute(log); err != nil {
return fmt.Sprintf("%v", err)
}
buf := new(bytes.Buffer)
for _, c := range tf.cases {
if diff := cmp.Diff(c.gotOutput, c.wantOutput); diff != "" {
fmt.Fprintf(buf, "%s:%d: got=-, want=+\n", tf.filename, c.startLine)
c.writeCommands(buf)
fmt.Fprintf(buf, "%s\n", diff)
}
}
return buf.String()
}
// update runs a subtest for each file in the test suite, updating their output.
// See Run.
func (ts *TestSuite) update(t *testing.T) {
for _, tf := range ts.files {
t.Run(strings.TrimSuffix(tf.filename, ".ct"), func(t *testing.T) {
tmpfile, err := tf.updateToTemp()
if err != nil {
t.Fatal(err)
}
if err := os.Rename(tmpfile, tf.filename); err != nil {
t.Fatal(err)
}
})
}
}
// updateToTemp executes tf and writes the output to a temporary file.
// It returns the name of the temporary file.
func (tf *testFile) updateToTemp() (fname string, err error) {
if err := tf.execute(noopLogger); err != nil {
return "", err
}
f, err := ioutil.TempFile("", "cmdtest")
if err != nil {
return "", err
}
defer func() {
err2 := f.Close()
if err == nil {
err = err2
}
if err != nil {
os.Remove(f.Name())
}
}()
if err := tf.write(f); err != nil {
return "", err
}
return f.Name(), nil
}
func (tf *testFile) execute(log func(string, ...interface{})) error {
rootDir, err := ioutil.TempDir("", "cmdtest")
if err != nil {
return fmt.Errorf("%s: %v", tf.filename, err)
}
if tf.suite.KeepRootDirs {
fmt.Printf("%s: test root directory: %s\n", tf.filename, rootDir)
} else {
defer os.RemoveAll(rootDir)
}
if err := os.Setenv("ROOTDIR", rootDir); err != nil {
return fmt.Errorf("%s: %v", tf.filename, err)
}
defer os.Unsetenv("ROOTDIR")
cwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("%s: %v", tf.filename, err)
}
if err := os.Chdir(rootDir); err != nil {
return fmt.Errorf("%s: %v", tf.filename, err)
}
defer func() { _ = os.Chdir(cwd) }()
if tf.suite.Setup != nil {
if err := tf.suite.Setup(rootDir); err != nil {
return fmt.Errorf("%s: calling Setup: %v", tf.filename, err)
}
}
for _, tc := range tf.cases {
if err := tc.execute(tf.suite, log); err != nil {
return fmt.Errorf("%s:%v", tf.filename, err) // no space after :, for line number
}
}
return nil
}
// A fatal error stops a test.
type fatal struct{ error }
// Run the test case by executing the commands. The concatenated output from all commands
// is saved in tc.gotOutput.
// An error is returned if: a command that should succeed instead failed; a command that should
// fail instead succeeded; or a built-in command was called incorrectly.
func (tc *testCase) execute(ts *TestSuite, log func(string, ...interface{})) error {
const failMarker = " --> FAIL"
tc.gotOutput = nil
var allout []byte
var err error
for i, cmd := range tc.commands {
wantFail := false
if strings.HasSuffix(cmd, failMarker) {
cmd = strings.TrimSuffix(cmd, failMarker)
wantFail = true
}
args := strings.Fields(cmd)
for i := range args {
args[i], err = expandVariables(args[i], os.LookupEnv)
if err != nil {
return err
}
}
log("$ %s", strings.Join(args, " "))
name := args[0]
args = args[1:]
var infile string
if len(args) >= 2 && args[len(args)-2] == "<" {
infile = args[len(args)-1]
args = args[:len(args)-2]
}
f := ts.Commands[name]
if f == nil {
return fmt.Errorf("%d: no such command %q", tc.startLine+i, name)
}
out, err := f(args, infile)
if _, ok := err.(fatal); ok {
return fmt.Errorf("%d: command %q failed fatally with %v", tc.startLine+i, cmd, err)
}
if err == nil && wantFail {
return fmt.Errorf("%d: %q succeeded, but it was expected to fail", tc.startLine+i, cmd)
}
if err != nil && !wantFail {
return fmt.Errorf("%d: %q failed with %v. Output:\n%s", tc.startLine+i, cmd, err, out)
}
log("%s\n", string(out))
allout = append(allout, out...)
}
if len(allout) > 0 {
allout = scrub(os.Getenv("ROOTDIR"), allout) // use Getenv because Setup could change ROOTDIR
// Remove final whitespace.
s := strings.TrimRight(string(allout), " \t\n")
tc.gotOutput = strings.Split(s, "\n")
}
return nil
}
// Program defines a command function that will run the executable at path using
// the exec.Command package and return its combined output. If path is relative,
// it is converted to an absolute path using the current directory at the time
// Program is called.
//
// In the unlikely event that Program cannot obtain the current directory, it
// panics.
func Program(path string) CommandFunc {
abspath, err := filepath.Abs(path)
if err != nil {
panic(fmt.Sprintf("Program(%q): %v", path, err))
}
return func(args []string, inputFile string) ([]byte, error) {
return execute(abspath, args, inputFile)
}
}
// InProcessProgram defines a command function that will invoke f, which must
// behave like an actual main function except that it returns an error code
// instead of calling os.Exit.
// Before calling f:
// - os.Args is set to the concatenation of name and args.
// - If inputFile is non-empty, it is redirected to standard input.
// - Standard output and standard error are redirected to a buffer, which is
// returned.
func InProcessProgram(name string, f func() int) CommandFunc {
return func(args []string, inputFile string) ([]byte, error) {
origArgs := os.Args
origOut := os.Stdout
origErr := os.Stderr
defer func() {
os.Args = origArgs
os.Stdout = origOut
os.Stderr = origErr
}()
os.Args = append([]string{name}, args...)
// Redirect stdout and stderr to pipes.
rOut, wOut, err := os.Pipe()
if err != nil {
return nil, err
}
rErr, wErr, err := os.Pipe()
if err != nil {
return nil, err
}
os.Stdout = wOut
os.Stderr = wErr
// Copy both stdout and stderr to the same buffer.
buf := &bytes.Buffer{}
lw := &lockingWriter{w: buf}
errc := make(chan error, 2)
go func() {
_, err := io.Copy(lw, rOut)
errc <- err
}()
go func() {
_, err := io.Copy(lw, rErr)
errc <- err
}()
// Redirect stdin if needed.
if inputFile != "" {
f, err := os.Open(inputFile)
if err != nil {
return nil, err
}
defer f.Close()
origIn := os.Stdin
defer func() { os.Stdin = origIn }()
os.Stdin = f
}
res := f()
if err := wOut.Close(); err != nil {
return nil, err
}
if err := wErr.Close(); err != nil {
return nil, err
}
// Wait for pipe copying to finish.
if err := <-errc; err != nil {
return nil, err
}
if err := <-errc; err != nil {
return nil, err
}
if res != 0 {
err = fmt.Errorf("%s failed with exit code %d", name, res)
}
return buf.Bytes(), err
}
}
// lockingWriter is an io.Writer whose Write method is safe for
// use by multiple goroutines.
type lockingWriter struct {
mu sync.Mutex
w io.Writer
}
func (w *lockingWriter) Write(b []byte) (int, error) {
w.mu.Lock()
defer w.mu.Unlock()
return w.w.Write(b)
}
// execute uses exec.Command to run the named program with the given args. The
// combined output is captured and returned. If infile is not empty, its contents
// become the command's standard input.
func execute(name string, args []string, infile string) ([]byte, error) {
ecmd := exec.Command(name, args...)
var errc chan error
if infile != "" {
f, err := os.Open(infile)
if err != nil {
return nil, err
}
defer f.Close()
ecmd.Stdin = f
}
out, err := ecmd.CombinedOutput()
if err != nil {
return out, err
}
if errc != nil {
if err = <-errc; err != nil {
return out, err
}
}
return out, nil
}
var varRegexp = regexp.MustCompile(`\$\{([^${}]+)\}`)
// expandVariables replaces variable references in s with their values. A reference
// to a variable V looks like "${V}".
// lookup is called on a variable's name to find its value. Its second return value
// is false if the variable doesn't exist.
// expandVariables fails if s contains a reference to a non-existent variable.
//
// This function differs from os.Expand in two ways. First, it does not expand $var,
// only ${var}. The former is fragile. Second, an undefined variable results in an error,
// rather than expanding to some string. We want to fail if a variable is undefined.
func expandVariables(s string, lookup func(string) (string, bool)) (string, error) {
var sb strings.Builder
for {
ixs := varRegexp.FindStringSubmatchIndex(s)
if ixs == nil {
sb.WriteString(s)
return sb.String(), nil
}
varName := s[ixs[2]:ixs[3]]
varVal, ok := lookup(varName)
if !ok {
return "", fmt.Errorf("variable %q not found", varName)
}
sb.WriteString(s[:ixs[0]])
sb.WriteString(varVal)
s = s[ixs[1]:]
}
}
// scrub removes dynamic content from output.
func scrub(rootDir string, b []byte) []byte {
const scrubbedRootDir = "${ROOTDIR}"
rootDirWithSeparator := rootDir + string(filepath.Separator)
scrubbedRootDirWithSeparator := scrubbedRootDir + "/"
b = bytes.Replace(b, []byte(rootDirWithSeparator), []byte(scrubbedRootDirWithSeparator), -1)
b = bytes.Replace(b, []byte(rootDir), []byte(scrubbedRootDir), -1)
return b
}
func (tf *testFile) write(w io.Writer) error {
for _, c := range tf.cases {
if err := c.write(w); err != nil {
return err
}
}
return writeLines(w, tf.suffix)
}
func (tc *testCase) write(w io.Writer) error {
if err := writeLines(w, tc.before); err != nil {
return err
}
if err := tc.writeCommands(w); err != nil {
return err
}
out := tc.gotOutput
if out == nil {
out = tc.wantOutput
}
return writeLines(w, out)
}
func (tc *testCase) writeCommands(w io.Writer) error {
for _, c := range tc.commands {
if _, err := fmt.Fprintf(w, "$ %s\n", c); err != nil {
return err
}
}
return nil
}
func writeLines(w io.Writer, lines []string) error {
for _, l := range lines {
if _, err := io.WriteString(w, l); err != nil {
return err
}
if _, err := w.Write([]byte{'\n'}); err != nil {
return err
}
}
return nil
}
func fixedArgBuiltin(nargs int, f func([]string) ([]byte, error)) CommandFunc {
return func(args []string, inputFile string) ([]byte, error) {
if len(args) != nargs {
return nil, fatal{fmt.Errorf("need exactly %d arguments", nargs)}
}
if inputFile != "" {
return nil, fatal{errors.New("input redirection not supported")}
}
return f(args)
}
}
// cd DIR
// change directory
func cdCmd(args []string) ([]byte, error) {
if err := checkPath(args[0]); err != nil {
return nil, err
}
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
return nil, os.Chdir(filepath.Join(cwd, args[0]))
}
// echo ARG1 ARG2 ...
// write args to stdout
//
// \n is added at the end of the input.
// Also, literal "\n" in the input will be replaced by \n.
func echoCmd(args []string, inputFile string) ([]byte, error) {
if inputFile != "" {
return nil, fatal{errors.New("input redirection not supported")}
}
s := strings.Join(args, " ")
s = strings.Replace(s, "\\n", "\n", -1)
s += "\n"
return []byte(s), nil
}
// echof FILE ARG1 ARG2 ...
// write args to FILE
//
// \n is added at the end of the input.
// Also, literal "\n" in the input will be replaced by \n.
func echofCmd(args []string, inputFile string) ([]byte, error) {
if len(args) < 1 {
return nil, fatal{errors.New("need at least 1 argument")}
}
if inputFile != "" {
return nil, fatal{errors.New("input redirection not supported")}
}
if err := checkPath(args[0]); err != nil {
return nil, err
}
s := strings.Join(args[1:], " ")
s = strings.Replace(s, "\\n", "\n", -1)
s += "\n"
return nil, ioutil.WriteFile(args[0], []byte(s), 0600)
}
// cat FILE
// copy file to stdout
func catCmd(args []string) ([]byte, error) {
if err := checkPath(args[0]); err != nil {
return nil, err
}
f, err := os.Open(args[0])
if err != nil {
return nil, err
}
defer f.Close()
buf := &bytes.Buffer{}
_, err = io.Copy(buf, f)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// mkdir DIR
// create directory
func mkdirCmd(args []string) ([]byte, error) {
if err := checkPath(args[0]); err != nil {
return nil, err
}
return nil, os.Mkdir(args[0], 0700)
}
// setenv VAR VALUE
// set environment variable
func setenvCmd(args []string) ([]byte, error) {
return nil, os.Setenv(args[0], args[1])
}
func checkPath(path string) error {
if strings.ContainsRune(path, '/') || strings.ContainsRune(path, '\\') {
return fatal{fmt.Errorf("argument must be in the current directory (%q has a '/')", path)}
}
return nil
}
| [
"\"ROOTDIR\""
]
| []
| [
"ROOTDIR"
]
| [] | ["ROOTDIR"] | go | 1 | 0 | |
test/e2e/run_test.go | package integration
import (
"fmt"
"io/ioutil"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/containers/common/pkg/cgroups"
"github.com/containers/podman/v4/pkg/rootless"
. "github.com/containers/podman/v4/test/utils"
"github.com/containers/storage/pkg/stringid"
"github.com/mrunalp/fileutils"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gexec"
)
var _ = Describe("Podman run", func() {
var (
tempdir string
err error
podmanTest *PodmanTestIntegration
)
BeforeEach(func() {
tempdir, err = CreateTempDirInTempDir()
if err != nil {
os.Exit(1)
}
podmanTest = PodmanTestCreate(tempdir)
podmanTest.Setup()
podmanTest.SeedImages()
})
AfterEach(func() {
podmanTest.Cleanup()
f := CurrentGinkgoTestDescription()
processTestResult(f)
})
It("podman run a container based on local image", func() {
session := podmanTest.Podman([]string{"run", ALPINE, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
})
It("podman run check /run/.containerenv", func() {
session := podmanTest.Podman([]string{"run", ALPINE, "cat", "/run/.containerenv"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(""))
session = podmanTest.Podman([]string{"run", "--privileged", "--name=test1", ALPINE, "cat", "/run/.containerenv"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("name=\"test1\""))
Expect(session.OutputToString()).To(ContainSubstring("image=\"" + ALPINE + "\""))
session = podmanTest.Podman([]string{"run", "-v", "/:/host", ALPINE, "cat", "/run/.containerenv"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("graphRootMounted=1"))
session = podmanTest.Podman([]string{"run", "-v", "/:/host", "--privileged", ALPINE, "cat", "/run/.containerenv"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("graphRootMounted=1"))
})
It("podman run a container based on a complex local image name", func() {
imageName := strings.TrimPrefix(nginx, "quay.io/")
session := podmanTest.Podman([]string{"run", imageName, "ls"})
session.WaitWithDefaultTimeout()
Expect(session.ErrorToString()).ToNot(ContainSubstring("Trying to pull"))
Expect(session).Should(Exit(0))
})
It("podman run --signature-policy", func() {
session := podmanTest.Podman([]string{"run", "--pull=always", "--signature-policy", "/no/such/file", ALPINE})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
session = podmanTest.Podman([]string{"run", "--pull=always", "--signature-policy", "/etc/containers/policy.json", ALPINE})
session.WaitWithDefaultTimeout()
if IsRemote() {
Expect(session).To(ExitWithError())
Expect(session.ErrorToString()).To(ContainSubstring("unknown flag"))
} else {
Expect(session).Should(Exit(0))
}
})
It("podman run --rm with --restart", func() {
session := podmanTest.Podman([]string{"run", "--rm", "--restart", "", ALPINE})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--rm", "--restart", "no", ALPINE})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--rm", "--restart", "on-failure", ALPINE})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--rm", "--restart", "always", ALPINE})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
session = podmanTest.Podman([]string{"run", "--rm", "--restart", "unless-stopped", ALPINE})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
})
It("podman run a container based on on a short name with localhost", func() {
tag := podmanTest.Podman([]string{"tag", nginx, "localhost/libpod/alpine_nginx:latest"})
tag.WaitWithDefaultTimeout()
rmi := podmanTest.Podman([]string{"rmi", nginx})
rmi.WaitWithDefaultTimeout()
session := podmanTest.Podman([]string{"run", "libpod/alpine_nginx:latest", "ls"})
session.WaitWithDefaultTimeout()
Expect(session.ErrorToString()).ToNot(ContainSubstring("Trying to pull"))
Expect(session).Should(Exit(0))
})
It("podman container run a container based on on a short name with localhost", func() {
tag := podmanTest.Podman([]string{"image", "tag", nginx, "localhost/libpod/alpine_nginx:latest"})
tag.WaitWithDefaultTimeout()
rmi := podmanTest.Podman([]string{"image", "rm", nginx})
rmi.WaitWithDefaultTimeout()
session := podmanTest.Podman([]string{"container", "run", "libpod/alpine_nginx:latest", "ls"})
session.WaitWithDefaultTimeout()
Expect(session.ErrorToString()).ToNot(ContainSubstring("Trying to pull"))
Expect(session).Should(Exit(0))
})
It("podman run a container based on local image with short options", func() {
session := podmanTest.Podman([]string{"run", "-dt", ALPINE, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
})
It("podman run a container based on local image with short options and args", func() {
// regression test for #714
session := podmanTest.Podman([]string{"run", ALPINE, "find", "/etc", "-name", "hosts"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("/etc/hosts"))
})
It("podman create pod with name in /etc/hosts", func() {
name := "test_container"
hostname := "test_hostname"
session := podmanTest.Podman([]string{"run", "-ti", "--rm", "--name", name, "--hostname", hostname, ALPINE, "cat", "/etc/hosts"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring(name))
Expect(session.OutputToString()).To(ContainSubstring(hostname))
})
It("podman run a container based on remote image", func() {
// Changing session to rsession
rsession := podmanTest.Podman([]string{"run", "-dt", ALPINE, "ls"})
rsession.WaitWithDefaultTimeout()
Expect(rsession).Should(Exit(0))
lock := GetPortLock("5000")
defer lock.Unlock()
session := podmanTest.Podman([]string{"run", "-d", "--name", "registry", "-p", "5000:5000", registry, "/entrypoint.sh", "/etc/docker/registry/config.yml"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
if !WaitContainerReady(podmanTest, "registry", "listening on", 20, 1) {
Skip("Cannot start docker registry.")
}
run := podmanTest.Podman([]string{"run", "--tls-verify=false", ALPINE})
run.WaitWithDefaultTimeout()
Expect(run).Should(Exit(0))
Expect(podmanTest.NumberOfContainers()).To(Equal(3))
// Now registries.conf will be consulted where localhost:5000
// is set to be insecure.
run = podmanTest.Podman([]string{"run", ALPINE})
run.WaitWithDefaultTimeout()
Expect(run).Should(Exit(0))
})
It("podman run a container with a --rootfs", func() {
rootfs := filepath.Join(tempdir, "rootfs")
uls := filepath.Join("/", "usr", "local", "share")
uniqueString := stringid.GenerateNonCryptoID()
testFilePath := filepath.Join(uls, uniqueString)
tarball := filepath.Join(tempdir, "rootfs.tar")
err := os.Mkdir(rootfs, 0770)
Expect(err).Should(BeNil())
// Change image in predictable way to validate export
csession := podmanTest.Podman([]string{"run", "--name", uniqueString, ALPINE,
"/bin/sh", "-c", fmt.Sprintf("echo %s > %s", uniqueString, testFilePath)})
csession.WaitWithDefaultTimeout()
Expect(csession).Should(Exit(0))
// Export from working container image guarantees working root
esession := podmanTest.Podman([]string{"export", "--output", tarball, uniqueString})
esession.WaitWithDefaultTimeout()
Expect(esession).Should(Exit(0))
Expect(tarball).Should(BeARegularFile())
// N/B: This will loose any extended attributes like SELinux types
fmt.Fprintf(os.Stderr, "Extracting container root tarball\n")
tarsession := SystemExec("tar", []string{"xf", tarball, "-C", rootfs})
Expect(tarsession).Should(Exit(0))
Expect(filepath.Join(rootfs, uls)).Should(BeADirectory())
// Other tests confirm SELinux types, just confirm --rootfs is working.
session := podmanTest.Podman([]string{"run", "-i", "--security-opt", "label=disable",
"--rootfs", rootfs, "cat", testFilePath})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
// Validate changes made in original container and export
stdoutLines := session.OutputToStringArray()
Expect(stdoutLines).Should(HaveLen(1))
Expect(stdoutLines[0]).Should(Equal(uniqueString))
SkipIfRemote("External overlay only work locally")
if os.Getenv("container") != "" {
Skip("Overlay mounts not supported when running in a container")
}
if rootless.IsRootless() {
if _, err := exec.LookPath("fuse-overlayfs"); err != nil {
Skip("Fuse-Overlayfs required for rootless overlay mount test")
}
}
// Test --rootfs with an external overlay
// use --rm to remove container and confirm if we did not leak anything
osession := podmanTest.Podman([]string{"run", "-i", "--rm", "--security-opt", "label=disable",
"--rootfs", rootfs + ":O", "cat", testFilePath})
osession.WaitWithDefaultTimeout()
Expect(osession).Should(Exit(0))
// Test podman start stop with overlay
osession = podmanTest.Podman([]string{"run", "--name", "overlay-foo", "--security-opt", "label=disable",
"--rootfs", rootfs + ":O", "echo", "hello"})
osession.WaitWithDefaultTimeout()
Expect(osession).Should(Exit(0))
osession = podmanTest.Podman([]string{"stop", "overlay-foo"})
osession.WaitWithDefaultTimeout()
Expect(osession).Should(Exit(0))
startsession := podmanTest.Podman([]string{"start", "--attach", "overlay-foo"})
startsession.WaitWithDefaultTimeout()
Expect(startsession).Should(Exit(0))
Expect(startsession.OutputToString()).To(Equal("hello"))
// remove container for above test overlay-foo
osession = podmanTest.Podman([]string{"rm", "overlay-foo"})
osession.WaitWithDefaultTimeout()
Expect(osession).Should(Exit(0))
// Test --rootfs with an external overlay with --uidmap
osession = podmanTest.Podman([]string{"run", "--uidmap", "0:1000:1000", "--rm", "--security-opt", "label=disable",
"--rootfs", rootfs + ":O", "echo", "hello"})
osession.WaitWithDefaultTimeout()
Expect(osession).Should(Exit(0))
Expect(osession.OutputToString()).To(Equal("hello"))
})
It("podman run a container with --init", func() {
session := podmanTest.Podman([]string{"run", "--name", "test", "--init", ALPINE, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
result := podmanTest.Podman([]string{"inspect", "test"})
result.WaitWithDefaultTimeout()
Expect(result).Should(Exit(0))
conData := result.InspectContainerToJSON()
Expect(conData[0].Path).To(Equal("/dev/init"))
Expect(conData[0].Config.Annotations).To(HaveKeyWithValue("io.podman.annotations.init", "TRUE"))
})
It("podman run a container with --init and --init-path", func() {
session := podmanTest.Podman([]string{"run", "--name", "test", "--init", "--init-path", "/usr/libexec/podman/catatonit", ALPINE, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
result := podmanTest.Podman([]string{"inspect", "test"})
result.WaitWithDefaultTimeout()
Expect(result).Should(Exit(0))
conData := result.InspectContainerToJSON()
Expect(conData[0].Path).To(Equal("/dev/init"))
Expect(conData[0].Config.Annotations).To(HaveKeyWithValue("io.podman.annotations.init", "TRUE"))
})
It("podman run a container without --init", func() {
session := podmanTest.Podman([]string{"run", "--name", "test", ALPINE, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
result := podmanTest.Podman([]string{"inspect", "test"})
result.WaitWithDefaultTimeout()
Expect(result).Should(Exit(0))
conData := result.InspectContainerToJSON()
Expect(conData[0].Path).To(Equal("ls"))
Expect(conData[0].Config.Annotations).To(HaveKeyWithValue("io.podman.annotations.init", "FALSE"))
})
forbidGetCWDSeccompProfile := func() string {
in := []byte(`{"defaultAction":"SCMP_ACT_ALLOW","syscalls":[{"name":"getcwd","action":"SCMP_ACT_ERRNO"}]}`)
jsonFile, err := podmanTest.CreateSeccompJSON(in)
if err != nil {
fmt.Println(err)
Skip("Failed to prepare seccomp.json for test.")
}
return jsonFile
}
It("podman run mask and unmask path test", func() {
session := podmanTest.Podman([]string{"run", "-d", "--name=maskCtr1", "--security-opt", "unmask=ALL", "--security-opt", "mask=/proc/acpi", ALPINE, "sleep", "200"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"exec", "maskCtr1", "ls", "/sys/firmware"})
session.WaitWithDefaultTimeout()
Expect(session.OutputToString()).To(Not(BeEmpty()))
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"exec", "maskCtr1", "ls", "/proc/acpi"})
session.WaitWithDefaultTimeout()
Expect(session.OutputToString()).To(BeEmpty())
session = podmanTest.Podman([]string{"run", "-d", "--name=maskCtr2", "--security-opt", "unmask=/proc/acpi:/sys/firmware", ALPINE, "sleep", "200"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"exec", "maskCtr2", "ls", "/sys/firmware"})
session.WaitWithDefaultTimeout()
Expect(session.OutputToString()).To(Not(BeEmpty()))
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"exec", "maskCtr2", "ls", "/proc/acpi"})
session.WaitWithDefaultTimeout()
Expect(session.OutputToString()).To(Not(BeEmpty()))
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "-d", "--name=maskCtr3", "--security-opt", "mask=/sys/power/disk", ALPINE, "sleep", "200"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"exec", "maskCtr3", "cat", "/sys/power/disk"})
session.WaitWithDefaultTimeout()
Expect(session.OutputToString()).To(BeEmpty())
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "-d", "--name=maskCtr4", "--security-opt", "systempaths=unconfined", ALPINE, "sleep", "200"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"exec", "maskCtr4", "ls", "/sys/firmware"})
session.WaitWithDefaultTimeout()
Expect(session.OutputToString()).To(Not(BeEmpty()))
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "-d", "--name=maskCtr5", "--security-opt", "systempaths=unconfined", ALPINE, "grep", "/proc", "/proc/self/mounts"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToStringArray()).Should(HaveLen(1))
session = podmanTest.Podman([]string{"run", "-d", "--security-opt", "unmask=/proc/*", ALPINE, "grep", "/proc", "/proc/self/mounts"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToStringArray()).Should(HaveLen(1))
session = podmanTest.Podman([]string{"run", "--security-opt", "unmask=/proc/a*", ALPINE, "ls", "/proc/acpi"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Not(BeEmpty()))
})
It("podman run security-opt unmask on /sys/fs/cgroup", func() {
SkipIfCgroupV1("podman umask on /sys/fs/cgroup will fail with cgroups V1")
SkipIfRootless("/sys/fs/cgroup rw access is needed")
rwOnCgroups := "/sys/fs/cgroup cgroup2 rw"
session := podmanTest.Podman([]string{"run", "--security-opt", "unmask=ALL", "--security-opt", "mask=/sys/fs/cgroup", ALPINE, "cat", "/proc/mounts"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring(rwOnCgroups))
session = podmanTest.Podman([]string{"run", "--security-opt", "unmask=/sys/fs/cgroup", ALPINE, "cat", "/proc/mounts"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring(rwOnCgroups))
session = podmanTest.Podman([]string{"run", "--security-opt", "unmask=/sys/fs/cgroup///", ALPINE, "cat", "/proc/mounts"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring(rwOnCgroups))
session = podmanTest.Podman([]string{"run", "--security-opt", "unmask=ALL", ALPINE, "cat", "/proc/mounts"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring(rwOnCgroups))
session = podmanTest.Podman([]string{"run", "--security-opt", "unmask=/sys/fs/cgroup", "--security-opt", "mask=/sys/fs/cgroup", ALPINE, "cat", "/proc/mounts"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring(rwOnCgroups))
session = podmanTest.Podman([]string{"run", "--security-opt", "unmask=/sys/fs/cgroup", ALPINE, "ls", "/sys/fs/cgroup"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).ToNot(BeEmpty())
})
It("podman run seccomp test", func() {
session := podmanTest.Podman([]string{"run", "-it", "--security-opt", strings.Join([]string{"seccomp=", forbidGetCWDSeccompProfile()}, ""), ALPINE, "pwd"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
Expect(session.OutputToString()).To(ContainSubstring("Operation not permitted"))
})
It("podman run seccomp test --privileged", func() {
session := podmanTest.Podman([]string{"run", "-it", "--privileged", "--security-opt", strings.Join([]string{"seccomp=", forbidGetCWDSeccompProfile()}, ""), ALPINE, "pwd"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
Expect(session.OutputToString()).To(ContainSubstring("Operation not permitted"))
})
It("podman run seccomp test --privileged no profile should be unconfined", func() {
session := podmanTest.Podman([]string{"run", "-it", "--privileged", ALPINE, "grep", "Seccomp", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session.OutputToString()).To(ContainSubstring("0"))
Expect(session).Should(Exit(0))
})
It("podman run seccomp test no profile should be default", func() {
session := podmanTest.Podman([]string{"run", "-it", ALPINE, "grep", "Seccomp", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session.OutputToString()).To(ContainSubstring("2"))
Expect(session).Should(Exit(0))
})
It("podman run capabilities test", func() {
session := podmanTest.Podman([]string{"run", "--rm", "--cap-add", "all", ALPINE, "cat", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--rm", "--cap-add", "sys_admin", ALPINE, "cat", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--rm", "--cap-drop", "all", ALPINE, "cat", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--rm", "--cap-drop", "setuid", ALPINE, "cat", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
})
It("podman run user capabilities test", func() {
// We need to ignore the containers.conf on the test distribution for this test
os.Setenv("CONTAINERS_CONF", "/dev/null")
if IsRemote() {
podmanTest.RestartRemoteService()
}
session := podmanTest.Podman([]string{"run", "--rm", "--user", "bin", ALPINE, "grep", "CapBnd", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("00000000a80425fb"))
session = podmanTest.Podman([]string{"run", "--rm", "--user", "bin", ALPINE, "grep", "CapEff", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("0000000000000000"))
session = podmanTest.Podman([]string{"run", "--rm", "--user", "bin", ALPINE, "grep", "CapInh", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("0000000000000000"))
session = podmanTest.Podman([]string{"run", "--rm", "--user", "root", ALPINE, "grep", "CapBnd", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("00000000a80425fb"))
session = podmanTest.Podman([]string{"run", "--rm", "--user", "root", ALPINE, "grep", "CapEff", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("00000000a80425fb"))
session = podmanTest.Podman([]string{"run", "--rm", "--user", "root", ALPINE, "grep", "CapInh", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("0000000000000000"))
session = podmanTest.Podman([]string{"run", "--rm", ALPINE, "grep", "CapBnd", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("00000000a80425fb"))
session = podmanTest.Podman([]string{"run", "--rm", ALPINE, "grep", "CapEff", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("00000000a80425fb"))
session = podmanTest.Podman([]string{"run", "--user=1000:1000", "--cap-add=DAC_OVERRIDE", "--rm", ALPINE, "grep", "CapAmb", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("0000000000000002"))
session = podmanTest.Podman([]string{"run", "--user=1000:1000", "--cap-add=DAC_OVERRIDE", "--rm", ALPINE, "grep", "CapInh", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("0000000000000002"))
session = podmanTest.Podman([]string{"run", "--user=0", "--cap-add=DAC_OVERRIDE", "--rm", ALPINE, "grep", "CapAmb", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("0000000000000000"))
session = podmanTest.Podman([]string{"run", "--user=0:0", "--cap-add=DAC_OVERRIDE", "--rm", ALPINE, "grep", "CapAmb", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("0000000000000000"))
session = podmanTest.Podman([]string{"run", "--user=0:0", "--cap-add=DAC_OVERRIDE", "--rm", ALPINE, "grep", "CapInh", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("0000000000000000"))
if os.Geteuid() > 0 {
if os.Getenv("SKIP_USERNS") != "" {
Skip("Skip userns tests.")
}
if _, err := os.Stat("/proc/self/uid_map"); err != nil {
Skip("User namespaces not supported.")
}
session = podmanTest.Podman([]string{"run", "--userns=keep-id", "--cap-add=DAC_OVERRIDE", "--rm", ALPINE, "grep", "CapAmb", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("0000000000000002"))
session = podmanTest.Podman([]string{"run", "--userns=keep-id", "--privileged", "--rm", ALPINE, "grep", "CapInh", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("0000000000000000"))
session = podmanTest.Podman([]string{"run", "--userns=keep-id", "--cap-add=DAC_OVERRIDE", "--rm", ALPINE, "grep", "CapInh", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("0000000000000002"))
}
})
It("podman run user capabilities test with image", func() {
// We need to ignore the containers.conf on the test distribution for this test
os.Setenv("CONTAINERS_CONF", "/dev/null")
if IsRemote() {
podmanTest.RestartRemoteService()
}
dockerfile := fmt.Sprintf(`FROM %s
USER bin`, BB)
podmanTest.BuildImage(dockerfile, "test", "false")
session := podmanTest.Podman([]string{"run", "--rm", "--user", "bin", "test", "grep", "CapBnd", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("00000000a80425fb"))
session = podmanTest.Podman([]string{"run", "--rm", "--user", "bin", "test", "grep", "CapEff", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("0000000000000000"))
})
It("podman run limits test", func() {
SkipIfRootlessCgroupsV1("Setting limits not supported on cgroupv1 for rootless users")
if !isRootless() {
session := podmanTest.Podman([]string{"run", "--rm", "--ulimit", "rtprio=99", "--cap-add=sys_nice", fedoraMinimal, "cat", "/proc/self/sched"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
}
session := podmanTest.Podman([]string{"run", "--rm", "--ulimit", "nofile=2048:2048", fedoraMinimal, "ulimit", "-n"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("2048"))
session = podmanTest.Podman([]string{"run", "--rm", "--ulimit", "nofile=1024:1028", fedoraMinimal, "ulimit", "-n"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("1024"))
if !CGROUPSV2 {
// --oom-kill-disable not supported on cgroups v2.
session = podmanTest.Podman([]string{"run", "--rm", "--oom-kill-disable=true", fedoraMinimal, "echo", "memory-hog"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
}
session = podmanTest.Podman([]string{"run", "--rm", "--oom-score-adj=111", fedoraMinimal, "cat", "/proc/self/oom_score_adj"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal("111"))
})
It("podman run limits host test", func() {
SkipIfRemote("This can only be used for local tests")
var l syscall.Rlimit
err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"run", "--rm", "--ulimit", "host", fedoraMinimal, "ulimit", "-Hn"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
ulimitCtrStr := strings.TrimSpace(session.OutputToString())
ulimitCtr, err := strconv.ParseUint(ulimitCtrStr, 10, 0)
Expect(err).To(BeNil())
Expect(ulimitCtr).Should(BeNumerically(">=", l.Max))
})
It("podman run with cidfile", func() {
session := podmanTest.Podman([]string{"run", "--cidfile", tempdir + "cidfile", ALPINE, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
err := os.Remove(tempdir + "cidfile")
Expect(err).To(BeNil())
})
It("podman run sysctl test", func() {
SkipIfRootless("Network sysctls are not available root rootless")
session := podmanTest.Podman([]string{"run", "--rm", "--sysctl", "net.core.somaxconn=65535", ALPINE, "sysctl", "net.core.somaxconn"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("net.core.somaxconn = 65535"))
// network sysctls should fail if --net=host is set
session = podmanTest.Podman([]string{"run", "--net", "host", "--rm", "--sysctl", "net.core.somaxconn=65535", ALPINE, "sysctl", "net.core.somaxconn"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(125))
})
It("podman run blkio-weight test", func() {
SkipIfRootlessCgroupsV1("Setting blkio-weight not supported on cgroupv1 for rootless users")
SkipIfRootless("By default systemd doesn't delegate io to rootless users")
if CGROUPSV2 {
if _, err := os.Stat("/sys/fs/cgroup/io.stat"); os.IsNotExist(err) {
Skip("Kernel does not have io.stat")
}
if _, err := os.Stat("/sys/fs/cgroup/system.slice/io.bfq.weight"); os.IsNotExist(err) {
Skip("Kernel does not support BFQ IO scheduler")
}
session := podmanTest.Podman([]string{"run", "--rm", "--blkio-weight=15", ALPINE, "sh", "-c", "cat /sys/fs/cgroup/io.bfq.weight"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
// there was a documentation issue in the kernel that reported a different range [1-10000] for the io controller.
// older versions of crun/runc used it. For the time being allow both versions to pass the test.
// FIXME: drop "|51" once all the runtimes we test have the fix in place.
Expect(strings.Replace(session.OutputToString(), "default ", "", 1)).To(MatchRegexp("15|51"))
} else {
if _, err := os.Stat("/sys/fs/cgroup/blkio/blkio.weight"); os.IsNotExist(err) {
Skip("Kernel does not support blkio.weight")
}
session := podmanTest.Podman([]string{"run", "--rm", "--blkio-weight=15", ALPINE, "cat", "/sys/fs/cgroup/blkio/blkio.weight"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("15"))
}
})
It("podman run device-read-bps test", func() {
SkipIfRootless("FIXME: requested cgroup controller `io` is not available")
SkipIfRootlessCgroupsV1("Setting device-read-bps not supported on cgroupv1 for rootless users")
var session *PodmanSessionIntegration
if CGROUPSV2 {
session = podmanTest.Podman([]string{"run", "--rm", "--device-read-bps=/dev/zero:1mb", ALPINE, "sh", "-c", "cat /sys/fs/cgroup/$(sed -e 's|0::||' < /proc/self/cgroup)/io.max"})
} else {
session = podmanTest.Podman([]string{"run", "--rm", "--device-read-bps=/dev/zero:1mb", ALPINE, "cat", "/sys/fs/cgroup/blkio/blkio.throttle.read_bps_device"})
}
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
if !CGROUPSV2 { // TODO: Test Simplification. For now, we only care about exit(0) w/ cgroupsv2
Expect(session.OutputToString()).To(ContainSubstring("1048576"))
}
})
It("podman run device-write-bps test", func() {
SkipIfRootless("FIXME: requested cgroup controller `io` is not available")
SkipIfRootlessCgroupsV1("Setting device-write-bps not supported on cgroupv1 for rootless users")
var session *PodmanSessionIntegration
if CGROUPSV2 {
session = podmanTest.Podman([]string{"run", "--rm", "--device-write-bps=/dev/zero:1mb", ALPINE, "sh", "-c", "cat /sys/fs/cgroup/$(sed -e 's|0::||' < /proc/self/cgroup)/io.max"})
} else {
session = podmanTest.Podman([]string{"run", "--rm", "--device-write-bps=/dev/zero:1mb", ALPINE, "cat", "/sys/fs/cgroup/blkio/blkio.throttle.write_bps_device"})
}
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
if !CGROUPSV2 { // TODO: Test Simplification. For now, we only care about exit(0) w/ cgroupsv2
Expect(session.OutputToString()).To(ContainSubstring("1048576"))
}
})
It("podman run device-read-iops test", func() {
SkipIfRootless("FIXME: requested cgroup controller `io` is not available")
SkipIfRootlessCgroupsV1("Setting device-read-iops not supported on cgroupv1 for rootless users")
var session *PodmanSessionIntegration
if CGROUPSV2 {
session = podmanTest.Podman([]string{"run", "--rm", "--device-read-iops=/dev/zero:100", ALPINE, "sh", "-c", "cat /sys/fs/cgroup/$(sed -e 's|0::||' < /proc/self/cgroup)/io.max"})
} else {
session = podmanTest.Podman([]string{"run", "--rm", "--device-read-iops=/dev/zero:100", ALPINE, "cat", "/sys/fs/cgroup/blkio/blkio.throttle.read_iops_device"})
}
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
if !CGROUPSV2 { // TODO: Test Simplification. For now, we only care about exit(0) w/ cgroupsv2
Expect(session.OutputToString()).To(ContainSubstring("100"))
}
})
It("podman run device-write-iops test", func() {
SkipIfRootless("FIXME: requested cgroup controller `io` is not available")
SkipIfRootlessCgroupsV1("Setting device-write-iops not supported on cgroupv1 for rootless users")
var session *PodmanSessionIntegration
if CGROUPSV2 {
session = podmanTest.Podman([]string{"run", "--rm", "--device-write-iops=/dev/zero:100", ALPINE, "sh", "-c", "cat /sys/fs/cgroup/$(sed -e 's|0::||' < /proc/self/cgroup)/io.max"})
} else {
session = podmanTest.Podman([]string{"run", "--rm", "--device-write-iops=/dev/zero:100", ALPINE, "cat", "/sys/fs/cgroup/blkio/blkio.throttle.write_iops_device"})
}
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
if !CGROUPSV2 { // TODO: Test Simplification. For now, we only care about exit(0) w/ cgroupsv2
Expect(session.OutputToString()).To(ContainSubstring("100"))
}
})
It("podman run notify_socket", func() {
SkipIfRemote("This can only be used for local tests")
host := GetHostDistributionInfo()
if host.Distribution != "rhel" && host.Distribution != "centos" && host.Distribution != "fedora" {
Skip("this test requires a working runc")
}
sock := filepath.Join(podmanTest.TempDir, "notify")
addr := net.UnixAddr{
Name: sock,
Net: "unixgram",
}
socket, err := net.ListenUnixgram("unixgram", &addr)
Expect(err).To(BeNil())
defer os.Remove(sock)
defer socket.Close()
os.Setenv("NOTIFY_SOCKET", sock)
defer os.Unsetenv("NOTIFY_SOCKET")
session := podmanTest.Podman([]string{"run", ALPINE, "printenv", "NOTIFY_SOCKET"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(len(session.OutputToStringArray())).To(BeNumerically(">", 0))
})
It("podman run log-opt", func() {
log := filepath.Join(podmanTest.TempDir, "/container.log")
session := podmanTest.Podman([]string{"run", "--rm", "--log-driver", "k8s-file", "--log-opt", fmt.Sprintf("path=%s", log), ALPINE, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
_, err := os.Stat(log)
Expect(err).To(BeNil())
_ = os.Remove(log)
})
It("podman run tagged image", func() {
podmanTest.AddImageToRWStore(BB)
tag := podmanTest.Podman([]string{"tag", BB, "bb"})
tag.WaitWithDefaultTimeout()
Expect(tag).Should(Exit(0))
session := podmanTest.Podman([]string{"run", "--rm", "bb", "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
})
It("podman test hooks", func() {
hcheck := "/run/hookscheck"
hooksDir := tempdir + "/hooks"
os.Mkdir(hooksDir, 0755)
fileutils.CopyFile("hooks/hooks.json", hooksDir)
os.Setenv("HOOK_OPTION", fmt.Sprintf("--hooks-dir=%s", hooksDir))
os.Remove(hcheck)
session := podmanTest.Podman([]string{"run", ALPINE, "ls"})
session.Wait(10)
os.Unsetenv("HOOK_OPTION")
Expect(session).Should(Exit(0))
})
It("podman run with subscription secrets", func() {
SkipIfRemote("--default-mount-file option is not supported in podman-remote")
containersDir := filepath.Join(podmanTest.TempDir, "containers")
err := os.MkdirAll(containersDir, 0755)
Expect(err).To(BeNil())
secretsDir := filepath.Join(podmanTest.TempDir, "rhel", "secrets")
err = os.MkdirAll(secretsDir, 0755)
Expect(err).To(BeNil())
mountsFile := filepath.Join(containersDir, "mounts.conf")
mountString := secretsDir + ":/run/secrets"
err = ioutil.WriteFile(mountsFile, []byte(mountString), 0755)
Expect(err).To(BeNil())
secretsFile := filepath.Join(secretsDir, "test.txt")
secretsString := "Testing secrets mount. I am mounted!"
err = ioutil.WriteFile(secretsFile, []byte(secretsString), 0755)
Expect(err).To(BeNil())
targetDir := tempdir + "/symlink/target"
err = os.MkdirAll(targetDir, 0755)
Expect(err).To(BeNil())
keyFile := filepath.Join(targetDir, "key.pem")
err = ioutil.WriteFile(keyFile, []byte(mountString), 0755)
Expect(err).To(BeNil())
execSession := SystemExec("ln", []string{"-s", targetDir, filepath.Join(secretsDir, "mysymlink")})
Expect(execSession).Should(Exit(0))
session := podmanTest.Podman([]string{"--default-mounts-file=" + mountsFile, "run", "--rm", ALPINE, "cat", "/run/secrets/test.txt"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(secretsString))
session = podmanTest.Podman([]string{"--default-mounts-file=" + mountsFile, "run", "--rm", ALPINE, "ls", "/run/secrets/mysymlink"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("key.pem"))
})
It("podman run with FIPS mode secrets", func() {
SkipIfRootless("rootless can not manipulate system-fips file")
fipsFile := "/etc/system-fips"
err = ioutil.WriteFile(fipsFile, []byte{}, 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"run", "--rm", ALPINE, "ls", "/run/secrets"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("system-fips"))
err = os.Remove(fipsFile)
Expect(err).To(BeNil())
})
It("podman run without group-add", func() {
session := podmanTest.Podman([]string{"run", "--rm", ALPINE, "id"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Not(ContainSubstring("27(video),777,65533(nogroup)")))
})
It("podman run with group-add", func() {
session := podmanTest.Podman([]string{"run", "--rm", "--group-add=audio", "--group-add=nogroup", "--group-add=777", ALPINE, "id"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("777,65533(nogroup)"))
})
It("podman run with user (default)", func() {
session := podmanTest.Podman([]string{"run", "--rm", ALPINE, "id"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("uid=0(root) gid=0(root)"))
})
It("podman run with user (integer, not in /etc/passwd)", func() {
session := podmanTest.Podman([]string{"run", "--rm", "--user=1234", ALPINE, "id"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal("uid=1234(1234) gid=0(root)"))
})
It("podman run with user (integer, in /etc/passwd)", func() {
session := podmanTest.Podman([]string{"run", "--rm", "--user=8", ALPINE, "id"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("uid=8(mail) gid=12(mail)"))
})
It("podman run with user (username)", func() {
session := podmanTest.Podman([]string{"run", "--rm", "--user=mail", ALPINE, "id"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("uid=8(mail) gid=12(mail)"))
})
It("podman run with user:group (username:integer)", func() {
session := podmanTest.Podman([]string{"run", "--rm", "--user=mail:21", ALPINE, "id"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal("uid=8(mail) gid=21(ftp)"))
})
It("podman run with user:group (integer:groupname)", func() {
session := podmanTest.Podman([]string{"run", "--rm", "--user=8:ftp", ALPINE, "id"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal("uid=8(mail) gid=21(ftp)"))
})
It("podman run with user, verify caps dropped", func() {
session := podmanTest.Podman([]string{"run", "--rm", "--user=1234", ALPINE, "grep", "CapEff", "/proc/self/status"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
capEff := strings.Split(session.OutputToString(), " ")
Expect("0000000000000000").To(Equal(capEff[1]))
})
It("podman run with attach stdin outputs container ID", func() {
session := podmanTest.Podman([]string{"run", "--attach", "stdin", ALPINE, "printenv"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
ps := podmanTest.Podman([]string{"ps", "-aq", "--no-trunc"})
ps.WaitWithDefaultTimeout()
Expect(ps).Should(Exit(0))
Expect(ps.OutputToString()).To(ContainSubstring(session.OutputToString()))
})
It("podman run with attach stdout does not print stderr", func() {
session := podmanTest.Podman([]string{"run", "--rm", "--attach", "stdout", ALPINE, "ls", "/doesnotexist"})
session.WaitWithDefaultTimeout()
Expect(session.OutputToString()).To(Equal(""))
})
It("podman run with attach stderr does not print stdout", func() {
session := podmanTest.Podman([]string{"run", "--rm", "--attach", "stderr", ALPINE, "ls", "/"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(""))
})
It("podman run attach nonsense errors", func() {
session := podmanTest.Podman([]string{"run", "--rm", "--attach", "asdfasdf", ALPINE, "ls", "/"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(125))
})
It("podman run exit code on failure to exec", func() {
session := podmanTest.Podman([]string{"run", ALPINE, "/etc"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(126))
})
It("podman run error on exec", func() {
session := podmanTest.Podman([]string{"run", ALPINE, "sh", "-c", "exit 100"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(100))
})
It("podman run with named volume", func() {
session := podmanTest.Podman([]string{"run", "--rm", ALPINE, "stat", "-c", "%a %Y", "/var/tmp"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
perms := session.OutputToString()
session = podmanTest.Podman([]string{"run", "--rm", "-v", "test:/var/tmp", ALPINE, "stat", "-c", "%a %Y", "/var/tmp"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(perms))
})
It("podman run with built-in volume image", func() {
session := podmanTest.Podman([]string{"run", "--rm", redis, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
dockerfile := fmt.Sprintf(`FROM %s
RUN mkdir -p /myvol/data && chown -R mail.0 /myvol
VOLUME ["/myvol/data"]
USER mail`, BB)
podmanTest.BuildImage(dockerfile, "test", "false")
session = podmanTest.Podman([]string{"run", "--rm", "test", "ls", "-al", "/myvol/data"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("mail root"))
})
It("podman run --volumes-from flag", func() {
vol := filepath.Join(podmanTest.TempDir, "vol-test")
err := os.MkdirAll(vol, 0755)
Expect(err).To(BeNil())
filename := "test.txt"
volFile := filepath.Join(vol, filename)
data := "Testing --volumes-from!!!"
err = ioutil.WriteFile(volFile, []byte(data), 0755)
Expect(err).To(BeNil())
mountpoint := "/myvol/"
session := podmanTest.Podman([]string{"create", "--volume", vol + ":" + mountpoint + ":z", ALPINE, "cat", mountpoint + filename})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
ctrID := session.OutputToString()
session = podmanTest.Podman([]string{"run", "--volumes-from", ctrID, ALPINE, "cat", mountpoint + filename})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(data))
session = podmanTest.Podman([]string{"run", "--volumes-from", ctrID, ALPINE, "sh", "-c", "echo test >> " + mountpoint + filename})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"start", "--attach", ctrID})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(data + "test"))
})
It("podman run --volumes-from flag options", func() {
vol := filepath.Join(podmanTest.TempDir, "vol-test")
err := os.MkdirAll(vol, 0755)
Expect(err).To(BeNil())
filename := "test.txt"
volFile := filepath.Join(vol, filename)
data := "Testing --volumes-from!!!"
err = ioutil.WriteFile(volFile, []byte(data), 0755)
Expect(err).To(BeNil())
mountpoint := "/myvol/"
session := podmanTest.Podman([]string{"create", "--volume", vol + ":" + mountpoint, ALPINE, "cat", mountpoint + filename})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
ctrID := session.OutputToString()
// check that the read only option works
session = podmanTest.Podman([]string{"run", "--volumes-from", ctrID + ":ro", ALPINE, "touch", mountpoint + "abc.txt"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(1))
Expect(session.ErrorToString()).To(ContainSubstring("Read-only file system"))
// check that both z and ro options work
session = podmanTest.Podman([]string{"run", "--volumes-from", ctrID + ":ro,z", ALPINE, "cat", mountpoint + filename})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(data))
// check that multiple ro/rw are not working
session = podmanTest.Podman([]string{"run", "--volumes-from", ctrID + ":ro,rw", ALPINE, "cat", mountpoint + filename})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(125))
Expect(session.ErrorToString()).To(ContainSubstring("cannot set ro or rw options more than once"))
// check that multiple z options are not working
session = podmanTest.Podman([]string{"run", "--volumes-from", ctrID + ":z,z,ro", ALPINE, "cat", mountpoint + filename})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(125))
Expect(session.ErrorToString()).To(ContainSubstring("cannot set :z more than once in mount options"))
// create new read only volume
session = podmanTest.Podman([]string{"create", "--volume", vol + ":" + mountpoint + ":ro", ALPINE, "cat", mountpoint + filename})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
ctrID = session.OutputToString()
// check if the original volume was mounted as read only that --volumes-from also mount it as read only
session = podmanTest.Podman([]string{"run", "--volumes-from", ctrID, ALPINE, "touch", mountpoint + "abc.txt"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(1))
Expect(session.ErrorToString()).To(ContainSubstring("Read-only file system"))
})
It("podman run --volumes-from flag with built-in volumes", func() {
session := podmanTest.Podman([]string{"create", redis, "sh"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
ctrID := session.OutputToString()
session = podmanTest.Podman([]string{"run", "--volumes-from", ctrID, ALPINE, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("data"))
})
It("podman run --volumes flag with multiple volumes", func() {
vol1 := filepath.Join(podmanTest.TempDir, "vol-test1")
err := os.MkdirAll(vol1, 0755)
Expect(err).To(BeNil())
vol2 := filepath.Join(podmanTest.TempDir, "vol-test2")
err = os.MkdirAll(vol2, 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"run", "--volume", vol1 + ":/myvol1:z", "--volume", vol2 + ":/myvol2:z", ALPINE, "touch", "/myvol2/foo.txt"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
})
It("podman run --volumes flag with empty host dir", func() {
vol1 := filepath.Join(podmanTest.TempDir, "vol-test1")
err := os.MkdirAll(vol1, 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"run", "--volume", ":/myvol1:z", ALPINE, "touch", "/myvol2/foo.txt"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
Expect(session.ErrorToString()).To(ContainSubstring("directory cannot be empty"))
session = podmanTest.Podman([]string{"run", "--volume", vol1 + ":", ALPINE, "touch", "/myvol2/foo.txt"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
Expect(session.ErrorToString()).To(ContainSubstring("directory cannot be empty"))
})
It("podman run --mount flag with multiple mounts", func() {
vol1 := filepath.Join(podmanTest.TempDir, "vol-test1")
err := os.MkdirAll(vol1, 0755)
Expect(err).To(BeNil())
vol2 := filepath.Join(podmanTest.TempDir, "vol-test2")
err = os.MkdirAll(vol2, 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"run", "--mount", "type=bind,src=" + vol1 + ",target=/myvol1,z", "--mount", "type=bind,src=" + vol2 + ",target=/myvol2,z", ALPINE, "touch", "/myvol2/foo.txt"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
})
It("podman run findmnt nothing shared", func() {
vol1 := filepath.Join(podmanTest.TempDir, "vol-test1")
err := os.MkdirAll(vol1, 0755)
Expect(err).To(BeNil())
vol2 := filepath.Join(podmanTest.TempDir, "vol-test2")
err = os.MkdirAll(vol2, 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"run", "--volume", vol1 + ":/myvol1:z", "--volume", vol2 + ":/myvol2:z", fedoraMinimal, "findmnt", "-o", "TARGET,PROPAGATION"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Not(ContainSubstring("shared")))
})
It("podman run findmnt shared", func() {
vol1 := filepath.Join(podmanTest.TempDir, "vol-test1")
err := os.MkdirAll(vol1, 0755)
Expect(err).To(BeNil())
vol2 := filepath.Join(podmanTest.TempDir, "vol-test2")
err = os.MkdirAll(vol2, 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"run", "--volume", vol1 + ":/myvol1:z", "--volume", vol2 + ":/myvol2:shared,z", fedoraMinimal, "findmnt", "-o", "TARGET,PROPAGATION"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
match, shared := session.GrepString("shared")
Expect(match).Should(BeTrue())
// make sure it's only shared (and not 'shared,slave')
isSharedOnly := !strings.Contains(shared[0], "shared,")
Expect(isSharedOnly).Should(BeTrue())
})
It("podman run --security-opts proc-opts=", func() {
session := podmanTest.Podman([]string{"run", "--security-opt", "proc-opts=nosuid,exec", fedoraMinimal, "findmnt", "-noOPTIONS", "/proc"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
output := session.OutputToString()
Expect(output).To(ContainSubstring("nosuid"))
Expect(output).To(Not(ContainSubstring("exec")))
})
It("podman run --mount type=bind,bind-nonrecursive", func() {
SkipIfRootless("FIXME: rootless users are not allowed to mount bind-nonrecursive (Could this be a Kernel bug?")
session := podmanTest.Podman([]string{"run", "--mount", "type=bind,bind-nonrecursive,slave,src=/,target=/host", fedoraMinimal, "findmnt", "-nR", "/host"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToStringArray()).To(HaveLen(1))
})
It("podman run --mount type=devpts,target=/foo/bar", func() {
session := podmanTest.Podman([]string{"run", "--mount", "type=devpts,target=/foo/bar", fedoraMinimal, "stat", "-f", "-c%T", "/foo/bar"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("devpts"))
})
It("podman run --mount type=devpts,target=/dev/pts with uid, gid and mode", func() {
// runc doesn't seem to honor uid= so avoid testing it
session := podmanTest.Podman([]string{"run", "-t", "--mount", "type=devpts,target=/dev/pts,uid=1000,gid=1001,mode=123", fedoraMinimal, "stat", "-c%g-%a", "/dev/pts/0"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("1001-123"))
})
It("podman run --pod automatically", func() {
session := podmanTest.Podman([]string{"run", "-d", "--pod", "new:foobar", ALPINE, "nc", "-l", "-p", "8686"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--pod", "foobar", ALPINE, "/bin/sh", "-c", "echo test | nc -w 1 127.0.0.1 8686"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
check := podmanTest.Podman([]string{"pod", "ps", "--no-trunc"})
check.WaitWithDefaultTimeout()
Expect(check.OutputToString()).To(ContainSubstring("foobar"))
})
It("podman run --pod new with hostname", func() {
hostname := "abc"
session := podmanTest.Podman([]string{"run", "--pod", "new:foobar", "--hostname", hostname, ALPINE, "cat", "/etc/hostname"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring(hostname))
})
It("podman run --rm should work", func() {
session := podmanTest.Podman([]string{"run", "--name", "test", "--rm", ALPINE, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"wait", "test"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
numContainers := podmanTest.NumberOfContainers()
Expect(numContainers).To(Equal(0))
})
It("podman run --rm failed container should delete itself", func() {
session := podmanTest.Podman([]string{"run", "--name", "test", "--rm", ALPINE, "foo"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
session = podmanTest.Podman([]string{"wait", "test"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
numContainers := podmanTest.NumberOfContainers()
Expect(numContainers).To(Equal(0))
})
It("podman run failed container should NOT delete itself", func() {
session := podmanTest.Podman([]string{"run", ALPINE, "foo"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
// If remote we could have a race condition
session = podmanTest.Podman([]string{"wait", "test"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
numContainers := podmanTest.NumberOfContainers()
Expect(numContainers).To(Equal(1))
})
It("podman run readonly container should NOT mount /dev/shm read/only", func() {
session := podmanTest.Podman([]string{"run", "--read-only", ALPINE, "mount"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Not(ContainSubstring("/dev/shm type tmpfs (ro,")))
})
It("podman run readonly container should NOT mount /run noexec", func() {
session := podmanTest.Podman([]string{"run", "--read-only", ALPINE, "sh", "-c", "mount | grep \"/run \""})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Not(ContainSubstring("noexec")))
})
It("podman run with bad healthcheck retries", func() {
session := podmanTest.Podman([]string{"run", "-dt", "--health-cmd", "[\"foo\"]", "--health-retries", "0", ALPINE, "top"})
session.Wait()
Expect(session).To(ExitWithError())
Expect(session.ErrorToString()).To(ContainSubstring("healthcheck-retries must be greater than 0"))
})
It("podman run with bad healthcheck timeout", func() {
session := podmanTest.Podman([]string{"run", "-dt", "--health-cmd", "foo", "--health-timeout", "0s", ALPINE, "top"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
Expect(session.ErrorToString()).To(ContainSubstring("healthcheck-timeout must be at least 1 second"))
})
It("podman run with bad healthcheck start-period", func() {
session := podmanTest.Podman([]string{"run", "-dt", "--health-cmd", "foo", "--health-start-period", "-1s", ALPINE, "top"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
Expect(session.ErrorToString()).To(ContainSubstring("healthcheck-start-period must be 0 seconds or greater"))
})
It("podman run with --add-host and --no-hosts fails", func() {
session := podmanTest.Podman([]string{"run", "-dt", "--add-host", "test1:127.0.0.1", "--no-hosts", ALPINE, "top"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
})
It("podman run with restart-policy always restarts containers", func() {
testDir := filepath.Join(podmanTest.RunRoot, "restart-test")
err := os.MkdirAll(testDir, 0755)
Expect(err).To(BeNil())
aliveFile := filepath.Join(testDir, "running")
file, err := os.Create(aliveFile)
Expect(err).To(BeNil())
file.Close()
session := podmanTest.Podman([]string{"run", "-dt", "--restart", "always", "-v", fmt.Sprintf("%s:/tmp/runroot:Z", testDir), ALPINE, "sh", "-c", "touch /tmp/runroot/ran && while test -r /tmp/runroot/running; do sleep 0.1s; done"})
found := false
testFile := filepath.Join(testDir, "ran")
for i := 0; i < 30; i++ {
time.Sleep(1 * time.Second)
if _, err := os.Stat(testFile); err == nil {
found = true
err = os.Remove(testFile)
Expect(err).To(BeNil())
break
}
}
Expect(found).To(BeTrue())
err = os.Remove(aliveFile)
Expect(err).To(BeNil())
session.WaitWithDefaultTimeout()
// 10 seconds to restart the container
found = false
for i := 0; i < 10; i++ {
time.Sleep(1 * time.Second)
if _, err := os.Stat(testFile); err == nil {
found = true
break
}
}
Expect(found).To(BeTrue())
})
It("podman run with cgroups=split", func() {
SkipIfNotSystemd(podmanTest.CgroupManager, "do not test --cgroups=split if not running on systemd")
SkipIfRootlessCgroupsV1("Disable cgroups not supported on cgroupv1 for rootless users")
SkipIfRemote("--cgroups=split cannot be used in remote mode")
checkLines := func(lines []string) {
cgroup := ""
for _, line := range lines {
parts := strings.SplitN(line, ":", 3)
if len(parts) < 2 {
continue
}
if !CGROUPSV2 {
// ignore unified on cgroup v1.
// both runc and crun do not set it.
// crun does not set named hierarchies.
if parts[1] == "" || strings.Contains(parts[1], "name=") {
continue
}
}
if parts[2] == "/" {
continue
}
if cgroup == "" {
cgroup = parts[2]
continue
}
Expect(cgroup).To(Equal(parts[2]))
}
}
container := podmanTest.PodmanSystemdScope([]string{"run", "--rm", "--cgroups=split", ALPINE, "cat", "/proc/self/cgroup"})
container.WaitWithDefaultTimeout()
Expect(container).Should(Exit(0))
checkLines(container.OutputToStringArray())
// check that --cgroups=split is honored also when a container runs in a pod
container = podmanTest.PodmanSystemdScope([]string{"run", "--rm", "--pod", "new:split-test-pod", "--cgroups=split", ALPINE, "cat", "/proc/self/cgroup"})
container.WaitWithDefaultTimeout()
Expect(container).Should(Exit(0))
checkLines(container.OutputToStringArray())
})
It("podman run with cgroups=disabled runs without cgroups", func() {
SkipIfRootlessCgroupsV1("Disable cgroups not supported on cgroupv1 for rootless users")
// Only works on crun
if !strings.Contains(podmanTest.OCIRuntime, "crun") {
Skip("Test only works on crun")
}
ownsCgroup, err := cgroups.UserOwnsCurrentSystemdCgroup()
Expect(err).ShouldNot(HaveOccurred())
if !ownsCgroup {
// Podman moves itself to a new cgroup if it doesn't own the current cgroup
Skip("Test only works when Podman owns the current cgroup")
}
trim := func(i string) string {
return strings.TrimSuffix(i, "\n")
}
curCgroupsBytes, err := ioutil.ReadFile("/proc/self/cgroup")
Expect(err).ShouldNot(HaveOccurred())
curCgroups := trim(string(curCgroupsBytes))
fmt.Printf("Output:\n%s\n", curCgroups)
Expect(curCgroups).ToNot(Equal(""))
container := podmanTest.Podman([]string{"run", "--cgroupns=host", "--cgroups=disabled", ALPINE, "cat", "/proc/self/cgroup"})
container.WaitWithDefaultTimeout()
Expect(container).Should(Exit(0))
ctrCgroups := trim(container.OutputToString())
fmt.Printf("Output\n:%s\n", ctrCgroups)
Expect(ctrCgroups).To(Equal(curCgroups))
})
It("podman run with cgroups=enabled makes cgroups", func() {
SkipIfRootlessCgroupsV1("Enable cgroups not supported on cgroupv1 for rootless users")
// Only works on crun
if !strings.Contains(podmanTest.OCIRuntime, "crun") {
Skip("Test only works on crun")
}
curCgroupsBytes, err := ioutil.ReadFile("/proc/self/cgroup")
Expect(err).To(BeNil())
var curCgroups string = string(curCgroupsBytes)
fmt.Printf("Output:\n%s\n", curCgroups)
Expect(curCgroups).To(Not(Equal("")))
ctrName := "testctr"
container := podmanTest.Podman([]string{"run", "--name", ctrName, "-d", "--cgroups=enabled", ALPINE, "top"})
container.WaitWithDefaultTimeout()
Expect(container).Should(Exit(0))
// Get PID and get cgroups of that PID
inspectOut := podmanTest.InspectContainer(ctrName)
Expect(inspectOut).To(HaveLen(1))
pid := inspectOut[0].State.Pid
Expect(pid).To(Not(Equal(0)))
ctrCgroupsBytes, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/cgroup", pid))
Expect(err).To(BeNil())
var ctrCgroups string = string(ctrCgroupsBytes)
fmt.Printf("Output\n:%s\n", ctrCgroups)
Expect(curCgroups).To(Not(Equal(ctrCgroups)))
})
It("podman run with cgroups=garbage errors", func() {
session := podmanTest.Podman([]string{"run", "-d", "--cgroups=garbage", ALPINE, "top"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
})
It("podman run should fail with nonexistent authfile", func() {
session := podmanTest.Podman([]string{"run", "--authfile", "/tmp/nonexistent", ALPINE, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
})
It("podman run --device-cgroup-rule", func() {
SkipIfRootless("rootless users are not allowed to mknod")
deviceCgroupRule := "c 42:* rwm"
session := podmanTest.Podman([]string{"run", "--cap-add", "mknod", "--name", "test", "-d", "--device-cgroup-rule", deviceCgroupRule, ALPINE, "top"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"exec", "test", "mknod", "newDev", "c", "42", "1"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
})
It("podman run --replace", func() {
// Make sure we error out with --name.
session := podmanTest.Podman([]string{"create", "--replace", ALPINE, "/bin/sh"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(125))
// Run and replace 5 times in a row the "same" container.
ctrName := "testCtr"
for i := 0; i < 5; i++ {
session := podmanTest.Podman([]string{"run", "--detach", "--replace", "--name", ctrName, ALPINE, "/bin/sh"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
}
})
It("podman run --preserve-fds", func() {
devNull, err := os.Open("/dev/null")
Expect(err).To(BeNil())
defer devNull.Close()
files := []*os.File{
devNull,
}
session := podmanTest.PodmanExtraFiles([]string{"run", "--preserve-fds", "1", ALPINE, "ls"}, files)
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
})
It("podman run --preserve-fds invalid fd", func() {
session := podmanTest.Podman([]string{"run", "--preserve-fds", "2", ALPINE})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
Expect(session.ErrorToString()).To(ContainSubstring("file descriptor 3 is not available"))
})
It("podman run --privileged and --group-add", func() {
groupName := "mail"
session := podmanTest.Podman([]string{"run", "-t", "-i", "--group-add", groupName, "--privileged", fedoraMinimal, "groups"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring(groupName))
})
It("podman run --tz", func() {
testDir := filepath.Join(podmanTest.RunRoot, "tz-test")
err := os.MkdirAll(testDir, 0755)
Expect(err).To(BeNil())
tzFile := filepath.Join(testDir, "tzfile.txt")
file, err := os.Create(tzFile)
Expect(err).To(BeNil())
_, err = file.WriteString("Hello")
Expect(err).To(BeNil())
file.Close()
badTZFile := fmt.Sprintf("../../../%s", tzFile)
session := podmanTest.Podman([]string{"run", "--tz", badTZFile, "--rm", ALPINE, "date"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
Expect(session.ErrorToString()).To(ContainSubstring("finding timezone for container"))
err = os.Remove(tzFile)
Expect(err).To(BeNil())
session = podmanTest.Podman([]string{"run", "--tz", "foo", "--rm", ALPINE, "date"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
session = podmanTest.Podman([]string{"run", "--tz", "America", "--rm", ALPINE, "date"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
session = podmanTest.Podman([]string{"run", "--tz", "Pacific/Honolulu", "--rm", ALPINE, "date", "+'%H %Z'"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("HST"))
session = podmanTest.Podman([]string{"run", "--tz", "local", "--rm", ALPINE, "date", "+'%H %Z'"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
t := time.Now()
z, _ := t.Zone()
h := strconv.Itoa(t.Hour())
Expect(session.OutputToString()).To(ContainSubstring(z))
Expect(session.OutputToString()).To(ContainSubstring(h))
})
It("podman run verify pids-limit", func() {
SkipIfCgroupV1("pids-limit not supported on cgroup V1")
limit := "4321"
session := podmanTest.Podman([]string{"run", "--pids-limit", limit, "--net=none", "--rm", ALPINE, "cat", "/sys/fs/cgroup/pids.max"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring(limit))
})
It("podman run umask", func() {
if !strings.Contains(podmanTest.OCIRuntime, "crun") {
Skip("Test only works on crun")
}
session := podmanTest.Podman([]string{"run", "--rm", ALPINE, "sh", "-c", "umask"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal("0022"))
session = podmanTest.Podman([]string{"run", "--umask", "0002", "--rm", ALPINE, "sh", "-c", "umask"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal("0002"))
session = podmanTest.Podman([]string{"run", "--umask", "0077", "--rm", fedoraMinimal, "umask"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal("0077"))
session = podmanTest.Podman([]string{"run", "--umask", "22", "--rm", ALPINE, "sh", "-c", "umask"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal("0022"))
session = podmanTest.Podman([]string{"run", "--umask", "9999", "--rm", ALPINE, "sh", "-c", "umask"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
Expect(session.ErrorToString()).To(ContainSubstring("Invalid umask"))
})
It("podman run makes workdir from image", func() {
// BuildImage does not seem to work remote
dockerfile := fmt.Sprintf(`FROM %s
WORKDIR /madethis`, BB)
podmanTest.BuildImage(dockerfile, "test", "false")
session := podmanTest.Podman([]string{"run", "--rm", "test", "pwd"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("/madethis"))
})
It("podman run --entrypoint does not use image command", func() {
session := podmanTest.Podman([]string{"run", "--entrypoint", "/bin/echo", ALPINE})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
// We can't guarantee the output is completely empty, some
// nonprintables seem to work their way in.
Expect(session.OutputToString()).To(Not(ContainSubstring("/bin/sh")))
})
It("podman run a container with log-level (lower case)", func() {
session := podmanTest.Podman([]string{"--log-level=info", "run", ALPINE, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
})
It("podman run a container with log-level (upper case)", func() {
session := podmanTest.Podman([]string{"--log-level=INFO", "run", ALPINE, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
})
It("podman run a container with --pull never should fail if no local store", func() {
session := podmanTest.Podman([]string{"run", "--pull", "never", "docker.io/library/debian:latest", "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(125))
})
It("podman run container with --pull missing and only pull once", func() {
session := podmanTest.Podman([]string{"run", "--pull", "missing", cirros, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.ErrorToString()).To(ContainSubstring("Trying to pull"))
session = podmanTest.Podman([]string{"run", "--pull", "missing", cirros, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.ErrorToString()).ToNot(ContainSubstring("Trying to pull"))
})
It("podman run container with --pull missing should pull image multiple times", func() {
session := podmanTest.Podman([]string{"run", "--pull", "always", cirros, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.ErrorToString()).To(ContainSubstring("Trying to pull"))
session = podmanTest.Podman([]string{"run", "--pull", "always", cirros, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.ErrorToString()).To(ContainSubstring("Trying to pull"))
})
It("podman run container with hostname and hostname environment variable", func() {
hostnameEnv := "test123"
session := podmanTest.Podman([]string{"run", "--hostname", "testctr", "--env", fmt.Sprintf("HOSTNAME=%s", hostnameEnv), ALPINE, "printenv", "HOSTNAME"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring(hostnameEnv))
})
It("podman run --secret", func() {
secretsString := "somesecretdata"
secretFilePath := filepath.Join(podmanTest.TempDir, "secret")
err := ioutil.WriteFile(secretFilePath, []byte(secretsString), 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"secret", "create", "mysecret", secretFilePath})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--secret", "mysecret", "--name", "secr", ALPINE, "cat", "/run/secrets/mysecret"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(secretsString))
session = podmanTest.Podman([]string{"inspect", "secr", "--format", " {{(index .Config.Secrets 0).Name}}"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("mysecret"))
})
It("podman run --secret source=mysecret,type=mount", func() {
secretsString := "somesecretdata"
secretFilePath := filepath.Join(podmanTest.TempDir, "secret")
err := ioutil.WriteFile(secretFilePath, []byte(secretsString), 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"secret", "create", "mysecret", secretFilePath})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--secret", "source=mysecret,type=mount", "--name", "secr", ALPINE, "cat", "/run/secrets/mysecret"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(secretsString))
session = podmanTest.Podman([]string{"inspect", "secr", "--format", " {{(index .Config.Secrets 0).Name}}"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("mysecret"))
})
It("podman run --secret source=mysecret,type=mount with target", func() {
secretsString := "somesecretdata"
secretFilePath := filepath.Join(podmanTest.TempDir, "secret")
err := ioutil.WriteFile(secretFilePath, []byte(secretsString), 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"secret", "create", "mysecret_target", secretFilePath})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--secret", "source=mysecret_target,type=mount,target=hello", "--name", "secr_target", ALPINE, "cat", "/run/secrets/hello"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(secretsString))
session = podmanTest.Podman([]string{"inspect", "secr_target", "--format", " {{(index .Config.Secrets 0).Name}}"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("mysecret_target"))
})
It("podman run --secret source=mysecret,type=mount with target at /tmp", func() {
secretsString := "somesecretdata"
secretFilePath := filepath.Join(podmanTest.TempDir, "secret")
err := ioutil.WriteFile(secretFilePath, []byte(secretsString), 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"secret", "create", "mysecret_target2", secretFilePath})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--secret", "source=mysecret_target2,type=mount,target=/tmp/hello", "--name", "secr_target2", ALPINE, "cat", "/tmp/hello"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(secretsString))
session = podmanTest.Podman([]string{"inspect", "secr_target2", "--format", " {{(index .Config.Secrets 0).Name}}"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("mysecret_target2"))
})
It("podman run --secret source=mysecret,type=env", func() {
secretsString := "somesecretdata"
secretFilePath := filepath.Join(podmanTest.TempDir, "secret")
err := ioutil.WriteFile(secretFilePath, []byte(secretsString), 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"secret", "create", "mysecret", secretFilePath})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--secret", "source=mysecret,type=env", "--name", "secr", ALPINE, "printenv", "mysecret"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(secretsString))
})
It("podman run --secret target option", func() {
secretsString := "somesecretdata"
secretFilePath := filepath.Join(podmanTest.TempDir, "secret")
err := ioutil.WriteFile(secretFilePath, []byte(secretsString), 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"secret", "create", "mysecret", secretFilePath})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--secret", "source=mysecret,type=env,target=anotherplace", "--name", "secr", ALPINE, "printenv", "anotherplace"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(secretsString))
})
It("podman run --secret mount with uid, gid, mode options", func() {
secretsString := "somesecretdata"
secretFilePath := filepath.Join(podmanTest.TempDir, "secret")
err := ioutil.WriteFile(secretFilePath, []byte(secretsString), 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"secret", "create", "mysecret", secretFilePath})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
// check default permissions
session = podmanTest.Podman([]string{"run", "--secret", "mysecret", "--name", "secr", ALPINE, "ls", "-l", "/run/secrets/mysecret"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
output := session.OutputToString()
Expect(output).To(ContainSubstring("-r--r--r--"))
Expect(output).To(ContainSubstring("root"))
session = podmanTest.Podman([]string{"run", "--secret", "source=mysecret,type=mount,uid=1000,gid=1001,mode=777", "--name", "secr2", ALPINE, "ls", "-ln", "/run/secrets/mysecret"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
output = session.OutputToString()
Expect(output).To(ContainSubstring("-rwxrwxrwx"))
Expect(output).To(ContainSubstring("1000"))
Expect(output).To(ContainSubstring("1001"))
})
It("podman run --secret with --user", func() {
secretsString := "somesecretdata"
secretFilePath := filepath.Join(podmanTest.TempDir, "secret")
err := ioutil.WriteFile(secretFilePath, []byte(secretsString), 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"secret", "create", "mysecret", secretFilePath})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
session = podmanTest.Podman([]string{"run", "--secret", "mysecret", "--name", "nonroot", "--user", "200:200", ALPINE, "cat", "/run/secrets/mysecret"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(Equal(secretsString))
})
It("podman run invalid secret option", func() {
secretsString := "somesecretdata"
secretFilePath := filepath.Join(podmanTest.TempDir, "secret")
err := ioutil.WriteFile(secretFilePath, []byte(secretsString), 0755)
Expect(err).To(BeNil())
session := podmanTest.Podman([]string{"secret", "create", "mysecret", secretFilePath})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
// Invalid type
session = podmanTest.Podman([]string{"run", "--secret", "source=mysecret,type=other", "--name", "secr", ALPINE, "printenv", "mysecret"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
// Invalid option
session = podmanTest.Podman([]string{"run", "--secret", "source=mysecret,invalid=invalid", "--name", "secr", ALPINE, "printenv", "mysecret"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
// Option syntax not valid
session = podmanTest.Podman([]string{"run", "--secret", "source=mysecret,type", "--name", "secr", ALPINE, "printenv", "mysecret"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
// mount option with env type
session = podmanTest.Podman([]string{"run", "--secret", "source=mysecret,type=env,uid=1000", "--name", "secr", ALPINE, "printenv", "mysecret"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
// No source given
session = podmanTest.Podman([]string{"run", "--secret", "type=env", "--name", "secr", ALPINE, "printenv", "mysecret"})
session.WaitWithDefaultTimeout()
Expect(session).To(ExitWithError())
})
It("podman run --requires", func() {
depName := "ctr1"
depContainer := podmanTest.Podman([]string{"create", "--name", depName, ALPINE, "top"})
depContainer.WaitWithDefaultTimeout()
Expect(depContainer).Should(Exit(0))
mainName := "ctr2"
mainContainer := podmanTest.Podman([]string{"run", "--name", mainName, "--requires", depName, "-d", ALPINE, "top"})
mainContainer.WaitWithDefaultTimeout()
Expect(mainContainer).Should(Exit(0))
stop := podmanTest.Podman([]string{"stop", "--all"})
stop.WaitWithDefaultTimeout()
Expect(stop).Should(Exit(0))
start := podmanTest.Podman([]string{"start", mainName})
start.WaitWithDefaultTimeout()
Expect(start).Should(Exit(0))
running := podmanTest.Podman([]string{"ps", "-q"})
running.WaitWithDefaultTimeout()
Expect(running).Should(Exit(0))
Expect(running.OutputToStringArray()).To(HaveLen(2))
})
It("podman run with pidfile", func() {
SkipIfRemote("pidfile not handled by remote")
pidfile := tempdir + "pidfile"
session := podmanTest.Podman([]string{"run", "--pidfile", pidfile, ALPINE, "ls"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
readFirstLine := func(path string) string {
content, err := ioutil.ReadFile(path)
Expect(err).To(BeNil())
return strings.Split(string(content), "\n")[0]
}
containerPID := readFirstLine(pidfile)
_, err = strconv.Atoi(containerPID) // Make sure it's a proper integer
Expect(err).To(BeNil())
})
It("podman run check personality support", func() {
// TODO: Remove this as soon as this is merged and made available in our CI https://github.com/opencontainers/runc/pull/3126.
if !strings.Contains(podmanTest.OCIRuntime, "crun") {
Skip("Test only works on crun")
}
session := podmanTest.Podman([]string{"run", "--personality=LINUX32", "--name=testpersonality", ALPINE, "uname", "-a"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
Expect(session.OutputToString()).To(ContainSubstring("i686"))
})
It("podman run /dev/shm has nosuid,noexec,nodev", func() {
session := podmanTest.Podman([]string{"run", ALPINE, "grep", "/dev/shm", "/proc/self/mountinfo"})
session.WaitWithDefaultTimeout()
Expect(session).Should(Exit(0))
output := session.OutputToString()
Expect(output).To(ContainSubstring("nosuid"))
Expect(output).To(ContainSubstring("noexec"))
Expect(output).To(ContainSubstring("nodev"))
})
})
| [
"\"container\"",
"\"SKIP_USERNS\""
]
| []
| [
"container",
"SKIP_USERNS"
]
| [] | ["container", "SKIP_USERNS"] | go | 2 | 0 | |
gallary/asgi.py | """
ASGI config for gallary project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gallary.settings')
application = get_asgi_application()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
inband_test.go | // ----------------------------------------------------------------------
// band implementation and framework for stateless distributed group identity
//
// MIT License
//
// Copyright (c) 2019 Charles Perkins
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// ----------------------------------------------------------------------
package inband
import (
"testing"
"os"
//"fmt"
)
func Test_reporting_nonexistant_keys_and_bandmemory(t *testing.T) {
pkey := "/badpublickeyfilename"
band := "/badbandmemoryfilename"
name := "Anonymous"
i := true
f := false
d := false
want := "open /badpublickeyfilename/id_ed25519: no such file or directory"
if got := Startup(pkey, band, name, i, f, d); got != nil && got.Error() != want {
t.Errorf("Load() = %q, want %q", got.Error(), want)
}else if got == nil{
t.Errorf("Load() = %q, want %q", error(nil), want)
}
}
func Test_Loading_keys(t *testing.T) {
pkey := os.Getenv("HOME")+"/.ssh"
band := os.Getenv("HOME")+"/.ssh/band_memory_ed25519"
if got := Startup( pkey, band, "Anonymous", true, true, false); got != nil {
t.Errorf("Startup( /ed25519/ ) = %q, expected error(nil)", got.Error())
}
want:=error(nil)
if got := recallFromFile(band); got != want {
t.Errorf("recallFromFile( /ed25519/ ) = %q, want %q", got, want)
}
}
| [
"\"HOME\"",
"\"HOME\""
]
| []
| [
"HOME"
]
| [] | ["HOME"] | go | 1 | 0 | |
mabel/logging/log_formatter.py | import os
import re
import hashlib
import logging
import ujson as json # use ujson rather than orjson for compatibility
from functools import lru_cache
from ..utils.colors import COLORS, colorize
from ..utils.ipython import is_running_from_ipython
# if we find a key which matches these strings, we hash the contents
KEYS_TO_SANITIZE = ["password$", "pwd$", ".*_secret$", ".*_key$"]
COLOR_EXCHANGES = {
" ALERT ": "{BOLD_RED} ALERT {OFF}",
" ERROR ": "{RED} ERROR {OFF}",
" DEBUG ": "{GREEN} DEBUG {OFF}",
" AUDIT ": "{YELLOW} AUDIT {OFF}",
" WARNING ": "{CYAN} WARNING {OFF}",
" INFO ": "{BOLD_WHITE} INFO {OFF}",
}
class LogFormatter(logging.Formatter):
def __init__(self, orig_formatter):
"""
Remove sensitive data from records before saving to external logs.
Note that the value is hashed using (SHA256) and only the first 8
characters of the hex-encoded hash are presented. This information
allows values to be traced without disclosing the actual value.
The Sanitizer can only sanitize dictionaries, it doesn't
sanitize strings, which could contain sensitive information
We use the message id as a salt to further protect sensitive
information.
Based On: https://github.com/joocer/cronicl/blob/main/cronicl/utils/sanitizer.py
"""
self.orig_formatter = orig_formatter
def format(self, record):
msg = self.orig_formatter.format(record)
msg = self.sanitize_record(msg)
if "://" in msg:
msg = re.sub(r":\/\/(.*?)\@", r"://{BOLD_PURPLE}<redacted>{OFF}", msg)
return msg
@lru_cache(1)
def _can_colorize(self):
if is_running_from_ipython():
return True
colorterm = os.environ.get("COLORTERM", "").lower()
term = os.environ.get("TERM", "").lower()
return "yes" in colorterm or "true" in colorterm or "256" in term
def color_code(self, record):
if self._can_colorize():
for k, v in COLOR_EXCHANGES.items():
if k in record:
return record.replace(k, v)
return record
def __getattr__(self, attr):
return getattr(self.orig_formatter, attr)
def hash_it(self, value_to_hash):
return hashlib.sha256(value_to_hash.encode()).hexdigest()[:8]
def sanitize_record(self, record):
record = self.color_code(record)
parts = record.split("|")
json_part = parts.pop()
try:
dirty_record = json.loads(json_part)
clean_record = {}
for key, value in dirty_record.items():
if any(
[
True
for expression in KEYS_TO_SANITIZE
if re.match(expression, key, re.IGNORECASE)
]
):
clean_record["{BLUE}" + key + "{OFF}"] = (
"{PURPLE}<redacted:" + self.hash_it(str(value)) + ">{OFF}"
)
else:
value = re.sub("`([^`]*)`", r"`{YELLOW}\1{GREEN}`", f"{value}")
value = re.sub("'([^']*)'", r"'{YELLOW}\1{GREEN}'", f"{value}")
clean_record["{BLUE}" + key + "{OFF}"] = (
"{GREEN}" + f"{value}" + "{OFF}"
)
parts.append(" " + json.dumps(clean_record))
except ValueError:
json_part = re.sub("`([^`]*)`", r"`{YELLOW}\1{OFF}`", f"{json_part}")
json_part = re.sub("'([^']*)'", r"'{YELLOW}\1{OFF}'", f"{json_part}")
json_part = re.sub('"([^"]*)"', r"'{YELLOW}\1{OFF}'", f"{json_part}")
parts.append(" " + json_part.strip())
record = "|".join(parts)
return colorize(record, self._can_colorize())
| []
| []
| [
"TERM",
"COLORTERM"
]
| [] | ["TERM", "COLORTERM"] | python | 2 | 0 | |
vendor/github.com/go-pkgz/rest/middleware.go | package rest
import (
"net/http"
"os"
"runtime/debug"
"strings"
"github.com/go-pkgz/rest/logger"
)
// Wrap converts a list of middlewares to nested calls (in reverse order)
func Wrap(handler http.Handler, mws ...func(http.Handler) http.Handler) http.Handler {
if len(mws) == 0 {
return handler
}
res := handler
for i := len(mws) - 1; i >= 0; i-- {
res = mws[i](res)
}
return res
}
// AppInfo adds custom app-info to the response header
func AppInfo(app, author, version string) func(http.Handler) http.Handler {
f := func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Author", author)
w.Header().Set("App-Name", app)
w.Header().Set("App-Version", version)
if mhost := os.Getenv("MHOST"); mhost != "" {
w.Header().Set("Host", mhost)
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
return f
}
// Ping middleware response with pong to /ping. Stops chain if ping request detected
func Ping(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && strings.HasSuffix(strings.ToLower(r.URL.Path), "/ping") {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("pong"))
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
// Recoverer is a middleware that recovers from panics, logs the panic and returns a HTTP 500 status if possible.
func Recoverer(l logger.Backend) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rvr := recover(); rvr != nil {
l.Logf("request panic, %v", rvr)
l.Logf(string(debug.Stack()))
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}()
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
// Headers middleware adds headers to request
func Headers(headers ...string) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
for _, h := range headers {
elems := strings.Split(h, ":")
if len(elems) != 2 {
continue
}
r.Header.Set(strings.TrimSpace(elems[0]), strings.TrimSpace(elems[1]))
}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
| [
"\"MHOST\""
]
| []
| [
"MHOST"
]
| [] | ["MHOST"] | go | 1 | 0 | |
kubernetes-model/vendor/k8s.io/kubernetes/staging/src/k8s.io/apimachinery/pkg/runtime/converter.go | /**
* Copyright (C) 2015 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package runtime
import (
"bytes"
encodingjson "encoding/json"
"fmt"
"math"
"os"
"reflect"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"k8s.io/apimachinery/pkg/conversion"
"k8s.io/apimachinery/pkg/util/json"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"github.com/golang/glog"
)
// UnstructuredConverter is an interface for converting between interface{}
// and map[string]interface representation.
type UnstructuredConverter interface {
ToUnstructured(obj interface{}) (map[string]interface{}, error)
FromUnstructured(u map[string]interface{}, obj interface{}) error
}
type structField struct {
structType reflect.Type
field int
}
type fieldInfo struct {
name string
nameValue reflect.Value
omitempty bool
}
type fieldsCacheMap map[structField]*fieldInfo
type fieldsCache struct {
sync.Mutex
value atomic.Value
}
func newFieldsCache() *fieldsCache {
cache := &fieldsCache{}
cache.value.Store(make(fieldsCacheMap))
return cache
}
var (
marshalerType = reflect.TypeOf(new(encodingjson.Marshaler)).Elem()
unmarshalerType = reflect.TypeOf(new(encodingjson.Unmarshaler)).Elem()
mapStringInterfaceType = reflect.TypeOf(map[string]interface{}{})
stringType = reflect.TypeOf(string(""))
int64Type = reflect.TypeOf(int64(0))
uint64Type = reflect.TypeOf(uint64(0))
float64Type = reflect.TypeOf(float64(0))
boolType = reflect.TypeOf(bool(false))
fieldCache = newFieldsCache()
// DefaultUnstructuredConverter performs unstructured to Go typed object conversions.
DefaultUnstructuredConverter = &unstructuredConverter{
mismatchDetection: parseBool(os.Getenv("KUBE_PATCH_CONVERSION_DETECTOR")),
comparison: conversion.EqualitiesOrDie(
func(a, b time.Time) bool {
return a.UTC() == b.UTC()
},
),
}
)
func parseBool(key string) bool {
if len(key) == 0 {
return false
}
value, err := strconv.ParseBool(key)
if err != nil {
utilruntime.HandleError(fmt.Errorf("Couldn't parse '%s' as bool for unstructured mismatch detection", key))
}
return value
}
// unstructuredConverter knows how to convert between interface{} and
// Unstructured in both ways.
type unstructuredConverter struct {
// If true, we will be additionally running conversion via json
// to ensure that the result is true.
// This is supposed to be set only in tests.
mismatchDetection bool
// comparison is the default test logic used to compare
comparison conversion.Equalities
}
// NewTestUnstructuredConverter creates an UnstructuredConverter that accepts JSON typed maps and translates them
// to Go types via reflection. It performs mismatch detection automatically and is intended for use by external
// test tools. Use DefaultUnstructuredConverter if you do not explicitly need mismatch detection.
func NewTestUnstructuredConverter(comparison conversion.Equalities) UnstructuredConverter {
return &unstructuredConverter{
mismatchDetection: true,
comparison: comparison,
}
}
// FromUnstructured converts an object from map[string]interface{} representation into a concrete type.
// It uses encoding/json/Unmarshaler if object implements it or reflection if not.
func (c *unstructuredConverter) FromUnstructured(u map[string]interface{}, obj interface{}) error {
t := reflect.TypeOf(obj)
value := reflect.ValueOf(obj)
if t.Kind() != reflect.Ptr || value.IsNil() {
return fmt.Errorf("FromUnstructured requires a non-nil pointer to an object, got %v", t)
}
err := fromUnstructured(reflect.ValueOf(u), value.Elem())
if c.mismatchDetection {
newObj := reflect.New(t.Elem()).Interface()
newErr := fromUnstructuredViaJSON(u, newObj)
if (err != nil) != (newErr != nil) {
glog.Fatalf("FromUnstructured unexpected error for %v: error: %v", u, err)
}
if err == nil && !c.comparison.DeepEqual(obj, newObj) {
glog.Fatalf("FromUnstructured mismatch\nobj1: %#v\nobj2: %#v", obj, newObj)
}
}
return err
}
func fromUnstructuredViaJSON(u map[string]interface{}, obj interface{}) error {
data, err := json.Marshal(u)
if err != nil {
return err
}
return json.Unmarshal(data, obj)
}
func fromUnstructured(sv, dv reflect.Value) error {
sv = unwrapInterface(sv)
if !sv.IsValid() {
dv.Set(reflect.Zero(dv.Type()))
return nil
}
st, dt := sv.Type(), dv.Type()
switch dt.Kind() {
case reflect.Map, reflect.Slice, reflect.Ptr, reflect.Struct, reflect.Interface:
// Those require non-trivial conversion.
default:
// This should handle all simple types.
if st.AssignableTo(dt) {
dv.Set(sv)
return nil
}
// We cannot simply use "ConvertibleTo", as JSON doesn't support conversions
// between those four groups: bools, integers, floats and string. We need to
// do the same.
if st.ConvertibleTo(dt) {
switch st.Kind() {
case reflect.String:
switch dt.Kind() {
case reflect.String:
dv.Set(sv.Convert(dt))
return nil
}
case reflect.Bool:
switch dt.Kind() {
case reflect.Bool:
dv.Set(sv.Convert(dt))
return nil
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
switch dt.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
dv.Set(sv.Convert(dt))
return nil
}
case reflect.Float32, reflect.Float64:
switch dt.Kind() {
case reflect.Float32, reflect.Float64:
dv.Set(sv.Convert(dt))
return nil
}
if sv.Float() == math.Trunc(sv.Float()) {
dv.Set(sv.Convert(dt))
return nil
}
}
return fmt.Errorf("cannot convert %s to %s", st.String(), dt.String())
}
}
// Check if the object has a custom JSON marshaller/unmarshaller.
if reflect.PtrTo(dt).Implements(unmarshalerType) {
data, err := json.Marshal(sv.Interface())
if err != nil {
return fmt.Errorf("error encoding %s to json: %v", st.String(), err)
}
unmarshaler := dv.Addr().Interface().(encodingjson.Unmarshaler)
return unmarshaler.UnmarshalJSON(data)
}
switch dt.Kind() {
case reflect.Map:
return mapFromUnstructured(sv, dv)
case reflect.Slice:
return sliceFromUnstructured(sv, dv)
case reflect.Ptr:
return pointerFromUnstructured(sv, dv)
case reflect.Struct:
return structFromUnstructured(sv, dv)
case reflect.Interface:
return interfaceFromUnstructured(sv, dv)
default:
return fmt.Errorf("unrecognized type: %v", dt.Kind())
}
}
func fieldInfoFromField(structType reflect.Type, field int) *fieldInfo {
fieldCacheMap := fieldCache.value.Load().(fieldsCacheMap)
if info, ok := fieldCacheMap[structField{structType, field}]; ok {
return info
}
// Cache miss - we need to compute the field name.
info := &fieldInfo{}
typeField := structType.Field(field)
jsonTag := typeField.Tag.Get("json")
if len(jsonTag) == 0 {
// Make the first character lowercase.
if typeField.Name == "" {
info.name = typeField.Name
} else {
info.name = strings.ToLower(typeField.Name[:1]) + typeField.Name[1:]
}
} else {
items := strings.Split(jsonTag, ",")
info.name = items[0]
for i := range items {
if items[i] == "omitempty" {
info.omitempty = true
}
}
}
info.nameValue = reflect.ValueOf(info.name)
fieldCache.Lock()
defer fieldCache.Unlock()
fieldCacheMap = fieldCache.value.Load().(fieldsCacheMap)
newFieldCacheMap := make(fieldsCacheMap)
for k, v := range fieldCacheMap {
newFieldCacheMap[k] = v
}
newFieldCacheMap[structField{structType, field}] = info
fieldCache.value.Store(newFieldCacheMap)
return info
}
func unwrapInterface(v reflect.Value) reflect.Value {
for v.Kind() == reflect.Interface {
v = v.Elem()
}
return v
}
func mapFromUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if st.Kind() != reflect.Map {
return fmt.Errorf("cannot restore map from %v", st.Kind())
}
if !st.Key().AssignableTo(dt.Key()) && !st.Key().ConvertibleTo(dt.Key()) {
return fmt.Errorf("cannot copy map with non-assignable keys: %v %v", st.Key(), dt.Key())
}
if sv.IsNil() {
dv.Set(reflect.Zero(dt))
return nil
}
dv.Set(reflect.MakeMap(dt))
for _, key := range sv.MapKeys() {
value := reflect.New(dt.Elem()).Elem()
if val := unwrapInterface(sv.MapIndex(key)); val.IsValid() {
if err := fromUnstructured(val, value); err != nil {
return err
}
} else {
value.Set(reflect.Zero(dt.Elem()))
}
if st.Key().AssignableTo(dt.Key()) {
dv.SetMapIndex(key, value)
} else {
dv.SetMapIndex(key.Convert(dt.Key()), value)
}
}
return nil
}
func sliceFromUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if st.Kind() == reflect.String && dt.Elem().Kind() == reflect.Uint8 {
// We store original []byte representation as string.
// This conversion is allowed, but we need to be careful about
// marshaling data appropriately.
if len(sv.Interface().(string)) > 0 {
marshalled, err := json.Marshal(sv.Interface())
if err != nil {
return fmt.Errorf("error encoding %s to json: %v", st, err)
}
// TODO: Is this Unmarshal needed?
var data []byte
err = json.Unmarshal(marshalled, &data)
if err != nil {
return fmt.Errorf("error decoding from json: %v", err)
}
dv.SetBytes(data)
} else {
dv.Set(reflect.Zero(dt))
}
return nil
}
if st.Kind() != reflect.Slice {
return fmt.Errorf("cannot restore slice from %v", st.Kind())
}
if sv.IsNil() {
dv.Set(reflect.Zero(dt))
return nil
}
dv.Set(reflect.MakeSlice(dt, sv.Len(), sv.Cap()))
for i := 0; i < sv.Len(); i++ {
if err := fromUnstructured(sv.Index(i), dv.Index(i)); err != nil {
return err
}
}
return nil
}
func pointerFromUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if st.Kind() == reflect.Ptr && sv.IsNil() {
dv.Set(reflect.Zero(dt))
return nil
}
dv.Set(reflect.New(dt.Elem()))
switch st.Kind() {
case reflect.Ptr, reflect.Interface:
return fromUnstructured(sv.Elem(), dv.Elem())
default:
return fromUnstructured(sv, dv.Elem())
}
}
func structFromUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if st.Kind() != reflect.Map {
return fmt.Errorf("cannot restore struct from: %v", st.Kind())
}
for i := 0; i < dt.NumField(); i++ {
fieldInfo := fieldInfoFromField(dt, i)
fv := dv.Field(i)
if len(fieldInfo.name) == 0 {
// This field is inlined.
if err := fromUnstructured(sv, fv); err != nil {
return err
}
} else {
value := unwrapInterface(sv.MapIndex(fieldInfo.nameValue))
if value.IsValid() {
if err := fromUnstructured(value, fv); err != nil {
return err
}
} else {
fv.Set(reflect.Zero(fv.Type()))
}
}
}
return nil
}
func interfaceFromUnstructured(sv, dv reflect.Value) error {
// TODO: Is this conversion safe?
dv.Set(sv)
return nil
}
// ToUnstructured converts an object into map[string]interface{} representation.
// It uses encoding/json/Marshaler if object implements it or reflection if not.
func (c *unstructuredConverter) ToUnstructured(obj interface{}) (map[string]interface{}, error) {
var u map[string]interface{}
var err error
if unstr, ok := obj.(Unstructured); ok {
// UnstructuredContent() mutates the object so we need to make a copy first
u = unstr.DeepCopyObject().(Unstructured).UnstructuredContent()
} else {
t := reflect.TypeOf(obj)
value := reflect.ValueOf(obj)
if t.Kind() != reflect.Ptr || value.IsNil() {
return nil, fmt.Errorf("ToUnstructured requires a non-nil pointer to an object, got %v", t)
}
u = map[string]interface{}{}
err = toUnstructured(value.Elem(), reflect.ValueOf(&u).Elem())
}
if c.mismatchDetection {
newUnstr := map[string]interface{}{}
newErr := toUnstructuredViaJSON(obj, &newUnstr)
if (err != nil) != (newErr != nil) {
glog.Fatalf("ToUnstructured unexpected error for %v: error: %v; newErr: %v", obj, err, newErr)
}
if err == nil && !c.comparison.DeepEqual(u, newUnstr) {
glog.Fatalf("ToUnstructured mismatch\nobj1: %#v\nobj2: %#v", u, newUnstr)
}
}
if err != nil {
return nil, err
}
return u, nil
}
// DeepCopyJSON deep copies the passed value, assuming it is a valid JSON representation i.e. only contains
// types produced by json.Unmarshal().
func DeepCopyJSON(x map[string]interface{}) map[string]interface{} {
return DeepCopyJSONValue(x).(map[string]interface{})
}
// DeepCopyJSONValue deep copies the passed value, assuming it is a valid JSON representation i.e. only contains
// types produced by json.Unmarshal().
func DeepCopyJSONValue(x interface{}) interface{} {
switch x := x.(type) {
case map[string]interface{}:
clone := make(map[string]interface{}, len(x))
for k, v := range x {
clone[k] = DeepCopyJSONValue(v)
}
return clone
case []interface{}:
clone := make([]interface{}, len(x))
for i, v := range x {
clone[i] = DeepCopyJSONValue(v)
}
return clone
case string, int64, bool, float64, nil, encodingjson.Number:
return x
default:
panic(fmt.Errorf("cannot deep copy %T", x))
}
}
func toUnstructuredViaJSON(obj interface{}, u *map[string]interface{}) error {
data, err := json.Marshal(obj)
if err != nil {
return err
}
return json.Unmarshal(data, u)
}
var (
nullBytes = []byte("null")
trueBytes = []byte("true")
falseBytes = []byte("false")
)
func getMarshaler(v reflect.Value) (encodingjson.Marshaler, bool) {
// Check value receivers if v is not a pointer and pointer receivers if v is a pointer
if v.Type().Implements(marshalerType) {
return v.Interface().(encodingjson.Marshaler), true
}
// Check pointer receivers if v is not a pointer
if v.Kind() != reflect.Ptr && v.CanAddr() {
v = v.Addr()
if v.Type().Implements(marshalerType) {
return v.Interface().(encodingjson.Marshaler), true
}
}
return nil, false
}
func toUnstructured(sv, dv reflect.Value) error {
// Check if the object has a custom JSON marshaller/unmarshaller.
if marshaler, ok := getMarshaler(sv); ok {
if sv.Kind() == reflect.Ptr && sv.IsNil() {
// We're done - we don't need to store anything.
return nil
}
data, err := marshaler.MarshalJSON()
if err != nil {
return err
}
switch {
case len(data) == 0:
return fmt.Errorf("error decoding from json: empty value")
case bytes.Equal(data, nullBytes):
// We're done - we don't need to store anything.
case bytes.Equal(data, trueBytes):
dv.Set(reflect.ValueOf(true))
case bytes.Equal(data, falseBytes):
dv.Set(reflect.ValueOf(false))
case data[0] == '"':
var result string
err := json.Unmarshal(data, &result)
if err != nil {
return fmt.Errorf("error decoding string from json: %v", err)
}
dv.Set(reflect.ValueOf(result))
case data[0] == '{':
result := make(map[string]interface{})
err := json.Unmarshal(data, &result)
if err != nil {
return fmt.Errorf("error decoding object from json: %v", err)
}
dv.Set(reflect.ValueOf(result))
case data[0] == '[':
result := make([]interface{}, 0)
err := json.Unmarshal(data, &result)
if err != nil {
return fmt.Errorf("error decoding array from json: %v", err)
}
dv.Set(reflect.ValueOf(result))
default:
var (
resultInt int64
resultFloat float64
err error
)
if err = json.Unmarshal(data, &resultInt); err == nil {
dv.Set(reflect.ValueOf(resultInt))
} else if err = json.Unmarshal(data, &resultFloat); err == nil {
dv.Set(reflect.ValueOf(resultFloat))
} else {
return fmt.Errorf("error decoding number from json: %v", err)
}
}
return nil
}
st, dt := sv.Type(), dv.Type()
switch st.Kind() {
case reflect.String:
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
dv.Set(reflect.New(stringType))
}
dv.Set(reflect.ValueOf(sv.String()))
return nil
case reflect.Bool:
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
dv.Set(reflect.New(boolType))
}
dv.Set(reflect.ValueOf(sv.Bool()))
return nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
dv.Set(reflect.New(int64Type))
}
dv.Set(reflect.ValueOf(sv.Int()))
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
dv.Set(reflect.New(uint64Type))
}
dv.Set(reflect.ValueOf(sv.Uint()))
return nil
case reflect.Float32, reflect.Float64:
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
dv.Set(reflect.New(float64Type))
}
dv.Set(reflect.ValueOf(sv.Float()))
return nil
case reflect.Map:
return mapToUnstructured(sv, dv)
case reflect.Slice:
return sliceToUnstructured(sv, dv)
case reflect.Ptr:
return pointerToUnstructured(sv, dv)
case reflect.Struct:
return structToUnstructured(sv, dv)
case reflect.Interface:
return interfaceToUnstructured(sv, dv)
default:
return fmt.Errorf("unrecognized type: %v", st.Kind())
}
}
func mapToUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if sv.IsNil() {
dv.Set(reflect.Zero(dt))
return nil
}
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
if st.Key().Kind() == reflect.String {
switch st.Elem().Kind() {
// TODO It should be possible to reuse the slice for primitive types.
// However, it is panicing in the following form.
// case reflect.String, reflect.Bool,
// reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
// reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
// sv.Set(sv)
// return nil
default:
// We need to do a proper conversion.
}
}
dv.Set(reflect.MakeMap(mapStringInterfaceType))
dv = dv.Elem()
dt = dv.Type()
}
if dt.Kind() != reflect.Map {
return fmt.Errorf("cannot convert struct to: %v", dt.Kind())
}
if !st.Key().AssignableTo(dt.Key()) && !st.Key().ConvertibleTo(dt.Key()) {
return fmt.Errorf("cannot copy map with non-assignable keys: %v %v", st.Key(), dt.Key())
}
for _, key := range sv.MapKeys() {
value := reflect.New(dt.Elem()).Elem()
if err := toUnstructured(sv.MapIndex(key), value); err != nil {
return err
}
if st.Key().AssignableTo(dt.Key()) {
dv.SetMapIndex(key, value)
} else {
dv.SetMapIndex(key.Convert(dt.Key()), value)
}
}
return nil
}
func sliceToUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if sv.IsNil() {
dv.Set(reflect.Zero(dt))
return nil
}
if st.Elem().Kind() == reflect.Uint8 {
dv.Set(reflect.New(stringType))
data, err := json.Marshal(sv.Bytes())
if err != nil {
return err
}
var result string
if err = json.Unmarshal(data, &result); err != nil {
return err
}
dv.Set(reflect.ValueOf(result))
return nil
}
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
switch st.Elem().Kind() {
// TODO It should be possible to reuse the slice for primitive types.
// However, it is panicing in the following form.
// case reflect.String, reflect.Bool,
// reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
// reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
// sv.Set(sv)
// return nil
default:
// We need to do a proper conversion.
dv.Set(reflect.MakeSlice(reflect.SliceOf(dt), sv.Len(), sv.Cap()))
dv = dv.Elem()
dt = dv.Type()
}
}
if dt.Kind() != reflect.Slice {
return fmt.Errorf("cannot convert slice to: %v", dt.Kind())
}
for i := 0; i < sv.Len(); i++ {
if err := toUnstructured(sv.Index(i), dv.Index(i)); err != nil {
return err
}
}
return nil
}
func pointerToUnstructured(sv, dv reflect.Value) error {
if sv.IsNil() {
// We're done - we don't need to store anything.
return nil
}
return toUnstructured(sv.Elem(), dv)
}
func isZero(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.String:
return v.Len() == 0
case reflect.Bool:
return !v.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return v.Int() == 0
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Map, reflect.Slice:
// TODO: It seems that 0-len maps are ignored in it.
return v.IsNil() || v.Len() == 0
case reflect.Ptr, reflect.Interface:
return v.IsNil()
}
return false
}
func structToUnstructured(sv, dv reflect.Value) error {
st, dt := sv.Type(), dv.Type()
if dt.Kind() == reflect.Interface && dv.NumMethod() == 0 {
dv.Set(reflect.MakeMap(mapStringInterfaceType))
dv = dv.Elem()
dt = dv.Type()
}
if dt.Kind() != reflect.Map {
return fmt.Errorf("cannot convert struct to: %v", dt.Kind())
}
realMap := dv.Interface().(map[string]interface{})
for i := 0; i < st.NumField(); i++ {
fieldInfo := fieldInfoFromField(st, i)
fv := sv.Field(i)
if fieldInfo.name == "-" {
// This field should be skipped.
continue
}
if fieldInfo.omitempty && isZero(fv) {
// omitempty fields should be ignored.
continue
}
if len(fieldInfo.name) == 0 {
// This field is inlined.
if err := toUnstructured(fv, dv); err != nil {
return err
}
continue
}
switch fv.Type().Kind() {
case reflect.String:
realMap[fieldInfo.name] = fv.String()
case reflect.Bool:
realMap[fieldInfo.name] = fv.Bool()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
realMap[fieldInfo.name] = fv.Int()
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
realMap[fieldInfo.name] = fv.Uint()
case reflect.Float32, reflect.Float64:
realMap[fieldInfo.name] = fv.Float()
default:
subv := reflect.New(dt.Elem()).Elem()
if err := toUnstructured(fv, subv); err != nil {
return err
}
dv.SetMapIndex(fieldInfo.nameValue, subv)
}
}
return nil
}
func interfaceToUnstructured(sv, dv reflect.Value) error {
if !sv.IsValid() || sv.IsNil() {
dv.Set(reflect.Zero(dv.Type()))
return nil
}
return toUnstructured(sv.Elem(), dv)
}
| [
"\"KUBE_PATCH_CONVERSION_DETECTOR\""
]
| []
| [
"KUBE_PATCH_CONVERSION_DETECTOR"
]
| [] | ["KUBE_PATCH_CONVERSION_DETECTOR"] | go | 1 | 0 | |
system_tests/system_tests_sync/test_app_engine.py | # Copyright 2016 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
TEST_APP_URL = os.environ["TEST_APP_URL"]
def test_live_application(http_request):
response = http_request(method="GET", url=TEST_APP_URL)
assert response.status == 200, response.data.decode("utf-8") | []
| []
| [
"TEST_APP_URL"
]
| [] | ["TEST_APP_URL"] | python | 1 | 0 | |
config.py | """
Configuration settings for Hetaira app.
"""
import os
from pygal.style import Style
# Settings related to Flask and extentions
DEBUG = False
# get the secret key from environment
SECRET_KEY = os.environ['SECRET_KEY']
# NCBI Pubchem PUG-REST settings
PUBCHEM_URL_START = 'http://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/'
PUBCHEM_URL_END = '/property/Fingerprint2D/JSON'
FP = 'fingerprint'
CID = 'cid'
CID_FP = 'Fingerprint2D'
CID_PAD_LEN = 17
# plot settings for pygal
STYLE = Style(label_font_size = 16,
major_label_font_size = 16,
title_font_size = 18,
colors = ('#00b2f0','#ffd541',
'#5ae345','#0662ab', '#42b9de'))
YLAB = [0.0, 0.25, 0.5, 0.75, 1.0]
YTITLE = 'Promiscuity Index'
| []
| []
| [
"SECRET_KEY"
]
| [] | ["SECRET_KEY"] | python | 1 | 0 | |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import os
import re
import sys
from setuptools import setup, Command
__PATH__ = os.path.abspath(os.path.dirname(__file__))
install_requires = [
'six',
'numpy',
'biwrap==0.1.6',
'matplotlib>=2.0.0',
]
test_require = [
'pytest',
'pytest-pudb',
'imgcat',
'termcolor',
'scipy',
'seaborn>=0.8.0',
]
# temporarily redirect config directory to prevent matplotlib and skimage
# cause a SandboxViolationError on Travis CI environments.
os.environ["MPLCONFIGDIR"] = "."
def read_version():
# importing the package causes an ImportError :-)
with open(os.path.join(__PATH__, 'tfplot/__init__.py')) as f:
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
f.read(), re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find __version__ string")
__version__ = read_version()
readme = codecs.open('README.md', encoding='utf-8').read()
# brought from https://github.com/kennethreitz/setup.py
class DeployCommand(Command):
description = 'Build and deploy the package to PyPI.'
user_options = []
def initialize_options(self): pass
def finalize_options(self): pass
@staticmethod
def status(s):
print(s)
def run(self):
import twine # we require twine locally
assert 'dev' not in __version__, \
"Only non-devel versions are allowed. __version__ == {}".format(__version__)
with os.popen("git status --short") as fp:
git_status = fp.read().strip()
if git_status:
print("Error: git repository is not clean.\n")
os.system("git status --short")
sys.exit(1)
try:
from shutil import rmtree
self.status('Removing previous builds ...')
rmtree(os.path.join(__PATH__, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution ...')
os.system('{0} setup.py sdist'.format(sys.executable))
self.status('Uploading the package to PyPI via Twine ...')
ret = os.system('twine upload dist/*')
if ret != 0:
sys.exit(ret)
self.status('Creating git tags ...')
os.system('git tag v{0}'.format(read_version()))
os.system('git tag --list')
sys.exit()
setup(
name='tensorflow-plot',
version=__version__,
description='TensorFlow Plot',
long_description=readme,
license='MIT License',
url='https://github.com/wookayin/tensorflow-plot',
author='Jongwook Choi',
author_email='[email protected]',
keywords='tensorflow matplotlib tensorboard plot tfplot',
packages=[
'tfplot',
],
classifiers=[
# https://pypi.python.org/pypi?%3Aaction=list_classifiers
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
install_requires=install_requires,
tests_require=test_require,
setup_requires=[
'pytest-runner',
],
cmdclass={
'deploy': DeployCommand,
},
include_package_data=True,
zip_safe=False,
)
| []
| []
| [
"MPLCONFIGDIR"
]
| [] | ["MPLCONFIGDIR"] | python | 1 | 0 | |
housing-api/app/config.py | """Configuration file for the Flask app"""
import os
from datetime import timedelta
SECRET_KEY = os.getenv('SECRET_KEY')
def get_database_url():
db_user = os.getenv('DB_USER')
db_password = os.getenv('DB_PWD')
db_host = os.getenv('DB_HOST')
return f'mongodb://{db_user}:{db_password}@{db_host}'
DATABASE_URL = get_database_url()
DATABASE_NAME = os.getenv('DB_NAME')
# ─── FLASK JWT CONFIGURATION ────────────────────────────────────────────────────
JWT_AUTH_USERNAME_KEY = 'email'
JWT_AUTH_PASSWORD_KEY = 'password'
JWT_AUTH_URL_RULE = '/auth/login'
JWT_AUTH_HEADER_PREFIX = 'Bearer'
JWT_EXPIRATION_DELTA = timedelta(hours=1)
| []
| []
| [
"DB_HOST",
"DB_NAME",
"SECRET_KEY",
"DB_PWD",
"DB_USER"
]
| [] | ["DB_HOST", "DB_NAME", "SECRET_KEY", "DB_PWD", "DB_USER"] | python | 5 | 0 | |
workflow/util/pod_name.go | package util
import (
"fmt"
"hash/fnv"
"os"
"github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
"github.com/argoproj/argo-workflows/v3/workflow/common"
)
const (
maxK8sResourceNameLength = 253
k8sNamingHashLength = 10
)
// PodNameVersion stores which type of pod names should be used.
// v1 represents the node id.
// v2 is the combination of a node id and template name.
type PodNameVersion string
const (
// PodNameV1 is the v1 name that uses node ids for pod names
PodNameV1 PodNameVersion = "v1"
// PodNameV2 is the v2 name that uses node id combined with
// the template name
PodNameV2 PodNameVersion = "v2"
)
// String stringifies the pod name version
func (v PodNameVersion) String() string {
return string(v)
}
// GetPodNameVersion returns the pod name version to be used
func GetPodNameVersion() PodNameVersion {
switch os.Getenv("POD_NAMES") {
case "v2":
return PodNameV2
case "v1":
return PodNameV1
default:
return PodNameV1
}
}
// PodName return a deterministic pod name
func PodName(workflowName, nodeName, templateName, nodeID string, version PodNameVersion) string {
if version == PodNameV1 {
return nodeID
}
if workflowName == nodeName {
return workflowName
}
prefix := fmt.Sprintf("%s-%s", workflowName, templateName)
prefix = ensurePodNamePrefixLength(prefix)
h := fnv.New32a()
_, _ = h.Write([]byte(nodeName))
return fmt.Sprintf("%s-%v", prefix, h.Sum32())
}
func ensurePodNamePrefixLength(prefix string) string {
maxPrefixLength := maxK8sResourceNameLength - k8sNamingHashLength
if len(prefix) > maxPrefixLength-1 {
return prefix[0 : maxPrefixLength-1]
}
return prefix
}
// GetWorkflowPodNameVersion gets the pod name version from the annotation of a
// given workflow
func GetWorkflowPodNameVersion(wf *v1alpha1.Workflow) PodNameVersion {
annotations := wf.GetAnnotations()
version := annotations[common.AnnotationKeyPodNameVersion]
if version == PodNameV2.String() {
return PodNameV2
}
return PodNameV1
}
| [
"\"POD_NAMES\""
]
| []
| [
"POD_NAMES"
]
| [] | ["POD_NAMES"] | go | 1 | 0 | |
pubsub/kafkapubsub/kafka.go | // Copyright 2019 The Go Cloud Development Kit Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package kafkapubsub provides an implementation of pubsub for Kafka.
// It requires a minimum Kafka version of 0.11.x for Header support.
// Some functionality may work with earlier versions of Kafka.
//
// See https://kafka.apache.org/documentation.html#semantics for a discussion
// of message semantics in Kafka. sarama.Config exposes many knobs that
// can affect performance and semantics, so review and set them carefully.
//
// kafkapubsub does not support Message.Nack; Message.Nackable will return
// false, and Message.Nack will panic if called.
//
// URLs
//
// For pubsub.OpenTopic and pubsub.OpenSubscription, kafkapubsub registers
// for the scheme "kafka".
// The default URL opener will connect to a default set of Kafka brokers based
// on the environment variable "KAFKA_BROKERS", expected to be a comma-delimited
// set of server addresses.
// To customize the URL opener, or for more details on the URL format,
// see URLOpener.
// See https://gocloud.dev/concepts/urls/ for background information.
//
// Escaping
//
// Go CDK supports all UTF-8 strings. No escaping is required for Kafka.
// Message metadata is supported through Kafka Headers, which allow arbitrary
// []byte for both key and value. These are converted to string for use in
// Message.Metadata.
//
// As
//
// kafkapubsub exposes the following types for As:
// - Topic: sarama.SyncProducer
// - Subscription: sarama.ConsumerGroup, sarama.ConsumerGroupSession (may be nil during session renegotiation, and session may go stale at any time)
// - Message: *sarama.ConsumerMessage
// - Message.BeforeSend: *sarama.ProducerMessage
// - Message.AfterSend: None
// - Error: sarama.ConsumerError, sarama.ConsumerErrors, sarama.ProducerError, sarama.ProducerErrors, sarama.ConfigurationError, sarama.PacketDecodingError, sarama.PacketEncodingError, sarama.KError
package kafkapubsub // import "gocloud.dev/pubsub/kafkapubsub"
import (
"context"
"errors"
"fmt"
"net/url"
"os"
"path"
"reflect"
"strings"
"sync"
"time"
"github.com/Shopify/sarama"
"gocloud.dev/gcerrors"
"gocloud.dev/pubsub"
"gocloud.dev/pubsub/batcher"
"gocloud.dev/pubsub/driver"
)
var sendBatcherOpts = &batcher.Options{
MaxBatchSize: 100,
MaxHandlers: 2,
}
var recvBatcherOpts = &batcher.Options{
MaxBatchSize: 1,
MaxHandlers: 1,
}
func init() {
opener := new(defaultOpener)
pubsub.DefaultURLMux().RegisterTopic(Scheme, opener)
pubsub.DefaultURLMux().RegisterSubscription(Scheme, opener)
}
// defaultOpener create a default opener.
type defaultOpener struct {
init sync.Once
opener *URLOpener
err error
}
func (o *defaultOpener) defaultOpener() (*URLOpener, error) {
o.init.Do(func() {
brokerList := os.Getenv("KAFKA_BROKERS")
if brokerList == "" {
o.err = errors.New("KAFKA_BROKERS environment variable not set")
return
}
brokers := strings.Split(brokerList, ",")
for i, b := range brokers {
brokers[i] = strings.TrimSpace(b)
}
o.opener = &URLOpener{
Brokers: brokers,
Config: MinimalConfig(),
}
})
return o.opener, o.err
}
func (o *defaultOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) {
opener, err := o.defaultOpener()
if err != nil {
return nil, fmt.Errorf("open topic %v: %v", u, err)
}
return opener.OpenTopicURL(ctx, u)
}
func (o *defaultOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) {
opener, err := o.defaultOpener()
if err != nil {
return nil, fmt.Errorf("open subscription %v: %v", u, err)
}
return opener.OpenSubscriptionURL(ctx, u)
}
// Scheme is the URL scheme that kafkapubsub registers its URLOpeners under on pubsub.DefaultMux.
const Scheme = "kafka"
// URLOpener opens Kafka URLs like "kafka://mytopic" for topics and
// "kafka://group?topic=mytopic" for subscriptions.
//
// For topics, the URL's host+path is used as the topic name.
//
// For subscriptions, the URL's host+path is used as the group name,
// and the "topic" query parameter(s) are used as the set of topics to
// subscribe to.
type URLOpener struct {
// Brokers is the slice of brokers in the Kafka cluster.
Brokers []string
// Config is the Sarama Config.
// Config.Producer.Return.Success must be set to true.
Config *sarama.Config
// TopicOptions specifies the options to pass to OpenTopic.
TopicOptions TopicOptions
// SubscriptionOptions specifies the options to pass to OpenSubscription.
SubscriptionOptions SubscriptionOptions
}
// OpenTopicURL opens a pubsub.Topic based on u.
func (o *URLOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) {
for param := range u.Query() {
return nil, fmt.Errorf("open topic %v: invalid query parameter %q", u, param)
}
topicName := path.Join(u.Host, u.Path)
return OpenTopic(o.Brokers, o.Config, topicName, &o.TopicOptions)
}
// OpenSubscriptionURL opens a pubsub.Subscription based on u.
func (o *URLOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) {
q := u.Query()
topics := q["topic"]
q.Del("topic")
for param := range q {
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q", u, param)
}
group := path.Join(u.Host, u.Path)
return OpenSubscription(o.Brokers, o.Config, group, topics, &o.SubscriptionOptions)
}
// MinimalConfig returns a minimal sarama.Config.
func MinimalConfig() *sarama.Config {
config := sarama.NewConfig()
config.Version = sarama.V0_11_0_0 // required for Headers
config.Producer.Return.Successes = true // required for SyncProducer
return config
}
type topic struct {
producer sarama.SyncProducer
topicName string
opts TopicOptions
}
// TopicOptions contains configuration options for topics.
type TopicOptions struct {
// KeyName optionally sets the Message.Metadata key to use as the optional
// Kafka message key. If set, and if a matching Message.Metadata key is found,
// the value for that key will be used as the message key when sending to
// Kafka, instead of being added to the message headers.
KeyName string
}
// OpenTopic creates a pubsub.Topic that sends to a Kafka topic.
//
// It uses a sarama.SyncProducer to send messages. Producer options can
// be configured in the Producer section of the sarama.Config:
// https://godoc.org/github.com/Shopify/sarama#Config.
//
// Config.Producer.Return.Success must be set to true.
func OpenTopic(brokers []string, config *sarama.Config, topicName string, opts *TopicOptions) (*pubsub.Topic, error) {
dt, err := openTopic(brokers, config, topicName, opts)
if err != nil {
return nil, err
}
return pubsub.NewTopic(dt, sendBatcherOpts), nil
}
// openTopic returns the driver for OpenTopic. This function exists so the test
// harness can get the driver interface implementation if it needs to.
func openTopic(brokers []string, config *sarama.Config, topicName string, opts *TopicOptions) (driver.Topic, error) {
if opts == nil {
opts = &TopicOptions{}
}
producer, err := sarama.NewSyncProducer(brokers, config)
if err != nil {
return nil, err
}
return &topic{producer: producer, topicName: topicName, opts: *opts}, nil
}
// SendBatch implements driver.Topic.SendBatch.
func (t *topic) SendBatch(ctx context.Context, dms []*driver.Message) error {
// Convert the messages to a slice of sarama.ProducerMessage.
ms := make([]*sarama.ProducerMessage, 0, len(dms))
for _, dm := range dms {
var kafkaKey sarama.Encoder
var headers []sarama.RecordHeader
for k, v := range dm.Metadata {
if k == t.opts.KeyName {
// Use this key's value as the Kafka message key instead of adding it
// to the headers.
kafkaKey = sarama.ByteEncoder(v)
} else {
headers = append(headers, sarama.RecordHeader{Key: []byte(k), Value: []byte(v)})
}
}
pm := &sarama.ProducerMessage{
Topic: t.topicName,
Key: kafkaKey,
Value: sarama.ByteEncoder(dm.Body),
Headers: headers,
}
if dm.BeforeSend != nil {
asFunc := func(i interface{}) bool {
if p, ok := i.(**sarama.ProducerMessage); ok {
*p = pm
return true
}
return false
}
if err := dm.BeforeSend(asFunc); err != nil {
return err
}
}
ms = append(ms, pm)
}
err := t.producer.SendMessages(ms)
if err != nil {
return err
}
for _, dm := range dms {
if dm.AfterSend != nil {
asFunc := func(i interface{}) bool { return false }
if err := dm.AfterSend(asFunc); err != nil {
return err
}
}
}
return nil
}
// Close implements io.Closer.
func (t *topic) Close() error {
return t.producer.Close()
}
// IsRetryable implements driver.Topic.IsRetryable.
func (t *topic) IsRetryable(error) bool {
return false
}
// As implements driver.Topic.As.
func (t *topic) As(i interface{}) bool {
if p, ok := i.(*sarama.SyncProducer); ok {
*p = t.producer
return true
}
return false
}
// ErrorAs implements driver.Topic.ErrorAs.
func (t *topic) ErrorAs(err error, i interface{}) bool {
return errorAs(err, i)
}
// ErrorCode implements driver.Topic.ErrorCode.
func (t *topic) ErrorCode(err error) gcerrors.ErrorCode {
return errorCode(err)
}
func errorCode(err error) gcerrors.ErrorCode {
if pes, ok := err.(sarama.ProducerErrors); ok && len(pes) == 1 {
return errorCode(pes[0])
}
if pe, ok := err.(*sarama.ProducerError); ok {
return errorCode(pe.Err)
}
if err == sarama.ErrUnknownTopicOrPartition {
return gcerrors.NotFound
}
return gcerrors.Unknown
}
type subscription struct {
opts SubscriptionOptions
closeCh chan struct{} // closed when we've shut down
joinCh chan struct{} // closed when we join for the first time
cancel func() // cancels the background consumer
closeErr error // fatal error detected by the background consumer
consumerGroup sarama.ConsumerGroup
mu sync.Mutex
unacked []*ackInfo
sess sarama.ConsumerGroupSession // current session, if any, used for marking offset updates
expectedClaims int // # of expected claims for the current session, they should be added via ConsumeClaim
claims []sarama.ConsumerGroupClaim // claims in the current session
}
// ackInfo stores info about a message and whether it has been acked.
// It is used as the driver.AckID.
type ackInfo struct {
msg *sarama.ConsumerMessage
acked bool
}
// SubscriptionOptions contains configuration for subscriptions.
type SubscriptionOptions struct {
// KeyName optionally sets the Message.Metadata key in which to store the
// Kafka message key. If set, and if the Kafka message key is non-empty,
// the key value will be stored in Message.Metadata under KeyName.
KeyName string
// WaitForJoin causes OpenSubscription to wait for up to WaitForJoin
// to allow the client to join the consumer group.
// Messages sent to the topic before the client joins the group
// may not be received by this subscription.
// OpenSubscription will succeed even if WaitForJoin elapses and
// the subscription still hasn't been joined successfully.
WaitForJoin time.Duration
}
// OpenSubscription creates a pubsub.Subscription that joins group, receiving
// messages from topics.
//
// It uses a sarama.ConsumerGroup to receive messages. Consumer options can
// be configured in the Consumer section of the sarama.Config:
// https://godoc.org/github.com/Shopify/sarama#Config.
func OpenSubscription(brokers []string, config *sarama.Config, group string, topics []string, opts *SubscriptionOptions) (*pubsub.Subscription, error) {
ds, err := openSubscription(brokers, config, group, topics, opts)
if err != nil {
return nil, err
}
return pubsub.NewSubscription(ds, recvBatcherOpts, nil), nil
}
// openSubscription returns the driver for OpenSubscription. This function
// exists so the test harness can get the driver interface implementation if it
// needs to.
func openSubscription(brokers []string, config *sarama.Config, group string, topics []string, opts *SubscriptionOptions) (driver.Subscription, error) {
if opts == nil {
opts = &SubscriptionOptions{}
}
consumerGroup, err := sarama.NewConsumerGroup(brokers, group, config)
if err != nil {
return nil, err
}
// Create a cancelable context for the background goroutine that
// consumes messages.
ctx, cancel := context.WithCancel(context.Background())
joinCh := make(chan struct{})
ds := &subscription{
opts: *opts,
consumerGroup: consumerGroup,
closeCh: make(chan struct{}),
joinCh: joinCh,
cancel: cancel,
}
// Start a background consumer. It should run until ctx is cancelled
// by Close, or until there's a fatal error (e.g., topic doesn't exist).
// We're registering ds as our ConsumerGroupHandler, so sarama will
// call [Setup, ConsumeClaim (possibly more than once), Cleanup]
// repeatedly as the consumer group is rebalanced.
// See https://godoc.org/github.com/Shopify/sarama#ConsumerGroup.
go func() {
for {
ds.closeErr = consumerGroup.Consume(ctx, topics, ds)
if ds.closeErr != nil || ctx.Err() != nil {
consumerGroup.Close()
close(ds.closeCh)
break
}
}
}()
if opts.WaitForJoin > 0 {
// Best effort wait for first consumer group session.
select {
case <-joinCh:
case <-ds.closeCh:
case <-time.After(opts.WaitForJoin):
}
}
return ds, nil
}
// Setup implements sarama.ConsumerGroupHandler.Setup. It is called whenever
// a new session with the broker is starting.
func (s *subscription) Setup(sess sarama.ConsumerGroupSession) error {
// Record the current session.
s.mu.Lock()
defer s.mu.Unlock()
s.sess = sess
s.expectedClaims = 0
for _, claims := range sess.Claims() {
s.expectedClaims += len(claims)
}
return nil
}
// Cleanup implements sarama.ConsumerGroupHandler.Cleanup.
func (s *subscription) Cleanup(sarama.ConsumerGroupSession) error {
// Clear the current session.
s.mu.Lock()
defer s.mu.Unlock()
s.sess = nil
s.expectedClaims = 0
s.claims = nil
return nil
}
// ConsumeClaim implements sarama.ConsumerGroupHandler.ConsumeClaim.
// This is where messages are actually delivered, via a channel.
func (s *subscription) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
s.mu.Lock()
s.claims = append(s.claims, claim)
// Once all of the expected claims have registered, close joinCh to (possibly) wake up OpenSubscription.
if s.joinCh != nil && len(s.claims) == s.expectedClaims {
close(s.joinCh)
s.joinCh = nil
}
s.mu.Unlock()
<-sess.Context().Done()
return nil
}
// ReceiveBatch implements driver.Subscription.ReceiveBatch.
func (s *subscription) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) {
// Try to read maxMessages for up to 100ms before giving up.
maxWaitCtx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
defer cancel()
for {
// We'll give up after maxWaitCtx is Done, or if s.closeCh is closed.
// Otherwise, we want to pull a message from one of the channels in the
// claim(s) we've been given.
//
// Note: we could multiplex this by ranging over each claim.Messages(),
// writing the messages to a single ch, and then reading from that ch
// here. However, this results in us reading messages from Kafka and
// essentially queueing them here; when the session is closed for whatever
// reason, those messages are lost, which may or may not be an issue
// depending on the Kafka configuration being used.
//
// It seems safer to use reflect.Select to explicitly only get a single
// message at a time, and hand it directly to the user.
//
// reflect.Select is essentially a "select" statement, but allows us to
// build the cases dynamically. We need that because we need a case for
// each of the claims in s.claims.
s.mu.Lock()
cases := make([]reflect.SelectCase, 0, len(s.claims)+2)
// Add a case for s.closeCh being closed, at index = 0.
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(s.closeCh),
})
// Add a case for maxWaitCtx being Done, at index = 1.
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(maxWaitCtx.Done()),
})
// Add a case per claim, reading from the claim's Messages channel.
for _, claim := range s.claims {
cases = append(cases, reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(claim.Messages()),
})
}
s.mu.Unlock()
i, v, ok := reflect.Select(cases)
if !ok {
// The i'th channel was closed.
switch i {
case 0: // s.closeCh
return nil, s.closeErr
case 1: // maxWaitCtx
// We've tried for a while to get a message, but didn't get any.
// Return an empty slice; the portable type will call us back.
return nil, ctx.Err()
}
// Otherwise, if one of the claim channels closed, we're probably ending
// a session. Just keep trying.
continue
}
msg := v.Interface().(*sarama.ConsumerMessage)
// We've got a message! It should not be nil.
// Read the metadata from msg.Headers.
md := map[string]string{}
for _, h := range msg.Headers {
md[string(h.Key)] = string(h.Value)
}
// Add a metadata entry for the message key if appropriate.
if len(msg.Key) > 0 && s.opts.KeyName != "" {
md[s.opts.KeyName] = string(msg.Key)
}
ack := &ackInfo{msg: msg}
var loggableID string
if len(msg.Key) == 0 {
loggableID = fmt.Sprintf("partition %d offset %d", msg.Partition, msg.Offset)
} else {
loggableID = string(msg.Key)
}
dm := &driver.Message{
LoggableID: loggableID,
Body: msg.Value,
Metadata: md,
AckID: ack,
AsFunc: func(i interface{}) bool {
if p, ok := i.(**sarama.ConsumerMessage); ok {
*p = msg
return true
}
return false
},
}
s.mu.Lock()
defer s.mu.Unlock()
s.unacked = append(s.unacked, ack)
return []*driver.Message{dm}, nil
}
}
// SendAcks implements driver.Subscription.SendAcks.
func (s *subscription) SendAcks(ctx context.Context, ids []driver.AckID) error {
s.mu.Lock()
defer s.mu.Unlock()
// Mark them all acked.
for _, id := range ids {
id.(*ackInfo).acked = true
}
if s.sess == nil {
// We don't have a current session, so we can't send offset updates.
// We'll just wait until next time and retry.
return nil
}
// Mark all of the acked messages at the head of the slice. Since Kafka only
// stores a single offset, we can't mark messages that aren't at the head; that
// would move the offset past other as-yet-unacked messages.
for len(s.unacked) > 0 && s.unacked[0].acked {
s.sess.MarkMessage(s.unacked[0].msg, "")
s.unacked = s.unacked[1:]
}
return nil
}
// CanNack implements driver.CanNack.
func (s *subscription) CanNack() bool {
// Nacking a single message doesn't make sense with the way Kafka maintains
// offsets.
return false
}
// SendNacks implements driver.Subscription.SendNacks.
func (s *subscription) SendNacks(ctx context.Context, ids []driver.AckID) error {
panic("unreachable")
}
// Close implements io.Closer.
func (s *subscription) Close() error {
// Cancel the ctx for the background goroutine and wait until it's done.
s.cancel()
<-s.closeCh
return nil
}
// IsRetryable implements driver.Subscription.IsRetryable.
func (*subscription) IsRetryable(error) bool {
return false
}
// As implements driver.Subscription.As.
func (s *subscription) As(i interface{}) bool {
if p, ok := i.(*sarama.ConsumerGroup); ok {
*p = s.consumerGroup
return true
}
if p, ok := i.(*sarama.ConsumerGroupSession); ok {
s.mu.Lock()
defer s.mu.Unlock()
*p = s.sess
return true
}
return false
}
// ErrorAs implements driver.Subscription.ErrorAs.
func (s *subscription) ErrorAs(err error, i interface{}) bool {
return errorAs(err, i)
}
// ErrorCode implements driver.Subscription.ErrorCode.
func (*subscription) ErrorCode(err error) gcerrors.ErrorCode {
return errorCode(err)
}
func errorAs(err error, i interface{}) bool {
switch terr := err.(type) {
case sarama.ConsumerError:
if p, ok := i.(*sarama.ConsumerError); ok {
*p = terr
return true
}
case sarama.ConsumerErrors:
if p, ok := i.(*sarama.ConsumerErrors); ok {
*p = terr
return true
}
case sarama.ProducerError:
if p, ok := i.(*sarama.ProducerError); ok {
*p = terr
return true
}
case sarama.ProducerErrors:
if p, ok := i.(*sarama.ProducerErrors); ok {
*p = terr
return true
}
case sarama.ConfigurationError:
if p, ok := i.(*sarama.ConfigurationError); ok {
*p = terr
return true
}
case sarama.PacketDecodingError:
if p, ok := i.(*sarama.PacketDecodingError); ok {
*p = terr
return true
}
case sarama.PacketEncodingError:
if p, ok := i.(*sarama.PacketEncodingError); ok {
*p = terr
return true
}
case sarama.KError:
if p, ok := i.(*sarama.KError); ok {
*p = terr
return true
}
}
return false
}
| [
"\"KAFKA_BROKERS\""
]
| []
| [
"KAFKA_BROKERS"
]
| [] | ["KAFKA_BROKERS"] | go | 1 | 0 | |
pytorch_lightning/accelerators/ddp_spawn_backend.py | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License
import os
import re
import torch
import torch.multiprocessing as mp
import torch.distributed as torch_distrib
import torch.distributed as dist
from pytorch_lightning import _logger as log
from pytorch_lightning.accelerators.base_backend import Accelerator
from pytorch_lightning.utilities import AMPType
from pytorch_lightning.utilities.cloud_io import atomic_save, load as pl_load
from pytorch_lightning.utilities.distributed import rank_zero_only, rank_zero_warn
from pytorch_lightning.utilities.seed import seed_everything
from pytorch_lightning.distributed.dist import LightningDistributed
from pytorch_lightning.utilities.distributed import find_free_network_port
try:
from hydra.core.hydra_config import HydraConfig
from hydra.utils import get_original_cwd, to_absolute_path
except ImportError:
HYDRA_AVAILABLE = False
else:
HYDRA_AVAILABLE = True
class DDPSpawnBackend(Accelerator):
def __init__(self, trainer, nprocs, cluster_environment=None):
super().__init__(trainer, cluster_environment)
self.mp_queue = None
self.nprocs = nprocs
self.dist = LightningDistributed()
def setup(self, model):
os.environ['MASTER_PORT'] = os.environ.get('MASTER_PORT', str(find_free_network_port()))
# pass in a state q
smp = mp.get_context('spawn')
self.mp_queue = smp.SimpleQueue()
self.trainer.model = model
def train(self):
model = self.trainer.model
# train in children process
mp.spawn(self.ddp_train, nprocs=self.nprocs, args=(self.mp_queue, model,))
# restore main state with best weights
best_path = self.mp_queue.get()
results = self.mp_queue.get()
last_path = self.mp_queue.get()
# recover the weights of the processes trained in the children
self.__recover_child_process_weights(model, best_path, last_path)
return results
def ddp_train(self, process_idx, mp_queue, model, is_master=False, proc_offset=0):
"""
Entry point for ddp
Args:
process_idx:
mp_queue: multiprocessing queue
model:
Returns:
"""
seed = os.environ.get("PL_GLOBAL_SEED")
if seed is not None:
seed_everything(int(seed))
# offset the process id if requested
process_idx = process_idx + proc_offset
# show progressbar only on progress_rank 0
if (self.trainer.node_rank != 0 or process_idx != 0) and self.trainer.progress_bar_callback is not None:
self.trainer.progress_bar_callback.disable()
# determine which process we are and world size
self.set_world_ranks(process_idx)
# set warning rank
rank_zero_only.rank = self.trainer.global_rank
# set up server using proc 0's ip address
# try to init for 20 times at max in case ports are taken
# where to store ip_table
model.trainer = self.trainer
self.init_ddp_connection(
self.trainer.global_rank,
self.trainer.world_size,
self.trainer.is_slurm_managing_tasks
)
# call setup after the ddp process has connected
self.trainer.call_setup_hook(model)
# on world_size=0 let everyone know training is starting
if self.trainer.is_global_zero and not torch.distributed.is_initialized():
log.info('-' * 100)
log.info(f'distributed_backend={self.trainer.distributed_backend}')
log.info(f'All DDP processes registered. Starting ddp with {self.trainer.world_size} processes')
log.info('-' * 100)
# call sync_bn before .cuda(), configure_apex and configure_ddp
if self.trainer.sync_batchnorm:
model = model.configure_sync_batchnorm(model)
# move the model to the correct device
self.model_to_device(model, process_idx, is_master)
# CHOOSE OPTIMIZER
# allow for lr schedulers as well
self.setup_optimizers(model)
# set model properties before going into wrapper
self.trainer.model_connector.copy_trainer_model_properties(model)
# 16-bit
model = self.trainer.precision_connector.connect(model)
# device ids change depending on the DDP setup
device_ids = self.get_device_ids()
# allow user to configure ddp
model = model.configure_ddp(model, device_ids)
# set up training routine
self.trainer.train_loop.setup_training(model)
# train or test
results = self.train_or_test()
# get original model
model = self.trainer.get_model()
# persist info in ddp_spawn
self.transfer_distrib_spawn_state_on_fit_end(model, mp_queue, results)
# clean up memory
torch.cuda.empty_cache()
def set_world_ranks(self, process_idx):
self.trainer.local_rank = process_idx
self.trainer.global_rank = self.trainer.node_rank * self.trainer.num_processes + process_idx
self.trainer.world_size = self.trainer.num_nodes * self.trainer.num_processes
def model_to_device(self, model, process_idx, is_master):
gpu_idx = process_idx
self.trainer.root_gpu = gpu_idx
torch.cuda.set_device(self.trainer.root_gpu)
model.cuda(self.trainer.root_gpu)
def get_device_ids(self):
device_ids = [self.trainer.root_gpu]
return device_ids
def training_step(self, args):
if self.trainer.amp_backend == AMPType.NATIVE:
with torch.cuda.amp.autocast():
output = self.trainer.model(*args)
else:
output = self.trainer.model(*args)
return output
def validation_step(self, args):
output = self.training_step(args)
return output
def test_step(self, args):
output = self.training_step(args)
return output
def barrier(self, name: str = None):
if torch_distrib.is_initialized():
torch_distrib.barrier()
def early_stopping_should_stop(self, pl_module):
stop = torch.tensor(int(self.trainer.should_stop), device=pl_module.device)
dist.all_reduce(stop, op=dist.reduce_op.SUM)
dist.barrier()
should_stop = stop == self.trainer.world_size
return should_stop
def broadcast(self, obj, src=0):
return self.dist.broadcast(obj)
def __recover_child_process_weights(self, model, best_path, last_path):
# transfer back the best path to the trainer
if self.trainer.checkpoint_callback:
self.trainer.checkpoint_callback.best_model_path = best_path
# todo, pass also best score
# load last weights
if last_path is not None and not self.trainer.testing:
ckpt = pl_load(last_path, map_location=lambda storage, loc: storage)
model.load_state_dict(ckpt)
self.trainer.model = model
def transfer_distrib_spawn_state_on_fit_end(self, model, mp_queue, results):
best_model_path = None
if self.trainer.checkpoint_callback is not None:
best_model_path = self.trainer.checkpoint_callback.best_model_path
if self.trainer.global_rank == 0 and mp_queue is not None:
rank_zero_warn('cleaning up ddp environment...')
# todo, pass complete checkpoint as state dictionary
mp_queue.put(best_model_path)
mp_queue.put(results)
# save the last weights
last_path = None
if not self.trainer.testing and best_model_path is not None and len(best_model_path) > 0:
last_path = re.sub('.ckpt', '.tmp_end.ckpt', best_model_path)
atomic_save(model.state_dict(), last_path)
mp_queue.put(last_path)
| []
| []
| [
"PL_GLOBAL_SEED",
"MASTER_PORT"
]
| [] | ["PL_GLOBAL_SEED", "MASTER_PORT"] | python | 2 | 0 | |
cmd/main.go | package main
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io/ioutil"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/alexei-led/pumba/pkg/chaos"
"github.com/alexei-led/pumba/pkg/chaos/docker/cmd"
netemCmd "github.com/alexei-led/pumba/pkg/chaos/netem/cmd"
stressCmd "github.com/alexei-led/pumba/pkg/chaos/stress/cmd"
"github.com/alexei-led/pumba/pkg/container"
log "github.com/sirupsen/logrus"
"github.com/urfave/cli"
"github.com/johntdyer/slackrus"
)
var (
topContext context.Context
)
var (
// Version that is passed on compile time through -ldflags
Version = "built locally"
// GitCommit that is passed on compile time through -ldflags
GitCommit = "none"
// GitBranch that is passed on compile time through -ldflags
GitBranch = "none"
// BuildTime that is passed on compile time through -ldflags
BuildTime = "none"
// HumanVersion is a human readable app version
HumanVersion = fmt.Sprintf("%s - %.7s (%s) %s", Version, GitCommit, GitBranch, BuildTime)
)
const (
// Re2Prefix re2 regexp string prefix
Re2Prefix = "re2:"
// DefaultInterface default network interface
DefaultInterface = "eth0"
)
func init() {
// set log level
log.SetLevel(log.WarnLevel)
log.SetFormatter(&log.TextFormatter{})
// handle termination signal
topContext = handleSignals()
}
func main() {
rootCertPath := "/etc/ssl/docker"
if os.Getenv("DOCKER_CERT_PATH") != "" {
rootCertPath = os.Getenv("DOCKER_CERT_PATH")
}
app := cli.NewApp()
app.Name = "Pumba"
app.Version = HumanVersion
app.Compiled = time.Now()
app.Authors = []cli.Author{
{
Name: "Alexei Ledenev",
Email: "[email protected]",
},
}
app.EnableBashCompletion = true
app.Usage = "Pumba is a resilience testing tool, that helps applications tolerate random Docker container failures: process, network and performance."
app.ArgsUsage = fmt.Sprintf("containers (name, list of names, or RE2 regex if prefixed with %q)", Re2Prefix)
app.Before = before
app.Commands = initializeCLICommands()
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "host, H",
Usage: "daemon socket to connect to",
Value: "unix:///var/run/docker.sock",
EnvVar: "DOCKER_HOST",
},
cli.BoolFlag{
Name: "tls",
Usage: "use TLS; implied by --tlsverify",
},
cli.BoolFlag{
Name: "tlsverify",
Usage: "use TLS and verify the remote",
EnvVar: "DOCKER_TLS_VERIFY",
},
cli.StringFlag{
Name: "tlscacert",
Usage: "trust certs signed only by this CA",
Value: fmt.Sprintf("%s/ca.pem", rootCertPath),
},
cli.StringFlag{
Name: "tlscert",
Usage: "client certificate for TLS authentication",
Value: fmt.Sprintf("%s/cert.pem", rootCertPath),
},
cli.StringFlag{
Name: "tlskey",
Usage: "client key for TLS authentication",
Value: fmt.Sprintf("%s/key.pem", rootCertPath),
},
cli.StringFlag{
Name: "log-level, l",
Usage: "set log level (debug, info, warning(*), error, fatal, panic)",
Value: "warning",
EnvVar: "LOG_LEVEL",
},
cli.BoolFlag{
Name: "json, j",
Usage: "produce log in JSON format: Logstash and Splunk friendly",
EnvVar: "LOG_JSON",
},
cli.StringFlag{
Name: "slackhook",
Usage: "web hook url; send Pumba log events to Slack",
},
cli.StringFlag{
Name: "slackchannel",
Usage: "Slack channel (default #pumba)",
Value: "#pumba",
},
cli.StringFlag{
Name: "interval, i",
Usage: "recurrent interval for chaos command; use with optional unit suffix: 'ms/s/m/h'",
},
cli.StringSliceFlag{
Name: "label",
Usage: "filter containers by labels, e.g '--label key=value' (multiple labels supported)",
},
cli.BoolFlag{
Name: "random, r",
Usage: "randomly select single matching container from list of target containers",
},
cli.BoolFlag{
Name: "dry-run",
Usage: "dry run does not create chaos, only logs planned chaos commands",
EnvVar: "DRY-RUN",
},
cli.BoolFlag{
Name: "skip-error",
Usage: "skip chaos command error and retry to execute the command on next interval tick",
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func before(c *cli.Context) error {
// set debug log level
switch level := c.GlobalString("log-level"); level {
case "debug", "DEBUG":
log.SetLevel(log.DebugLevel)
case "info", "INFO":
log.SetLevel(log.InfoLevel)
case "warning", "WARNING":
log.SetLevel(log.WarnLevel)
case "error", "ERROR":
log.SetLevel(log.ErrorLevel)
case "fatal", "FATAL":
log.SetLevel(log.FatalLevel)
case "panic", "PANIC":
log.SetLevel(log.PanicLevel)
default:
log.SetLevel(log.WarnLevel)
}
// set log formatter to JSON
if c.GlobalBool("json") {
log.SetFormatter(&log.JSONFormatter{})
}
// set Slack log channel
if c.GlobalString("slackhook") != "" {
log.AddHook(&slackrus.SlackrusHook{
HookURL: c.GlobalString("slackhook"),
AcceptedLevels: slackrus.LevelThreshold(log.GetLevel()),
Channel: c.GlobalString("slackchannel"),
IconEmoji: ":boar:",
Username: "pumba_bot",
})
}
// Set-up container client
tlsCfg, err := tlsConfig(c)
if err != nil {
return err
}
// create new Docker client
chaos.DockerClient, err = container.NewClient(c.GlobalString("host"), tlsCfg)
return err
}
func handleSignals() context.Context {
// Graceful shut-down on SIGINT/SIGTERM
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
// create cancelable context
ctx, cancel := context.WithCancel(context.Background())
go func() {
defer cancel()
sid := <-sig
log.Debugf("Received signal: %d\n", sid)
log.Debug("Canceling running chaos commands ...")
log.Debug("Gracefully exiting after some cleanup ...")
}()
return ctx
}
// tlsConfig translates the command-line options into a tls.Config struct
func tlsConfig(c *cli.Context) (*tls.Config, error) {
var tlsCfg *tls.Config
var err error
caCertFlag := c.GlobalString("tlscacert")
certFlag := c.GlobalString("tlscert")
keyFlag := c.GlobalString("tlskey")
if c.GlobalBool("tls") || c.GlobalBool("tlsverify") {
tlsCfg = &tls.Config{
InsecureSkipVerify: !c.GlobalBool("tlsverify"),
}
// Load CA cert
if caCertFlag != "" {
var caCert []byte
if strings.HasPrefix(caCertFlag, "/") {
caCert, err = ioutil.ReadFile(caCertFlag)
if err != nil {
return nil, err
}
} else {
caCert = []byte(caCertFlag)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsCfg.RootCAs = caCertPool
}
// Load client certificate
if certFlag != "" && keyFlag != "" {
var cert tls.Certificate
if strings.HasPrefix(certFlag, "/") && strings.HasPrefix(keyFlag, "/") {
cert, err = tls.LoadX509KeyPair(certFlag, keyFlag)
if err != nil {
return nil, err
}
} else {
cert, err = tls.X509KeyPair([]byte(certFlag), []byte(keyFlag))
if err != nil {
return nil, err
}
}
tlsCfg.Certificates = []tls.Certificate{cert}
}
}
return tlsCfg, nil
}
func initializeCLICommands() []cli.Command {
return []cli.Command{
*cmd.NewKillCLICommand(topContext),
*cmd.NewStopCLICommand(topContext),
*cmd.NewPauseCLICommand(topContext),
*cmd.NewRemoveCLICommand(topContext),
*stressCmd.NewStressCLICommand(topContext),
{
Name: "netem",
Flags: []cli.Flag{
cli.StringFlag{
Name: "duration, d",
Usage: "network emulation duration; should be smaller than recurrent interval; use with optional unit suffix: 'ms/s/m/h'",
},
cli.StringFlag{
Name: "interface, i",
Usage: "network interface to apply delay on",
Value: DefaultInterface,
},
cli.StringSliceFlag{
Name: "target, t",
Usage: "target IP filter; supports multiple IPs; supports CIDR notation",
},
cli.StringFlag{
Name: "egressPort",
Usage: "target port filter for egress, or sport; supports multiple ports;",
},
cli.StringFlag{
Name: "ingressPort",
Usage: "target port filter for ingress, or dport; supports multiple ports;",
},
cli.StringFlag{
Name: "tc-image",
Usage: "Docker image with tc (iproute2 package); try 'gaiadocker/iproute2'",
},
cli.BoolTFlag{
Name: "pull-image",
Usage: "try to pull tc-image",
},
},
Usage: "emulate the properties of wide area networks",
ArgsUsage: fmt.Sprintf("containers (name, list of names, or RE2 regex if prefixed with %q", Re2Prefix),
Description: "delay, loss, duplicate and re-order (run 'netem') packets, and limit the bandwidth, to emulate different network problems",
Subcommands: []cli.Command{
*netemCmd.NewDelayCLICommand(topContext),
*netemCmd.NewLossCLICommand(topContext),
*netemCmd.NewLossStateCLICommand(topContext),
*netemCmd.NewLossGECLICommand(topContext),
*netemCmd.NewRateCLICommand(topContext),
*netemCmd.NewDuplicateCLICommand(topContext),
*netemCmd.NewCorruptCLICommand(topContext),
},
},
}
}
| [
"\"DOCKER_CERT_PATH\"",
"\"DOCKER_CERT_PATH\""
]
| []
| [
"DOCKER_CERT_PATH"
]
| [] | ["DOCKER_CERT_PATH"] | go | 1 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.