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 |
---|---|---|---|---|---|---|---|---|---|---|
pkg/persist/persist.go | // Copyright 2020 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.
// Package persist provides a bootstrap for the in-memory cache
package persist
import (
"encoding/gob"
"fmt"
"os"
"time"
"github.com/google/triage-party/pkg/provider"
)
var (
// MaxSaveAge is the oldest allowable entry to persist
MaxSaveAge = 2 * 24 * time.Hour
// MaxLoadAge is the oldest allowable entry to load
MaxLoadAge = 10 * 24 * time.Hour
)
// Config is cache configuration
type Config struct {
Type string
Path string
}
// Cacher is the cache interface we support
type Cacher interface {
String() string
Set(string, *provider.Thing) error
DeleteOlderThan(string, time.Time) error
GetNewerThan(string, time.Time) *provider.Thing
Initialize() error
Cleanup() error
}
func New(cfg Config) (Cacher, error) {
gob.Register(&provider.Thing{})
switch cfg.Type {
case "mysql":
return NewMySQL(cfg)
case "cloudsql":
return NewCloudSQL(cfg)
case "postgres":
return NewPostgres(cfg)
case "disk", "":
return NewDisk(cfg)
case "memory":
return NewMemory(cfg)
default:
return nil, fmt.Errorf("unknown backend: %q", cfg.Type)
}
}
// FromEnv is shared magic between binaries
func FromEnv(backend string, path string, configPath string, reposOverride string) (Cacher, error) {
if backend == "" {
backend = os.Getenv("PERSIST_BACKEND")
}
if backend == "" {
backend = "disk"
}
if path == "" {
path = os.Getenv("PERSIST_PATH")
}
if backend == "disk" && path == "" {
path = DefaultDiskPath(configPath, reposOverride)
}
c, err := New(Config{
Type: backend,
Path: path,
})
if err != nil {
return nil, fmt.Errorf("new from %s: %s: %w", backend, path, err)
}
return c, nil
}
| [
"\"PERSIST_BACKEND\"",
"\"PERSIST_PATH\""
]
| []
| [
"PERSIST_PATH",
"PERSIST_BACKEND"
]
| [] | ["PERSIST_PATH", "PERSIST_BACKEND"] | go | 2 | 0 | |
src/radical/pilot/agent/executing/popen.py | # pylint: disable=subprocess-popen-preexec-fn
# FIXME: review pylint directive - https://github.com/PyCQA/pylint/pull/2087
# (https://docs.python.org/3/library/subprocess.html#popen-constructor)
__copyright__ = "Copyright 2013-2016, http://radical.rutgers.edu"
__license__ = "MIT"
import os
import stat
import time
import queue
import atexit
import pprint
import signal
import tempfile
import threading as mt
import traceback
import subprocess
import radical.utils as ru
from ... import agent as rpa
from ... import utils as rpu
from ... import states as rps
from ... import constants as rpc
from .base import AgentExecutingComponent
# ------------------------------------------------------------------------------
# ensure tasks are killed on termination
_pids = list()
def _kill():
for pid in _pids:
os.killpg(pid, signal.SIGTERM)
atexit.register(_kill)
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
#
class Popen(AgentExecutingComponent) :
# --------------------------------------------------------------------------
#
def __init__(self, cfg, session):
self._watcher = None
self._terminate = mt.Event()
AgentExecutingComponent.__init__ (self, cfg, session)
# --------------------------------------------------------------------------
#
def initialize(self):
self._pwd = os.getcwd()
self.register_input(rps.AGENT_EXECUTING_PENDING,
rpc.AGENT_EXECUTING_QUEUE, self.work)
self.register_output(rps.AGENT_STAGING_OUTPUT_PENDING,
rpc.AGENT_STAGING_OUTPUT_QUEUE)
self.register_publisher (rpc.AGENT_UNSCHEDULE_PUBSUB)
self.register_subscriber(rpc.CONTROL_PUBSUB, self.command_cb)
self._cancel_lock = ru.RLock()
self._cus_to_cancel = list()
self._cus_to_watch = list()
self._watch_queue = queue.Queue ()
self._pid = self._cfg['pid']
# run watcher thread
self._watcher = mt.Thread(target=self._watch)
# self._watcher.daemon = True
self._watcher.start()
# The AgentExecutingComponent needs the LaunchMethod to construct
# commands.
self._task_launcher = rpa.LaunchMethod.create(
name = self._cfg.get('task_launch_method'),
cfg = self._cfg,
session = self._session)
self._mpi_launcher = rpa.LaunchMethod.create(
name = self._cfg.get('mpi_launch_method'),
cfg = self._cfg,
session = self._session)
self.gtod = "%s/gtod" % self._pwd
self.tmpdir = tempfile.gettempdir()
# --------------------------------------------------------------------------
#
def command_cb(self, topic, msg):
self._log.info('command_cb [%s]: %s', topic, msg)
cmd = msg['cmd']
arg = msg['arg']
if cmd == 'cancel_units':
self._log.info("cancel_units command (%s)" % arg)
with self._cancel_lock:
self._cus_to_cancel.extend(arg['uids'])
return True
# --------------------------------------------------------------------------
#
def work(self, units):
if not isinstance(units, list):
units = [units]
self.advance(units, rps.AGENT_EXECUTING, publish=True, push=False)
for unit in units:
self._handle_unit(unit)
# --------------------------------------------------------------------------
#
def _handle_unit(self, cu):
try:
# prep stdout/err so that we can append w/o checking for None
cu['stdout'] = ''
cu['stderr'] = ''
cpt = cu['description']['cpu_process_type']
# gpt = cu['description']['gpu_process_type'] # FIXME: use
# FIXME: this switch is insufficient for mixed units (MPI/OpenMP)
if cpt == 'MPI': launcher = self._mpi_launcher
else : launcher = self._task_launcher
if not launcher:
raise RuntimeError("no launcher (process type = %s)" % cpt)
self._log.debug("Launching unit with %s (%s).",
launcher.name, launcher.launch_command)
# Start a new subprocess to launch the unit
self.spawn(launcher=launcher, cu=cu)
except Exception as e:
# append the startup error to the units stderr. This is
# not completely correct (as this text is not produced
# by the unit), but it seems the most intuitive way to
# communicate that error to the application/user.
self._log.exception("error running CU")
if cu.get('stderr') is None:
cu['stderr'] = ''
cu['stderr'] += "\nPilot cannot start compute unit:\n%s\n%s" \
% (str(e), traceback.format_exc())
# Free the Slots, Flee the Flots, Ree the Frots!
self._prof.prof('unschedule_start', uid=cu['uid'])
self.publish(rpc.AGENT_UNSCHEDULE_PUBSUB, cu)
self.advance(cu, rps.FAILED, publish=True, push=False)
# --------------------------------------------------------------------------
#
def spawn(self, launcher, cu):
descr = cu['description']
sandbox = cu['unit_sandbox_path']
# make sure the sandbox exists
self._prof.prof('exec_mkdir', uid=cu['uid'])
rpu.rec_makedir(sandbox)
self._prof.prof('exec_mkdir_done', uid=cu['uid'])
launch_script_name = '%s/%s.sh' % (sandbox, cu['uid'])
slots_fname = '%s/%s.sl' % (sandbox, cu['uid'])
self._log.debug("Created launch_script: %s", launch_script_name)
# prep stdout/err so that we can append w/o checking for None
cu['stdout'] = ''
cu['stderr'] = ''
with open(slots_fname, "w") as launch_script:
launch_script.write('\n%s\n\n' % pprint.pformat(cu['slots']))
with open(launch_script_name, "w") as launch_script:
launch_script.write('#!/bin/sh\n\n')
# Create string for environment variable setting
env_string = ''
# env_string += '. %s/env.orig\n' % self._pwd
env_string += 'export RADICAL_BASE="%s"\n' % self._pwd
env_string += 'export RP_SESSION_ID="%s"\n' % self._cfg['sid']
env_string += 'export RP_PILOT_ID="%s"\n' % self._cfg['pid']
env_string += 'export RP_AGENT_ID="%s"\n' % self._cfg['aid']
env_string += 'export RP_SPAWNER_ID="%s"\n' % self.uid
env_string += 'export RP_UNIT_ID="%s"\n' % cu['uid']
env_string += 'export RP_UNIT_NAME="%s"\n' % cu['description'].get('name')
env_string += 'export RP_GTOD="%s"\n' % self.gtod
env_string += 'export RP_TMP="%s"\n' % self._cu_tmp
env_string += 'export RP_PILOT_SANDBOX="%s"\n' % self._pwd
env_string += 'export RP_PILOT_STAGING="%s/staging_area"\n' \
% self._pwd
if self._prof.enabled:
env_string += 'export RP_PROF="%s/%s.prof"\n' % (sandbox, cu['uid'])
else:
env_string += 'unset RP_PROF\n'
if 'RP_APP_TUNNEL' in os.environ:
env_string += 'export RP_APP_TUNNEL="%s"\n' % os.environ['RP_APP_TUNNEL']
env_string += '''
prof(){
if test -z "$RP_PROF"
then
return
fi
event=$1
msg=$2
now=$($RP_GTOD)
echo "$now,$event,unit_script,MainThread,$RP_UNIT_ID,AGENT_EXECUTING,$msg" >> $RP_PROF
}
'''
# FIXME: this should be set by an LaunchMethod filter or something (GPU)
env_string += 'export OMP_NUM_THREADS="%s"\n' % descr['cpu_threads']
# The actual command line, constructed per launch-method
try:
launch_command, hop_cmd = launcher.construct_command(cu, launch_script_name)
if hop_cmd : cmdline = hop_cmd
else : cmdline = launch_script_name
except Exception as e:
msg = "Error in spawner (%s)" % e
self._log.exception(msg)
raise RuntimeError (msg) from e
# also add any env vars requested in the unit description
if descr['environment']:
for key,val in descr['environment'].items():
env_string += 'export "%s=%s"\n' % (key, val)
launch_script.write('\n# Environment variables\n%s\n' % env_string)
launch_script.write('prof cu_start\n')
launch_script.write('\n# Change to unit sandbox\ncd %s\n' % sandbox)
# Before the Big Bang there was nothing
if self._cfg.get('cu_pre_exec'):
for val in self._cfg['cu_pre_exec']:
launch_script.write("%s\n" % val)
if descr['pre_exec']:
fail = ' (echo "pre_exec failed"; false) || exit'
pre = ''
for elem in descr['pre_exec']:
pre += "%s || %s\n" % (elem, fail)
# Note: extra spaces below are for visual alignment
launch_script.write("\n# Pre-exec commands\n")
launch_script.write('prof cu_pre_start\n')
launch_script.write(pre)
launch_script.write('prof cu_pre_stop\n')
launch_script.write("\n# The command to run\n")
launch_script.write('prof cu_exec_start\n')
launch_script.write('%s\n' % launch_command)
launch_script.write('RETVAL=$?\n')
launch_script.write('prof cu_exec_stop\n')
# After the universe dies the infrared death, there will be nothing
if descr['post_exec']:
fail = ' (echo "post_exec failed"; false) || exit'
post = ''
for elem in descr['post_exec']:
post += "%s || %s\n" % (elem, fail)
launch_script.write("\n# Post-exec commands\n")
launch_script.write('prof cu_post_start\n')
launch_script.write('%s\n' % post)
launch_script.write('prof cu_post_stop "$ret=RETVAL"\n')
launch_script.write("\n# Exit the script with the return code from the command\n")
launch_script.write("prof cu_stop\n")
launch_script.write("exit $RETVAL\n")
# done writing to launch script, get it ready for execution.
st = os.stat(launch_script_name)
os.chmod(launch_script_name, st.st_mode | stat.S_IEXEC)
# prepare stdout/stderr
stdout_file = descr.get('stdout') or 'STDOUT'
stderr_file = descr.get('stderr') or 'STDERR'
cu['stdout_file'] = os.path.join(sandbox, stdout_file)
cu['stderr_file'] = os.path.join(sandbox, stderr_file)
_stdout_file_h = open(cu['stdout_file'], "w")
_stderr_file_h = open(cu['stderr_file'], "w")
self._log.info("Launching unit %s via %s in %s", cu['uid'], cmdline, sandbox)
self._prof.prof('exec_start', uid=cu['uid'])
cu['proc'] = subprocess.Popen(args = cmdline,
executable = None,
stdin = None,
stdout = _stdout_file_h,
stderr = _stderr_file_h,
preexec_fn = os.setsid,
close_fds = True,
shell = True,
cwd = sandbox)
self._prof.prof('exec_ok', uid=cu['uid'])
# store pid for last-effort termination
_pids.append(cu['proc'].pid)
self._watch_queue.put(cu)
# --------------------------------------------------------------------------
#
def _watch(self):
try:
while not self._terminate.is_set():
cus = list()
try:
# we don't want to only wait for one CU -- then we would
# pull CU state too frequently. OTOH, we also don't want to
# learn about CUs until all slots are filled, because then
# we may not be able to catch finishing CUs in time -- so
# there is a fine balance here. Balance means 100 (FIXME).
MAX_QUEUE_BULKSIZE = 100
while len(cus) < MAX_QUEUE_BULKSIZE :
cus.append (self._watch_queue.get_nowait())
except queue.Empty:
# nothing found -- no problem, see if any CUs finished
pass
# add all cus we found to the watchlist
for cu in cus :
self._cus_to_watch.append (cu)
# check on the known cus.
action = self._check_running()
if not action and not cus :
# nothing happened at all! Zzz for a bit.
# FIXME: make configurable
time.sleep(0.1)
except Exception as e:
self._log.exception("Error in ExecWorker watch loop (%s)" % e)
# FIXME: this should signal the ExecWorker for shutdown...
# --------------------------------------------------------------------------
# Iterate over all running tasks, check their status, and decide on the
# next step. Also check for a requested cancellation for the tasks.
def _check_running(self):
action = 0
for cu in self._cus_to_watch:
# poll subprocess object
exit_code = cu['proc'].poll()
uid = cu['uid']
if exit_code is None:
# Process is still running
if cu['uid'] in self._cus_to_cancel:
# FIXME: there is a race condition between the state poll
# above and the kill command below. We probably should pull
# state after kill again?
self._prof.prof('exec_cancel_start', uid=uid)
# We got a request to cancel this cu - send SIGTERM to the
# process group (which should include the actual launch
# method)
# cu['proc'].kill()
action += 1
try:
os.killpg(cu['proc'].pid, signal.SIGTERM)
except OSError:
# unit is already gone, we ignore this
pass
cu['proc'].wait() # make sure proc is collected
with self._cancel_lock:
self._cus_to_cancel.remove(uid)
self._prof.prof('exec_cancel_stop', uid=uid)
del(cu['proc']) # proc is not json serializable
self._prof.prof('unschedule_start', uid=cu['uid'])
self.publish(rpc.AGENT_UNSCHEDULE_PUBSUB, cu)
self.advance(cu, rps.CANCELED, publish=True, push=False)
# we don't need to watch canceled CUs
self._cus_to_watch.remove(cu)
else:
self._prof.prof('exec_stop', uid=uid)
# make sure proc is collected
cu['proc'].wait()
# we have a valid return code -- unit is final
action += 1
self._log.info("Unit %s has return code %s.", uid, exit_code)
cu['exit_code'] = exit_code
# Free the Slots, Flee the Flots, Ree the Frots!
self._cus_to_watch.remove(cu)
del(cu['proc']) # proc is not json serializable
self._prof.prof('unschedule_start', uid=cu['uid'])
self.publish(rpc.AGENT_UNSCHEDULE_PUBSUB, cu)
if exit_code != 0:
# The unit failed - fail after staging output
cu['target_state'] = rps.FAILED
else:
# The unit finished cleanly, see if we need to deal with
# output data. We always move to stageout, even if there are no
# directives -- at the very least, we'll upload stdout/stderr
cu['target_state'] = rps.DONE
self.advance(cu, rps.AGENT_STAGING_OUTPUT_PENDING, publish=True, push=True)
return action
# ------------------------------------------------------------------------------
| []
| []
| [
"RP_APP_TUNNEL"
]
| [] | ["RP_APP_TUNNEL"] | python | 1 | 0 | |
qa/rpc-tests/test_framework/util.py | # Copyright (c) 2014-2015 The Bitcoin Core developers
# Copyright (c) 2014-2017 The Archimed Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Helpful routines for regression testing
#
# Add python-bitcoinrpc to module search path:
import os
import sys
from binascii import hexlify, unhexlify
from base64 import b64encode
from decimal import Decimal, ROUND_DOWN
import json
import random
import shutil
import subprocess
import time
import re
import errno
from . import coverage
from .authproxy import AuthServiceProxy, JSONRPCException
COVERAGE_DIR = None
#Set Mocktime default to OFF.
#MOCKTIME is only needed for scripts that use the
#cached version of the blockchain. If the cached
#version of the blockchain is used without MOCKTIME
#then the mempools will not sync due to IBD.
MOCKTIME = 0
def enable_mocktime():
#For backwared compatibility of the python scripts
#with previous versions of the cache, set MOCKTIME
#to regtest genesis time + (201 * 156)
global MOCKTIME
MOCKTIME = 1417713337 + (201 * 156)
def disable_mocktime():
global MOCKTIME
MOCKTIME = 0
def get_mocktime():
return MOCKTIME
def enable_coverage(dirname):
"""Maintain a log of which RPC calls are made during testing."""
global COVERAGE_DIR
COVERAGE_DIR = dirname
def get_rpc_proxy(url, node_number, timeout=None):
"""
Args:
url (str): URL of the RPC server to call
node_number (int): the node number (or id) that this calls to
Kwargs:
timeout (int): HTTP timeout in seconds
Returns:
AuthServiceProxy. convenience object for making RPC calls.
"""
proxy_kwargs = {}
if timeout is not None:
proxy_kwargs['timeout'] = timeout
proxy = AuthServiceProxy(url, **proxy_kwargs)
proxy.url = url # store URL on proxy for info
coverage_logfile = coverage.get_filename(
COVERAGE_DIR, node_number) if COVERAGE_DIR else None
return coverage.AuthServiceProxyWrapper(proxy, coverage_logfile)
def get_mnsync_status(node):
result = node.mnsync("status")
return result['IsSynced']
def wait_to_sync(node):
synced = False
while not synced:
synced = get_mnsync_status(node)
time.sleep(0.5)
def p2p_port(n):
return 11000 + n + os.getpid()%999
def rpc_port(n):
return 12000 + n + os.getpid()%999
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def count_bytes(hex_string):
return len(bytearray.fromhex(hex_string))
def bytes_to_hex_str(byte_str):
return hexlify(byte_str).decode('ascii')
def hex_str_to_bytes(hex_str):
return unhexlify(hex_str.encode('ascii'))
def str_to_b64str(string):
return b64encode(string.encode('utf-8')).decode('ascii')
def sync_blocks(rpc_connections, wait=1):
"""
Wait until everybody has the same block count
"""
while True:
counts = [ x.getblockcount() for x in rpc_connections ]
if counts == [ counts[0] ]*len(counts):
break
time.sleep(wait)
def sync_mempools(rpc_connections, wait=1):
"""
Wait until everybody has the same transactions in their memory
pools
"""
while True:
pool = set(rpc_connections[0].getrawmempool())
num_match = 1
for i in range(1, len(rpc_connections)):
if set(rpc_connections[i].getrawmempool()) == pool:
num_match = num_match+1
if num_match == len(rpc_connections):
break
time.sleep(wait)
def sync_masternodes(rpc_connections):
for node in rpc_connections:
wait_to_sync(node)
bitcoind_processes = {}
def initialize_datadir(dirname, n):
datadir = os.path.join(dirname, "node"+str(n))
if not os.path.isdir(datadir):
os.makedirs(datadir)
with open(os.path.join(datadir, "archimed.conf"), 'w') as f:
f.write("regtest=1\n")
f.write("rpcuser=rt\n")
f.write("rpcpassword=rt\n")
f.write("port="+str(p2p_port(n))+"\n")
f.write("rpcport="+str(rpc_port(n))+"\n")
f.write("listenonion=0\n")
return datadir
def rpc_url(i, rpchost=None):
return "http://rt:rt@%s:%d" % (rpchost or '127.0.0.1', rpc_port(i))
def wait_for_bitcoind_start(process, url, i):
'''
Wait for archimedd to start. This means that RPC is accessible and fully initialized.
Raise an exception if archimedd exits during initialization.
'''
while True:
if process.poll() is not None:
raise Exception('archimedd exited with status %i during initialization' % process.returncode)
try:
rpc = get_rpc_proxy(url, i)
blocks = rpc.getblockcount()
break # break out of loop on success
except IOError as e:
if e.errno != errno.ECONNREFUSED: # Port not yet open?
raise # unknown IO error
except JSONRPCException as e: # Initialization phase
if e.error['code'] != -28: # RPC in warmup?
raise # unkown JSON RPC exception
time.sleep(0.25)
def initialize_chain(test_dir):
"""
Create (or copy from cache) a 200-block-long chain and
4 wallets.
"""
if (not os.path.isdir(os.path.join("cache","node0"))
or not os.path.isdir(os.path.join("cache","node1"))
or not os.path.isdir(os.path.join("cache","node2"))
or not os.path.isdir(os.path.join("cache","node3"))):
#find and delete old cache directories if any exist
for i in range(4):
if os.path.isdir(os.path.join("cache","node"+str(i))):
shutil.rmtree(os.path.join("cache","node"+str(i)))
# Create cache directories, run archimedds:
for i in range(4):
datadir=initialize_datadir("cache", i)
args = [ os.getenv("ARCHIMEDD", "archimedd"), "-server", "-keypool=1", "-datadir="+datadir, "-discover=0" ]
if i > 0:
args.append("-connect=127.0.0.1:"+str(p2p_port(0)))
bitcoind_processes[i] = subprocess.Popen(args)
if os.getenv("PYTHON_DEBUG", ""):
print "initialize_chain: archimedd started, waiting for RPC to come up"
wait_for_bitcoind_start(bitcoind_processes[i], rpc_url(i), i)
if os.getenv("PYTHON_DEBUG", ""):
print "initialize_chain: RPC succesfully started"
rpcs = []
for i in range(4):
try:
rpcs.append(get_rpc_proxy(rpc_url(i), i))
except:
sys.stderr.write("Error connecting to "+url+"\n")
sys.exit(1)
# Create a 200-block-long chain; each of the 4 nodes
# gets 25 mature blocks and 25 immature.
# blocks are created with timestamps 156 seconds apart
# starting from 31356 seconds in the past
enable_mocktime()
block_time = get_mocktime() - (201 * 156)
for i in range(2):
for peer in range(4):
for j in range(25):
set_node_times(rpcs, block_time)
rpcs[peer].generate(1)
block_time += 156
# Must sync before next peer starts generating blocks
sync_blocks(rpcs)
# Shut them down, and clean up cache directories:
stop_nodes(rpcs)
wait_bitcoinds()
disable_mocktime()
for i in range(4):
os.remove(log_filename("cache", i, "debug.log"))
os.remove(log_filename("cache", i, "db.log"))
os.remove(log_filename("cache", i, "peers.dat"))
os.remove(log_filename("cache", i, "fee_estimates.dat"))
for i in range(4):
from_dir = os.path.join("cache", "node"+str(i))
to_dir = os.path.join(test_dir, "node"+str(i))
shutil.copytree(from_dir, to_dir)
initialize_datadir(test_dir, i) # Overwrite port/rpcport in archimed.conf
def initialize_chain_clean(test_dir, num_nodes):
"""
Create an empty blockchain and num_nodes wallets.
Useful if a test case wants complete control over initialization.
"""
for i in range(num_nodes):
datadir=initialize_datadir(test_dir, i)
def _rpchost_to_args(rpchost):
'''Convert optional IP:port spec to rpcconnect/rpcport args'''
if rpchost is None:
return []
match = re.match('(\[[0-9a-fA-f:]+\]|[^:]+)(?::([0-9]+))?$', rpchost)
if not match:
raise ValueError('Invalid RPC host spec ' + rpchost)
rpcconnect = match.group(1)
rpcport = match.group(2)
if rpcconnect.startswith('['): # remove IPv6 [...] wrapping
rpcconnect = rpcconnect[1:-1]
rv = ['-rpcconnect=' + rpcconnect]
if rpcport:
rv += ['-rpcport=' + rpcport]
return rv
def start_node(i, dirname, extra_args=None, rpchost=None, timewait=None, binary=None):
"""
Start a archimedd and return RPC connection to it
"""
datadir = os.path.join(dirname, "node"+str(i))
if binary is None:
binary = os.getenv("ARCHIMEDD", "archimedd")
# RPC tests still depend on free transactions
args = [ binary, "-datadir="+datadir, "-server", "-keypool=1", "-discover=0", "-rest", "-blockprioritysize=50000", "-mocktime="+str(get_mocktime()) ]
if extra_args is not None: args.extend(extra_args)
bitcoind_processes[i] = subprocess.Popen(args)
if os.getenv("PYTHON_DEBUG", ""):
print "start_node: archimedd started, waiting for RPC to come up"
url = rpc_url(i, rpchost)
wait_for_bitcoind_start(bitcoind_processes[i], url, i)
if os.getenv("PYTHON_DEBUG", ""):
print "start_node: RPC succesfully started"
proxy = get_rpc_proxy(url, i, timeout=timewait)
if COVERAGE_DIR:
coverage.write_all_rpc_commands(COVERAGE_DIR, proxy)
return proxy
def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None, binary=None):
"""
Start multiple archimedds, return RPC connections to them
"""
if extra_args is None: extra_args = [ None for i in range(num_nodes) ]
if binary is None: binary = [ None for i in range(num_nodes) ]
rpcs = []
try:
for i in range(num_nodes):
rpcs.append(start_node(i, dirname, extra_args[i], rpchost, binary=binary[i]))
except: # If one node failed to start, stop the others
stop_nodes(rpcs)
raise
return rpcs
def log_filename(dirname, n_node, logname):
return os.path.join(dirname, "node"+str(n_node), "regtest", logname)
def stop_node(node, i):
node.stop()
bitcoind_processes[i].wait()
del bitcoind_processes[i]
def stop_nodes(nodes):
for node in nodes:
node.stop()
del nodes[:] # Emptying array closes connections as a side effect
def set_node_times(nodes, t):
for node in nodes:
node.setmocktime(t)
def wait_bitcoinds():
# Wait for all bitcoinds to cleanly exit
for bitcoind in bitcoind_processes.values():
bitcoind.wait()
bitcoind_processes.clear()
def connect_nodes(from_connection, node_num):
ip_port = "127.0.0.1:"+str(p2p_port(node_num))
from_connection.addnode(ip_port, "onetry")
# poll until version handshake complete to avoid race conditions
# with transaction relaying
while any(peer['version'] == 0 for peer in from_connection.getpeerinfo()):
time.sleep(0.1)
def connect_nodes_bi(nodes, a, b):
connect_nodes(nodes[a], b)
connect_nodes(nodes[b], a)
def find_output(node, txid, amount):
"""
Return index to output of txid with value amount
Raises exception if there is none.
"""
txdata = node.getrawtransaction(txid, 1)
for i in range(len(txdata["vout"])):
if txdata["vout"][i]["value"] == amount:
return i
raise RuntimeError("find_output txid %s : %s not found"%(txid,str(amount)))
def gather_inputs(from_node, amount_needed, confirmations_required=1):
"""
Return a random set of unspent txouts that are enough to pay amount_needed
"""
assert(confirmations_required >=0)
utxo = from_node.listunspent(confirmations_required)
random.shuffle(utxo)
inputs = []
total_in = Decimal("0.00000000")
while total_in < amount_needed and len(utxo) > 0:
t = utxo.pop()
total_in += t["amount"]
inputs.append({ "txid" : t["txid"], "vout" : t["vout"], "address" : t["address"] } )
if total_in < amount_needed:
raise RuntimeError("Insufficient funds: need %d, have %d"%(amount_needed, total_in))
return (total_in, inputs)
def make_change(from_node, amount_in, amount_out, fee):
"""
Create change output(s), return them
"""
outputs = {}
amount = amount_out+fee
change = amount_in - amount
if change > amount*2:
# Create an extra change output to break up big inputs
change_address = from_node.getnewaddress()
# Split change in two, being careful of rounding:
outputs[change_address] = Decimal(change/2).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
change = amount_in - amount - outputs[change_address]
if change > 0:
outputs[from_node.getnewaddress()] = change
return outputs
def send_zeropri_transaction(from_node, to_node, amount, fee):
"""
Create&broadcast a zero-priority transaction.
Returns (txid, hex-encoded-txdata)
Ensures transaction is zero-priority by first creating a send-to-self,
then using its output
"""
# Create a send-to-self with confirmed inputs:
self_address = from_node.getnewaddress()
(total_in, inputs) = gather_inputs(from_node, amount+fee*2)
outputs = make_change(from_node, total_in, amount+fee, fee)
outputs[self_address] = float(amount+fee)
self_rawtx = from_node.createrawtransaction(inputs, outputs)
self_signresult = from_node.signrawtransaction(self_rawtx)
self_txid = from_node.sendrawtransaction(self_signresult["hex"], True)
vout = find_output(from_node, self_txid, amount+fee)
# Now immediately spend the output to create a 1-input, 1-output
# zero-priority transaction:
inputs = [ { "txid" : self_txid, "vout" : vout } ]
outputs = { to_node.getnewaddress() : float(amount) }
rawtx = from_node.createrawtransaction(inputs, outputs)
signresult = from_node.signrawtransaction(rawtx)
txid = from_node.sendrawtransaction(signresult["hex"], True)
return (txid, signresult["hex"])
def random_zeropri_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
"""
Create a random zero-priority transaction.
Returns (txid, hex-encoded-transaction-data, fee)
"""
from_node = random.choice(nodes)
to_node = random.choice(nodes)
fee = min_fee + fee_increment*random.randint(0,fee_variants)
(txid, txhex) = send_zeropri_transaction(from_node, to_node, amount, fee)
return (txid, txhex, fee)
def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
"""
Create a random transaction.
Returns (txid, hex-encoded-transaction-data, fee)
"""
from_node = random.choice(nodes)
to_node = random.choice(nodes)
fee = min_fee + fee_increment*random.randint(0,fee_variants)
(total_in, inputs) = gather_inputs(from_node, amount+fee)
outputs = make_change(from_node, total_in, amount, fee)
outputs[to_node.getnewaddress()] = float(amount)
rawtx = from_node.createrawtransaction(inputs, outputs)
signresult = from_node.signrawtransaction(rawtx)
txid = from_node.sendrawtransaction(signresult["hex"], True)
return (txid, signresult["hex"], fee)
def assert_equal(thing1, thing2):
if thing1 != thing2:
raise AssertionError("%s != %s"%(str(thing1),str(thing2)))
def assert_greater_than(thing1, thing2):
if thing1 <= thing2:
raise AssertionError("%s <= %s"%(str(thing1),str(thing2)))
def assert_raises(exc, fun, *args, **kwds):
try:
fun(*args, **kwds)
except exc:
pass
except Exception as e:
raise AssertionError("Unexpected exception raised: "+type(e).__name__)
else:
raise AssertionError("No exception raised")
def assert_is_hex_string(string):
try:
int(string, 16)
except Exception as e:
raise AssertionError(
"Couldn't interpret %r as hexadecimal; raised: %s" % (string, e))
def assert_is_hash_string(string, length=64):
if not isinstance(string, basestring):
raise AssertionError("Expected a string, got type %r" % type(string))
elif length and len(string) != length:
raise AssertionError(
"String of length %d expected; got %d" % (length, len(string)))
elif not re.match('[abcdef0-9]+$', string):
raise AssertionError(
"String %r contains invalid characters for a hash." % string)
def assert_array_result(object_array, to_match, expected, should_not_find = False):
"""
Pass in array of JSON objects, a dictionary with key/value pairs
to match against, and another dictionary with expected key/value
pairs.
If the should_not_find flag is true, to_match should not be found
in object_array
"""
if should_not_find == True:
assert_equal(expected, { })
num_matched = 0
for item in object_array:
all_match = True
for key,value in to_match.items():
if item[key] != value:
all_match = False
if not all_match:
continue
elif should_not_find == True:
num_matched = num_matched+1
for key,value in expected.items():
if item[key] != value:
raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value)))
num_matched = num_matched+1
if num_matched == 0 and should_not_find != True:
raise AssertionError("No objects matched %s"%(str(to_match)))
if num_matched > 0 and should_not_find == True:
raise AssertionError("Objects were found %s"%(str(to_match)))
def satoshi_round(amount):
return Decimal(amount).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
# Helper to create at least "count" utxos
# Pass in a fee that is sufficient for relay and mining new transactions.
def create_confirmed_utxos(fee, node, count):
node.generate(int(0.5*count)+101)
utxos = node.listunspent()
iterations = count - len(utxos)
addr1 = node.getnewaddress()
addr2 = node.getnewaddress()
if iterations <= 0:
return utxos
for i in xrange(iterations):
t = utxos.pop()
inputs = []
inputs.append({ "txid" : t["txid"], "vout" : t["vout"]})
outputs = {}
send_value = t['amount'] - fee
outputs[addr1] = satoshi_round(send_value/2)
outputs[addr2] = satoshi_round(send_value/2)
raw_tx = node.createrawtransaction(inputs, outputs)
signed_tx = node.signrawtransaction(raw_tx)["hex"]
txid = node.sendrawtransaction(signed_tx)
while (node.getmempoolinfo()['size'] > 0):
node.generate(1)
utxos = node.listunspent()
assert(len(utxos) >= count)
return utxos
# Create large OP_RETURN txouts that can be appended to a transaction
# to make it large (helper for constructing large transactions).
def gen_return_txouts():
# Some pre-processing to create a bunch of OP_RETURN txouts to insert into transactions we create
# So we have big transactions (and therefore can't fit very many into each block)
# create one script_pubkey
script_pubkey = "6a4d0200" #OP_RETURN OP_PUSH2 512 bytes
for i in xrange (512):
script_pubkey = script_pubkey + "01"
# concatenate 128 txouts of above script_pubkey which we'll insert before the txout for change
txouts = "81"
for k in xrange(128):
# add txout value
txouts = txouts + "0000000000000000"
# add length of script_pubkey
txouts = txouts + "fd0402"
# add script_pubkey
txouts = txouts + script_pubkey
return txouts
def create_tx(node, coinbase, to_address, amount):
inputs = [{ "txid" : coinbase, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
assert_equal(signresult["complete"], True)
return signresult["hex"]
# Create a spend of each passed-in utxo, splicing in "txouts" to each raw
# transaction to make it large. See gen_return_txouts() above.
def create_lots_of_big_transactions(node, txouts, utxos, fee):
addr = node.getnewaddress()
txids = []
for i in xrange(len(utxos)):
t = utxos.pop()
inputs = []
inputs.append({ "txid" : t["txid"], "vout" : t["vout"]})
outputs = {}
send_value = t['amount'] - fee
outputs[addr] = satoshi_round(send_value)
rawtx = node.createrawtransaction(inputs, outputs)
newtx = rawtx[0:92]
newtx = newtx + txouts
newtx = newtx + rawtx[94:]
signresult = node.signrawtransaction(newtx, None, None, "NONE")
txid = node.sendrawtransaction(signresult["hex"], True)
txids.append(txid)
return txids
def get_bip9_status(node, key):
info = node.getblockchaininfo()
for row in info['bip9_softforks']:
if row['id'] == key:
return row
raise IndexError ('key:"%s" not found' % key)
| []
| []
| [
"ARCHIMEDD",
"PYTHON_DEBUG"
]
| [] | ["ARCHIMEDD", "PYTHON_DEBUG"] | python | 2 | 0 | |
go/src/github.com/hashicorp/terraform/builtin/providers/cloudflare/provider_test.go | package cloudflare
import (
"os"
"testing"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/terraform"
)
var testAccProviders map[string]terraform.ResourceProvider
var testAccProvider *schema.Provider
func init() {
testAccProvider = Provider().(*schema.Provider)
testAccProviders = map[string]terraform.ResourceProvider{
"cloudflare": testAccProvider,
}
}
func TestProvider(t *testing.T) {
if err := Provider().(*schema.Provider).InternalValidate(); err != nil {
t.Fatalf("err: %s", err)
}
}
func TestProvider_impl(t *testing.T) {
var _ terraform.ResourceProvider = Provider()
}
func testAccPreCheck(t *testing.T) {
if v := os.Getenv("CLOUDFLARE_EMAIL"); v == "" {
t.Fatal("CLOUDFLARE_EMAIL must be set for acceptance tests")
}
if v := os.Getenv("CLOUDFLARE_TOKEN"); v == "" {
t.Fatal("CLOUDFLARE_TOKEN must be set for acceptance tests")
}
if v := os.Getenv("CLOUDFLARE_DOMAIN"); v == "" {
t.Fatal("CLOUDFLARE_DOMAIN must be set for acceptance tests. The domain is used to ` and destroy record against.")
}
}
| [
"\"CLOUDFLARE_EMAIL\"",
"\"CLOUDFLARE_TOKEN\"",
"\"CLOUDFLARE_DOMAIN\""
]
| []
| [
"CLOUDFLARE_TOKEN",
"CLOUDFLARE_EMAIL",
"CLOUDFLARE_DOMAIN"
]
| [] | ["CLOUDFLARE_TOKEN", "CLOUDFLARE_EMAIL", "CLOUDFLARE_DOMAIN"] | go | 3 | 0 | |
patch_files/horovod/torch/optimizer.py | # Copyright 2019 Uber Technologies, Inc. All Rights Reserved.
# Modifications copyright Microsoft
#
# 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 warnings
from contextlib import contextmanager
import torch
from horovod.common.util import split_list
from horovod.torch.compression import Compression
from horovod.torch.functions import broadcast_object
from horovod.torch.mpi_ops import allreduce_async_, grouped_allreduce_async_
from horovod.torch.mpi_ops import synchronize
from horovod.torch.mpi_ops import size
from horovod.torch.mpi_ops import Average, Adasum, Sum
from horovod.torch.mpi_ops import rocm_built
class _DistributedOptimizer(torch.optim.Optimizer):
def __init__(self, params, named_parameters, grace, compression,
backward_passes_per_step=1, op=Average,
gradient_predivide_factor=1.0,
num_groups=0):
super(self.__class__, self).__init__(params)
self._compression = compression
self._grace = grace
if named_parameters is not None:
named_parameters = list(named_parameters)
else:
named_parameters = [('allreduce.noname.%s' % i, v)
for param_group in self.param_groups
for i, v in enumerate(param_group['params'])]
# make sure that named_parameters are tuples
if any([not isinstance(p, tuple) for p in named_parameters]):
raise ValueError('named_parameters should be a sequence of '
'tuples (name, parameter), usually produced by '
'model.named_parameters().')
dups = _DistributedOptimizer.find_duplicates([k for k, _ in named_parameters])
if len(dups) > 0:
raise ValueError('Parameter names in named_parameters must be unique. '
'Found duplicates: %s' % ', '.join(dups))
all_param_ids = {id(v)
for param_group in self.param_groups
for v in param_group['params']}
named_param_ids = {id(v) for k, v in named_parameters}
unnamed_param_ids = all_param_ids - named_param_ids
if len(unnamed_param_ids):
raise ValueError('named_parameters was specified, but one or more model '
'parameters were not named. Python object ids: '
'%s' % ', '.join(str(id) for id in unnamed_param_ids))
self._parameter_names = {v: k for k, v in sorted(named_parameters)}
self.backward_passes_per_step = backward_passes_per_step
self._allreduce_delay = {v: self.backward_passes_per_step
for _, v in sorted(named_parameters)}
self.op = op
self.gradient_predivide_factor = gradient_predivide_factor
self._handles = {}
self._grad_accs = []
self._requires_update = set()
self._synchronized = False
self._should_synchronize = True
self._num_groups = num_groups
self._p_to_group = {}
self._group_counts = {}
if size() > 1 or os.environ.get('HOROVOD_ELASTIC') == '1':
self._register_hooks()
def load_state_dict(self, *args, **kwargs):
self._handles = {}
self._synchronized = False
self._should_synchronize = True
for p in self._allreduce_delay:
self._allreduce_delay[p] = self.backward_passes_per_step
super(self.__class__, self).load_state_dict(*args, **kwargs)
@staticmethod
def find_duplicates(lst):
seen = set()
dups = set()
for el in lst:
if el in seen:
dups.add(el)
seen.add(el)
return dups
def set_backward_passes_per_step(self, passes):
self.backward_passes_per_step = passes
for p in self._allreduce_delay:
self._allreduce_delay[p] = self.backward_passes_per_step
def _register_hooks(self):
if self._num_groups > 0:
p_list = []
# Get list of parameters with grads
for param_group in self.param_groups:
for p in param_group['params']:
if p.requires_grad:
p_list.append(p)
# To ensure parameter order and group formation is consistent, broadcast p_list order
# from rank 0 and use for every worker
p_list_names = [self._parameter_names.get(p) for p in p_list]
p_list_names = broadcast_object(p_list_names, root_rank=0)
p_list = sorted(p_list, key=lambda p : p_list_names.index(self._parameter_names.get(p)))
# Form groups
p_groups = split_list(p_list, self._num_groups)
p_groups = [tuple(p) for p in p_groups]
for group in p_groups:
for p in group:
self._p_to_group[p] = group
self._group_counts[group] = 0
for param_group in self.param_groups:
for p in param_group['params']:
if p.requires_grad:
p.grad = p.data.new(p.size()).zero_()
self._requires_update.add(p)
p_tmp = p.expand_as(p)
grad_acc = p_tmp.grad_fn.next_functions[0][0]
grad_acc.register_hook(self._make_hook(p))
self._grad_accs.append(grad_acc)
def _allreduce_grad_async(self, p):
name = self._parameter_names.get(p)
tensor = p.grad
if self._grace and self._num_groups == 0 and self.op == Average:
handle, ctx = self._grace.send_step(tensor, name)
else:
tensor_compressed, ctx = self._compression.compress(tensor)
if self.op == Average:
# Split average operation across pre/postscale factors
# C++ backend will apply additional 1 / size() factor to postscale_factor for op == Average.
prescale_factor = 1.0 / self.gradient_predivide_factor
postscale_factor = self.gradient_predivide_factor
else:
prescale_factor = 1.0
postscale_factor = 1.0
handle = allreduce_async_(tensor_compressed, name=name, op=self.op,
prescale_factor=prescale_factor,
postscale_factor=postscale_factor)
return handle, ctx
def _grouped_allreduce_grad_async(self, ps):
name = self._parameter_names.get(ps[0])
tensors_compressed, ctxs = zip(*[self._compression.compress(p.grad) for p in ps])
handle = grouped_allreduce_async_(tensors_compressed, name=name, op=self.op)
return handle, ctxs
def _make_hook(self, p):
def hook(*ignore):
if p in self._handles and self._handles[p][0] is not None:
if self._allreduce_delay[p] <= 0:
raise AssertionError(
"Gradients were computed more than "
"backward_passes_per_step times before call "
"to step(). Increase backward_passes_per_step to "
"accumulate gradients locally.")
assert not p.grad.requires_grad
assert self._allreduce_delay[p] > 0
handle, ctx = None, None
self._allreduce_delay[p] -= 1
if self._allreduce_delay[p] == 0:
if self._num_groups > 0:
group = self._p_to_group[p]
self._group_counts[group] += 1
if self._group_counts[group] == len(group):
handle, ctxs = self._grouped_allreduce_grad_async(group)
self._handles[group] = (handle, ctxs)
# Remove any None entries from previous no-op hook calls
for gp in group:
self._handles.pop(gp, None)
self._group_counts[group] = 0
return
else:
handle, ctx = self._allreduce_grad_async(p)
self._handles[p] = (handle, ctx)
return hook
def synchronize(self):
completed = set()
for x in self._handles.keys():
completed.update(x) if isinstance(x, tuple) else completed.add(x)
missing_p = self._requires_update - completed
for p in missing_p:
handle, ctx = self._allreduce_grad_async(p)
self._handles[p] = (handle, ctx)
for p, (handle, ctx) in self._handles.items():
if handle is None:
handle, ctx = self._allreduce_grad_async(p)
self._handles[p] = (handle, ctx)
for p, (handle, ctx) in self._handles.items():
if isinstance(p, tuple):
# This was a grouped result, need to unpack
outputs = synchronize(handle)
for gp, output, gctx in zip(p, outputs, ctx):
self._allreduce_delay[gp] = self.backward_passes_per_step
gp.grad.set_(self._compression.decompress(output, gctx))
else:
if self._grace and self._num_groups == 0 and self.op == Average:
# in GRACE, p is not tuple, but handle is.
output = self._grace.receive_step(handle, ctx)
self._allreduce_delay[p] = self.backward_passes_per_step
p.grad.set_(output)
else:
output = synchronize(handle)
self._allreduce_delay[p] = self.backward_passes_per_step
p.grad.set_(self._compression.decompress(output, ctx))
self._handles.clear()
self._synchronized = True
@contextmanager
def skip_synchronize(self):
"""
A context manager used to specify that optimizer.step() should
not perform synchronization.
It's typically used in a following pattern:
.. code-block:: python
optimizer.synchronize()
with optimizer.skip_synchronize():
optimizer.step()
"""
self._should_synchronize = False
try:
yield
finally:
self._should_synchronize = True
def step(self, closure=None):
if self._should_synchronize:
if self._synchronized:
warnings.warn("optimizer.step() called without "
"optimizer.skip_synchronize() context after "
"optimizer.synchronize(). This can cause training "
"slowdown. You may want to consider using "
"optimizer.skip_synchronize() context if you use "
"optimizer.synchronize() in your code.")
self.synchronize()
self._synchronized = False
return super(self.__class__, self).step(closure)
def zero_grad(self):
if self._handles:
raise AssertionError("optimizer.zero_grad() was called after loss.backward() "
"but before optimizer.step() or optimizer.synchronize(). "
"This is prohibited as it can cause a race condition.")
return super(self.__class__, self).zero_grad()
class _DistributedAdasumOptimizer(torch.optim.Optimizer):
def __init__(self, params, named_parameters, compression,
backward_passes_per_step=1):
super(self.__class__, self).__init__(params)
self._compression = compression
if named_parameters is not None:
named_parameters = list(named_parameters)
else:
named_parameters = [('allreduce.noname.%s' % i, v)
for param_group in self.param_groups
for i, v in enumerate(param_group['params'])]
# make sure that named_parameters are tuples
if any([not isinstance(p, tuple) for p in named_parameters]):
raise ValueError('named_parameters should be a sequence of '
'tuples (name, parameter), usually produced by '
'model.named_parameters().')
dups = _DistributedOptimizer.find_duplicates([k for k, _ in named_parameters])
if len(dups) > 0:
raise ValueError('Parameter names in named_parameters must be unique. '
'Found duplicates: %s' % ', '.join(dups))
all_param_ids = {id(v)
for param_group in self.param_groups
for v in param_group['params']}
named_param_ids = {id(v) for k, v in named_parameters}
unnamed_param_ids = all_param_ids - named_param_ids
if len(unnamed_param_ids):
raise ValueError('named_parameters was specified, but one or more model '
'parameters were not named. Python object ids: '
'%s' % ', '.join(str(id) for id in unnamed_param_ids))
self._parameter_names = {v: k for k, v in sorted(named_parameters)}
self.backward_passes_per_step = backward_passes_per_step
self._allreduce_delay = {v: self.backward_passes_per_step
for _, v in sorted(named_parameters)}
self._handles = {}
self._grad_accs = []
self._requires_update = set()
self._synchronized = False
self._should_synchronize = True
self._starting_models = {
p : torch.zeros_like(p, requires_grad=False)
for _, p in named_parameters
}
self._register_hooks()
def set_backward_passes_per_step(self, passes):
self.backward_passes_per_step = passes
for p in self._allreduce_delay:
self._allreduce_delay[p] = self.backward_passes_per_step
def _register_hooks(self):
for param_group in self.param_groups:
for p in param_group['params']:
if p.requires_grad:
p.grad = p.data.new(p.size()).zero_()
self._requires_update.add(p)
p_tmp = p.expand_as(p)
grad_acc = p_tmp.grad_fn.next_functions[0][0]
grad_acc.register_hook(self._make_hook(p))
self._grad_accs.append(grad_acc)
def _allreduce_grad_async(self, p):
# Delta optimizer implements this logic:
# start = current.copy()
# step() -> computes 'current - \alpha.f(g)' where f is
# optimizer logic and g is the gradient
# delta = current-start
# allreduce_(delta)
# start += delta
# current = start
# In order to suppport this logic using function hook to improve performance,
# we do:
# delta = (start - \alpha.f(g)) - start
# = -\alpha.f(g)
# set start to zero and step computes -\alpha.f(g)
# where f is the underlying optimizer logic
name = self._parameter_names.get(p)
start = self._starting_models[p]
stashed_params = []
for group in self.param_groups:
stashed_params.append(group['params'])
# only want to step on p
if any([p is v for v in group['params']]):
group['params'] = [p]
else:
group['params'] = []
start.data.copy_(p)
super(self.__class__, self).step()
# compute delta = curr - start
p.data.sub_(start)
# allreduce as before
tensor_compressed, ctx = self._compression.compress(p)
handle = allreduce_async_(tensor_compressed.data, name=name, op=Adasum)
# reset stashed parameters
for stashed, group in zip(stashed_params, self.param_groups):
group['params'] = stashed
return handle, ctx
def _make_hook(self, p):
def hook(*ignore):
if p in self._handles and self._handles[p][0] is not None:
if self._allreduce_delay[p] <= 0:
raise AssertionError(
"Gradients were computed more than "
"backward_passes_per_step times before call "
"to step(). Increase backward_passes_per_step to "
"accumulate gradients locally.")
assert not p.grad.requires_grad
assert self._allreduce_delay[p] > 0
handle, ctx = None, None
self._allreduce_delay[p] -= 1
if self._allreduce_delay[p] == 0:
handle, ctx = self._allreduce_grad_async(p)
self._handles[p] = (handle, ctx)
return hook
def synchronize(self):
pass
@contextmanager
def skip_synchronize(self):
raise AssertionError("Skipping synchronization is not supported when using Adasum optimizer.")
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
missing_p = self._requires_update - set(self._handles.keys())
for p in missing_p:
handle, ctx = self._allreduce_grad_async(p)
self._handles[p] = (handle, ctx)
for p, (handle, ctx) in self._handles.items():
# This means step() is called before backward_passes_per_steps finished.
# We do a synchoronous allreduce here.
if not handle:
handle, ctx = self._allreduce_grad_async(p)
self._handles[p] = (handle, ctx)
delta = synchronize(handle)
delta = self._compression.decompress(delta, ctx)
start = self._starting_models[p]
start.data.add_(delta.data)
p.data.copy_(start)
self._allreduce_delay[p] = self.backward_passes_per_step
self._handles.clear()
return loss
def zero_grad(self):
if self._handles:
raise AssertionError("optimizer.zero_grad() was called after loss.backward() "
"but before optimizer.step() or optimizer.synchronize(). "
"This is prohibited as it can cause a race condition.")
return super(self.__class__, self).zero_grad()
def DistributedOptimizer(optimizer,
grace=None, named_parameters=None,
compression=Compression.none,
backward_passes_per_step=1,
op=Average,
gradient_predivide_factor=1.0,
num_groups=0):
"""
An optimizer that wraps another torch.optim.Optimizer, using an allreduce to
combine gradient values before applying gradients to model weights.
Allreduce operations are executed after each gradient is computed by ``loss.backward()``
in parallel with each other. The ``step()`` method ensures that all allreduce operations are
finished before applying gradients to the model.
DistributedOptimizer exposes the ``synchronize()`` method, which forces allreduce operations
to finish before continuing the execution. It's useful in conjunction with gradient
clipping, or other operations that modify gradients in place before ``step()`` is executed.
Make sure to use ``optimizer.skip_synchronize()`` if you're calling ``synchronize()``
in your code.
Example of gradient clipping:
.. code-block:: python
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.synchronize()
torch.nn.utils.clip_grad_norm_(model.parameters(), args.clip)
with optimizer.skip_synchronize():
optimizer.step()
Arguments:
optimizer: Optimizer to use for computing gradients and applying updates.
named_parameters: A mapping between parameter names and values. Used for naming of
allreduce operations. Typically just ``model.named_parameters()``.
compression: Compression algorithm used during allreduce to reduce the amount
of data sent during the each parameter update step. Defaults to
not using compression.
backward_passes_per_step: Number of expected backward passes to perform
before calling step()/synchronize(). This
allows accumulating gradients over multiple
mini-batches before reducing and applying them.
op: The reduction operation to use when combining gradients across different ranks.
gradient_predivide_factor: If op == Average, gradient_predivide_factor splits the averaging
before and after the sum. Gradients are scaled by
1.0 / gradient_predivide_factor before the sum and
gradient_predivide_factor / size after the sum.
num_groups: Number of groups to assign gradient allreduce ops to for explicit
grouping. Defaults to no explicit groups.
"""
# We dynamically create a new class that inherits from the optimizer that was passed in.
# The goal is to override the `step()` method with an allreduce implementation.
if gradient_predivide_factor != 1.0:
if rocm_built():
raise ValueError('gradient_predivide_factor not supported yet with ROCm')
if op != Average:
raise ValueError('gradient_predivide_factor not supported with op != Average')
if op != Adasum or size() == 1:
cls = type(optimizer.__class__.__name__, (optimizer.__class__,),
dict(_DistributedOptimizer.__dict__))
return cls(optimizer.param_groups, named_parameters, grace, compression, backward_passes_per_step, op,
gradient_predivide_factor, num_groups)
else:
cls = type(optimizer.__class__.__name__, (optimizer.__class__,),
dict(_DistributedAdasumOptimizer.__dict__))
return cls(optimizer.param_groups, named_parameters, compression, backward_passes_per_step)
| []
| []
| [
"HOROVOD_ELASTIC"
]
| [] | ["HOROVOD_ELASTIC"] | python | 1 | 0 | |
test/systemtests/util_test.go | package systemtests
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/contiv/contivmodel/client"
"github.com/contiv/remotessh"
. "gopkg.in/check.v1"
)
func (s *systemtestSuite) checkConnectionPair(containers1, containers2 []*container, port int) error {
for _, cont := range containers1 {
for _, cont2 := range containers2 {
if err := cont.node.exec.checkConnection(cont, cont2.eth0.ip, "tcp", port); err != nil {
return err
}
}
}
return nil
}
func (s *systemtestSuite) checkConnectionPairRetry(containers1, containers2 []*container, port, delay, retries int) error {
for _, cont := range containers1 {
for _, cont2 := range containers2 {
if err := cont.node.exec.checkConnectionRetry(cont, cont2.eth0.ip, "tcp", port, delay, retries); err != nil {
return err
}
}
}
return nil
}
func (s *systemtestSuite) checkNoConnectionPairRetry(containers1, containers2 []*container, port, delay, retries int) error {
for _, cont := range containers1 {
for _, cont2 := range containers2 {
if err := cont.node.exec.checkNoConnectionRetry(cont, cont2.eth0.ip, "tcp", port, delay, retries); err != nil {
return err
}
}
}
return nil
}
func (s *systemtestSuite) runContainersInGroups(num int, netName string, tenantName string, groupNames []string) (map[*container]string, error) {
containers := map[*container]string{}
for _, groupName := range groupNames {
names := []string{}
for i := 0; i < num; i++ {
names = append(names, fmt.Sprintf("grp-%s-%d", groupName, i))
}
// XXX we don't use anything but private for this function right now
conts, err := s.runContainersInService(num, groupName, netName, tenantName, names)
if err != nil {
return nil, err
}
for _, cont := range conts {
containers[cont] = groupName
}
}
return containers, nil
}
func (s *systemtestSuite) runContainersInService(num int, serviceName, networkName string, tenantName string, names []string) ([]*container, error) {
containers := []*container{}
mutex := sync.Mutex{}
if networkName == "" {
networkName = "private"
}
errChan := make(chan error)
for i := 0; i < num; i++ {
go func(i int) {
nodeNum := i % len(s.nodes)
var name string
mutex.Lock()
if len(names) > 0 {
name = names[0]
names = names[1:]
}
mutex.Unlock()
if name == "" {
name = fmt.Sprintf("%s-srv%d-%d", strings.Replace(networkName, "/", "-", -1), i, nodeNum)
}
spec := containerSpec{
imageName: "contiv/alpine",
networkName: networkName,
name: name,
serviceName: serviceName,
tenantName: tenantName,
}
cont, err := s.nodes[nodeNum].exec.runContainer(spec)
if err != nil {
errChan <- err
}
mutex.Lock()
containers = append(containers, cont)
mutex.Unlock()
errChan <- nil
}(i)
}
for i := 0; i < num; i++ {
if err := <-errChan; err != nil {
return nil, err
}
}
return containers, nil
}
func (s *systemtestSuite) runContainers(num int, withService bool, networkName string, tenantName string,
names []string, labels []string) ([]*container, error) {
containers := []*container{}
mutex := sync.Mutex{}
if networkName == "" {
networkName = "private"
}
errChan := make(chan error)
for i := 0; i < num; i++ {
go func(i int) {
nodeNum := i % len(s.nodes)
var name string
mutex.Lock()
if len(names) > 0 {
name = names[0]
names = names[1:]
}
mutex.Unlock()
if name == "" {
name = fmt.Sprintf("%s-srv%d-%d", strings.Replace(networkName, "/", "-", -1), i, nodeNum)
}
var serviceName string
if withService {
serviceName = name
}
cname := fmt.Sprintf("%s-%d", name, i)
spec := containerSpec{
imageName: "contiv/alpine",
networkName: networkName,
name: cname,
serviceName: serviceName,
tenantName: tenantName,
}
if len(labels) > 0 {
spec.labels = append(spec.labels, labels...)
}
cont, err := s.nodes[nodeNum].exec.runContainer(spec)
if err != nil {
errChan <- err
}
mutex.Lock()
containers = append(containers, cont)
mutex.Unlock()
errChan <- nil
}(i)
}
for i := 0; i < num; i++ {
if err := <-errChan; err != nil {
return nil, err
}
}
return containers, nil
}
func (s *systemtestSuite) runContainersSerial(num int, withService bool, networkName string, tenantName string, names []string) ([]*container, error) {
containers := []*container{}
mutex := sync.Mutex{}
if networkName == "" {
networkName = "private"
}
for i := 0; i < num; i++ {
nodeNum := i % len(s.nodes)
var name string
mutex.Lock()
if len(names) > 0 {
name = names[0]
names = names[1:]
}
mutex.Unlock()
if name == "" {
name = fmt.Sprintf("%s-srv%d-%d", strings.Replace(networkName, "/", "-", -1), i, nodeNum)
}
var serviceName string
if withService {
serviceName = name
}
spec := containerSpec{
imageName: "contiv/alpine",
networkName: networkName,
name: name,
serviceName: serviceName,
tenantName: tenantName,
}
cont, err := s.nodes[nodeNum].exec.runContainer(spec)
if err != nil {
return nil, err
}
mutex.Lock()
containers = append(containers, cont)
mutex.Unlock()
}
return containers, nil
}
func randSeq(n int) string {
letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func (s *systemtestSuite) runContainersOnNode(num int, networkName, tenantName, groupname string, n *node) ([]*container, error) {
containers := []*container{}
mutex := sync.Mutex{}
errChan := make(chan error)
for i := 0; i < num; i++ {
go func(i int) {
spec := containerSpec{
imageName: "contiv/alpine",
networkName: networkName,
tenantName: tenantName,
serviceName: groupname,
}
if groupname == "" {
spec.name = strings.ToLower(fmt.Sprintf("%s-%d-%s", n.Name(), i, randSeq(16)))
} else {
spec.name = fmt.Sprintf("%s-%d-%s", n.Name(), i, groupname)
}
cont, err := n.exec.runContainer(spec)
if err != nil {
errChan <- err
}
mutex.Lock()
containers = append(containers, cont)
mutex.Unlock()
errChan <- nil
}(i)
}
for i := 0; i < num; i++ {
if err := <-errChan; err != nil {
return nil, err
}
}
return containers, nil
}
func (s *systemtestSuite) runContainersWithDNS(num int, tenantName, networkName, serviceName string) ([]*container, error) {
containers := []*container{}
mutex := sync.Mutex{}
errChan := make(chan error)
// Get the dns server for the network
dnsServer, err := s.getNetworkDNSServer(tenantName, networkName)
if err != nil {
logrus.Errorf("Error getting DNS server for network %s/%s", networkName, tenantName)
return nil, err
}
docknetName := fmt.Sprintf("%s/%s", networkName, tenantName)
if tenantName == "default" {
docknetName = networkName
}
docSrvName := docknetName
if serviceName != "" {
docSrvName = fmt.Sprintf("%s.%s", serviceName, docknetName)
}
for i := 0; i < num; i++ {
go func(i int) {
nodeNum := i % len(s.nodes)
name := fmt.Sprintf("%s-srv%d-%d", strings.Replace(docSrvName, "/", "-", -1), i, nodeNum)
spec := containerSpec{
imageName: "contiv/alpine",
networkName: networkName,
name: name,
serviceName: serviceName,
dnsServer: dnsServer,
tenantName: tenantName,
}
cont, err := s.nodes[nodeNum].exec.runContainer(spec)
if err != nil {
errChan <- err
}
mutex.Lock()
containers = append(containers, cont)
mutex.Unlock()
errChan <- nil
}(i)
}
for i := 0; i < num; i++ {
if err := <-errChan; err != nil {
return nil, err
}
}
return containers, nil
}
func (s *systemtestSuite) pingTest(containers []*container) error {
ips := []string{}
v6ips := []string{}
for _, cont := range containers {
ips = append(ips, cont.eth0.ip)
if cont.eth0.ipv6 != "" {
v6ips = append(v6ips, cont.eth0.ipv6)
}
}
errChan := make(chan error, len(containers)*len(ips))
for _, cont := range containers {
for _, ip := range ips {
go func(cont *container, ip string) { errChan <- cont.node.exec.checkPingWithCount(cont, ip, 3) }(cont, ip)
}
}
for i := 0; i < len(containers)*len(ips); i++ {
if err := <-errChan; err != nil {
return err
}
}
if len(v6ips) > 0 {
v6errChan := make(chan error, len(containers)*len(v6ips))
for _, cont := range containers {
for _, ipv6 := range v6ips {
go func(cont *container, ipv6 string) { v6errChan <- cont.node.exec.checkPing6WithCount(cont, ipv6, 2) }(cont, ipv6)
}
}
for i := 0; i < len(containers)*len(v6ips); i++ {
if err := <-v6errChan; err != nil {
return err
}
}
}
return nil
}
func (s *systemtestSuite) pingTestByName(containers []*container, hostName string) error {
errChan := make(chan error, len(containers))
for _, cont := range containers {
go func(cont *container, hostName string) { errChan <- cont.node.exec.checkPing(cont, hostName) }(cont, hostName)
}
for i := 0; i < len(containers); i++ {
if err := <-errChan; err != nil {
return err
}
}
return nil
}
func (s *systemtestSuite) pingFailureTest(containers1 []*container, containers2 []*container) error {
errChan := make(chan error, len(containers1)*len(containers2))
for _, cont1 := range containers1 {
for _, cont2 := range containers2 {
go func(cont1 *container, cont2 *container) {
errChan <- cont1.node.exec.checkPingFailure(cont1, cont2.eth0.ip)
}(cont1, cont2)
}
}
for i := 0; i < len(containers1)*len(containers2); i++ {
if err := <-errChan; err != nil {
return err
}
}
return nil
}
func (s *systemtestSuite) hostIsolationTest(containers []*container) error {
numTests := 0
errChan := make(chan error, len(containers)-1)
hBridgeIPs := make(map[string]string)
for _, cont := range containers {
ip, err := cont.node.exec.getIPAddr(cont, "host1")
if err != nil {
logrus.Errorf("Error getting host1 ip for container: %+v err: %v",
cont, err)
return err
}
hBridgeIPs[cont.containerID] = ip
}
for _, cont := range containers {
for _, hIP := range hBridgeIPs {
if hIP != hBridgeIPs[cont.containerID] {
go func(c *container, dest string) {
errChan <- c.node.exec.checkPingFailure(c, dest)
}(cont, hIP)
numTests++
}
}
break // ping from one container to all others is sufficient
}
for i := 0; i < numTests; i++ {
if err := <-errChan; err != nil {
return err
}
}
return nil
}
func (s *systemtestSuite) removeContainers(containers []*container) error {
errChan := make(chan error, len(containers))
for _, cont := range containers {
go func(cont *container) { errChan <- cont.node.exec.rm(cont) }(cont)
}
for range containers {
if err := <-errChan; err != nil {
return err
}
}
return nil
}
func (s *systemtestSuite) startListeners(containers []*container, ports []int) error {
errChan := make(chan error, len(containers)*len(ports))
for _, cont := range containers {
for _, port := range ports {
go func(cont *container, port int) { errChan <- cont.node.exec.startListener(cont, port, "tcp") }(cont, port)
}
}
for i := 0; i < len(containers)*len(ports); i++ {
if err := <-errChan; err != nil {
return err
}
}
return nil
}
func (s *systemtestSuite) startIperfServers(containers []*container) error {
for _, cont := range containers {
err := cont.node.exec.startIperfServer(cont)
if err != nil {
logrus.Errorf("Error starting the iperf server")
return err
}
}
return nil
}
func (s *systemtestSuite) checkConnections(containers []*container, port int) error {
ips := []string{}
for _, cont := range containers {
ips = append(ips, cont.eth0.ip)
}
endChan := make(chan error, len(containers))
for _, cont := range containers {
for _, ip := range ips {
if cont.eth0.ip == ip {
continue
}
go func(cont *container, ip string, port int) {
endChan <- cont.node.exec.checkConnection(cont, ip, "tcp", port)
}(cont, ip, port)
}
}
for i := 0; i < len(containers)*(len(ips)-1); i++ {
if err := <-endChan; err != nil {
return err
}
}
return nil
}
func (s *systemtestSuite) startIperfClients(containers []*container, limit string, isErr bool) error {
// get the ips of containers in a slice.
ips := []string{}
for _, cont := range containers {
ips = append(ips, cont.eth0.ip)
}
for _, cont := range containers {
for _, ip := range ips {
if cont.eth0.ip == ip {
continue
}
err := cont.node.exec.startIperfClient(cont, ip, limit, isErr)
if err != nil {
logrus.Errorf("Error starting the iperf client")
return err
}
}
}
return nil
}
func (s *systemtestSuite) checkIperfAcrossGroup(containers []*container, containers1 []*container, limit string, isErr bool) error {
// get the ips of containers in a slice.
ips := []string{}
for _, cont := range containers1 {
ips = append(ips, cont.eth0.ip)
}
for _, cont := range containers {
for _, ip := range ips {
if cont.eth0.ip == ip {
continue
}
err := cont.node.exec.startIperfClient(cont, ip, limit, isErr)
if err != nil {
logrus.Errorf("Error starting the iperf client")
return err
}
}
}
return nil
}
func (s *systemtestSuite) checkIngressRate(containers []*container, bw string) error {
for _, cont := range containers {
err := cont.node.exec.tcFilterShow(bw)
return err
}
return nil
}
func (s *systemtestSuite) checkNoConnections(containers []*container, port int) error {
ips := []string{}
for _, cont := range containers {
ips = append(ips, cont.eth0.ip)
}
endChan := make(chan error, len(containers))
for _, cont := range containers {
for _, ip := range ips {
if cont.eth0.ip == ip {
continue
}
go func(cont *container, ip string, port int) {
endChan <- cont.node.exec.checkNoConnection(cont, ip, "tcp", port)
}(cont, ip, port)
}
}
for i := 0; i < len(containers)*(len(ips)-1); i++ {
if err := <-endChan; err != nil {
return err
}
}
return nil
}
func (s *systemtestSuite) checkConnectionsAcrossGroup(containers map[*container]string, port int, expFail bool) error {
groups := map[string][]*container{}
for cont1, group := range containers {
if _, ok := groups[group]; !ok {
groups[group] = []*container{}
}
groups[group] = append(groups[group], cont1)
}
for cont1, group := range containers {
for group2, conts := range groups {
if group != group2 {
for _, cont := range conts {
err := cont1.node.exec.checkConnection(cont1, cont.eth0.ip, "tcp", port)
if !expFail && err != nil {
return err
}
}
}
}
}
return nil
}
func (s *systemtestSuite) checkConnectionsWithinGroup(containers map[*container]string, port int) error {
groups := map[string][]*container{}
for cont1, group := range containers {
if _, ok := groups[group]; !ok {
groups[group] = []*container{}
}
groups[group] = append(groups[group], cont1)
}
for cont1, group := range containers {
for group2, conts := range groups {
if group == group2 {
for _, cont := range conts {
if err := cont1.node.exec.checkConnection(cont1, cont.eth0.ip, "tcp", port); err != nil {
return err
}
}
}
}
}
return nil
}
func (s *systemtestSuite) checkPingContainersInNetworks(containers map[*container]string) error {
networks := map[string][]*container{}
for cont1, network := range containers {
if _, ok := networks[network]; !ok {
networks[network] = []*container{}
}
networks[network] = append(networks[network], cont1)
}
for cont1, network := range containers {
for network2, conts := range networks {
if network2 == network {
for _, cont := range conts {
if err := cont1.node.exec.checkPing(cont1, cont.eth0.ip); err != nil {
return err
}
}
}
}
}
return nil
}
func (s *systemtestSuite) checkAllConnection(netContainers map[*container]string, groupContainers map[*container]string) error {
if err := s.checkPingContainersInNetworks(netContainers); err != nil {
return err
}
if err := s.checkConnectionsWithinGroup(groupContainers, 8000); err != nil {
return err
}
if err := s.checkConnectionsWithinGroup(groupContainers, 8001); err != nil {
return err
}
if err := s.checkConnectionsAcrossGroup(groupContainers, 8000, false); err != nil {
return err
}
if err := s.checkConnectionsAcrossGroup(groupContainers, 8001, true); err != nil {
return fmt.Errorf("Connections across group achieved for port 8001")
}
return nil
}
func (s *systemtestSuite) pingFailureTestDifferentNode(containers1 []*container, containers2 []*container) error {
count := 0
for _, cont1 := range containers1 {
for _, cont2 := range containers2 {
if cont1.node != cont2.node {
count++
}
}
}
errChan := make(chan error, count)
for _, cont1 := range containers1 {
for _, cont2 := range containers2 {
if cont1.node != cont2.node {
go func(cont1 *container, cont2 *container) {
errChan <- cont1.node.exec.checkPingFailure(cont1, cont2.eth0.ip)
}(cont1, cont2)
}
}
}
for i := 0; i < count; i++ {
if err := <-errChan; err != nil {
return err
}
}
return nil
}
func (s *systemtestSuite) pingTestToNonContainer(containers []*container, nonContIps []string) error {
errChan := make(chan error, len(containers)*len(nonContIps))
for _, cont := range containers {
for _, ip := range nonContIps {
go func(cont *container, ip string) { errChan <- cont.node.exec.checkPingWithCount(cont, ip, 3) }(cont, ip)
}
}
for i := 0; i < len(containers)*len(nonContIps); i++ {
if err := <-errChan; err != nil {
return err
}
}
return nil
}
func (s *systemtestSuite) getJSON(url string, target interface{}) error {
content, err := s.nodes[0].runCommand(fmt.Sprintf("curl -s %s", url))
if err != nil {
logrus.Errorf("Error getting curl output: Err %v", err)
return err
}
return json.Unmarshal([]byte(content), target)
}
func (s *systemtestSuite) clusterStoreGet(path string) (string, error) {
if strings.Contains(s.basicInfo.ClusterStore, "etcd://") {
var etcdKv map[string]interface{}
// Get from etcd
etcdURL := strings.Replace(s.basicInfo.ClusterStore, "etcd://", "http://", 1)
etcdURL = etcdURL + "/v2/keys" + path
// get json from etcd
err := s.getJSON(etcdURL, &etcdKv)
if err != nil {
logrus.Errorf("Error getting json from host. Err: %v", err)
return "", err
}
node, ok := etcdKv["node"]
if !ok {
logrus.Errorf("Invalid json from etcd. %+v", etcdKv)
return "", errors.New("node not found")
}
value, ok := node.(map[string]interface{})["value"]
if !ok {
logrus.Errorf("Invalid json from etcd. %+v", etcdKv)
return "", errors.New("Value not found")
}
return value.(string), nil
} else if strings.Contains(s.basicInfo.ClusterStore, "consul://") {
var consulKv []map[string]interface{}
// Get from consul
consulURL := strings.Replace(s.basicInfo.ClusterStore, "consul://", "http://", 1)
consulURL = consulURL + "/v1/kv" + path
// get kv json from consul
err := s.getJSON(consulURL, &consulKv)
if err != nil {
return "", err
}
value, ok := consulKv[0]["Value"]
if !ok {
logrus.Errorf("Invalid json from consul. %+v", consulKv)
return "", errors.New("Value not found")
}
retVal, err := base64.StdEncoding.DecodeString(value.(string))
return string(retVal), err
} else {
// Unknown cluster store
return "", errors.New("Unknown cluster store")
}
}
func (s *systemtestSuite) getNetworkDNSServer(tenant, network string) (string, error) {
netInspect, err := s.cli.NetworkInspect(tenant, network)
if err != nil {
return "", err
}
return netInspect.Oper.DnsServerIP, nil
}
func (s *systemtestSuite) checkConnectionToService(containers []*container, ips []string, port int, protocol string) error {
for _, cont := range containers {
for _, ip := range ips {
if err := cont.node.exec.checkConnection(cont, ip, "tcp", port); err != nil {
return err
}
}
}
return nil
}
//ports is of the form 80:8080:TCP
func (s *systemtestSuite) startListenersOnProviders(containers []*container, ports []string) error {
portList := []int{}
for _, port := range ports {
p := strings.Split(port, ":")
providerPort, _ := strconv.Atoi(p[1])
portList = append(portList, providerPort)
}
errChan := make(chan error, len(containers)*len(portList))
for _, cont := range containers {
for _, port := range portList {
go func(cont *container, port int) { errChan <- cont.node.exec.startListener(cont, port, "tcp") }(cont, port)
}
}
for i := 0; i < len(containers)*len(portList); i++ {
if err := <-errChan; err != nil {
return err
}
}
return nil
}
func (s *systemtestSuite) getVTEPList() (map[string]bool, error) {
vtepMap := make(map[string]bool)
for _, n := range s.nodes {
if s.basicInfo.Scheduler == "k8" && n.Name() == "k8master" {
continue
}
vtep, err := n.getIPAddr(s.hostInfo.HostMgmtInterface)
if err != nil {
logrus.Errorf("Error getting eth1 IP address for node %s", n.Name())
return nil, err
}
vtepMap[vtep] = true
}
return vtepMap, nil
}
// Verify that the node is removed from VTEP table and the agentDB
func (s *systemtestSuite) verifyNodeRemoved(removed *node) error {
vteps, err := s.getVTEPList()
if err != nil {
logrus.Errorf("Failed to get VTEPs")
return err
}
nutIP, err := removed.getIPAddr(s.hostInfo.HostMgmtInterface)
if err != nil {
logrus.Errorf("Failed to get node VTEP")
return err
}
// Exclude the node-under-test
delete(vteps, nutIP)
failNode := ""
err = nil
dbgOut := ""
for try := 0; try < 20; try++ {
for _, n := range s.nodes {
if n.Name() == removed.Name() {
continue
}
dbgOut, err = n.verifyAgentDB(vteps)
if err != nil {
failNode = n.Name()
break
}
if n.Name() == "k8master" {
continue
}
dbgOut, err = n.verifyVTEPs(vteps)
if err != nil {
failNode = n.Name()
break
}
}
if err == nil {
return nil
}
time.Sleep(1 * time.Second)
}
logrus.Errorf("Node %s failed to verify node removal ERR: %v", failNode, err)
logrus.Infof("Debug output:\n %s", dbgOut)
return errors.New("Failed to verify VTEPs after 20 sec")
}
func (s *systemtestSuite) verifyVTEPs() error {
// get all expected VTEPs
var err error
expVTEPs, err := s.getVTEPList()
if err != nil {
logrus.Errorf("Failed to get VTEPs")
return err
}
failNode := ""
err = nil
dbgOut := ""
for try := 0; try < 20; try++ {
for _, n := range s.nodes {
if n.Name() == "k8master" {
continue
}
dbgOut, err = n.verifyVTEPs(expVTEPs)
if err != nil {
failNode = n.Name()
break
}
}
if err == nil {
return nil
}
time.Sleep(1 * time.Second)
}
logrus.Errorf("Node %s failed to verify all VTEPs", failNode)
logrus.Infof("Debug output:\n %s", dbgOut)
return errors.New("Failed to verify VTEPs after 20 sec")
}
func (s *systemtestSuite) verifyEPs(containers []*container) error {
var err error
// get the list of eps to verify
epList := make([]string, len(containers))
for ix, cont := range containers {
epList[ix] = cont.eth0.ip
}
err = nil
dbgOut := ""
for try := 0; try < 20; try++ {
for _, n := range s.nodes {
if n.Name() == "k8master" {
continue
}
dbgOut, err = n.verifyEPs(epList)
if err != nil {
break
}
}
if err == nil {
logrus.Infof("EPs %v verified on all nodes", epList)
return nil
}
time.Sleep(1 * time.Second)
}
logrus.Errorf("Failed to verify EPs after 20 sec %v", err)
logrus.Infof("Debug output:\n %s", dbgOut)
return err
}
func (s *systemtestSuite) verifyIPs(ipaddrs []string) error {
var err error
err = nil
dbgOut := ""
for try := 0; try < 20; try++ {
for _, n := range s.nodes {
if n.Name() == "k8master" {
continue
}
dbgOut, err = n.verifyEPs(ipaddrs)
if err != nil {
break
}
if err == nil {
logrus.Info("IPs %v verified on node %s", ipaddrs, n.Name())
return nil
}
}
time.Sleep(1 * time.Second)
}
logrus.Errorf("Failed to verify EP after 20 sec %v ", err)
logrus.Info("Debug output:\n %s", dbgOut)
return err
}
//Function to extract cfg Info from JSON file
func getInfo(file string) (BasicInfo, HostInfo, GlobInfo) {
raw, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
var b BasicInfo
json.Unmarshal(raw, &b)
var c HostInfo
json.Unmarshal(raw, &c)
var d GlobInfo
json.Unmarshal(raw, &d)
return b, c, d
}
// Setup suite and test methods for all platforms
func (s *systemtestSuite) SetUpSuiteBaremetal(c *C) {
logrus.Infof("Private keyFile = %s", s.basicInfo.KeyFile)
logrus.Infof("Binary binpath = %s", s.basicInfo.BinPath)
logrus.Infof("Interface vlanIf = %s", s.hostInfo.HostDataInterface)
s.baremetal = remotessh.Baremetal{}
bm := &s.baremetal
// To fill the hostInfo data structure for Baremetal VMs
var name string
if s.basicInfo.AciMode == "on" {
name = "aci-" + s.basicInfo.Scheduler + "-baremetal-node"
} else {
name = s.basicInfo.Scheduler + "-baremetal-node"
}
hostIPs := strings.Split(s.hostInfo.HostIPs, ",")
hostNames := strings.Split(s.hostInfo.HostUsernames, ",")
hosts := make([]remotessh.HostInfo, len(hostNames))
for i := range hostIPs {
hosts[i].Name = name + strconv.Itoa(i+1)
logrus.Infof("Name=%s", hosts[i].Name)
hosts[i].SSHAddr = hostIPs[i]
logrus.Infof("SHAddr=%s", hosts[i].SSHAddr)
hosts[i].SSHPort = "22"
hosts[i].User = hostNames[i]
logrus.Infof("User=%s", hosts[i].User)
hosts[i].PrivKeyFile = s.basicInfo.KeyFile
logrus.Infof("PrivKeyFile=%s", hosts[i].PrivKeyFile)
hosts[i].Env = append([]string{}, s.basicInfo.SwarmEnv)
logrus.Infof("Env variables are =%s", hosts[i].Env)
}
c.Assert(bm.Setup(hosts), IsNil)
s.nodes = []*node{}
for _, nodeObj := range s.baremetal.GetNodes() {
nodeName := nodeObj.GetName()
if strings.Contains(nodeName, s.basicInfo.Scheduler) {
node := &node{}
node.tbnode = nodeObj
node.suite = s
switch s.basicInfo.Scheduler {
case "k8":
node.exec = s.NewK8sExec(node)
case "swarm":
node.exec = s.NewSwarmExec(node)
default:
node.exec = s.NewDockerExec(node)
}
s.nodes = append(s.nodes, node)
}
//s.nodes = append(s.nodes, &node{tbnode: nodeObj, suite: s})
}
logrus.Info("Pulling alpine on all nodes")
s.baremetal.IterateNodes(func(node remotessh.TestbedNode) error {
node.RunCommand("sudo rm /tmp/*net*")
return node.RunCommand("docker pull contiv/alpine")
})
//Copying binaries
s.copyBinary("netmaster")
s.copyBinary("netplugin")
s.copyBinary("netctl")
s.copyBinary("contivk8s")
}
func (s *systemtestSuite) SetUpSuiteVagrant(c *C) {
s.vagrant = remotessh.Vagrant{}
nodesStr := os.Getenv("CONTIV_NODES")
var contivNodes int
if nodesStr == "" {
contivNodes = 3
} else {
var err error
contivNodes, err = strconv.Atoi(nodesStr)
if err != nil {
c.Fatal(err)
}
}
s.nodes = []*node{}
if s.fwdMode == "routing" {
contivL3Nodes := 2
switch s.basicInfo.Scheduler {
case "k8":
topDir := os.Getenv("GOPATH")
//topDir contains the godeps path. hence purging the gopath
topDir = strings.Split(topDir, ":")[1]
contivNodes = 4 // 3 contiv nodes + 1 k8master
c.Assert(s.vagrant.Setup(false, []string{"CONTIV_L3=1 VAGRANT_CWD=" + topDir + "/src/github.com/contiv/netplugin/vagrant/k8s/"}, contivNodes), IsNil)
case "swarm":
c.Assert(s.vagrant.Setup(false, append([]string{"CONTIV_NODES=3 CONTIV_L3=1"}, s.basicInfo.SwarmEnv), contivNodes+contivL3Nodes), IsNil)
default:
c.Assert(s.vagrant.Setup(false, []string{"CONTIV_NODES=3 CONTIV_L3=1"}, contivNodes+contivL3Nodes), IsNil)
}
} else {
switch s.basicInfo.Scheduler {
case "k8":
contivNodes = contivNodes + 1 //k8master
topDir := os.Getenv("GOPATH")
//topDir may contain the godeps path. hence purging the gopath
dirs := strings.Split(topDir, ":")
if len(dirs) > 1 {
topDir = dirs[1]
} else {
topDir = dirs[0]
}
c.Assert(s.vagrant.Setup(false, []string{"VAGRANT_CWD=" + topDir + "/src/github.com/contiv/netplugin/vagrant/k8s/"}, contivNodes), IsNil)
case "swarm":
c.Assert(s.vagrant.Setup(false, append([]string{}, s.basicInfo.SwarmEnv), contivNodes), IsNil)
default:
c.Assert(s.vagrant.Setup(false, []string{}, contivNodes), IsNil)
}
}
for _, nodeObj := range s.vagrant.GetNodes() {
nodeName := nodeObj.GetName()
if strings.Contains(nodeName, "netplugin-node") ||
strings.Contains(nodeName, "k8") {
node := &node{}
node.tbnode = nodeObj
node.suite = s
switch s.basicInfo.Scheduler {
case "k8":
node.exec = s.NewK8sExec(node)
case "swarm":
node.exec = s.NewSwarmExec(node)
default:
node.exec = s.NewDockerExec(node)
}
s.nodes = append(s.nodes, node)
}
}
logrus.Info("Pulling alpine on all nodes")
s.vagrant.IterateNodes(func(node remotessh.TestbedNode) error {
node.RunCommand("sudo rm /tmp/net*")
return node.RunCommand("docker pull contiv/alpine")
})
}
func (s *systemtestSuite) SetUpTestBaremetal(c *C) {
for _, node := range s.nodes {
node.exec.cleanupContainers()
//node.exec.cleanupDockerNetwork()
node.stopNetplugin()
node.cleanupSlave()
node.deleteFile("/etc/systemd/system/netplugin.service")
node.stopNetmaster()
node.deleteFile("/etc/systemd/system/netmaster.service")
node.deleteFile("/usr/bin/netplugin")
node.deleteFile("/usr/bin/netmaster")
node.deleteFile("/usr/bin/netctl")
}
for _, node := range s.nodes {
node.cleanupMaster()
}
for _, node := range s.nodes {
c.Assert(node.startNetplugin(""), IsNil)
c.Assert(node.exec.runCommandUntilNoNetpluginError(), IsNil)
}
time.Sleep(15 * time.Second)
for _, node := range s.nodes {
c.Assert(node.startNetmaster(), IsNil)
time.Sleep(1 * time.Second)
c.Assert(node.exec.runCommandUntilNoNetmasterError(), IsNil)
}
time.Sleep(5 * time.Second)
if s.basicInfo.Scheduler != "k8" {
for i := 0; i < 11; i++ {
_, err := s.cli.TenantGet("default")
if err == nil {
break
}
// Fail if we reached last iteration
c.Assert((i < 10), Equals, true)
time.Sleep(500 * time.Millisecond)
}
}
if s.fwdMode == "routing" {
c.Assert(s.cli.GlobalPost(&client.Global{FwdMode: "routing",
Name: "global",
NetworkInfraType: "default",
Vlans: "1-4094",
Vxlans: "1-10000",
}), IsNil)
time.Sleep(40 * time.Second)
}
}
func (s *systemtestSuite) SetUpTestVagrant(c *C) {
for _, node := range s.nodes {
node.exec.cleanupContainers()
node.stopNetplugin()
node.cleanupSlave()
}
for _, node := range s.nodes {
node.stopNetmaster()
}
for _, node := range s.nodes {
node.cleanupMaster()
}
for _, node := range s.nodes {
c.Assert(node.startNetplugin(""), IsNil)
c.Assert(node.exec.runCommandUntilNoNetpluginError(), IsNil)
}
time.Sleep(15 * time.Second)
// temporarily enable DNS for service discovery tests
prevDNSEnabled := s.basicInfo.EnableDNS
if strings.Contains(c.TestName(), "SvcDiscovery") {
s.basicInfo.EnableDNS = true
}
defer func() { s.basicInfo.EnableDNS = prevDNSEnabled }()
for _, node := range s.nodes {
c.Assert(node.startNetmaster(), IsNil)
time.Sleep(1 * time.Second)
c.Assert(node.exec.runCommandUntilNoNetmasterError(), IsNil)
}
time.Sleep(5 * time.Second)
if s.basicInfo.Scheduler != "k8" {
for i := 0; i < 11; i++ {
_, err := s.cli.TenantGet("default")
if err == nil {
break
}
// Fail if we reached last iteration
c.Assert((i < 10), Equals, true)
time.Sleep(500 * time.Millisecond)
}
}
if s.fwdMode == "routing" {
c.Assert(s.cli.GlobalPost(&client.Global{FwdMode: "routing",
Name: "global",
NetworkInfraType: "default",
Vlans: "1-4094",
Vxlans: "1-10000",
}), IsNil)
time.Sleep(120 * time.Second)
}
}
| [
"\"CONTIV_NODES\"",
"\"GOPATH\"",
"\"GOPATH\""
]
| []
| [
"GOPATH",
"CONTIV_NODES"
]
| [] | ["GOPATH", "CONTIV_NODES"] | go | 2 | 0 | |
sdk/formrecognizer/azure-ai-formrecognizer/samples/async_samples/sample_authentication_async.py | # coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
FILE: sample_authentication_async.py
DESCRIPTION:
This sample demonstrates how to authenticate to the Form Recognizer service.
There are two supported methods of authentication:
1) Use a Form Recognizer API key with AzureKeyCredential from azure.core.credentials
2) Use a token credential from azure-identity to authenticate with Azure Active Directory
See more details about authentication here:
https://docs.microsoft.com/azure/cognitive-services/authentication
USAGE:
python sample_authentication_async.py
Set the environment variables with your own values before running the sample:
1) AZURE_FORM_RECOGNIZER_ENDPOINT - the endpoint to your Form Recognizer resource.
2) AZURE_FORM_RECOGNIZER_KEY - your Form Recognizer API key
3) AZURE_CLIENT_ID - the client ID of your active directory application.
4) AZURE_TENANT_ID - the tenant ID of your active directory application.
5) AZURE_CLIENT_SECRET - the secret of your active directory application.
"""
import os
import asyncio
class AuthenticationSampleAsync(object):
url = "https://raw.githubusercontent.com/Azure/azure-sdk-for-python/master/sdk/formrecognizer/azure-ai-formrecognizer/tests/sample_forms/receipt/contoso-receipt.png"
async def authentication_with_api_key_credential_form_recognizer_client_async(self):
# [START create_fr_client_with_key_async]
from azure.core.credentials import AzureKeyCredential
from azure.ai.formrecognizer.aio import FormRecognizerClient
endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
key = os.environ["AZURE_FORM_RECOGNIZER_KEY"]
form_recognizer_client = FormRecognizerClient(endpoint, AzureKeyCredential(key))
# [END create_fr_client_with_key_async]
async with form_recognizer_client:
poller = await form_recognizer_client.begin_recognize_receipts_from_url(self.url)
result = await poller.result()
async def authentication_with_azure_active_directory_form_recognizer_client_async(self):
"""DefaultAzureCredential will use the values from these environment
variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
"""
# [START create_fr_client_with_aad_async]
from azure.ai.formrecognizer.aio import FormRecognizerClient
from azure.identity.aio import DefaultAzureCredential
endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
credential = DefaultAzureCredential()
form_recognizer_client = FormRecognizerClient(endpoint, credential)
# [END create_fr_client_with_aad_async]
async with form_recognizer_client:
poller = await form_recognizer_client.begin_recognize_receipts_from_url(self.url)
result = await poller.result()
async def authentication_with_api_key_credential_form_training_client_async(self):
# [START create_ft_client_with_key_async]
from azure.core.credentials import AzureKeyCredential
from azure.ai.formrecognizer.aio import FormTrainingClient
endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
key = os.environ["AZURE_FORM_RECOGNIZER_KEY"]
form_training_client = FormTrainingClient(endpoint, AzureKeyCredential(key))
# [END create_ft_client_with_key_async]
async with form_training_client:
properties = await form_training_client.get_account_properties()
async def authentication_with_azure_active_directory_form_training_client_async(self):
"""DefaultAzureCredential will use the values from these environment
variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET
"""
# [START create_ft_client_with_aad_async]
from azure.ai.formrecognizer.aio import FormTrainingClient
from azure.identity.aio import DefaultAzureCredential
endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"]
credential = DefaultAzureCredential()
form_training_client = FormTrainingClient(endpoint, credential)
# [END create_ft_client_with_aad_async]
async with form_training_client:
properties = await form_training_client.get_account_properties()
async def main():
sample = AuthenticationSampleAsync()
await sample.authentication_with_api_key_credential_form_recognizer_client_async()
await sample.authentication_with_azure_active_directory_form_recognizer_client_async()
await sample.authentication_with_api_key_credential_form_training_client_async()
await sample.authentication_with_azure_active_directory_form_training_client_async()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
| []
| []
| [
"AZURE_FORM_RECOGNIZER_KEY",
"AZURE_FORM_RECOGNIZER_ENDPOINT"
]
| [] | ["AZURE_FORM_RECOGNIZER_KEY", "AZURE_FORM_RECOGNIZER_ENDPOINT"] | python | 2 | 0 | |
qa/rpc-tests/test_framework/util.py | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Copyright (c) 2014-2019 The MarteX Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Helpful routines for regression testing
#
import os
import sys
from binascii import hexlify, unhexlify
from base64 import b64encode
from decimal import Decimal, ROUND_DOWN
import json
import http.client
import random
import shutil
import subprocess
import time
import re
import errno
from . import coverage
from .authproxy import AuthServiceProxy, JSONRPCException
COVERAGE_DIR = None
# The maximum number of nodes a single test can spawn
MAX_NODES = 8
# Don't assign rpc or p2p ports lower than this
PORT_MIN = 11000
# The number of ports to "reserve" for p2p and rpc, each
PORT_RANGE = 5000
BITCOIND_PROC_WAIT_TIMEOUT = 60
class PortSeed:
# Must be initialized with a unique integer for each process
n = None
#Set Mocktime default to OFF.
#MOCKTIME is only needed for scripts that use the
#cached version of the blockchain. If the cached
#version of the blockchain is used without MOCKTIME
#then the mempools will not sync due to IBD.
MOCKTIME = 0
GENESISTIME = 1417713337
def set_mocktime(t):
global MOCKTIME
MOCKTIME = t
def disable_mocktime():
set_mocktime(0)
def get_mocktime():
return MOCKTIME
def set_cache_mocktime():
#For backwared compatibility of the python scripts
#with previous versions of the cache, set MOCKTIME
#to regtest genesis time + (201 * 156)
set_mocktime(GENESISTIME + (201 * 156))
def set_genesis_mocktime():
set_mocktime(GENESISTIME)
def enable_coverage(dirname):
"""Maintain a log of which RPC calls are made during testing."""
global COVERAGE_DIR
COVERAGE_DIR = dirname
def get_rpc_proxy(url, node_number, timeout=None):
"""
Args:
url (str): URL of the RPC server to call
node_number (int): the node number (or id) that this calls to
Kwargs:
timeout (int): HTTP timeout in seconds
Returns:
AuthServiceProxy. convenience object for making RPC calls.
"""
proxy_kwargs = {}
if timeout is not None:
proxy_kwargs['timeout'] = timeout
proxy = AuthServiceProxy(url, **proxy_kwargs)
proxy.url = url # store URL on proxy for info
coverage_logfile = coverage.get_filename(
COVERAGE_DIR, node_number) if COVERAGE_DIR else None
return coverage.AuthServiceProxyWrapper(proxy, coverage_logfile)
def get_mnsync_status(node):
result = node.mnsync("status")
return result['IsSynced']
def wait_to_sync(node):
synced = False
while not synced:
synced = get_mnsync_status(node)
time.sleep(0.5)
def p2p_port(n):
assert(n <= MAX_NODES)
return PORT_MIN + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
def rpc_port(n):
return PORT_MIN + PORT_RANGE + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def count_bytes(hex_string):
return len(bytearray.fromhex(hex_string))
def bytes_to_hex_str(byte_str):
return hexlify(byte_str).decode('ascii')
def hex_str_to_bytes(hex_str):
return unhexlify(hex_str.encode('ascii'))
def str_to_b64str(string):
return b64encode(string.encode('utf-8')).decode('ascii')
def sync_blocks(rpc_connections, *, wait=1, timeout=60):
"""
Wait until everybody has the same tip.
sync_blocks needs to be called with an rpc_connections set that has least
one node already synced to the latest, stable tip, otherwise there's a
chance it might return before all nodes are stably synced.
"""
# Use getblockcount() instead of waitforblockheight() to determine the
# initial max height because the two RPCs look at different internal global
# variables (chainActive vs latestBlock) and the former gets updated
# earlier.
maxheight = max(x.getblockcount() for x in rpc_connections)
start_time = cur_time = time.time()
while cur_time <= start_time + timeout:
tips = [r.waitforblockheight(maxheight, int(wait * 1000)) for r in rpc_connections]
if all(t["height"] == maxheight for t in tips):
if all(t["hash"] == tips[0]["hash"] for t in tips):
return
raise AssertionError("Block sync failed, mismatched block hashes:{}".format(
"".join("\n {!r}".format(tip) for tip in tips)))
cur_time = time.time()
raise AssertionError("Block sync to height {} timed out:{}".format(
maxheight, "".join("\n {!r}".format(tip) for tip in tips)))
def sync_chain(rpc_connections, *, wait=1, timeout=60):
"""
Wait until everybody has the same best block
"""
while timeout > 0:
best_hash = [x.getbestblockhash() for x in rpc_connections]
if best_hash == [best_hash[0]]*len(best_hash):
return
time.sleep(wait)
timeout -= wait
raise AssertionError("Chain sync failed: Best block hashes don't match")
def sync_mempools(rpc_connections, *, wait=1, timeout=60):
"""
Wait until everybody has the same transactions in their memory
pools
"""
while timeout > 0:
pool = set(rpc_connections[0].getrawmempool())
num_match = 1
for i in range(1, len(rpc_connections)):
if set(rpc_connections[i].getrawmempool()) == pool:
num_match = num_match+1
if num_match == len(rpc_connections):
return
time.sleep(wait)
timeout -= wait
raise AssertionError("Mempool sync failed")
def sync_masternodes(rpc_connections):
for node in rpc_connections:
wait_to_sync(node)
bitcoind_processes = {}
def initialize_datadir(dirname, n):
datadir = os.path.join(dirname, "node"+str(n))
if not os.path.isdir(datadir):
os.makedirs(datadir)
rpc_u, rpc_p = rpc_auth_pair(n)
with open(os.path.join(datadir, "MarteX.conf"), 'w', encoding='utf8') as f:
f.write("regtest=1\n")
f.write("rpcuser=" + rpc_u + "\n")
f.write("rpcpassword=" + rpc_p + "\n")
f.write("port="+str(p2p_port(n))+"\n")
f.write("rpcport="+str(rpc_port(n))+"\n")
f.write("listenonion=0\n")
return datadir
def rpc_auth_pair(n):
return 'rpcuser💻' + str(n), 'rpcpass🔑' + str(n)
def rpc_url(i, rpchost=None):
rpc_u, rpc_p = rpc_auth_pair(i)
host = '127.0.0.1'
port = rpc_port(i)
if rpchost:
parts = rpchost.split(':')
if len(parts) == 2:
host, port = parts
else:
host = rpchost
return "http://%s:%s@%s:%d" % (rpc_u, rpc_p, host, int(port))
def wait_for_bitcoind_start(process, url, i):
'''
Wait for martexd to start. This means that RPC is accessible and fully initialized.
Raise an exception if martexd exits during initialization.
'''
while True:
if process.poll() is not None:
raise Exception('martexd exited with status %i during initialization' % process.returncode)
try:
rpc = get_rpc_proxy(url, i)
blocks = rpc.getblockcount()
break # break out of loop on success
except IOError as e:
if e.errno != errno.ECONNREFUSED: # Port not yet open?
raise # unknown IO error
except JSONRPCException as e: # Initialization phase
if e.error['code'] != -28: # RPC in warmup?
raise # unknown JSON RPC exception
time.sleep(0.25)
def initialize_chain(test_dir, num_nodes, cachedir, extra_args=None, redirect_stderr=False):
"""
Create a cache of a 200-block-long chain (with wallet) for MAX_NODES
Afterward, create num_nodes copies from the cache
"""
assert num_nodes <= MAX_NODES
create_cache = False
for i in range(MAX_NODES):
if not os.path.isdir(os.path.join(cachedir, 'node'+str(i))):
create_cache = True
break
if create_cache:
#find and delete old cache directories if any exist
for i in range(MAX_NODES):
if os.path.isdir(os.path.join(cachedir,"node"+str(i))):
shutil.rmtree(os.path.join(cachedir,"node"+str(i)))
set_genesis_mocktime()
# Create cache directories, run martexds:
for i in range(MAX_NODES):
datadir=initialize_datadir(cachedir, i)
args = [ os.getenv("MARTEXD", "martexd"), "-server", "-keypool=1", "-datadir="+datadir, "-discover=0", "-mocktime="+str(GENESISTIME) ]
if i > 0:
args.append("-connect=127.0.0.1:"+str(p2p_port(0)))
if extra_args is not None:
args += extra_args
stderr = None
if redirect_stderr:
stderr = sys.stdout
bitcoind_processes[i] = subprocess.Popen(args, stderr=stderr)
if os.getenv("PYTHON_DEBUG", ""):
print("initialize_chain: martexd started, waiting for RPC to come up")
wait_for_bitcoind_start(bitcoind_processes[i], rpc_url(i), i)
if os.getenv("PYTHON_DEBUG", ""):
print("initialize_chain: RPC successfully started")
rpcs = []
for i in range(MAX_NODES):
try:
rpcs.append(get_rpc_proxy(rpc_url(i), i))
except:
sys.stderr.write("Error connecting to "+url+"\n")
sys.exit(1)
# Create a 200-block-long chain; each of the 4 first nodes
# gets 25 mature blocks and 25 immature.
# Note: To preserve compatibility with older versions of
# initialize_chain, only 4 nodes will generate coins.
#
# blocks are created with timestamps 156 seconds apart
block_time = GENESISTIME
for i in range(2):
for peer in range(4):
for j in range(25):
set_node_times(rpcs, block_time)
rpcs[peer].generate(1)
block_time += 156
# Must sync before next peer starts generating blocks
sync_blocks(rpcs)
# Shut them down, and clean up cache directories:
stop_nodes(rpcs)
disable_mocktime()
for i in range(MAX_NODES):
os.remove(log_filename(cachedir, i, "debug.log"))
os.remove(log_filename(cachedir, i, "db.log"))
os.remove(log_filename(cachedir, i, "peers.dat"))
os.remove(log_filename(cachedir, i, "fee_estimates.dat"))
for i in range(num_nodes):
from_dir = os.path.join(cachedir, "node"+str(i))
to_dir = os.path.join(test_dir, "node"+str(i))
shutil.copytree(from_dir, to_dir)
initialize_datadir(test_dir, i) # Overwrite port/rpcport in MarteX.conf
def initialize_chain_clean(test_dir, num_nodes):
"""
Create an empty blockchain and num_nodes wallets.
Useful if a test case wants complete control over initialization.
"""
for i in range(num_nodes):
datadir=initialize_datadir(test_dir, i)
def _rpchost_to_args(rpchost):
'''Convert optional IP:port spec to rpcconnect/rpcport args'''
if rpchost is None:
return []
match = re.match('(\[[0-9a-fA-f:]+\]|[^:]+)(?::([0-9]+))?$', rpchost)
if not match:
raise ValueError('Invalid RPC host spec ' + rpchost)
rpcconnect = match.group(1)
rpcport = match.group(2)
if rpcconnect.startswith('['): # remove IPv6 [...] wrapping
rpcconnect = rpcconnect[1:-1]
rv = ['-rpcconnect=' + rpcconnect]
if rpcport:
rv += ['-rpcport=' + rpcport]
return rv
def start_node(i, dirname, extra_args=None, rpchost=None, timewait=None, binary=None, redirect_stderr=False):
"""
Start a martexd and return RPC connection to it
"""
datadir = os.path.join(dirname, "node"+str(i))
if binary is None:
binary = os.getenv("MARTEXD", "martexd")
# RPC tests still depend on free transactions
args = [ binary, "-datadir="+datadir, "-server", "-keypool=1", "-discover=0", "-rest", "-blockprioritysize=50000", "-mocktime="+str(get_mocktime()) ]
# Don't try auto backups (they fail a lot when running tests)
args += [ "-createwalletbackups=0" ]
if extra_args is not None: args.extend(extra_args)
# Allow to redirect stderr to stdout in case we expect some non-critical warnings/errors printed to stderr
# Otherwise the whole test would be considered to be failed in such cases
stderr = None
if redirect_stderr:
stderr = sys.stdout
bitcoind_processes[i] = subprocess.Popen(args, stderr=stderr)
if os.getenv("PYTHON_DEBUG", ""):
print("start_node: martexd started, waiting for RPC to come up")
url = rpc_url(i, rpchost)
wait_for_bitcoind_start(bitcoind_processes[i], url, i)
if os.getenv("PYTHON_DEBUG", ""):
print("start_node: RPC successfully started")
proxy = get_rpc_proxy(url, i, timeout=timewait)
if COVERAGE_DIR:
coverage.write_all_rpc_commands(COVERAGE_DIR, proxy)
return proxy
def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None, timewait=None, binary=None, redirect_stderr=False):
"""
Start multiple martexds, return RPC connections to them
"""
if extra_args is None: extra_args = [ None for _ in range(num_nodes) ]
if binary is None: binary = [ None for _ in range(num_nodes) ]
rpcs = []
try:
for i in range(num_nodes):
rpcs.append(start_node(i, dirname, extra_args[i], rpchost, timewait=timewait, binary=binary[i], redirect_stderr=redirect_stderr))
except: # If one node failed to start, stop the others
stop_nodes(rpcs)
raise
return rpcs
def log_filename(dirname, n_node, logname):
return os.path.join(dirname, "node"+str(n_node), "regtest", logname)
def stop_node(node, i):
try:
node.stop()
except http.client.CannotSendRequest as e:
print("WARN: Unable to stop node: " + repr(e))
return_code = bitcoind_processes[i].wait(timeout=BITCOIND_PROC_WAIT_TIMEOUT)
assert_equal(return_code, 0)
del bitcoind_processes[i]
def stop_nodes(nodes):
for i, node in enumerate(nodes):
stop_node(node, i)
assert not bitcoind_processes.values() # All connections must be gone now
def set_node_times(nodes, t):
for node in nodes:
node.setmocktime(t)
def connect_nodes(from_connection, node_num):
ip_port = "127.0.0.1:"+str(p2p_port(node_num))
from_connection.addnode(ip_port, "onetry")
# poll until version handshake complete to avoid race conditions
# with transaction relaying
while any(peer['version'] == 0 for peer in from_connection.getpeerinfo()):
time.sleep(0.1)
def connect_nodes_bi(nodes, a, b):
connect_nodes(nodes[a], b)
connect_nodes(nodes[b], a)
def find_output(node, txid, amount):
"""
Return index to output of txid with value amount
Raises exception if there is none.
"""
txdata = node.getrawtransaction(txid, 1)
for i in range(len(txdata["vout"])):
if txdata["vout"][i]["value"] == amount:
return i
raise RuntimeError("find_output txid %s : %s not found"%(txid,str(amount)))
def gather_inputs(from_node, amount_needed, confirmations_required=1):
"""
Return a random set of unspent txouts that are enough to pay amount_needed
"""
assert(confirmations_required >=0)
utxo = from_node.listunspent(confirmations_required)
random.shuffle(utxo)
inputs = []
total_in = Decimal("0.00000000")
while total_in < amount_needed and len(utxo) > 0:
t = utxo.pop()
total_in += t["amount"]
inputs.append({ "txid" : t["txid"], "vout" : t["vout"], "address" : t["address"] } )
if total_in < amount_needed:
raise RuntimeError("Insufficient funds: need %d, have %d"%(amount_needed, total_in))
return (total_in, inputs)
def make_change(from_node, amount_in, amount_out, fee):
"""
Create change output(s), return them
"""
outputs = {}
amount = amount_out+fee
change = amount_in - amount
if change > amount*2:
# Create an extra change output to break up big inputs
change_address = from_node.getnewaddress()
# Split change in two, being careful of rounding:
outputs[change_address] = Decimal(change/2).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
change = amount_in - amount - outputs[change_address]
if change > 0:
outputs[from_node.getnewaddress()] = change
return outputs
def send_zeropri_transaction(from_node, to_node, amount, fee):
"""
Create&broadcast a zero-priority transaction.
Returns (txid, hex-encoded-txdata)
Ensures transaction is zero-priority by first creating a send-to-self,
then using its output
"""
# Create a send-to-self with confirmed inputs:
self_address = from_node.getnewaddress()
(total_in, inputs) = gather_inputs(from_node, amount+fee*2)
outputs = make_change(from_node, total_in, amount+fee, fee)
outputs[self_address] = float(amount+fee)
self_rawtx = from_node.createrawtransaction(inputs, outputs)
self_signresult = from_node.signrawtransaction(self_rawtx)
self_txid = from_node.sendrawtransaction(self_signresult["hex"], True)
vout = find_output(from_node, self_txid, amount+fee)
# Now immediately spend the output to create a 1-input, 1-output
# zero-priority transaction:
inputs = [ { "txid" : self_txid, "vout" : vout } ]
outputs = { to_node.getnewaddress() : float(amount) }
rawtx = from_node.createrawtransaction(inputs, outputs)
signresult = from_node.signrawtransaction(rawtx)
txid = from_node.sendrawtransaction(signresult["hex"], True)
return (txid, signresult["hex"])
def random_zeropri_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
"""
Create a random zero-priority transaction.
Returns (txid, hex-encoded-transaction-data, fee)
"""
from_node = random.choice(nodes)
to_node = random.choice(nodes)
fee = min_fee + fee_increment*random.randint(0,fee_variants)
(txid, txhex) = send_zeropri_transaction(from_node, to_node, amount, fee)
return (txid, txhex, fee)
def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
"""
Create a random transaction.
Returns (txid, hex-encoded-transaction-data, fee)
"""
from_node = random.choice(nodes)
to_node = random.choice(nodes)
fee = min_fee + fee_increment*random.randint(0,fee_variants)
(total_in, inputs) = gather_inputs(from_node, amount+fee)
outputs = make_change(from_node, total_in, amount, fee)
outputs[to_node.getnewaddress()] = float(amount)
rawtx = from_node.createrawtransaction(inputs, outputs)
signresult = from_node.signrawtransaction(rawtx)
txid = from_node.sendrawtransaction(signresult["hex"], True)
return (txid, signresult["hex"], fee)
def assert_fee_amount(fee, tx_size, fee_per_kB):
"""Assert the fee was in range"""
target_fee = tx_size * fee_per_kB / 1000
if fee < target_fee:
raise AssertionError("Fee of %s MXT too low! (Should be %s MXT)"%(str(fee), str(target_fee)))
# allow the wallet's estimation to be at most 2 bytes off
if fee > (tx_size + 2) * fee_per_kB / 1000:
raise AssertionError("Fee of %s MXT too high! (Should be %s MXT)"%(str(fee), str(target_fee)))
def assert_equal(thing1, thing2, *args):
if thing1 != thing2 or any(thing1 != arg for arg in args):
raise AssertionError("not(%s)" % " == ".join(str(arg) for arg in (thing1, thing2) + args))
def assert_greater_than(thing1, thing2):
if thing1 <= thing2:
raise AssertionError("%s <= %s"%(str(thing1),str(thing2)))
def assert_greater_than_or_equal(thing1, thing2):
if thing1 < thing2:
raise AssertionError("%s < %s"%(str(thing1),str(thing2)))
def assert_raises(exc, fun, *args, **kwds):
assert_raises_message(exc, None, fun, *args, **kwds)
def assert_raises_message(exc, message, fun, *args, **kwds):
try:
fun(*args, **kwds)
except exc as e:
if message is not None and message not in e.error['message']:
raise AssertionError("Expected substring not found:"+e.error['message'])
except Exception as e:
raise AssertionError("Unexpected exception raised: "+type(e).__name__)
else:
raise AssertionError("No exception raised")
def assert_raises_jsonrpc(code, message, fun, *args, **kwds):
"""Run an RPC and verify that a specific JSONRPC exception code and message is raised.
Calls function `fun` with arguments `args` and `kwds`. Catches a JSONRPCException
and verifies that the error code and message are as expected. Throws AssertionError if
no JSONRPCException was returned or if the error code/message are not as expected.
Args:
code (int), optional: the error code returned by the RPC call (defined
in src/rpc/protocol.h). Set to None if checking the error code is not required.
message (string), optional: [a substring of] the error string returned by the
RPC call. Set to None if checking the error string is not required
fun (function): the function to call. This should be the name of an RPC.
args*: positional arguments for the function.
kwds**: named arguments for the function.
"""
try:
fun(*args, **kwds)
except JSONRPCException as e:
# JSONRPCException was thrown as expected. Check the code and message values are correct.
if (code is not None) and (code != e.error["code"]):
raise AssertionError("Unexpected JSONRPC error code %i" % e.error["code"])
if (message is not None) and (message not in e.error['message']):
raise AssertionError("Expected substring not found:"+e.error['message'])
except Exception as e:
raise AssertionError("Unexpected exception raised: "+type(e).__name__)
else:
raise AssertionError("No exception raised")
def assert_is_hex_string(string):
try:
int(string, 16)
except Exception as e:
raise AssertionError(
"Couldn't interpret %r as hexadecimal; raised: %s" % (string, e))
def assert_is_hash_string(string, length=64):
if not isinstance(string, str):
raise AssertionError("Expected a string, got type %r" % type(string))
elif length and len(string) != length:
raise AssertionError(
"String of length %d expected; got %d" % (length, len(string)))
elif not re.match('[abcdef0-9]+$', string):
raise AssertionError(
"String %r contains invalid characters for a hash." % string)
def assert_array_result(object_array, to_match, expected, should_not_find = False):
"""
Pass in array of JSON objects, a dictionary with key/value pairs
to match against, and another dictionary with expected key/value
pairs.
If the should_not_find flag is true, to_match should not be found
in object_array
"""
if should_not_find == True:
assert_equal(expected, { })
num_matched = 0
for item in object_array:
all_match = True
for key,value in to_match.items():
if item[key] != value:
all_match = False
if not all_match:
continue
elif should_not_find == True:
num_matched = num_matched+1
for key,value in expected.items():
if item[key] != value:
raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value)))
num_matched = num_matched+1
if num_matched == 0 and should_not_find != True:
raise AssertionError("No objects matched %s"%(str(to_match)))
if num_matched > 0 and should_not_find == True:
raise AssertionError("Objects were found %s"%(str(to_match)))
def satoshi_round(amount):
return Decimal(amount).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
# Helper to create at least "count" utxos
# Pass in a fee that is sufficient for relay and mining new transactions.
def create_confirmed_utxos(fee, node, count):
node.generate(int(0.5*count)+101)
utxos = node.listunspent()
iterations = count - len(utxos)
addr1 = node.getnewaddress()
addr2 = node.getnewaddress()
if iterations <= 0:
return utxos
for i in range(iterations):
t = utxos.pop()
inputs = []
inputs.append({ "txid" : t["txid"], "vout" : t["vout"]})
outputs = {}
send_value = t['amount'] - fee
outputs[addr1] = satoshi_round(send_value/2)
outputs[addr2] = satoshi_round(send_value/2)
raw_tx = node.createrawtransaction(inputs, outputs)
signed_tx = node.signrawtransaction(raw_tx)["hex"]
txid = node.sendrawtransaction(signed_tx)
while (node.getmempoolinfo()['size'] > 0):
node.generate(1)
utxos = node.listunspent()
assert(len(utxos) >= count)
return utxos
# Create large OP_RETURN txouts that can be appended to a transaction
# to make it large (helper for constructing large transactions).
def gen_return_txouts():
# Some pre-processing to create a bunch of OP_RETURN txouts to insert into transactions we create
# So we have big transactions (and therefore can't fit very many into each block)
# create one script_pubkey
script_pubkey = "6a4d0200" #OP_RETURN OP_PUSH2 512 bytes
for i in range (512):
script_pubkey = script_pubkey + "01"
# concatenate 128 txouts of above script_pubkey which we'll insert before the txout for change
txouts = "81"
for k in range(128):
# add txout value
txouts = txouts + "0000000000000000"
# add length of script_pubkey
txouts = txouts + "fd0402"
# add script_pubkey
txouts = txouts + script_pubkey
return txouts
def create_tx(node, coinbase, to_address, amount):
inputs = [{ "txid" : coinbase, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
assert_equal(signresult["complete"], True)
return signresult["hex"]
# Create a spend of each passed-in utxo, splicing in "txouts" to each raw
# transaction to make it large. See gen_return_txouts() above.
def create_lots_of_big_transactions(node, txouts, utxos, num, fee):
addr = node.getnewaddress()
txids = []
for _ in range(num):
t = utxos.pop()
inputs=[{ "txid" : t["txid"], "vout" : t["vout"]}]
outputs = {}
change = t['amount'] - fee
outputs[addr] = satoshi_round(change)
rawtx = node.createrawtransaction(inputs, outputs)
newtx = rawtx[0:92]
newtx = newtx + txouts
newtx = newtx + rawtx[94:]
signresult = node.signrawtransaction(newtx, None, None, "NONE")
txid = node.sendrawtransaction(signresult["hex"], True)
txids.append(txid)
return txids
def mine_large_block(node, utxos=None):
# generate a 66k transaction,
# and 14 of them is close to the 1MB block limit
num = 14
txouts = gen_return_txouts()
utxos = utxos if utxos is not None else []
if len(utxos) < num:
utxos.clear()
utxos.extend(node.listunspent())
fee = 100 * node.getnetworkinfo()["relayfee"]
create_lots_of_big_transactions(node, txouts, utxos, num, fee=fee)
node.generate(1)
def get_bip9_status(node, key):
info = node.getblockchaininfo()
return info['bip9_softforks'][key]
| []
| []
| [
"PYTHON_DEBUG",
"MARTEXD"
]
| [] | ["PYTHON_DEBUG", "MARTEXD"] | python | 2 | 0 | |
py/ec2_cmd.py | #!/usr/bin/python
import argparse
import boto
import os, time, sys, socket
import h2o_cmd
import h2o
import h2o_hosts
import json
import commands
import traceback
'''
Simple EC2 utility:
* to setup clooud of 5 nodes: ./ec2_cmd.py create --instances 5
* to terminated the cloud : ./ec2_cmd.py terminate --hosts <host file returned by previous command>
'''
DEFAULT_NUMBER_OF_INSTANCES = 4
DEFAULT_HOSTS_FILENAME = 'ec2-config-{0}.json'
DEFAULT_REGION = 'us-east-1'
DEFAULT_INSTANCE_NAME='node_{0}'.format(os.getenv('USER'))
ADVANCED_SSH_OPTIONS='-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o GlobalKnownHostsFile=/dev/null'
'''
Default EC2 instance setup
'''
DEFAULT_EC2_INSTANCE_CONFIGS = {
'us-east-1':{
'image_id' : 'ami-cf5132a6', #'ami-30c6a059', #'ami-b85cc4d1', # 'ami-cd9a11a4',
'security_groups' : [ 'MrJenkinsTest' ],
'key_name' : 'mrjenkins_test',
'instance_type' : 'm1.xlarge',
'region' : 'us-east-1',
'pem' : '~/.ec2/keys/mrjenkins_test.pem',
'username' : '0xdiag',
'aws_credentials' : '~/.ec2/AwsCredentials.properties',
'hdfs_config' : '~/.ec2/core-site.xml',
},
'us-west-1':{
'image_id' : 'ami-a6cbe6e3', # 'ami-cd9a11a4',
'security_groups' : [ 'MrJenkinsTest' ],
'key_name' : 'mrjenkins_test',
'instance_type' : 'm1.xlarge',
'pem' : '~/.ec2/keys/mrjenkins_test.pem',
'username' : '0xdiag',
'aws_credentials' : '~/.ec2/AwsCredentials.properties',
'hdfs_config' : '~/.ec2/core-site.xml',
'region' : 'us-west-1',
},
}
''' Memory mappings for instance kinds '''
MEMORY_MAPPING = {
'm1.small' : { 'xmx' : 1 },
'm1.medium' : { 'xmx' : 3 },
'm1.large' : { 'xmx' : 5 }, # $0.24/hr
'm1.xlarge' : { 'xmx' : 12 }, # $0.48/hr
'm2.xlarge' : { 'xmx' : 13 }, # $0.41/hr
'm2.2xlarge' : { 'xmx' : 30 }, # $0.82/hr
'm2.4xlarge' : { 'xmx' : 64 }, # $1.64/hr
'm3.medium' : { 'xmx' : 3 },
'm3.large' : { 'xmx' : 5 },
'm3.xlarge' : { 'xmx' : 12 }, # $0.50/hr
'm3.2xlarge' : { 'xmx' : 26 }, # $1.00/hr
'c1.medium' : { 'xmx' : 1 },
'c1.xlarge' : { 'xmx' : 6 }, # $0.58/hr
'c3.large' : { 'xmx' : 3 },
'c3.xlarge' : { 'xmx' : 5 }, # $0.30/hr
'c3.2xlarge' : { 'xmx' : 12 },
'c3.4xlarge' : { 'xmx' : 27 },
'c3.8xlarge' : { 'xmx' : 56 },
'cc2.8xlarge' : { 'xmx' : 56 },
'hi1.4xlarge' : { 'xmx' : 56 }, # $3.10/hr 60.5GB dram. 8 cores/8 threads. 2TB SSD. 10GE
'cr1.8xlarge' : { 'xmx' : 230}, # $4.60/hr 244GB dram. 2 E5-2670. 240GB SSD. 10GE
'g2.2xlarge' : { 'xmx' : 12 },
'i2.xlarge' : { 'xmx' : 27 },
'i2.2xlarge' : { 'xmx' : 57 },
'cg1.4xlarge' : { 'xmx' : 19 },
'i2.4xlarge' : { 'xmx' : 116},
'hs1.8xlarge' : { 'xmx' : 112},
'i2.8xlarge' : { 'xmx' : 236},
}
''' EC2 API default configuration. The corresponding values are replaces by EC2 user config. '''
EC2_API_RUN_INSTANCE = {
'image_id' :None,
'min_count' :1,
'max_count' :1,
'key_name' :None,
'security_groups' :None,
'user_data' :None,
'addressing_type' :None,
'instance_type' :None,
'placement' :None,
'monitoring_enabled':False,
'subnet_id' :None,
'block_device_map':None,
'disable_api_termination':False,
'instance_initiated_shutdown_behavior':None
}
def inheritparams(parent, kid):
newkid = {}
for k,v in kid.items():
if parent.has_key(k):
newkid[k] = parent[k]
return newkid
def find_file(base):
f = base
if not os.path.exists(f): f = os.path.expanduser(base)
if not os.path.exists(f): f = os.path.expanduser("~")+ '/' + base
if not os.path.exists(f):
return None
return f
''' Returns a boto connection to given region '''
def ec2_connect(region):
check_required_env_variables()
import boto.ec2
conn = boto.ec2.connect_to_region(region)
if not conn:
raise Exception("\033[91m[ec2] Cannot create EC2 connection into {0} region!\033[0m".format(region))
return conn
def check_required_env_variables():
ok = True
if not os.environ['AWS_ACCESS_KEY_ID']:
warn("AWS_ACCESS_KEY_ID need to be defined!")
ok = False
if not os.environ['AWS_SECRET_ACCESS_KEY']:
warn("AWS_SECRET_ACCESS_KEY need to be defined!")
ok = False
if not ok: raise Exception("\033[91m[ec2] Missing AWS environment variables!\033[0m")
''' Run number of EC2 instance.
Waits forthem and optionaly waits for ssh service.
'''
def run_instances(count, ec2_config, region, waitForSSH=True, tags=None):
'''Create a new reservation for count instances'''
ec2params = inheritparams(ec2_config, EC2_API_RUN_INSTANCE)
ec2params.setdefault('min_count', count)
ec2params.setdefault('max_count', count)
reservation = None
conn = ec2_connect(region)
try:
reservation = conn.run_instances(**ec2params)
log('Reservation: {0}'.format(reservation.id))
log('Waiting for {0} EC2 instances {1} to come up, this can take 1-2 minutes.'.format(len(reservation.instances), reservation.instances))
start = time.time()
time.sleep(1)
for instance in reservation.instances:
while instance.update() == 'pending':
time.sleep(1)
h2o_cmd.dot()
if not instance.state == 'running':
raise Exception('\033[91m[ec2] Error waiting for running state. Instance is in state {0}.\033[0m'.format(instance.state))
log('Instances started in {0} seconds'.format(time.time() - start))
log('Instances: ')
for inst in reservation.instances: log(" {0} ({1}) : public ip: {2}, private ip: {3}".format(inst.public_dns_name, inst.id, inst.ip_address, inst.private_ip_address))
if waitForSSH:
# kbn: changing to private address, so it should fail if not in right domain
# used to have the public ip address
wait_for_ssh([ i.private_ip_address for i in reservation.instances ])
# Tag instances
try:
if tags:
conn.create_tags([i.id for i in reservation.instances], tags)
except:
warn('Something wrong during tagging instances. Exceptions IGNORED!')
print sys.exc_info()
pass
return reservation
except:
print "\033[91mUnexpected error\033[0m :", sys.exc_info()
if reservation:
terminate_reservation(reservation, region)
raise
''' Wait for ssh port
'''
def ssh_live(ip, port=22):
return h2o_cmd.port_live(ip,port)
def terminate_reservation(reservation, region):
terminate_instances([ i.id for i in reservation.instances ], region)
def terminate_instances(instances, region):
'''terminate all the instances given by its ids'''
if not instances: return
conn = ec2_connect(region)
log("Terminating instances {0}.".format(instances))
conn.terminate_instances(instances)
log("Done")
def stop_instances(instances, region):
'''stop all the instances given by its ids'''
if not instances: return
conn = ec2_connect(region)
log("Stopping instances {0}.".format(instances))
conn.stop_instances(instances)
log("Done")
def start_instances(instances, region):
'''Start all the instances given by its ids'''
if not instances: return
conn = ec2_connect(region)
log("Starting instances {0}.".format(instances))
conn.start_instances(instances)
log("Done")
def reboot_instances(instances, region):
'''Reboot all the instances given by its ids'''
if not instances: return
conn = ec2_connect(region)
log("Rebooting instances {0}.".format(instances))
conn.reboot_instances(instances)
log("Done")
def wait_for_ssh(ips, port=22, skipAlive=True, requiredsuccess=3):
''' Wait for ssh service to appear on given hosts'''
log('Waiting for SSH on following hosts: {0}'.format(ips))
for ip in ips:
if not skipAlive or not ssh_live(ip, port):
log('Waiting for SSH on instance {0}...'.format(ip))
count = 0
while count < requiredsuccess:
if ssh_live(ip, port):
count += 1
else:
count = 0
time.sleep(1)
h2o_cmd.dot()
def dump_hosts_config(ec2_config, reservation, filename=DEFAULT_HOSTS_FILENAME, save=True, h2o_per_host=1):
if not filename: filename=DEFAULT_HOSTS_FILENAME
cfg = {}
f = find_file(ec2_config['aws_credentials'])
if f: cfg['aws_credentials'] = f
else: warn_file_miss(ec2_config['aws_credentials'])
f = find_file(ec2_config['pem'])
if f: cfg['key_filename'] = f
else: warn_file_miss(ec2_config['key_filename'])
f = find_file(ec2_config['hdfs_config'])
if f: cfg['hdfs_config'] = f
else: warn_file_miss(ec2_config['hdfs_config'])
cfg['username'] = ec2_config['username']
cfg['use_flatfile'] = True
cfg['h2o_per_host'] = h2o_per_host
cfg['java_heap_GB'] = MEMORY_MAPPING[ec2_config['instance_type']]['xmx']
cfg['java_extra_args'] = '' # No default Java arguments '-XX:MaxDirectMemorySize=1g'
cfg['base_port'] = 54321
cfg['ip'] = [ i.private_ip_address for i in reservation.instances ]
cfg['ec2_instances'] = [ { 'id': i.id, 'private_ip_address': i.private_ip_address, 'public_ip_address': i.ip_address, 'public_dns_name': i.public_dns_name } for i in reservation.instances ]
cfg['ec2_reservation_id'] = reservation.id
cfg['ec2_region'] = ec2_config['region']
# cfg['redirect_import_folder_to_s3_path'] = True
# New! we can redirect import folder to s3n thru hdfs, now (ec2)
# cfg['redirect_import_folder_to_s3n_path'] = True
# kbn 9/28/14..change it back to s3 to see what breaks
cfg['redirect_import_folder_to_s3_path'] = True
# put ssh commands into comments
cmds = get_ssh_commands(ec2_config, reservation)
idx = 1
for cmd in cmds:
cfg['ec2_comment_ssh_{0}'.format(idx)] = cmd
idx += 1
if save:
# save config
filename = filename.format(reservation.id)
with open(filename, 'w+') as f:
f.write(json.dumps(cfg, indent=4))
log("Host config dumped into {0}".format(filename))
log("To terminate instances call:")
log("\033[93mpython ec2_cmd.py terminate --hosts {0}\033[0m".format(filename))
log("To start H2O cloud call:")
log("\033[93mpython ec2_cmd.py start_h2o --hosts {0}\033[0m".format(filename))
log("To watch cloud in browser follow address:")
log(" http://{0}:{1}".format(reservation.instances[0].public_dns_name, cfg['base_port']))
return (cfg, filename)
def get_ssh_commands(ec2_config, reservation, ssh_options=""):
cmds = []
if not ssh_options: ssh_options = ""
for i in reservation.instances:
cmds.append( "ssh -i ~/.ec2/keys/mrjenkins_test.pem {1} ubuntu@{0}".format(i.private_ip_address,ssh_options) )
return cmds
def dump_ssh_commands(ec2_config, reservation):
cmds = get_ssh_commands(ec2_config, reservation)
for cmd in cmds:
print cmd
# for cleaning /tmp after it becomes full, or any one string command (can separate with semicolon)
def execute_using_ssh_commands(ec2_config, reservation, command_string='df'):
if not command_string: log("Nothing to execute. Exiting...")
cmds = get_ssh_commands(ec2_config, reservation, ADVANCED_SSH_OPTIONS)
for cmd in cmds:
c = cmd + " '" + command_string + "'"
print "\n"+c
ret,out = commands.getstatusoutput(c)
print out
def load_ec2_region(region):
for r in DEFAULT_EC2_INSTANCE_CONFIGS:
if r == region:
return region
raise Exception('\033[91m[ec2] Unsupported EC2 region: {0}. The available regions are: {1}\033[0m'.format(region, [r for r in DEFAULT_EC2_INSTANCE_CONFIGS ]))
def load_ec2_config(config_file, region, instance_type=None, image_id=None):
if config_file:
f = find_file(config_file)
with open(f, 'rb') as fp:
ec2_cfg = json.load(fp)
else:
ec2_cfg = {}
for k,v in DEFAULT_EC2_INSTANCE_CONFIGS[region].items():
ec2_cfg.setdefault(k, v)
if instance_type: ec2_cfg['instance_type'] = instance_type
if image_id : ec2_cfg['image_id' ] = image_id
return ec2_cfg
def load_ec2_reservation(reservation, region):
conn = ec2_connect(region)
lr = [ r for r in conn.get_all_instances() if r.id == reservation ]
if not lr: raise Exception('Reservation id {0} not found !'.format(reservation))
return lr[0]
def load_hosts_config(config_file):
f = find_file(config_file)
with open(f, 'rb') as fp:
host_cfg = json.load(fp)
return host_cfg
def log(msg):
print "\033[92m[ec2] \033[0m", msg
def warn(msg):
print "\033[92m[ec2] \033[0m \033[91m{0}\033[0m".format(msg)
def warn_file_miss(f):
warn("File {0} is missing! Please update the generated config manually.".format(f))
def invoke_hosts_action(action, hosts_config, args, ec2_reservation=None):
ids = [ inst['id'] for inst in hosts_config['ec2_instances'] ]
ips = [ inst['private_ip_address'] for inst in hosts_config['ec2_instances'] ]
region = hosts_config['ec2_region']
if (action == 'terminate'):
terminate_instances(ids, region)
elif (action == 'stop'):
stop_instances(ids, region)
elif (action == 'reboot'):
reboot_instances(ids, region)
wait_for_ssh(ips, skipAlive=False, requiredsuccess=10)
elif (action == 'start'):
start_instances(ids, region)
# FIXME after start instances receive new IPs: wait_for_ssh(ips)
elif (action == 'distribute_h2o'):
pass
elif (action == 'start_h2o'):
try:
h2o.config_json = args.hosts
log("Starting H2O cloud...")
h2o_hosts.build_cloud_with_hosts(timeoutSecs=120, retryDelaySecs=5)
h2o.touch_cloud()
log("Cloud started. Let's roll!")
log("You can start for example here \033[93mhttp://{0}:{1}\033[0m".format(hosts_config['ec2_instances'][0]['public_dns_name'],hosts_config['base_port']))
if args.timeout:
log("Cloud will shutdown after {0} seconds or use Ctrl+C to shutdown it.".format(args.timeout))
time.sleep(args.timeout)
else:
log("To kill the cloud please use Ctrl+C as usual.")
while (True): time.sleep(3600)
except:
print traceback.format_exc()
finally:
log("Goodbye H2O cloud...")
h2o.tear_down_cloud()
log("Cloud is gone.")
elif (action == 'stop_h2o'):
pass
elif (action == 'clean_tmp'):
execute_using_ssh_commands(hosts_config, ec2_reservation, command_string='sudo rm -rf /tmp/*; df')
elif (action == 'nexec'):
execute_using_ssh_commands(hosts_config, ec2_reservation, command_string=args.cmd)
def report_reservations(region, reservation_id=None):
conn = ec2_connect(region)
reservations = conn.get_all_instances()
if reservation_id: reservations = [i for i in reservations if i.id == reservation_id ]
log('Reservations:')
for r in reservations: report_reservation(r); log('')
def report_reservation(r):
log(' Reservation : {0}'.format(r.id))
log(' Instances : {0}'.format(len(r.instances)))
for i in r.instances:
log(' [{0} : {4}] {5} {1}/{2}/{3} {6}'.format(i.id, i.public_dns_name, i.ip_address, i.private_ip_address,i.instance_type, format_state(i.state), format_name(i.tags)))
def format_state(state):
if state == 'stopped': return '\033[093mSTOPPED\033[0m'
if state == 'running': return '\033[092mRUNNING\033[0m'
if state == 'terminated': return '\033[090mTERMINATED\033[0m'
return state.upper()
def format_name(tags):
if 'Name' in tags: return '\033[91m<{0}>\033[0m'.format(tags['Name'])
else: return '\033[94m<NONAME>\033[0m'
def merge_reservations(reservations):
pass
def create_tags(**kwargs):
tags = { }
for key,value in kwargs.iteritems():
tags[key] = value
return tags
def main():
parser = argparse.ArgumentParser(description='H2O EC2 instances launcher')
parser.add_argument('action', choices=['help', 'demo', 'create', 'terminate', 'stop', 'reboot', 'start', 'distribute_h2o', 'start_h2o', 'show_defaults', 'dump_reservation', 'show_reservations', 'clean_tmp','nexec'], help='EC2 instances action!')
parser.add_argument('-c', '--config', help='Configuration file to configure NEW EC2 instances (if not specified default is used - see "show_defaults")', type=str, default=None)
parser.add_argument('-i', '--instances', help='Number of instances to launch', type=int, default=DEFAULT_NUMBER_OF_INSTANCES)
parser.add_argument('-H', '--hosts', help='Hosts file describing existing "EXISTING" EC2 instances ', type=str, default=None)
parser.add_argument('-r', '--region', help='Specifies target create region', type=str, default=DEFAULT_REGION)
parser.add_argument('--reservation', help='Reservation ID, for example "r-1824ec65"', type=str, default=None)
parser.add_argument('--name', help='Name for launched instances', type=str, default=DEFAULT_INSTANCE_NAME)
parser.add_argument('--timeout', help='Timeout in seconds.', type=int, default=None)
parser.add_argument('--instance_type', help='Enfore a type of EC2 to launch (e.g., m2.2xlarge).', type=str, default=None)
parser.add_argument('--cmd', help='Shell command to be executed by nexec.', type=str, default=None)
parser.add_argument('--image_id', help='Override defautl image_id', type=str, default=None)
parser.add_argument('--h2o_per_host', help='Number of JVM launched per node', type=int, default=1)
args = parser.parse_args()
ec2_region = load_ec2_region(args.region)
if (args.action == 'help'):
parser.print_help()
elif (args.action == 'create' or args.action == 'demo'):
ec2_config = load_ec2_config(args.config, ec2_region, args.instance_type, args.image_id)
tags = create_tags(Name=args.name)
log("EC2 region : {0}".format(ec2_region))
log("EC2 itype : {0}".format(ec2_config['instance_type']))
log("EC2 ami : {0}".format(ec2_config['image_id']))
log("EC2 config : {0}".format(ec2_config))
log("Instances : {0}".format(args.instances))
log("Tags : {0}".format(tags))
reservation = run_instances(args.instances, ec2_config, ec2_region, tags=tags)
hosts_cfg, filename = dump_hosts_config(ec2_config, reservation, filename=args.hosts, h2o_per_host=args.h2o_per_host)
dump_ssh_commands(ec2_config, reservation)
if (args.action == 'demo'):
args.hosts = filename
try:
invoke_hosts_action('start_h2o', hosts_cfg, args)
finally:
invoke_hosts_action('terminate', hosts_cfg, args)
elif (args.action == 'show_defaults'):
print
print "\033[92mConfig\033[0m : {0}".format(json.dumps(DEFAULT_EC2_INSTANCE_CONFIGS,indent=2))
print "\033[92mInstances\033[0m : {0}".format(DEFAULT_NUMBER_OF_INSTANCES)
print "\033[92mSupported regions\033[0m : {0}".format( [ i for i in DEFAULT_EC2_INSTANCE_CONFIGS ] )
print
elif (args.action == 'merge_reservations'):
merge_reservations(args.reservations, args.region)
elif (args.action == 'dump_reservation'):
ec2_config = load_ec2_config(args.config, ec2_region)
ec2_reservation = load_ec2_reservation(args.reservation, ec2_region)
dump_hosts_config(ec2_config, ec2_reservation, filename=args.hosts)
elif (args.action == 'show_reservations'):
report_reservations(args.region, args.reservation)
else:
if args.hosts:
hosts_config = load_hosts_config(args.hosts)
if hosts_config['ec2_reservation_id']: ec2_reservation = load_ec2_reservation(hosts_config['ec2_reservation_id'], ec2_region)
else: ec2_reservation = None
elif args.reservation: # TODO allows for specifying multiple reservations and merge them
ec2_config = load_ec2_config(args.config, ec2_region)
ec2_reservation = load_ec2_reservation(args.reservation, ec2_region)
hosts_config,_ = dump_hosts_config(ec2_config, ec2_reservation, save=False)
invoke_hosts_action(args.action, hosts_config, args, ec2_reservation)
if (args.action == 'terminate' and args.hosts):
log("Deleting {0} host file.".format(args.hosts))
os.remove(args.hosts)
if __name__ == '__main__':
main()
| []
| []
| [
"USER",
"AWS_ACCESS_KEY_ID",
"AWS_SECRET_ACCESS_KEY"
]
| [] | ["USER", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"] | python | 3 | 0 | |
vendor/github.com/bugsnag/bugsnag-go/tests/fixtures/negroni.go | package main
import (
"github.com/bugsnag/bugsnag-go"
"github.com/bugsnag/bugsnag-go/negroni"
"github.com/urfave/negroni"
"net/http"
"os"
)
func main() {
errorReporterConfig := bugsnag.Configuration{
APIKey: "166f5ad3590596f9aa8d601ea89af845",
Endpoint: os.Getenv("BUGSNAG_ENDPOINT"),
}
if os.Getenv("BUGSNAG_TEST_VARIANT") == "beforenotify" {
bugsnag.OnBeforeNotify(func(event *bugsnag.Event, config *bugsnag.Configuration) error {
event.Severity = bugsnag.SeverityInfo
return nil
})
}
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(200)
w.Write([]byte("OK\n"))
var a struct{}
crash(a)
})
n := negroni.New()
n.Use(negroni.NewRecovery())
n.Use(bugsnagnegroni.AutoNotify(errorReporterConfig))
n.UseHandler(mux)
http.ListenAndServe(":9078", n)
}
func crash(a interface{}) string {
return a.(string)
}
| [
"\"BUGSNAG_ENDPOINT\"",
"\"BUGSNAG_TEST_VARIANT\""
]
| []
| [
"BUGSNAG_ENDPOINT",
"BUGSNAG_TEST_VARIANT"
]
| [] | ["BUGSNAG_ENDPOINT", "BUGSNAG_TEST_VARIANT"] | go | 2 | 0 | |
auth/src/__init__.py | import os
from common import service
# Initialize modules
import roles # noqa
import session # noqa
if __name__ == "__main__":
service.run(workers=int(os.getenv("WORKERS", "2")))
| []
| []
| [
"WORKERS"
]
| [] | ["WORKERS"] | python | 1 | 0 | |
manage.py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'afan.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 | |
example/main.go | package main
import (
"log"
"os"
"time"
"github.com/microcmsio/microcms-go-sdk"
)
type Blog struct {
ID *string `json:"id,omitempty"`
CreatedAt *time.Time `json:"createdAt,omitempty"`
UpdatedAt *time.Time `json:"updatedAt,omitempty"`
RevisedAt *time.Time `json:"revisedAt,omitempty"`
PublishedAt *time.Time `json:"publishedAt,omitempty"`
Title string `json:"title,omitempty"`
Contents string `json:"contents,omitempty"`
}
type BlogList struct {
Contents []Blog `json:"contents"`
TotalCount int `json:"totalCount"`
Offset int `json:"offset"`
Limit int `json:"limit"`
}
func main() {
serviceDomain := os.Getenv("YOUR_DOMAIN")
apiKey := os.Getenv("YOUR_API_KEY")
client := microcms.New(serviceDomain, apiKey)
var blogList BlogList
if err := client.List(
microcms.ListParams{
Endpoint: "blog",
Limit: 100,
Offset: 1,
Orders: []string{"updatedAt"},
Q: "Hello",
Fields: []string{"id", "title"},
Filters: "publishedAt[greater_than]2021-01-01",
},
&blogList,
); err != nil {
panic(err)
}
log.Printf("%+v", blogList)
var blog Blog
if err := client.Get(
microcms.GetParams{
Endpoint: "blog",
ContentID: "my-content-id",
},
&blog,
); err != nil {
panic(err)
}
log.Printf("%+v", blog)
postResult, err := client.Create(microcms.CreateParams{
Endpoint: "blog",
Content: Blog{
Title: "my-content",
Contents: "Hello, POST request!",
},
})
if err != nil {
panic(err)
}
log.Printf("%+v", postResult)
putResult, err := client.Create(
microcms.CreateParams{
Endpoint: "blog",
ContentID: "my-content-id",
Content: Blog{
Title: "my-content",
Contents: "Hello, PUT request!",
},
})
if err != nil {
panic(err)
}
log.Printf("%+v", putResult)
draftResult, err := client.Create(microcms.CreateParams{
Endpoint: "blog",
ContentID: "draft-content-id",
Status: microcms.StatusDraft,
Content: Blog{
Title: "draft-content",
Contents: "Hello, draft content!",
},
})
if err != nil {
panic(err)
}
log.Printf("%+v", draftResult)
updateResult, err := client.Update(microcms.UpdateParams{
Endpoint: "blog",
ContentID: postResult.ID,
Content: Blog{
Contents: "Hello, new content!",
},
})
if err != nil {
panic(err)
}
log.Printf("%+v", updateResult)
if err := client.Delete(microcms.DeleteParams{
Endpoint: "blog",
ContentID: "my-content-id",
}); err != nil {
panic(err)
}
}
| [
"\"YOUR_DOMAIN\"",
"\"YOUR_API_KEY\""
]
| []
| [
"YOUR_API_KEY",
"YOUR_DOMAIN"
]
| [] | ["YOUR_API_KEY", "YOUR_DOMAIN"] | go | 2 | 0 | |
recipes/libtool/all/test_package/conanfile.py | from conans import AutoToolsBuildEnvironment, CMake, ConanFile, tools
from contextlib import contextmanager
import glob
import os
import shutil
class TestPackageConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "cmake"
test_type = "explicit"
short_paths = True
@property
def _settings_build(self):
return getattr(self, "settings_build", self.settings)
def requirements(self):
self.requires(self.tested_reference_str)
def build_requirements(self):
self.build_requires(self.tested_reference_str)
if self._settings_build.os == "Windows" and not tools.get_env("CONAN_BASH_PATH"):
self.build_requires("msys2/cci.latest")
@contextmanager
def _build_context(self):
if self.settings.compiler == "Visual Studio":
with tools.vcvars(self.settings):
with tools.environment_append({
"CC": "{} cl -nologo".format(tools.unix_path(self.deps_user_info["automake"].compile)),
"CXX": "{} cl -nologo".format(tools.unix_path(self.deps_user_info["automake"].compile)),
"AR": "{} lib".format(tools.unix_path(self.deps_user_info["automake"].ar_lib)),
"LD": "link",
}):
yield
else:
yield
@property
def _package_folder(self):
return os.path.join(self.build_folder, "package")
def _build_autotools(self):
""" Test autotools integration """
# Copy autotools directory to build folder
shutil.copytree(os.path.join(self.source_folder, "autotools"), os.path.join(self.build_folder, "autotools"))
with tools.chdir("autotools"):
self.run("{} --install --verbose -Wall".format(os.environ["AUTORECONF"]), win_bash=tools.os_info.is_windows)
tools.mkdir(self._package_folder)
conf_args = [
"--prefix={}".format(tools.unix_path(self._package_folder)),
"--enable-shared", "--enable-static",
]
os.mkdir("bin_autotools")
with tools.chdir("bin_autotools"):
with self._build_context():
autotools = AutoToolsBuildEnvironment(self, win_bash=tools.os_info.is_windows)
autotools.libs = []
autotools.configure(args=conf_args, configure_dir=os.path.join(self.build_folder, "autotools"))
autotools.make(args=["V=1"])
autotools.install()
def _test_autotools(self):
assert os.path.isdir(os.path.join(self._package_folder, "bin"))
assert os.path.isfile(os.path.join(self._package_folder, "include", "lib.h"))
assert os.path.isdir(os.path.join(self._package_folder, "lib"))
if not tools.cross_building(self):
self.run(os.path.join(self._package_folder, "bin", "test_package"), run_environment=True)
def _build_ltdl(self):
""" Build library using ltdl library """
cmake = CMake(self)
cmake.configure(source_folder="ltdl")
cmake.build()
def _test_ltdl(self):
""" Test library using ltdl library"""
lib_suffix = {
"Linux": "so",
"FreeBSD": "so",
"Macos": "dylib",
"Windows": "dll",
}[str(self.settings.os)]
if not tools.cross_building(self):
bin_path = os.path.join("bin", "test_package")
libdir = "bin" if self.settings.os == "Windows" else "lib"
lib_path = os.path.join(libdir, "liba.{}".format(lib_suffix))
self.run("{} {}".format(bin_path, lib_path), run_environment=True)
def _build_static_lib_in_shared(self):
""" Build shared library using libtool (while linking to a static library) """
# Copy static-in-shared directory to build folder
autotools_folder = os.path.join(self.build_folder, "sis")
shutil.copytree(os.path.join(self.source_folder, "sis"), autotools_folder)
install_prefix = os.path.join(autotools_folder, "prefix")
# Build static library using CMake
cmake = CMake(self)
cmake.definitions["CMAKE_INSTALL_PREFIX"] = install_prefix
cmake.configure(source_folder=autotools_folder, build_folder=os.path.join(autotools_folder, "cmake_build"))
cmake.build()
cmake.install()
# Copy autotools directory to build folder
with tools.chdir(autotools_folder):
self.run("{} -ifv -Wall".format(os.environ["AUTORECONF"]), win_bash=tools.os_info.is_windows)
with tools.chdir(autotools_folder):
conf_args = [
"--enable-shared",
"--disable-static",
"--prefix={}".format(tools.unix_path(os.path.join(install_prefix))),
]
with self._build_context():
autotools = AutoToolsBuildEnvironment(self, win_bash=tools.os_info.is_windows)
autotools.libs = []
autotools.link_flags.append("-L{}".format(tools.unix_path(os.path.join(install_prefix, "lib"))))
autotools.configure(args=conf_args, configure_dir=autotools_folder)
autotools.make(args=["V=1"])
autotools.install()
def _test_static_lib_in_shared(self):
""" Test existence of shared library """
install_prefix = os.path.join(self.build_folder, "sis", "prefix")
with tools.chdir(install_prefix):
if self.settings.os == "Windows":
assert len(list(glob.glob(os.path.join("bin", "*.dll")))) > 0
elif tools.is_apple_os(self.settings.os):
assert len(list(glob.glob(os.path.join("lib", "*.dylib")))) > 0
else:
assert len(list(glob.glob(os.path.join("lib", "*.so")))) > 0
def build(self):
self._build_ltdl()
if not tools.cross_building(self):
self._build_autotools()
self._build_static_lib_in_shared()
def test(self):
self._test_ltdl()
if not tools.cross_building(self):
self._test_autotools()
self._test_static_lib_in_shared()
| []
| []
| [
"AUTORECONF"
]
| [] | ["AUTORECONF"] | python | 1 | 0 | |
vendor/github.com/skuid/helm-value-store/store/types.go | package store
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/ghodss/yaml"
"github.com/kubernetes/helm/cmd/helm/downloader"
"k8s.io/helm/cmd/helm/helmpath"
"k8s.io/helm/pkg/helm"
rls "k8s.io/helm/pkg/proto/hapi/services"
"k8s.io/helm/pkg/strvals"
)
var client *helm.Client
func init() {
client = helm.NewClient(helm.Host(os.Getenv("TILLER_HOST")))
}
// A Release contains metadata about a release of a healm chart
type Release struct {
UniqueID string `json:"unique_id"`
Labels map[string]string `json:"labels"`
Name string `json:"name"`
Chart string `json:"chart"`
Namespace string `json:"namespace"`
Version string `json:"version"`
Values string `json:"values"`
}
func (r Release) String() string {
return fmt.Sprintf("%s\t%s\t%s\t%s", r.UniqueID, r.Name, r.Chart, r.Version)
}
// MatchesSelector checks if the specified release contains all the key/value pairs in it's Labels
func (r Release) MatchesSelector(selector map[string]string) bool {
if (r.Labels == nil || len(r.Labels) == 0) && len(selector) > 0 {
return false
}
for selectorK, selectorV := range selector {
labelValue, ok := r.Labels[selectorK]
if !ok || (strings.Compare(labelValue, selectorV) != 0 && len(selectorV) > 0) {
return false
}
}
return true
}
// ReleaseUnmarshaler is an interface for unmarshaling a release
type ReleaseUnmarshaler interface {
UnmarshalRelease(Release) error
}
// ReleaseMarshaler is an interface for marshaling a release
type ReleaseMarshaler interface {
MarshalRelease() (*Release, error)
}
// Upgrade sends an update to an existing release in a cluster
func (r Release) Upgrade(chartLocation string, dryRun bool, timeout int64) (*rls.UpdateReleaseResponse, error) {
return client.UpdateRelease(
r.Name,
chartLocation,
helm.UpdateValueOverrides([]byte(r.Values)),
helm.UpgradeDryRun(dryRun),
helm.UpgradeTimeout(timeout),
)
}
// Install creates an new release in a cluster
func (r Release) Install(chartLocation string, dryRun bool, timeout int64) (*rls.InstallReleaseResponse, error) {
return client.InstallRelease(
chartLocation,
r.Namespace,
helm.ValueOverrides([]byte(r.Values)),
helm.ReleaseName(r.Name),
helm.InstallDryRun(dryRun),
helm.InstallTimeout(timeout),
)
}
// Download gets the release from an index server
func (r Release) Download() (string, error) {
dl := downloader.ChartDownloader{
HelmHome: helmpath.Home(os.Getenv("HELM_HOME")),
Out: os.Stdout,
}
tmpDir, err := ioutil.TempDir("", "")
if err != nil {
return "", err
}
filename, _, err := dl.DownloadTo(r.Chart, r.Version, tmpDir)
if err == nil {
lname, err := filepath.Abs(filename)
if err != nil {
return filename, err
}
return lname, nil
}
return filename, fmt.Errorf("file %q not found", r.Chart)
}
// Get the release content from Tiller
func (r Release) Get() (*rls.GetReleaseContentResponse, error) {
return client.ReleaseContent(r.Name)
}
// MergeValues parses string values and then merges them into the
// existing Values for a release.
// Adopted from kubernetes/helm/cmd/helm/install.go
func (r *Release) MergeValues(values []string) error {
base := map[string]interface{}{}
if err := yaml.Unmarshal([]byte(r.Values), &base); err != nil {
return fmt.Errorf("Error parsing values for release %s: %s", r.Name, err)
}
// User specified a value via --set
for _, value := range values {
if err := strvals.ParseInto(value, base); err != nil {
return fmt.Errorf("failed parsing --set data: %s", err)
}
}
mergedValues, err := yaml.Marshal(base)
if err != nil {
return fmt.Errorf("Error parsing merged values for release %s: %s", r.Name, err)
}
r.Values = string(mergedValues)
return nil
}
// Releases is a slice of release
type Releases []Release
// ReleasesUnmarshaler is an interface for unmarshaling slices of release
type ReleasesUnmarshaler interface {
UnmarshalReleases(Releases) error
}
// ReleasesMarshaler is an interface for marshaling slices of release
type ReleasesMarshaler interface {
MarshalReleases() (Releases, error)
}
// A ReleaseStore is a backend that stores releases
type ReleaseStore interface {
Get(uniqueID string) (*Release, error)
Put(Release) error
Delete(uniqueID string) error
List(selector map[string]string) (Releases, error)
Load(Releases) error
Setup() error
}
| [
"\"TILLER_HOST\"",
"\"HELM_HOME\""
]
| []
| [
"HELM_HOME",
"TILLER_HOST"
]
| [] | ["HELM_HOME", "TILLER_HOST"] | go | 2 | 0 | |
tests/unit/gapic/compute_v1/test_instance_group_managers.py | # -*- coding: utf-8 -*-
# Copyright 2020 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
import mock
import packaging.version
import grpc
from grpc.experimental import aio
import math
import pytest
from proto.marshal.rules.dates import DurationRule, TimestampRule
from requests import Response
from requests.sessions import Session
from google.api_core import client_options
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import grpc_helpers
from google.api_core import grpc_helpers_async
from google.auth import credentials as ga_credentials
from google.auth.exceptions import MutualTLSChannelError
from google.cloud.compute_v1.services.instance_group_managers import (
InstanceGroupManagersClient,
)
from google.cloud.compute_v1.services.instance_group_managers import pagers
from google.cloud.compute_v1.services.instance_group_managers import transports
from google.cloud.compute_v1.services.instance_group_managers.transports.base import (
_GOOGLE_AUTH_VERSION,
)
from google.cloud.compute_v1.types import compute
from google.oauth2 import service_account
import google.auth
# TODO(busunkim): Once google-auth >= 1.25.0 is required transitively
# through google-api-core:
# - Delete the auth "less than" test cases
# - Delete these pytest markers (Make the "greater than or equal to" tests the default).
requires_google_auth_lt_1_25_0 = pytest.mark.skipif(
packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"),
reason="This test requires google-auth < 1.25.0",
)
requires_google_auth_gte_1_25_0 = pytest.mark.skipif(
packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"),
reason="This test requires google-auth >= 1.25.0",
)
def client_cert_source_callback():
return b"cert bytes", b"key bytes"
# If default endpoint is localhost, then default mtls endpoint will be the same.
# This method modifies the default endpoint so the client can produce a different
# mtls endpoint for endpoint testing purposes.
def modify_default_endpoint(client):
return (
"foo.googleapis.com"
if ("localhost" in client.DEFAULT_ENDPOINT)
else client.DEFAULT_ENDPOINT
)
def test__get_default_mtls_endpoint():
api_endpoint = "example.googleapis.com"
api_mtls_endpoint = "example.mtls.googleapis.com"
sandbox_endpoint = "example.sandbox.googleapis.com"
sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com"
non_googleapi = "api.example.com"
assert InstanceGroupManagersClient._get_default_mtls_endpoint(None) is None
assert (
InstanceGroupManagersClient._get_default_mtls_endpoint(api_endpoint)
== api_mtls_endpoint
)
assert (
InstanceGroupManagersClient._get_default_mtls_endpoint(api_mtls_endpoint)
== api_mtls_endpoint
)
assert (
InstanceGroupManagersClient._get_default_mtls_endpoint(sandbox_endpoint)
== sandbox_mtls_endpoint
)
assert (
InstanceGroupManagersClient._get_default_mtls_endpoint(sandbox_mtls_endpoint)
== sandbox_mtls_endpoint
)
assert (
InstanceGroupManagersClient._get_default_mtls_endpoint(non_googleapi)
== non_googleapi
)
@pytest.mark.parametrize("client_class", [InstanceGroupManagersClient,])
def test_instance_group_managers_client_from_service_account_info(client_class):
creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_info"
) as factory:
factory.return_value = creds
info = {"valid": True}
client = client_class.from_service_account_info(info)
assert client.transport._credentials == creds
assert isinstance(client, client_class)
assert client.transport._host == "compute.googleapis.com:443"
@pytest.mark.parametrize("client_class", [InstanceGroupManagersClient,])
def test_instance_group_managers_client_from_service_account_file(client_class):
creds = ga_credentials.AnonymousCredentials()
with mock.patch.object(
service_account.Credentials, "from_service_account_file"
) as factory:
factory.return_value = creds
client = client_class.from_service_account_file("dummy/file/path.json")
assert client.transport._credentials == creds
assert isinstance(client, client_class)
client = client_class.from_service_account_json("dummy/file/path.json")
assert client.transport._credentials == creds
assert isinstance(client, client_class)
assert client.transport._host == "compute.googleapis.com:443"
def test_instance_group_managers_client_get_transport_class():
transport = InstanceGroupManagersClient.get_transport_class()
available_transports = [
transports.InstanceGroupManagersRestTransport,
]
assert transport in available_transports
transport = InstanceGroupManagersClient.get_transport_class("rest")
assert transport == transports.InstanceGroupManagersRestTransport
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
[
(
InstanceGroupManagersClient,
transports.InstanceGroupManagersRestTransport,
"rest",
),
],
)
@mock.patch.object(
InstanceGroupManagersClient,
"DEFAULT_ENDPOINT",
modify_default_endpoint(InstanceGroupManagersClient),
)
def test_instance_group_managers_client_client_options(
client_class, transport_class, transport_name
):
# Check that if channel is provided we won't create a new one.
with mock.patch.object(InstanceGroupManagersClient, "get_transport_class") as gtc:
transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
client = client_class(transport=transport)
gtc.assert_not_called()
# Check that if channel is provided via str we will create a new one.
with mock.patch.object(InstanceGroupManagersClient, "get_transport_class") as gtc:
client = client_class(transport=transport_name)
gtc.assert_called()
# Check the case api_endpoint is provided.
options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(client_options=options)
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host="squid.clam.whelk",
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
# "never".
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
# "always".
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_MTLS_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
# unsupported value.
with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
with pytest.raises(MutualTLSChannelError):
client = client_class()
# Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value.
with mock.patch.dict(
os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}
):
with pytest.raises(ValueError):
client = client_class()
# Check the case quota_project_id is provided
options = client_options.ClientOptions(quota_project_id="octopus")
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(client_options=options)
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id="octopus",
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@pytest.mark.parametrize(
"client_class,transport_class,transport_name,use_client_cert_env",
[
(
InstanceGroupManagersClient,
transports.InstanceGroupManagersRestTransport,
"rest",
"true",
),
(
InstanceGroupManagersClient,
transports.InstanceGroupManagersRestTransport,
"rest",
"false",
),
],
)
@mock.patch.object(
InstanceGroupManagersClient,
"DEFAULT_ENDPOINT",
modify_default_endpoint(InstanceGroupManagersClient),
)
@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
def test_instance_group_managers_client_mtls_env_auto(
client_class, transport_class, transport_name, use_client_cert_env
):
# This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
# mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
# Check the case client_cert_source is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
with mock.patch.dict(
os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
):
options = client_options.ClientOptions(
client_cert_source=client_cert_source_callback
)
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(client_options=options)
if use_client_cert_env == "false":
expected_client_cert_source = None
expected_host = client.DEFAULT_ENDPOINT
else:
expected_client_cert_source = client_cert_source_callback
expected_host = client.DEFAULT_MTLS_ENDPOINT
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=expected_host,
scopes=None,
client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case ADC client cert is provided. Whether client cert is used depends on
# GOOGLE_API_USE_CLIENT_CERTIFICATE value.
with mock.patch.dict(
os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
"google.auth.transport.mtls.has_default_client_cert_source",
return_value=True,
):
with mock.patch(
"google.auth.transport.mtls.default_client_cert_source",
return_value=client_cert_source_callback,
):
if use_client_cert_env == "false":
expected_host = client.DEFAULT_ENDPOINT
expected_client_cert_source = None
else:
expected_host = client.DEFAULT_MTLS_ENDPOINT
expected_client_cert_source = client_cert_source_callback
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=expected_host,
scopes=None,
client_cert_source_for_mtls=expected_client_cert_source,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
# Check the case client_cert_source and ADC client cert are not provided.
with mock.patch.dict(
os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
):
with mock.patch.object(transport_class, "__init__") as patched:
with mock.patch(
"google.auth.transport.mtls.has_default_client_cert_source",
return_value=False,
):
patched.return_value = None
client = client_class()
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
[
(
InstanceGroupManagersClient,
transports.InstanceGroupManagersRestTransport,
"rest",
),
],
)
def test_instance_group_managers_client_client_options_scopes(
client_class, transport_class, transport_name
):
# Check the case scopes are provided.
options = client_options.ClientOptions(scopes=["1", "2"],)
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(client_options=options)
patched.assert_called_once_with(
credentials=None,
credentials_file=None,
host=client.DEFAULT_ENDPOINT,
scopes=["1", "2"],
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
@pytest.mark.parametrize(
"client_class,transport_class,transport_name",
[
(
InstanceGroupManagersClient,
transports.InstanceGroupManagersRestTransport,
"rest",
),
],
)
def test_instance_group_managers_client_client_options_credentials_file(
client_class, transport_class, transport_name
):
# Check the case credentials file is provided.
options = client_options.ClientOptions(credentials_file="credentials.json")
with mock.patch.object(transport_class, "__init__") as patched:
patched.return_value = None
client = client_class(client_options=options)
patched.assert_called_once_with(
credentials=None,
credentials_file="credentials.json",
host=client.DEFAULT_ENDPOINT,
scopes=None,
client_cert_source_for_mtls=None,
quota_project_id=None,
client_info=transports.base.DEFAULT_CLIENT_INFO,
)
def test_abandon_instances_rest(
transport: str = "rest",
request_type=compute.AbandonInstancesInstanceGroupManagerRequest,
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.abandon_instances(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_abandon_instances_rest_from_dict():
test_abandon_instances_rest(request_type=dict)
def test_abandon_instances_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
instance_group_managers_abandon_instances_request_resource = compute.InstanceGroupManagersAbandonInstancesRequest(
instances=["instances_value"]
)
client.abandon_instances(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_abandon_instances_request_resource=instance_group_managers_abandon_instances_request_resource,
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
assert compute.InstanceGroupManagersAbandonInstancesRequest.to_json(
instance_group_managers_abandon_instances_request_resource,
including_default_value_fields=False,
use_integers_for_enums=False,
) in http_call[1] + str(body)
def test_abandon_instances_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.abandon_instances(
compute.AbandonInstancesInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_abandon_instances_request_resource=compute.InstanceGroupManagersAbandonInstancesRequest(
instances=["instances_value"]
),
)
def test_aggregated_list_rest(
transport: str = "rest",
request_type=compute.AggregatedListInstanceGroupManagersRequest,
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.InstanceGroupManagerAggregatedList(
id="id_value",
items={
"key_value": compute.InstanceGroupManagersScopedList(
instance_group_managers=[
compute.InstanceGroupManager(
auto_healing_policies=[
compute.InstanceGroupManagerAutoHealingPolicy(
health_check="health_check_value"
)
]
)
]
)
},
kind="kind_value",
next_page_token="next_page_token_value",
self_link="self_link_value",
unreachables=["unreachables_value"],
warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED),
)
# Wrap the value into a proper Response obj
json_return_value = compute.InstanceGroupManagerAggregatedList.to_json(
return_value
)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.aggregated_list(request)
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.AggregatedListPager)
assert response.id == "id_value"
assert response.items == {
"key_value": compute.InstanceGroupManagersScopedList(
instance_group_managers=[
compute.InstanceGroupManager(
auto_healing_policies=[
compute.InstanceGroupManagerAutoHealingPolicy(
health_check="health_check_value"
)
]
)
]
)
}
assert response.kind == "kind_value"
assert response.next_page_token == "next_page_token_value"
assert response.self_link == "self_link_value"
assert response.unreachables == ["unreachables_value"]
assert response.warning == compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED)
def test_aggregated_list_rest_from_dict():
test_aggregated_list_rest(request_type=dict)
def test_aggregated_list_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.InstanceGroupManagerAggregatedList()
# Wrap the value into a proper Response obj
json_return_value = compute.InstanceGroupManagerAggregatedList.to_json(
return_value
)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.aggregated_list(project="project_value",)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
def test_aggregated_list_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.aggregated_list(
compute.AggregatedListInstanceGroupManagersRequest(),
project="project_value",
)
def test_aggregated_list_pager():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Set the response as a series of pages
response = (
compute.InstanceGroupManagerAggregatedList(
items={
"a": compute.InstanceGroupManagersScopedList(),
"b": compute.InstanceGroupManagersScopedList(),
"c": compute.InstanceGroupManagersScopedList(),
},
next_page_token="abc",
),
compute.InstanceGroupManagerAggregatedList(
items={}, next_page_token="def",
),
compute.InstanceGroupManagerAggregatedList(
items={"g": compute.InstanceGroupManagersScopedList(),},
next_page_token="ghi",
),
compute.InstanceGroupManagerAggregatedList(
items={
"h": compute.InstanceGroupManagersScopedList(),
"i": compute.InstanceGroupManagersScopedList(),
},
),
)
# Two responses for two calls
response = response + response
# Wrap the values into proper Response objs
response = tuple(
compute.InstanceGroupManagerAggregatedList.to_json(x) for x in response
)
return_values = tuple(Response() for i in response)
for return_val, response_val in zip(return_values, response):
return_val._content = response_val.encode("UTF-8")
return_val.status_code = 200
req.side_effect = return_values
metadata = ()
pager = client.aggregated_list(request={})
assert pager._metadata == metadata
assert isinstance(pager.get("a"), compute.InstanceGroupManagersScopedList)
assert pager.get("h") is None
results = list(pager)
assert len(results) == 6
assert all(isinstance(i, tuple) for i in results)
for result in results:
assert isinstance(result, tuple)
assert tuple(type(t) for t in result) == (
str,
compute.InstanceGroupManagersScopedList,
)
assert pager.get("a") is None
assert isinstance(pager.get("h"), compute.InstanceGroupManagersScopedList)
pages = list(client.aggregated_list(request={}).pages)
for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page_.raw_page.next_page_token == token
def test_apply_updates_to_instances_rest(
transport: str = "rest",
request_type=compute.ApplyUpdatesToInstancesInstanceGroupManagerRequest,
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.apply_updates_to_instances(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_apply_updates_to_instances_rest_from_dict():
test_apply_updates_to_instances_rest(request_type=dict)
def test_apply_updates_to_instances_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
instance_group_managers_apply_updates_request_resource = compute.InstanceGroupManagersApplyUpdatesRequest(
all_instances=True
)
client.apply_updates_to_instances(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_apply_updates_request_resource=instance_group_managers_apply_updates_request_resource,
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
assert compute.InstanceGroupManagersApplyUpdatesRequest.to_json(
instance_group_managers_apply_updates_request_resource,
including_default_value_fields=False,
use_integers_for_enums=False,
) in http_call[1] + str(body)
def test_apply_updates_to_instances_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.apply_updates_to_instances(
compute.ApplyUpdatesToInstancesInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_apply_updates_request_resource=compute.InstanceGroupManagersApplyUpdatesRequest(
all_instances=True
),
)
def test_create_instances_rest(
transport: str = "rest",
request_type=compute.CreateInstancesInstanceGroupManagerRequest,
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.create_instances(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_create_instances_rest_from_dict():
test_create_instances_rest(request_type=dict)
def test_create_instances_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
instance_group_managers_create_instances_request_resource = compute.InstanceGroupManagersCreateInstancesRequest(
instances=[compute.PerInstanceConfig(fingerprint="fingerprint_value")]
)
client.create_instances(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_create_instances_request_resource=instance_group_managers_create_instances_request_resource,
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
assert compute.InstanceGroupManagersCreateInstancesRequest.to_json(
instance_group_managers_create_instances_request_resource,
including_default_value_fields=False,
use_integers_for_enums=False,
) in http_call[1] + str(body)
def test_create_instances_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.create_instances(
compute.CreateInstancesInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_create_instances_request_resource=compute.InstanceGroupManagersCreateInstancesRequest(
instances=[compute.PerInstanceConfig(fingerprint="fingerprint_value")]
),
)
def test_delete_rest(
transport: str = "rest", request_type=compute.DeleteInstanceGroupManagerRequest
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.delete(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_delete_rest_from_dict():
test_delete_rest(request_type=dict)
def test_delete_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.delete(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
def test_delete_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.delete(
compute.DeleteInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
)
def test_delete_instances_rest(
transport: str = "rest",
request_type=compute.DeleteInstancesInstanceGroupManagerRequest,
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.delete_instances(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_delete_instances_rest_from_dict():
test_delete_instances_rest(request_type=dict)
def test_delete_instances_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
instance_group_managers_delete_instances_request_resource = compute.InstanceGroupManagersDeleteInstancesRequest(
instances=["instances_value"]
)
client.delete_instances(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_delete_instances_request_resource=instance_group_managers_delete_instances_request_resource,
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
assert compute.InstanceGroupManagersDeleteInstancesRequest.to_json(
instance_group_managers_delete_instances_request_resource,
including_default_value_fields=False,
use_integers_for_enums=False,
) in http_call[1] + str(body)
def test_delete_instances_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.delete_instances(
compute.DeleteInstancesInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_delete_instances_request_resource=compute.InstanceGroupManagersDeleteInstancesRequest(
instances=["instances_value"]
),
)
def test_delete_per_instance_configs_rest(
transport: str = "rest",
request_type=compute.DeletePerInstanceConfigsInstanceGroupManagerRequest,
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.delete_per_instance_configs(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_delete_per_instance_configs_rest_from_dict():
test_delete_per_instance_configs_rest(request_type=dict)
def test_delete_per_instance_configs_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
instance_group_managers_delete_per_instance_configs_req_resource = compute.InstanceGroupManagersDeletePerInstanceConfigsReq(
names=["names_value"]
)
client.delete_per_instance_configs(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_delete_per_instance_configs_req_resource=instance_group_managers_delete_per_instance_configs_req_resource,
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
assert compute.InstanceGroupManagersDeletePerInstanceConfigsReq.to_json(
instance_group_managers_delete_per_instance_configs_req_resource,
including_default_value_fields=False,
use_integers_for_enums=False,
) in http_call[1] + str(body)
def test_delete_per_instance_configs_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.delete_per_instance_configs(
compute.DeletePerInstanceConfigsInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_delete_per_instance_configs_req_resource=compute.InstanceGroupManagersDeletePerInstanceConfigsReq(
names=["names_value"]
),
)
def test_get_rest(
transport: str = "rest", request_type=compute.GetInstanceGroupManagerRequest
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.InstanceGroupManager(
auto_healing_policies=[
compute.InstanceGroupManagerAutoHealingPolicy(
health_check="health_check_value"
)
],
base_instance_name="base_instance_name_value",
creation_timestamp="creation_timestamp_value",
current_actions=compute.InstanceGroupManagerActionsSummary(abandoning=1041),
description="description_value",
distribution_policy=compute.DistributionPolicy(
target_shape=compute.DistributionPolicy.TargetShape.ANY
),
fingerprint="fingerprint_value",
id="id_value",
instance_group="instance_group_value",
instance_template="instance_template_value",
kind="kind_value",
name="name_value",
named_ports=[compute.NamedPort(name="name_value")],
region="region_value",
self_link="self_link_value",
stateful_policy=compute.StatefulPolicy(
preserved_state=compute.StatefulPolicyPreservedState(
disks={
"key_value": compute.StatefulPolicyPreservedStateDiskDevice(
auto_delete=compute.StatefulPolicyPreservedStateDiskDevice.AutoDelete.NEVER
)
}
)
),
status=compute.InstanceGroupManagerStatus(autoscaler="autoscaler_value"),
target_pools=["target_pools_value"],
target_size=1185,
update_policy=compute.InstanceGroupManagerUpdatePolicy(
instance_redistribution_type="instance_redistribution_type_value"
),
versions=[
compute.InstanceGroupManagerVersion(
instance_template="instance_template_value"
)
],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.InstanceGroupManager.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.get(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.InstanceGroupManager)
assert response.auto_healing_policies == [
compute.InstanceGroupManagerAutoHealingPolicy(health_check="health_check_value")
]
assert response.base_instance_name == "base_instance_name_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.current_actions == compute.InstanceGroupManagerActionsSummary(
abandoning=1041
)
assert response.description == "description_value"
assert response.distribution_policy == compute.DistributionPolicy(
target_shape=compute.DistributionPolicy.TargetShape.ANY
)
assert response.fingerprint == "fingerprint_value"
assert response.id == "id_value"
assert response.instance_group == "instance_group_value"
assert response.instance_template == "instance_template_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.named_ports == [compute.NamedPort(name="name_value")]
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.stateful_policy == compute.StatefulPolicy(
preserved_state=compute.StatefulPolicyPreservedState(
disks={
"key_value": compute.StatefulPolicyPreservedStateDiskDevice(
auto_delete=compute.StatefulPolicyPreservedStateDiskDevice.AutoDelete.NEVER
)
}
)
)
assert response.status == compute.InstanceGroupManagerStatus(
autoscaler="autoscaler_value"
)
assert response.target_pools == ["target_pools_value"]
assert response.target_size == 1185
assert response.update_policy == compute.InstanceGroupManagerUpdatePolicy(
instance_redistribution_type="instance_redistribution_type_value"
)
assert response.versions == [
compute.InstanceGroupManagerVersion(instance_template="instance_template_value")
]
assert response.zone == "zone_value"
def test_get_rest_from_dict():
test_get_rest(request_type=dict)
def test_get_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.InstanceGroupManager()
# Wrap the value into a proper Response obj
json_return_value = compute.InstanceGroupManager.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.get(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
def test_get_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.get(
compute.GetInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
)
def test_insert_rest(
transport: str = "rest", request_type=compute.InsertInstanceGroupManagerRequest
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.insert(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_insert_rest_from_dict():
test_insert_rest(request_type=dict)
def test_insert_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
instance_group_manager_resource = compute.InstanceGroupManager(
auto_healing_policies=[
compute.InstanceGroupManagerAutoHealingPolicy(
health_check="health_check_value"
)
]
)
client.insert(
project="project_value",
zone="zone_value",
instance_group_manager_resource=instance_group_manager_resource,
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert compute.InstanceGroupManager.to_json(
instance_group_manager_resource,
including_default_value_fields=False,
use_integers_for_enums=False,
) in http_call[1] + str(body)
def test_insert_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.insert(
compute.InsertInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager_resource=compute.InstanceGroupManager(
auto_healing_policies=[
compute.InstanceGroupManagerAutoHealingPolicy(
health_check="health_check_value"
)
]
),
)
def test_list_rest(
transport: str = "rest", request_type=compute.ListInstanceGroupManagersRequest
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.InstanceGroupManagerList(
id="id_value",
items=[
compute.InstanceGroupManager(
auto_healing_policies=[
compute.InstanceGroupManagerAutoHealingPolicy(
health_check="health_check_value"
)
]
)
],
kind="kind_value",
next_page_token="next_page_token_value",
self_link="self_link_value",
warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED),
)
# Wrap the value into a proper Response obj
json_return_value = compute.InstanceGroupManagerList.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.list(request)
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListPager)
assert response.id == "id_value"
assert response.items == [
compute.InstanceGroupManager(
auto_healing_policies=[
compute.InstanceGroupManagerAutoHealingPolicy(
health_check="health_check_value"
)
]
)
]
assert response.kind == "kind_value"
assert response.next_page_token == "next_page_token_value"
assert response.self_link == "self_link_value"
assert response.warning == compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED)
def test_list_rest_from_dict():
test_list_rest(request_type=dict)
def test_list_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.InstanceGroupManagerList()
# Wrap the value into a proper Response obj
json_return_value = compute.InstanceGroupManagerList.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list(
project="project_value", zone="zone_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
def test_list_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.list(
compute.ListInstanceGroupManagersRequest(),
project="project_value",
zone="zone_value",
)
def test_list_pager():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Set the response as a series of pages
response = (
compute.InstanceGroupManagerList(
items=[
compute.InstanceGroupManager(),
compute.InstanceGroupManager(),
compute.InstanceGroupManager(),
],
next_page_token="abc",
),
compute.InstanceGroupManagerList(items=[], next_page_token="def",),
compute.InstanceGroupManagerList(
items=[compute.InstanceGroupManager(),], next_page_token="ghi",
),
compute.InstanceGroupManagerList(
items=[compute.InstanceGroupManager(), compute.InstanceGroupManager(),],
),
)
# Two responses for two calls
response = response + response
# Wrap the values into proper Response objs
response = tuple(compute.InstanceGroupManagerList.to_json(x) for x in response)
return_values = tuple(Response() for i in response)
for return_val, response_val in zip(return_values, response):
return_val._content = response_val.encode("UTF-8")
return_val.status_code = 200
req.side_effect = return_values
metadata = ()
pager = client.list(request={})
assert pager._metadata == metadata
results = list(pager)
assert len(results) == 6
assert all(isinstance(i, compute.InstanceGroupManager) for i in results)
pages = list(client.list(request={}).pages)
for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page_.raw_page.next_page_token == token
def test_list_errors_rest(
transport: str = "rest", request_type=compute.ListErrorsInstanceGroupManagersRequest
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.InstanceGroupManagersListErrorsResponse(
items=[
compute.InstanceManagedByIgmError(
error=compute.InstanceManagedByIgmErrorManagedInstanceError(
code="code_value"
)
)
],
next_page_token="next_page_token_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.InstanceGroupManagersListErrorsResponse.to_json(
return_value
)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.list_errors(request)
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListErrorsPager)
assert response.items == [
compute.InstanceManagedByIgmError(
error=compute.InstanceManagedByIgmErrorManagedInstanceError(
code="code_value"
)
)
]
assert response.next_page_token == "next_page_token_value"
def test_list_errors_rest_from_dict():
test_list_errors_rest(request_type=dict)
def test_list_errors_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.InstanceGroupManagersListErrorsResponse()
# Wrap the value into a proper Response obj
json_return_value = compute.InstanceGroupManagersListErrorsResponse.to_json(
return_value
)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_errors(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
def test_list_errors_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.list_errors(
compute.ListErrorsInstanceGroupManagersRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
)
def test_list_errors_pager():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Set the response as a series of pages
response = (
compute.InstanceGroupManagersListErrorsResponse(
items=[
compute.InstanceManagedByIgmError(),
compute.InstanceManagedByIgmError(),
compute.InstanceManagedByIgmError(),
],
next_page_token="abc",
),
compute.InstanceGroupManagersListErrorsResponse(
items=[], next_page_token="def",
),
compute.InstanceGroupManagersListErrorsResponse(
items=[compute.InstanceManagedByIgmError(),], next_page_token="ghi",
),
compute.InstanceGroupManagersListErrorsResponse(
items=[
compute.InstanceManagedByIgmError(),
compute.InstanceManagedByIgmError(),
],
),
)
# Two responses for two calls
response = response + response
# Wrap the values into proper Response objs
response = tuple(
compute.InstanceGroupManagersListErrorsResponse.to_json(x) for x in response
)
return_values = tuple(Response() for i in response)
for return_val, response_val in zip(return_values, response):
return_val._content = response_val.encode("UTF-8")
return_val.status_code = 200
req.side_effect = return_values
metadata = ()
pager = client.list_errors(request={})
assert pager._metadata == metadata
results = list(pager)
assert len(results) == 6
assert all(isinstance(i, compute.InstanceManagedByIgmError) for i in results)
pages = list(client.list_errors(request={}).pages)
for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page_.raw_page.next_page_token == token
def test_list_managed_instances_rest(
transport: str = "rest",
request_type=compute.ListManagedInstancesInstanceGroupManagersRequest,
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.InstanceGroupManagersListManagedInstancesResponse(
managed_instances=[
compute.ManagedInstance(
current_action=compute.ManagedInstance.CurrentAction.ABANDONING
)
],
next_page_token="next_page_token_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.InstanceGroupManagersListManagedInstancesResponse.to_json(
return_value
)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.list_managed_instances(request)
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListManagedInstancesPager)
assert response.managed_instances == [
compute.ManagedInstance(
current_action=compute.ManagedInstance.CurrentAction.ABANDONING
)
]
assert response.next_page_token == "next_page_token_value"
def test_list_managed_instances_rest_from_dict():
test_list_managed_instances_rest(request_type=dict)
def test_list_managed_instances_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.InstanceGroupManagersListManagedInstancesResponse()
# Wrap the value into a proper Response obj
json_return_value = compute.InstanceGroupManagersListManagedInstancesResponse.to_json(
return_value
)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_managed_instances(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
def test_list_managed_instances_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.list_managed_instances(
compute.ListManagedInstancesInstanceGroupManagersRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
)
def test_list_managed_instances_pager():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Set the response as a series of pages
response = (
compute.InstanceGroupManagersListManagedInstancesResponse(
managed_instances=[
compute.ManagedInstance(),
compute.ManagedInstance(),
compute.ManagedInstance(),
],
next_page_token="abc",
),
compute.InstanceGroupManagersListManagedInstancesResponse(
managed_instances=[], next_page_token="def",
),
compute.InstanceGroupManagersListManagedInstancesResponse(
managed_instances=[compute.ManagedInstance(),], next_page_token="ghi",
),
compute.InstanceGroupManagersListManagedInstancesResponse(
managed_instances=[
compute.ManagedInstance(),
compute.ManagedInstance(),
],
),
)
# Two responses for two calls
response = response + response
# Wrap the values into proper Response objs
response = tuple(
compute.InstanceGroupManagersListManagedInstancesResponse.to_json(x)
for x in response
)
return_values = tuple(Response() for i in response)
for return_val, response_val in zip(return_values, response):
return_val._content = response_val.encode("UTF-8")
return_val.status_code = 200
req.side_effect = return_values
metadata = ()
pager = client.list_managed_instances(request={})
assert pager._metadata == metadata
results = list(pager)
assert len(results) == 6
assert all(isinstance(i, compute.ManagedInstance) for i in results)
pages = list(client.list_managed_instances(request={}).pages)
for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page_.raw_page.next_page_token == token
def test_list_per_instance_configs_rest(
transport: str = "rest",
request_type=compute.ListPerInstanceConfigsInstanceGroupManagersRequest,
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.InstanceGroupManagersListPerInstanceConfigsResp(
items=[compute.PerInstanceConfig(fingerprint="fingerprint_value")],
next_page_token="next_page_token_value",
warning=compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED),
)
# Wrap the value into a proper Response obj
json_return_value = compute.InstanceGroupManagersListPerInstanceConfigsResp.to_json(
return_value
)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.list_per_instance_configs(request)
# Establish that the response is the type that we expect.
assert isinstance(response, pagers.ListPerInstanceConfigsPager)
assert response.items == [
compute.PerInstanceConfig(fingerprint="fingerprint_value")
]
assert response.next_page_token == "next_page_token_value"
assert response.warning == compute.Warning(code=compute.Warning.Code.CLEANUP_FAILED)
def test_list_per_instance_configs_rest_from_dict():
test_list_per_instance_configs_rest(request_type=dict)
def test_list_per_instance_configs_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.InstanceGroupManagersListPerInstanceConfigsResp()
# Wrap the value into a proper Response obj
json_return_value = compute.InstanceGroupManagersListPerInstanceConfigsResp.to_json(
return_value
)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.list_per_instance_configs(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
def test_list_per_instance_configs_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.list_per_instance_configs(
compute.ListPerInstanceConfigsInstanceGroupManagersRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
)
def test_list_per_instance_configs_pager():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Set the response as a series of pages
response = (
compute.InstanceGroupManagersListPerInstanceConfigsResp(
items=[
compute.PerInstanceConfig(),
compute.PerInstanceConfig(),
compute.PerInstanceConfig(),
],
next_page_token="abc",
),
compute.InstanceGroupManagersListPerInstanceConfigsResp(
items=[], next_page_token="def",
),
compute.InstanceGroupManagersListPerInstanceConfigsResp(
items=[compute.PerInstanceConfig(),], next_page_token="ghi",
),
compute.InstanceGroupManagersListPerInstanceConfigsResp(
items=[compute.PerInstanceConfig(), compute.PerInstanceConfig(),],
),
)
# Two responses for two calls
response = response + response
# Wrap the values into proper Response objs
response = tuple(
compute.InstanceGroupManagersListPerInstanceConfigsResp.to_json(x)
for x in response
)
return_values = tuple(Response() for i in response)
for return_val, response_val in zip(return_values, response):
return_val._content = response_val.encode("UTF-8")
return_val.status_code = 200
req.side_effect = return_values
metadata = ()
pager = client.list_per_instance_configs(request={})
assert pager._metadata == metadata
results = list(pager)
assert len(results) == 6
assert all(isinstance(i, compute.PerInstanceConfig) for i in results)
pages = list(client.list_per_instance_configs(request={}).pages)
for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
assert page_.raw_page.next_page_token == token
def test_patch_rest(
transport: str = "rest", request_type=compute.PatchInstanceGroupManagerRequest
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.patch(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_patch_rest_from_dict():
test_patch_rest(request_type=dict)
def test_patch_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
instance_group_manager_resource = compute.InstanceGroupManager(
auto_healing_policies=[
compute.InstanceGroupManagerAutoHealingPolicy(
health_check="health_check_value"
)
]
)
client.patch(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_manager_resource=instance_group_manager_resource,
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
assert compute.InstanceGroupManager.to_json(
instance_group_manager_resource,
including_default_value_fields=False,
use_integers_for_enums=False,
) in http_call[1] + str(body)
def test_patch_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.patch(
compute.PatchInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_manager_resource=compute.InstanceGroupManager(
auto_healing_policies=[
compute.InstanceGroupManagerAutoHealingPolicy(
health_check="health_check_value"
)
]
),
)
def test_patch_per_instance_configs_rest(
transport: str = "rest",
request_type=compute.PatchPerInstanceConfigsInstanceGroupManagerRequest,
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.patch_per_instance_configs(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_patch_per_instance_configs_rest_from_dict():
test_patch_per_instance_configs_rest(request_type=dict)
def test_patch_per_instance_configs_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
instance_group_managers_patch_per_instance_configs_req_resource = compute.InstanceGroupManagersPatchPerInstanceConfigsReq(
per_instance_configs=[
compute.PerInstanceConfig(fingerprint="fingerprint_value")
]
)
client.patch_per_instance_configs(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_patch_per_instance_configs_req_resource=instance_group_managers_patch_per_instance_configs_req_resource,
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
assert compute.InstanceGroupManagersPatchPerInstanceConfigsReq.to_json(
instance_group_managers_patch_per_instance_configs_req_resource,
including_default_value_fields=False,
use_integers_for_enums=False,
) in http_call[1] + str(body)
def test_patch_per_instance_configs_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.patch_per_instance_configs(
compute.PatchPerInstanceConfigsInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_patch_per_instance_configs_req_resource=compute.InstanceGroupManagersPatchPerInstanceConfigsReq(
per_instance_configs=[
compute.PerInstanceConfig(fingerprint="fingerprint_value")
]
),
)
def test_recreate_instances_rest(
transport: str = "rest",
request_type=compute.RecreateInstancesInstanceGroupManagerRequest,
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.recreate_instances(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_recreate_instances_rest_from_dict():
test_recreate_instances_rest(request_type=dict)
def test_recreate_instances_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
instance_group_managers_recreate_instances_request_resource = compute.InstanceGroupManagersRecreateInstancesRequest(
instances=["instances_value"]
)
client.recreate_instances(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_recreate_instances_request_resource=instance_group_managers_recreate_instances_request_resource,
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
assert compute.InstanceGroupManagersRecreateInstancesRequest.to_json(
instance_group_managers_recreate_instances_request_resource,
including_default_value_fields=False,
use_integers_for_enums=False,
) in http_call[1] + str(body)
def test_recreate_instances_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.recreate_instances(
compute.RecreateInstancesInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_recreate_instances_request_resource=compute.InstanceGroupManagersRecreateInstancesRequest(
instances=["instances_value"]
),
)
def test_resize_rest(
transport: str = "rest", request_type=compute.ResizeInstanceGroupManagerRequest
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.resize(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_resize_rest_from_dict():
test_resize_rest(request_type=dict)
def test_resize_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
client.resize(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
size=443,
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
assert str(443) in http_call[1] + str(body)
def test_resize_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.resize(
compute.ResizeInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
size=443,
)
def test_set_instance_template_rest(
transport: str = "rest",
request_type=compute.SetInstanceTemplateInstanceGroupManagerRequest,
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.set_instance_template(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_set_instance_template_rest_from_dict():
test_set_instance_template_rest(request_type=dict)
def test_set_instance_template_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
instance_group_managers_set_instance_template_request_resource = compute.InstanceGroupManagersSetInstanceTemplateRequest(
instance_template="instance_template_value"
)
client.set_instance_template(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_set_instance_template_request_resource=instance_group_managers_set_instance_template_request_resource,
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
assert compute.InstanceGroupManagersSetInstanceTemplateRequest.to_json(
instance_group_managers_set_instance_template_request_resource,
including_default_value_fields=False,
use_integers_for_enums=False,
) in http_call[1] + str(body)
def test_set_instance_template_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.set_instance_template(
compute.SetInstanceTemplateInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_set_instance_template_request_resource=compute.InstanceGroupManagersSetInstanceTemplateRequest(
instance_template="instance_template_value"
),
)
def test_set_target_pools_rest(
transport: str = "rest",
request_type=compute.SetTargetPoolsInstanceGroupManagerRequest,
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.set_target_pools(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_set_target_pools_rest_from_dict():
test_set_target_pools_rest(request_type=dict)
def test_set_target_pools_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
instance_group_managers_set_target_pools_request_resource = compute.InstanceGroupManagersSetTargetPoolsRequest(
fingerprint="fingerprint_value"
)
client.set_target_pools(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_set_target_pools_request_resource=instance_group_managers_set_target_pools_request_resource,
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
assert compute.InstanceGroupManagersSetTargetPoolsRequest.to_json(
instance_group_managers_set_target_pools_request_resource,
including_default_value_fields=False,
use_integers_for_enums=False,
) in http_call[1] + str(body)
def test_set_target_pools_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.set_target_pools(
compute.SetTargetPoolsInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_set_target_pools_request_resource=compute.InstanceGroupManagersSetTargetPoolsRequest(
fingerprint="fingerprint_value"
),
)
def test_update_per_instance_configs_rest(
transport: str = "rest",
request_type=compute.UpdatePerInstanceConfigsInstanceGroupManagerRequest,
):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# Everything is optional in proto3 as far as the runtime is concerned,
# and we are mocking out the actual API, so just send an empty request.
request = request_type()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation(
client_operation_id="client_operation_id_value",
creation_timestamp="creation_timestamp_value",
description="description_value",
end_time="end_time_value",
error=compute.Error(errors=[compute.Errors(code="code_value")]),
http_error_message="http_error_message_value",
http_error_status_code=2374,
id="id_value",
insert_time="insert_time_value",
kind="kind_value",
name="name_value",
operation_group_id="operation_group_id_value",
operation_type="operation_type_value",
progress=885,
region="region_value",
self_link="self_link_value",
start_time="start_time_value",
status=compute.Operation.Status.DONE,
status_message="status_message_value",
target_id="target_id_value",
target_link="target_link_value",
user="user_value",
warnings=[compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)],
zone="zone_value",
)
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
response = client.update_per_instance_configs(request)
# Establish that the response is the type that we expect.
assert isinstance(response, compute.Operation)
assert response.client_operation_id == "client_operation_id_value"
assert response.creation_timestamp == "creation_timestamp_value"
assert response.description == "description_value"
assert response.end_time == "end_time_value"
assert response.error == compute.Error(errors=[compute.Errors(code="code_value")])
assert response.http_error_message == "http_error_message_value"
assert response.http_error_status_code == 2374
assert response.id == "id_value"
assert response.insert_time == "insert_time_value"
assert response.kind == "kind_value"
assert response.name == "name_value"
assert response.operation_group_id == "operation_group_id_value"
assert response.operation_type == "operation_type_value"
assert response.progress == 885
assert response.region == "region_value"
assert response.self_link == "self_link_value"
assert response.start_time == "start_time_value"
assert response.status == compute.Operation.Status.DONE
assert response.status_message == "status_message_value"
assert response.target_id == "target_id_value"
assert response.target_link == "target_link_value"
assert response.user == "user_value"
assert response.warnings == [
compute.Warnings(code=compute.Warnings.Code.CLEANUP_FAILED)
]
assert response.zone == "zone_value"
def test_update_per_instance_configs_rest_from_dict():
test_update_per_instance_configs_rest(request_type=dict)
def test_update_per_instance_configs_rest_flattened():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# Designate an appropriate value for the returned response.
return_value = compute.Operation()
# Wrap the value into a proper Response obj
json_return_value = compute.Operation.to_json(return_value)
response_value = Response()
response_value.status_code = 200
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
instance_group_managers_update_per_instance_configs_req_resource = compute.InstanceGroupManagersUpdatePerInstanceConfigsReq(
per_instance_configs=[
compute.PerInstanceConfig(fingerprint="fingerprint_value")
]
)
client.update_per_instance_configs(
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_update_per_instance_configs_req_resource=instance_group_managers_update_per_instance_configs_req_resource,
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(req.mock_calls) == 1
_, http_call, http_params = req.mock_calls[0]
body = http_params.get("data")
assert "project_value" in http_call[1] + str(body)
assert "zone_value" in http_call[1] + str(body)
assert "instance_group_manager_value" in http_call[1] + str(body)
assert compute.InstanceGroupManagersUpdatePerInstanceConfigsReq.to_json(
instance_group_managers_update_per_instance_configs_req_resource,
including_default_value_fields=False,
use_integers_for_enums=False,
) in http_call[1] + str(body)
def test_update_per_instance_configs_rest_flattened_error():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
client.update_per_instance_configs(
compute.UpdatePerInstanceConfigsInstanceGroupManagerRequest(),
project="project_value",
zone="zone_value",
instance_group_manager="instance_group_manager_value",
instance_group_managers_update_per_instance_configs_req_resource=compute.InstanceGroupManagersUpdatePerInstanceConfigsReq(
per_instance_configs=[
compute.PerInstanceConfig(fingerprint="fingerprint_value")
]
),
)
def test_credentials_transport_error():
# It is an error to provide credentials and a transport instance.
transport = transports.InstanceGroupManagersRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), transport=transport,
)
# It is an error to provide a credentials file and a transport instance.
transport = transports.InstanceGroupManagersRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = InstanceGroupManagersClient(
client_options={"credentials_file": "credentials.json"},
transport=transport,
)
# It is an error to provide scopes and a transport instance.
transport = transports.InstanceGroupManagersRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
with pytest.raises(ValueError):
client = InstanceGroupManagersClient(
client_options={"scopes": ["1", "2"]}, transport=transport,
)
def test_transport_instance():
# A client may be instantiated with a custom transport instance.
transport = transports.InstanceGroupManagersRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
client = InstanceGroupManagersClient(transport=transport)
assert client.transport is transport
@pytest.mark.parametrize(
"transport_class", [transports.InstanceGroupManagersRestTransport,]
)
def test_transport_adc(transport_class):
# Test default credentials are used if not provided.
with mock.patch.object(google.auth, "default") as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport_class()
adc.assert_called_once()
def test_instance_group_managers_base_transport_error():
# Passing both a credentials object and credentials_file should raise an error
with pytest.raises(core_exceptions.DuplicateCredentialArgs):
transport = transports.InstanceGroupManagersTransport(
credentials=ga_credentials.AnonymousCredentials(),
credentials_file="credentials.json",
)
def test_instance_group_managers_base_transport():
# Instantiate the base transport.
with mock.patch(
"google.cloud.compute_v1.services.instance_group_managers.transports.InstanceGroupManagersTransport.__init__"
) as Transport:
Transport.return_value = None
transport = transports.InstanceGroupManagersTransport(
credentials=ga_credentials.AnonymousCredentials(),
)
# Every method on the transport should just blindly
# raise NotImplementedError.
methods = (
"abandon_instances",
"aggregated_list",
"apply_updates_to_instances",
"create_instances",
"delete",
"delete_instances",
"delete_per_instance_configs",
"get",
"insert",
"list",
"list_errors",
"list_managed_instances",
"list_per_instance_configs",
"patch",
"patch_per_instance_configs",
"recreate_instances",
"resize",
"set_instance_template",
"set_target_pools",
"update_per_instance_configs",
)
for method in methods:
with pytest.raises(NotImplementedError):
getattr(transport, method)(request=object())
@requires_google_auth_gte_1_25_0
def test_instance_group_managers_base_transport_with_credentials_file():
# Instantiate the base transport with a credentials file
with mock.patch.object(
google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.compute_v1.services.instance_group_managers.transports.InstanceGroupManagersTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.InstanceGroupManagersTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
default_scopes=(
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/cloud-platform",
),
quota_project_id="octopus",
)
@requires_google_auth_lt_1_25_0
def test_instance_group_managers_base_transport_with_credentials_file_old_google_auth():
# Instantiate the base transport with a credentials file
with mock.patch.object(
google.auth, "load_credentials_from_file", autospec=True
) as load_creds, mock.patch(
"google.cloud.compute_v1.services.instance_group_managers.transports.InstanceGroupManagersTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.InstanceGroupManagersTransport(
credentials_file="credentials.json", quota_project_id="octopus",
)
load_creds.assert_called_once_with(
"credentials.json",
scopes=(
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/cloud-platform",
),
quota_project_id="octopus",
)
def test_instance_group_managers_base_transport_with_adc():
# Test the default credentials are used if credentials and credentials_file are None.
with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch(
"google.cloud.compute_v1.services.instance_group_managers.transports.InstanceGroupManagersTransport._prep_wrapped_messages"
) as Transport:
Transport.return_value = None
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
transport = transports.InstanceGroupManagersTransport()
adc.assert_called_once()
@requires_google_auth_gte_1_25_0
def test_instance_group_managers_auth_adc():
# If no credentials are provided, we should use ADC credentials.
with mock.patch.object(google.auth, "default", autospec=True) as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
InstanceGroupManagersClient()
adc.assert_called_once_with(
scopes=None,
default_scopes=(
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/cloud-platform",
),
quota_project_id=None,
)
@requires_google_auth_lt_1_25_0
def test_instance_group_managers_auth_adc_old_google_auth():
# If no credentials are provided, we should use ADC credentials.
with mock.patch.object(google.auth, "default", autospec=True) as adc:
adc.return_value = (ga_credentials.AnonymousCredentials(), None)
InstanceGroupManagersClient()
adc.assert_called_once_with(
scopes=(
"https://www.googleapis.com/auth/compute",
"https://www.googleapis.com/auth/cloud-platform",
),
quota_project_id=None,
)
def test_instance_group_managers_http_transport_client_cert_source_for_mtls():
cred = ga_credentials.AnonymousCredentials()
with mock.patch(
"google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
) as mock_configure_mtls_channel:
transports.InstanceGroupManagersRestTransport(
credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
)
mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
def test_instance_group_managers_host_no_port():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="compute.googleapis.com"
),
)
assert client.transport._host == "compute.googleapis.com:443"
def test_instance_group_managers_host_with_port():
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(),
client_options=client_options.ClientOptions(
api_endpoint="compute.googleapis.com:8000"
),
)
assert client.transport._host == "compute.googleapis.com:8000"
def test_common_billing_account_path():
billing_account = "squid"
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
actual = InstanceGroupManagersClient.common_billing_account_path(billing_account)
assert expected == actual
def test_parse_common_billing_account_path():
expected = {
"billing_account": "clam",
}
path = InstanceGroupManagersClient.common_billing_account_path(**expected)
# Check that the path construction is reversible.
actual = InstanceGroupManagersClient.parse_common_billing_account_path(path)
assert expected == actual
def test_common_folder_path():
folder = "whelk"
expected = "folders/{folder}".format(folder=folder,)
actual = InstanceGroupManagersClient.common_folder_path(folder)
assert expected == actual
def test_parse_common_folder_path():
expected = {
"folder": "octopus",
}
path = InstanceGroupManagersClient.common_folder_path(**expected)
# Check that the path construction is reversible.
actual = InstanceGroupManagersClient.parse_common_folder_path(path)
assert expected == actual
def test_common_organization_path():
organization = "oyster"
expected = "organizations/{organization}".format(organization=organization,)
actual = InstanceGroupManagersClient.common_organization_path(organization)
assert expected == actual
def test_parse_common_organization_path():
expected = {
"organization": "nudibranch",
}
path = InstanceGroupManagersClient.common_organization_path(**expected)
# Check that the path construction is reversible.
actual = InstanceGroupManagersClient.parse_common_organization_path(path)
assert expected == actual
def test_common_project_path():
project = "cuttlefish"
expected = "projects/{project}".format(project=project,)
actual = InstanceGroupManagersClient.common_project_path(project)
assert expected == actual
def test_parse_common_project_path():
expected = {
"project": "mussel",
}
path = InstanceGroupManagersClient.common_project_path(**expected)
# Check that the path construction is reversible.
actual = InstanceGroupManagersClient.parse_common_project_path(path)
assert expected == actual
def test_common_location_path():
project = "winkle"
location = "nautilus"
expected = "projects/{project}/locations/{location}".format(
project=project, location=location,
)
actual = InstanceGroupManagersClient.common_location_path(project, location)
assert expected == actual
def test_parse_common_location_path():
expected = {
"project": "scallop",
"location": "abalone",
}
path = InstanceGroupManagersClient.common_location_path(**expected)
# Check that the path construction is reversible.
actual = InstanceGroupManagersClient.parse_common_location_path(path)
assert expected == actual
def test_client_withDEFAULT_CLIENT_INFO():
client_info = gapic_v1.client_info.ClientInfo()
with mock.patch.object(
transports.InstanceGroupManagersTransport, "_prep_wrapped_messages"
) as prep:
client = InstanceGroupManagersClient(
credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
with mock.patch.object(
transports.InstanceGroupManagersTransport, "_prep_wrapped_messages"
) as prep:
transport_class = InstanceGroupManagersClient.get_transport_class()
transport = transport_class(
credentials=ga_credentials.AnonymousCredentials(), client_info=client_info,
)
prep.assert_called_once_with(client_info)
| []
| []
| []
| [] | [] | python | 0 | 0 | |
controllers/helmrelease_controller_chart.go | /*
Copyright 2020 The Flux 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 controllers
import (
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"reflect"
"strings"
"github.com/go-logr/logr"
"github.com/hashicorp/go-retryablehttp"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chart/loader"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
v2 "github.com/fluxcd/helm-controller/api/v2beta1"
)
func (r *HelmReleaseReconciler) reconcileChart(ctx context.Context, hr *v2.HelmRelease) (*sourcev1.HelmChart, error) {
chartName := types.NamespacedName{
Namespace: hr.Spec.Chart.GetNamespace(hr.Namespace),
Name: hr.GetHelmChartName(),
}
// Garbage collect the previous HelmChart if the namespace named changed.
if hr.Status.HelmChart != "" && hr.Status.HelmChart != chartName.String() {
if err := r.deleteHelmChart(ctx, hr); err != nil {
return nil, err
}
}
// Continue with the reconciliation of the current template.
var helmChart sourcev1.HelmChart
err := r.Client.Get(ctx, chartName, &helmChart)
if err != nil && !apierrors.IsNotFound(err) {
return nil, err
}
hc := buildHelmChartFromTemplate(hr)
switch {
case apierrors.IsNotFound(err):
if err = r.Client.Create(ctx, hc); err != nil {
return nil, err
}
hr.Status.HelmChart = chartName.String()
return hc, nil
case helmChartRequiresUpdate(hr, &helmChart):
logr.FromContext(ctx).Info("chart diverged from template", strings.ToLower(sourcev1.HelmChartKind), chartName.String())
helmChart.Spec = hc.Spec
if err = r.Client.Update(ctx, &helmChart); err != nil {
return nil, err
}
hr.Status.HelmChart = chartName.String()
}
return &helmChart, nil
}
// getHelmChart retrieves the v1beta1.HelmChart for the given
// v2beta1.HelmRelease using the name that is advertised in the status
// object. It returns the v1beta1.HelmChart, or an error.
func (r *HelmReleaseReconciler) getHelmChart(ctx context.Context, hr *v2.HelmRelease) (*sourcev1.HelmChart, error) {
namespace, name := hr.Status.GetHelmChart()
hc := &sourcev1.HelmChart{}
if err := r.Client.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, hc); err != nil {
return nil, err
}
return hc, nil
}
// loadHelmChart attempts to download the artifact from the provided source,
// loads it into a chart.Chart, and removes the downloaded artifact.
// It returns the loaded chart.Chart on success, or an error.
func (r *HelmReleaseReconciler) loadHelmChart(source *sourcev1.HelmChart) (*chart.Chart, error) {
f, err := ioutil.TempFile("", fmt.Sprintf("%s-%s-*.tgz", source.GetNamespace(), source.GetName()))
if err != nil {
return nil, err
}
defer f.Close()
defer os.Remove(f.Name())
artifactURL := source.GetArtifact().URL
if hostname := os.Getenv("SOURCE_CONTROLLER_LOCALHOST"); hostname != "" {
u, err := url.Parse(artifactURL)
if err != nil {
return nil, err
}
u.Host = hostname
artifactURL = u.String()
}
req, err := retryablehttp.NewRequest(http.MethodGet, artifactURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create a new request: %w", err)
}
resp, err := r.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to download artifact, error: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("artifact '%s' download failed (status code: %s)", source.GetArtifact().URL, resp.Status)
}
if _, err = io.Copy(f, resp.Body); err != nil {
return nil, err
}
return loader.Load(f.Name())
}
// deleteHelmChart deletes the v1beta1.HelmChart of the v2beta1.HelmRelease.
func (r *HelmReleaseReconciler) deleteHelmChart(ctx context.Context, hr *v2.HelmRelease) error {
if hr.Status.HelmChart == "" {
return nil
}
var hc sourcev1.HelmChart
chartNS, chartName := hr.Status.GetHelmChart()
err := r.Client.Get(ctx, types.NamespacedName{Namespace: chartNS, Name: chartName}, &hc)
if err != nil {
if apierrors.IsNotFound(err) {
hr.Status.HelmChart = ""
return nil
}
err = fmt.Errorf("failed to delete HelmChart '%s': %w", hr.Status.HelmChart, err)
return err
}
if err = r.Client.Delete(ctx, &hc); err != nil {
err = fmt.Errorf("failed to delete HelmChart '%s': %w", hr.Status.HelmChart, err)
return err
}
// Truncate the chart reference in the status object.
hr.Status.HelmChart = ""
return nil
}
// buildHelmChartFromTemplate builds a v1beta1.HelmChart from the
// v2beta1.HelmChartTemplate of the given v2beta1.HelmRelease.
func buildHelmChartFromTemplate(hr *v2.HelmRelease) *sourcev1.HelmChart {
template := hr.Spec.Chart
return &sourcev1.HelmChart{
ObjectMeta: metav1.ObjectMeta{
Name: hr.GetHelmChartName(),
Namespace: hr.Spec.Chart.GetNamespace(hr.Namespace),
},
Spec: sourcev1.HelmChartSpec{
Chart: template.Spec.Chart,
Version: template.Spec.Version,
SourceRef: sourcev1.LocalHelmChartSourceReference{
Name: template.Spec.SourceRef.Name,
Kind: template.Spec.SourceRef.Kind,
},
Interval: template.GetInterval(hr.Spec.Interval),
ValuesFiles: template.Spec.ValuesFiles,
ValuesFile: template.Spec.ValuesFile,
},
}
}
// helmChartRequiresUpdate compares the v2beta1.HelmChartTemplate of the
// v2beta1.HelmRelease to the given v1beta1.HelmChart to determine if an
// update is required.
func helmChartRequiresUpdate(hr *v2.HelmRelease, chart *sourcev1.HelmChart) bool {
template := hr.Spec.Chart
switch {
case template.Spec.Chart != chart.Spec.Chart:
return true
// TODO(hidde): remove emptiness checks on next MINOR version
case template.Spec.Version == "" && chart.Spec.Version != "*",
template.Spec.Version != "" && template.Spec.Version != chart.Spec.Version:
return true
case template.Spec.SourceRef.Name != chart.Spec.SourceRef.Name:
return true
case template.Spec.SourceRef.Kind != chart.Spec.SourceRef.Kind:
return true
case template.GetInterval(hr.Spec.Interval) != chart.Spec.Interval:
return true
case !reflect.DeepEqual(template.Spec.ValuesFiles, chart.Spec.ValuesFiles):
return true
case template.Spec.ValuesFile != chart.Spec.ValuesFile:
return true
default:
return false
}
}
| [
"\"SOURCE_CONTROLLER_LOCALHOST\""
]
| []
| [
"SOURCE_CONTROLLER_LOCALHOST"
]
| [] | ["SOURCE_CONTROLLER_LOCALHOST"] | go | 1 | 0 | |
teen/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', 'teen.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 | |
exams/utils.py | import subprocess
import os
def compile_tex(tex_content, output_directory, output_file_name, env=os.environ):
compiler = subprocess.Popen(["xelatex", "-jobname=" + output_file_name], env=env, cwd=output_directory,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
return compiler.communicate(input=tex_content)
| []
| []
| []
| [] | [] | python | 0 | 0 | |
main.go | package main
import (
"context"
"errors"
"flag"
"fmt"
"os"
"strings"
"github.com/genuinetools/pkg/cli"
"github.com/genuinetools/weather/forecast"
"github.com/genuinetools/weather/geocode"
"github.com/genuinetools/weather/version"
"github.com/mitchellh/colorstring"
)
const (
defaultServerURI string = "https://geocode.jessfraz.com"
)
var (
location string
units string
days int
ignoreAlerts bool
hideIcon bool
noForecast bool
server string
client bool
geo geocode.Geocode
)
//go:generate go run icons/generate.go
func main() {
// Create a new cli program.
p := cli.NewProgram()
p.Name = "weather"
p.Description = "Weather forecast via the command line"
// Set the GitCommit and Version.
p.GitCommit = version.GITCOMMIT
p.Version = version.VERSION
// Build the list of available commands.
p.Commands = []cli.Command{
&serverCommand{},
}
// Setup the global flags.
p.FlagSet = flag.NewFlagSet("global", flag.ExitOnError)
p.FlagSet.StringVar(&location, "location", "", "Location to get the weather")
p.FlagSet.StringVar(&location, "l", "", "Location to get the weather (shorthand)")
p.FlagSet.BoolVar(&client, "client", false, "Get location for the ssh client")
p.FlagSet.BoolVar(&client, "c", false, "Get location for the ssh client (shorthand)")
p.FlagSet.StringVar(&units, "units", "auto", "System of units (e.g. auto, us, si, ca, uk2)")
p.FlagSet.StringVar(&units, "u", "auto", "System of units (shorthand) (e.g. auto, us, si, ca, uk2)")
p.FlagSet.StringVar(&server, "server", defaultServerURI, "Weather API server uri")
p.FlagSet.StringVar(&server, "s", defaultServerURI, "Weather API server uri (shorthand)")
p.FlagSet.IntVar(&days, "days", 0, "No. of days to get forecast")
p.FlagSet.IntVar(&days, "d", 0, "No. of days to get forecast (shorthand)")
p.FlagSet.BoolVar(&ignoreAlerts, "ignore-alerts", false, "Ignore alerts in weather output")
p.FlagSet.BoolVar(&hideIcon, "hide-icon", false, "Hide the weather icons from being output")
p.FlagSet.BoolVar(&noForecast, "no-forecast", false, "Hide the forecast for the next 16 hours")
// Set the before function.
p.Before = func(ctx context.Context) error {
if len(server) < 1 {
return errors.New("Please enter a Weather API server uri or leave blank to use the default")
}
return nil
}
// Set the main program action.
p.Action = func(ctx context.Context) error {
var err error
if location == "" {
sshConn := os.Getenv("SSH_CONNECTION")
if client && len(sshConn) > 0 {
// use their ssh connection to locate them
ipports := strings.Split(sshConn, " ")
geo, err = geocode.IPLocate(ipports[0])
if err != nil {
printError(err)
}
} else {
// auto locate them
geo, err = geocode.Autolocate()
if err != nil {
printError(err)
}
if geo.Latitude == 0 || geo.Longitude == 0 {
printError(errors.New("Latitude and Longitude could not be determined from your IP so the weather will not be accurate\nTry: weather -l <your_zipcode> OR weather -l \"your city, state\""))
}
}
} else {
// get geolocation data for the given location
geo, err = geocode.Locate(location, server)
if err != nil {
printError(err)
}
}
if geo.Latitude == 0 || geo.Longitude == 0 {
printError(errors.New("Latitude and Longitude could not be determined so the weather will not be accurate"))
}
data := forecast.Request{
Latitude: geo.Latitude,
Longitude: geo.Longitude,
Units: units,
Exclude: []string{"minutely"},
}
if noForecast {
data.Exclude = append(data.Exclude, "hourly")
}
fc, err := forecast.Get(fmt.Sprintf("%s/forecast", server), data)
if err != nil {
printError(err)
}
if err := forecast.PrintCurrent(fc, geo, ignoreAlerts, hideIcon); err != nil {
printError(err)
}
if days > 0 {
forecast.PrintDaily(fc, days)
}
return nil
}
// Run our program.
p.Run()
}
func printError(err error) {
fmt.Println(colorstring.Color("[red]" + err.Error()))
os.Exit(1)
}
| [
"\"SSH_CONNECTION\""
]
| []
| [
"SSH_CONNECTION"
]
| [] | ["SSH_CONNECTION"] | go | 1 | 0 | |
utils.py | import hashlib
import logging
import os
import shutil
import sys
import tarfile
import tempfile
import urllib.error
import urllib.parse
import urllib.request
import zipfile
from contextlib import closing
from urllib.parse import urlparse
import boto3
import click
import requests
import ujson
CHUNK_SIZE = 1024
def get_files(path):
"""Returns an iterable containing the full path of all files in the
specified path.
:param path: string
:yields: string
"""
if os.path.isdir(path):
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
if not filename[0] == ".":
yield os.path.join(dirpath, filename)
else:
yield path
def read_json(path):
"""Returns JSON dict from file.
:param path: string
:returns: dict
"""
with open(path, "r") as jsonfile:
return ujson.loads(jsonfile.read())
def write_json(path, data):
with open(path, "w") as jsonfile:
jsonfile.write(
ujson.dumps(data, escape_forward_slashes=False, double_precision=5)
)
def make_sure_path_exists(path):
"""Make directories in path if they do not exist.
Modified from http://stackoverflow.com/a/5032238/1377021
:param path: string
"""
try:
os.makedirs(path)
except:
pass
def get_path_parts(path):
"""Splits a path into parent directories and file.
:param path: string
"""
return path.split(os.sep)
def download(url):
"""Downloads a file and returns a file pointer to a temporary file.
:param url: string
"""
parsed_url = urlparse(url)
urlfile = parsed_url.path.split("/")[-1]
_, extension = os.path.split(urlfile)
fp = tempfile.NamedTemporaryFile("wb", suffix=extension, delete=False)
download_cache = os.getenv("DOWNLOAD_CACHE")
cache_path = None
if download_cache is not None:
cache_path = os.path.join(
download_cache, hashlib.sha224(url.encode()).hexdigest()
)
if os.path.exists(cache_path):
logging.info("Returning %s from local cache at %s" % (url, cache_path))
fp.close()
shutil.copy(cache_path, fp.name)
return fp
s3_cache_bucket = os.getenv("S3_CACHE_BUCKET")
s3_cache_key = None
if s3_cache_bucket is not None and s3_cache_bucket not in url:
s3_cache_key = (
os.getenv("S3_CACHE_PREFIX", "") + hashlib.sha224(url.encode()).hexdigest()
)
s3 = boto3.client("s3")
try:
s3.download_fileobj(s3_cache_bucket, s3_cache_key, fp)
logging.info(
"Found %s in s3 cache at s3://%s/%s"
% (url, s3_cache_bucket, s3_cache_key)
)
fp.close()
return fp
except:
pass
if parsed_url.scheme == "http" or parsed_url.scheme == "https":
res = requests.get(url, stream=True, verify=False)
if not res.ok:
raise IOError
for chunk in res.iter_content(CHUNK_SIZE):
fp.write(chunk)
elif parsed_url.scheme == "ftp":
download = urllib.request.urlopen(url)
file_size_dl = 0
block_sz = 8192
while True:
buffer = download.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
fp.write(buffer)
fp.close()
if cache_path:
if not os.path.exists(download_cache):
os.makedirs(download_cache)
shutil.copy(fp.name, cache_path)
if s3_cache_key:
logging.info(
"Putting %s to s3 cache at s3://%s/%s"
% (url, s3_cache_bucket, s3_cache_key)
)
s3.upload_file(fp.name, Bucket=s3_cache_bucket, Key=s3_cache_key)
return fp
class ZipCompatibleTarFile(tarfile.TarFile):
"""Wrapper around TarFile to make it more compatible with ZipFile"""
def infolist(self):
members = self.getmembers()
for m in members:
m.filename = m.name
return members
def namelist(self):
return self.getnames()
ARCHIVE_FORMAT_ZIP = "zip"
ARCHIVE_FORMAT_TAR_GZ = "tar.gz"
ARCHIVE_FORMAT_TAR_BZ2 = "tar.bz2"
def get_compressed_file_wrapper(path):
archive_format = None
if path.endswith(".zip"):
archive_format = ARCHIVE_FORMAT_ZIP
elif path.endswith(".tar.gz") or path.endswith(".tgz"):
archive_format = ARCHIVE_FORMAT_TAR_GZ
elif path.endswith(".tar.bz2"):
archive_format = ARCHIVE_FORMAT_TAR_BZ2
else:
try:
with zipfile.ZipFile(path, "r") as f:
archive_format = ARCHIVE_FORMAT_ZIP
except:
try:
f = tarfile.TarFile.open(path, "r")
f.close()
archive_format = ARCHIVE_FORMAT_ZIP
except:
pass
if archive_format is None:
raise Exception("Unable to determine archive format")
if archive_format == ARCHIVE_FORMAT_ZIP:
return zipfile.ZipFile(path, "r")
elif archive_format == ARCHIVE_FORMAT_TAR_GZ:
return ZipCompatibleTarFile.open(path, "r:gz")
elif archive_format == ARCHIVE_FORMAT_TAR_BZ2:
return ZipCompatibleTarFile.open(path, "r:bz2")
| []
| []
| [
"S3_CACHE_BUCKET",
"S3_CACHE_PREFIX",
"DOWNLOAD_CACHE"
]
| [] | ["S3_CACHE_BUCKET", "S3_CACHE_PREFIX", "DOWNLOAD_CACHE"] | python | 3 | 0 | |
src/python/pants/base/exception_sink.py | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import datetime
import faulthandler
import logging
import os
import signal
import sys
import threading
import traceback
from contextlib import contextmanager
from typing import Callable, Iterator, Optional
import setproctitle
from pants.base.exiter import Exiter
from pants.util.dirutil import safe_mkdir, safe_open
from pants.util.osutil import Pid
logger = logging.getLogger(__name__)
class SignalHandler:
"""A specification for how to handle a fixed set of nonfatal signals.
This is subclassed and registered with ExceptionSink.reset_signal_handler() whenever the signal
handling behavior is modified for different pants processes, for example in the remote client when
pantsd is enabled. The default behavior is to exit "gracefully" by leaving a detailed log of which
signal was received, then exiting with failure.
Note that the terminal will convert a ctrl-c from the user into a SIGINT.
"""
@property
def signal_handler_mapping(self):
"""A dict mapping (signal number) -> (a method handling the signal)."""
# Could use an enum here, but we never end up doing any matching on the specific signal value,
# instead just iterating over the registered signals to set handlers, so a dict is probably
# better.
return {
signal.SIGINT: self._handle_sigint_if_enabled,
signal.SIGQUIT: self.handle_sigquit,
signal.SIGTERM: self.handle_sigterm,
}
def __init__(self):
self._ignore_sigint_lock = threading.Lock()
self._threads_ignoring_sigint = 0
self._ignoring_sigint_v2_engine = False
def _check_sigint_gate_is_correct(self):
assert self._threads_ignoring_sigint >= 0, \
"This should never happen, someone must have modified the counter outside of SignalHandler."
def _handle_sigint_if_enabled(self, signum, _frame):
with self._ignore_sigint_lock:
self._check_sigint_gate_is_correct()
threads_ignoring_sigint = self._threads_ignoring_sigint
ignoring_sigint_v2_engine = self._ignoring_sigint_v2_engine
if threads_ignoring_sigint == 0 and not ignoring_sigint_v2_engine:
self.handle_sigint(signum, _frame)
def _toggle_ignoring_sigint_v2_engine(self, toggle: bool):
with self._ignore_sigint_lock:
self._ignoring_sigint_v2_engine = toggle
@contextmanager
def _ignoring_sigint(self):
with self._ignore_sigint_lock:
self._check_sigint_gate_is_correct()
self._threads_ignoring_sigint += 1
try:
yield
finally:
with self._ignore_sigint_lock:
self._threads_ignoring_sigint -= 1
self._check_sigint_gate_is_correct()
def handle_sigint(self, signum, _frame):
raise KeyboardInterrupt('User interrupted execution with control-c!')
# TODO(#7406): figure out how to let sys.exit work in a signal handler instead of having to raise
# this exception!
class SignalHandledNonLocalExit(Exception):
"""Raised in handlers for non-fatal signals to overcome Python limitations.
When waiting on a subprocess and in a signal handler, sys.exit appears to be ignored, and causes
the signal handler to return. We want to (eventually) exit after these signals, not ignore them,
so we raise this exception instead and check it in our sys.excepthook override.
"""
def __init__(self, signum, signame):
self.signum = signum
self.signame = signame
self.traceback_lines = traceback.format_stack()
super(SignalHandler.SignalHandledNonLocalExit, self).__init__()
def handle_sigquit(self, signum, _frame):
raise self.SignalHandledNonLocalExit(signum, 'SIGQUIT')
def handle_sigterm(self, signum, _frame):
raise self.SignalHandledNonLocalExit(signum, 'SIGTERM')
class ExceptionSink:
"""A mutable singleton object representing where exceptions should be logged to."""
# NB: see the bottom of this file where we call reset_log_location() and other mutators in order
# to properly setup global state.
_log_dir = None
# We need an exiter in order to know what to do after we log a fatal exception or handle a
# catchable signal.
_exiter: Optional[Exiter] = None
# Where to log stacktraces to in a SIGUSR2 handler.
_interactive_output_stream = None
# Whether to print a stacktrace in any fatal error message printed to the terminal.
_should_print_backtrace_to_terminal = True
# An instance of `SignalHandler` which is invoked to handle a static set of specific
# nonfatal signals (these signal handlers are allowed to make pants exit, but unlike SIGSEGV they
# don't need to exit immediately).
_signal_handler: Optional[SignalHandler] = None
# These persistent open file descriptors are kept so the signal handler can do almost no work
# (and lets faulthandler figure out signal safety).
_pid_specific_error_fileobj = None
_shared_error_fileobj = None
def __new__(cls, *args, **kwargs):
raise TypeError('Instances of {} are not allowed to be constructed!'
.format(cls.__name__))
class ExceptionSinkError(Exception): pass
@classmethod
def reset_should_print_backtrace_to_terminal(cls, should_print_backtrace):
"""Set whether a backtrace gets printed to the terminal error stream on a fatal error.
Class state:
- Overwrites `cls._should_print_backtrace_to_terminal`.
"""
cls._should_print_backtrace_to_terminal = should_print_backtrace
# All reset_* methods are ~idempotent!
@classmethod
def reset_log_location(cls, new_log_location):
"""Re-acquire file handles to error logs based in the new location.
Class state:
- Overwrites `cls._log_dir`, `cls._pid_specific_error_fileobj`, and
`cls._shared_error_fileobj`.
OS state:
- May create a new directory.
- Overwrites signal handlers for many fatal and non-fatal signals (but not SIGUSR2).
:raises: :class:`ExceptionSink.ExceptionSinkError` if the directory does not exist or is not
writable.
"""
# We could no-op here if the log locations are the same, but there's no reason not to have the
# additional safety of re-acquiring file descriptors each time (and erroring out early if the
# location is no longer writable).
# Create the directory if possible, or raise if not writable.
cls._check_or_create_new_destination(new_log_location)
pid_specific_error_stream, shared_error_stream = cls._recapture_fatal_error_log_streams(
new_log_location)
# NB: mutate process-global state!
if faulthandler.is_enabled():
logger.debug('re-enabling faulthandler')
# Call Py_CLEAR() on the previous error stream:
# https://github.com/vstinner/faulthandler/blob/master/faulthandler.c
faulthandler.disable()
# Send a stacktrace to this file if interrupted by a fatal error.
faulthandler.enable(file=pid_specific_error_stream, all_threads=True)
# NB: mutate the class variables!
cls._log_dir = new_log_location
cls._pid_specific_error_fileobj = pid_specific_error_stream
cls._shared_error_fileobj = shared_error_stream
class AccessGlobalExiterMixin:
@property
def _exiter(self) -> Optional[Exiter]:
return ExceptionSink.get_global_exiter()
@classmethod
def get_global_exiter(cls) -> Optional[Exiter]:
return cls._exiter
@classmethod
@contextmanager
def exiter_as(cls, new_exiter_fun: Callable[[Optional[Exiter]], Exiter]) -> Iterator[None]:
"""Temporarily override the global exiter.
NB: We don't want to try/finally here, because we want exceptions to propagate
with the most recent exiter installed in sys.excepthook.
If we wrap this in a try:finally, exceptions will be caught and exiters unset.
"""
previous_exiter = cls._exiter
new_exiter = new_exiter_fun(previous_exiter)
cls._reset_exiter(new_exiter)
yield
cls._reset_exiter(previous_exiter)
@classmethod
@contextmanager
def exiter_as_until_exception(
cls, new_exiter_fun: Callable[[Optional[Exiter]], Exiter]
) -> Iterator[None]:
"""Temporarily override the global exiter, except this will unset it when an exception happens."""
previous_exiter = cls._exiter
new_exiter = new_exiter_fun(previous_exiter)
try:
cls._reset_exiter(new_exiter)
yield
finally:
cls._reset_exiter(previous_exiter)
@classmethod
def _reset_exiter(cls, exiter: Optional[Exiter]) -> None:
"""
Class state:
- Overwrites `cls._exiter`.
Python state:
- Overwrites sys.excepthook.
"""
logger.debug(f"overriding the global exiter with {exiter} (from {cls._exiter})")
# NB: mutate the class variables! This is done before mutating the exception hook, because the
# uncaught exception handler uses cls._exiter to exit.
cls._exiter = exiter
# NB: mutate process-global state!
sys.excepthook = cls._log_unhandled_exception_and_exit
@classmethod
def reset_interactive_output_stream(
cls,
interactive_output_stream,
override_faulthandler_destination=True
):
"""
Class state:
- Overwrites `cls._interactive_output_stream`.
OS state:
- Overwrites the SIGUSR2 handler.
This method registers a SIGUSR2 handler, which permits a non-fatal `kill -31 <pants pid>` for
stacktrace retrieval. This is also where the the error message on fatal exit will be printed to.
"""
try:
# NB: mutate process-global state!
# This permits a non-fatal `kill -31 <pants pid>` for stacktrace retrieval.
if override_faulthandler_destination:
faulthandler.register(signal.SIGUSR2, interactive_output_stream,
all_threads=True, chain=False)
# NB: mutate the class variables!
cls._interactive_output_stream = interactive_output_stream
except ValueError:
# Warn about "ValueError: IO on closed file" when the stream is closed.
cls.log_exception(
"Cannot reset interactive_output_stream -- stream (probably stderr) is closed")
@classmethod
def exceptions_log_path(cls, for_pid=None, in_dir=None):
"""Get the path to either the shared or pid-specific fatal errors log file."""
if for_pid is None:
intermediate_filename_component = ''
else:
assert isinstance(for_pid, Pid)
intermediate_filename_component = '.{}'.format(for_pid)
in_dir = in_dir or cls._log_dir
return os.path.join(
in_dir,
'.pids',
'exceptions{}.log'.format(intermediate_filename_component))
@classmethod
def log_exception(cls, msg):
"""Try to log an error message to this process's error log and the shared error log.
NB: Doesn't raise (logs an error instead).
"""
pid = os.getpid()
fatal_error_log_entry = cls._format_exception_message(msg, pid)
# We care more about this log than the shared log, so write to it first.
try:
cls._try_write_with_flush(cls._pid_specific_error_fileobj, fatal_error_log_entry)
except Exception as e:
logger.error(
"Error logging the message '{}' to the pid-specific file handle for {} at pid {}:\n{}"
.format(msg, cls._log_dir, pid, e))
# Write to the shared log.
try:
# TODO: we should probably guard this against concurrent modification by other pants
# subprocesses somehow.
cls._try_write_with_flush(cls._shared_error_fileobj, fatal_error_log_entry)
except Exception as e:
logger.error(
"Error logging the message '{}' to the shared file handle for {} at pid {}:\n{}"
.format(msg, cls._log_dir, pid, e))
@classmethod
def _try_write_with_flush(cls, fileobj, payload):
"""This method is here so that it can be patched to simulate write errors.
This is because mock can't patch primitive objects like file objects.
"""
fileobj.write(payload)
fileobj.flush()
@classmethod
def _check_or_create_new_destination(cls, destination):
try:
safe_mkdir(destination)
except Exception as e:
raise cls.ExceptionSinkError(
"The provided exception sink path at '{}' is not writable or could not be created: {}."
.format(destination, str(e)),
e)
@classmethod
def _recapture_fatal_error_log_streams(cls, new_log_location):
# NB: We do not close old file descriptors under the assumption their lifetimes are managed
# elsewhere.
# We recapture both log streams each time.
pid = os.getpid()
pid_specific_log_path = cls.exceptions_log_path(for_pid=pid, in_dir=new_log_location)
shared_log_path = cls.exceptions_log_path(in_dir=new_log_location)
assert pid_specific_log_path != shared_log_path
try:
# Truncate the pid-specific error log file.
pid_specific_error_stream = safe_open(pid_specific_log_path, mode='w')
# Append to the shared error file.
shared_error_stream = safe_open(shared_log_path, mode='a')
except Exception as e:
raise cls.ExceptionSinkError(
"Error opening fatal error log streams for log location '{}': {}"
.format(new_log_location, str(e)))
return (pid_specific_error_stream, shared_error_stream)
@classmethod
def reset_signal_handler(cls, signal_handler):
"""
Class state:
- Overwrites `cls._signal_handler`.
OS state:
- Overwrites signal handlers for SIGINT, SIGQUIT, and SIGTERM.
NB: This method calls signal.signal(), which will crash if not called from the main thread!
:returns: The :class:`SignalHandler` that was previously registered, or None if this is
the first time this method was called.
"""
assert isinstance(signal_handler, SignalHandler)
# NB: Modify process-global state!
for signum, handler in signal_handler.signal_handler_mapping.items():
signal.signal(signum, handler)
# Retry any system calls interrupted by any of the signals we just installed handlers for
# (instead of having them raise EINTR). siginterrupt(3) says this is the default behavior on
# Linux and OSX.
signal.siginterrupt(signum, False)
previous_signal_handler = cls._signal_handler
# NB: Mutate the class variables!
cls._signal_handler = signal_handler
return previous_signal_handler
@classmethod
@contextmanager
def trapped_signals(cls, new_signal_handler):
"""
A contextmanager which temporarily overrides signal handling.
NB: This method calls signal.signal(), which will crash if not called from the main thread!
"""
previous_signal_handler = cls.reset_signal_handler(new_signal_handler)
try:
yield
finally:
cls.reset_signal_handler(previous_signal_handler)
@classmethod
@contextmanager
def ignoring_sigint(cls):
"""
A contextmanager which disables handling sigint in the current signal handler.
This allows threads that are not the main thread to ignore sigint.
NB: Only use this if you can't use ExceptionSink.trapped_signals().
Class state:
- Toggles `self._ignore_sigint` in `cls._signal_handler`.
"""
with cls._signal_handler._ignoring_sigint():
yield
@classmethod
def toggle_ignoring_sigint_v2_engine(cls, toggle: bool) -> None:
assert cls._signal_handler is not None
cls._signal_handler._toggle_ignoring_sigint_v2_engine(toggle)
@classmethod
def _iso_timestamp_for_now(cls):
return datetime.datetime.now().isoformat()
# NB: This includes a trailing newline, but no leading newline.
_EXCEPTION_LOG_FORMAT = """\
timestamp: {timestamp}
process title: {process_title}
sys.argv: {args}
pid: {pid}
{message}
"""
@classmethod
def _format_exception_message(cls, msg, pid):
return cls._EXCEPTION_LOG_FORMAT.format(
timestamp=cls._iso_timestamp_for_now(),
process_title=setproctitle.getproctitle(),
args=sys.argv,
pid=pid,
message=msg)
_traceback_omitted_default_text = '(backtrace omitted)'
@classmethod
def _format_traceback(cls, traceback_lines, should_print_backtrace):
if should_print_backtrace:
traceback_string = '\n{}'.format(''.join(traceback_lines))
else:
traceback_string = ' {}'.format(cls._traceback_omitted_default_text)
return traceback_string
_UNHANDLED_EXCEPTION_LOG_FORMAT = """\
Exception caught: ({exception_type}){backtrace}
Exception message: {exception_message}{maybe_newline}
"""
@classmethod
def _format_unhandled_exception_log(cls, exc, tb, add_newline, should_print_backtrace):
exc_type = type(exc)
exception_full_name = '{}.{}'.format(exc_type.__module__, exc_type.__name__)
exception_message = str(exc) if exc else '(no message)'
maybe_newline = '\n' if add_newline else ''
return cls._UNHANDLED_EXCEPTION_LOG_FORMAT.format(
exception_type=exception_full_name,
backtrace=cls._format_traceback(traceback_lines=traceback.format_tb(tb),
should_print_backtrace=should_print_backtrace),
exception_message=exception_message,
maybe_newline=maybe_newline)
_EXIT_FAILURE_TERMINAL_MESSAGE_FORMAT = """\
{timestamp_msg}{terminal_msg}{details_msg}
"""
@classmethod
def _exit_with_failure(cls, terminal_msg):
timestamp_msg = (f'timestamp: {cls._iso_timestamp_for_now()}\n'
if cls._should_print_backtrace_to_terminal else '')
details_msg = ('' if cls._should_print_backtrace_to_terminal
else '\n\n(Use --print-exception-stacktrace to see more error details.)')
terminal_msg = terminal_msg or '<no exit reason provided>'
formatted_terminal_msg = cls._EXIT_FAILURE_TERMINAL_MESSAGE_FORMAT.format(
timestamp_msg=timestamp_msg, terminal_msg=terminal_msg, details_msg=details_msg)
# Exit with failure, printing a message to the terminal (or whatever the interactive stream is).
cls._exiter.exit_and_fail(msg=formatted_terminal_msg, out=cls._interactive_output_stream)
@classmethod
def _log_unhandled_exception_and_exit(cls, exc_class=None, exc=None, tb=None, add_newline=False):
"""A sys.excepthook implementation which logs the error and exits with failure."""
exc_class = exc_class or sys.exc_info()[0]
exc = exc or sys.exc_info()[1]
tb = tb or sys.exc_info()[2]
# This exception was raised by a signal handler with the intent to exit the program.
if exc_class == SignalHandler.SignalHandledNonLocalExit:
return cls._handle_signal_gracefully(exc.signum, exc.signame, exc.traceback_lines)
extra_err_msg = None
try:
# Always output the unhandled exception details into a log file, including the traceback.
exception_log_entry = cls._format_unhandled_exception_log(exc, tb, add_newline,
should_print_backtrace=True)
cls.log_exception(exception_log_entry)
except Exception as e:
extra_err_msg = 'Additional error logging unhandled exception {}: {}'.format(exc, e)
logger.error(extra_err_msg)
# Generate an unhandled exception report fit to be printed to the terminal (respecting the
# Exiter's should_print_backtrace field).
if cls._should_print_backtrace_to_terminal:
stderr_printed_error = cls._format_unhandled_exception_log(
exc, tb, add_newline,
should_print_backtrace=cls._should_print_backtrace_to_terminal)
if extra_err_msg:
stderr_printed_error = '{}\n{}'.format(stderr_printed_error, extra_err_msg)
else:
# If the user didn't ask for a backtrace, show a succinct error message without
# all the exception-related preamble. A power-user/pants developer can still
# get all the preamble info along with the backtrace, but the end user shouldn't
# see that boilerplate by default.
error_msgs = getattr(exc, 'end_user_messages', lambda: [str(exc)])()
stderr_printed_error = '\n' + '\n'.join(f'ERROR: {msg}' for msg in error_msgs)
cls._exit_with_failure(stderr_printed_error)
_CATCHABLE_SIGNAL_ERROR_LOG_FORMAT = """\
Signal {signum} ({signame}) was raised. Exiting with failure.{formatted_traceback}
"""
@classmethod
def _handle_signal_gracefully(cls, signum, signame, traceback_lines):
"""Signal handler for non-fatal signals which raises or logs an error and exits with failure."""
# Extract the stack, and format an entry to be written to the exception log.
formatted_traceback = cls._format_traceback(traceback_lines=traceback_lines,
should_print_backtrace=True)
signal_error_log_entry = cls._CATCHABLE_SIGNAL_ERROR_LOG_FORMAT.format(
signum=signum,
signame=signame,
formatted_traceback=formatted_traceback)
# TODO: determine the appropriate signal-safe behavior here (to avoid writing to our file
# descriptors re-entrantly, which raises an IOError).
# This method catches any exceptions raised within it.
cls.log_exception(signal_error_log_entry)
# Create a potentially-abbreviated traceback for the terminal or other interactive stream.
formatted_traceback_for_terminal = cls._format_traceback(
traceback_lines=traceback_lines,
should_print_backtrace=cls._should_print_backtrace_to_terminal)
terminal_log_entry = cls._CATCHABLE_SIGNAL_ERROR_LOG_FORMAT.format(
signum=signum,
signame=signame,
formatted_traceback=formatted_traceback_for_terminal)
# Exit, printing the output to the terminal.
cls._exit_with_failure(terminal_log_entry)
# Setup global state such as signal handlers and sys.excepthook with probably-safe values at module
# import time.
# Set the log location for writing logs before bootstrap options are parsed.
ExceptionSink.reset_log_location(os.getcwd())
# Sets except hook for exceptions at import time.
ExceptionSink._reset_exiter(Exiter(exiter=sys.exit))
# Sets a SIGUSR2 handler.
ExceptionSink.reset_interactive_output_stream(sys.stderr.buffer)
# Sets a handler that logs nonfatal signals to the exception sink before exiting.
ExceptionSink.reset_signal_handler(SignalHandler())
# Set whether to print stacktraces on exceptions or signals during import time.
# NB: This will be overridden by bootstrap options in PantsRunner, so we avoid printing out a full
# stacktrace when a user presses control-c during import time unless the environment variable is set
# to explicitly request it. The exception log will have any stacktraces regardless so this should
# not hamper debugging.
ExceptionSink.reset_should_print_backtrace_to_terminal(
should_print_backtrace=os.environ.get('PANTS_PRINT_EXCEPTION_STACKTRACE', 'True') == 'True')
| []
| []
| [
"PANTS_PRINT_EXCEPTION_STACKTRACE"
]
| [] | ["PANTS_PRINT_EXCEPTION_STACKTRACE"] | python | 1 | 0 | |
app/delivery/send_to_providers.py | from datetime import datetime
import os
import urllib.request
import magic
import re
from flask import current_app
from notifications_utils.recipients import (
validate_and_format_phone_number,
validate_and_format_email_address
)
from notifications_utils.template import HTMLEmailTemplate, PlainTextEmailTemplate, SMSMessageTemplate
from app import clients, statsd_client, create_uuid
from app.dao.notifications_dao import (
dao_update_notification
)
from app.dao.provider_details_dao import (
get_provider_details_by_notification_type,
dao_toggle_sms_provider
)
from app.celery.research_mode_tasks import send_sms_response, send_email_response
from app.dao.templates_dao import dao_get_template_by_id
from app.exceptions import NotificationTechnicalFailureException, MalwarePendingException
from app.models import (
SMS_TYPE,
KEY_TYPE_TEST,
BRANDING_BOTH_EN,
BRANDING_BOTH_FR,
BRANDING_ORG_BANNER_NEW,
EMAIL_TYPE,
NOTIFICATION_TECHNICAL_FAILURE,
NOTIFICATION_VIRUS_SCAN_FAILED,
NOTIFICATION_CONTAINS_PII,
NOTIFICATION_SENDING,
NOTIFICATION_SENT,
)
from app.clients.mlwr.mlwr import check_mlwr_score
from app.utils import get_logo_url
def send_sms_to_provider(notification):
service = notification.service
if not service.active:
technical_failure(notification=notification)
return
if notification.status == 'created':
provider = provider_to_use(
SMS_TYPE,
notification.id,
notification.international,
notification.reply_to_text
)
template_model = dao_get_template_by_id(notification.template_id, notification.template_version)
template = SMSMessageTemplate(
template_model.__dict__,
values=notification.personalisation,
prefix=service.name,
show_prefix=service.prefix_sms,
)
if service.research_mode or notification.key_type == KEY_TYPE_TEST:
update_notification_to_sending(notification, provider)
send_sms_response(provider.get_name(), str(notification.id), notification.to)
else:
try:
reference = provider.send_sms(
to=validate_and_format_phone_number(notification.to, international=notification.international),
content=str(template),
reference=str(notification.id),
sender=notification.reply_to_text
)
except Exception as e:
notification.billable_units = template.fragment_count
dao_update_notification(notification)
dao_toggle_sms_provider(provider.name)
raise e
else:
notification.reference = reference
notification.billable_units = template.fragment_count
update_notification_to_sending(notification, provider)
delta_milliseconds = (datetime.utcnow() - notification.created_at).total_seconds() * 1000
statsd_client.timing("sms.total-time", delta_milliseconds)
def send_email_to_provider(notification):
service = notification.service
if not service.active:
technical_failure(notification=notification)
return
if notification.status == 'created':
provider = provider_to_use(EMAIL_TYPE, notification.id)
# Extract any file objects from the personalization
file_keys = [
k for k, v in (notification.personalisation or {}).items() if isinstance(v, dict) and 'document' in v
]
attachments = []
personalisation_data = notification.personalisation.copy()
for key in file_keys:
# Check if a MLWR sid exists
if (current_app.config["MLWR_HOST"] and
'mlwr_sid' in personalisation_data[key]['document'] and
personalisation_data[key]['document']['mlwr_sid'] != "false"):
mlwr_result = check_mlwr(personalisation_data[key]['document']['mlwr_sid'])
if "state" in mlwr_result and mlwr_result["state"] == "completed":
# Update notification that it contains malware
if "submission" in mlwr_result and mlwr_result["submission"]['max_score'] >= 500:
malware_failure(notification=notification)
return
else:
# Throw error so celery will retry in sixty seconds
raise MalwarePendingException
try:
req = urllib.request.Request(personalisation_data[key]['document']['direct_file_url'])
with urllib.request.urlopen(req) as response:
buffer = response.read()
mime_type = magic.from_buffer(buffer, mime=True)
if mime_type == 'application/pdf':
attachments.append({"name": "{}.pdf".format(key), "data": buffer})
except Exception:
current_app.logger.error(
"Could not download and attach {}".format(personalisation_data[key]['document']['direct_file_url'])
)
personalisation_data[key] = personalisation_data[key]['document']['url']
template_dict = dao_get_template_by_id(notification.template_id, notification.template_version).__dict__
# Local Jinja support - Add USE_LOCAL_JINJA_TEMPLATES=True to .env
# Add a folder to the project root called 'jinja_templates'
# with a copy of 'email_template.jinja2' from notification-utils repo
debug_template_path = (os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if os.environ.get('USE_LOCAL_JINJA_TEMPLATES') == 'True' else None)
html_email = HTMLEmailTemplate(
template_dict,
values=personalisation_data,
jinja_path=debug_template_path,
**get_html_email_options(service)
)
plain_text_email = PlainTextEmailTemplate(
template_dict,
values=personalisation_data
)
if current_app.config["SCAN_FOR_PII"]:
contains_pii(notification, str(plain_text_email))
if service.research_mode or notification.key_type == KEY_TYPE_TEST:
notification.reference = str(create_uuid())
update_notification_to_sending(notification, provider)
send_email_response(notification.reference, notification.to)
else:
if service.sending_domain is None or service.sending_domain.strip() == "":
sending_domain = current_app.config['NOTIFY_EMAIL_DOMAIN']
else:
sending_domain = service.sending_domain
from_address = '"{}" <{}@{}>'.format(service.name, service.email_from,
sending_domain)
email_reply_to = notification.reply_to_text
reference = provider.send_email(
from_address,
validate_and_format_email_address(notification.to),
plain_text_email.subject,
body=str(plain_text_email),
html_body=str(html_email),
reply_to_address=validate_and_format_email_address(email_reply_to) if email_reply_to else None,
attachments=attachments
)
notification.reference = reference
update_notification_to_sending(notification, provider)
delta_milliseconds = (datetime.utcnow() - notification.created_at).total_seconds() * 1000
statsd_client.timing("email.total-time", delta_milliseconds)
def update_notification_to_sending(notification, provider):
notification.sent_at = datetime.utcnow()
notification.sent_by = provider.get_name()
notification.status = NOTIFICATION_SENT if notification.notification_type == "sms" else NOTIFICATION_SENDING
dao_update_notification(notification)
def provider_to_use(notification_type, notification_id, international=False, sender=None):
active_providers_in_order = [
p for p in get_provider_details_by_notification_type(notification_type, international) if p.active
]
if not active_providers_in_order:
current_app.logger.error(
"{} {} failed as no active providers".format(notification_type, notification_id)
)
raise Exception("No active {} providers".format(notification_type))
return clients.get_client_by_name_and_type(active_providers_in_order[0].identifier, notification_type)
def get_html_email_options(service):
if service.email_branding is None:
if service.default_branding_is_french is True:
return {
'fip_banner_english': False,
'fip_banner_french': True,
'logo_with_background_colour': False,
}
else:
return {
'fip_banner_english': True,
'fip_banner_french': False,
'logo_with_background_colour': False,
}
logo_url = get_logo_url(
service.email_branding.logo
) if service.email_branding.logo else None
return {
'fip_banner_english': service.email_branding.brand_type == BRANDING_BOTH_EN,
'fip_banner_french': service.email_branding.brand_type == BRANDING_BOTH_FR,
'logo_with_background_colour': service.email_branding.brand_type == BRANDING_ORG_BANNER_NEW,
'brand_colour': service.email_branding.colour,
'brand_logo': logo_url,
'brand_text': service.email_branding.text,
'brand_name': service.email_branding.name,
}
def technical_failure(notification):
notification.status = NOTIFICATION_TECHNICAL_FAILURE
dao_update_notification(notification)
raise NotificationTechnicalFailureException(
"Send {} for notification id {} to provider is not allowed: service {} is inactive".format(
notification.notification_type,
notification.id,
notification.service_id))
def malware_failure(notification):
notification.status = NOTIFICATION_VIRUS_SCAN_FAILED
dao_update_notification(notification)
raise NotificationTechnicalFailureException(
"Send {} for notification id {} to provider is not allowed. Notification contains malware".format(
notification.notification_type,
notification.id))
def check_mlwr(sid):
return check_mlwr_score(sid)
def contains_pii(notification, text_content):
for sin in re.findall(r'\s\d{3}-\d{3}-\d{3}\s', text_content):
if luhn(sin.replace("-", "").strip()):
fail_pii(notification, "Social Insurance Number")
return
def fail_pii(notification, pii_type):
notification.status = NOTIFICATION_CONTAINS_PII
dao_update_notification(notification)
raise NotificationTechnicalFailureException(
"Send {} for notification id {} to provider is not allowed. Notification contains PII: {}".format(
notification.notification_type,
notification.id,
pii_type))
def luhn(n):
r = [int(ch) for ch in n][::-1]
return (sum(r[0::2]) + sum(sum(divmod(d * 2, 10)) for d in r[1::2])) % 10 == 0
| []
| []
| [
"USE_LOCAL_JINJA_TEMPLATES"
]
| [] | ["USE_LOCAL_JINJA_TEMPLATES"] | python | 1 | 0 | |
samples/python/80.skills-simple-bot-to-bot/simple-root-bot/app.py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import sys
import traceback
from datetime import datetime
from aiohttp import web
from aiohttp.web import Request, Response
from botbuilder.core import (
BotFrameworkAdapterSettings,
ConversationState,
MemoryStorage,
TurnContext,
BotFrameworkAdapter,
)
from botbuilder.core.integration import (
aiohttp_channel_service_routes,
aiohttp_error_middleware,
)
from botbuilder.core.skills import SkillHandler
from botbuilder.schema import Activity, ActivityTypes
from botframework.connector.auth import (
AuthenticationConfiguration,
SimpleCredentialProvider,
)
from bots.root_bot import ACTIVE_SKILL_PROPERTY_NAME
from skill_http_client import SkillHttpClient
from skill_conversation_id_factory import SkillConversationIdFactory
from authentication import AllowedSkillsClaimsValidator
from bots import RootBot
from config import DefaultConfig, SkillConfiguration
CONFIG = DefaultConfig()
SKILL_CONFIG = SkillConfiguration()
# Whitelist skills from SKILL_CONFIG
ALLOWED_CALLER_IDS = {s.app_id for s in [*SKILL_CONFIG.SKILLS.values()]}
CLAIMS_VALIDATOR = AllowedSkillsClaimsValidator(ALLOWED_CALLER_IDS)
AUTH_CONFIG = AuthenticationConfiguration(
claims_validator=CLAIMS_VALIDATOR.validate_claims
)
# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
SETTINGS = BotFrameworkAdapterSettings(
app_id=CONFIG.APP_ID,
app_password=CONFIG.APP_PASSWORD,
auth_configuration=AUTH_CONFIG,
)
ADAPTER = BotFrameworkAdapter(SETTINGS)
STORAGE = MemoryStorage()
CONVERSATION_STATE = ConversationState(STORAGE)
ID_FACTORY = SkillConversationIdFactory(STORAGE)
CREDENTIAL_PROVIDER = SimpleCredentialProvider(CONFIG.APP_ID, CONFIG.APP_PASSWORD)
CLIENT = SkillHttpClient(CREDENTIAL_PROVIDER, ID_FACTORY)
# Catch-all for errors.
async def on_error(context: TurnContext, error: Exception):
# This check writes out errors to console log .vs. app insights.
# NOTE: In production environment, you should consider logging this to Azure
# application insights.
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
traceback.print_exc()
# Send a message to the user
await context.send_activity("The bot encountered an error or bug.")
await context.send_activity(
"To continue to run this bot, please fix the bot source code."
)
# Send a trace activity if we're talking to the Bot Framework Emulator
if context.activity.channel_id == "emulator":
# Create a trace activity that contains the error object
trace_activity = Activity(
label="TurnError",
name="on_turn_error Trace",
timestamp=datetime.utcnow(),
type=ActivityTypes.trace,
value=f"{error}",
value_type="https://www.botframework.com/schemas/error",
)
await context.send_activity(trace_activity)
# Inform the active skill that the conversation is ended so that it has
# a chance to clean up.
# Note: ActiveSkillPropertyName is set by the RooBot while messages are being
# forwarded to a Skill.
active_skill_id = await CONVERSATION_STATE.create_property(ACTIVE_SKILL_PROPERTY_NAME).get(context)
if active_skill_id:
end_of_conversation = Activity(
type=ActivityTypes.end_of_conversation, code="RootSkillError"
)
TurnContext.apply_conversation_reference(
end_of_conversation,
TurnContext.get_conversation_reference(context.activity),
is_incoming=True
)
await CONVERSATION_STATE.save_changes(context, True)
await CLIENT.post_activity(
CONFIG.APP_ID,
SKILL_CONFIG.SKILLS[active_skill_id],
SKILL_CONFIG.SKILL_HOST_ENDPOINT,
end_of_conversation,
)
# Clear out state
await CONVERSATION_STATE.delete(context)
ADAPTER.on_turn_error = on_error
# Create the Bot
BOT = RootBot(CONVERSATION_STATE, SKILL_CONFIG, CLIENT, CONFIG)
SKILL_HANDLER = SkillHandler(
ADAPTER, BOT, ID_FACTORY, CREDENTIAL_PROVIDER, AuthenticationConfiguration()
)
# Listen for incoming requests on /api/messages
async def messages(req: Request) -> Response:
# Main bot message handler.
if "application/json" in req.headers["Content-Type"]:
body = await req.json()
else:
return Response(status=415)
activity = Activity().deserialize(body)
auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
try:
await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
return Response(status=201)
except Exception as exception:
raise exception
APP = web.Application(middlewares=[aiohttp_error_middleware])
APP.router.add_post("/api/messages", messages)
APP.router.add_routes(aiohttp_channel_service_routes(SKILL_HANDLER, "/api/skills"))
if __name__ == "__main__":
try:
web.run_app(APP, host="localhost", port=CONFIG.PORT)
except Exception as error:
raise error
| []
| []
| []
| [] | [] | python | null | null | null |
scout/server/app.py | """Code for flask app"""
import logging
import re
import coloredlogs
from flask import Flask, current_app, redirect, request, url_for
from flask_babel import Babel
from flask_cors import CORS
from flask_login import current_user
from flaskext.markdown import Markdown
from . import extensions
from .blueprints import (
alignviewers,
api,
cases,
dashboard,
diagnoses,
genes,
institutes,
login,
managed_variants,
panels,
phenotypes,
public,
variant,
variants,
)
try:
from urllib.parse import unquote
except ImportError:
from urllib2 import unquote
LOG = logging.getLogger(__name__)
try:
from chanjo_report.server.app import configure_template_filters
from chanjo_report.server.blueprints import report_bp
from chanjo_report.server.extensions import api as chanjo_api
except ImportError:
chanjo_api = None
report_bp = None
configure_template_filters = None
LOG.info("chanjo report not installed!")
def create_app(config_file=None, config=None):
"""Flask app factory function."""
app = Flask(__name__)
CORS(app)
app.jinja_env.add_extension("jinja2.ext.do")
app.config.from_pyfile("config.py") # Load default config file
if (
config
): # Params from an optional .yaml config file provided by the user or created by the app cli
app.config.update((k, v) for k, v in config.items() if v is not None)
if config_file: # Params from an optional .py config file provided by the user
app.config.from_pyfile(config_file)
app.config["JSON_SORT_KEYS"] = False
current_log_level = LOG.getEffectiveLevel()
coloredlogs.install(level="DEBUG" if app.debug else current_log_level)
configure_extensions(app)
register_blueprints(app)
register_filters(app)
if not (app.debug or app.testing) and app.config.get("MAIL_USERNAME"):
# setup email logging of errors
configure_email_logging(app)
@app.before_request
def check_user():
if not app.config.get("LOGIN_DISABLED") and request.endpoint:
# check if the endpoint requires authentication
static_endpoint = "static" in request.endpoint or request.endpoint in [
"report.report",
"report.json_chrom_coverage",
]
public_endpoint = getattr(app.view_functions[request.endpoint], "is_public", False)
relevant_endpoint = not (static_endpoint or public_endpoint)
# if endpoint requires auth, check if user is authenticated
if relevant_endpoint and not current_user.is_authenticated:
# combine visited URL (convert byte string query string to unicode!)
next_url = "{}?{}".format(request.path, request.query_string.decode())
login_url = url_for("public.index", next=next_url)
return redirect(login_url)
return app
def configure_extensions(app):
"""Configure Flask extensions."""
extensions.toolbar.init_app(app)
extensions.bootstrap.init_app(app)
extensions.mongo.init_app(app)
extensions.store.init_app(app)
extensions.login_manager.init_app(app)
extensions.mail.init_app(app)
Markdown(app)
if app.config.get("SQLALCHEMY_DATABASE_URI"):
LOG.info("Chanjo extension enabled")
configure_coverage(app)
if app.config.get("LOQUSDB_SETTINGS"):
LOG.info("LoqusDB enabled")
# setup LoqusDB
extensions.loqusdb.init_app(app)
if app.config.get("GENS_HOST"):
LOG.info("Gens enabled")
extensions.gens.init_app(app)
if all(
[
app.config.get("MME_URL"),
app.config.get("MME_ACCEPTS"),
app.config.get("MME_TOKEN"),
]
):
LOG.info("MatchMaker Exchange enabled")
extensions.matchmaker.init_app(app)
if app.config.get("RERUNNER_API_ENTRYPOINT") and app.config.get("RERUNNER_API_KEY"):
LOG.info("Rerunner service enabled")
# setup rerunner service
extensions.rerunner.init_app(app)
if app.config.get("LDAP_HOST"):
LOG.info("LDAP login enabled")
# setup connection to server
extensions.ldap_manager.init_app(app)
if app.config.get("GOOGLE"):
LOG.info("Google login enabled")
# setup connection to google oauth2
configure_oauth_login(app)
if app.config.get("CLOUD_IGV_TRACKS"):
LOG.info("Collecting IGV tracks from cloud resources")
extensions.cloud_tracks.init_app(app)
def register_blueprints(app):
"""Register Flask blueprints."""
app.register_blueprint(public.public_bp)
app.register_blueprint(genes.genes_bp)
app.register_blueprint(cases.cases_bp)
app.register_blueprint(login.login_bp)
app.register_blueprint(variant.variant_bp)
app.register_blueprint(variants.variants_bp)
app.register_blueprint(panels.panels_bp)
app.register_blueprint(dashboard.dashboard_bp)
app.register_blueprint(api.api_bp)
app.register_blueprint(alignviewers.alignviewers_bp)
app.register_blueprint(phenotypes.hpo_bp)
app.register_blueprint(diagnoses.omim_bp)
app.register_blueprint(institutes.overview)
app.register_blueprint(managed_variants.managed_variants_bp)
def register_filters(app):
@app.template_filter()
def human_decimal(number, ndigits=4):
"""Return a standard representation of a decimal number.
Args:
number (float): number to humanize
ndigits (int, optional): max number of digits to round to
Return:
str: humanized string of the decimal number
"""
min_number = 10 ** -ndigits
if isinstance(number, str):
number = None
if number is None:
# NaN
return "-"
if number == 0:
# avoid confusion over what is rounded and what is actually 0
return 0
if number < min_number:
# make human readable and sane
return "< {}".format(min_number)
# round all other numbers
return round(number, ndigits)
@app.template_filter()
def url_decode(string):
"""Decode a string with encoded hex values."""
return unquote(string)
@app.template_filter()
def cosmic_prefix(cosmicId):
"""If cosmicId is an integer, add 'COSM' as prefix
otherwise return unchanged"""
if isinstance(cosmicId, int):
return "COSM" + str(cosmicId)
return cosmicId
@app.template_filter()
def count_cursor(pymongo_cursor):
"""Count numer of returned documents (deprecated pymongo.cursor.count())"""
# Perform operations on a copy of the cursor so original does not move
cursor_copy = pymongo_cursor.clone()
return len(list(cursor_copy))
def configure_oauth_login(app):
"""Register the Google Oauth login client using config settings"""
google_conf = app.config["GOOGLE"]
discovery_url = google_conf.get("discovery_url")
client_id = google_conf.get("client_id")
client_secret = google_conf.get("client_secret")
extensions.oauth_client.init_app(app)
extensions.oauth_client.register(
name="google",
server_metadata_url=discovery_url,
client_id=client_id,
client_secret=client_secret,
client_kwargs={"scope": "openid email profile"},
)
def configure_email_logging(app):
"""Setup logging of error/exceptions to email."""
import logging
from scout.log import TlsSMTPHandler
mail_handler = TlsSMTPHandler(
mailhost=app.config["MAIL_SERVER"],
fromaddr=app.config["MAIL_USERNAME"],
toaddrs=app.config["ADMINS"],
subject="O_ops... {} failed!".format(app.name),
credentials=(app.config["MAIL_USERNAME"], app.config["MAIL_PASSWORD"]),
)
mail_handler.setLevel(logging.ERROR)
mail_handler.setFormatter(
logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s: %(message)s " "[in %(pathname)s:%(lineno)d]"
)
)
app.logger.addHandler(mail_handler)
def configure_coverage(app):
"""Setup coverage related extensions."""
# setup chanjo report
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True if app.debug else False
if chanjo_api:
chanjo_api.init_app(app)
configure_template_filters(app)
# register chanjo report blueprint
app.register_blueprint(report_bp, url_prefix="/reports")
babel = Babel(app)
@babel.localeselector
def get_locale():
"""Determine locale to use for translations."""
accept_languages = current_app.config.get("ACCEPT_LANGUAGES", ["en"])
# first check request args
session_language = request.args.get("lang")
if session_language in accept_languages:
current_app.logger.info("using session language: %s", session_language)
return session_language
# language can be forced in config
user_language = current_app.config.get("REPORT_LANGUAGE")
if user_language:
return user_language
# try to guess the language from the user accept header that
# the browser transmits. We support de/fr/en in this example.
# The best match wins.
return request.accept_languages.best_match(accept_languages)
| []
| []
| []
| [] | [] | python | null | null | null |
deployer/src/helpdesk_helper.py | import os
import re
import json
from . import helpers
from ratelimit import rate_limited
def get_helpscout_api_key():
hs_api_key = os.environ.get('HELP_SCOUT_API_KEY')
if not hs_api_key:
raise ValueError("None HELP_SCOUT_API_KEY from environment variables")
return hs_api_key
def is_helpdesk_url(u):
return 'secure.helpscout.net/conversation'in u
def get_conversation_ID_from_url(hs_url):
capture_conversation_uid = re.compile('.+/conversation/(\d+)/.*')
cuid = capture_conversation_uid.match(hs_url).group(1)
if not len(cuid) > 0:
raise ValueError("Wrong help scout url " + hs_url + ", must have a conversation sub part with ID")
if not RepresentsInt(cuid):
raise ValueError("Conversation ID : " + cuid + " must be an integer")
return cuid
def get_conversation(cuid):
conversation_endpoint = "https://api.helpscout.net/v1/conversations/" + cuid + ".json"
hs_api_key=get_helpscout_api_key()
response_json = json.loads(helpers.make_request(conversation_endpoint,
username = hs_api_key,
password = "X"))
conversation = response_json.get('item')
if not conversation:
raise ValueError("Wrong json returned from help scout, must have an item attribute")
return conversation
def get_start_url_from_conversation(conversation):
if not conversation or not conversation.get('threads')[-1]:
raise ValueError("Wrong input conversation, must be not evaluate at None and have at least one thread")
# The message to extract is the first from the thread and it was sent by a customer
first_thread = conversation.get('threads')[-1]
was_sent_by_customer = first_thread.get('createdByCustomer')
url_from_conversation = first_thread.get('body')
if not len(url_from_conversation):
raise ValueError("First thread from the conversation thread is empty")
if not was_sent_by_customer:
raise ValueError("First thread from the conversation thread wasn't sent by customer")
print "URL fetched is \033[1;36m" + url_from_conversation + "\033[0m sent by \033[1;33m" + first_thread.get("customer").get("email") + "\033[0m"
return url_from_conversation
def get_emails_from_conversation(conversation):
emails=[]
if not conversation or not conversation.get('threads')[-1]:
raise ValueError("Wrong input conversation, must be not evaluate at None and have at least one thread")
# Extract customer
customer = conversation.get('customer')
customers_mail = customer.get('email')
first_thread = conversation.get('threads')[-1]
was_sent_by_customer = first_thread.get('createdByCustomer')
if not was_sent_by_customer:
raise ValueError("First thread from the conversation thread wasn't sent by customer")
emails.append(customers_mail)
cc=conversation.get('cc')
if cc:
emails=emails+cc
bcc=conversation.get('bcc')
if bcc:
emails=emails+bcc
if len(emails) > 1:
print "Conversation sent by \033[1;33m" + customers_mail + "\033[0m" + (" with " + " ".join(emails[1:]))
return emails
def add_note(cuid, body):
conversation_endpoint = "https://api.helpscout.net/v1/conversations/" + cuid + ".json"
hs_api_key=get_helpscout_api_key()
# Inserting HTML code into HTML mail, snippet need to be HTML escaped
body = body.replace('<', '<').replace('>', '>').replace('\n', '<br/>').replace(' ', ' ')
response=helpers.make_request(conversation_endpoint,
json_request=True,
data={ "createdBy":
{ "id": "75881", "type": "user" },
"type": "note",
"body": body },
username=hs_api_key,
password="X",
type='POST')
return response
def get_conversation_url_from_cuid(cuid):
if not cuid :
raise ValueError("Wrong input conversation ID")
return "https://secure.helpscout.net/conversation/"+cuid
def is_docusaurus_conversation(conversation):
return "docusaurus" in conversation.get("tags")
@rate_limited(200,60)
def search(query, page=1, pageSize=50, sortField="modifiedAt", sortOrder="asc"):
search_endpoint = "https://api.helpscout.net/v1/search/conversations.json"
hs_api_key = get_helpscout_api_key()
response_json = json.loads(helpers.make_request(search_endpoint,
username = hs_api_key,
password = "X",
data = {
"query" : query,
"page" : page,
"pageSize" : pageSize,
"sortField" : sortField,
"sortOrder" : sortOrder
},
json_request=True)
)
return response_json
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
| []
| []
| [
"HELP_SCOUT_API_KEY"
]
| [] | ["HELP_SCOUT_API_KEY"] | python | 1 | 0 | |
src/urlscanio/__main__.py | import asyncio
import os
import platform
from pathlib import Path
from . import urlscan, utils
def main():
parser = utils.create_arg_parser()
args = parser.parse_args()
utils.validate_arguments(args)
api_key = os.environ["URLSCAN_API_KEY"]
data_dir = Path(os.getenv("URLSCAN_DATA_DIR", "."))
log_level = utils.convert_int_to_logging_level(args.verbose)
utils.create_data_dir(data_dir)
# See https://github.com/iojw/socialscan/issues/13
if platform.system() == "Windows":
asyncio.set_event_loop_policy(policy=asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(execute(args, api_key, data_dir, log_level))
async def execute(args, api_key, data_dir, log_level):
async with urlscan.UrlScan(api_key=api_key, data_dir=data_dir, log_level=log_level) as url_scan:
if args.investigate:
investigation_result = await url_scan.investigate(args.investigate, args.private)
if investigation_result == {}:
print("\nInvestigation failed. Please try again later.")
else:
if investigation_result.keys() >= {"report", "screenshot", "dom"}:
print(f"\nScan report URL:\t\t{investigation_result['report']}")
print(f"Screenshot download location:\t{investigation_result['screenshot']}")
print(f"DOM download location:\t\t{investigation_result['dom']}\n")
elif args.retrieve:
retrieve_result = await url_scan.fetch_result(args.retrieve)
print(f"\nScan report URL:\t\t{retrieve_result['report']}")
print(f"Screenshot download location:\t{retrieve_result['screenshot']}")
print(f"DOM download location:\t\t{retrieve_result['dom']}\n")
elif args.submit:
scan_uuid = await url_scan.submit_scan_request(args.submit, args.private)
if scan_uuid == "":
print(f"\nFailed to submit scan request for {args.submit}. Please try again later.\n")
else:
print(f"\nScan UUID:\t\t{scan_uuid}\n")
elif args.batch_investigate:
await url_scan.batch_investigate(args.batch_investigate, args.private)
print(f"Investigation outputs written to {Path(args.batch_investigate).stem}.csv")
| []
| []
| [
"URLSCAN_API_KEY",
"URLSCAN_DATA_DIR"
]
| [] | ["URLSCAN_API_KEY", "URLSCAN_DATA_DIR"] | python | 2 | 0 | |
gcc-gcc-7_3_0-release/libgo/go/cmd/cgo/main.go | // Copyright 2009 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.
// Cgo; see gmp.go for an overview.
// TODO(rsc):
// Emit correct line number annotations.
// Make gc understand the annotations.
package main
import (
"crypto/md5"
"flag"
"fmt"
"go/ast"
"go/printer"
"go/token"
"io"
"os"
"path/filepath"
"reflect"
"runtime"
"sort"
"strings"
)
// A Package collects information about the package we're going to write.
type Package struct {
PackageName string // name of package
PackagePath string
PtrSize int64
IntSize int64
GccOptions []string
GccIsClang bool
CgoFlags map[string][]string // #cgo flags (CFLAGS, LDFLAGS)
Written map[string]bool
Name map[string]*Name // accumulated Name from Files
ExpFunc []*ExpFunc // accumulated ExpFunc from Files
Decl []ast.Decl
GoFiles []string // list of Go files
GccFiles []string // list of gcc output files
Preamble string // collected preamble for _cgo_export.h
}
// A File collects information about a single Go input file.
type File struct {
AST *ast.File // parsed AST
Comments []*ast.CommentGroup // comments from file
Package string // Package name
Preamble string // C preamble (doc comment on import "C")
Ref []*Ref // all references to C.xxx in AST
Calls []*Call // all calls to C.xxx in AST
ExpFunc []*ExpFunc // exported functions for this file
Name map[string]*Name // map from Go name to Name
}
func nameKeys(m map[string]*Name) []string {
var ks []string
for k := range m {
ks = append(ks, k)
}
sort.Strings(ks)
return ks
}
// A Call refers to a call of a C.xxx function in the AST.
type Call struct {
Call *ast.CallExpr
Deferred bool
}
// A Ref refers to an expression of the form C.xxx in the AST.
type Ref struct {
Name *Name
Expr *ast.Expr
Context string // "type", "expr", "call", or "call2"
}
func (r *Ref) Pos() token.Pos {
return (*r.Expr).Pos()
}
// A Name collects information about C.xxx.
type Name struct {
Go string // name used in Go referring to package C
Mangle string // name used in generated Go
C string // name used in C
Define string // #define expansion
Kind string // "const", "type", "var", "fpvar", "func", "not-type"
Type *Type // the type of xxx
FuncType *FuncType
AddError bool
Const string // constant definition
}
// IsVar reports whether Kind is either "var" or "fpvar"
func (n *Name) IsVar() bool {
return n.Kind == "var" || n.Kind == "fpvar"
}
// A ExpFunc is an exported function, callable from C.
// Such functions are identified in the Go input file
// by doc comments containing the line //export ExpName
type ExpFunc struct {
Func *ast.FuncDecl
ExpName string // name to use from C
Doc string
}
// A TypeRepr contains the string representation of a type.
type TypeRepr struct {
Repr string
FormatArgs []interface{}
}
// A Type collects information about a type in both the C and Go worlds.
type Type struct {
Size int64
Align int64
C *TypeRepr
Go ast.Expr
EnumValues map[string]int64
Typedef string
}
// A FuncType collects information about a function type in both the C and Go worlds.
type FuncType struct {
Params []*Type
Result *Type
Go *ast.FuncType
}
func usage() {
fmt.Fprint(os.Stderr, "usage: cgo -- [compiler options] file.go ...\n")
flag.PrintDefaults()
os.Exit(2)
}
var ptrSizeMap = map[string]int64{
"386": 4,
"alpha": 8,
"amd64": 8,
"arm": 4,
"arm64": 8,
"m68k": 4,
"mips": 4,
"mipsle": 4,
"mips64": 8,
"mips64le": 8,
"mips64p32": 4,
"mips64p32le": 4,
"ppc": 4,
"ppc64": 8,
"ppc64le": 8,
"s390": 4,
"s390x": 8,
"sparc": 4,
"sparc64": 8,
}
var intSizeMap = map[string]int64{
"386": 4,
"alpha": 8,
"amd64": 8,
"arm": 4,
"arm64": 8,
"m68k": 4,
"mips": 4,
"mipsle": 4,
"mips64": 8,
"mips64le": 8,
"mips64p32": 8,
"mips64p32le": 8,
"ppc": 4,
"ppc64": 8,
"ppc64le": 8,
"s390": 4,
"s390x": 8,
"sparc": 4,
"sparc64": 8,
}
var cPrefix string
var fset = token.NewFileSet()
var dynobj = flag.String("dynimport", "", "if non-empty, print dynamic import data for that file")
var dynout = flag.String("dynout", "", "write -dynimport output to this file")
var dynpackage = flag.String("dynpackage", "main", "set Go package for -dynimport output")
var dynlinker = flag.Bool("dynlinker", false, "record dynamic linker information in -dynimport mode")
// This flag is for bootstrapping a new Go implementation,
// to generate Go types that match the data layout and
// constant values used in the host's C libraries and system calls.
var godefs = flag.Bool("godefs", false, "for bootstrap: write Go definitions for C file to standard output")
var srcDir = flag.String("srcdir", "", "source directory")
var objDir = flag.String("objdir", "", "object directory")
var importPath = flag.String("importpath", "", "import path of package being built (for comments in generated files)")
var exportHeader = flag.String("exportheader", "", "where to write export header if any exported functions")
var gccgo = flag.Bool("gccgo", false, "generate files for use with gccgo")
var gccgoprefix = flag.String("gccgoprefix", "", "-fgo-prefix option used with gccgo")
var gccgopkgpath = flag.String("gccgopkgpath", "", "-fgo-pkgpath option used with gccgo")
var importRuntimeCgo = flag.Bool("import_runtime_cgo", true, "import runtime/cgo in generated code")
var importSyscall = flag.Bool("import_syscall", true, "import syscall in generated code")
var goarch, goos string
func main() {
flag.Usage = usage
flag.Parse()
if *dynobj != "" {
// cgo -dynimport is essentially a separate helper command
// built into the cgo binary. It scans a gcc-produced executable
// and dumps information about the imported symbols and the
// imported libraries. The 'go build' rules for cgo prepare an
// appropriate executable and then use its import information
// instead of needing to make the linkers duplicate all the
// specialized knowledge gcc has about where to look for imported
// symbols and which ones to use.
dynimport(*dynobj)
return
}
if *godefs {
// Generating definitions pulled from header files,
// to be checked into Go repositories.
// Line numbers are just noise.
conf.Mode &^= printer.SourcePos
}
args := flag.Args()
if len(args) < 1 {
usage()
}
// Find first arg that looks like a go file and assume everything before
// that are options to pass to gcc.
var i int
for i = len(args); i > 0; i-- {
if !strings.HasSuffix(args[i-1], ".go") {
break
}
}
if i == len(args) {
usage()
}
goFiles := args[i:]
for _, arg := range args[:i] {
if arg == "-fsanitize=thread" {
tsanProlog = yesTsanProlog
}
}
p := newPackage(args[:i])
// Record CGO_LDFLAGS from the environment for external linking.
if ldflags := os.Getenv("CGO_LDFLAGS"); ldflags != "" {
args, err := splitQuoted(ldflags)
if err != nil {
fatalf("bad CGO_LDFLAGS: %q (%s)", ldflags, err)
}
p.addToFlag("LDFLAGS", args)
}
// Need a unique prefix for the global C symbols that
// we use to coordinate between gcc and ourselves.
// We already put _cgo_ at the beginning, so the main
// concern is other cgo wrappers for the same functions.
// Use the beginning of the md5 of the input to disambiguate.
h := md5.New()
for _, input := range goFiles {
if *srcDir != "" {
input = filepath.Join(*srcDir, input)
}
f, err := os.Open(input)
if err != nil {
fatalf("%s", err)
}
io.Copy(h, f)
f.Close()
}
cPrefix = fmt.Sprintf("_%x", h.Sum(nil)[0:6])
fs := make([]*File, len(goFiles))
for i, input := range goFiles {
if *srcDir != "" {
input = filepath.Join(*srcDir, input)
}
f := new(File)
f.ReadGo(input)
f.DiscardCgoDirectives()
fs[i] = f
}
if *objDir == "" {
// make sure that _obj directory exists, so that we can write
// all the output files there.
os.Mkdir("_obj", 0777)
*objDir = "_obj"
}
*objDir += string(filepath.Separator)
for i, input := range goFiles {
f := fs[i]
p.Translate(f)
for _, cref := range f.Ref {
switch cref.Context {
case "call", "call2":
if cref.Name.Kind != "type" {
break
}
*cref.Expr = cref.Name.Type.Go
}
}
if nerrors > 0 {
os.Exit(2)
}
p.PackagePath = f.Package
p.Record(f)
if *godefs {
os.Stdout.WriteString(p.godefs(f, input))
} else {
p.writeOutput(f, input)
}
}
if !*godefs {
p.writeDefs()
}
if nerrors > 0 {
os.Exit(2)
}
}
// newPackage returns a new Package that will invoke
// gcc with the additional arguments specified in args.
func newPackage(args []string) *Package {
goarch = runtime.GOARCH
if s := os.Getenv("GOARCH"); s != "" {
goarch = s
}
goos = runtime.GOOS
if s := os.Getenv("GOOS"); s != "" {
goos = s
}
ptrSize := ptrSizeMap[goarch]
if ptrSize == 0 {
fatalf("unknown ptrSize for $GOARCH %q", goarch)
}
intSize := intSizeMap[goarch]
if intSize == 0 {
fatalf("unknown intSize for $GOARCH %q", goarch)
}
// Reset locale variables so gcc emits English errors [sic].
os.Setenv("LANG", "en_US.UTF-8")
os.Setenv("LC_ALL", "C")
p := &Package{
PtrSize: ptrSize,
IntSize: intSize,
CgoFlags: make(map[string][]string),
Written: make(map[string]bool),
}
p.addToFlag("CFLAGS", args)
return p
}
// Record what needs to be recorded about f.
func (p *Package) Record(f *File) {
if p.PackageName == "" {
p.PackageName = f.Package
} else if p.PackageName != f.Package {
error_(token.NoPos, "inconsistent package names: %s, %s", p.PackageName, f.Package)
}
if p.Name == nil {
p.Name = f.Name
} else {
for k, v := range f.Name {
if p.Name[k] == nil {
p.Name[k] = v
} else if !reflect.DeepEqual(p.Name[k], v) {
error_(token.NoPos, "inconsistent definitions for C.%s", fixGo(k))
}
}
}
if f.ExpFunc != nil {
p.ExpFunc = append(p.ExpFunc, f.ExpFunc...)
p.Preamble += "\n" + f.Preamble
}
p.Decl = append(p.Decl, f.AST.Decls...)
}
| [
"\"CGO_LDFLAGS\"",
"\"GOARCH\"",
"\"GOOS\""
]
| []
| [
"CGO_LDFLAGS",
"GOARCH",
"GOOS"
]
| [] | ["CGO_LDFLAGS", "GOARCH", "GOOS"] | go | 3 | 0 | |
enterprise/dev/ci/gen-pipeline.go | package main
import (
"fmt"
"os"
"regexp"
"strconv"
"strings"
"time"
bk "github.com/sourcegraph/sourcegraph/pkg/buildkite"
)
func init() {
bk.Plugins["gopath-checkout#v1.0.1"] = map[string]string{
"import": "github.com/sourcegraph/sourcegraph",
}
}
func main() {
pipeline := &bk.Pipeline{}
branch := os.Getenv("BUILDKITE_BRANCH")
version := os.Getenv("BUILDKITE_TAG")
taggedRelease := true // true if this is a semver tagged release
if !strings.HasPrefix(version, "v") {
taggedRelease = false
commit := os.Getenv("BUILDKITE_COMMIT")
if commit == "" {
commit = "1234567890123456789012345678901234567890" // for testing
}
buildNum, _ := strconv.Atoi(os.Getenv("BUILDKITE_BUILD_NUMBER"))
version = fmt.Sprintf("%05d_%s_%.7s", buildNum, time.Now().Format("2006-01-02"), commit)
} else {
// The Git tag "v1.2.3" should map to the Docker image "1.2.3" (without v prefix).
version = strings.TrimPrefix(version, "v")
}
releaseBranch := regexp.MustCompile(`^[0-9]+\.[0-9]+$`).MatchString(branch)
bk.OnEveryStepOpts = append(bk.OnEveryStepOpts,
bk.Env("GO111MODULE", "on"),
bk.Env("ENTERPRISE", "1"),
bk.Env("CYPRESS_INSTALL_BINARY", "0"),
bk.Cmd("pushd enterprise"),
)
pipeline.AddStep(":white_check_mark:",
bk.Cmd("popd"),
bk.Cmd("./dev/check/all.sh"),
bk.Cmd("pushd enterprise"),
bk.Cmd("./dev/check/all.sh"),
bk.Cmd("popd"),
)
pipeline.AddStep(":lipstick:",
bk.Cmd("popd"),
bk.Cmd("yarn --frozen-lockfile"),
bk.Cmd("yarn run prettier"))
pipeline.AddStep(":typescript:",
bk.Cmd("popd"),
bk.Env("PUPPETEER_SKIP_CHROMIUM_DOWNLOAD", "true"),
bk.Env("FORCE_COLOR", "1"),
bk.Cmd("yarn --frozen-lockfile"),
bk.Cmd("yarn run tslint"))
pipeline.AddStep(":stylelint:",
bk.Cmd("popd"),
bk.Env("PUPPETEER_SKIP_CHROMIUM_DOWNLOAD", "true"),
bk.Env("FORCE_COLOR", "1"),
bk.Cmd("yarn --frozen-lockfile"),
bk.Cmd("yarn run stylelint --quiet"))
pipeline.AddStep(":webpack:",
bk.Cmd("popd"),
bk.Env("PUPPETEER_SKIP_CHROMIUM_DOWNLOAD", "true"),
bk.Env("FORCE_COLOR", "1"),
bk.Cmd("yarn --frozen-lockfile"),
bk.Cmd("yarn workspace sourcegraph run build"),
bk.Cmd("yarn workspace @sourcegraph/extensions-client-common run build"),
bk.Cmd("NODE_ENV=production yarn workspace webapp run build --color"),
bk.Cmd("GITHUB_TOKEN= yarn workspace webapp run bundlesize"))
// There are no tests yet
// pipeline.AddStep(":mocha:",
// bk.Env("PUPPETEER_SKIP_CHROMIUM_DOWNLOAD", "true"),
// bk.Env("FORCE_COLOR", "1"),
// bk.Cmd("yarn --frozen-lockfile"),
// bk.Cmd("yarn run cover"),
// bk.Cmd("node_modules/.bin/nyc report -r json"),
// bk.ArtifactPaths("coverage/coverage-final.json"))
// addDockerImageStep adds a build step for a given app.
// If the app is not in the cmd directory, it is assumed to be from the open source repo.
addDockerImageStep := func(app string, insiders bool) {
cmdDir := "cmd/" + app
var pkgPath string
if _, err := os.Stat(cmdDir); err != nil {
fmt.Fprintf(os.Stderr, "github.com/sourcegraph/sourcegraph/enterprise/cmd/%s does not exist so building github.com/sourcegraph/sourcegraph/cmd/%s instead\n", app, app)
pkgPath = "github.com/sourcegraph/sourcegraph/cmd/" + app
} else {
pkgPath = "github.com/sourcegraph/sourcegraph/enterprise/cmd/" + app
}
cmds := []bk.StepOpt{
bk.Cmd(fmt.Sprintf(`echo "Building %s..."`, app)),
}
preBuildScript := cmdDir + "/pre-build.sh"
if _, err := os.Stat(preBuildScript); err == nil {
cmds = append(cmds, bk.Cmd(preBuildScript))
}
image := "sourcegraph/" + app
buildScript := cmdDir + "/build.sh"
if _, err := os.Stat(buildScript); err == nil {
cmds = append(cmds,
bk.Env("IMAGE", image+":"+version),
bk.Env("VERSION", version),
bk.Cmd(buildScript),
)
} else {
cmds = append(cmds,
bk.Cmd("go build github.com/sourcegraph/godockerize"),
bk.Cmd(fmt.Sprintf("./godockerize build -t %s:%s --go-build-flags='-ldflags' --go-build-flags='-X github.com/sourcegraph/sourcegraph/pkg/version.version=%s' --env VERSION=%s %s", image, version, version, version, pkgPath)),
)
}
if app != "server" || taggedRelease {
cmds = append(cmds,
bk.Cmd(fmt.Sprintf("docker push %s:%s", image, version)),
)
}
if app == "server" && releaseBranch {
cmds = append(cmds,
bk.Cmd(fmt.Sprintf("docker tag %s:%s %s:%s-insiders", image, version, image, branch)),
bk.Cmd(fmt.Sprintf("docker push %s:%s-insiders", image, branch)),
)
}
if insiders {
cmds = append(cmds,
bk.Cmd(fmt.Sprintf("docker tag %s:%s %s:insiders", image, version, image)),
bk.Cmd(fmt.Sprintf("docker push %s:insiders", image)),
)
}
pipeline.AddStep(":docker:", cmds...)
}
pipeline.AddStep(":go:", bk.Cmd("go install ./cmd/..."))
pipeline.AddStep(":go:",
bk.Cmd("pushd .."),
bk.Cmd("go generate ./cmd/..."),
bk.Cmd("popd"),
bk.Cmd("go generate ./cmd/..."),
bk.Cmd("go install -tags dist ./cmd/..."),
)
if strings.HasPrefix(branch, "docker-images-patch-notest/") {
version = version + "_patch"
addDockerImageStep(branch[27:], false)
_, err := pipeline.WriteTo(os.Stdout)
if err != nil {
panic(err)
}
return
}
pipeline.AddStep(":go:",
bk.Cmd("go test -coverprofile=coverage.txt -covermode=atomic -race ./..."),
bk.ArtifactPaths("coverage.txt"))
pipeline.AddWait()
pipeline.AddStep(":codecov:",
bk.Cmd("buildkite-agent artifact download 'coverage.txt' . || true"), // ignore error when no report exists
bk.Cmd("buildkite-agent artifact download '*/coverage-final.json' . || true"),
bk.Cmd("bash <(curl -s https://codecov.io/bash) -X gcov -X coveragepy -X xcode"))
fetchClusterCredentials := func(name, zone, project string) bk.StepOpt {
return bk.Cmd(fmt.Sprintf("gcloud container clusters get-credentials %s --zone %s --project %s", name, zone, project))
}
addDeploySteps := func() {
// Deploy to dogfood
pipeline.AddStep(":dog:",
// Protect against concurrent/out-of-order deploys
bk.ConcurrencyGroup("deploy"),
bk.Concurrency(1),
bk.Env("VERSION", version),
bk.Env("CONTEXT", "gke_sourcegraph-dev_us-central1-a_dogfood-cluster-7"),
bk.Env("NAMESPACE", "default"),
fetchClusterCredentials("dogfood-cluster-7", "us-central1-a", "sourcegraph-dev"),
bk.Cmd("./dev/ci/deploy-dogfood.sh"))
pipeline.AddWait()
// Run e2e tests against dogfood
pipeline.AddStep(":chromium:",
// Protect against deploys while tests are running
bk.ConcurrencyGroup("deploy"),
bk.Concurrency(1),
bk.Env("FORCE_COLOR", "1"),
bk.Cmd("yarn --frozen-lockfile"),
bk.Cmd("yarn workspace webapp run test-e2e-sgdev --retries 5"),
bk.ArtifactPaths("./puppeteer/*.png"))
pipeline.AddWait()
// Deploy to prod
pipeline.AddStep(":rocket:",
bk.Env("VERSION", version),
bk.Cmd("./dev/ci/deploy-prod.sh"))
}
switch {
case taggedRelease:
allDockerImages := []string{
"frontend",
"github-proxy",
"gitserver",
"indexer",
"lsp-proxy",
"query-runner",
"repo-updater",
"searcher",
"server",
"symbols",
"xlang-go",
}
for _, dockerImage := range allDockerImages {
addDockerImageStep(dockerImage, false)
}
pipeline.AddWait()
case releaseBranch:
addDockerImageStep("server", false)
pipeline.AddWait()
case branch == "master":
addDockerImageStep("frontend", true)
addDockerImageStep("server", true)
pipeline.AddWait()
addDeploySteps()
case strings.HasPrefix(branch, "master-dry-run/"): // replicates `master` build but does not deploy
addDockerImageStep("frontend", true)
addDockerImageStep("server", true)
pipeline.AddWait()
case strings.HasPrefix(branch, "docker-images-patch/"):
version = version + "_patch"
addDockerImageStep(branch[20:], false)
case strings.HasPrefix(branch, "docker-images/"):
addDockerImageStep(branch[14:], true)
pipeline.AddWait()
// Only deploy images that aren't auto deployed from master.
if branch != "docker-images/server" && branch != "docker-images/frontend" {
addDeploySteps()
}
}
_, err := pipeline.WriteTo(os.Stdout)
if err != nil {
panic(err)
}
}
| [
"\"BUILDKITE_BRANCH\"",
"\"BUILDKITE_TAG\"",
"\"BUILDKITE_COMMIT\"",
"\"BUILDKITE_BUILD_NUMBER\""
]
| []
| [
"BUILDKITE_BUILD_NUMBER",
"BUILDKITE_COMMIT",
"BUILDKITE_TAG",
"BUILDKITE_BRANCH"
]
| [] | ["BUILDKITE_BUILD_NUMBER", "BUILDKITE_COMMIT", "BUILDKITE_TAG", "BUILDKITE_BRANCH"] | go | 4 | 0 | |
config/config.go | package config
import (
"fmt"
"github.com/go-playground/validator/v10"
"github.com/spf13/viper"
"log"
"os"
"reflect"
"strings"
)
type Config struct {
Connections Connections `mapstructure:"connections" validate:"required"`
Profiling Profiling `mapstructure:"profiling" validate:"required"`
Rules []Rule `mapstructure:"rules" validate:"required"`
}
type Profiling struct {
// ProfilingInterval is how frequently sessions are profiled in seconds.
ProfilingInterval *int `mapstructure:"interval" validate:"required"`
}
type Connections struct {
Redis Redis `mapstructure:"redis" validate:"required"`
InfluxDB InfluxDB `mapstructure:"influxdb" validate:"required"`
}
// Redis represents the key-value store of session cookies. Currently, only the
// Redis driver is available.
type Redis struct {
Addr *string `mapstructure:"addr" validate:"required"`
Password *string `mapstructure:"pass" validate:"required"`
StoreDB *int `mapstructure:"storeDB" validate:"required"`
// QueueDB is the store for the session ID queue. Currently shared with
// Redis above.
QueueDB *int `mapstructure:"queueDB" validate:"required"`
}
// InfluxDB represents the store for the session browsing history. Currently,
// only InfluxDB is available.
type InfluxDB struct {
Addr *string `mapstructure:"addr" validate:"required"`
Token *string `mapstructure:"token" validate:"required"`
Org *string `mapstructure:"org" validate:"required"`
SessionBucket *string `mapstructure:"sessionBucket" validate:"required"`
// LoggingBucket is the store for logging output. Currently shared
// with InfluxDB above.
LoggingBucket *string `mapstructure:"loggingBucket" validate:"required"`
}
type Rule struct {
Description *string `mapstructure:"description" validate:"required"`
Method MatchableMethod
Path *string `mapstructure:"path" validate:"required"`
Occurrences *int `mapstructure:"occurrences" validate:"required"`
Result *string `mapstructure:"result" validate:"oneof=low high"`
}
type MatchableMethod struct {
ShouldMatchAll *bool `mapstructure:"shouldMatchAll" validate:"required_without=Method"`
// Method must be set if ShouldMatchAll is false. If ShouldMatchAll is true,
// Method is ignored.
Method *string `mapstructure:"method" validate:"required_without=ShouldMatchAll"`
}
func setDefaults() {
viper.SetDefault("Profiling.Interval", 10)
}
func ReadConfig() *Config {
// Dots are not valid identifiers for environment variables.
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
setDefaults()
viper.SetConfigType("yaml")
viper.SetConfigName("config")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
log.Fatalf("error: /app/config.yaml not found. Are you sure you have configured the ConfigMap?\nerr = %s", err)
} else {
log.Fatalf("error when reading config file at /app/config.yaml: err = %s", err)
}
}
var config Config
bindEnvs(config)
if err := viper.Unmarshal(&config); err != nil {
log.Fatalf("error occurred while reading configuration file: err = %s", err)
}
validate := validator.New()
err := validate.Struct(&config)
if err != nil {
if _, ok := err.(*validator.InvalidValidationError); ok {
log.Printf("unable to validate config: err = %s", err)
}
log.Printf("encountered validation errors:\n")
for _, err := range err.(validator.ValidationErrors) {
fmt.Printf("\t%s\n", err.Error())
}
fmt.Println("Check your configuration file and try again.")
os.Exit(1)
}
return &config
}
// bindEnvs binds all environment variables automatically.
// See: https://github.com/spf13/viper/issues/188#issuecomment-399884438
func bindEnvs(iface interface{}, parts ...string) {
ifv := reflect.ValueOf(iface)
ift := reflect.TypeOf(iface)
for i := 0; i < ift.NumField(); i++ {
v := ifv.Field(i)
t := ift.Field(i)
tv, ok := t.Tag.Lookup("mapstructure")
if !ok {
continue
}
switch v.Kind() {
case reflect.Struct:
bindEnvs(v.Interface(), append(parts, tv)...)
default:
_ = viper.BindEnv(strings.Join(append(parts, tv), "."))
}
}
}
| []
| []
| []
| [] | [] | go | null | null | null |
.mvn/wrapper/MavenWrapperDownloader.java | /*
* Copyright 2007-present the original author or 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 java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.3";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + " .jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
| [
"\"MVNW_USERNAME\"",
"\"MVNW_PASSWORD\"",
"\"MVNW_USERNAME\"",
"\"MVNW_PASSWORD\""
]
| []
| [
"MVNW_USERNAME",
"MVNW_PASSWORD"
]
| [] | ["MVNW_USERNAME", "MVNW_PASSWORD"] | java | 2 | 0 | |
test.py | from os.path import getmtime, join as path_join
from osext import filesystem as fs
import calendar
import httpext
import os
import tempfile
import unittest
class TestDownloadFunctions(unittest.TestCase):
TEST_URI = 'http://www.example.com'
_temp_files = []
def test_normal_use(self):
local_file = tempfile.mkstemp(prefix='_test-httpext_')[1]
self._temp_files.append(local_file)
httpext.dl(self.TEST_URI, local_file)
with open(local_file) as f:
line = f.readline().strip()
self.assertEqual(line, '<!doctype html>')
self.assertTrue('This domain is established to be used for illustrative examples in documents.' in ' '.join(f.readlines()))
def test_cached_response(self):
local_file = tempfile.mkstemp(prefix='_test-httpext_')[1]
self._temp_files.append(local_file)
expected_file_path = path_join(os.environ['HOME'], '.cache', 'httpext', local_file)
self._temp_files.append(expected_file_path)
httpext.dl(self.TEST_URI, local_file)
self.assertTrue(fs.isfile(expected_file_path))
last_modified = httpext.get_last_modified_time(self.TEST_URI)
file_time = getmtime(expected_file_path)
self.assertEqual(file_time, calendar.timegm(last_modified))
def test_append_url_contents(self):
local_file = tempfile.mkstemp(prefix='_test-httpext_')[1]
self._temp_files.append(local_file)
with open(local_file, 'w') as f:
f.write('Not HTML\n')
httpext.append_url_contents(self.TEST_URI, local_file)
with open(local_file) as f:
first_line = f.readline().strip()
self.assertEqual('Not HTML', first_line)
self.assertEqual('<!doctype html>', f.readline().strip())
def tearDown(self):
for file in self._temp_files:
if fs.isfile(file):
os.remove(file)
# This is used to keep compatibility with 2.6
if __name__ == '__main__':
unittest.main()
| []
| []
| [
"HOME"
]
| [] | ["HOME"] | python | 1 | 0 | |
app/tests/functional_tests.py | import os
import pytest
from selenium import webdriver
@pytest.fixture(scope="module")
def driver():
driver = webdriver.Firefox()
yield driver
driver.quit()
def test_homepage(driver):
driver.get(os.getenv('HOMEPAGE'))
expected = 'Dashboard'
assert expected in driver.title | []
| []
| [
"HOMEPAGE"
]
| [] | ["HOMEPAGE"] | python | 1 | 0 | |
opus/application/apps/search/views.py | ################################################################################
#
# search/views.py
#
# The API interface for doing things related to searches plus major internal
# support routines for searching:
#
# Format: __api/normalizeinput.json
# Format: __api/stringsearchchoices/<slug>.json
#
################################################################################
import hashlib
import json
import logging
import re
import regex # This is used instead of "re" because it's closer to the ICU
# regex library used by MySQL
import time
from django.apps import apps
from django.core.cache import cache
from django.db import connection, DatabaseError
from django.db.models import Q
from django.db.utils import IntegrityError
from django.http import Http404, HttpResponseServerError
from paraminfo.models import ParamInfo
from search.models import UserSearches
from tools.app_utils import (enter_api_call,
exit_api_call,
get_mult_name,
get_reqno,
json_response,
sort_dictionary,
strip_numeric_suffix,
throw_random_http404_error,
throw_random_http500_error,
HTTP404_BAD_LIMIT,
HTTP404_BAD_OR_MISSING_REQNO,
HTTP404_NO_REQUEST,
HTTP404_SEARCH_PARAMS_INVALID,
HTTP404_UNKNOWN_SLUG,
HTTP500_DATABASE_ERROR,
HTTP500_SEARCH_CACHE_FAILED)
from tools.db_utils import (MYSQL_EXECUTION_TIME_EXCEEDED,
MYSQL_TABLE_ALREADY_EXISTS)
import settings
from opus_support import (convert_from_default_unit,
convert_to_default_unit,
format_unit_value,
get_default_unit,
get_valid_units,
parse_form_type,
parse_unit_value)
log = logging.getLogger(__name__)
################################################################################
#
# API INTERFACES
#
################################################################################
def api_normalize_input(request):
"""Validate and normalize slug values.
This is a PRIVATE API.
For each searchable slug, check its value to see if it can be parsed.
If it can be, return a normalized value by parsing it and then un-parsing
it. If it can't be, return false.
Format: __api/normalizeinput.json
Arguments: reqno=<N>
Normal search arguments
Returned JSON is of the format:
{"slug1": "normalizedval1", "slug2": "normalizedval2",
"reqno": N}
"""
api_code = enter_api_call('api_normalize_input', request)
if not request or request.GET is None:
ret = Http404(HTTP404_NO_REQUEST('/__api/normalizeinput.json'))
exit_api_call(api_code, ret)
raise ret
(selections, extras) = url_to_search_params(request.GET,
allow_errors=True,
return_slugs=True,
pretty_results=True)
if selections is None or throw_random_http404_error():
log.error('api_normalize_input: Could not find selections for'
+' request %s', str(request.GET))
ret = Http404(HTTP404_SEARCH_PARAMS_INVALID(request))
exit_api_call(api_code, ret)
raise ret
reqno = get_reqno(request)
if reqno is None or throw_random_http404_error():
log.error('api_normalize_input: Missing or badly formatted reqno')
ret = Http404(HTTP404_BAD_OR_MISSING_REQNO(request))
exit_api_call(api_code, ret)
raise ret
selections['reqno'] = reqno
ret = json_response(selections)
exit_api_call(api_code, ret)
return ret
def api_string_search_choices(request, slug):
"""Return valid choices for a string search given other search criteria.
This is a PRIVATE API.
Return all valid choices for a given string search slug given the partial
search value entered for that slug, its q-type, and the remainder of the
normal search parameters.
Format: __api/stringsearchchoices/<slug>.json
Arguments: limit=<N>
reqno=<N>
Normal search arguments
Returned JSON is of the format:
{"choices": ["choice1", "choice2"],
"full_search": true/false,
"truncated_results": true/false,
"reqno": N}
The portion of each choice selected by the partial search is highlighted
with <b>...</b>.
full_search is true if the search was so large that it either exceeded the
query timeout or the maximum count allowed, thus requiring the results
to be on the entire database. full_search is false if the search was
performed restricted to the user's other constraints.
truncated_results is true if the the number of results exceeded the
specified limit. Only the limit number will be returned.
"""
api_code = enter_api_call('api_string_search_choices', request)
if not request or request.GET is None:
ret = Http404(HTTP404_NO_REQUEST(
f'/__api/stringsearchchoices/{slug}.json'))
exit_api_call(api_code, ret)
raise ret
param_info = get_param_info_by_slug(slug, 'search')
if not param_info or throw_random_http404_error():
log.error('api_string_search_choices: unknown slug "%s"',
slug)
ret = Http404(HTTP404_UNKNOWN_SLUG(slug, request))
exit_api_call(api_code, ret)
raise ret
param_qualified_name = param_info.param_qualified_name()
param_category = param_info.category_name
param_name = param_info.name
# We'd really rather not have to use allow_regex_errors here,
# but the front end will send us search strings with bad regex
# in the current input field due to the way autocomplete is timed
# relative to input validation. Note that we'll delete this bad
# search term later and catch the bad regex below.
(selections, extras) = url_to_search_params(request.GET,
allow_regex_errors=True)
if selections is None or throw_random_http404_error():
log.error('api_string_search_choices: Could not find selections for'
+' request %s', str(request.GET))
ret = Http404(HTTP404_SEARCH_PARAMS_INVALID(request))
exit_api_call(api_code, ret)
raise ret
reqno = get_reqno(request)
if reqno is None or throw_random_http404_error():
log.error('api_normalize_input: Missing or badly formatted reqno')
ret = Http404(HTTP404_BAD_OR_MISSING_REQNO(request))
exit_api_call(api_code, ret)
raise ret
if param_qualified_name not in selections:
selections[param_qualified_name] = ['']
qtypes = {}
query_qtype_list = []
query_qtype = 'contains'
if 'qtypes' in extras: # pragma: no cover
qtypes = extras['qtypes']
if param_qualified_name in qtypes:
query_qtype_list = qtypes[param_qualified_name]
if query_qtype_list == ['matches']:
query_qtype_list = ['contains']
query_qtype = query_qtype_list[0]
del qtypes[param_qualified_name]
# Must do this here before deleting the slug from selections below
like_query, like_params = get_string_query(selections, param_qualified_name,
query_qtype_list)
if like_query is None or throw_random_http500_error(): # pragma: no cover
# This is usually caused by a bad regex
result = {'choices': [],
'full_search': True,
'truncated_results': False}
result['reqno'] = reqno
ret = json_response(result)
exit_api_call(api_code, ret)
return ret
partial_query = selections[param_qualified_name][0]
del selections[param_qualified_name]
user_query_table = get_user_query_table(selections, extras,
api_code=api_code)
if not user_query_table or throw_random_http500_error(): # pragma: no cover
log.error('api_string_search_choices: get_user_query_table failed '
+'*** Selections %s *** Extras %s',
str(selections), str(extras))
ret = HttpResponseServerError(HTTP500_SEARCH_CACHE_FAILED(request))
exit_api_call(api_code, ret)
return ret
limit = request.GET.get('limit', settings.DEFAULT_STRINGCHOICE_LIMIT)
try:
limit = int(limit)
if throw_random_http404_error(): # pragma: no cover
raise ValueError
except ValueError:
log.error('api_string_search_choices: Bad limit for'
+' request %s', str(request.GET))
ret = Http404(HTTP404_BAD_LIMIT(limit, request))
exit_api_call(api_code, ret)
raise ret
if (limit < 1 or limit > settings.SQL_MAX_LIMIT or
throw_random_http404_error()):
log.error('api_string_search_choices: Bad limit for'
+' request %s', str(request.GET))
ret = Http404(HTTP404_BAD_LIMIT(limit, request))
exit_api_call(api_code, ret)
raise ret
# We do this because the user may have included characters that aren't
# allowed in a cache key
partial_query_hash = hashlib.md5(str.encode(partial_query)).hexdigest()
# Is this result already cached?
cache_key = (settings.CACHE_SERVER_PREFIX + settings.CACHE_KEY_PREFIX
+':stringsearchchoices:'
+param_qualified_name + ':'
+partial_query_hash + ':'
+user_query_table + ':'
+query_qtype + ':'
+str(limit))
cached_val = cache.get(cache_key)
if cached_val is not None:
cached_val['reqno'] = reqno
ret = json_response(cached_val)
exit_api_call(api_code, ret)
return ret
quoted_table_name = connection.ops.quote_name(param_category)
quoted_param_qualified_name = (quoted_table_name + '.'
+connection.ops.quote_name(param_name))
# Check the size of the cache table to see if we can afford to do a
# search retricted by the cache table contents. The JOIN of the cache
# table can be slow if it has too many entries and gives a bad user
# experience.
sql = 'SELECT COUNT(*) FROM '+connection.ops.quote_name(user_query_table)
cursor = connection.cursor()
cursor.execute(sql)
results = cursor.fetchall()
if (len(results) != 1 or len(results[0]) != 1 or
throw_random_http500_error()): # pragma: no cover
log.error('api_string_search_choices: SQL failure: %s', sql)
ret = HttpResponseServerError(HTTP500_DATABASE_ERROR(request))
exit_api_call(api_code, ret)
return ret
final_results = None
truncated_results = False
do_simple_search = False
count = int(results[0][0])
if count >= settings.STRINGCHOICE_FULL_SEARCH_COUNT_THRESHOLD:
do_simple_search = True
if not do_simple_search:
max_time = settings.STRINGCHOICE_FULL_SEARCH_TIME_THRESHOLD
sql = f'SELECT /*+ MAX_EXECUTION_TIME({max_time}) */'
sql += ' DISTINCT ' + quoted_param_qualified_name
sql += ' FROM '+quoted_table_name
# The cache table is an INNER JOIN because we only want opus_ids
# that appear in the cache table to cause result rows
sql += ' INNER JOIN '+connection.ops.quote_name(user_query_table)
sql += ' ON '+quoted_table_name+'.'
if param_category == 'obs_general': # pragma: no cover
# There are currently no string fields in obs_general
sql += connection.ops.quote_name('id')+'='
else:
sql += connection.ops.quote_name('obs_general_id')+'='
sql += connection.ops.quote_name(user_query_table)+'.'
sql += connection.ops.quote_name('id')
sql_params = []
if partial_query:
sql += ' WHERE '
sql += like_query
sql_params += like_params
sql += ' ORDER BY '+quoted_param_qualified_name
sql += ' LIMIT '+str(limit+1)
try:
cursor.execute(sql, tuple(sql_params))
if throw_random_http500_error(): # pragma: no cover
raise DatabaseError('random')
except DatabaseError as e:
if e.args[0] != MYSQL_EXECUTION_TIME_EXCEEDED: # pragma: no cover
log.error('api_string_search_choices: "%s" returned %s',
sql, str(e))
ret = HttpResponseServerError(HTTP500_DATABASE_ERROR(request))
exit_api_call(api_code, ret)
return ret
do_simple_search = True
if do_simple_search:
# Same thing but no cache table join
# This will give more results than we really want, but will be much
# faster
max_time = settings.STRINGCHOICE_FULL_SEARCH_TIME_THRESHOLD2
sql = f'SELECT /*+ MAX_EXECUTION_TIME({max_time}) */'
sql += ' DISTINCT ' + quoted_param_qualified_name
sql += ' FROM '+quoted_table_name
sql_params = []
if partial_query:
sql += ' WHERE '
sql += like_query
sql_params += like_params
sql += ' ORDER BY '+quoted_param_qualified_name
sql += ' LIMIT '+str(limit+1)
try:
cursor.execute(sql, tuple(sql_params))
if throw_random_http500_error(): # pragma: no cover
raise DatabaseError('random')
except DatabaseError as e:
if e.args[0] != MYSQL_EXECUTION_TIME_EXCEEDED: # pragma: no cover
log.error('api_string_search_choices: "%s" returned %s',
sql, str(e))
ret = HttpResponseServerError(HTTP500_DATABASE_ERROR(request))
exit_api_call(api_code, ret)
return ret
final_results = []
if final_results is None: # pragma: no cover
# This is always true except when BOTH queries time out
final_results = []
more = True
while more:
part_results = cursor.fetchall()
final_results += part_results
more = cursor.nextset()
final_results = [x[0] for x in final_results]
if partial_query:
esc_partial_query = partial_query
if query_qtype != 'regex':
# Note - there is no regex.escape function available
esc_partial_query = re.escape(partial_query)
try:
# We have to catch all random exceptions here because the
# compile may fail if the user gives regex that is bad for
# the regex library but wasn't caught by _valid_regex
# because it wasn't bad for MySQL
pattern = regex.compile(f'({esc_partial_query})',
regex.IGNORECASE | regex.V1)
final_results = [pattern.sub('<b>\\1</b>', x)
for x in final_results]
except:
pass
if len(final_results) > limit:
final_results = final_results[:limit]
truncated_results = True
result = {'choices': final_results,
'full_search': do_simple_search,
'truncated_results': truncated_results}
cache.set(cache_key, result)
result['reqno'] = reqno
ret = json_response(result)
exit_api_call(api_code, ret)
return ret
################################################################################
#
# MAJOR INTERNAL ROUTINES
#
################################################################################
def url_to_search_params(request_get, allow_errors=False,
allow_regex_errors=False,
return_slugs=False,
pretty_results=False,
allow_empty=False):
"""Convert a URL to a set of selections and extras.
This is the MAIN routine for taking a URL and parsing it for searching.
OPUS lets users put nice readable things in the URL, like "planet=Jupiter"
rather than "planet_id=3".
This function takes the URL params and translates them into a list that
contains 2 dictionaries:
The first dict is the user selections: keys of the dictionary are
param_names of data columns in the data table; values are always
lists and represent the user's selections.
The 2nd dict is any extras being passed by user, like qtypes that
define what types of queries will be performed for each
param-value set in the first dict, units for numeric values,
or sort order.
NOTE: Pass request_get = request.GET to this func please
(This func doesn't return an http response so unit tests freak if you
pass it an HTTP request)
If allow_errors is True, then even if a value can't be parsed, the rest
of the slugs are processed and the bad slug is just marked with None.
If allow_regex_errors is True, then even if a regex is badly formatted,
the rest of the slugs are processed and the bad slug is just marked with
None.
If return_slugs is True, the indexes into selections are slug names, not
qualified names (table.column).
If pretty_results is True, the resulting values are unparsed back into
strings based on the ParamInfo format.
If allow_empty is True, then search terms that have no values for either
min or max are kept. This is used to create UI forms for search widgets.
Example command line usage:
from search.views import *
from django.http import QueryDict
q = QueryDict("planet=Saturn&volumeid=COISS_2&qtype-volumeid=begins&rightasc1=10&order=time1,-RINGGEOringcenterdistance")
(selections,extras) = url_to_search_params(q)
selections
{'obs_general.planet_id': ['Saturn'],
'obs_pds.volume_id': ['COISS_2'],
'obs_general.right_asc1': [10.0],
'obs_general.right_asc2': [None]}
extras
{'order': (['obs_general.time1',
'obs_ring_geometry.ring_center_distance',
'obs_general.opus_id'],
[False, True, False]),
'qtypes': {'obs_pds.volume_id': ['begins'],
'obs_general.right_asc': ['any']},
'units': {'obs_general.right_asc': ['degrees']}}
"""
selections = {}
extras = {}
qtypes = {}
units = {}
order_params = []
order_descending_params = []
# Note that request_get.items() automatically gets rid of duplicate entries
# because it returns a dict.
search_params = list(request_get.items())
used_slugs = []
if 'order' not in [x[0] for x in search_params]:
# If there's no order slug, then force one
search_params.append(('order', settings.DEFAULT_SORT_ORDER))
# Go through the search_params one at a time and use whatever slug we find
# to look for the other ones we could be paired with.
for slug, value in search_params:
orig_slug = slug
if slug in used_slugs:
continue
if slug == 'order':
all_order = value
order_params, order_descending_params = parse_order_slug(all_order)
if order_params is None:
return None, None
extras['order'] = (order_params, order_descending_params)
used_slugs.append(slug)
continue
if slug in settings.SLUGS_NOT_IN_DB:
used_slugs.append(slug)
continue
# STRING and RANGE types can can have multiple clauses ORed together by
# putting "_NNN" after the slug name.
clause_num = 1
clause_num_str = ''
if '_' in slug:
clause_num_str = slug[slug.rindex('_'):]
try:
clause_num = int(clause_num_str[1:])
if clause_num > 0:
slug = slug[:slug.rindex('_')]
else:
raise ValueError
except ValueError:
# If clause_num is not a positive integer, leave the slug as is.
# If the slug is unknown, it will be caught later as an unknown
# slug.
clause_num = 1
clause_num_str = ''
# Find the master param_info
param_info = None
# The unit is the unit we want the field to be in
is_unit = None
# The sourceunit is used by normalizeurl to allow the conversion of
# values from ones unit to another. The original unit is available in
# "sourceunit" and the desination unit is available in "unit".
# sourceunit should not be used anywhere else.
is_sourceunit = None
if slug.startswith('qtype-'): # like qtype-time=all
slug = slug[6:]
slug_no_num = strip_numeric_suffix(slug)
if slug_no_num != slug:
log.error('url_to_search_params: qtype slug has '+
'numeric suffix "%s"', orig_slug)
return None, None
param_info = get_param_info_by_slug(slug, 'qtype')
elif slug.startswith('unit-'): # like unit-observationduration=msec
is_unit = True
slug = slug[5:]
slug_no_num = strip_numeric_suffix(slug)
if slug_no_num != slug:
log.error('url_to_search_params: unit slug has '+
'numeric suffix "%s"', orig_slug)
return None, None
param_info = get_param_info_by_slug(slug, 'qtype')
elif slug.startswith('sourceunit-'):
is_sourceunit = True
slug = slug[11:]
slug_no_num = strip_numeric_suffix(slug)
if slug_no_num != slug:
log.error('url_to_search_params: sourceunit slug has '+
'numeric suffix "%s"', orig_slug)
return None, None
param_info = get_param_info_by_slug(slug, 'qtype')
else:
param_info = get_param_info_by_slug(slug, 'search')
if not param_info:
log.error('url_to_search_params: unknown slug "%s"',
orig_slug)
return None, None
slug_no_num = strip_numeric_suffix(slug)
param_qualified_name = param_info.param_qualified_name()
if param_qualified_name == 'obs_pds.opus_id':
# Force OPUS_ID to be searched from obs_general for efficiency
# even though the user sees it in PDS Constraints.
param_qualified_name = 'obs_general.opus_id'
param_qualified_name_no_num = strip_numeric_suffix(param_qualified_name)
(form_type, form_type_format,
form_type_unit_id) = parse_form_type(param_info.form_type)
valid_units = get_valid_units(form_type_unit_id)
if param_info.slug: # Should always be true # pragma: no cover
# Kill off all the original slugs
pi_slug_no_num = strip_numeric_suffix(param_info.slug)
used_slugs.append(pi_slug_no_num+clause_num_str)
used_slugs.append(pi_slug_no_num+'1'+clause_num_str)
used_slugs.append(pi_slug_no_num+'2'+clause_num_str)
used_slugs.append('qtype-'+pi_slug_no_num+clause_num_str)
used_slugs.append('unit-'+pi_slug_no_num+clause_num_str)
used_slugs.append('sourceunit-'+pi_slug_no_num+clause_num_str)
if param_info.old_slug:
# Kill off all the old slugs - this prevents cases where someone
# uses the new slug and old slug names in the same query.
pi_old_slug_no_num = strip_numeric_suffix(param_info.old_slug)
used_slugs.append(pi_old_slug_no_num+clause_num_str)
used_slugs.append(pi_old_slug_no_num+'1'+clause_num_str)
used_slugs.append(pi_old_slug_no_num+'2'+clause_num_str)
used_slugs.append('qtype-'+pi_old_slug_no_num+clause_num_str)
used_slugs.append('unit-'+pi_old_slug_no_num+clause_num_str)
used_slugs.append('sourceunit-'+pi_old_slug_no_num+clause_num_str)
# Look for an associated qtype.
# Use the original slug name here since we hope if someone says
# XXX=5 then they also say qtype-XXX=all
qtype_slug = 'qtype-'+slug_no_num+clause_num_str
valid_qtypes = None
if form_type not in settings.MULT_FORM_TYPES:
valid_qtypes = settings.STRING_QTYPES
if form_type in settings.RANGE_FORM_TYPES:
valid_qtypes = settings.RANGE_QTYPES
qtype_val = None
if qtype_slug in request_get:
qtype_val = request_get[qtype_slug].lower()
if valid_qtypes is None or qtype_val not in valid_qtypes:
if allow_errors: # pragma: no cover
# We never actually hit this because normalizeurl catches
# the bad qtype first
qtype_val = None
else:
log.error('url_to_search_params: Bad qtype value for '
+'"%s": %s', qtype_slug, str(qtype_val))
return None, None
else:
if valid_qtypes is not None:
qtype_val = valid_qtypes[0] # Default if not specified
# Look for an associated unit.
# Use the original slug name here since we hope if someone says
# XXX=5 then they also say unit-XXX=msec
unit_slug = 'unit-'+slug_no_num+clause_num_str
unit_val = None
if unit_slug in request_get:
unit_val = request_get[unit_slug].lower()
if valid_units is None or unit_val not in valid_units:
if allow_errors: # pragma: no cover
# We never actually hit this because normalizeurl catches
# the bad unit first
unit_val = None
else:
log.error('url_to_search_params: Bad unit value for '
+'"%s": %s', unit_slug, str(unit_val))
return None, None
else:
# Default if not specified
unit_val = get_default_unit(form_type_unit_id)
# Look for an associated sourceunit.
# Use the original slug name here since we hope if someone says
# XXX=5 then they also say sourceunit-XXX=msec
sourceunit_slug = 'sourceunit-'+slug_no_num+clause_num_str
# sourceunit_val will be the same as unit_val if sourceunit_slug doesn't
# exist in the URL
sourceunit_val = unit_val
if sourceunit_slug in request_get:
sourceunit_val = request_get[sourceunit_slug].lower()
if (valid_units is None or
sourceunit_val not in valid_units):
log.error('url_to_search_params: Bad sourceunit value'
+' for "%s": %s', sourceunit_slug,
str(sourceunit_val))
if allow_errors: # pragma: no cover
# We never actually hit this because normalizeurl catches
# the bad unit first
sourceunit_val = None
else:
return None, None
if form_type in settings.MULT_FORM_TYPES:
# MULT types have no qtype, units, or 1/2 split.
# They also can't accept a clause number.
if clause_num_str:
log.error('url_to_search_params: Mult field "%s" has clause'
+' number where none permitted', orig_slug)
return None, None
# Presence of qtype or unit slug will be caught earalier
# If nothing is specified, just ignore the slug.
values = [x.strip() for x in value.split(',')]
has_value = False
for value in values:
if value:
has_value = True
break
if not has_value:
if pretty_results and return_slugs:
selections[slug] = ""
continue
# Mult form types can be sorted and uniquified to save duplicate
# queries being built.
# No other form types can be sorted since their ordering
# corresponds to qtype/unit ordering.
new_val = sorted(set(values))
# Now check to see if the mult values are all valid
mult_name = get_mult_name(param_qualified_name)
model_name = mult_name.title().replace('_','')
model = apps.get_model('search', model_name)
mult_values = [x['pk'] for x in
list(model.objects.filter( Q(label__in=new_val)
| Q(value__in=new_val))
.values('pk'))]
if len(mult_values) != len(new_val):
if allow_errors:
new_val = None
else:
log.error('url_to_search_params: Bad mult data for "%s", '
+'wanted "%s" found "%s"',
param_qualified_name, str(new_val),
str(mult_values))
return None, None
if pretty_results and new_val:
new_val = ','.join(new_val)
if return_slugs:
selections[slug] = new_val
else:
selections[param_qualified_name] = new_val
continue
# This is either a RANGE or a STRING type.
if form_type in settings.RANGE_FORM_TYPES:
# For RANGE form types, there can be 1/2 slugs. Just ignore the slug
# we're currently looking at and start over for simplicity.
new_param_qualified_names = []
new_values = []
for suffix in ('1', '2'):
new_slug = slug_no_num+suffix+clause_num_str
new_param_qualified_name = param_qualified_name_no_num+suffix
new_value = None
if new_slug in request_get:
value = request_get[new_slug].strip()
if value:
try:
# Convert the strings into the internal
# representation if necessary. If there is not
# sourceunit slug, then sourceunit and unit are the
# same and we parse the value in that unit and then
# convert it to and back from default (which should
# do nothing). If they are different, then we parse
# the value as sourceunit, convert it to default as
# sourceunit, and convert it back to unit to do the
# unit conversion.
new_value = parse_unit_value(value,
form_type_format,
form_type_unit_id,
sourceunit_val)
if is_sourceunit or sourceunit_val is not None:
default_val = (convert_to_default_unit(
new_value,
form_type_unit_id,
sourceunit_val))
new_value = (convert_from_default_unit(
default_val,
form_type_unit_id,
unit_val))
# Do a conversion of the given value to the default
# units. We do this so that if the conversion throws
# an error (like overflow), we mark this search
# term as invalid, since it will fail later in
# construct_query_string anyway. This allows
# normalizeinput to report it as bad immediately.
default_val = convert_to_default_unit(
new_value,
form_type_unit_id,
unit_val)
if pretty_results:
# We keep the returned value in the original
# unit rather than converting it, but we have
# to specify the unit here so the number
# of digits after the decimal can be adjusted.
# The actual conversion to the default unit
# will happen when creating a query.
new_value = format_unit_value(
new_value, form_type_format,
form_type_unit_id,
unit_val,
convert_from_default=False)
except ValueError as e:
new_value = None
if not allow_errors:
log.error('url_to_search_params: Unit ID "%s" '
+'slug "%s" source unit "%s" unit '
+'"%s" threw ValueError(%s) for %s',
form_type_unit_id, slug,
sourceunit_val, unit_val,
e, value)
return None, None
else:
new_value = None
if return_slugs:
# Always put values for present slugs in for
# return_slugs
if value == '':
selections[new_slug] = ''
else:
selections[new_slug] = new_value
new_param_qualified_names.append(new_param_qualified_name)
new_values.append(new_value)
if return_slugs:
if not is_single_column_range(param_qualified_name_no_num):
# Always include qtype no matter what
# The following if should always be true because we only hit
# this once for each slug
if param_qualified_name_no_num not in qtypes: # pragma: no cover
qtypes[param_qualified_name_no_num] = []
qtypes[param_qualified_name_no_num].append(qtype_val)
# Always include unit no matter what
# The following if should always be true because we only hit
# this once for each slug
if param_qualified_name_no_num not in units: # pragma: no cover
units[param_qualified_name_no_num] = []
units[param_qualified_name_no_num].append(unit_val)
elif (allow_empty or
new_values[0] is not None or
new_values[1] is not None):
# If both values are None, then don't include this slug at all
if new_param_qualified_names[0] not in selections:
selections[new_param_qualified_names[0]] = []
if allow_empty and clause_num_str:
range_min_selection = selections[
new_param_qualified_names[0]]
len_min = len(range_min_selection)
# Note: clause_num here will not be a very large
# number because allow_empty is only True when it's
# called from api_get_widget, and in that case,
# clause numbers have already been normalized.
if len_min < clause_num:
range_min_selection += [None] * (clause_num-len_min)
range_min_selection[clause_num-1] = new_values[0]
else:
selections[new_param_qualified_names[0]].append(
new_values[0])
if new_param_qualified_names[1] not in selections:
selections[new_param_qualified_names[1]] = []
if allow_empty and clause_num_str:
range_max_selection = selections[
new_param_qualified_names[1]]
len_max = len(range_max_selection)
if len_max < clause_num:
range_max_selection += [None] * (clause_num-len_max)
range_max_selection[clause_num-1] = new_values[1]
else:
selections[new_param_qualified_names[1]].append(
new_values[1])
if not is_single_column_range(param_qualified_name_no_num):
# There was at least one value added or allow_empty
# is set - include the qtype
if param_qualified_name_no_num not in qtypes:
qtypes[param_qualified_name_no_num] = []
if allow_empty and clause_num_str:
range_qtype = qtypes[param_qualified_name_no_num]
len_qtype = len(range_qtype)
if len_qtype < clause_num:
range_qtype += [None] * (clause_num-len_qtype)
range_qtype[clause_num-1] = qtype_val
else:
qtypes[param_qualified_name_no_num].append(
qtype_val)
# There was at least one value added - include the unit
if param_qualified_name_no_num not in units:
units[param_qualified_name_no_num] = []
units[param_qualified_name_no_num].append(unit_val)
continue
# For STRING form types, there is only a single slug. Just ignore the
# slug we're currently looking at and start over for simplicity.
if is_unit or unit_val is not None: # pragma: no cover
# We shouldn't ever get here because string fields have no valid
# units and this will be caught above
log.error('url_to_search_params: String field "%s" has unit',
orig_slug)
return None, None
new_value = ''
new_slug = slug_no_num+clause_num_str
if new_slug in request_get:
new_value = request_get[new_slug]
if new_value and qtype_val == 'regex' and not allow_regex_errors:
if not _valid_regex(new_value):
if not allow_errors:
log.error('url_to_search_params: String "%s" '
+'slug "%s" is not a valid regex',
new_value, slug)
return None, None
new_value = None
if return_slugs:
selections[new_slug] = new_value
qtypes[new_slug] = qtype_val
units[new_slug] = unit_val
elif (allow_empty or
(new_value is not None and
new_value != '')):
# If the value is None or '', then don't include this slug at all
if new_value == '':
new_value = None
if param_qualified_name_no_num not in selections:
selections[param_qualified_name_no_num] = []
if allow_empty and clause_num_str:
str_selection = selections[param_qualified_name_no_num]
len_s = len(str_selection)
if len_s < clause_num:
str_selection += [None] * (clause_num-len_s)
str_selection[clause_num-1] = new_value
else:
selections[param_qualified_name_no_num].append(new_value)
if param_qualified_name_no_num not in qtypes:
qtypes[param_qualified_name_no_num] = []
if allow_empty and clause_num_str:
str_qtype = qtypes[param_qualified_name_no_num]
len_qtype = len(str_qtype)
if len_qtype < clause_num:
str_qtype += [None] * (clause_num-len_qtype)
str_qtype[clause_num-1] = qtype_val
else:
qtypes[param_qualified_name_no_num].append(qtype_val)
extras['qtypes'] = qtypes
extras['units'] = units
# log.debug('url_to_search_params: GET %s *** Selections %s *** Extras %s',
# request_get, str(selections), str(extras))
return selections, extras
def get_user_query_table(selections, extras, api_code=None):
"""Perform a data search and create a table of matching IDs.
This is THE main data query place.
- Look in the "user_searches" table to see if this search has already
been requested before. If so, retrieve the cache table number. If not,
create the entry in "user_searches", which assigns a cache table number.
- See if the cache table name has been cached in memory. (This means that
we are SURE the table actually exists and don't have to check again)
- If so, return the cached table name.
- Otherwise, try to perform the search and store the results in the
cache_NNN table.
- If the table already existed, or was in the process of being created
by another process, this will throw an error (after possibly waiting for
the lock to clear), which we ignore.
- Store the cache table name in the memory cache and return it. (At this
point we KNOW the table exists and has been fully populated)
The cache_NNN table has two columns:
1) sort_order: A unique, monotonically increasing id that gives the
order of the results based on the sort order requested when the
search was done.
2) id: A unique is corresponding to the obs_general.id of the
observation.
Note: The function url_to_search_params takes the user HTTP request object
and creates the data objects that are passed to this function.
"""
cursor = connection.cursor()
if selections is None or extras is None: # pragma: no cover
# This should never happen...
return None
# Create a cache key
cache_table_num, cache_new_flag = set_user_search_number(selections, extras)
if cache_table_num is None: # pragma: no cover
log.error('get_user_query_table: Failed to make entry in user_searches'+
' *** Selections %s *** Extras %s',
str(selections), str(extras))
return None
cache_table_name = get_user_search_table_name(cache_table_num)
# Is this key set in the cache?
cache_key = (settings.CACHE_SERVER_PREFIX + settings.CACHE_KEY_PREFIX
+ ':cache_table:' + str(cache_table_num))
cached_val = cache.get(cache_key)
if cached_val:
return cached_val
# Try to create the table using the selection criteria.
# If the table already exists from earlier, this will throw a
# MYSQL_TABLE_ALREADY_EXISTS exception and we can just return the table
# name.
# If the table is in the process of being created by another process,
# the CREATE TABLE will hang due to the lock and eventually return
# when the CREATE TABLE is finished, at which point it will throw
# a MYSQL_TABLE_ALREADY_EXISTS exception and we can just return the table
# name.
sql, params = construct_query_string(selections, extras)
if sql is None: # pragma: no cover
log.error('get_user_query_table: construct_query_string failed'
+' *** Selections %s *** Extras %s',
str(selections), str(extras))
return None
if not sql: # pragma: no cover
log.error('get_user_query_table: Query string is empty'
+' *** Selections %s *** Extras %s',
str(selections), str(extras))
return None
# With this we can create a table that contains the single column
create_sql = ('CREATE TABLE '
+ connection.ops.quote_name(cache_table_name)
+ '(sort_order INT NOT NULL AUTO_INCREMENT, '
+ 'PRIMARY KEY(sort_order), id INT UNSIGNED, '
+ 'UNIQUE KEY(id)) '
+ sql)
try:
time1 = time.time()
cursor.execute(create_sql, tuple(params))
except DatabaseError as e: # pragma: no cover
if e.args[0] == MYSQL_TABLE_ALREADY_EXISTS: # pragma: no cover
cache.set(cache_key, cache_table_name)
return cache_table_name
log.error('get_user_query_table: "%s" with params "%s" failed with '
+'%s', create_sql, str(tuple(params)), str(e))
return None
log.debug('API %s (%.3f) get_user_query_table: %s *** PARAMS %s',
str(api_code), time.time()-time1, create_sql, str(params))
cache.set(cache_key, cache_table_name)
return cache_table_name
def set_user_search_number(selections, extras):
"""Creates a new row in the user_searches table for each search request.
This table lists query params+values plus any extra info needed to
run a data search query.
This method looks in user_searches table for current selections.
If none exist, creates it.
Returns the number of the cache table that should be used along with a flag
indicating if this is a new entry in user_searches so the cache table
shouldn't exist yet.
"""
if selections is None or extras is None: # pragma: no cover
return None, False
selections_json = str(json.dumps(sort_dictionary(selections)))
selections_hash = hashlib.md5(str.encode(selections_json)).hexdigest()
qtypes_json = None
qtypes_hash = 'NONE' # Needed for UNIQUE constraint to work
if 'qtypes' in extras:
qtypes = extras['qtypes']
# Remove qtypes that aren't used for searching because they don't
# do anything to make the search unique
new_qtypes = {}
for qtype, val in qtypes.items():
qtype_no_num = strip_numeric_suffix(qtype)
if (qtype_no_num in selections or
qtype_no_num+'1' in selections or
qtype_no_num+'2' in selections):
new_qtypes[qtype] = val
if len(new_qtypes):
qtypes_json = str(json.dumps(sort_dictionary(new_qtypes)))
qtypes_hash = hashlib.md5(str.encode(qtypes_json)).hexdigest()
units_json = None
units_hash = 'NONE' # Needed for UNIQUE constraint to work
if 'units' in extras:
units = extras['units']
# Remove units that aren't used for searching because they don't
# do anything to make the search unique
new_units = {}
for unit, val in units.items():
unit_no_num = strip_numeric_suffix(unit)
if (unit_no_num in selections or
unit_no_num+'1' in selections or
unit_no_num+'2' in selections):
new_units[unit] = val
if len(new_units):
units_json = str(json.dumps(sort_dictionary(new_units)))
units_hash = hashlib.md5(str.encode(units_json)).hexdigest()
order_json = None
order_hash = 'NONE' # Needed for UNIQUE constraint to work
if 'order' in extras:
order_json = str(json.dumps(extras['order']))
order_hash = hashlib.md5(str.encode(order_json)).hexdigest()
cache_key = (settings.CACHE_SERVER_PREFIX + settings.CACHE_KEY_PREFIX
+':usersearchno:selections_hash:' + str(selections_hash)
+':qtypes_hash:' + str(qtypes_hash)
+':units_hash:' + str(units_hash)
+':order_hash:' + str(order_hash))
cached_val = cache.get(cache_key)
if cached_val is not None:
return cached_val, False
# This operation has to be atomic because multiple threads may be trying
# to lookup/create the same selections entry at the same time. Thus,
# rather than looking it up, and then creating it if it doesn't exist
# (which leaves a nice hole for two threads to try to create it
# simultaneously), instead we go ahead and try to create it and let the
# UNIQUE CONSTRAINT on the hash fields throw an error if it already exists.
# That gives us an atomic write.
new_entry = False
s = UserSearches(selections_json=selections_json,
selections_hash=selections_hash,
qtypes_json=qtypes_json,
qtypes_hash=qtypes_hash,
units_json=units_json,
units_hash=units_hash,
order_json=order_json,
order_hash=order_hash)
try:
s.save()
new_entry = True
except IntegrityError:
# This means it's already there and we tried to duplicate the constraint
s = UserSearches.objects.get(selections_hash=selections_hash,
qtypes_hash=qtypes_hash,
units_hash=units_hash,
order_hash=order_hash)
except UserSearches.MultipleObjectsReturned: # pragma: no cover
# This really shouldn't be possible
s = UserSearches.objects.filter(selections_hash=selections_hash,
qtypes_hash=qtypes_hash,
units_hash=units_hash,
order_hash=order_hash)
s = s[0]
log.error('set_user_search_number: Multiple entries in user_searches'
+' for *** Selections %s *** Qtypes %s *** Units %s '
+' *** Order %s',
str(selections_json),
str(qtypes_json),
str(units_json),
str(order_json))
cache.set(cache_key, s.id)
return s.id, new_entry
def get_param_info_by_slug(slug, source):
"""Given a slug, look up the corresponding ParamInfo.
If source == 'col', then this is a column name. We look at the
slug name as given (current or old).
If source == 'widget', then this is a widget name. Widget names have a
'1' on the end even if they are single-column ranges, so we just remove the
'1' before searching if we don't find the original name.
If source == 'qtype', then this is a qtype for a column. Qtypes don't have
any numeric suffix, even if though the columns do, so we just add on a '1'
if we don't find the original name. This also gets used for looking up
'unit' slugs.
If source == 'search', then this is a search term. Numeric search terms
can always have a '1' or '2' suffix even for single-column ranges.
"""
assert source in ('col', 'widget', 'qtype', 'search')
# Qtypes are forbidden from having a numeric suffix`
if source == 'qtype' and slug[-1] in ('1', '2'): # pragma: no cover
log.error('get_param_info_by_slug: Qtype slug "%s" has unpermitted '+
'numeric suffix', slug)
return None
ret = None
# Current slug as given
try:
ret = ParamInfo.objects.get(slug=slug)
except ParamInfo.DoesNotExist:
pass
if not ret:
# Old slug as given
try:
ret = ParamInfo.objects.get(old_slug=slug)
except ParamInfo.DoesNotExist:
pass
if ret:
if source == 'search':
if slug[-1] in ('1', '2'):
# Search slug has 1/2, param_info has 1/2 - all is good
return ret
# For a single-column range, the slug we were given MUST end
# in a '1' or '2' - but for non-range types, it's OK to not
# have the '1' or '2'. Note the non-single-column ranges were
# already dealt with above.
(form_type, form_type_format,
form_type_unit_id) = parse_form_type(ret.form_type)
if form_type in settings.RANGE_FORM_TYPES: # pragma: no cover
# Whoops! We are missing the numeric suffix.
return None
return ret
# For widgets, if this is a multi-column range, return the version with
# the '1' suffix.
if source == 'widget':
try:
return ParamInfo.objects.get(slug=slug+'1')
except ParamInfo.DoesNotExist:
pass
try:
return ParamInfo.objects.get(old_slug=slug+'1')
except ParamInfo.DoesNotExist:
pass
# Q-types can never have a '1' or '2' suffix, but the database entries
# might.
if source == 'qtype' and slug[-1] not in ('1', '2'):
try:
return ParamInfo.objects.get(slug=slug+'1')
except ParamInfo.DoesNotExist:
pass
try:
return ParamInfo.objects.get(old_slug=slug+'1')
except ParamInfo.DoesNotExist:
pass
# Searching on a single-column range is done with '1' or '2' suffixes
# even though the database entry is just a single column without a numeric
# suffix.
if source == 'search' and (slug[-1] == '1' or slug[-1] == '2'):
ret = None
try:
ret = ParamInfo.objects.get(slug=slug[:-1])
except ParamInfo.DoesNotExist:
pass
if not ret:
try:
ret = ParamInfo.objects.get(old_slug=slug[:-1])
except ParamInfo.DoesNotExist:
pass
if ret:
(form_type, form_type_format,
form_type_unit_id) = parse_form_type(ret.form_type)
if form_type not in settings.RANGE_FORM_TYPES:
# Whoops! It's not a range, but we have a numeric suffix.
return None
return ret
log.error('get_param_info_by_slug: Slug "%s" source "%s" not found',
slug, source)
return None
################################################################################
#
# CREATE AN SQL QUERY
#
################################################################################
def construct_query_string(selections, extras):
"""Given a set selections,extras generate the appropriate SQL SELECT"""
all_qtypes = extras['qtypes'] if 'qtypes' in extras else []
all_units = extras['units'] if 'units' in extras else []
finished_ranges = [] # Ranges are done for both sides at once so track
# which are finished to avoid duplicates
clauses = []
clause_params = []
obs_tables = set()
mult_tables = set()
# We always have to have obs_general since it's the master keeper of IDs
obs_tables.add('obs_general')
# We sort this so that testing results are predictable
for param_qualified_name in sorted(selections.keys()):
value_list = selections[param_qualified_name]
# Lookup info about this param_qualified_name
param_qualified_name_no_num = strip_numeric_suffix(param_qualified_name)
param_info = _get_param_info_by_qualified_name(param_qualified_name)
if not param_info:
log.error('construct_query_string: No param_info for "%s"'
+' *** Selections %s *** Extras *** %s',
param_qualified_name,
str(selections), str(extras))
return None, None
cat_name = param_info.category_name
quoted_cat_name = connection.ops.quote_name(cat_name)
if param_qualified_name_no_num in all_qtypes:
qtypes = all_qtypes[param_qualified_name_no_num]
else:
qtypes = []
if param_qualified_name_no_num in all_units:
units = all_units[param_qualified_name_no_num]
else:
units = []
(form_type, form_type_format,
form_type_unit_id) = parse_form_type(param_info.form_type)
if form_type in settings.MULT_FORM_TYPES:
# This is where we convert from the "pretty" name the user selected
# to the internal name stored in the database and mapped to the
# mult table.
mult_name = get_mult_name(param_qualified_name)
model_name = mult_name.title().replace('_','')
model = apps.get_model('search', model_name)
mult_values = [x['pk'] for x in
list(model.objects.filter( Q(label__in=value_list)
| Q(value__in=value_list))
.values('pk'))]
if len(mult_values) != len(value_list):
log.error('construct_query_string: Bad mult data for "%s", '
+'found %s'
+' *** Selections %s *** Extras *** %s',
param_qualified_name,
str(mult_values), str(selections), str(extras))
return None, None
if mult_values:
clause = (quoted_cat_name+'.'
+connection.ops.quote_name(mult_name))
clause += ' IN ('
clause += ','.join(['%s']*len(mult_values))
clause += ')'
clauses.append(clause)
clause_params += mult_values
obs_tables.add(cat_name)
elif form_type in settings.RANGE_FORM_TYPES:
# This prevents range queries from getting through twice.
# If one range side has been processed we can skip the 2nd, because
# it gets done when the first is.
if param_qualified_name_no_num in finished_ranges:
continue
finished_ranges.append(param_qualified_name_no_num)
clause = None
params = None
# Longitude queries
if form_type == 'LONG':
# This parameter requires a longitudinal query.
# Both sides of range must be defined by user for this to work.
clause, params = get_longitude_query(selections,
param_qualified_name,
qtypes, units)
else:
# Get the range query object and append it to the query
clause, params = get_range_query(selections,
param_qualified_name,
qtypes, units)
if clause is None:
return None, None
if clause:
clauses.append(clause)
clause_params += params
obs_tables.add(cat_name)
elif form_type == 'STRING': # pragma: no cover
clause, params = get_string_query(selections, param_qualified_name,
qtypes)
if clause is None:
return None, None
clauses.append(clause)
clause_params += params
obs_tables.add(cat_name)
else: # pragma: no cover
log.error('construct_query_string: Unknown field type "%s" for '
+'param "%s"', form_type, param_qualified_name)
return None, None
# Make the ordering SQL
order_sql = ''
if 'order' in extras:
order_params, descending_params = extras['order']
(order_sql, order_mult_tables,
order_obs_tables) = create_order_by_sql(order_params,
descending_params)
if order_sql is None:
return None, None
mult_tables |= order_mult_tables
obs_tables |= order_obs_tables
sql = 'SELECT '
sql += connection.ops.quote_name('obs_general')+'.'
sql += connection.ops.quote_name('id')
# Now JOIN all the obs_ tables together
sql += ' FROM '+connection.ops.quote_name('obs_general')
for table in sorted(obs_tables):
if table == 'obs_general':
continue
sql += ' LEFT JOIN '+connection.ops.quote_name(table)
sql += ' ON '+connection.ops.quote_name('obs_general')+'.'
sql += connection.ops.quote_name('id')+'='
sql += connection.ops.quote_name(table)+'.'
sql += connection.ops.quote_name('obs_general_id')
# And JOIN all the mult_ tables together
for mult_table, category in sorted(mult_tables):
sql += ' LEFT JOIN '+connection.ops.quote_name(mult_table)
sql += ' ON '+connection.ops.quote_name(category)+'.'
sql += connection.ops.quote_name(mult_table)+'='
sql += connection.ops.quote_name(mult_table)+'.'
sql += connection.ops.quote_name('id')
# Add in the WHERE clauses
if clauses:
sql += ' WHERE '
if len(clauses) == 1:
sql += clauses[0]
else:
sql += ' AND '.join(['('+c+')' for c in clauses])
# Add in the ORDER BY clause
sql += order_sql
# log.debug('SEARCH SQL: %s *** PARAMS %s', sql, str(clause_params))
return sql, clause_params
def _valid_regex(r):
# Validate the regex syntax. The only way to do this with certainty
# is to actually try it on the SQL server and see if it throws
# an error. No need to log this, though, because it's just bad
# user input, not a real internal error.
cursor = connection.cursor()
try:
cursor.execute('SELECT REGEXP_LIKE("x", %s)', (r,))
except DatabaseError:
return False
return True
def get_string_query(selections, param_qualified_name, qtypes):
"""Builds query for strings.
The following q-types are supported:
contains
begins
ends
matches
excludes
"""
if selections is None or param_qualified_name not in selections:
return None, None
values = selections[param_qualified_name]
param_info = _get_param_info_by_qualified_name(param_qualified_name)
if not param_info:
return None, None
(form_type, form_type_format,
form_type_unit_id) = parse_form_type(param_info.form_type)
cat_name = param_info.category_name
quoted_cat_name = connection.ops.quote_name(cat_name)
name = param_info.name
quoted_param_qualified_name = (quoted_cat_name+'.'
+connection.ops.quote_name(name))
if len(qtypes) == 0:
qtypes = ['contains'] * len(values)
if len(qtypes) != len(values):
log.error('get_string_query: Inconsistent qtype/values lengths '
+'for "%s" '
+'*** Selections %s *** Qtypes %s ***',
param_qualified_name, str(selections), str(qtypes))
return None, None
clauses = []
params = []
for idx in range(len(values)):
value = values[idx]
qtype = qtypes[idx]
clause = ''
if qtype != 'regex':
value = value.replace('\\', '\\\\')
if qtype != 'matches':
value = value.replace('%', '\\%')
value = value.replace('_', '\\_')
if qtype == 'contains':
clause = quoted_param_qualified_name + ' LIKE %s'
params.append('%'+value+'%')
elif qtype == 'begins':
clause = quoted_param_qualified_name + ' LIKE %s'
params.append(value+'%')
elif qtype == 'ends':
clause = quoted_param_qualified_name + ' LIKE %s'
params.append('%'+value)
elif qtype == 'matches':
clause = quoted_param_qualified_name + ' = %s'
params.append(value)
elif qtype == 'excludes':
clause = quoted_param_qualified_name + ' NOT LIKE %s'
params.append('%'+value+'%')
elif qtype == 'regex':
if not _valid_regex(value):
return None, None
clause = quoted_param_qualified_name + ' RLIKE %s'
params.append(value)
else:
log.error('_get_string_query: Unknown qtype "%s" '
+'for "%s" '
+'*** Selections %s *** Qtypes %s ***',
qtype, param_qualified_name, str(selections), str(qtypes))
return None, None
if clause: # pragma: no cover
clauses.append(clause)
if len(clauses) == 1:
clause = clauses[0]
else:
clause = ' OR '.join(['('+c+')' for c in clauses])
return clause, params
def get_range_query(selections, param_qualified_name, qtypes, units):
"""Builds query for numeric ranges.
This can either be a single column range (one table column holds the value)
or a normal dual-column range (2 table columns hold min and max values).
The following q-types are supported:
any
all
only
"""
if selections is None:
return None, None
param_info = _get_param_info_by_qualified_name(param_qualified_name)
if not param_info:
return None, None
(form_type, form_type_format,
form_type_unit_id) = parse_form_type(param_info.form_type)
param_qualified_name_no_num = strip_numeric_suffix(param_qualified_name)
param_qualified_name_min = param_qualified_name_no_num + '1'
param_qualified_name_max = param_qualified_name_no_num + '2'
values_min = selections.get(param_qualified_name_min, [])
values_max = selections.get(param_qualified_name_max, [])
(form_type, form_type_format,
form_type_unit_id) = parse_form_type(param_info.form_type)
if qtypes is None or len(qtypes) == 0:
qtypes = ['any'] * len(values_min)
if units is None or len(units) == 0:
default_unit = get_default_unit(form_type_unit_id)
units = [default_unit] * len(values_min)
# But, for constructing the query, if this is a single column range,
# the param_names are both the same
cat_name = param_info.category_name
quoted_cat_name = connection.ops.quote_name(cat_name)
name_no_num = strip_numeric_suffix(param_info.name)
name_min = name_no_num + '1'
name_max = name_no_num + '2'
if is_single_column_range(param_qualified_name):
param_qualified_name_min = param_qualified_name_no_num
param_qualified_name_max = param_qualified_name_no_num
name_min = name_max = name_no_num
for qtype in qtypes:
if qtype != 'any':
log.error('get_range_query: bad qtype "%s" '
+'for "%s" '
+'*** Selections %s *** Qtypes %s *** Units %s',
qtype, param_qualified_name,
str(selections), str(qtypes), str(units))
return None, None
# qtypes are meaningless for single column ranges!
qtypes = ['any'] * len(values_min)
quoted_param_qualified_name_min = (quoted_cat_name+'.'
+connection.ops.quote_name(name_min))
quoted_param_qualified_name_max = (quoted_cat_name+'.'
+connection.ops.quote_name(name_max))
if (len(qtypes) != len(values_min) or len(units) != len(values_min) or
len(values_min) != len(values_max)):
log.error('get_range_query: Inconsistent qtype/unit/min/max lengths '
+'for "%s" '
+'*** Selections %s *** Qtypes %s *** Units %s',
param_qualified_name, str(selections), str(qtypes),
str(units))
return None, None
clauses = []
params = []
for idx in range(len(values_min)):
unit = units[idx]
try:
value_min = convert_to_default_unit(values_min[idx],
form_type_unit_id,
unit)
value_max = convert_to_default_unit(values_max[idx],
form_type_unit_id,
unit)
except KeyError:
log.error('get_range_query: Unknown unit "%s" for "%s" '
+'*** Selections %s *** Qtypes %s *** Units %s',
unit, param_qualified_name, str(selections), str(qtypes),
str(units))
return None, None
except ValueError:
log.error('get_range_query: Unit "%s" on "%s" conversion failed '
+'*** Selections %s *** Qtypes %s *** Units %s',
unit, param_qualified_name, str(selections), str(qtypes),
str(units))
return None, None
qtype = qtypes[idx]
clause = ''
if qtype == 'all':
# param_name_min <= value_min AND param_name_max >= value_max
if value_min is not None:
clause += quoted_param_qualified_name_min + ' <= %s'
params.append(value_min)
if value_max is not None:
if clause:
clause += ' AND '
clause += quoted_param_qualified_name_max + ' >= %s'
params.append(value_max)
if clause:
clauses.append(clause)
elif qtype == 'only':
# param_name_min >= value_min AND param_name_max <= value_max
if value_min is not None:
clause += quoted_param_qualified_name_min + ' >= %s'
params.append(value_min)
if value_max is not None:
if clause:
clause += ' AND '
clause += quoted_param_qualified_name_max + ' <= %s'
params.append(value_max)
if clause:
clauses.append(clause)
elif qtype == 'any' or qtype == '':
# param_name_min <= value_max AND param_name_max >= value_min
if value_min is not None:
clause += quoted_param_qualified_name_max + ' >= %s'
params.append(value_min)
if value_max is not None:
if clause:
clause += ' AND '
clause += quoted_param_qualified_name_min + ' <= %s'
params.append(value_max)
if clause:
clauses.append(clause)
else:
log.error('get_range_query: Unknown qtype "%s" '
+'for "%s" '
+'*** Selections %s *** Qtypes %s *** Units %s',
qtype, param_qualified_name,
str(selections), str(qtypes), str(units))
return None, None
if len(clauses) == 1:
clause = clauses[0]
else:
clause = ' OR '.join(['('+c+')' for c in clauses])
return clause, params
def get_longitude_query(selections, param_qualified_name, qtypes, units):
"""Builds query for longitude ranges.
Both sides of the range must be specified.
The following q-types are supported:
any
all
only
"""
if selections is None:
return None, None
param_info = _get_param_info_by_qualified_name(param_qualified_name)
if not param_info:
return None, None
(form_type, form_type_format,
form_type_unit_id) = parse_form_type(param_info.form_type)
param_qualified_name_no_num = strip_numeric_suffix(param_qualified_name)
param_qualified_name_min = param_qualified_name_no_num + '1'
param_qualified_name_max = param_qualified_name_no_num + '2'
values_min = selections.get(param_qualified_name_min, [])
values_max = selections.get(param_qualified_name_max, [])
# But, for constructing the query, if this is a single column range,
# the param_names are both the same
cat_name = param_info.category_name
quoted_cat_name = connection.ops.quote_name(cat_name)
name_no_num = strip_numeric_suffix(param_info.name)
col_d_long = cat_name + '.d_' + name_no_num
(form_type, form_type_format,
form_type_unit_id) = parse_form_type(param_info.form_type)
if qtypes is None or len(qtypes) == 0:
qtypes = ['any'] * len(values_min)
if units is None or len(units) == 0:
default_unit = get_default_unit(form_type_unit_id)
units = [default_unit] * len(values_min)
if (len(qtypes) != len(values_min) or len(units) != len(values_min) or
len(values_min) != len(values_max)):
log.error('get_longitude_query: Inconsistent qtype/unit/min/max lengths '
+'for "%s" '
+'*** Selections %s *** Qtypes %s *** Units %s',
param_qualified_name, str(selections), str(qtypes),
str(units))
return None, None
clauses = []
params = []
for idx in range(len(values_min)):
unit = units[idx]
try:
value_min = convert_to_default_unit(values_min[idx],
form_type_unit_id,
unit)
value_max = convert_to_default_unit(values_max[idx],
form_type_unit_id,
unit)
except KeyError:
log.error('get_longitude_query: Unknown unit "%s" for "%s" '
+'*** Selections %s *** Qtypes %s *** Units %s',
unit, param_qualified_name, str(selections), str(qtypes),
str(units))
return None, None
except ValueError:
log.error('get_longitude_query: Unit "%s" on "%s" conversion '
+'failed '
+'*** Selections %s *** Qtypes %s *** Units %s',
unit, param_qualified_name, str(selections), str(qtypes),
str(units))
return None, None
qtype = qtypes[idx]
if value_min is None and value_max is None:
# Ignore if nothing to search on
continue
clause = ''
if value_min is None or value_max is None:
# Pretend this is a range query - fake up a new selections and
# qtypes containing only this one entry
new_selections = {param_qualified_name_min: [value_min],
param_qualified_name_max: [value_max]}
new_qtypes = [qtype]
clause, r_params = get_range_query(new_selections,
param_qualified_name,
new_qtypes, None)
if clause is None:
return None, None
params += r_params
elif is_single_column_range(param_qualified_name):
# A single column range doesn't have center and d_ fields
if qtype != 'any':
log.error('get_longitude_query: Bad qtype "%s" for "%s" '
+'*** Selections %s *** Qtypes %s *** Units %s',
qtype, param_qualified_name,
str(selections), str(qtypes), str(units))
return None, None
quoted_param_qualified_name = (quoted_cat_name+'.'
+connection.ops.quote_name(name_no_num))
if value_max >= value_min:
# Normal range MIN to MAX
clause = quoted_param_qualified_name + ' >= %s AND '
clause += quoted_param_qualified_name + ' <= %s'
params.append(value_min)
params.append(value_max)
else:
# Wraparound range MIN to 360, 0 to MAX
clause = quoted_param_qualified_name + ' >= %s OR '
clause += quoted_param_qualified_name + ' <= %s'
params.append(value_min)
params.append(value_max)
else:
# Find the midpoint and dx of the user's range
if value_max >= value_min:
longit = (value_min + value_max)/2.
else:
longit = (value_min + value_max + 360.)/2.
longit = longit % 360.
d_long = (longit - value_min) % 360.
sep_sql = 'ABS(MOD(%s - ' + param_qualified_name_no_num + ' + 540., 360.) - 180.)'
sep_params = [longit]
if qtype == 'any' or qtype == '':
clause += sep_sql + ' <= %s + ' + col_d_long
params += sep_params
params.append(d_long)
elif qtype == 'all':
clause += sep_sql + ' <= ' + col_d_long + ' - %s'
params += sep_params
params.append(d_long)
elif qtype == 'only':
clause += sep_sql + ' <= %s - ' + col_d_long
params += sep_params
params.append(d_long)
else:
log.error('get_longitude_query: Unknown qtype "%s" '
+'for "%s"'
+'*** Selections %s *** Qtypes %s *** Units %s',
qtype, param_qualified_name,
str(selections), str(qtypes), str(units))
return None, None
if clause: # pragma: no cover
clauses.append(clause)
if len(clauses) == 1:
clause = clauses[0]
else:
clause = ' OR '.join(['('+c+')' for c in clauses])
return clause, params
def get_user_search_table_name(num):
""" pass cache_no, returns user search table name"""
return 'cache_' + str(num)
################################################################################
#
# INTERNAL SUPPORT ROUTINES
#
################################################################################
def _get_param_info_by_qualified_name(param_qualified_name):
"Given a qualified name cat.name return the ParamInfo"
if param_qualified_name.find('.') == -1:
return None
cat_name = param_qualified_name.split('.')[0]
name = param_qualified_name.split('.')[1]
try:
return ParamInfo.objects.get(category_name=cat_name, name=name)
except ParamInfo.DoesNotExist:
# Single column range queries will not have the numeric suffix
name_no_num = strip_numeric_suffix(name)
try:
return ParamInfo.objects.get(category_name=cat_name,
name=name_no_num)
except ParamInfo.DoesNotExist:
return None
def is_single_column_range(param_qualified_name):
"Given a qualified name cat.name return True if it's a single-column range"
if param_qualified_name.find('.') == -1:
return False
cat_name = param_qualified_name.split('.')[0]
name = param_qualified_name.split('.')[1]
# Single column range queries will not have the numeric suffix
name_no_num = strip_numeric_suffix(name)
try:
_ = ParamInfo.objects.get(category_name=cat_name,
name=name_no_num)
return True
except ParamInfo.DoesNotExist:
return False
return False
def _clean_numeric_field(s):
def clean_func(x):
return x.replace(' ', '').replace(',', '').replace('_','')
if isinstance(s, (list, tuple)):
return [clean_func(z) for z in s]
return clean_func(s)
def parse_order_slug(all_order):
"Given a list of slugs a,b,-c,d create the params and descending lists"
order_params = []
order_descending_params = []
if not all_order:
all_order = settings.DEFAULT_SORT_ORDER
if (settings.FINAL_SORT_ORDER
not in all_order.replace('-','').split(',')):
if all_order:
all_order += ','
all_order += settings.FINAL_SORT_ORDER
orders = all_order.split(',')
for order in orders:
descending = order[0] == '-'
order = order.strip('-')
param_info = get_param_info_by_slug(order, 'col')
if not param_info:
log.error('parse_order_slug: Unable to resolve order '
+'slug "%s"', order)
return None, None
order_param = param_info.param_qualified_name()
if order_param == 'obs_pds.opus_id':
# Force opus_id to be from obs_general for efficiency
order_param = 'obs_general.opus_id'
order_params.append(order_param)
order_descending_params.append(descending)
return order_params, order_descending_params
def create_order_by_sql(order_params, descending_params):
"Given params and descending lists, make ORDER BY SQL"
order_mult_tables = set()
order_obs_tables = set()
order_sql = ''
if order_params:
order_str_list = []
for i in range(len(order_params)):
order_slug = order_params[i]
pi = _get_param_info_by_qualified_name(order_slug)
if not pi:
log.error('create_order_by_sql: Unable to resolve order'
+' slug "%s"', order_slug)
return None, None, None
(form_type, form_type_format,
form_type_unit_id) = parse_form_type(pi.form_type)
order_param = pi.param_qualified_name()
order_obs_tables.add(pi.category_name)
if form_type in settings.MULT_FORM_TYPES:
mult_table = get_mult_name(pi.param_qualified_name())
order_param = mult_table + '.label'
order_mult_tables.add((mult_table, pi.category_name))
if descending_params[i]:
order_param += ' DESC'
else:
order_param += ' ASC'
order_str_list.append(order_param)
order_sql = ' ORDER BY ' + ','.join(order_str_list)
return order_sql, order_mult_tables, order_obs_tables
| []
| []
| []
| [] | [] | python | null | null | null |
pkg/camo/proxy_test.go | // Copyright (c) 2012-2019 Eli Janssen
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package camo
import (
"flag"
"fmt"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
"github.com/cactus/mlog"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
)
var camoConfig = Config{
HMACKey: []byte("0x24FEEDFACEDEADBEEFCAFE"),
MaxSize: 5120 * 1024,
RequestTimeout: time.Duration(10) * time.Second,
MaxRedirects: 3,
ServerName: "go-camo",
AllowContentVideo: false,
AllowCredetialURLs: false,
}
func skipIfCI(t *testing.T) {
if os.Getenv("CI") != "" {
t.Skip("Skipping test. CI environments generally enable something similar to unbound's private-address functionality, making this test fail.")
}
}
func TestNotFound(t *testing.T) {
t.Parallel()
req, err := http.NewRequest("GET", "http://example.com/favicon.ico", nil)
assert.Check(t, err)
resp, err := processRequest(req, 404, camoConfig, nil)
if assert.Check(t, err) {
statusCodeAssert(t, 404, resp)
bodyAssert(t, "404 Not Found\n", resp)
headerAssert(t, "test", "X-Go-Camo", resp)
headerAssert(t, "go-camo", "Server", resp)
}
}
func TestSimpleValidImageURL(t *testing.T) {
t.Parallel()
testURL := "http://www.google.com/images/srpr/logo11w.png"
resp, err := makeTestReq(testURL, 200, camoConfig)
if assert.Check(t, err) {
headerAssert(t, "test", "X-Go-Camo", resp)
headerAssert(t, "go-camo", "Server", resp)
}
}
func TestGoogleChartURL(t *testing.T) {
t.Parallel()
testURL := "http://chart.apis.google.com/chart?chs=920x200&chxl=0:%7C2010-08-13%7C2010-09-12%7C2010-10-12%7C2010-11-11%7C1:%7C0%7C0%7C0%7C0%7C0%7C0&chm=B,EBF5FB,0,0,0&chco=008Cd6&chls=3,1,0&chg=8.3,20,1,4&chd=s:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&chxt=x,y&cht=lc"
_, err := makeTestReq(testURL, 200, camoConfig)
assert.Check(t, err)
}
func TestChunkedImageFile(t *testing.T) {
t.Parallel()
testURL := "https://www.igvita.com/posts/12/spdyproxy-diagram.png"
_, err := makeTestReq(testURL, 200, camoConfig)
assert.Check(t, err)
}
func TestFollowRedirects(t *testing.T) {
t.Parallel()
testURL := "http://cl.ly/1K0X2Y2F1P0o3z140p0d/boom-headshot.gif"
_, err := makeTestReq(testURL, 200, camoConfig)
assert.Check(t, err)
}
func TestStrangeFormatRedirects(t *testing.T) {
t.Parallel()
testURL := "http://cl.ly/DPcp/Screen%20Shot%202012-01-17%20at%203.42.32%20PM.png"
_, err := makeTestReq(testURL, 200, camoConfig)
assert.Check(t, err)
}
func TestRedirectsWithPathOnly(t *testing.T) {
t.Parallel()
testURL := "http://mockbin.org/redirect/302?to=%2Fredirect%2F302%3Fto%3Dhttp%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo11w.png"
_, err := makeTestReq(testURL, 200, camoConfig)
assert.Check(t, err)
}
func TestFollowPermRedirects(t *testing.T) {
t.Parallel()
testURL := "http://mockbin.org/redirect/301?to=http://www.google.com/images/srpr/logo11w.png"
_, err := makeTestReq(testURL, 200, camoConfig)
assert.Check(t, err)
}
func TestFollowTempRedirects(t *testing.T) {
t.Parallel()
testURL := "http://mockbin.org/redirect/302?to=http://www.google.com/images/srpr/logo11w.png"
_, err := makeTestReq(testURL, 200, camoConfig)
assert.Check(t, err)
}
func TestBadContentType(t *testing.T) {
t.Parallel()
testURL := "http://httpbin.org/response-headers?Content-Type=what"
_, err := makeTestReq(testURL, 400, camoConfig)
assert.Check(t, err)
}
func TestContentTypeParams(t *testing.T) {
t.Parallel()
testURL := "http://httpbin.org/response-headers?Content-Type=image/svg%2Bxml;charset=UTF-8"
resp, err := makeTestReq(testURL, 200, camoConfig)
assert.Check(t, err)
if assert.Check(t, err) {
headerAssert(t, "image/svg+xml; charset=UTF-8", "content-type", resp)
}
}
func TestBadContentTypeSmuggle(t *testing.T) {
t.Parallel()
testURL := "http://httpbin.org/response-headers?Content-Type=image/png,%20text/html;%20charset%3DUTF-8"
_, err := makeTestReq(testURL, 400, camoConfig)
assert.Check(t, err)
testURL = "http://httpbin.org/response-headers?Content-Type=image/png,text/html;%20charset%3DUTF-8"
_, err = makeTestReq(testURL, 400, camoConfig)
assert.Check(t, err)
testURL = "http://httpbin.org/response-headers?Content-Type=image/png%20text/html"
_, err = makeTestReq(testURL, 400, camoConfig)
assert.Check(t, err)
testURL = "http://httpbin.org/response-headers?Content-Type=image/png%;text/html"
_, err = makeTestReq(testURL, 400, camoConfig)
assert.Check(t, err)
testURL = "http://httpbin.org/response-headers?Content-Type=image/png;%20charset%3DUTF-8;text/html"
_, err = makeTestReq(testURL, 400, camoConfig)
assert.Check(t, err)
}
func TestXForwardedFor(t *testing.T) {
t.Parallel()
camoConfigWithoutFwd4 := Config{
HMACKey: []byte("0x24FEEDFACEDEADBEEFCAFE"),
MaxSize: 180 * 1024,
RequestTimeout: time.Duration(10) * time.Second,
MaxRedirects: 3,
ServerName: "go-camo",
EnableXFwdFor: true,
noIPFiltering: true,
}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Close = true
w.Header().Set("Content-Type", "image/png")
_, err := w.Write([]byte(r.Header.Get("X-Forwarded-For")))
assert.Check(t, err)
}))
defer ts.Close()
req, err := makeReq(camoConfig, ts.URL)
assert.Check(t, err)
req.Header.Set("X-Forwarded-For", "2.2.2.2, 1.1.1.1")
resp, err := processRequest(req, 200, camoConfigWithoutFwd4, nil)
assert.Check(t, err)
bodyAssert(t, "2.2.2.2, 1.1.1.1", resp)
camoConfigWithoutFwd4.EnableXFwdFor = false
resp, err = processRequest(req, 200, camoConfigWithoutFwd4, nil)
assert.Check(t, err)
bodyAssert(t, "", resp)
}
func TestVideoContentTypeAllowed(t *testing.T) {
t.Parallel()
camoConfigWithVideo := Config{
HMACKey: []byte("0x24FEEDFACEDEADBEEFCAFE"),
MaxSize: 180 * 1024,
RequestTimeout: time.Duration(10) * time.Second,
MaxRedirects: 3,
ServerName: "go-camo",
AllowContentVideo: true,
}
testURL := "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4"
// try a range request (should succeed, MaxSize is larger than requested range)
req, err := makeReq(camoConfigWithVideo, testURL)
assert.Check(t, err)
req.Header.Add("Range", "bytes=0-10")
resp, err := processRequest(req, 206, camoConfigWithVideo, nil)
assert.Check(t, is.Equal(resp.Header.Get("Content-Range"), "bytes 0-10/2299653"))
assert.Check(t, err)
// try a range request (should fail, MaxSize is smaller than requested range)
camoConfigWithVideo.MaxSize = 1 * 1024
req, err = makeReq(camoConfigWithVideo, testURL)
assert.Check(t, err)
req.Header.Add("Range", "bytes=0-1025")
_, err = processRequest(req, 404, camoConfigWithVideo, nil)
assert.Check(t, err)
// try full request (should fail, too large)
_, err = makeTestReq(testURL, 404, camoConfigWithVideo)
assert.Check(t, err)
// bump limit, try again (should succeed)
camoConfigWithVideo.MaxSize = 5000 * 1024
_, err = makeTestReq(testURL, 200, camoConfigWithVideo)
fmt.Println(err)
assert.Check(t, err)
}
func TestAudioContentTypeAllowed(t *testing.T) {
t.Parallel()
camoConfigWithAudio := Config{
HMACKey: []byte("0x24FEEDFACEDEADBEEFCAFE"),
MaxSize: 180 * 1024,
RequestTimeout: time.Duration(10) * time.Second,
MaxRedirects: 3,
ServerName: "go-camo",
AllowContentAudio: true,
}
testURL := "https://actions.google.com/sounds/v1/alarms/alarm_clock.ogg"
_, err := makeTestReq(testURL, 200, camoConfigWithAudio)
assert.Check(t, err)
// try a range request
req, err := makeReq(camoConfigWithAudio, testURL)
assert.Check(t, err)
req.Header.Add("Range", "bytes=0-10")
resp, err := processRequest(req, 206, camoConfigWithAudio, nil)
assert.Check(t, is.Equal(resp.Header.Get("Content-Range"), "bytes 0-10/49872"))
assert.Check(t, err)
}
func TestCredetialURLsAllowed(t *testing.T) {
t.Parallel()
camoConfigWithCredentials := Config{
HMACKey: []byte("0x24FEEDFACEDEADBEEFCAFE"),
MaxSize: 180 * 1024,
RequestTimeout: time.Duration(10) * time.Second,
MaxRedirects: 3,
ServerName: "go-camo",
AllowCredetialURLs: true,
}
testURL := "http://user:[email protected]/images/srpr/logo11w.png"
_, err := makeTestReq(testURL, 200, camoConfigWithCredentials)
assert.Check(t, err)
}
func TestSupplyAcceptIfNoneGiven(t *testing.T) {
t.Parallel()
testURL := "http://images.anandtech.com/doci/6673/OpenMoboAMD30_575px.png"
req, err := makeReq(camoConfig, testURL)
req.Header.Del("Accept")
assert.Check(t, err)
_, err = processRequest(req, 200, camoConfig, nil)
assert.Check(t, err)
}
func Test404OnVideo(t *testing.T) {
t.Parallel()
testURL := "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerEscapes.mp4"
_, err := makeTestReq(testURL, 400, camoConfig)
assert.Check(t, err)
}
func Test404OnCredentialURL(t *testing.T) {
t.Parallel()
testURL := "http://user:[email protected]/images/srpr/logo11w.png"
_, err := makeTestReq(testURL, 404, camoConfig)
assert.Check(t, err)
}
func Test404InfiniRedirect(t *testing.T) {
t.Parallel()
testURL := "http://mockbin.org/redirect/302/4"
_, err := makeTestReq(testURL, 404, camoConfig)
assert.Check(t, err)
}
func Test404URLWithoutHTTPHost(t *testing.T) {
t.Parallel()
testURL := "/picture/Mincemeat/Pimp.jpg"
_, err := makeTestReq(testURL, 404, camoConfig)
assert.Check(t, err)
}
func Test404ImageLargerThan5MB(t *testing.T) {
t.Parallel()
testURL := "https://apod.nasa.gov/apod/image/0505/larryslookout_spirit_big.jpg"
_, err := makeTestReq(testURL, 404, camoConfig)
assert.Check(t, err)
}
func Test404HostNotFound(t *testing.T) {
t.Parallel()
testURL := "http://flabergasted.cx"
_, err := makeTestReq(testURL, 404, camoConfig)
assert.Check(t, err)
}
func Test404OnExcludes(t *testing.T) {
t.Parallel()
testURL := "http://iphone.internal.example.org/foo.cgi"
_, err := makeTestReq(testURL, 404, camoConfig)
assert.Check(t, err)
}
func Test404OnNonImageContent(t *testing.T) {
t.Parallel()
testURL := "https://github.com/atmos/cinderella/raw/master/bootstrap.sh"
_, err := makeTestReq(testURL, 404, camoConfig)
assert.Check(t, err)
}
func Test404On10xIpRange(t *testing.T) {
t.Parallel()
testURL := "http://10.0.0.1/foo.cgi"
_, err := makeTestReq(testURL, 404, camoConfig)
assert.Check(t, err)
}
func Test404On169Dot254Net(t *testing.T) {
t.Parallel()
testURL := "http://169.254.0.1/foo.cgi"
_, err := makeTestReq(testURL, 404, camoConfig)
assert.Check(t, err)
}
func Test404On172Dot16Net(t *testing.T) {
t.Parallel()
for i := 16; i < 32; i++ {
testURL := "http://172.%d.0.1/foo.cgi"
_, err := makeTestReq(fmt.Sprintf(testURL, i), 404, camoConfig)
assert.Check(t, err)
}
}
func Test404On192Dot168Net(t *testing.T) {
t.Parallel()
testURL := "http://192.168.0.1/foo.cgi"
_, err := makeTestReq(testURL, 404, camoConfig)
assert.Check(t, err)
}
func Test404OnLocalhost(t *testing.T) {
t.Parallel()
testURL := "http://localhost/foo.cgi"
resp, err := makeTestReq(testURL, 404, camoConfig)
if assert.Check(t, err) {
bodyAssert(t, "Bad url host\n", resp)
}
}
func Test404OnLocalhostWithPort(t *testing.T) {
t.Parallel()
testURL := "http://localhost:80/foo.cgi"
resp, err := makeTestReq(testURL, 404, camoConfig)
if assert.Check(t, err) {
bodyAssert(t, "Bad url host\n", resp)
}
}
func Test404OnRedirectWithLocalhostTarget(t *testing.T) {
t.Parallel()
testURL := "http://mockbin.org/redirect/302?to=http://localhost/some.png"
resp, err := makeTestReq(testURL, 404, camoConfig)
if assert.Check(t, err) {
bodyAssert(t, "Error Fetching Resource\n", resp)
}
}
func Test404OnRedirectWithLoopbackIP(t *testing.T) {
t.Parallel()
testURL := "http://mockbin.org/redirect/302?to=http://127.0.0.100/some.png"
resp, err := makeTestReq(testURL, 404, camoConfig)
if assert.Check(t, err) {
bodyAssert(t, "Error Fetching Resource\n", resp)
}
}
func Test404OnRedirectWithLoopbackIPwCreds(t *testing.T) {
t.Parallel()
testURL := "http://mockbin.org/redirect/302?to=http://user:[email protected]/some.png"
resp, err := makeTestReq(testURL, 404, camoConfig)
if assert.Check(t, err) {
bodyAssert(t, "Error Fetching Resource\n", resp)
}
}
// Test will always pass if dns relay implements dns rebind prevention
//
// Even if local dns is doing rebinding prevention, we will still get back the
// same final response. The difference is where the error originates. If there
// is no dns rebinding prevention in the dns resolver, then the proxy code
// rejects in net.dail. If there IS dns rebinding prevention, the dns resolver
// does not return an ip address, and we get a "No address associated with
// hostname" result.
// As such, there is little sense running this when dns rebinding
// prevention is present in the dns resolver....
func Test404OnLoopback(t *testing.T) {
skipIfCI(t)
t.Parallel()
testURL := "http://mockbin.org/redirect/302?to=http://test.vcap.me"
req, err := makeReq(camoConfig, testURL)
assert.Check(t, err)
resp, err := processRequest(req, 404, camoConfig, nil)
if assert.Check(t, err) {
bodyAssert(t, "Error Fetching Resource\n", resp)
}
}
func TestMain(m *testing.M) {
flag.Parse()
debug := os.Getenv("DEBUG")
// now configure a standard logger
mlog.SetFlags(mlog.Lstd)
if debug != "" {
mlog.SetFlags(mlog.Flags() | mlog.Ldebug)
mlog.Debug("debug logging enabled")
}
os.Exit(m.Run())
}
| [
"\"CI\"",
"\"DEBUG\""
]
| []
| [
"CI",
"DEBUG"
]
| [] | ["CI", "DEBUG"] | go | 2 | 0 | |
ucloud-sdk-java-umem/src/test/java/cn/ucloud/umem/client/CreateURedisBackupTest.java | package cn.ucloud.umem.client;
import cn.ucloud.common.pojo.Account;
import cn.ucloud.umem.model.CreateURedisBackupParam;
import cn.ucloud.umem.model.CreateURedisBackupResult;
import cn.ucloud.umem.pojo.UMEMConfig;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertNull;
/**
* @Description : UMEM.CreateURedisBackup 测试
* @Author : ucloud-sdk-generator
* @Date : 2019-03-15 10:00
**/
public class CreateURedisBackupTest {
private UMEMClient client;
private CreateURedisBackupParam param;
@Before
public void setUp() throws Exception {
client = new DefaultUMEMClient(new UMEMConfig(
new Account(System.getenv("UCloudPrivateKey"),
System.getenv("UCloudPublicKey"))));
String region = "cn-sh2";
String groupId = "uredis-pgouk5n1";
String backupName = "bsk";
param = new CreateURedisBackupParam(region, groupId, backupName);
param.setProjectId("org-izug1m");
}
@Test
public void createURedisBackup() {
try {
CreateURedisBackupResult result = client.createURedisBackup(param);
JSONComparator.jsonComparator(result);
} catch (Exception e) {
assertNull(e);
}
}
} | [
"\"UCloudPrivateKey\"",
"\"UCloudPublicKey\""
]
| []
| [
"UCloudPrivateKey",
"UCloudPublicKey"
]
| [] | ["UCloudPrivateKey", "UCloudPublicKey"] | java | 2 | 0 | |
findapi/main.go | package main
import (
"errors"
"flag"
"fmt"
"os"
"runtime"
"github.com/sjsafranek/find5/findapi/lib/api"
"github.com/sjsafranek/find5/findapi/lib/clients/repl"
"github.com/sjsafranek/find5/findapi/lib/clients/web"
"github.com/sjsafranek/find5/findapi/lib/config"
"github.com/sjsafranek/logger"
)
const (
PROJECT string = "Find"
VERSION string = "5.0.7"
DEFAULT_HTTP_PORT int = 8080
DEFAULT_HTTP_HOST string = "localhost"
DEFAULT_HTTP_PROTOCOL string = "http"
DEFAULT_HTTP_DOMAIN string = ""
DEFAULT_DATABASE_ENGINE string = "postgres"
DEFAULT_DATABASE_DATABASE string = "finddb"
DEFAULT_DATABASE_PASSWORD string = "dev"
DEFAULT_DATABASE_USERNAME string = "finduser"
DEFAULT_DATABASE_HOST string = "localhost"
DEFAULT_DATABASE_PORT int64 = 5432
DEFAULT_REDIS_PORT int64 = 6379
DEFAULT_REDIS_HOST string = ""
DEFAULT_AI_HOST string = "localhost"
DEFAULT_AI_PORT int64 = 7005
DEFAULT_CONFIG_FILE string = "config.json"
)
var (
FACEBOOK_CLIENT_ID string = os.Getenv("FACEBOOK_CLIENT_ID")
FACEBOOK_CLIENT_SECRET string = os.Getenv("FACEBOOK_CLIENT_SECRET")
GOOGLE_CLIENT_ID string = os.Getenv("GOOGLE_CLIENT_ID")
GOOGLE_CLIENT_SECRET string = os.Getenv("GOOGLE_CLIENT_SECRET")
GITHUB_CLIENT_ID string = os.Getenv("GITHUB_CLIENT_ID")
GITHUB_CLIENT_SECRET string = os.Getenv("GITHUB_CLIENT_SECRET")
// DATABASE_ENGINE string = DEFAULT_DATABASE_ENGINE
// DATABASE_DATABASE string = DEFAULT_DATABASE_DATABASE
// DATABASE_PASSWORD string = DEFAULT_DATABASE_PASSWORD
// DATABASE_USERNAME string = DEFAULT_DATABASE_USERNAME
// DATABASE_HOST string = DEFAULT_DATABASE_HOST
// DATABASE_PORT int64 = DEFAULT_DATABASE_PORT
// REDIS_PORT int64 = DEFAULT_REDIS_PORT
// REDIS_HOST string = DEFAULT_REDIS_HOST
// AI_HOST string = DEFAULT_AI_HOST
// AI_PORT int64 = DEFAULT_AI_PORT
CONFIG_FILE string = DEFAULT_CONFIG_FILE
API_REQUEST string = ""
MODE string = "web"
findapi *api.Api
conf *config.Config
)
func init() {
var printVersion bool
// read credentials from environment variables if available
conf = &config.Config{
Api: config.Api{
PublicMethods: []string{
"get_devices",
"create_device",
"create_sensor",
"get_sensors",
"get_locations",
"set_password",
},
},
Server: config.Server{
HttpPort: DEFAULT_HTTP_PORT,
HttpHost: DEFAULT_HTTP_HOST,
HttpProtocol: DEFAULT_HTTP_PROTOCOL,
HttpDomain: DEFAULT_HTTP_DOMAIN,
},
OAuth2: config.OAuth2{
Facebook: config.SocialOAuth2{
ClientID: FACEBOOK_CLIENT_ID,
ClientSecret: FACEBOOK_CLIENT_SECRET,
},
Google: config.SocialOAuth2{
ClientID: GOOGLE_CLIENT_ID,
ClientSecret: GOOGLE_CLIENT_SECRET,
},
},
Database: config.Database{
DatabaseEngine: DEFAULT_DATABASE_ENGINE,
DatabaseHost: DEFAULT_DATABASE_HOST,
DatabaseName: DEFAULT_DATABASE_DATABASE,
DatabasePass: DEFAULT_DATABASE_PASSWORD,
DatabaseUser: DEFAULT_DATABASE_USERNAME,
DatabasePort: DEFAULT_DATABASE_PORT,
},
Redis: config.Redis{
Host: DEFAULT_REDIS_HOST,
Port: DEFAULT_REDIS_PORT,
},
Ai: config.Ai{
Host: DEFAULT_AI_HOST,
Port: DEFAULT_AI_PORT,
},
}
flag.IntVar(&conf.Server.HttpPort, "httpport", DEFAULT_HTTP_PORT, "Server port")
flag.StringVar(&conf.Server.HttpHost, "httphost", DEFAULT_HTTP_HOST, "Server host")
flag.StringVar(&conf.Server.HttpProtocol, "httpprotocol", DEFAULT_HTTP_PROTOCOL, "Server protocol")
flag.StringVar(&conf.Server.HttpDomain, "httpdomain", DEFAULT_HTTP_DOMAIN, "Http domain")
flag.StringVar(&conf.OAuth2.Facebook.ClientID, "facebook-client-id", FACEBOOK_CLIENT_ID, "Facebook Client ID")
flag.StringVar(&conf.OAuth2.Facebook.ClientSecret, "facebook-client-secret", FACEBOOK_CLIENT_SECRET, "Facebook Client Secret")
flag.StringVar(&conf.OAuth2.Google.ClientID, "gmail-client-id", GOOGLE_CLIENT_ID, "Google Client ID")
flag.StringVar(&conf.OAuth2.Google.ClientSecret, "gmail-client-secret", GOOGLE_CLIENT_SECRET, "Google Client Secret")
flag.StringVar(&conf.OAuth2.GitHub.ClientID, "github-client-id", GITHUB_CLIENT_ID, "GitHub Client ID")
flag.StringVar(&conf.OAuth2.GitHub.ClientSecret, "github-client-secret", GITHUB_CLIENT_SECRET, "GitHub Client Secret")
flag.StringVar(&conf.Database.DatabaseHost, "dbhost", DEFAULT_DATABASE_HOST, "database host")
flag.StringVar(&conf.Database.DatabaseName, "dbname", DEFAULT_DATABASE_DATABASE, "database name")
flag.StringVar(&conf.Database.DatabasePass, "dbpass", DEFAULT_DATABASE_PASSWORD, "database password")
flag.StringVar(&conf.Database.DatabaseUser, "dbuser", DEFAULT_DATABASE_USERNAME, "database username")
flag.Int64Var(&conf.Database.DatabasePort, "dbport", DEFAULT_DATABASE_PORT, "Database port")
flag.StringVar(&conf.Redis.Host, "redishost", DEFAULT_REDIS_HOST, "Redis host")
flag.Int64Var(&conf.Redis.Port, "redisport", DEFAULT_REDIS_PORT, "Redis port")
flag.StringVar(&conf.Ai.Host, "aihost", DEFAULT_AI_HOST, "AI host")
flag.Int64Var(&conf.Ai.Port, "aiport", DEFAULT_AI_PORT, "AI port")
flag.StringVar(&CONFIG_FILE, "c", DEFAULT_CONFIG_FILE, "config file")
flag.StringVar(&API_REQUEST, "query", "", "Api query to execute")
flag.BoolVar(&printVersion, "V", false, "Print version and exit")
flag.Parse()
if printVersion {
fmt.Println(PROJECT, VERSION)
os.Exit(0)
}
args := flag.Args()
if 1 == len(args) {
MODE = args[0]
}
}
func main() {
findapi = api.New(conf)
if "" != API_REQUEST {
request := api.Request{}
request.Unmarshal(API_REQUEST)
response, err := findapi.Do(&request)
if nil != err {
panic(err)
}
results, err := response.Marshal()
if nil != err {
panic(err)
}
fmt.Println(results)
return
}
logger.Debug("GOOS: ", runtime.GOOS)
logger.Debug("CPUS: ", runtime.NumCPU())
logger.Debug("PID: ", os.Getpid())
logger.Debug("Go Version: ", runtime.Version())
logger.Debug("Go Arch: ", runtime.GOARCH)
logger.Debug("Go Compiler: ", runtime.Compiler)
logger.Debug("NumGoroutine: ", runtime.NumGoroutine())
resp, err := findapi.DoJSON(`{"method":"get_database_version"}`)
if nil != err {
panic(err)
}
logger.Debugf("Database version: %v", resp.Message)
switch MODE {
case "repl":
repl.New(findapi).Run()
break
case "web":
app := web.New(findapi, conf)
err = app.ListenAndServe(fmt.Sprintf(":%v", conf.Server.HttpPort))
if err != nil {
panic(err)
}
break
default:
panic(errors.New("api client not found"))
}
}
| [
"\"FACEBOOK_CLIENT_ID\"",
"\"FACEBOOK_CLIENT_SECRET\"",
"\"GOOGLE_CLIENT_ID\"",
"\"GOOGLE_CLIENT_SECRET\"",
"\"GITHUB_CLIENT_ID\"",
"\"GITHUB_CLIENT_SECRET\""
]
| []
| [
"GITHUB_CLIENT_SECRET",
"FACEBOOK_CLIENT_ID",
"GOOGLE_CLIENT_SECRET",
"FACEBOOK_CLIENT_SECRET",
"GOOGLE_CLIENT_ID",
"GITHUB_CLIENT_ID"
]
| [] | ["GITHUB_CLIENT_SECRET", "FACEBOOK_CLIENT_ID", "GOOGLE_CLIENT_SECRET", "FACEBOOK_CLIENT_SECRET", "GOOGLE_CLIENT_ID", "GITHUB_CLIENT_ID"] | go | 6 | 0 | |
server.py | import json
import os
from functools import partial
from aiohttp import web
from dotenv import load_dotenv
import sqlalchemy as sa
from db import accounts, close_pg, init_pg, create_sa_transaction_tables
from handlers import (PARAMS_ERROR, PARSE_ERROR, UNIDENTIFIED_ERROR,
handle_request)
from validators import validator
@validator
async def create_account(conn, name: str, overdraft: bool, amount=0):
cursor = await conn.execute(sa.insert(accounts).values(name=name, overdraft=overdraft, amount=amount))
account = await cursor.fetchone()
return account.id
@validator
async def transfer_money(conn, donor_id: int, recipient_id: int, amount: int):
donor_where = accounts.c.id == donor_id
donor_query = accounts.select().where(donor_where)
donor = await (await conn.execute(donor_query)).fetchone()
recipient_where = accounts.c.id == recipient_id
recipient_query = accounts.select().where(recipient_where)
recipient = await (await conn.execute(recipient_query)).fetchone()
if (not donor.overdraft) and (donor.amount - amount < 0):
return False
trans = await conn.begin()
try:
await conn.execute(sa.update(accounts).values({'amount': donor.amount - amount}).where(donor_where))
await conn.execute(sa.update(accounts).values({'amount': recipient.amount + amount}).where(recipient_where))
except:
await trans.rollback()
return False
else:
await trans.commit()
return True
@validator
async def get_balance(conn, account_id: int):
where = accounts.c.id == account_id
query = accounts.select().where(where)
account = await (await conn.execute(query)).fetchone()
return account.amount
async def handle_jsonrpc(request):
try:
request_dict = await request.json()
except json.JSONDecodeError:
return web.json_response(PARSE_ERROR)
methods = {
'create_account': create_account,
'transfer_money': transfer_money,
'get_balance': get_balance,
}
error_response = handle_request(request_dict, methods)
if error_response:
return web.json_response(error_response)
method = methods[request_dict['method']]
params = request_dict.get('params', [])
try:
async with request.app['db'].acquire() as conn:
await create_sa_transaction_tables(conn)
if isinstance(params, list):
result = await method(conn, *params)
else:
result = await method(conn, **params)
except TypeError:
error = PARAMS_ERROR.copy()
error['id'] = request_dict.get('id', None)
return web.json_response(error)
response_dict = {
'result': result,
'id': request_dict.get('id', None),
'jsonrpc': '2.0'
}
return web.json_response(
response_dict
)
async def run_json_rpc_server(request):
try:
result = await handle_jsonrpc(request)
return result
except:
return web.json_response(UNIDENTIFIED_ERROR)
def is_true(value: str) -> bool:
return value.lower() == 'true'
if __name__ == '__main__':
load_dotenv()
db_url = 'postgresql://{user}:{password}@{host}:{port}/{dbname}'.format(
user=os.getenv('DATABASE_USERNAME'),
password=os.getenv('DATABASE_PASSWORD'),
host=os.getenv('DATABASE_HOST'),
port=os.getenv('DATABASE_PORT'),
dbname=os.getenv('DATABASE_NAME'),
)
app = web.Application()
app.add_routes([
web.post('/jsonrpc', run_json_rpc_server),
])
app.on_startup.append(partial(init_pg, db_url=db_url))
app.on_cleanup.append(close_pg)
web.run_app(app,
host=os.getenv('SERVER_HOST'),
port=os.getenv('SERVER_PORT'),
)
| []
| []
| [
"SERVER_HOST",
"SERVER_PORT",
"DATABASE_PASSWORD",
"DATABASE_NAME",
"DATABASE_HOST",
"DATABASE_USERNAME",
"DATABASE_PORT"
]
| [] | ["SERVER_HOST", "SERVER_PORT", "DATABASE_PASSWORD", "DATABASE_NAME", "DATABASE_HOST", "DATABASE_USERNAME", "DATABASE_PORT"] | python | 7 | 0 | |
integration_tests/binaries/build.go | package binaries
import (
"encoding/json"
"fmt"
"os"
"sync"
"github.com/onsi/gomega/gexec"
)
type BuildPaths struct {
Agent string `json:"agent"`
Router string `json:"router"`
TrafficController string `json:"traffic_controller"`
}
func (bp BuildPaths) Marshal() ([]byte, error) {
return json.Marshal(bp)
}
func (bp *BuildPaths) Unmarshal(text []byte) error {
return json.Unmarshal(text, bp)
}
func (bp BuildPaths) SetEnv() {
os.Setenv("AGENT_BUILD_PATH", bp.Agent)
os.Setenv("ROUTER_BUILD_PATH", bp.Router)
os.Setenv("TRAFFIC_CONTROLLER_BUILD_PATH", bp.TrafficController)
}
func Build() (BuildPaths, chan error) {
var bp BuildPaths
errors := make(chan error, 100)
defer close(errors)
if os.Getenv("SKIP_BUILD") != "" {
fmt.Println("Skipping building of binaries")
bp.Agent = os.Getenv("AGENT_BUILD_PATH")
bp.Router = os.Getenv("ROUTER_BUILD_PATH")
bp.TrafficController = os.Getenv("TRAFFIC_CONTROLLER_BUILD_PATH")
return bp, errors
}
var (
mu sync.Mutex
wg sync.WaitGroup
)
wg.Add(3)
go func() {
defer wg.Done()
agentPath, err := gexec.Build("code.cloudfoundry.org/loggregator-agent/cmd/agent", "-race")
if err != nil {
errors <- err
return
}
mu.Lock()
defer mu.Unlock()
bp.Agent = agentPath
}()
go func() {
defer wg.Done()
routerPath, err := gexec.Build("code.cloudfoundry.org/loggregator/router", "-race")
if err != nil {
errors <- err
return
}
mu.Lock()
defer mu.Unlock()
bp.Router = routerPath
}()
go func() {
defer wg.Done()
tcPath, err := gexec.Build("code.cloudfoundry.org/loggregator/trafficcontroller", "-race")
if err != nil {
errors <- err
return
}
mu.Lock()
defer mu.Unlock()
bp.TrafficController = tcPath
}()
wg.Wait()
return bp, errors
}
func Cleanup() {
gexec.CleanupBuildArtifacts()
}
| [
"\"SKIP_BUILD\"",
"\"AGENT_BUILD_PATH\"",
"\"ROUTER_BUILD_PATH\"",
"\"TRAFFIC_CONTROLLER_BUILD_PATH\""
]
| []
| [
"AGENT_BUILD_PATH",
"SKIP_BUILD",
"ROUTER_BUILD_PATH",
"TRAFFIC_CONTROLLER_BUILD_PATH"
]
| [] | ["AGENT_BUILD_PATH", "SKIP_BUILD", "ROUTER_BUILD_PATH", "TRAFFIC_CONTROLLER_BUILD_PATH"] | go | 4 | 0 | |
API v2/python/points.py | """Demonstrates Points CloudRF API."""
import argparse
import configparser
import csv
import os
import textwrap
import json
from pathlib import Path
import pprint
from cloudrf import CloudRFAPITemplated
# TODO: Deal with html / url
class CloudRFPoints(CloudRFAPITemplated):
"""Points API class"""
endpoint = '/points/'
api_id = 'points'
file_types = ['kmz']
def download(self, select=None):
select = self.file_types if select is None else select
for fmt in select:
if fmt == 'url':
self.save_cov_map_url()
elif fmt == 'html':
self.save_cov_map_html()
else:
self.download_direct(self.response[fmt])
class App:
"""Application class
This class's base class is configured using a cloudrf.ini configuration file.
At first run, a default configuration file will be created. Change all values as required.
Alternatively, the CLOUDRF_KEY environment variables may be used to override the file configuration.
This behaviour may be changed by removing the AppAddOn base class
"""
config_filename = 'cloudrf.ini'
# Default template, we need all values supplied in CSV source
template = """
{
"site": "{{nam}}",
"network": "{{net}}",
"transmitter": {
"lat": {{lat}},
"lon": {{lon}},
"alt": {{alt}},
"frq": {{frq}},
"txw": {{txw}},
"bwi": {{bwi}}
},
"points": [],
"receiver": {
"lat": {{rlat}},
"lon": {{rlon}},
"alt": {{ralt}},
"rxg": {{rxg}},
"rxs": {{rxs}}
},
"antenna": {
"txg": {{txg}},
"txl": {{txl}},
"ant": {{ant}},
"azi": {{azi}},
"tlt": {{tlt}},
"hbw": {{hbw}},
"vbw": {{vbw}},
"pol": "{{pol}}"
},
"model": {
"pm": {{pm}},
"pe": {{pe}},
"cli": {{cli}},
"ked": {{ked}},
"rel": {{rel}},
"ter": {{ter}}
},
"environment": {
"clm": {{clm}},
"cll": {{cll}},
"mat": {{mat}}
},
"output": {
"units": "{{units}}",
"col": "{{col}}",
"out": {{out}},
"ber": {{ber}},
"mod": {{mod}},
"nf": {{nf}},
"res": {{res}},
"rad": {{rad}}
}
}
"""
def __init__(self, args=None):
print('CloudRF API demo')
self.parse_args(args)
print(f'Reading data from {self.args.data_files}')
print(f'Will download {self.args.dl_types}')
self.configure()
if self.args.output_dir is not None:
self.data_dir = self.args.output_dir
if self.data_dir is None:
self.data_dir = Path.cwd() / 'data'
print(f'All files generated to {self.data_dir}')
def parse_args(self, args):
parser = argparse.ArgumentParser(description=textwrap.dedent(f'''
CloudRF Points application
Points coverage performs a circular sweep around a transmitter out to a user defined radius.
It factors in system parameters, antenna patterns, environmental characteristics and terrain data
to show a heatmap in customisable colours and units.
This demonstration program utilizes the CloudRF Points API to generate any
of the possible file outputs offered by the API from {CloudRFPoints.file_types}.
The API arguments are sourced from csv file(s).
please use -s all to generate ALL outputs available.
Please refer to API Reference https://api.cloudrf.com/'''),
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-i', dest='data_files', metavar='data_file', nargs='+', help='data input filename(csv)')
parser.add_argument('-s', dest='dl_types', nargs='+',
choices=CloudRFPoints.file_types + ['all'],
help='type of output file to be downloaded', default=['kmz'])
parser.add_argument('-o', dest='output_dir', metavar='output_dir',
help='output directory where files are downloaded')
parser.add_argument('-r', dest='save_response', action="store_true", help='save response content (json/html)')
parser.add_argument('-v', dest='verbose', action="store_true", help='Output more information on screen')
parser.add_argument('-t', dest='template', help='JSON template to use')
# for unit testing it is useful to be able to pass arguments.
if args is None:
self.args = parser.parse_args()
else:
if isinstance(args, str):
args = args.split(' ')
self.args = parser.parse_args(args)
# if all selected then we reset the list to all types.
if 'all' in self.args.dl_types:
self.args.dl_types = CloudRFPoints.file_types
if self.args.template is not None:
with open(self.args.template, mode='r') as json_file:
self.template = json_file.read()
self.save_response = self.args.save_response
def configure(self):
"""Application configuration
Adds functionality to load the key from configuration or environment
you may find simpler to use the following assignments instead
self.key = "CHANGEME"
"""
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise Exception(f'Boolean value expected in {v}.')
self.key = os.environ['CLOUDRF_KEY'] if 'CLOUDRF_KEY' in os.environ else None
self.strict_ssl = os.environ['CLOUDRF_STRICT_SSL'] if 'CLOUDRF_STRICT_SSL' in os.environ else None
self.base_url = os.environ['CLOUDRF_BASE_URL'] if 'CLOUDRF_BASE_URL' in os.environ else None
self.data_dir = os.environ['CLOUDRF_DATA_DIR'] if 'CLOUDRF_DATA_DIR' in os.environ else None
# is any value is not None we read the config
if not any([bool(self.key), bool(self.strict_ssl), bool(self.base_url)]):
config = configparser.ConfigParser()
# we read the configuration file if it exists
if Path(self.config_filename).is_file():
config.read(self.config_filename)
# if user section does not exist we create it with default value
if 'user' not in config.sections():
config.add_section('user')
config['user']['key'] = 'CHANGEME'
config.add_section('api')
config['api']['strict_ssl'] = 'CHANGEME'
config['api']['base_url'] = 'CHANGEME'
config.add_section('data')
config['data']['dir'] = ''
with open('cloudrf.ini', 'w') as fp:
config.write(fp)
if config['user']['key'] == 'CHANGEME':
raise Exception(f'Please change configuration in {self.config_filename}')
if self.key is None:
self.key = config['user']['key']
if self.strict_ssl is None:
self.strict_ssl = config['api']['strict_ssl']
if self.base_url is None:
self.base_url = config['api']['base_url']
if self.data_dir is None and config['data']['dir'].strip() != '':
self.data_dir = config['data']['dir']
self.strict_ssl = str2bool(self.strict_ssl)
def run_points(self):
"""Points coverage analysis"""
responses = []
self.api = CloudRFPoints(self.key, self.base_url, self.strict_ssl, self.save_response)
self.api.set_download_dir(self.data_dir)
print('Points API demo')
print('fetching antenna calculations')
self.row_count = 0
for f in self.args.data_files:
with open(f, 'r') as fp:
self.csv_data = csv.DictReader(fp)
self.csv_rows = [row for row in self.csv_data]
self.row_count += len(self.csv_rows)
for row in self.csv_rows:
if self.args.verbose:
print(f'data: {row}')
self.api.request(row, self.template)
if self.args.verbose:
print(f'response: {self.api.response}')
self.api.download(select=self.args.dl_types) # remove select to download all types available
responses.append(self.api.response)
print('Done.', flush=True)
return responses
if __name__ == '__main__':
pp = pprint.PrettyPrinter(depth=6)
app = App()
pp.pprint(app.run_points())
| []
| []
| [
"CLOUDRF_DATA_DIR",
"CLOUDRF_BASE_URL",
"CLOUDRF_STRICT_SSL",
"CLOUDRF_KEY"
]
| [] | ["CLOUDRF_DATA_DIR", "CLOUDRF_BASE_URL", "CLOUDRF_STRICT_SSL", "CLOUDRF_KEY"] | python | 4 | 0 | |
tests/components_users_test.py | """ Tests the users components """
import os
import shutil
import pytest
from bot.components import users
@pytest.fixture
def env():
""" Configures the environment before and after tests """
# Attempt to remove existing temp path if needed
try:
shutil.rmtree('/tmp/discord_bot')
except FileNotFoundError:
pass
os.makedirs('/tmp/discord_bot/test')
os.environ["DATA_PATH"] = '/tmp/discord_bot/test'
yield
shutil.rmtree('/tmp/discord_bot')
#@pytest.mark.skip(reason="implementing")
def test_user(env): # pylint: disable=redefined-outer-name,unused-argument
""" Create, save, and load a user """
name_1 = "Testy123"
name_2 = "Yolo420"
user_1 = users.User.create(name_1)
user_1._gold = 0 # Reset gold to avoid debugging gold starting values conflicting with tests
assert user_1.name == "Testy123"
assert user_1.level == 1
assert user_1.experience == 0
assert user_1.body
assert user_1.mind
assert user_1.agility
assert user_1.life
assert user_1.mana
assert user_1.speed
assert user_1.weapon is None
assert user_1.armor is None
assert user_1.accessory is None
assert len(user_1.spells) == 0
assert len(user_1.inventory) == 0
assert user_1._gold == 0
assert not user_1.defending
# Verify loading a user does not mutate it
filename = os.path.join(os.getenv('DATA_PATH'), 'test_user.json')
user_1.save(filename)
user_1_copy = users.User.load(filename)
assert user_1.name == user_1_copy.name
def test_level(env):
""" Test leveling and point usage """
user = users.User.create("69420")
# Ensure user doesn't level up until 1000XP is gained
user.gain_xp(1000)
user.level_up()
# User should now have stat points to spend
assert user.points == 5
# Spending points should increase stats
old_body = user.body.base
old_mind = user.mind.base
old_agility = user.agility.base
old_life = user.life.base
old_mana = user.mana.base
old_speed = user.speed.base
user.upgrade('body')
user.upgrade('mind')
user.upgrade('agility', 3)
assert user.points == 0
assert user.body.base == (old_body + 1)
assert user.mind.base == (old_mind + 1)
assert user.agility.base == (old_agility + 3)
assert user.life.base > old_life
assert user.mana.base > old_mana
assert user.speed.base > old_speed
# Restarting the points goes back to base line
user.restart()
assert user.points == 5
assert user.body.base == old_body
assert user.mind.base == old_mind
assert user.agility.base == old_agility
assert user.life.base == old_life
assert user.mana.base == old_mana
assert user.speed.base == old_speed
| []
| []
| [
"DATA_PATH"
]
| [] | ["DATA_PATH"] | python | 1 | 0 | |
examples.py | from __future__ import print_function
import freesound
import os
import sys
api_key = os.getenv('FREESOUND_API_KEY', None)
if api_key is None:
print("You need to set your API key as an evironment variable",)
print("named FREESOUND_API_KEY")
sys.exit(-1)
freesound_client = freesound.FreesoundClient()
freesound_client.set_token(api_key)
# Get sound info example
print("Sound info:")
print("-----------")
sound = freesound_client.get_sound(96541)
print("Getting sound:", sound.name)
print("Url:", sound.url)
print("Description:", sound.description)
print("Tags:", " ".join(sound.tags))
print()
# Get sound info example specifying some request parameters
print("Sound info specifying some request parameters:")
print("-----------")
sound = freesound_client.get_sound(
96541,
fields="id,name,username,duration,analysis",
descriptors="lowlevel.spectral_centroid",
normalized=1
)
print("Getting sound:", sound.name)
print("Username:", sound.username)
print("Duration:", str(sound.duration), "(s)")
print("Spectral centroid:",)
print(sound.analysis.lowlevel.spectral_centroid.as_dict())
print()
# Get sound analysis example
print("Get analysis:")
print("-------------")
analysis = sound.get_analysis()
mfcc = analysis.lowlevel.mfcc.mean
print("Mfccs:", mfcc)
# you can also get the original json (this apply to any FreesoundObject):
print(analysis.as_dict())
print()
# Get sound analysis example specifying some request parameters
print("Get analysis with specific normalized descriptor:")
print("-------------")
analysis = sound.get_analysis(
descriptors="lowlevel.spectral_centroid.mean",
normalized=1
)
spectral_centroid_mean = analysis.lowlevel.spectral_centroid.mean
print("Normalized mean of spectral centroid:", spectral_centroid_mean)
print()
# Get similar sounds example
print("Similar sounds: ")
print("---------------")
results_pager = sound.get_similar()
for similar_sound in results_pager:
print("\t-", similar_sound.name, "by", similar_sound.username)
print()
# Get similar sounds example specifying some request parameters
print("Similar sounds specifying some request parameters:")
print("---------------")
results_pager = sound.get_similar(
page_size=10,
fields="name,username",
descriptors_filter="lowlevel.pitch.mean:[110 TO 180]"
)
for similar_sound in results_pager:
print("\t-", similar_sound.name, "by", similar_sound.username)
print()
# Search Example
print("Searching for 'violoncello':")
print("----------------------------")
results_pager = freesound_client.text_search(
query="violoncello",
filter="tag:tenuto duration:[1.0 TO 15.0]",
sort="rating_desc",
fields="id,name,previews,username"
)
print("Num results:", results_pager.count)
print("\t----- PAGE 1 -----")
for sound in results_pager:
print("\t-", sound.name, "by", sound.username)
print("\t----- PAGE 2 -----")
results_pager = results_pager.next_page()
for sound in results_pager:
print("\t-", sound.name, "by", sound.username)
print()
# Content based search example
print("Content based search:")
print("---------------------")
results_pager = freesound_client.content_based_search(
descriptors_filter="lowlevel.pitch.var:[* TO 20]",
target='lowlevel.pitch_salience.mean:1.0 lowlevel.pitch.mean:440'
)
print("Num results:", results_pager.count)
for sound in results_pager:
print("\t-", sound.name, "by", sound.username)
print()
# Getting sounds from a user example
print("User sounds:")
print("-----------")
user = freesound_client.get_user("Jovica")
print("User name:", user.username)
results_pager = user.get_sounds()
print("Num results:", results_pager.count)
print("\t----- PAGE 1 -----")
for sound in results_pager:
print("\t-", sound.name, "by", sound.username)
print("\t----- PAGE 2 -----")
results_pager = results_pager.next_page()
for sound in results_pager:
print("\t-", sound.name, "by", sound.username)
print()
# Getting sounds from a user example specifying some request parameters
print("User sounds specifying some request parameters:")
print("-----------")
user = freesound_client.get_user("Jovica")
print("User name:", user.username)
results_pager = user.get_sounds(
page_size=10,
fields="name,username,samplerate,duration,analysis",
descriptors="rhythm.bpm"
)
print("Num results:", results_pager.count)
print("\t----- PAGE 1 -----")
for sound in results_pager:
print("\t-", sound.name, "by", sound.username,)
print(", with sample rate of", sound.samplerate, "Hz and duration of",)
print(sound.duration, "s")
print("\t----- PAGE 2 -----")
results_pager = results_pager.next_page()
for sound in results_pager:
print("\t-", sound.name, "by", sound.username,)
print(", with sample rate of", sound.samplerate, "Hz and duration of",)
print(sound.duration, "s")
print()
# Getting sounds from a pack example specifying some request parameters
print("Pack sounds specifying some request parameters:")
print("-----------")
pack = freesound_client.get_pack(3524)
print("Pack name:", pack.name)
results_pager = pack.get_sounds(
page_size=5,
fields="id,name,username,duration,analysis",
descriptors="lowlevel.spectral_flatness_db"
)
print("Num results:", results_pager.count)
print("\t----- PAGE 1 -----")
for sound in results_pager:
print("\t-", sound.name, "by", sound.username, ", with duration of",)
print(sound.duration, "s and a mean spectral flatness of",)
print(sound.analysis.lowlevel.spectral_flatness_db.mean)
print("\t----- PAGE 2 -----")
results_pager = results_pager.next_page()
for sound in results_pager:
print("\t-", sound.name, "by", sound.username, ", with duration of",)
print(sound.duration, "s and a mean spectral flatness of",)
print(sound.analysis.lowlevel.spectral_flatness_db.mean)
print()
# Getting bookmark categories from a user example
print("User bookmark categories:")
print("-----------")
user = freesound_client.get_user("frederic.font")
print("User name:", user.username)
results_pager = user.get_bookmark_categories(page_size=10)
print("Num results:", results_pager.count)
print("\t----- PAGE 1 -----")
for bookmark_category in results_pager:
print("\t-", bookmark_category.name, "with", bookmark_category.num_sounds,)
print("sounds at", bookmark_category.url)
print()
| []
| []
| [
"FREESOUND_API_KEY"
]
| [] | ["FREESOUND_API_KEY"] | python | 1 | 0 | |
server.py | import os
import random
import cherrypy
"""
This is a simple Battlesnake server written in Python.
For instructions see https://github.com/BattlesnakeOfficial/starter-snake-python/README.md
"""
class Battlesnake(object):
@cherrypy.expose
@cherrypy.tools.json_out()
def index(self):
# This function is called when you register your Battlesnake on play.battlesnake.com
# It controls your Battlesnake appearance and author permissions.
# TIP: If you open your Battlesnake URL in browser you should see this data
return {
"apiversion": "1",
"author": "", # TODO: Your Battlesnake Username
"color": "#888888", # TODO: Personalize
"head": "default", # TODO: Personalize
"tail": "default", # TODO: Personalize
}
@cherrypy.expose
@cherrypy.tools.json_in()
def start(self):
# This function is called everytime your snake is entered into a game.
# cherrypy.request.json contains information about the game that's about to be played.
data = cherrypy.request.json
print("START")
return "ok"
@cherrypy.expose
@cherrypy.tools.json_in()
@cherrypy.tools.json_out()
def move(self):
# This function is called on every turn of a game. It's how your snake decides where to move.
# Valid moves are "up", "down", "left", or "right".
# TODO: Use the information in cherrypy.request.json to decide your next move.
data = cherrypy.request.json
board = data.board
# Choose a random direction to move in
possible_moves = ["up", "down", "left", "right"]
move = random.choice(possible_moves)
print(f"MOVE: {move}")
return {"move": move}
@cherrypy.expose
@cherrypy.tools.json_in()
def end(self):
# This function is called when a game your snake was in ends.
# It's purely for informational purposes, you don't have to make any decisions here.
data = cherrypy.request.json
print("END")
return "ok"
if __name__ == "__main__":
server = Battlesnake()
cherrypy.config.update({"server.socket_host": "0.0.0.0"})
cherrypy.config.update(
{"server.socket_port": int(os.environ.get("PORT", "8080")),}
)
print("Starting Battlesnake Server...")
cherrypy.quickstart(server)
| []
| []
| [
"PORT"
]
| [] | ["PORT"] | python | 1 | 0 | |
maven-extension/src/main/java/io/opentelemetry/maven/OtelExecutionListener.java | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.maven;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanBuilder;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.api.trace.StatusCode;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.TextMapGetter;
import io.opentelemetry.maven.handler.MojoGoalExecutionHandler;
import io.opentelemetry.maven.handler.MojoGoalExecutionHandlerConfiguration;
import io.opentelemetry.maven.semconv.MavenOtelSemanticAttributes;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.apache.maven.execution.AbstractExecutionListener;
import org.apache.maven.execution.ExecutionEvent;
import org.apache.maven.execution.ExecutionListener;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.lifecycle.LifecycleExecutionException;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Close the OpenTelemetry SDK (see {@link OpenTelemetrySdkService#dispose()}) on the end of
* execution of the last project ({@link #projectSucceeded(ExecutionEvent)} and {@link
* #projectFailed(ExecutionEvent)}) rather than on the end of the Maven session {@link
* #sessionEnded(ExecutionEvent)} because OpenTelemetry and GRPC classes are unloaded by the Maven
* classloader before {@link #sessionEnded(ExecutionEvent)} causing {@link NoClassDefFoundError}
* messages in the logs.
*/
@Component(role = ExecutionListener.class, hint = "otel-execution-listener")
public final class OtelExecutionListener extends AbstractExecutionListener {
private static final Logger logger = LoggerFactory.getLogger(OtelExecutionListener.class);
@SuppressWarnings("NullAway") // Automatically initialized by DI
@Requirement
private SpanRegistry spanRegistry;
@SuppressWarnings("NullAway") // Automatically initialized by DI
@Requirement
private OpenTelemetrySdkService openTelemetrySdkService;
private Map<MavenGoal, MojoGoalExecutionHandler> mojoGoalExecutionHandlers = new HashMap<>();
public OtelExecutionListener() {
this.mojoGoalExecutionHandlers =
MojoGoalExecutionHandlerConfiguration.loadMojoGoalExecutionHandler(
OtelExecutionListener.class.getClassLoader());
if (logger.isDebugEnabled()) {
logger.debug(
"OpenTelemetry: mojoGoalExecutionHandlers: "
+ mojoGoalExecutionHandlers.entrySet().stream()
.map(entry -> entry.getKey().toString() + ": " + entry.getValue().toString())
.collect(Collectors.joining(", ")));
}
}
/**
* Register in given {@link OtelExecutionListener} to the lifecycle of the given {@link
* MavenSession}
*
* @see org.apache.maven.execution.MavenExecutionRequest#setExecutionListener(ExecutionListener)
*/
public static void registerOtelExecutionListener(
MavenSession session, OtelExecutionListener otelExecutionListener) {
ExecutionListener initialExecutionListener = session.getRequest().getExecutionListener();
if (initialExecutionListener instanceof ChainedExecutionListener
|| initialExecutionListener instanceof OtelExecutionListener) {
// already initialized
logger.debug(
"OpenTelemetry: OpenTelemetry extension already registered as execution listener, skip.");
} else if (initialExecutionListener == null) {
session.getRequest().setExecutionListener(otelExecutionListener);
logger.debug(
"OpenTelemetry: OpenTelemetry extension registered as execution listener. No execution listener initially defined");
} else {
session
.getRequest()
.setExecutionListener(
new ChainedExecutionListener(otelExecutionListener, initialExecutionListener));
logger.debug(
"OpenTelemetry: OpenTelemetry extension registered as execution listener. InitialExecutionListener: "
+ initialExecutionListener);
}
}
@Override
public void sessionStarted(ExecutionEvent executionEvent) {
MavenProject project = executionEvent.getSession().getTopLevelProject();
TextMapGetter<Map<String, String>> toUpperCaseTextMapGetter = new ToUpperCaseTextMapGetter();
io.opentelemetry.context.Context context =
openTelemetrySdkService
.getPropagators()
.getTextMapPropagator()
.extract(
io.opentelemetry.context.Context.current(),
System.getenv(),
toUpperCaseTextMapGetter);
// TODO question: is this the root span name we want?
// It's interesting for the root span name to
// - start with an operation name: "Build"
// - identify the build with a popular identifier of what is being built, in the java culture,
// it's the artifact identifier
String spanName =
"Build: "
+ project.getGroupId()
+ ":"
+ project.getArtifactId()
+ ":"
+ project.getVersion();
logger.debug("OpenTelemetry: Start session span: {}", spanName);
Span sessionSpan =
this.openTelemetrySdkService
.getTracer()
.spanBuilder(spanName)
.setParent(context)
.setAttribute(MavenOtelSemanticAttributes.MAVEN_PROJECT_GROUP_ID, project.getGroupId())
.setAttribute(
MavenOtelSemanticAttributes.MAVEN_PROJECT_ARTIFACT_ID, project.getArtifactId())
.setAttribute(MavenOtelSemanticAttributes.MAVEN_PROJECT_VERSION, project.getVersion())
.setSpanKind(SpanKind.SERVER)
.startSpan();
spanRegistry.setRootSpan(sessionSpan);
}
@Override
public void projectStarted(ExecutionEvent executionEvent) {
MavenProject project = executionEvent.getProject();
String spanName = project.getGroupId() + ":" + project.getArtifactId();
logger.debug("OpenTelemetry: Start project span: {}", spanName);
Span rootSpan = spanRegistry.getRootSpanNotNull();
Tracer tracer = this.openTelemetrySdkService.getTracer();
Span projectSpan =
tracer
.spanBuilder(spanName)
.setParent(Context.current().with(Span.wrap(rootSpan.getSpanContext())))
.setAttribute(MavenOtelSemanticAttributes.MAVEN_PROJECT_GROUP_ID, project.getGroupId())
.setAttribute(
MavenOtelSemanticAttributes.MAVEN_PROJECT_ARTIFACT_ID, project.getArtifactId())
.setAttribute(MavenOtelSemanticAttributes.MAVEN_PROJECT_VERSION, project.getVersion())
.startSpan();
spanRegistry.putSpan(projectSpan, project);
}
@Override
public void projectSucceeded(ExecutionEvent executionEvent) {
logger.debug(
"OpenTelemetry: End succeeded project span: {}:{}",
executionEvent.getProject().getArtifactId(),
executionEvent.getProject().getArtifactId());
spanRegistry.removeSpan(executionEvent.getProject()).end();
}
@Override
public void projectFailed(ExecutionEvent executionEvent) {
logger.debug(
"OpenTelemetry: End failed project span: {}:{}",
executionEvent.getProject().getArtifactId(),
executionEvent.getProject().getArtifactId());
Span span = spanRegistry.removeSpan(executionEvent.getProject());
span.setStatus(StatusCode.ERROR);
span.recordException(executionEvent.getException());
span.end();
}
@Override
public void mojoStarted(ExecutionEvent executionEvent) {
if (!this.openTelemetrySdkService.isMojosInstrumentationEnabled()) {
return;
}
MojoExecution mojoExecution = executionEvent.getMojoExecution();
Span rootSpan = spanRegistry.getSpan(executionEvent.getProject());
String spanName =
MavenUtils.getPluginArtifactIdShortName(mojoExecution.getArtifactId())
+ ":"
+ mojoExecution.getGoal();
logger.debug("OpenTelemetry: Start mojo execution: span {}", spanName);
SpanBuilder spanBuilder =
this.openTelemetrySdkService
.getTracer()
.spanBuilder(spanName)
.setParent(Context.current().with(Span.wrap(rootSpan.getSpanContext())))
.setAttribute(
MavenOtelSemanticAttributes.MAVEN_PROJECT_GROUP_ID,
executionEvent.getProject().getGroupId())
.setAttribute(
MavenOtelSemanticAttributes.MAVEN_PROJECT_ARTIFACT_ID,
executionEvent.getProject().getArtifactId())
.setAttribute(
MavenOtelSemanticAttributes.MAVEN_PROJECT_VERSION,
executionEvent.getProject().getVersion())
.setAttribute(
MavenOtelSemanticAttributes.MAVEN_PLUGIN_GROUP_ID,
mojoExecution.getPlugin().getGroupId())
.setAttribute(
MavenOtelSemanticAttributes.MAVEN_PLUGIN_ARTIFACT_ID,
mojoExecution.getPlugin().getArtifactId())
.setAttribute(
MavenOtelSemanticAttributes.MAVEN_PLUGIN_VERSION,
mojoExecution.getPlugin().getVersion())
.setAttribute(MavenOtelSemanticAttributes.MAVEN_EXECUTION_GOAL, mojoExecution.getGoal())
.setAttribute(
MavenOtelSemanticAttributes.MAVEN_EXECUTION_ID, mojoExecution.getExecutionId())
.setAttribute(
MavenOtelSemanticAttributes.MAVEN_EXECUTION_LIFECYCLE_PHASE,
mojoExecution.getLifecyclePhase());
// enrich spans with MojoGoalExecutionHandler
MojoGoalExecutionHandler handler =
this.mojoGoalExecutionHandlers.get(MavenGoal.create(mojoExecution));
logger.debug("OpenTelemetry: {} handler {}", executionEvent, handler);
if (handler != null) {
handler.enrichSpan(spanBuilder, executionEvent);
}
Span span = spanBuilder.startSpan();
spanRegistry.putSpan(span, mojoExecution, executionEvent.getProject());
}
@Override
public void mojoSucceeded(ExecutionEvent executionEvent) {
if (!this.openTelemetrySdkService.isMojosInstrumentationEnabled()) {
return;
}
MojoExecution mojoExecution = executionEvent.getMojoExecution();
logger.debug(
"OpenTelemetry: End succeeded mojo execution span: {}, {}",
mojoExecution,
executionEvent.getProject());
Span mojoExecutionSpan = spanRegistry.removeSpan(mojoExecution, executionEvent.getProject());
mojoExecutionSpan.setStatus(StatusCode.OK);
mojoExecutionSpan.end();
}
@Override
public void mojoFailed(ExecutionEvent executionEvent) {
if (!this.openTelemetrySdkService.isMojosInstrumentationEnabled()) {
return;
}
MojoExecution mojoExecution = executionEvent.getMojoExecution();
logger.debug(
"OpenTelemetry: End failed mojo execution span: {}, {}",
mojoExecution,
executionEvent.getProject());
Span mojoExecutionSpan = spanRegistry.removeSpan(mojoExecution, executionEvent.getProject());
mojoExecutionSpan.setStatus(StatusCode.ERROR, "Mojo Failed"); // TODO verify description
Throwable exception = executionEvent.getException();
if (exception instanceof LifecycleExecutionException) {
LifecycleExecutionException executionException = (LifecycleExecutionException) exception;
// we already capture the context, no need to capture it again
exception = executionException.getCause();
}
mojoExecutionSpan.recordException(exception);
mojoExecutionSpan.end();
}
@Override
public void sessionEnded(ExecutionEvent event) {
logger.debug("OpenTelemetry: Maven session ended");
spanRegistry.removeRootSpan().end();
}
private static class ToUpperCaseTextMapGetter implements TextMapGetter<Map<String, String>> {
@Override
public Iterable<String> keys(Map<String, String> environmentVariables) {
return environmentVariables.keySet();
}
@Override
@Nullable
public String get(@Nullable Map<String, String> environmentVariables, String key) {
return environmentVariables == null
? null
: environmentVariables.get(key.toUpperCase(Locale.ROOT));
}
}
}
| []
| []
| []
| [] | [] | java | 0 | 0 | |
services/filesstore/filesstore_test.go | // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package filesstore
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/zgordan-vv/zacmm-server/mlog"
"github.com/zgordan-vv/zacmm-server/model"
"github.com/zgordan-vv/zacmm-server/utils"
)
type FileBackendTestSuite struct {
suite.Suite
settings model.FileSettings
backend FileBackend
}
func TestLocalFileBackendTestSuite(t *testing.T) {
// Setup a global logger to catch tests logging outside of app context
// The global logger will be stomped by apps initializing but that's fine for testing. Ideally this won't happen.
mlog.InitGlobalLogger(mlog.NewLogger(&mlog.LoggerConfiguration{
EnableConsole: true,
ConsoleJson: true,
ConsoleLevel: "error",
EnableFile: false,
}))
dir, err := ioutil.TempDir("", "")
require.NoError(t, err)
defer os.RemoveAll(dir)
suite.Run(t, &FileBackendTestSuite{
settings: model.FileSettings{
DriverName: model.NewString(model.IMAGE_DRIVER_LOCAL),
Directory: &dir,
},
})
}
func TestS3FileBackendTestSuite(t *testing.T) {
runBackendTest(t, false)
}
func TestS3FileBackendTestSuiteWithEncryption(t *testing.T) {
runBackendTest(t, true)
}
func runBackendTest(t *testing.T, encrypt bool) {
s3Host := os.Getenv("CI_MINIO_HOST")
if s3Host == "" {
s3Host = "localhost"
}
s3Port := os.Getenv("CI_MINIO_PORT")
if s3Port == "" {
s3Port = "9000"
}
s3Endpoint := fmt.Sprintf("%s:%s", s3Host, s3Port)
suite.Run(t, &FileBackendTestSuite{
settings: model.FileSettings{
DriverName: model.NewString(model.IMAGE_DRIVER_S3),
AmazonS3AccessKeyId: model.NewString(model.MINIO_ACCESS_KEY),
AmazonS3SecretAccessKey: model.NewString(model.MINIO_SECRET_KEY),
AmazonS3Bucket: model.NewString(model.MINIO_BUCKET),
AmazonS3Region: model.NewString(""),
AmazonS3Endpoint: model.NewString(s3Endpoint),
AmazonS3PathPrefix: model.NewString(""),
AmazonS3SSL: model.NewBool(false),
AmazonS3SSE: model.NewBool(encrypt),
},
})
}
func (s *FileBackendTestSuite) SetupTest() {
utils.TranslationsPreInit()
backend, err := NewFileBackend(&s.settings, true)
require.Nil(s.T(), err)
s.backend = backend
// This is needed to create the bucket if it doesn't exist.
s.Nil(s.backend.TestConnection())
}
func (s *FileBackendTestSuite) TestConnection() {
s.Nil(s.backend.TestConnection())
}
func (s *FileBackendTestSuite) TestReadWriteFile() {
b := []byte("test")
path := "tests/" + model.NewId()
written, err := s.backend.WriteFile(bytes.NewReader(b), path)
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
defer s.backend.RemoveFile(path)
read, err := s.backend.ReadFile(path)
s.Nil(err)
readString := string(read)
s.EqualValues(readString, "test")
}
func (s *FileBackendTestSuite) TestReadWriteFileImage() {
b := []byte("testimage")
path := "tests/" + model.NewId() + ".png"
written, err := s.backend.WriteFile(bytes.NewReader(b), path)
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
defer s.backend.RemoveFile(path)
read, err := s.backend.ReadFile(path)
s.Nil(err)
readString := string(read)
s.EqualValues(readString, "testimage")
}
func (s *FileBackendTestSuite) TestFileExists() {
b := []byte("testimage")
path := "tests/" + model.NewId() + ".png"
_, err := s.backend.WriteFile(bytes.NewReader(b), path)
s.Nil(err)
defer s.backend.RemoveFile(path)
res, err := s.backend.FileExists(path)
s.Nil(err)
s.True(res)
res, err = s.backend.FileExists("tests/idontexist.png")
s.Nil(err)
s.False(res)
}
func (s *FileBackendTestSuite) TestCopyFile() {
b := []byte("test")
path1 := "tests/" + model.NewId()
path2 := "tests/" + model.NewId()
written, err := s.backend.WriteFile(bytes.NewReader(b), path1)
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
defer s.backend.RemoveFile(path1)
err = s.backend.CopyFile(path1, path2)
s.Nil(err)
defer s.backend.RemoveFile(path2)
data1, err := s.backend.ReadFile(path1)
s.Nil(err)
data2, err := s.backend.ReadFile(path2)
s.Nil(err)
s.Equal(b, data1)
s.Equal(b, data2)
}
func (s *FileBackendTestSuite) TestCopyFileToDirectoryThatDoesntExist() {
b := []byte("test")
path1 := "tests/" + model.NewId()
path2 := "tests/newdirectory/" + model.NewId()
written, err := s.backend.WriteFile(bytes.NewReader(b), path1)
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
defer s.backend.RemoveFile(path1)
err = s.backend.CopyFile(path1, path2)
s.Nil(err)
defer s.backend.RemoveFile(path2)
_, err = s.backend.ReadFile(path1)
s.Nil(err)
_, err = s.backend.ReadFile(path2)
s.Nil(err)
}
func (s *FileBackendTestSuite) TestMoveFile() {
b := []byte("test")
path1 := "tests/" + model.NewId()
path2 := "tests/" + model.NewId()
written, err := s.backend.WriteFile(bytes.NewReader(b), path1)
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
defer s.backend.RemoveFile(path1)
s.Nil(s.backend.MoveFile(path1, path2))
defer s.backend.RemoveFile(path2)
_, err = s.backend.ReadFile(path1)
s.Error(err)
data, err := s.backend.ReadFile(path2)
s.Nil(err)
s.Equal(b, data)
}
func (s *FileBackendTestSuite) TestRemoveFile() {
b := []byte("test")
path := "tests/" + model.NewId()
written, err := s.backend.WriteFile(bytes.NewReader(b), path)
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
s.Nil(s.backend.RemoveFile(path))
_, err = s.backend.ReadFile(path)
s.Error(err)
written, err = s.backend.WriteFile(bytes.NewReader(b), "tests2/foo")
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
written, err = s.backend.WriteFile(bytes.NewReader(b), "tests2/bar")
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
written, err = s.backend.WriteFile(bytes.NewReader(b), "tests2/asdf")
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
s.Nil(s.backend.RemoveDirectory("tests2"))
}
func (s *FileBackendTestSuite) TestListDirectory() {
b := []byte("test")
path1 := "19700101/" + model.NewId()
path2 := "19800101/" + model.NewId()
paths, err := s.backend.ListDirectory("19700101")
s.Nil(err)
s.Len(*paths, 0)
written, err := s.backend.WriteFile(bytes.NewReader(b), path1)
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
written, err = s.backend.WriteFile(bytes.NewReader(b), path2)
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
paths, err = s.backend.ListDirectory("19700101")
s.Nil(err)
s.Len(*paths, 1)
s.Equal(path1, (*paths)[0])
paths, err = s.backend.ListDirectory("19700101/")
s.Nil(err)
s.Len(*paths, 1)
s.Equal(path1, (*paths)[0])
paths, err = s.backend.ListDirectory("")
s.Nil(err)
found1 := false
found2 := false
for _, path := range *paths {
if path == "19700101" {
found1 = true
} else if path == "19800101" {
found2 = true
}
}
s.True(found1)
s.True(found2)
s.backend.RemoveFile(path1)
s.backend.RemoveFile(path2)
}
func (s *FileBackendTestSuite) TestRemoveDirectory() {
b := []byte("test")
written, err := s.backend.WriteFile(bytes.NewReader(b), "tests2/foo")
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
written, err = s.backend.WriteFile(bytes.NewReader(b), "tests2/bar")
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
written, err = s.backend.WriteFile(bytes.NewReader(b), "tests2/aaa")
s.Nil(err)
s.EqualValues(len(b), written, "expected given number of bytes to have been written")
s.Nil(s.backend.RemoveDirectory("tests2"))
_, err = s.backend.ReadFile("tests2/foo")
s.Error(err)
_, err = s.backend.ReadFile("tests2/bar")
s.Error(err)
_, err = s.backend.ReadFile("tests2/asdf")
s.Error(err)
}
func (s *FileBackendTestSuite) TestAppendFile() {
s.Run("should fail if target file is missing", func() {
path := "tests/" + model.NewId()
b := make([]byte, 1024)
written, err := s.backend.AppendFile(bytes.NewReader(b), path)
s.Error(err)
s.Zero(written)
})
s.Run("should correctly append the data", func() {
// First part needs to be at least 5MB for the S3 implementation to work.
size := 5 * 1024 * 1024
b := make([]byte, size)
for i := range b {
b[i] = 'A'
}
path := "tests/" + model.NewId()
written, err := s.backend.WriteFile(bytes.NewReader(b), path)
s.Nil(err)
s.EqualValues(len(b), written)
defer s.backend.RemoveFile(path)
b2 := make([]byte, 1024)
for i := range b2 {
b2[i] = 'B'
}
written, err = s.backend.AppendFile(bytes.NewReader(b2), path)
s.Nil(err)
s.EqualValues(int64(len(b2)), written)
read, err := s.backend.ReadFile(path)
s.Nil(err)
s.EqualValues(len(b)+len(b2), len(read))
s.EqualValues(append(b, b2...), read)
b3 := make([]byte, 1024)
for i := range b3 {
b3[i] = 'C'
}
written, err = s.backend.AppendFile(bytes.NewReader(b3), path)
s.Nil(err)
s.EqualValues(int64(len(b3)), written)
read, err = s.backend.ReadFile(path)
s.Nil(err)
s.EqualValues(len(b)+len(b2)+len(b3), len(read))
s.EqualValues(append(append(b, b2...), b3...), read)
})
}
func BenchmarkS3WriteFile(b *testing.B) {
utils.TranslationsPreInit()
settings := &model.FileSettings{
DriverName: model.NewString(model.IMAGE_DRIVER_S3),
AmazonS3AccessKeyId: model.NewString(model.MINIO_ACCESS_KEY),
AmazonS3SecretAccessKey: model.NewString(model.MINIO_SECRET_KEY),
AmazonS3Bucket: model.NewString(model.MINIO_BUCKET),
AmazonS3Region: model.NewString(""),
AmazonS3Endpoint: model.NewString("localhost:9000"),
AmazonS3PathPrefix: model.NewString(""),
AmazonS3SSL: model.NewBool(false),
AmazonS3SSE: model.NewBool(false),
}
backend, err := NewFileBackend(settings, true)
require.Nil(b, err)
// This is needed to create the bucket if it doesn't exist.
require.Nil(b, backend.TestConnection())
path := "tests/" + model.NewId()
size := 1 * 1024 * 1024
data := make([]byte, size)
b.ResetTimer()
for i := 0; i < b.N; i++ {
written, err := backend.WriteFile(bytes.NewReader(data), path)
defer backend.RemoveFile(path)
require.Nil(b, err)
require.Equal(b, len(data), int(written))
}
b.StopTimer()
}
| [
"\"CI_MINIO_HOST\"",
"\"CI_MINIO_PORT\""
]
| []
| [
"CI_MINIO_PORT",
"CI_MINIO_HOST"
]
| [] | ["CI_MINIO_PORT", "CI_MINIO_HOST"] | go | 2 | 0 | |
tools/build-containers.py | #!/usr/bin/env python
"""Docker image builder for distributing molecule as a container."""
import os
import socket
import sys
from shutil import which
from packaging.version import Version
from setuptools_scm import get_version
def run(cmd):
"""Build docker container distribution."""
print(cmd)
r = os.system(cmd)
if r:
print("ERROR: command returned {0}".format(r))
sys.exit(r)
if __name__ == "__main__":
version = get_version()
version_tag = version.replace("+", "-")
image_name = os.environ.get("QUAY_REPO", "quay.io/ansible/molecule")
expire = ""
tagging_args = ""
tags_to_push = [version_tag]
if Version(version).is_prerelease:
expire = "--label quay.expires-after=2w"
mobile_tag = "master"
tags_to_push.append(mobile_tag)
else:
# we have a release
mobile_tag = "latest"
tagging_args += "-t " + image_name + ":latest "
tags_to_push.append("latest")
# if on master, we want to also move the master tag
if os.environ.get("TRAVIS_BRANCH", None) == "master":
tagging_args += "-t " + image_name + ":master "
tags_to_push.append("master")
engine = which("podman") or which("docker")
engine_opts = ""
# hack to avoid apk fetch getting stuck on systems where host machine has ipv6 enabled
# as containers support for IPv6 is almost for sure not working on both docker/podman.
# https://github.com/gliderlabs/docker-alpine/issues/307
# https://stackoverflow.com/a/41497555/99834
if not engine:
raise NotImplementedError("Unsupported container engine")
elif engine.endswith("podman"):
# https://github.com/containers/libpod/issues/5403
ip = socket.getaddrinfo("dl-cdn.alpinelinux.org", 80, socket.AF_INET)[0][4][0]
engine_opts = "--add-host dl-cdn.alpinelinux.org:" + ip
print(f"Building version {version_tag} using {engine} container engine")
# using '--network host' may fail in some cases where not specifying the
# network works fine.
run(
f"{engine} build {engine_opts} --pull "
f"-t {image_name}:{version_tag} {tagging_args} {expire} ."
)
# Decide to push when all conditions below are met:
if os.environ.get("TRAVIS_BUILD_STAGE_NAME", None) == "deploy":
run(f"{engine} login quay.io")
for tag in tags_to_push:
run(f"{engine} push {image_name}:{tag}")
| []
| []
| [
"TRAVIS_BRANCH",
"QUAY_REPO",
"TRAVIS_BUILD_STAGE_NAME"
]
| [] | ["TRAVIS_BRANCH", "QUAY_REPO", "TRAVIS_BUILD_STAGE_NAME"] | python | 3 | 0 | |
rbqwrapper/rbqwrapper.py | #!/usr/bin/env python
"""
Run a provided tool with arguments, look for a correctly formatted JSON result, and send it over RabbitMQ.
Usage:
rbqwrapper.py /tool/executable arg arg...
The tool must output a JSON file of the following form (using mac_addresses, ipv4_addresses, or ipv6_addresses):
{
"tool": "tool name",
"data": {
"mac_addresses": {
"01:02:03:04:05:06": { ..metadata for MAC.. },
},
},
}
"""
import logging
import json
import os
import socket
import subprocess
import sys
import pika
logging.getLogger("pika").setLevel(logging.WARNING)
class RbqWrapper:
def __init__(self):
logging.basicConfig(
level=logging.INFO,
handlers=[logging.StreamHandler(sys.stdout)]
)
self.logger = logging.getLogger('rbqwrapper')
self.result_path = os.getenv('RESULT_PATH', 'result.json')
self.rabbit_host = os.getenv('RABBIT_HOST', '')
self.rabbit_queue_name = os.getenv('RABBIT_QUEUE_NAME', 'task_queue')
self.rabbit_exchange = os.getenv('RABBIT_EXCHANGE', 'task_queue')
self.rabbit_port = int(os.getenv('RABBIT_PORT', '5672'))
self.rabbit_routing_key = os.getenv('RABBIT_ROUTING_KEY', 'task_queue')
def _connect_rabbit(self):
params = pika.ConnectionParameters(host=self.rabbit_host, port=self.rabbit_port)
connection = pika.BlockingConnection(params)
channel = connection.channel()
channel.queue_declare(queue=self.rabbit_queue_name, durable=True)
self.logger.info('_connect_rabbit: channel open %s:%u', self.rabbit_host, self.rabbit_port)
return (connection, channel)
def _send_rabbit_msg(self, msg, channel):
body = json.dumps(msg)
channel.basic_publish(
exchange=self.rabbit_exchange,
routing_key=self.rabbit_routing_key,
body=body,
properties=pika.BasicProperties(delivery_mode=2))
self.logger.info('_send_rabbit_msg: %s', body)
def _validate_results(self, results):
if isinstance(results, dict):
results = [results]
for required_field in ('tool', 'data'):
for result in results:
if required_field not in result:
self.logger.error('results are missing field %s', required_field)
return False
for result in results:
data = result.get('data', None)
if data != "":
if not isinstance(data, dict):
self.logger.error('results data must be a dict')
return False
for required_metadata_field in ('mac_addresses', 'ipv4_addresses', 'ipv6_addresses'):
required_metadata = data.get(required_metadata_field, None)
self.logger.info(required_metadata)
if required_metadata and not isinstance(required_metadata, dict):
self.logger.error('results have an incorrect datatype, %s should be a dict', required_metadata)
return False
return True
def output_msg(self):
try:
with open(self.result_path) as result_path:
results = json.load(result_path)
except (FileNotFoundError,) as err:
self.logger.error('could not read/parse JSON results from %s: %s', self.result_path, err)
return
self.logger.info('read %s', results)
if not self._validate_results(results):
return
try:
(connection, channel) = self._connect_rabbit()
for result in results:
self._send_rabbit_msg(result, channel)
connection.close()
except (socket.gaierror, pika.exceptions.AMQPConnectionError) as err:
self.logger.error('Failed to send Rabbit message %s because: %s', results, err)
def main(argv):
if argv:
try:
subprocess.check_call(argv)
except subprocess.CalledProcessError as err:
sys.exit(err.returncode)
rbqwrapper = RbqWrapper()
if rbqwrapper.rabbit_host:
rbqwrapper.output_msg()
if __name__ == '__main__': # pragma: no cover
main(sys.argv[1:])
| []
| []
| [
"RABBIT_EXCHANGE",
"RABBIT_HOST",
"RESULT_PATH",
"RABBIT_QUEUE_NAME",
"RABBIT_ROUTING_KEY",
"RABBIT_PORT"
]
| [] | ["RABBIT_EXCHANGE", "RABBIT_HOST", "RESULT_PATH", "RABBIT_QUEUE_NAME", "RABBIT_ROUTING_KEY", "RABBIT_PORT"] | python | 6 | 0 | |
kapi/kdash/main.go | package main
import (
"net/http"
"os"
"github.com/codegangsta/negroni"
"github.com/gorilla/mux"
"github.com/unrolled/render"
)
func main() {
port := os.Getenv("PORT")
if len(port) == 0 {
port = "8100"
}
server := NewServer()
server.Run(":" + port)
}
var webRoot string
// NewServer configures and returns a Server.
func NewServer() *negroni.Negroni {
formatter := render.New(render.Options{
IndentJSON: true,
})
n := negroni.Classic()
mx := mux.NewRouter()
initRoutes(mx, formatter)
n.UseHandler(mx)
return n
}
func initRoutes(mx *mux.Router, formatter *render.Render) {
webRoot = os.Getenv("WEBROOT")
if len(webRoot) == 0 {
root, err := os.Getwd()
if err != nil {
panic("Could not retrieve working directory")
} else {
webRoot = root
}
}
mx.PathPrefix("/").Handler(http.FileServer(http.Dir(webRoot + "/static/")))
}
| [
"\"PORT\"",
"\"WEBROOT\""
]
| []
| [
"PORT",
"WEBROOT"
]
| [] | ["PORT", "WEBROOT"] | go | 2 | 0 | |
test/e2e/e2e_test.go | // Copyright © 2022 Kaleido, Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// 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 e2e
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"strings"
"testing"
"time"
"github.com/go-resty/resty/v2"
"github.com/gorilla/websocket"
"github.com/hyperledger/firefly/pkg/fftypes"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type testState struct {
startTime time.Time
t *testing.T
client1 *resty.Client
client2 *resty.Client
ws1 *websocket.Conn
ws2 *websocket.Conn
org1 *fftypes.Organization
org2 *fftypes.Organization
done func()
}
var widgetSchemaJSON = []byte(`{
"$id": "https://example.com/widget.schema.json",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Widget",
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "The unique identifier for the widget."
},
"name": {
"type": "string",
"description": "The person's last name."
}
},
"additionalProperties": false
}`)
func pollForUp(t *testing.T, client *resty.Client) {
var resp *resty.Response
var err error
for i := 0; i < 3; i++ {
resp, err = GetNamespaces(client)
if err == nil && resp.StatusCode() == 200 {
break
}
time.Sleep(5 * time.Second)
}
require.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode())
}
func validateReceivedMessages(ts *testState, client *resty.Client, topic string, msgType fftypes.MessageType, txtype fftypes.TransactionType, count int) (data []*fftypes.Data) {
var group *fftypes.Bytes32
messages := GetMessages(ts.t, client, ts.startTime, msgType, topic, 200)
for i, message := range messages {
ts.t.Logf("Message %d: %+v", i, *message)
if group != nil {
assert.Equal(ts.t, group.String(), message.Header.Group.String(), "All messages must be same group")
}
group = message.Header.Group
}
assert.Equal(ts.t, count, len(messages))
var returnData []*fftypes.Data
for idx := 0; idx < len(messages); idx++ {
assert.Equal(ts.t, txtype, (messages)[idx].Header.TxType)
assert.Equal(ts.t, fftypes.FFStringArray{topic}, (messages)[idx].Header.Topics)
assert.Equal(ts.t, topic, (messages)[idx].Header.Topics[0])
data := GetDataForMessage(ts.t, client, ts.startTime, (messages)[idx].Header.ID)
var msgData *fftypes.Data
for i, d := range data {
ts.t.Logf("Data %d: %+v", i, *d)
if *d.ID == *messages[idx].Data[0].ID {
msgData = d
}
}
assert.NotNil(ts.t, msgData, "Found data with ID '%s'", messages[idx].Data[0].ID)
if group == nil {
assert.Equal(ts.t, 1, len(data))
}
returnData = append(returnData, msgData)
assert.Equal(ts.t, "default", msgData.Namespace)
expectedHash, err := msgData.CalcHash(context.Background())
assert.NoError(ts.t, err)
assert.Equal(ts.t, *expectedHash, *msgData.Hash)
if msgData.Blob != nil {
blob := GetBlob(ts.t, client, msgData, 200)
assert.NotNil(ts.t, blob)
var hash fftypes.Bytes32 = sha256.Sum256(blob)
assert.Equal(ts.t, *msgData.Blob.Hash, hash)
}
}
// Flip data (returned in most recent order) into delivery order
return returnData
}
func validateAccountBalances(t *testing.T, client *resty.Client, poolID *fftypes.UUID, tokenIndex string, balances map[string]int64) {
for key, balance := range balances {
account := GetTokenBalance(t, client, poolID, tokenIndex, key)
assert.Equal(t, "erc1155", account.Connector)
assert.Equal(t, balance, account.Balance.Int().Int64())
}
}
func pickTopic(i int, options []string) string {
return options[i%len(options)]
}
func readStackFile(t *testing.T) *Stack {
stackFile := os.Getenv("STACK_FILE")
if stackFile == "" {
t.Fatal("STACK_FILE must be set")
}
stack, err := ReadStack(stackFile)
assert.NoError(t, err)
return stack
}
func beforeE2ETest(t *testing.T) *testState {
stack := readStackFile(t)
var authHeader1 http.Header
var authHeader2 http.Header
ts := &testState{
t: t,
startTime: time.Now(),
client1: NewResty(t),
client2: NewResty(t),
}
httpProtocolClient1 := "http"
websocketProtocolClient1 := "ws"
httpProtocolClient2 := "http"
websocketProtocolClient2 := "ws"
if stack.Members[0].UseHTTPS {
httpProtocolClient1 = "https"
websocketProtocolClient1 = "wss"
}
if stack.Members[1].UseHTTPS {
httpProtocolClient2 = "https"
websocketProtocolClient2 = "wss"
}
member0WithPort := ""
if stack.Members[0].ExposedFireflyPort != 0 {
member0WithPort = fmt.Sprintf(":%d", stack.Members[0].ExposedFireflyPort)
}
member1WithPort := ""
if stack.Members[1].ExposedFireflyPort != 0 {
member1WithPort = fmt.Sprintf(":%d", stack.Members[1].ExposedFireflyPort)
}
ts.client1.SetBaseURL(fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient1, stack.Members[0].FireflyHostname, member0WithPort))
ts.client2.SetBaseURL(fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient2, stack.Members[1].FireflyHostname, member1WithPort))
if stack.Members[0].Username != "" && stack.Members[0].Password != "" {
t.Log("Setting auth for user 1")
ts.client1.SetBasicAuth(stack.Members[0].Username, stack.Members[0].Password)
authHeader1 = http.Header{
"Authorization": []string{fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", stack.Members[0].Username, stack.Members[0].Password))))},
}
}
if stack.Members[1].Username != "" && stack.Members[1].Password != "" {
t.Log("Setting auth for user 2")
ts.client2.SetBasicAuth(stack.Members[1].Username, stack.Members[1].Password)
authHeader2 = http.Header{
"Authorization": []string{fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", stack.Members[1].Username, stack.Members[1].Password))))},
}
}
t.Logf("Client 1: " + ts.client1.HostURL)
t.Logf("Client 2: " + ts.client2.HostURL)
pollForUp(t, ts.client1)
pollForUp(t, ts.client2)
for {
orgsC1 := GetOrgs(t, ts.client1, 200)
orgsC2 := GetOrgs(t, ts.client2, 200)
if len(orgsC1) >= 2 && len(orgsC2) >= 2 {
// in case there are more than two orgs in the network we need to ensure
// we select the same two that were provided in the first two elements
// of the stack file
for _, org := range orgsC1 {
if org.Name == stack.Members[0].OrgName {
ts.org1 = org
} else if org.Name == stack.Members[1].OrgName {
ts.org2 = org
}
}
if ts.org1 != nil && ts.org2 != nil {
break
}
}
t.Logf("Waiting for 2 orgs to appear. Currently have: node1=%d node2=%d", len(orgsC1), len(orgsC2))
time.Sleep(3 * time.Second)
}
eventNames := "message_confirmed|token_pool_confirmed|token_transfer_confirmed|blockchain_event|token_approval_confirmed"
queryString := fmt.Sprintf("namespace=default&ephemeral&autoack&filter.events=%s&changeevents=.*", eventNames)
wsUrl1 := url.URL{
Scheme: websocketProtocolClient1,
Host: fmt.Sprintf("%s%s", stack.Members[0].FireflyHostname, member0WithPort),
Path: "/ws",
RawQuery: queryString,
}
wsUrl2 := url.URL{
Scheme: websocketProtocolClient2,
Host: fmt.Sprintf("%s%s", stack.Members[1].FireflyHostname, member1WithPort),
Path: "/ws",
RawQuery: queryString,
}
t.Logf("Websocket 1: " + wsUrl1.String())
t.Logf("Websocket 2: " + wsUrl2.String())
var err error
ts.ws1, _, err = websocket.DefaultDialer.Dial(wsUrl1.String(), authHeader1)
if err != nil {
t.Logf(err.Error())
}
require.NoError(t, err)
ts.ws2, _, err = websocket.DefaultDialer.Dial(wsUrl2.String(), authHeader2)
require.NoError(t, err)
ts.done = func() {
ts.ws1.Close()
ts.ws2.Close()
t.Log("WebSockets closed")
}
return ts
}
func wsReader(conn *websocket.Conn) (chan *fftypes.EventDelivery, chan *fftypes.ChangeEvent) {
events := make(chan *fftypes.EventDelivery, 100)
changeEvents := make(chan *fftypes.ChangeEvent, 100)
go func() {
for {
_, b, err := conn.ReadMessage()
if err != nil {
fmt.Printf("Websocket %s closing, error: %s", conn.RemoteAddr(), err)
return
}
fmt.Printf("Websocket %s receive: %s", conn.RemoteAddr(), b)
var wsa fftypes.WSClientActionBase
err = json.Unmarshal(b, &wsa)
if err != nil {
panic(fmt.Errorf("Invalid JSON received on WebSocket: %s", err))
}
switch wsa.Type {
case fftypes.WSClientActionChangeNotifcation:
var wscn fftypes.WSChangeNotification
err = json.Unmarshal(b, &wscn)
if err != nil {
panic(fmt.Errorf("Invalid JSON received on WebSocket: %s", err))
}
if err == nil {
changeEvents <- wscn.ChangeEvent
}
default:
var ed fftypes.EventDelivery
err = json.Unmarshal(b, &ed)
if err != nil {
panic(fmt.Errorf("Invalid JSON received on WebSocket: %s", err))
}
if err == nil {
events <- &ed
}
}
}
}()
return events, changeEvents
}
func waitForEvent(t *testing.T, c chan *fftypes.EventDelivery, eventType fftypes.EventType, ref *fftypes.UUID) {
for {
eventDelivery := <-c
if eventDelivery.Type == eventType && (ref == nil || *ref == *eventDelivery.Reference) {
return
}
}
}
func waitForMessageConfirmed(t *testing.T, c chan *fftypes.EventDelivery, msgType fftypes.MessageType) *fftypes.EventDelivery {
for {
ed := <-c
if ed.Type == fftypes.EventTypeMessageConfirmed && ed.Message != nil && ed.Message.Header.Type == msgType {
t.Logf("Detected '%s' event for message '%s' of type '%s'", ed.Type, ed.Message.Header.ID, msgType)
return ed
}
t.Logf("Ignored event '%s'", ed.ID)
}
}
func waitForContractEvent(t *testing.T, client *resty.Client, c chan *fftypes.EventDelivery, match map[string]interface{}) map[string]interface{} {
for {
eventDelivery := <-c
if eventDelivery.Type == fftypes.EventTypeBlockchainEvent {
event, err := GetBlockchainEvent(t, client, eventDelivery.Event.Reference.String())
if err != nil {
t.Logf("WARN: unable to get event: %v", err.Error())
continue
}
eventJSON, ok := event.(map[string]interface{})
if !ok {
t.Logf("WARN: unable to parse changeEvent: %v", event)
continue
}
if checkObject(t, match, eventJSON) {
return eventJSON
}
}
}
}
func checkObject(t *testing.T, expected interface{}, actual interface{}) bool {
match := true
// check if this is a nested object
expectedObject, expectedIsObject := expected.(map[string]interface{})
actualObject, actualIsObject := actual.(map[string]interface{})
t.Logf("Matching blockchain event: %s", fftypes.JSONObject(actualObject).String())
// check if this is an array
expectedArray, expectedIsArray := expected.([]interface{})
actualArray, actualIsArray := actual.([]interface{})
switch {
case expectedIsObject && actualIsObject:
for expectedKey, expectedValue := range expectedObject {
if !checkObject(t, expectedValue, actualObject[expectedKey]) {
return false
}
}
case expectedIsArray && actualIsArray:
for _, expectedItem := range expectedArray {
for j, actualItem := range actualArray {
if checkObject(t, expectedItem, actualItem) {
break
}
if j == len(actualArray)-1 {
return false
}
}
}
default:
expectedString, expectedIsString := expected.(string)
actualString, actualIsString := expected.(string)
if expectedIsString && actualIsString {
return strings.ToLower(expectedString) == strings.ToLower(actualString)
}
return expected == actual
}
return match
}
| [
"\"STACK_FILE\""
]
| []
| [
"STACK_FILE"
]
| [] | ["STACK_FILE"] | go | 1 | 0 | |
markov_gen.py | import markovify
from pymongo import MongoClient
import logging
import os
import re
import nltk
import requests
logger = logging.getLogger(__name__)
MONGODB_URI = os.getenv('MONGODB_URI')
USER_KEY = os.getenv('USER_KEY')
class POSifiedText(markovify.Text):
def word_split(self, sentence):
words = re.split(self.word_split_pattern, sentence)
words = [ "::".join(tag) for tag in nltk.pos_tag(words) ]
return words
def word_join(self, words):
sentence = " ".join(word.split("::")[0] for word in words)
return sentence
def gen_markov(user_id):
client = MongoClient(MONGODB_URI)
db = client.get_default_database()
posts = db.posts
entry = posts.find_one({"_id": str(user_id)})
if entry:
corpus = entry['text']
text_model = markovify.Text(corpus)
return text_model.make_sentence()
else:
logger.info('No corpus for user' + str(user_id))
| []
| []
| [
"USER_KEY",
"MONGODB_URI"
]
| [] | ["USER_KEY", "MONGODB_URI"] | python | 2 | 0 | |
pkg/model/model.go | package model
// modeled after
// https://www.opsdash.com/blog/persistent-key-value-store-golang.html
import (
"errors"
"os"
"time"
log "github.com/Sirupsen/logrus"
"github.com/boltdb/bolt"
"github.com/vouch/vouch-proxy/pkg/cfg"
)
var (
// ErrNotFound is returned when the key supplied to a Get or Delete
// method does not exist in the database.
ErrNotFound = errors.New("key not found")
// ErrBadValue is returned when the value supplied to the Put method
// is nil.
ErrBadValue = errors.New("bad value")
//Db holds the db
Db *bolt.DB
dbpath string
userBucket = []byte("users")
teamBucket = []byte("teams")
siteBucket = []byte("sites")
)
// may want to use encode/gob to store the user record
func init() {
dbpath = os.Getenv("VOUCH_ROOT") + cfg.Cfg.DB.File
Db, _ = OpenDB(dbpath)
}
// OpenDB the boltdb
func OpenDB(dbfile string) (*bolt.DB, error) {
opts := &bolt.Options{
Timeout: 50 * time.Millisecond,
}
db, err := bolt.Open(dbfile, 0644, opts)
if err != nil {
log.Fatal(err)
return nil, err
}
return db, nil
}
func getBucket(tx *bolt.Tx, key []byte) *bolt.Bucket {
b, err := tx.CreateBucketIfNotExists(key)
if err != nil {
log.Errorf("could not create bucket in db %s", err)
log.Errorf("check the dbfile permissions at %s", dbpath)
log.Errorf("if there's really something wrong with the data ./do.sh includes a utility to browse the dbfile")
return nil
}
return b
}
| [
"\"VOUCH_ROOT\""
]
| []
| [
"VOUCH_ROOT"
]
| [] | ["VOUCH_ROOT"] | go | 1 | 0 | |
pkg/network/multus.go | package network
import (
"os"
"path/filepath"
operv1 "github.com/openshift/api/operator/v1"
"github.com/openshift/cluster-network-operator/pkg/render"
"github.com/pkg/errors"
uns "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
const (
SystemCNIConfDir = "/etc/kubernetes/cni/net.d"
MultusCNIConfDir = "/var/run/multus/cni/net.d"
CNIBinDir = "/var/lib/cni/bin"
)
// RenderMultus generates the manifests of Multus
func RenderMultus(conf *operv1.NetworkSpec, manifestDir string) ([]*uns.Unstructured, error) {
if *conf.DisableMultiNetwork {
return nil, nil
}
var err error
out := []*uns.Unstructured{}
objs := []*uns.Unstructured{}
// enabling Multus always renders the CRD since Multus uses it
objs, err = renderAdditionalNetworksCRD(manifestDir)
if err != nil {
return nil, err
}
out = append(out, objs...)
usedhcp := UseDHCP(conf)
objs, err = renderMultusConfig(manifestDir, string(conf.DefaultNetwork.Type), usedhcp)
if err != nil {
return nil, err
}
out = append(out, objs...)
return out, nil
}
// renderMultusConfig returns the manifests of Multus
func renderMultusConfig(manifestDir, defaultNetworkType string, useDHCP bool) ([]*uns.Unstructured, error) {
objs := []*uns.Unstructured{}
// render the manifests on disk
data := render.MakeRenderData()
data.Data["ReleaseVersion"] = os.Getenv("RELEASE_VERSION")
data.Data["MultusImage"] = os.Getenv("MULTUS_IMAGE")
data.Data["CNIPluginsImage"] = os.Getenv("CNI_PLUGINS_IMAGE")
data.Data["WhereaboutsImage"] = os.Getenv("WHEREABOUTS_CNI_IMAGE")
data.Data["RouteOverrideImage"] = os.Getenv("ROUTE_OVERRRIDE_CNI_IMAGE")
data.Data["KUBERNETES_SERVICE_HOST"] = os.Getenv("KUBERNETES_SERVICE_HOST")
data.Data["KUBERNETES_SERVICE_PORT"] = os.Getenv("KUBERNETES_SERVICE_PORT")
data.Data["RenderDHCP"] = useDHCP
data.Data["MultusCNIConfDir"] = MultusCNIConfDir
data.Data["SystemCNIConfDir"] = SystemCNIConfDir
data.Data["DefaultNetworkType"] = defaultNetworkType
data.Data["CNIBinDir"] = CNIBinDir
manifests, err := render.RenderDir(filepath.Join(manifestDir, "network/multus"), &data)
if err != nil {
return nil, errors.Wrap(err, "failed to render multus manifests")
}
objs = append(objs, manifests...)
return objs, nil
}
// pluginCNIDir is the directory where plugins should install their CNI
// configuration file. By default, it is where multus looks, unless multus
// is disabled
func pluginCNIConfDir(conf *operv1.NetworkSpec) string {
if *conf.DisableMultiNetwork {
return SystemCNIConfDir
}
return MultusCNIConfDir
}
| [
"\"RELEASE_VERSION\"",
"\"MULTUS_IMAGE\"",
"\"CNI_PLUGINS_IMAGE\"",
"\"WHEREABOUTS_CNI_IMAGE\"",
"\"ROUTE_OVERRRIDE_CNI_IMAGE\"",
"\"KUBERNETES_SERVICE_HOST\"",
"\"KUBERNETES_SERVICE_PORT\""
]
| []
| [
"WHEREABOUTS_CNI_IMAGE",
"ROUTE_OVERRRIDE_CNI_IMAGE",
"KUBERNETES_SERVICE_HOST",
"RELEASE_VERSION",
"KUBERNETES_SERVICE_PORT",
"CNI_PLUGINS_IMAGE",
"MULTUS_IMAGE"
]
| [] | ["WHEREABOUTS_CNI_IMAGE", "ROUTE_OVERRRIDE_CNI_IMAGE", "KUBERNETES_SERVICE_HOST", "RELEASE_VERSION", "KUBERNETES_SERVICE_PORT", "CNI_PLUGINS_IMAGE", "MULTUS_IMAGE"] | go | 7 | 0 | |
config/config.go | package config
import (
"os"
"strconv"
)
// Config struct for config values
type Config struct {
Port int
DbURL string
ProxyURL string
LineChannelSecret string
LineChannelAccessToken string
}
// New returns config struct with default values.
func New() *Config {
return &Config{
Port: 8000,
DbURL: "mysql://root:@localhost/totsuka_ps_bot",
}
}
// Load is loading config values.
func (c *Config) Load() error {
if err := c.loadPort(); err != nil {
return err
}
if err := c.loadDbURL(); err != nil {
return err
}
if err := c.loadProxyURL(); err != nil {
return err
}
if err := c.loadLineChannelSecret(); err != nil {
return err
}
if err := c.loadLineChannelAccessToken(); err != nil {
return err
}
return nil
}
func (c *Config) loadPort() error {
port := os.Getenv("PORT")
if port != "" {
p, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil {
return err
}
c.Port = p
}
return nil
}
func (c *Config) loadDbURL() error {
if os.Getenv("DATABASE_URL") != "" {
c.DbURL = os.Getenv("DATABASE_URL")
}
if os.Getenv("CLEARDB_DATABASE_URL") != "" {
c.DbURL = os.Getenv("CLEARDB_DATABASE_URL")
}
return nil
}
func (c *Config) loadProxyURL() error {
if os.Getenv("PROXY_URL") != "" {
c.ProxyURL = os.Getenv("PROXY_URL")
}
if os.Getenv("FIXIE_URL") != "" {
c.ProxyURL = os.Getenv("FIXIE_URL")
}
return nil
}
func (c *Config) loadLineChannelSecret() error {
c.LineChannelSecret = os.Getenv("LINE_CHANNEL_SECRET")
return nil
}
func (c *Config) loadLineChannelAccessToken() error {
c.LineChannelAccessToken = os.Getenv("LINE_CHANNEL_ACCESS_TOKEN")
return nil
}
| [
"\"PORT\"",
"\"PORT\"",
"\"DATABASE_URL\"",
"\"DATABASE_URL\"",
"\"CLEARDB_DATABASE_URL\"",
"\"CLEARDB_DATABASE_URL\"",
"\"PROXY_URL\"",
"\"PROXY_URL\"",
"\"FIXIE_URL\"",
"\"FIXIE_URL\"",
"\"LINE_CHANNEL_SECRET\"",
"\"LINE_CHANNEL_ACCESS_TOKEN\""
]
| []
| [
"PORT",
"LINE_CHANNEL_ACCESS_TOKEN",
"DATABASE_URL",
"PROXY_URL",
"CLEARDB_DATABASE_URL",
"FIXIE_URL",
"LINE_CHANNEL_SECRET"
]
| [] | ["PORT", "LINE_CHANNEL_ACCESS_TOKEN", "DATABASE_URL", "PROXY_URL", "CLEARDB_DATABASE_URL", "FIXIE_URL", "LINE_CHANNEL_SECRET"] | go | 7 | 0 | |
chain/store/store.go | package store
import (
"context"
"encoding/json"
"errors"
"os"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/sync/errgroup"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/lotus/api"
bstore "github.com/filecoin-project/lotus/blockstore"
"github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/actors/adt"
"github.com/filecoin-project/lotus/journal"
"github.com/filecoin-project/lotus/metrics"
"go.opencensus.io/stats"
"go.opencensus.io/trace"
"go.uber.org/multierr"
"github.com/filecoin-project/lotus/chain/types"
lru "github.com/hashicorp/golang-lru"
block "github.com/ipfs/go-block-format"
"github.com/ipfs/go-cid"
dstore "github.com/ipfs/go-datastore"
"github.com/ipfs/go-datastore/query"
cbor "github.com/ipfs/go-ipld-cbor"
logging "github.com/ipfs/go-log/v2"
"github.com/whyrusleeping/pubsub"
"golang.org/x/xerrors"
)
var log = logging.Logger("chainstore")
var (
chainHeadKey = dstore.NewKey("head")
checkpointKey = dstore.NewKey("/chain/checks")
blockValidationCacheKeyPrefix = dstore.NewKey("blockValidation")
)
var DefaultTipSetCacheSize = 8192
var DefaultMsgMetaCacheSize = 2048
var ErrNotifeeDone = errors.New("notifee is done and should be removed")
func init() {
if s := os.Getenv("LOTUS_CHAIN_TIPSET_CACHE"); s != "" {
tscs, err := strconv.Atoi(s)
if err != nil {
log.Errorf("failed to parse 'LOTUS_CHAIN_TIPSET_CACHE' env var: %s", err)
}
DefaultTipSetCacheSize = tscs
}
if s := os.Getenv("LOTUS_CHAIN_MSGMETA_CACHE"); s != "" {
mmcs, err := strconv.Atoi(s)
if err != nil {
log.Errorf("failed to parse 'LOTUS_CHAIN_MSGMETA_CACHE' env var: %s", err)
}
DefaultMsgMetaCacheSize = mmcs
}
}
// ReorgNotifee represents a callback that gets called upon reorgs.
type ReorgNotifee = func(rev, app []*types.TipSet) error
// Journal event types.
const (
evtTypeHeadChange = iota
)
type HeadChangeEvt struct {
From types.TipSetKey
FromHeight abi.ChainEpoch
To types.TipSetKey
ToHeight abi.ChainEpoch
RevertCount int
ApplyCount int
}
// ChainStore is the main point of access to chain data.
//
// Raw chain data is stored in the Blockstore, with relevant markers (genesis,
// latest head tipset references) being tracked in the Datastore (key-value
// store).
//
// To alleviate disk access, the ChainStore has two ARC caches:
// 1. a tipset cache
// 2. a block => messages references cache.
type ChainStore struct {
chainBlockstore bstore.Blockstore
stateBlockstore bstore.Blockstore
metadataDs dstore.Batching
chainLocalBlockstore bstore.Blockstore
heaviestLk sync.RWMutex
heaviest *types.TipSet
checkpoint *types.TipSet
bestTips *pubsub.PubSub
pubLk sync.Mutex
tstLk sync.Mutex
tipsets map[abi.ChainEpoch][]cid.Cid
cindex *ChainIndex
reorgCh chan<- reorg
reorgNotifeeCh chan ReorgNotifee
mmCache *lru.ARCCache // msg meta cache (mh.Messages -> secp, bls []cid)
tsCache *lru.ARCCache
evtTypes [1]journal.EventType
journal journal.Journal
cancelFn context.CancelFunc
wg sync.WaitGroup
}
func NewChainStore(chainBs bstore.Blockstore, stateBs bstore.Blockstore, ds dstore.Batching, j journal.Journal) *ChainStore {
c, _ := lru.NewARC(DefaultMsgMetaCacheSize)
tsc, _ := lru.NewARC(DefaultTipSetCacheSize)
if j == nil {
j = journal.NilJournal()
}
ctx, cancel := context.WithCancel(context.Background())
// unwraps the fallback store in case one is configured.
// some methods _need_ to operate on a local blockstore only.
localbs, _ := bstore.UnwrapFallbackStore(chainBs)
cs := &ChainStore{
chainBlockstore: chainBs,
stateBlockstore: stateBs,
chainLocalBlockstore: localbs,
metadataDs: ds,
bestTips: pubsub.New(64),
tipsets: make(map[abi.ChainEpoch][]cid.Cid),
mmCache: c,
tsCache: tsc,
cancelFn: cancel,
journal: j,
}
cs.evtTypes = [1]journal.EventType{
evtTypeHeadChange: j.RegisterEventType("sync", "head_change"),
}
ci := NewChainIndex(cs.LoadTipSet)
cs.cindex = ci
hcnf := func(rev, app []*types.TipSet) error {
cs.pubLk.Lock()
defer cs.pubLk.Unlock()
notif := make([]*api.HeadChange, len(rev)+len(app))
for i, r := range rev {
notif[i] = &api.HeadChange{
Type: HCRevert,
Val: r,
}
}
for i, r := range app {
notif[i+len(rev)] = &api.HeadChange{
Type: HCApply,
Val: r,
}
}
cs.bestTips.Pub(notif, "headchange")
return nil
}
hcmetric := func(rev, app []*types.TipSet) error {
for _, r := range app {
stats.Record(context.Background(), metrics.ChainNodeHeight.M(int64(r.Height())))
}
return nil
}
cs.reorgNotifeeCh = make(chan ReorgNotifee)
cs.reorgCh = cs.reorgWorker(ctx, []ReorgNotifee{hcnf, hcmetric})
return cs
}
func (cs *ChainStore) Close() error {
cs.cancelFn()
cs.wg.Wait()
return nil
}
func (cs *ChainStore) Load() error {
if err := cs.loadHead(); err != nil {
return err
}
if err := cs.loadCheckpoint(); err != nil {
return err
}
return nil
}
func (cs *ChainStore) loadHead() error {
head, err := cs.metadataDs.Get(chainHeadKey)
if err == dstore.ErrNotFound {
log.Warn("no previous chain state found")
return nil
}
if err != nil {
return xerrors.Errorf("failed to load chain state from datastore: %w", err)
}
var tscids []cid.Cid
if err := json.Unmarshal(head, &tscids); err != nil {
return xerrors.Errorf("failed to unmarshal stored chain head: %w", err)
}
ts, err := cs.LoadTipSet(types.NewTipSetKey(tscids...))
if err != nil {
return xerrors.Errorf("loading tipset: %w", err)
}
cs.heaviest = ts
return nil
}
func (cs *ChainStore) loadCheckpoint() error {
tskBytes, err := cs.metadataDs.Get(checkpointKey)
if err == dstore.ErrNotFound {
return nil
}
if err != nil {
return xerrors.Errorf("failed to load checkpoint from datastore: %w", err)
}
var tsk types.TipSetKey
err = json.Unmarshal(tskBytes, &tsk)
if err != nil {
return err
}
ts, err := cs.LoadTipSet(tsk)
if err != nil {
return xerrors.Errorf("loading tipset: %w", err)
}
cs.checkpoint = ts
return nil
}
func (cs *ChainStore) writeHead(ts *types.TipSet) error {
data, err := json.Marshal(ts.Cids())
if err != nil {
return xerrors.Errorf("failed to marshal tipset: %w", err)
}
if err := cs.metadataDs.Put(chainHeadKey, data); err != nil {
return xerrors.Errorf("failed to write chain head to datastore: %w", err)
}
return nil
}
const (
HCRevert = "revert"
HCApply = "apply"
HCCurrent = "current"
)
func (cs *ChainStore) SubHeadChanges(ctx context.Context) chan []*api.HeadChange {
cs.pubLk.Lock()
subch := cs.bestTips.Sub("headchange")
head := cs.GetHeaviestTipSet()
cs.pubLk.Unlock()
out := make(chan []*api.HeadChange, 16)
out <- []*api.HeadChange{{
Type: HCCurrent,
Val: head,
}}
go func() {
defer func() {
// Tell the caller we're done first, the following may block for a bit.
close(out)
// Unsubscribe.
cs.bestTips.Unsub(subch)
// Drain the channel.
for range subch {
}
}()
for {
select {
case val, ok := <-subch:
if !ok {
// Shutting down.
return
}
select {
case out <- val.([]*api.HeadChange):
default:
log.Errorf("closing head change subscription due to slow reader")
return
}
if len(out) > 5 {
log.Warnf("head change sub is slow, has %d buffered entries", len(out))
}
case <-ctx.Done():
return
}
}
}()
return out
}
func (cs *ChainStore) SubscribeHeadChanges(f ReorgNotifee) {
cs.reorgNotifeeCh <- f
}
func (cs *ChainStore) IsBlockValidated(ctx context.Context, blkid cid.Cid) (bool, error) {
key := blockValidationCacheKeyPrefix.Instance(blkid.String())
return cs.metadataDs.Has(key)
}
func (cs *ChainStore) MarkBlockAsValidated(ctx context.Context, blkid cid.Cid) error {
key := blockValidationCacheKeyPrefix.Instance(blkid.String())
if err := cs.metadataDs.Put(key, []byte{0}); err != nil {
return xerrors.Errorf("cache block validation: %w", err)
}
return nil
}
func (cs *ChainStore) UnmarkBlockAsValidated(ctx context.Context, blkid cid.Cid) error {
key := blockValidationCacheKeyPrefix.Instance(blkid.String())
if err := cs.metadataDs.Delete(key); err != nil {
return xerrors.Errorf("removing from valid block cache: %w", err)
}
return nil
}
func (cs *ChainStore) SetGenesis(b *types.BlockHeader) error {
ts, err := types.NewTipSet([]*types.BlockHeader{b})
if err != nil {
return err
}
if err := cs.PutTipSet(context.TODO(), ts); err != nil {
return err
}
return cs.metadataDs.Put(dstore.NewKey("0"), b.Cid().Bytes())
}
func (cs *ChainStore) PutTipSet(ctx context.Context, ts *types.TipSet) error {
for _, b := range ts.Blocks() {
if err := cs.PersistBlockHeaders(b); err != nil {
return err
}
}
expanded, err := cs.expandTipset(ts.Blocks()[0])
if err != nil {
return xerrors.Errorf("errored while expanding tipset: %w", err)
}
log.Debugf("expanded %s into %s\n", ts.Cids(), expanded.Cids())
if err := cs.MaybeTakeHeavierTipSet(ctx, expanded); err != nil {
return xerrors.Errorf("MaybeTakeHeavierTipSet failed in PutTipSet: %w", err)
}
return nil
}
// MaybeTakeHeavierTipSet evaluates the incoming tipset and locks it in our
// internal state as our new head, if and only if it is heavier than the current
// head and does not exceed the maximum fork length.
func (cs *ChainStore) MaybeTakeHeavierTipSet(ctx context.Context, ts *types.TipSet) error {
for {
cs.heaviestLk.Lock()
if len(cs.reorgCh) < reorgChBuf/2 {
break
}
cs.heaviestLk.Unlock()
log.Errorf("reorg channel is heavily backlogged, waiting a bit before trying to take process new tipsets")
select {
case <-time.After(time.Second / 2):
case <-ctx.Done():
return ctx.Err()
}
}
defer cs.heaviestLk.Unlock()
w, err := cs.Weight(ctx, ts)
if err != nil {
return err
}
heaviestW, err := cs.Weight(ctx, cs.heaviest)
if err != nil {
return err
}
if w.GreaterThan(heaviestW) {
// TODO: don't do this for initial sync. Now that we don't have a
// difference between 'bootstrap sync' and 'caught up' sync, we need
// some other heuristic.
exceeds, err := cs.exceedsForkLength(cs.heaviest, ts)
if err != nil {
return err
}
if exceeds {
return nil
}
return cs.takeHeaviestTipSet(ctx, ts)
} else if w.Equals(heaviestW) && !ts.Equals(cs.heaviest) {
log.Errorw("weight draw", "currTs", cs.heaviest, "ts", ts)
}
return nil
}
// Check if the two tipsets have a fork length above `ForkLengthThreshold`.
// `synced` is the head of the chain we are currently synced to and `external`
// is the incoming tipset potentially belonging to a forked chain. It assumes
// the external chain has already been validated and available in the ChainStore.
// The "fast forward" case is covered in this logic as a valid fork of length 0.
//
// FIXME: We may want to replace some of the logic in `syncFork()` with this.
// `syncFork()` counts the length on both sides of the fork at the moment (we
// need to settle on that) but here we just enforce it on the `synced` side.
func (cs *ChainStore) exceedsForkLength(synced, external *types.TipSet) (bool, error) {
if synced == nil || external == nil {
// FIXME: If `cs.heaviest` is nil we should just bypass the entire
// `MaybeTakeHeavierTipSet` logic (instead of each of the called
// functions having to handle the nil case on their own).
return false, nil
}
var err error
// `forkLength`: number of tipsets we need to walk back from the our `synced`
// chain to the common ancestor with the new `external` head in order to
// adopt the fork.
for forkLength := 0; forkLength < int(build.ForkLengthThreshold); forkLength++ {
// First walk back as many tipsets in the external chain to match the
// `synced` height to compare them. If we go past the `synced` height
// the subsequent match will fail but it will still be useful to get
// closer to the `synced` head parent's height in the next loop.
for external.Height() > synced.Height() {
if external.Height() == 0 {
// We reached the genesis of the external chain without a match;
// this is considered a fork outside the allowed limit (of "infinite"
// length).
return true, nil
}
external, err = cs.LoadTipSet(external.Parents())
if err != nil {
return false, xerrors.Errorf("failed to load parent tipset in external chain: %w", err)
}
}
// Now check if we arrived at the common ancestor.
if synced.Equals(external) {
return false, nil
}
// Now check to see if we've walked back to the checkpoint.
if synced.Equals(cs.checkpoint) {
return true, nil
}
// If we didn't, go back *one* tipset on the `synced` side (incrementing
// the `forkLength`).
if synced.Height() == 0 {
// Same check as the `external` side, if we reach the start (genesis)
// there is no common ancestor.
return true, nil
}
synced, err = cs.LoadTipSet(synced.Parents())
if err != nil {
return false, xerrors.Errorf("failed to load parent tipset in synced chain: %w", err)
}
}
// We traversed the fork length allowed without finding a common ancestor.
return true, nil
}
// ForceHeadSilent forces a chain head tipset without triggering a reorg
// operation.
//
// CAUTION: Use it only for testing, such as to teleport the chain to a
// particular tipset to carry out a benchmark, verification, etc. on a chain
// segment.
func (cs *ChainStore) ForceHeadSilent(_ context.Context, ts *types.TipSet) error {
log.Warnf("(!!!) forcing a new head silently; new head: %s", ts)
cs.heaviestLk.Lock()
defer cs.heaviestLk.Unlock()
if err := cs.removeCheckpoint(); err != nil {
return err
}
cs.heaviest = ts
err := cs.writeHead(ts)
if err != nil {
err = xerrors.Errorf("failed to write chain head: %s", err)
}
return err
}
type reorg struct {
old *types.TipSet
new *types.TipSet
}
const reorgChBuf = 32
func (cs *ChainStore) reorgWorker(ctx context.Context, initialNotifees []ReorgNotifee) chan<- reorg {
out := make(chan reorg, reorgChBuf)
notifees := make([]ReorgNotifee, len(initialNotifees))
copy(notifees, initialNotifees)
cs.wg.Add(1)
go func() {
defer cs.wg.Done()
defer log.Warn("reorgWorker quit")
for {
select {
case n := <-cs.reorgNotifeeCh:
notifees = append(notifees, n)
case r := <-out:
revert, apply, err := cs.ReorgOps(r.old, r.new)
if err != nil {
log.Error("computing reorg ops failed: ", err)
continue
}
cs.journal.RecordEvent(cs.evtTypes[evtTypeHeadChange], func() interface{} {
return HeadChangeEvt{
From: r.old.Key(),
FromHeight: r.old.Height(),
To: r.new.Key(),
ToHeight: r.new.Height(),
RevertCount: len(revert),
ApplyCount: len(apply),
}
})
// reverse the apply array
for i := len(apply)/2 - 1; i >= 0; i-- {
opp := len(apply) - 1 - i
apply[i], apply[opp] = apply[opp], apply[i]
}
var toremove map[int]struct{}
for i, hcf := range notifees {
err := hcf(revert, apply)
switch err {
case nil:
case ErrNotifeeDone:
if toremove == nil {
toremove = make(map[int]struct{})
}
toremove[i] = struct{}{}
default:
log.Error("head change func errored (BAD): ", err)
}
}
if len(toremove) > 0 {
newNotifees := make([]ReorgNotifee, 0, len(notifees)-len(toremove))
for i, hcf := range notifees {
_, remove := toremove[i]
if remove {
continue
}
newNotifees = append(newNotifees, hcf)
}
notifees = newNotifees
}
case <-ctx.Done():
return
}
}
}()
return out
}
// takeHeaviestTipSet actually sets the incoming tipset as our head both in
// memory and in the ChainStore. It also sends a notification to deliver to
// ReorgNotifees.
func (cs *ChainStore) takeHeaviestTipSet(ctx context.Context, ts *types.TipSet) error {
_, span := trace.StartSpan(ctx, "takeHeaviestTipSet")
defer span.End()
if cs.heaviest != nil { // buf
if len(cs.reorgCh) > 0 {
log.Warnf("Reorg channel running behind, %d reorgs buffered", len(cs.reorgCh))
}
cs.reorgCh <- reorg{
old: cs.heaviest,
new: ts,
}
} else {
log.Warnf("no heaviest tipset found, using %s", ts.Cids())
}
span.AddAttributes(trace.BoolAttribute("newHead", true))
log.Infof("New heaviest tipset! %s (height=%d)", ts.Cids(), ts.Height())
cs.heaviest = ts
if err := cs.writeHead(ts); err != nil {
log.Errorf("failed to write chain head: %s", err)
return nil
}
return nil
}
// FlushValidationCache removes all results of block validation from the
// chain metadata store. Usually the first step after a new chain import.
func (cs *ChainStore) FlushValidationCache() error {
return FlushValidationCache(cs.metadataDs)
}
func FlushValidationCache(ds dstore.Batching) error {
log.Infof("clearing block validation cache...")
dsWalk, err := ds.Query(query.Query{
// Potential TODO: the validation cache is not a namespace on its own
// but is rather constructed as prefixed-key `foo:bar` via .Instance(), which
// in turn does not work with the filter, which can match only on `foo/bar`
//
// If this is addressed (blockcache goes into its own sub-namespace) then
// strings.HasPrefix(...) below can be skipped
//
//Prefix: blockValidationCacheKeyPrefix.String()
KeysOnly: true,
})
if err != nil {
return xerrors.Errorf("failed to initialize key listing query: %w", err)
}
allKeys, err := dsWalk.Rest()
if err != nil {
return xerrors.Errorf("failed to run key listing query: %w", err)
}
batch, err := ds.Batch()
if err != nil {
return xerrors.Errorf("failed to open a DS batch: %w", err)
}
delCnt := 0
for _, k := range allKeys {
if strings.HasPrefix(k.Key, blockValidationCacheKeyPrefix.String()) {
delCnt++
batch.Delete(dstore.RawKey(k.Key)) // nolint:errcheck
}
}
if err := batch.Commit(); err != nil {
return xerrors.Errorf("failed to commit the DS batch: %w", err)
}
log.Infof("%d block validation entries cleared.", delCnt)
return nil
}
// SetHead sets the chainstores current 'best' head node.
// This should only be called if something is broken and needs fixing.
//
// This function will bypass and remove any checkpoints.
func (cs *ChainStore) SetHead(ts *types.TipSet) error {
cs.heaviestLk.Lock()
defer cs.heaviestLk.Unlock()
if err := cs.removeCheckpoint(); err != nil {
return err
}
return cs.takeHeaviestTipSet(context.TODO(), ts)
}
// RemoveCheckpoint removes the current checkpoint.
func (cs *ChainStore) RemoveCheckpoint() error {
cs.heaviestLk.Lock()
defer cs.heaviestLk.Unlock()
return cs.removeCheckpoint()
}
func (cs *ChainStore) removeCheckpoint() error {
if err := cs.metadataDs.Delete(checkpointKey); err != nil {
return err
}
cs.checkpoint = nil
return nil
}
// SetCheckpoint will set a checkpoint past which the chainstore will not allow forks.
//
// NOTE: Checkpoints cannot be set beyond ForkLengthThreshold epochs in the past.
func (cs *ChainStore) SetCheckpoint(ts *types.TipSet) error {
tskBytes, err := json.Marshal(ts.Key())
if err != nil {
return err
}
cs.heaviestLk.Lock()
defer cs.heaviestLk.Unlock()
if ts.Height() > cs.heaviest.Height() {
return xerrors.Errorf("cannot set a checkpoint in the future")
}
// Otherwise, this operation could get _very_ expensive.
if cs.heaviest.Height()-ts.Height() > build.ForkLengthThreshold {
return xerrors.Errorf("cannot set a checkpoint before the fork threshold")
}
if !ts.Equals(cs.heaviest) {
anc, err := cs.IsAncestorOf(ts, cs.heaviest)
if err != nil {
return xerrors.Errorf("cannot determine whether checkpoint tipset is in main-chain: %w", err)
}
if !anc {
return xerrors.Errorf("cannot mark tipset as checkpoint, since it isn't in the main-chain: %w", err)
}
}
err = cs.metadataDs.Put(checkpointKey, tskBytes)
if err != nil {
return err
}
cs.checkpoint = ts
return nil
}
func (cs *ChainStore) GetCheckpoint() *types.TipSet {
cs.heaviestLk.RLock()
chkpt := cs.checkpoint
cs.heaviestLk.RUnlock()
return chkpt
}
// Contains returns whether our BlockStore has all blocks in the supplied TipSet.
func (cs *ChainStore) Contains(ts *types.TipSet) (bool, error) {
for _, c := range ts.Cids() {
has, err := cs.chainBlockstore.Has(c)
if err != nil {
return false, err
}
if !has {
return false, nil
}
}
return true, nil
}
// GetBlock fetches a BlockHeader with the supplied CID. It returns
// blockstore.ErrNotFound if the block was not found in the BlockStore.
func (cs *ChainStore) GetBlock(c cid.Cid) (*types.BlockHeader, error) {
var blk *types.BlockHeader
err := cs.chainLocalBlockstore.View(c, func(b []byte) (err error) {
blk, err = types.DecodeBlock(b)
return err
})
return blk, err
}
func (cs *ChainStore) LoadTipSet(tsk types.TipSetKey) (*types.TipSet, error) {
v, ok := cs.tsCache.Get(tsk)
if ok {
return v.(*types.TipSet), nil
}
// Fetch tipset block headers from blockstore in parallel
var eg errgroup.Group
cids := tsk.Cids()
blks := make([]*types.BlockHeader, len(cids))
for i, c := range cids {
i, c := i, c
eg.Go(func() error {
b, err := cs.GetBlock(c)
if err != nil {
return xerrors.Errorf("get block %s: %w", c, err)
}
blks[i] = b
return nil
})
}
err := eg.Wait()
if err != nil {
return nil, err
}
ts, err := types.NewTipSet(blks)
if err != nil {
return nil, err
}
cs.tsCache.Add(tsk, ts)
return ts, nil
}
// IsAncestorOf returns true if 'a' is an ancestor of 'b'
func (cs *ChainStore) IsAncestorOf(a, b *types.TipSet) (bool, error) {
if b.Height() <= a.Height() {
return false, nil
}
cur := b
for !a.Equals(cur) && cur.Height() > a.Height() {
next, err := cs.LoadTipSet(cur.Parents())
if err != nil {
return false, err
}
cur = next
}
return cur.Equals(a), nil
}
func (cs *ChainStore) NearestCommonAncestor(a, b *types.TipSet) (*types.TipSet, error) {
l, _, err := cs.ReorgOps(a, b)
if err != nil {
return nil, err
}
return cs.LoadTipSet(l[len(l)-1].Parents())
}
// ReorgOps takes two tipsets (which can be at different heights), and walks
// their corresponding chains backwards one step at a time until we find
// a common ancestor. It then returns the respective chain segments that fork
// from the identified ancestor, in reverse order, where the first element of
// each slice is the supplied tipset, and the last element is the common
// ancestor.
//
// If an error happens along the way, we return the error with nil slices.
func (cs *ChainStore) ReorgOps(a, b *types.TipSet) ([]*types.TipSet, []*types.TipSet, error) {
return ReorgOps(cs.LoadTipSet, a, b)
}
func ReorgOps(lts func(types.TipSetKey) (*types.TipSet, error), a, b *types.TipSet) ([]*types.TipSet, []*types.TipSet, error) {
left := a
right := b
var leftChain, rightChain []*types.TipSet
for !left.Equals(right) {
if left.Height() > right.Height() {
leftChain = append(leftChain, left)
par, err := lts(left.Parents())
if err != nil {
return nil, nil, err
}
left = par
} else {
rightChain = append(rightChain, right)
par, err := lts(right.Parents())
if err != nil {
log.Infof("failed to fetch right.Parents: %s", err)
return nil, nil, err
}
right = par
}
}
return leftChain, rightChain, nil
}
// GetHeaviestTipSet returns the current heaviest tipset known (i.e. our head).
func (cs *ChainStore) GetHeaviestTipSet() (ts *types.TipSet) {
cs.heaviestLk.RLock()
ts = cs.heaviest
cs.heaviestLk.RUnlock()
return
}
func (cs *ChainStore) AddToTipSetTracker(b *types.BlockHeader) error {
cs.tstLk.Lock()
defer cs.tstLk.Unlock()
tss := cs.tipsets[b.Height]
for _, oc := range tss {
if oc == b.Cid() {
log.Debug("tried to add block to tipset tracker that was already there")
return nil
}
h, err := cs.GetBlock(oc)
if err == nil && h != nil {
if h.Miner == b.Miner {
log.Warnf("Have multiple blocks from miner %s at height %d in our tipset cache %s-%s", b.Miner, b.Height, b.Cid(), h.Cid())
}
}
}
// This function is called 5 times per epoch on average
// It is also called with tipsets that are done with initial validation
// so they cannot be from the future.
// We are guaranteed not to use tipsets older than 900 epochs (fork limit)
// This means that we ideally want to keep only most recent 900 epochs in here
// Golang's map iteration starts at a random point in a map.
// With 5 tries per epoch, and 900 entries to keep, on average we will have
// ~136 garbage entires in the `cs.tipsets` map. (solve for 1-(1-x/(900+x))^5 == 0.5)
// Seems good enough to me
for height := range cs.tipsets {
if height < b.Height-build.Finality {
delete(cs.tipsets, height)
}
break
}
cs.tipsets[b.Height] = append(tss, b.Cid())
return nil
}
func (cs *ChainStore) PersistBlockHeaders(b ...*types.BlockHeader) error {
sbs := make([]block.Block, len(b))
for i, header := range b {
var err error
sbs[i], err = header.ToStorageBlock()
if err != nil {
return err
}
}
batchSize := 256
calls := len(b) / batchSize
var err error
for i := 0; i <= calls; i++ {
start := batchSize * i
end := start + batchSize
if end > len(b) {
end = len(b)
}
err = multierr.Append(err, cs.chainLocalBlockstore.PutMany(sbs[start:end]))
}
return err
}
func (cs *ChainStore) expandTipset(b *types.BlockHeader) (*types.TipSet, error) {
// Hold lock for the whole function for now, if it becomes a problem we can
// fix pretty easily
cs.tstLk.Lock()
defer cs.tstLk.Unlock()
all := []*types.BlockHeader{b}
tsets, ok := cs.tipsets[b.Height]
if !ok {
return types.NewTipSet(all)
}
inclMiners := map[address.Address]cid.Cid{b.Miner: b.Cid()}
for _, bhc := range tsets {
if bhc == b.Cid() {
continue
}
h, err := cs.GetBlock(bhc)
if err != nil {
return nil, xerrors.Errorf("failed to load block (%s) for tipset expansion: %w", bhc, err)
}
if cid, found := inclMiners[h.Miner]; found {
log.Warnf("Have multiple blocks from miner %s at height %d in our tipset cache %s-%s", h.Miner, h.Height, h.Cid(), cid)
continue
}
if types.CidArrsEqual(h.Parents, b.Parents) {
all = append(all, h)
inclMiners[h.Miner] = bhc
}
}
// TODO: other validation...?
return types.NewTipSet(all)
}
func (cs *ChainStore) AddBlock(ctx context.Context, b *types.BlockHeader) error {
if err := cs.PersistBlockHeaders(b); err != nil {
return err
}
ts, err := cs.expandTipset(b)
if err != nil {
return err
}
if err := cs.MaybeTakeHeavierTipSet(ctx, ts); err != nil {
return xerrors.Errorf("MaybeTakeHeavierTipSet failed: %w", err)
}
return nil
}
func (cs *ChainStore) GetGenesis() (*types.BlockHeader, error) {
data, err := cs.metadataDs.Get(dstore.NewKey("0"))
if err != nil {
return nil, err
}
c, err := cid.Cast(data)
if err != nil {
return nil, err
}
return cs.GetBlock(c)
}
// GetPath returns the sequence of atomic head change operations that
// need to be applied in order to switch the head of the chain from the `from`
// tipset to the `to` tipset.
func (cs *ChainStore) GetPath(ctx context.Context, from types.TipSetKey, to types.TipSetKey) ([]*api.HeadChange, error) {
fts, err := cs.LoadTipSet(from)
if err != nil {
return nil, xerrors.Errorf("loading from tipset %s: %w", from, err)
}
tts, err := cs.LoadTipSet(to)
if err != nil {
return nil, xerrors.Errorf("loading to tipset %s: %w", to, err)
}
revert, apply, err := cs.ReorgOps(fts, tts)
if err != nil {
return nil, xerrors.Errorf("error getting tipset branches: %w", err)
}
path := make([]*api.HeadChange, len(revert)+len(apply))
for i, r := range revert {
path[i] = &api.HeadChange{Type: HCRevert, Val: r}
}
for j, i := 0, len(apply)-1; i >= 0; j, i = j+1, i-1 {
path[j+len(revert)] = &api.HeadChange{Type: HCApply, Val: apply[i]}
}
return path, nil
}
// ChainBlockstore returns the chain blockstore. Currently the chain and state
// // stores are both backed by the same physical store, albeit with different
// // caching policies, but in the future they will segregate.
func (cs *ChainStore) ChainBlockstore() bstore.Blockstore {
return cs.chainBlockstore
}
// StateBlockstore returns the state blockstore. Currently the chain and state
// stores are both backed by the same physical store, albeit with different
// caching policies, but in the future they will segregate.
func (cs *ChainStore) StateBlockstore() bstore.Blockstore {
return cs.stateBlockstore
}
func ActorStore(ctx context.Context, bs bstore.Blockstore) adt.Store {
return adt.WrapStore(ctx, cbor.NewCborStore(bs))
}
func (cs *ChainStore) ActorStore(ctx context.Context) adt.Store {
return ActorStore(ctx, cs.stateBlockstore)
}
func (cs *ChainStore) TryFillTipSet(ts *types.TipSet) (*FullTipSet, error) {
var out []*types.FullBlock
for _, b := range ts.Blocks() {
bmsgs, smsgs, err := cs.MessagesForBlock(b)
if err != nil {
// TODO: check for 'not found' errors, and only return nil if this
// is actually a 'not found' error
return nil, nil
}
fb := &types.FullBlock{
Header: b,
BlsMessages: bmsgs,
SecpkMessages: smsgs,
}
out = append(out, fb)
}
return NewFullTipSet(out), nil
}
// GetTipsetByHeight returns the tipset on the chain behind 'ts' at the given
// height. In the case that the given height is a null round, the 'prev' flag
// selects the tipset before the null round if true, and the tipset following
// the null round if false.
func (cs *ChainStore) GetTipsetByHeight(ctx context.Context, h abi.ChainEpoch, ts *types.TipSet, prev bool) (*types.TipSet, error) {
if ts == nil {
ts = cs.GetHeaviestTipSet()
}
if h > ts.Height() {
return nil, xerrors.Errorf("looking for tipset with height greater than start point")
}
if h == ts.Height() {
return ts, nil
}
lbts, err := cs.cindex.GetTipsetByHeight(ctx, ts, h)
if err != nil {
return nil, err
}
if lbts.Height() < h {
log.Warnf("chain index returned the wrong tipset at height %d, using slow retrieval", h)
lbts, err = cs.cindex.GetTipsetByHeightWithoutCache(ts, h)
if err != nil {
return nil, err
}
}
if lbts.Height() == h || !prev {
return lbts, nil
}
return cs.LoadTipSet(lbts.Parents())
}
| [
"\"LOTUS_CHAIN_TIPSET_CACHE\"",
"\"LOTUS_CHAIN_MSGMETA_CACHE\""
]
| []
| [
"LOTUS_CHAIN_TIPSET_CACHE",
"LOTUS_CHAIN_MSGMETA_CACHE"
]
| [] | ["LOTUS_CHAIN_TIPSET_CACHE", "LOTUS_CHAIN_MSGMETA_CACHE"] | go | 2 | 0 | |
server.go | package docker
import (
"fmt"
"github.com/dotcloud/docker/auth"
"github.com/dotcloud/docker/registry"
"github.com/dotcloud/docker/utils"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path"
"runtime"
"strings"
)
func (srv *Server) DockerVersion() ApiVersion {
return ApiVersion{
Version: VERSION,
GitCommit: GIT_COMMIT,
GoVersion: runtime.Version(),
}
}
func (srv *Server) ContainerKill(name string) error {
if container := srv.runtime.Get(name); container != nil {
if err := container.Kill(); err != nil {
return fmt.Errorf("Error restarting container %s: %s", name, err.Error())
}
} else {
return fmt.Errorf("No such container: %s", name)
}
return nil
}
func (srv *Server) ContainerExport(name string, out io.Writer) error {
if container := srv.runtime.Get(name); container != nil {
data, err := container.Export()
if err != nil {
return err
}
// Stream the entire contents of the container (basically a volatile snapshot)
if _, err := io.Copy(out, data); err != nil {
return err
}
return nil
}
return fmt.Errorf("No such container: %s", name)
}
func (srv *Server) ImagesSearch(term string) ([]ApiSearch, error) {
results, err := registry.NewRegistry(srv.runtime.root).SearchRepositories(term)
if err != nil {
return nil, err
}
var outs []ApiSearch
for _, repo := range results.Results {
var out ApiSearch
out.Description = repo["description"]
if len(out.Description) > 45 {
out.Description = utils.Trunc(out.Description, 42) + "..."
}
out.Name = repo["name"]
outs = append(outs, out)
}
return outs, nil
}
func (srv *Server) ImageInsert(name, url, path string, out io.Writer, sf *utils.StreamFormatter) (string, error) {
out = utils.NewWriteFlusher(out)
img, err := srv.runtime.repositories.LookupImage(name)
if err != nil {
return "", err
}
file, err := utils.Download(url, out)
if err != nil {
return "", err
}
defer file.Body.Close()
config, _, err := ParseRun([]string{img.Id, "echo", "insert", url, path}, srv.runtime.capabilities)
if err != nil {
return "", err
}
b := NewBuilder(srv.runtime)
c, err := b.Create(config)
if err != nil {
return "", err
}
if err := c.Inject(utils.ProgressReader(file.Body, int(file.ContentLength), out, sf.FormatProgress("Downloading", "%v/%v (%v)"), sf), path); err != nil {
return "", err
}
// FIXME: Handle custom repo, tag comment, author
img, err = b.Commit(c, "", "", img.Comment, img.Author, nil)
if err != nil {
return "", err
}
out.Write(sf.FormatStatus(img.Id))
return img.ShortId(), nil
}
func (srv *Server) ImagesViz(out io.Writer) error {
images, _ := srv.runtime.graph.All()
if images == nil {
return nil
}
out.Write([]byte("digraph docker {\n"))
var (
parentImage *Image
err error
)
for _, image := range images {
parentImage, err = image.GetParent()
if err != nil {
return fmt.Errorf("Error while getting parent image: %v", err)
}
if parentImage != nil {
out.Write([]byte(" \"" + parentImage.ShortId() + "\" -> \"" + image.ShortId() + "\"\n"))
} else {
out.Write([]byte(" base -> \"" + image.ShortId() + "\" [style=invis]\n"))
}
}
reporefs := make(map[string][]string)
for name, repository := range srv.runtime.repositories.Repositories {
for tag, id := range repository {
reporefs[utils.TruncateId(id)] = append(reporefs[utils.TruncateId(id)], fmt.Sprintf("%s:%s", name, tag))
}
}
for id, repos := range reporefs {
out.Write([]byte(" \"" + id + "\" [label=\"" + id + "\\n" + strings.Join(repos, "\\n") + "\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n"))
}
out.Write([]byte(" base [style=invisible]\n}\n"))
return nil
}
func (srv *Server) Images(all bool, filter string) ([]ApiImages, error) {
var (
allImages map[string]*Image
err error
)
if all {
allImages, err = srv.runtime.graph.Map()
} else {
allImages, err = srv.runtime.graph.Heads()
}
if err != nil {
return nil, err
}
outs := []ApiImages{} //produce [] when empty instead of 'null'
for name, repository := range srv.runtime.repositories.Repositories {
if filter != "" && name != filter {
continue
}
for tag, id := range repository {
var out ApiImages
image, err := srv.runtime.graph.Get(id)
if err != nil {
log.Printf("Warning: couldn't load %s from %s/%s: %s", id, name, tag, err)
continue
}
delete(allImages, id)
out.Repository = name
out.Tag = tag
out.Id = image.Id
out.Created = image.Created.Unix()
outs = append(outs, out)
}
}
// Display images which aren't part of a
if filter == "" {
for _, image := range allImages {
var out ApiImages
out.Id = image.Id
out.Created = image.Created.Unix()
outs = append(outs, out)
}
}
return outs, nil
}
func (srv *Server) DockerInfo() *ApiInfo {
images, _ := srv.runtime.graph.All()
var imgcount int
if images == nil {
imgcount = 0
} else {
imgcount = len(images)
}
return &ApiInfo{
Containers: len(srv.runtime.List()),
Images: imgcount,
MemoryLimit: srv.runtime.capabilities.MemoryLimit,
SwapLimit: srv.runtime.capabilities.SwapLimit,
Debug: os.Getenv("DEBUG") != "",
NFd: utils.GetTotalUsedFds(),
NGoroutines: runtime.NumGoroutine(),
}
}
func (srv *Server) ImageHistory(name string) ([]ApiHistory, error) {
image, err := srv.runtime.repositories.LookupImage(name)
if err != nil {
return nil, err
}
var outs []ApiHistory = []ApiHistory{} //produce [] when empty instead of 'null'
err = image.WalkHistory(func(img *Image) error {
var out ApiHistory
out.Id = srv.runtime.repositories.ImageName(img.ShortId())
out.Created = img.Created.Unix()
out.CreatedBy = strings.Join(img.ContainerConfig.Cmd, " ")
outs = append(outs, out)
return nil
})
return outs, nil
}
func (srv *Server) ContainerChanges(name string) ([]Change, error) {
if container := srv.runtime.Get(name); container != nil {
return container.Changes()
}
return nil, fmt.Errorf("No such container: %s", name)
}
func (srv *Server) Containers(all bool, n int, since, before string) []ApiContainers {
var foundBefore bool
var displayed int
retContainers := []ApiContainers{}
for _, container := range srv.runtime.List() {
if !container.State.Running && !all && n == -1 && since == "" && before == "" {
continue
}
if before != "" {
if container.ShortId() == before {
foundBefore = true
continue
}
if !foundBefore {
continue
}
}
if displayed == n {
break
}
if container.ShortId() == since {
break
}
displayed++
c := ApiContainers{
Id: container.Id,
}
c.Image = srv.runtime.repositories.ImageName(container.Image)
c.Command = fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " "))
c.Created = container.Created.Unix()
c.Status = container.State.String()
c.Ports = container.NetworkSettings.PortMappingHuman()
retContainers = append(retContainers, c)
}
return retContainers
}
func (srv *Server) ContainerCommit(name, repo, tag, author, comment string, config *Config) (string, error) {
container := srv.runtime.Get(name)
if container == nil {
return "", fmt.Errorf("No such container: %s", name)
}
img, err := NewBuilder(srv.runtime).Commit(container, repo, tag, comment, author, config)
if err != nil {
return "", err
}
return img.ShortId(), err
}
func (srv *Server) ContainerTag(name, repo, tag string, force bool) error {
if err := srv.runtime.repositories.Set(repo, tag, name, force); err != nil {
return err
}
return nil
}
func (srv *Server) pullImage(r *registry.Registry, out io.Writer, imgId, endpoint string, token []string, sf *utils.StreamFormatter) error {
history, err := r.GetRemoteHistory(imgId, endpoint, token)
if err != nil {
return err
}
// FIXME: Try to stream the images?
// FIXME: Launch the getRemoteImage() in goroutines
for _, id := range history {
if !srv.runtime.graph.Exists(id) {
out.Write(sf.FormatStatus("Pulling %s metadata", id))
imgJson, err := r.GetRemoteImageJson(id, endpoint, token)
if err != nil {
// FIXME: Keep goging in case of error?
return err
}
img, err := NewImgJson(imgJson)
if err != nil {
return fmt.Errorf("Failed to parse json: %s", err)
}
// Get the layer
out.Write(sf.FormatStatus("Pulling %s fs layer", id))
layer, contentLength, err := r.GetRemoteImageLayer(img.Id, endpoint, token)
if err != nil {
return err
}
defer layer.Close()
if err := srv.runtime.graph.Register(utils.ProgressReader(layer, contentLength, out, sf.FormatProgress("Downloading", "%v/%v (%v)"), sf), false, img); err != nil {
return err
}
}
}
return nil
}
func (srv *Server) pullRepository(r *registry.Registry, out io.Writer, remote, askedTag string, sf *utils.StreamFormatter) error {
out.Write(sf.FormatStatus("Pulling repository %s from %s", remote, auth.IndexServerAddress()))
repoData, err := r.GetRepositoryData(remote)
if err != nil {
return err
}
utils.Debugf("Updating checksums")
// Reload the json file to make sure not to overwrite faster sums
if err := srv.runtime.graph.UpdateChecksums(repoData.ImgList); err != nil {
return err
}
utils.Debugf("Retrieving the tag list")
tagsList, err := r.GetRemoteTags(repoData.Endpoints, remote, repoData.Tokens)
if err != nil {
return err
}
utils.Debugf("Registering tags")
// If not specific tag have been asked, take all
if askedTag == "" {
for tag, id := range tagsList {
repoData.ImgList[id].Tag = tag
}
} else {
// Otherwise, check that the tag exists and use only that one
if id, exists := tagsList[askedTag]; !exists {
return fmt.Errorf("Tag %s not found in repositoy %s", askedTag, remote)
} else {
repoData.ImgList[id].Tag = askedTag
}
}
for _, img := range repoData.ImgList {
if askedTag != "" && img.Tag != askedTag {
utils.Debugf("(%s) does not match %s (id: %s), skipping", img.Tag, askedTag, img.Id)
continue
}
out.Write(sf.FormatStatus("Pulling image %s (%s) from %s", img.Id, img.Tag, remote))
success := false
for _, ep := range repoData.Endpoints {
if err := srv.pullImage(r, out, img.Id, "https://"+ep+"/v1", repoData.Tokens, sf); err != nil {
out.Write(sf.FormatStatus("Error while retrieving image for tag: %s (%s); checking next endpoint", askedTag, err))
continue
}
success = true
break
}
if !success {
return fmt.Errorf("Could not find repository on any of the indexed registries.")
}
}
for tag, id := range tagsList {
if askedTag != "" && tag != askedTag {
continue
}
if err := srv.runtime.repositories.Set(remote, tag, id, true); err != nil {
return err
}
}
if err := srv.runtime.repositories.Save(); err != nil {
return err
}
return nil
}
func (srv *Server) ImagePull(name, tag, endpoint string, out io.Writer, sf *utils.StreamFormatter) error {
r := registry.NewRegistry(srv.runtime.root)
out = utils.NewWriteFlusher(out)
if endpoint != "" {
if err := srv.pullImage(r, out, name, endpoint, nil, sf); err != nil {
return err
}
return nil
}
if err := srv.pullRepository(r, out, name, tag, sf); err != nil {
return err
}
return nil
}
// Retrieve the checksum of an image
// Priority:
// - Check on the stored checksums
// - Check if the archive exists, if it does not, ask the registry
// - If the archive does exists, process the checksum from it
// - If the archive does not exists and not found on registry, process checksum from layer
func (srv *Server) getChecksum(imageId string) (string, error) {
// FIXME: Use in-memory map instead of reading the file each time
if sums, err := srv.runtime.graph.getStoredChecksums(); err != nil {
return "", err
} else if checksum, exists := sums[imageId]; exists {
return checksum, nil
}
img, err := srv.runtime.graph.Get(imageId)
if err != nil {
return "", err
}
if _, err := os.Stat(layerArchivePath(srv.runtime.graph.imageRoot(imageId))); err != nil {
if os.IsNotExist(err) {
// TODO: Ask the registry for the checksum
// As the archive is not there, it is supposed to come from a pull.
} else {
return "", err
}
}
checksum, err := img.Checksum()
if err != nil {
return "", err
}
return checksum, nil
}
// Retrieve the all the images to be uploaded in the correct order
// Note: we can't use a map as it is not ordered
func (srv *Server) getImageList(localRepo map[string]string) ([]*registry.ImgData, error) {
var imgList []*registry.ImgData
imageSet := make(map[string]struct{})
for tag, id := range localRepo {
img, err := srv.runtime.graph.Get(id)
if err != nil {
return nil, err
}
img.WalkHistory(func(img *Image) error {
if _, exists := imageSet[img.Id]; exists {
return nil
}
imageSet[img.Id] = struct{}{}
checksum, err := srv.getChecksum(img.Id)
if err != nil {
return err
}
imgList = append([]*registry.ImgData{{
Id: img.Id,
Checksum: checksum,
Tag: tag,
}}, imgList...)
return nil
})
}
return imgList, nil
}
func (srv *Server) pushRepository(r *registry.Registry, out io.Writer, name string, localRepo map[string]string, sf *utils.StreamFormatter) error {
out = utils.NewWriteFlusher(out)
out.Write(sf.FormatStatus("Processing checksums"))
imgList, err := srv.getImageList(localRepo)
if err != nil {
return err
}
out.Write(sf.FormatStatus("Sending image list"))
repoData, err := r.PushImageJsonIndex(name, imgList, false)
if err != nil {
return err
}
for _, ep := range repoData.Endpoints {
out.Write(sf.FormatStatus("Pushing repository %s to %s (%d tags)", name, ep, len(localRepo)))
// For each image within the repo, push them
for _, elem := range imgList {
if _, exists := repoData.ImgList[elem.Id]; exists {
out.Write(sf.FormatStatus("Image %s already on registry, skipping", name))
continue
}
if err := srv.pushImage(r, out, name, elem.Id, ep, repoData.Tokens, sf); err != nil {
// FIXME: Continue on error?
return err
}
out.Write(sf.FormatStatus("Pushing tags for rev [%s] on {%s}", elem.Id, ep+"/users/"+name+"/"+elem.Tag))
if err := r.PushRegistryTag(name, elem.Id, elem.Tag, ep, repoData.Tokens); err != nil {
return err
}
}
}
if _, err := r.PushImageJsonIndex(name, imgList, true); err != nil {
return err
}
return nil
}
func (srv *Server) pushImage(r *registry.Registry, out io.Writer, remote, imgId, ep string, token []string, sf *utils.StreamFormatter) error {
out = utils.NewWriteFlusher(out)
jsonRaw, err := ioutil.ReadFile(path.Join(srv.runtime.graph.Root, imgId, "json"))
if err != nil {
return fmt.Errorf("Error while retreiving the path for {%s}: %s", imgId, err)
}
out.Write(sf.FormatStatus("Pushing %s", imgId))
// Make sure we have the image's checksum
checksum, err := srv.getChecksum(imgId)
if err != nil {
return err
}
imgData := ®istry.ImgData{
Id: imgId,
Checksum: checksum,
}
// Send the json
if err := r.PushImageJsonRegistry(imgData, jsonRaw, ep, token); err != nil {
if err == registry.ErrAlreadyExists {
out.Write(sf.FormatStatus("Image %s already uploaded ; skipping", imgData.Id))
return nil
}
return err
}
// Retrieve the tarball to be sent
var layerData *TempArchive
// If the archive exists, use it
file, err := os.Open(layerArchivePath(srv.runtime.graph.imageRoot(imgId)))
if err != nil {
if os.IsNotExist(err) {
// If the archive does not exist, create one from the layer
layerData, err = srv.runtime.graph.TempLayerArchive(imgId, Xz, out)
if err != nil {
return fmt.Errorf("Failed to generate layer archive: %s", err)
}
} else {
return err
}
} else {
defer file.Close()
st, err := file.Stat()
if err != nil {
return err
}
layerData = &TempArchive{
File: file,
Size: st.Size(),
}
}
// Send the layer
if err := r.PushImageLayerRegistry(imgData.Id, utils.ProgressReader(layerData, int(layerData.Size), out, sf.FormatProgress("", "%v/%v (%v)"), sf), ep, token); err != nil {
return err
}
return nil
}
func (srv *Server) ImagePush(name, endpoint string, out io.Writer, sf *utils.StreamFormatter) error {
out = utils.NewWriteFlusher(out)
img, err := srv.runtime.graph.Get(name)
r := registry.NewRegistry(srv.runtime.root)
if err != nil {
out.Write(sf.FormatStatus("The push refers to a repository [%s] (len: %d)", name, len(srv.runtime.repositories.Repositories[name])))
// If it fails, try to get the repository
if localRepo, exists := srv.runtime.repositories.Repositories[name]; exists {
if err := srv.pushRepository(r, out, name, localRepo, sf); err != nil {
return err
}
return nil
}
return err
}
out.Write(sf.FormatStatus("The push refers to an image: [%s]", name))
if err := srv.pushImage(r, out, name, img.Id, endpoint, nil, sf); err != nil {
return err
}
return nil
}
func (srv *Server) ImageImport(src, repo, tag string, in io.Reader, out io.Writer, sf *utils.StreamFormatter) error {
var archive io.Reader
var resp *http.Response
if src == "-" {
archive = in
} else {
u, err := url.Parse(src)
if err != nil {
return err
}
if u.Scheme == "" {
u.Scheme = "http"
u.Host = src
u.Path = ""
}
out.Write(sf.FormatStatus("Downloading from %s", u))
// Download with curl (pretty progress bar)
// If curl is not available, fallback to http.Get()
resp, err = utils.Download(u.String(), out)
if err != nil {
return err
}
archive = utils.ProgressReader(resp.Body, int(resp.ContentLength), out, sf.FormatProgress("Importing", "%v/%v (%v)"), sf)
}
img, err := srv.runtime.graph.Create(archive, nil, "Imported from "+src, "", nil)
if err != nil {
return err
}
// Optionally register the image at REPO/TAG
if repo != "" {
if err := srv.runtime.repositories.Set(repo, tag, img.Id, true); err != nil {
return err
}
}
out.Write(sf.FormatStatus(img.ShortId()))
return nil
}
func (srv *Server) ContainerCreate(config *Config) (string, error) {
if config.Memory > 0 && !srv.runtime.capabilities.MemoryLimit {
config.Memory = 0
}
if config.Memory > 0 && !srv.runtime.capabilities.SwapLimit {
config.MemorySwap = -1
}
b := NewBuilder(srv.runtime)
container, err := b.Create(config)
if err != nil {
if srv.runtime.graph.IsNotExist(err) {
return "", fmt.Errorf("No such image: %s", config.Image)
}
return "", err
}
return container.ShortId(), nil
}
func (srv *Server) ContainerRestart(name string, t int) error {
if container := srv.runtime.Get(name); container != nil {
if err := container.Restart(t); err != nil {
return fmt.Errorf("Error restarting container %s: %s", name, err.Error())
}
} else {
return fmt.Errorf("No such container: %s", name)
}
return nil
}
func (srv *Server) ContainerDestroy(name string, removeVolume bool) error {
if container := srv.runtime.Get(name); container != nil {
volumes := make(map[string]struct{})
// Store all the deleted containers volumes
for _, volumeId := range container.Volumes {
volumes[volumeId] = struct{}{}
}
if err := srv.runtime.Destroy(container); err != nil {
return fmt.Errorf("Error destroying container %s: %s", name, err.Error())
}
if removeVolume {
// Retrieve all volumes from all remaining containers
usedVolumes := make(map[string]*Container)
for _, container := range srv.runtime.List() {
for _, containerVolumeId := range container.Volumes {
usedVolumes[containerVolumeId] = container
}
}
for volumeId := range volumes {
// If the requested volu
if c, exists := usedVolumes[volumeId]; exists {
log.Printf("The volume %s is used by the container %s. Impossible to remove it. Skipping.\n", volumeId, c.Id)
continue
}
if err := srv.runtime.volumes.Delete(volumeId); err != nil {
return err
}
}
}
} else {
return fmt.Errorf("No such container: %s", name)
}
return nil
}
func (srv *Server) ImageDelete(name string) error {
img, err := srv.runtime.repositories.LookupImage(name)
if err != nil {
return fmt.Errorf("No such image: %s", name)
} else {
if err := srv.runtime.graph.Delete(img.Id); err != nil {
return fmt.Errorf("Error deleting image %s: %s", name, err.Error())
}
}
return nil
}
func (srv *Server) ImageGetCached(imgId string, config *Config) (*Image, error) {
// Retrieve all images
images, err := srv.runtime.graph.All()
if err != nil {
return nil, err
}
// Store the tree in a map of map (map[parentId][childId])
imageMap := make(map[string]map[string]struct{})
for _, img := range images {
if _, exists := imageMap[img.Parent]; !exists {
imageMap[img.Parent] = make(map[string]struct{})
}
imageMap[img.Parent][img.Id] = struct{}{}
}
// Loop on the children of the given image and check the config
for elem := range imageMap[imgId] {
img, err := srv.runtime.graph.Get(elem)
if err != nil {
return nil, err
}
if CompareConfig(&img.ContainerConfig, config) {
return img, nil
}
}
return nil, nil
}
func (srv *Server) ContainerStart(name string) error {
if container := srv.runtime.Get(name); container != nil {
if err := container.Start(); err != nil {
return fmt.Errorf("Error starting container %s: %s", name, err.Error())
}
} else {
return fmt.Errorf("No such container: %s", name)
}
return nil
}
func (srv *Server) ContainerStop(name string, t int) error {
if container := srv.runtime.Get(name); container != nil {
if err := container.Stop(t); err != nil {
return fmt.Errorf("Error stopping container %s: %s", name, err.Error())
}
} else {
return fmt.Errorf("No such container: %s", name)
}
return nil
}
func (srv *Server) ContainerWait(name string) (int, error) {
if container := srv.runtime.Get(name); container != nil {
return container.Wait(), nil
}
return 0, fmt.Errorf("No such container: %s", name)
}
func (srv *Server) ContainerResize(name string, h, w int) error {
if container := srv.runtime.Get(name); container != nil {
return container.Resize(h, w)
}
return fmt.Errorf("No such container: %s", name)
}
func (srv *Server) ContainerAttach(name string, logs, stream, stdin, stdout, stderr bool, in io.ReadCloser, out io.Writer) error {
container := srv.runtime.Get(name)
if container == nil {
return fmt.Errorf("No such container: %s", name)
}
//logs
if logs {
if stdout {
cLog, err := container.ReadLog("stdout")
if err != nil {
utils.Debugf(err.Error())
} else if _, err := io.Copy(out, cLog); err != nil {
utils.Debugf(err.Error())
}
}
if stderr {
cLog, err := container.ReadLog("stderr")
if err != nil {
utils.Debugf(err.Error())
} else if _, err := io.Copy(out, cLog); err != nil {
utils.Debugf(err.Error())
}
}
}
//stream
if stream {
if container.State.Ghost {
return fmt.Errorf("Impossible to attach to a ghost container")
}
if !container.State.Running {
return fmt.Errorf("Impossible to attach to a stopped container, start it first")
}
var (
cStdin io.ReadCloser
cStdout, cStderr io.Writer
cStdinCloser io.Closer
)
if stdin {
r, w := io.Pipe()
go func() {
defer w.Close()
defer utils.Debugf("Closing buffered stdin pipe")
io.Copy(w, in)
}()
cStdin = r
cStdinCloser = in
}
if stdout {
cStdout = out
}
if stderr {
cStderr = out
}
<-container.Attach(cStdin, cStdinCloser, cStdout, cStderr)
// If we are in stdinonce mode, wait for the process to end
// otherwise, simply return
if container.Config.StdinOnce && !container.Config.Tty {
container.Wait()
}
}
return nil
}
func (srv *Server) ContainerInspect(name string) (*Container, error) {
if container := srv.runtime.Get(name); container != nil {
return container, nil
}
return nil, fmt.Errorf("No such container: %s", name)
}
func (srv *Server) ImageInspect(name string) (*Image, error) {
if image, err := srv.runtime.repositories.LookupImage(name); err == nil && image != nil {
return image, nil
}
return nil, fmt.Errorf("No such image: %s", name)
}
func NewServer(autoRestart bool) (*Server, error) {
if runtime.GOARCH != "amd64" {
log.Fatalf("The docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
}
runtime, err := NewRuntime(autoRestart)
if err != nil {
return nil, err
}
srv := &Server{
runtime: runtime,
}
runtime.srv = srv
return srv, nil
}
type Server struct {
runtime *Runtime
}
| [
"\"DEBUG\""
]
| []
| [
"DEBUG"
]
| [] | ["DEBUG"] | go | 1 | 0 | |
manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "williezh_blog.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| []
| []
| []
| [] | [] | python | 0 | 0 | |
make.py | #!/usr/bin/python
import os, sys, re, json, shutil, multiprocessing
from subprocess import Popen, PIPE, STDOUT
# Definitions
INCLUDES = ['btBulletDynamicsCommon.h',
os.path.join('BulletCollision', 'CollisionShapes', 'btHeightfieldTerrainShape.h'),
os.path.join('BulletCollision', 'CollisionShapes', 'btConvexPolyhedron.h'),
os.path.join('BulletCollision', 'CollisionShapes', 'btShapeHull.h'),
os.path.join('BulletCollision', 'CollisionDispatch', 'btGhostObject.h'),
os.path.join('BulletDynamics', 'Character', 'btKinematicCharacterController.h'),
os.path.join('BulletSoftBody', 'btSoftBody.h'),
os.path.join('BulletSoftBody', 'btSoftRigidDynamicsWorld.h'), os.path.join('BulletSoftBody', 'btDefaultSoftBodySolver.h'),
os.path.join('BulletSoftBody', 'btSoftBodyRigidBodyCollisionConfiguration.h'),
os.path.join('BulletSoftBody', 'btSoftBodyHelpers.h'),
os.path.join('..', '..', 'idl_templates.h')]
# Startup
stage_counter = 0
def which(program):
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if os.path.exists(exe_file):
return exe_file
return None
def build():
EMSCRIPTEN_ROOT = os.environ.get('EMSCRIPTEN')
if not EMSCRIPTEN_ROOT:
emcc = which('emcc')
EMSCRIPTEN_ROOT = os.path.dirname(emcc)
if not EMSCRIPTEN_ROOT:
print "ERROR: EMSCRIPTEN_ROOT environment variable (which should be equal to emscripten's root dir) not found"
sys.exit(1)
sys.path.append(EMSCRIPTEN_ROOT)
import tools.shared as emscripten
# Settings
'''
Settings.INLINING_LIMIT = 0
Settings.DOUBLE_MODE = 0
Settings.PRECISE_I64_MATH = 0
Settings.CORRECT_SIGNS = 0
Settings.CORRECT_OVERFLOWS = 0
Settings.CORRECT_ROUNDINGS = 0
'''
wasm = 'wasm' in sys.argv
closure = 'closure' in sys.argv
add_function_support = 'add_func' in sys.argv
args = '-O3 --llvm-lto 1 -s NO_EXIT_RUNTIME=1 -s NO_FILESYSTEM=1 -s EXPORTED_RUNTIME_METHODS=["Pointer_stringify"]'
if add_function_support:
args += ' -s RESERVED_FUNCTION_POINTERS=20 -s EXTRA_EXPORTED_RUNTIME_METHODS=["addFunction"]'
if not wasm:
args += ' -s WASM=0 -s AGGRESSIVE_VARIABLE_ELIMINATION=1 -s ELIMINATE_DUPLICATE_FUNCTIONS=1 -s SINGLE_FILE=1 -s LEGACY_VM_SUPPORT=1'
else:
args += ''' -s WASM=1 -s BINARYEN_IGNORE_IMPLICIT_TRAPS=1 -s BINARYEN_TRAP_MODE="clamp"'''
if closure:
args += ' --closure 1 -s IGNORE_CLOSURE_COMPILER_ERRORS=1' # closure complains about the bullet Node class (Node is a DOM thing too)
else:
args += ' -s NO_DYNAMIC_EXECUTION=1'
emcc_args = args.split(' ')
emcc_args += ['-s', 'TOTAL_MEMORY=%d' % (64*1024*1024)] # default 64MB. Compile with ALLOW_MEMORY_GROWTH if you want a growable heap (slower though).
#emcc_args += ['-s', 'ALLOW_MEMORY_GROWTH=1'] # resizable heap, with some amount of slowness
emcc_args += '-s EXPORT_NAME="Ammo" -s MODULARIZE=1'.split(' ')
target = 'ammo.js' if not wasm else 'ammo.wasm.js'
print
print '--------------------------------------------------'
print 'Building ammo.js, build type:', emcc_args
print '--------------------------------------------------'
print
'''
import os, sys, re
infile = open(sys.argv[1], 'r').read()
outfile = open(sys.argv[2], 'w')
t1 = infile
while True:
t2 = re.sub(r'\(\n?!\n?1\n?\+\n?\(\n?!\n?1\n?\+\n?(\w)\n?\)\n?\)', lambda m: '(!1+' + m.group(1) + ')', t1)
print len(infile), len(t2)
if t1 == t2: break
t1 = t2
outfile.write(t2)
'''
# Utilities
def stage(text):
global stage_counter
stage_counter += 1
text = 'Stage %d: %s' % (stage_counter, text)
print
print '=' * len(text)
print text
print '=' * len(text)
print
# Main
try:
this_dir = os.getcwd()
os.chdir('bullet')
if not os.path.exists('build'):
os.makedirs('build')
os.chdir('build')
stage('Generate bindings')
Popen([emscripten.PYTHON, os.path.join(EMSCRIPTEN_ROOT, 'tools', 'webidl_binder.py'), os.path.join(this_dir, 'ammo.idl'), 'glue']).communicate()
assert os.path.exists('glue.js')
assert os.path.exists('glue.cpp')
stage('Build bindings')
args = ['-I../src', '-c']
for include in INCLUDES:
args += ['-include', include]
emscripten.Building.emcc('glue.cpp', args, 'glue.o')
assert(os.path.exists('glue.o'))
# Configure with CMake on Windows, and with configure on Unix.
# Update - always use CMake
cmake_build = True
if cmake_build:
if not os.path.exists('CMakeCache.txt'):
stage('Configure via CMake')
emscripten.Building.configure([emscripten.PYTHON, os.path.join(EMSCRIPTEN_ROOT, 'emcmake'), 'cmake', '..', '-DBUILD_PYBULLET=OFF', '-DUSE_DOUBLE_PRECISION=OFF', '-DBUILD_EXTRAS=OFF', '-DBUILD_CPU_DEMOS=OFF', '-DUSE_GLUT=OFF', '-DBUILD_BULLET2_DEMOS=OFF', '-DBUILD_CLSOCKET=OFF', '-DBUILD_OPENGL3_DEMOS=OFF', '-DBUILD_EGL=OFF', '-DBUILD_ENET=OFF', '-DBUILD_UNIT_TESTS=OFF', '-DCMAKE_BUILD_TYPE=Release'])
stage('Make')
CORES = multiprocessing.cpu_count()
if emscripten.WINDOWS:
emscripten.Building.make(['mingw32-make', '-j', str(CORES)])
else:
emscripten.Building.make(['make', '-j', str(CORES)])
stage('Link')
if cmake_build:
bullet_libs = [os.path.join('src', 'BulletSoftBody', 'libBulletSoftBody.a'),
os.path.join('src', 'BulletDynamics', 'libBulletDynamics.a'),
os.path.join('src', 'BulletCollision', 'libBulletCollision.a'),
os.path.join('src', 'LinearMath', 'libLinearMath.a')]
else:
bullet_libs = [os.path.join('src', '.libs', 'libBulletSoftBody.a'),
os.path.join('src', '.libs', 'libBulletDynamics.a'),
os.path.join('src', '.libs', 'libBulletCollision.a'),
os.path.join('src', '.libs', 'libLinearMath.a')]
stage('emcc: ' + ' '.join(emcc_args))
temp = os.path.join('..', '..', 'builds', target)
emscripten.Building.emcc('-DNOTHING_WAKA_WAKA', emcc_args + ['glue.o'] + bullet_libs + ['--js-transform', 'python %s' % os.path.join('..', '..', 'bundle.py')],
temp)
assert os.path.exists(temp), 'Failed to create script code'
stage('wrap')
wrapped = '''
// This is ammo.js, a port of Bullet Physics to JavaScript. zlib licensed.
''' + open(temp).read()
open(temp, 'w').write(wrapped)
finally:
os.chdir(this_dir);
if __name__ == '__main__':
build()
| []
| []
| [
"EMSCRIPTEN",
"PATH"
]
| [] | ["EMSCRIPTEN", "PATH"] | python | 2 | 0 | |
cmd/ctd-decoder/main_windows.go | // +build windows
/*
Copyright The containerd 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 main
import (
"fmt"
"io/ioutil"
"os"
winio "github.com/Microsoft/go-winio"
)
func readPayload() ([]byte, error) {
path := os.Getenv("STREAM_PROCESSOR_PIPE")
conn, err := winio.DialPipe(path, nil)
if err != nil {
return nil, fmt.Errorf("could not DialPipe: %w", err)
}
defer conn.Close()
return ioutil.ReadAll(conn)
}
| [
"\"STREAM_PROCESSOR_PIPE\""
]
| []
| [
"STREAM_PROCESSOR_PIPE"
]
| [] | ["STREAM_PROCESSOR_PIPE"] | go | 1 | 0 | |
go/vt/vttablet/tabletserver/query_engine_test.go | /*
Copyright 2019 The Vitess 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 tabletserver
import (
"context"
"expvar"
"fmt"
"math/rand"
"net/http"
"net/http/httptest"
"os"
"path"
"reflect"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"vitess.io/vitess/go/mysql"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"vitess.io/vitess/go/cache"
"vitess.io/vitess/go/mysql/fakesqldb"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/streamlog"
"vitess.io/vitess/go/vt/dbconfigs"
"vitess.io/vitess/go/vt/tableacl"
"vitess.io/vitess/go/vt/vttablet/tabletserver/planbuilder"
"vitess.io/vitess/go/vt/vttablet/tabletserver/schema"
"vitess.io/vitess/go/vt/vttablet/tabletserver/schema/schematest"
"vitess.io/vitess/go/vt/vttablet/tabletserver/tabletenv"
querypb "vitess.io/vitess/go/vt/proto/query"
)
func TestStrictMode(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
schematest.AddDefaultQueries(db)
// Test default behavior.
config := tabletenv.NewDefaultConfig()
config.DB = newDBConfigs(db)
env := tabletenv.NewEnv(config, "TabletServerTest")
se := schema.NewEngine(env)
qe := NewQueryEngine(env, se)
qe.se.InitDBConfig(newDBConfigs(db).DbaWithDB())
qe.se.Open()
if err := qe.Open(); err != nil {
t.Error(err)
}
qe.Close()
// Check that we fail if STRICT_TRANS_TABLES or STRICT_ALL_TABLES is not set.
db.AddQuery(
"select @@global.sql_mode",
&sqltypes.Result{
Fields: []*querypb.Field{{Type: sqltypes.VarChar}},
Rows: [][]sqltypes.Value{{sqltypes.NewVarBinary("")}},
},
)
qe = NewQueryEngine(env, se)
err := qe.Open()
wantErr := "require sql_mode to be STRICT_TRANS_TABLES or STRICT_ALL_TABLES: got ''"
if err == nil || err.Error() != wantErr {
t.Errorf("Open: %v, want %s", err, wantErr)
}
qe.Close()
// Test that we succeed if the enforcement flag is off.
config.EnforceStrictTransTables = false
qe = NewQueryEngine(env, se)
if err := qe.Open(); err != nil {
t.Fatal(err)
}
qe.Close()
}
func TestGetPlanPanicDuetoEmptyQuery(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
schematest.AddDefaultQueries(db)
qe := newTestQueryEngine(10*time.Second, true, newDBConfigs(db))
qe.se.Open()
qe.Open()
defer qe.Close()
ctx := context.Background()
logStats := tabletenv.NewLogStats(ctx, "GetPlanStats")
_, err := qe.GetPlan(ctx, logStats, "", false, false /* inReservedConn */)
require.EqualError(t, err, "query was empty")
}
func addSchemaEngineQueries(db *fakesqldb.DB) {
db.AddQueryPattern(baseShowTablesPattern, &sqltypes.Result{
Fields: mysql.BaseShowTablesFields,
Rows: [][]sqltypes.Value{
mysql.BaseShowTablesRow("test_table_01", false, ""),
mysql.BaseShowTablesRow("test_table_02", false, ""),
mysql.BaseShowTablesRow("test_table_03", false, ""),
mysql.BaseShowTablesRow("seq", false, "vitess_sequence"),
mysql.BaseShowTablesRow("msg", false, "vitess_message,vt_ack_wait=30,vt_purge_after=120,vt_batch_size=1,vt_cache_size=10,vt_poller_interval=30"),
}})
db.AddQuery("show status like 'Innodb_rows_read'", sqltypes.MakeTestResult(sqltypes.MakeTestFields(
"Variable_name|Value",
"varchar|int64"),
"Innodb_rows_read|0",
))
}
func TestGetMessageStreamPlan(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
schematest.AddDefaultQueries(db)
addSchemaEngineQueries(db)
qe := newTestQueryEngine(10*time.Second, true, newDBConfigs(db))
qe.se.Open()
qe.Open()
defer qe.Close()
plan, err := qe.GetMessageStreamPlan("msg")
if err != nil {
t.Fatal(err)
}
wantPlan := &planbuilder.Plan{
PlanID: planbuilder.PlanMessageStream,
Table: qe.tables["msg"],
Permissions: []planbuilder.Permission{{
TableName: "msg",
Role: tableacl.WRITER,
}},
}
if !reflect.DeepEqual(plan.Plan, wantPlan) {
t.Errorf("GetMessageStreamPlan(msg): %v, want %v", plan.Plan, wantPlan)
}
if plan.Rules == nil || plan.Authorized == nil {
t.Errorf("GetMessageStreamPlan(msg): Rules or ACLResult are nil. Rules: %v, Authorized: %v", plan.Rules, plan.Authorized)
}
}
func assertPlanCacheSize(t *testing.T, qe *QueryEngine, expected int) {
var size int
qe.plans.Wait()
qe.plans.ForEach(func(_ any) bool {
size++
return true
})
if size != expected {
t.Fatalf("expected query plan cache to contain %d entries, found %d", expected, size)
}
}
func TestQueryPlanCache(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
schematest.AddDefaultQueries(db)
firstQuery := "select * from test_table_01"
secondQuery := "select * from test_table_02"
db.AddQuery("select * from test_table_01 where 1 != 1", &sqltypes.Result{})
db.AddQuery("select * from test_table_02 where 1 != 1", &sqltypes.Result{})
qe := newTestQueryEngine(10*time.Second, true, newDBConfigs(db))
qe.se.Open()
qe.Open()
defer qe.Close()
ctx := context.Background()
logStats := tabletenv.NewLogStats(ctx, "GetPlanStats")
if cache.DefaultConfig.LFU {
qe.SetQueryPlanCacheCap(1024)
} else {
qe.SetQueryPlanCacheCap(1)
}
firstPlan, err := qe.GetPlan(ctx, logStats, firstQuery, false, false /* inReservedConn */)
if err != nil {
t.Fatal(err)
}
if firstPlan == nil {
t.Fatalf("plan should not be nil")
}
secondPlan, err := qe.GetPlan(ctx, logStats, secondQuery, false, false /* inReservedConn */)
if err != nil {
t.Fatal(err)
}
if secondPlan == nil {
t.Fatalf("plan should not be nil")
}
expvar.Do(func(kv expvar.KeyValue) {
_ = kv.Value.String()
})
assertPlanCacheSize(t, qe, 1)
qe.ClearQueryPlanCache()
}
func TestNoQueryPlanCache(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
schematest.AddDefaultQueries(db)
firstQuery := "select * from test_table_01"
db.AddQuery("select * from test_table_01 where 1 != 1", &sqltypes.Result{})
db.AddQuery("select * from test_table_02 where 1 != 1", &sqltypes.Result{})
qe := newTestQueryEngine(10*time.Second, true, newDBConfigs(db))
qe.se.Open()
qe.Open()
defer qe.Close()
ctx := context.Background()
logStats := tabletenv.NewLogStats(ctx, "GetPlanStats")
qe.SetQueryPlanCacheCap(1024)
firstPlan, err := qe.GetPlan(ctx, logStats, firstQuery, true, false /* inReservedConn */)
if err != nil {
t.Fatal(err)
}
if firstPlan == nil {
t.Fatalf("plan should not be nil")
}
assertPlanCacheSize(t, qe, 0)
qe.ClearQueryPlanCache()
}
func TestNoQueryPlanCacheDirective(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
schematest.AddDefaultQueries(db)
firstQuery := "select /*vt+ SKIP_QUERY_PLAN_CACHE=1 */ * from test_table_01"
db.AddQuery("select * from test_table_01 where 1 != 1", &sqltypes.Result{})
db.AddQuery("select /*vt+ SKIP_QUERY_PLAN_CACHE=1 */ * from test_table_01 where 1 != 1", &sqltypes.Result{})
db.AddQuery("select /*vt+ SKIP_QUERY_PLAN_CACHE=1 */ * from test_table_02 where 1 != 1", &sqltypes.Result{})
qe := newTestQueryEngine(10*time.Second, true, newDBConfigs(db))
qe.se.Open()
qe.Open()
defer qe.Close()
ctx := context.Background()
logStats := tabletenv.NewLogStats(ctx, "GetPlanStats")
qe.SetQueryPlanCacheCap(1024)
firstPlan, err := qe.GetPlan(ctx, logStats, firstQuery, false, false /* inReservedConn */)
if err != nil {
t.Fatal(err)
}
if firstPlan == nil {
t.Fatalf("plan should not be nil")
}
assertPlanCacheSize(t, qe, 0)
qe.ClearQueryPlanCache()
}
func TestStatsURL(t *testing.T) {
db := fakesqldb.New(t)
defer db.Close()
schematest.AddDefaultQueries(db)
query := "select * from test_table_01"
db.AddQuery("select * from test_table_01 where 1 != 1", &sqltypes.Result{})
qe := newTestQueryEngine(1*time.Second, true, newDBConfigs(db))
qe.se.Open()
qe.Open()
defer qe.Close()
// warm up cache
ctx := context.Background()
logStats := tabletenv.NewLogStats(ctx, "GetPlanStats")
qe.GetPlan(ctx, logStats, query, false, false /* inReservedConn */)
request, _ := http.NewRequest("GET", "/debug/tablet_plans", nil)
response := httptest.NewRecorder()
qe.handleHTTPQueryPlans(response, request)
request, _ = http.NewRequest("GET", "/debug/query_stats", nil)
response = httptest.NewRecorder()
qe.handleHTTPQueryStats(response, request)
request, _ = http.NewRequest("GET", "/debug/query_rules", nil)
response = httptest.NewRecorder()
qe.handleHTTPQueryRules(response, request)
}
func newTestQueryEngine(idleTimeout time.Duration, strict bool, dbcfgs *dbconfigs.DBConfigs) *QueryEngine {
config := tabletenv.NewDefaultConfig()
config.DB = dbcfgs
config.OltpReadPool.IdleTimeoutSeconds.Set(idleTimeout)
config.OlapReadPool.IdleTimeoutSeconds.Set(idleTimeout)
config.TxPool.IdleTimeoutSeconds.Set(idleTimeout)
env := tabletenv.NewEnv(config, "TabletServerTest")
se := schema.NewEngine(env)
qe := NewQueryEngine(env, se)
se.InitDBConfig(dbcfgs.DbaWithDB())
return qe
}
func runConsolidatedQuery(t *testing.T, sql string) *QueryEngine {
db := fakesqldb.New(t)
defer db.Close()
qe := newTestQueryEngine(1*time.Second, true, newDBConfigs(db))
qe.se.Open()
qe.Open()
defer qe.Close()
r1, ok := qe.consolidator.Create(sql)
if !ok {
t.Errorf("expected first consolidator ok")
}
r2, ok := qe.consolidator.Create(sql)
if ok {
t.Errorf("expected second consolidator not ok")
}
r1.Broadcast()
r2.Wait()
return qe
}
func TestConsolidationsUIRedaction(t *testing.T) {
// Reset to default redaction state.
defer func() {
*streamlog.RedactDebugUIQueries = false
}()
request, _ := http.NewRequest("GET", "/debug/consolidations", nil)
sql := "select * from test_db_01 where col = 'secret'"
redactedSQL := "select * from test_db_01 where col = :redacted1"
// First with the redaction off
*streamlog.RedactDebugUIQueries = false
unRedactedResponse := httptest.NewRecorder()
qe := runConsolidatedQuery(t, sql)
qe.handleHTTPConsolidations(unRedactedResponse, request)
if !strings.Contains(unRedactedResponse.Body.String(), sql) {
t.Fatalf("Response is missing the consolidated query: %v %v", sql, unRedactedResponse.Body.String())
}
// Now with the redaction on
*streamlog.RedactDebugUIQueries = true
redactedResponse := httptest.NewRecorder()
qe.handleHTTPConsolidations(redactedResponse, request)
if strings.Contains(redactedResponse.Body.String(), "secret") {
t.Fatalf("Response contains unredacted consolidated query: %v %v", sql, redactedResponse.Body.String())
}
if !strings.Contains(redactedResponse.Body.String(), redactedSQL) {
t.Fatalf("Response missing redacted consolidated query: %v %v", redactedSQL, redactedResponse.Body.String())
}
}
func BenchmarkPlanCacheThroughput(b *testing.B) {
db := fakesqldb.New(b)
defer db.Close()
schematest.AddDefaultQueries(db)
db.AddQueryPattern(".*", &sqltypes.Result{})
qe := newTestQueryEngine(10*time.Second, true, newDBConfigs(db))
qe.se.Open()
qe.Open()
defer qe.Close()
ctx := context.Background()
logStats := tabletenv.NewLogStats(ctx, "GetPlanStats")
for i := 0; i < b.N; i++ {
query := fmt.Sprintf("SELECT (a, b, c) FROM test_table_%d", rand.Intn(500))
_, err := qe.GetPlan(ctx, logStats, query, false, false /* inReservedConn */)
if err != nil {
b.Fatal(err)
}
}
}
func benchmarkPlanCache(b *testing.B, db *fakesqldb.DB, lfu bool, par int) {
b.Helper()
dbcfgs := newDBConfigs(db)
config := tabletenv.NewDefaultConfig()
config.DB = dbcfgs
config.QueryCacheLFU = lfu
env := tabletenv.NewEnv(config, "TabletServerTest")
se := schema.NewEngine(env)
qe := NewQueryEngine(env, se)
se.InitDBConfig(dbcfgs.DbaWithDB())
require.NoError(b, se.Open())
require.NoError(b, qe.Open())
defer qe.Close()
b.SetParallelism(par)
b.RunParallel(func(pb *testing.PB) {
ctx := context.Background()
logStats := tabletenv.NewLogStats(ctx, "GetPlanStats")
for pb.Next() {
query := fmt.Sprintf("SELECT (a, b, c) FROM test_table_%d", rand.Intn(500))
_, err := qe.GetPlan(ctx, logStats, query, false, false /* inReservedConn */)
require.NoErrorf(b, err, "bad query: %s", query)
}
})
}
func BenchmarkPlanCacheContention(b *testing.B) {
db := fakesqldb.New(b)
defer db.Close()
schematest.AddDefaultQueries(db)
db.AddQueryPattern(".*", &sqltypes.Result{})
for par := 1; par <= 8; par *= 2 {
b.Run(fmt.Sprintf("ContentionLRU-%d", par), func(b *testing.B) {
benchmarkPlanCache(b, db, false, par)
})
b.Run(fmt.Sprintf("ContentionLFU-%d", par), func(b *testing.B) {
benchmarkPlanCache(b, db, true, par)
})
}
}
func TestPlanCachePollution(t *testing.T) {
plotPath := os.Getenv("CACHE_PLOT_PATH")
if plotPath == "" {
t.Skipf("CACHE_PLOT_PATH not set")
}
const NormalQueries = 500000
const PollutingQueries = NormalQueries / 2
db := fakesqldb.New(t)
defer db.Close()
schematest.AddDefaultQueries(db)
db.AddQueryPattern(".*", &sqltypes.Result{})
dbcfgs := newDBConfigs(db)
config := tabletenv.NewDefaultConfig()
config.DB = dbcfgs
// config.LFUQueryCacheSizeBytes = 3 * 1024 * 1024
env := tabletenv.NewEnv(config, "TabletServerTest")
se := schema.NewEngine(env)
qe := NewQueryEngine(env, se)
se.InitDBConfig(dbcfgs.DbaWithDB())
se.Open()
qe.Open()
defer qe.Close()
type Stats struct {
queries uint64
cached uint64
interval time.Duration
}
var stats1, stats2 Stats
var wg sync.WaitGroup
go func() {
cacheMode := "lru"
if config.QueryCacheLFU {
cacheMode = "lfu"
}
out, err := os.Create(path.Join(plotPath,
fmt.Sprintf("cache_plot_%d_%d_%s.dat",
config.QueryCacheSize, config.QueryCacheMemory, cacheMode,
)),
)
require.NoError(t, err)
defer out.Close()
var last1 uint64
var last2 uint64
for range time.Tick(100 * time.Millisecond) {
var avg1, avg2 time.Duration
if stats1.queries-last1 > 0 {
avg1 = stats1.interval / time.Duration(stats1.queries-last1)
}
if stats2.queries-last2 > 0 {
avg2 = stats2.interval / time.Duration(stats2.queries-last2)
}
stats1.interval = 0
last1 = stats1.queries
stats2.interval = 0
last2 = stats2.queries
cacheUsed, cacheCap := qe.plans.UsedCapacity(), qe.plans.MaxCapacity()
t.Logf("%d queries (%f hit rate), cache %d / %d (%f usage), %v %v",
stats1.queries+stats2.queries,
float64(stats1.cached)/float64(stats1.queries),
cacheUsed, cacheCap,
float64(cacheUsed)/float64(cacheCap), avg1, avg2)
if out != nil {
fmt.Fprintf(out, "%d %f %f %f %f %d %d\n",
stats1.queries+stats2.queries,
float64(stats1.queries)/float64(NormalQueries),
float64(stats2.queries)/float64(PollutingQueries),
float64(stats1.cached)/float64(stats1.queries),
float64(cacheUsed)/float64(cacheCap),
avg1.Microseconds(),
avg2.Microseconds(),
)
}
}
}()
runner := func(totalQueries uint64, stats *Stats, sample func() string) {
for i := uint64(0); i < totalQueries; i++ {
ctx := context.Background()
logStats := tabletenv.NewLogStats(ctx, "GetPlanStats")
query := sample()
start := time.Now()
_, err := qe.GetPlan(ctx, logStats, query, false, false /* inReservedConn */)
require.NoErrorf(t, err, "bad query: %s", query)
stats.interval += time.Since(start)
atomic.AddUint64(&stats.queries, 1)
if logStats.CachedPlan {
atomic.AddUint64(&stats.cached, 1)
}
}
}
wg.Add(2)
go func() {
defer wg.Done()
runner(NormalQueries, &stats1, func() string {
return fmt.Sprintf("SELECT (a, b, c) FROM test_table_%d", rand.Intn(5000))
})
}()
go func() {
defer wg.Done()
time.Sleep(500 * time.Millisecond)
runner(PollutingQueries, &stats2, func() string {
return fmt.Sprintf("INSERT INTO test_table_00 VALUES (1, 2, 3, %d)", rand.Int())
})
}()
wg.Wait()
}
func TestAddQueryStats(t *testing.T) {
testcases := []struct {
name string
planType planbuilder.PlanType
tableName string
queryCount int64
duration time.Duration
mysqlTime time.Duration
rowsAffected int64
rowsReturned int64
errorCount int64
expectedQueryCounts string
expectedQueryTimes string
expectedQueryRowsAffected string
expectedQueryRowsReturned string
expectedQueryRowCounts string
expectedQueryErrorCounts string
}{
{
name: "select query",
planType: planbuilder.PlanSelect,
tableName: "A",
queryCount: 1,
duration: 10,
rowsAffected: 0,
rowsReturned: 15,
errorCount: 0,
expectedQueryCounts: `{"A.Select": 1}`,
expectedQueryTimes: `{"A.Select": 10}`,
expectedQueryRowsAffected: `{}`,
expectedQueryRowsReturned: `{"A.Select": 15}`,
expectedQueryRowCounts: `{"A.Select": 0}`,
expectedQueryErrorCounts: `{"A.Select": 0}`,
}, {
name: "select into query",
planType: planbuilder.PlanSelect,
tableName: "A",
queryCount: 1,
duration: 10,
rowsAffected: 15,
rowsReturned: 0,
errorCount: 0,
expectedQueryCounts: `{"A.Select": 1}`,
expectedQueryTimes: `{"A.Select": 10}`,
expectedQueryRowsAffected: `{"A.Select": 15}`,
expectedQueryRowsReturned: `{"A.Select": 0}`,
expectedQueryRowCounts: `{"A.Select": 15}`,
expectedQueryErrorCounts: `{"A.Select": 0}`,
}, {
name: "error",
planType: planbuilder.PlanSelect,
tableName: "A",
queryCount: 1,
duration: 10,
rowsAffected: 0,
rowsReturned: 0,
errorCount: 1,
expectedQueryCounts: `{"A.Select": 1}`,
expectedQueryTimes: `{"A.Select": 10}`,
expectedQueryRowsAffected: `{}`,
expectedQueryRowsReturned: `{"A.Select": 0}`,
expectedQueryRowCounts: `{"A.Select": 0}`,
expectedQueryErrorCounts: `{"A.Select": 1}`,
}, {
name: "insert query",
planType: planbuilder.PlanInsert,
tableName: "A",
queryCount: 1,
duration: 10,
rowsAffected: 15,
rowsReturned: 0,
errorCount: 0,
expectedQueryCounts: `{"A.Insert": 1}`,
expectedQueryTimes: `{"A.Insert": 10}`,
expectedQueryRowsAffected: `{"A.Insert": 15}`,
expectedQueryRowsReturned: `{}`,
expectedQueryRowCounts: `{"A.Insert": 15}`,
expectedQueryErrorCounts: `{"A.Insert": 0}`,
},
}
t.Parallel()
for _, testcase := range testcases {
t.Run(testcase.name, func(t *testing.T) {
config := tabletenv.NewDefaultConfig()
config.DB = newDBConfigs(fakesqldb.New(t))
env := tabletenv.NewEnv(config, "TestAddQueryStats_"+testcase.name)
se := schema.NewEngine(env)
qe := NewQueryEngine(env, se)
qe.AddStats(testcase.planType, testcase.tableName, testcase.queryCount, testcase.duration, testcase.mysqlTime, testcase.rowsAffected, testcase.rowsReturned, testcase.errorCount)
assert.Equal(t, testcase.expectedQueryCounts, qe.queryCounts.String())
assert.Equal(t, testcase.expectedQueryTimes, qe.queryTimes.String())
assert.Equal(t, testcase.expectedQueryRowsAffected, qe.queryRowsAffected.String())
assert.Equal(t, testcase.expectedQueryRowsReturned, qe.queryRowsReturned.String())
assert.Equal(t, testcase.expectedQueryRowCounts, qe.queryRowCounts.String())
assert.Equal(t, testcase.expectedQueryErrorCounts, qe.queryErrorCounts.String())
})
}
}
| [
"\"CACHE_PLOT_PATH\""
]
| []
| [
"CACHE_PLOT_PATH"
]
| [] | ["CACHE_PLOT_PATH"] | go | 1 | 0 | |
pkg/kube/client.go | package kube
import (
"os"
"github.com/sirupsen/logrus"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
var klog = logrus.WithField("module", "kube")
type Client struct {
clientset *kubernetes.Clientset
}
func LoadKubeClient(path string) (*Client, error) {
cls, err := kubernetes.NewForConfig(loadKubeConfig(path))
if err != nil {
return nil, err
}
return &Client{
clientset: cls,
}, nil
}
func loadKubeConfig(path string) *rest.Config {
var config *rest.Config
var err error
if path != "" {
flog := klog.WithField("kubeConfig", path)
flog.Info("Using command line supplied kube config")
config, err = clientcmd.BuildConfigFromFlags("", path)
if err != nil {
flog.WithError(err).Fatal("Can't load kube config file")
}
} else if kfgPath := os.Getenv("KUBECONFIG"); kfgPath != "" {
flog := klog.WithField("kubeConfig", kfgPath)
flog.Info("Using environment KUBECONFIG")
config, err = clientcmd.BuildConfigFromFlags("", kfgPath)
if err != nil {
flog.WithError(err).WithField("kubeConfig", kfgPath).
Fatal("can't find provided KUBECONFIG env path")
}
} else {
klog.Info("Using in-cluster kube config")
config, err = rest.InClusterConfig()
if err != nil {
klog.WithError(err).Fatal("can't load in-cluster REST config")
}
}
return config
}
| [
"\"KUBECONFIG\""
]
| []
| [
"KUBECONFIG"
]
| [] | ["KUBECONFIG"] | go | 1 | 0 | |
senlin/tests/unit/common/base.py | # 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 time
import fixtures
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
import testscenarios
import testtools
from senlin.common import messaging
from senlin.engine import service
from senlin.tests.unit.common import utils
TEST_DEFAULT_LOGLEVELS = {'migrate': logging.WARN,
'sqlalchemy': logging.WARN}
_LOG_FORMAT = "%(levelname)8s [%(name)s] %(message)s"
_TRUE_VALUES = ('True', 'true', '1', 'yes')
class FakeLogMixin(object):
def setup_logging(self):
# Assign default logs to self.LOG so we can still
# assert on senlin logs.
default_level = logging.INFO
if os.environ.get('OS_DEBUG') in _TRUE_VALUES:
default_level = logging.DEBUG
self.LOG = self.useFixture(
fixtures.FakeLogger(level=default_level, format=_LOG_FORMAT))
base_list = set([nlog.split('.')[0] for nlog in
logging.getLogger().logger.manager.loggerDict])
for base in base_list:
if base in TEST_DEFAULT_LOGLEVELS:
self.useFixture(fixtures.FakeLogger(
level=TEST_DEFAULT_LOGLEVELS[base],
name=base, format=_LOG_FORMAT))
elif base != 'senlin':
self.useFixture(fixtures.FakeLogger(
name=base, format=_LOG_FORMAT))
class SenlinTestCase(testscenarios.WithScenarios,
testtools.TestCase, FakeLogMixin):
TIME_STEP = 0.1
def setUp(self):
super(SenlinTestCase, self).setUp()
self.setup_logging()
service.ENABLE_SLEEP = False
self.useFixture(fixtures.MonkeyPatch(
'senlin.common.exception._FATAL_EXCEPTION_FORMAT_ERRORS',
True))
def enable_sleep():
service.ENABLE_SLEEP = True
self.addCleanup(enable_sleep)
self.addCleanup(cfg.CONF.reset)
messaging.setup("fake://", optional=True)
self.addCleanup(messaging.cleanup)
utils.setup_dummy_db()
self.addCleanup(utils.reset_dummy_db)
def stub_wallclock(self):
# Overrides scheduler wallclock to speed up tests expecting timeouts.
self._wallclock = time.time()
def fake_wallclock():
self._wallclock += self.TIME_STEP
return self._wallclock
self.m.StubOutWithMock(service, 'wallclock')
service.wallclock = fake_wallclock
def patchobject(self, obj, attr, **kwargs):
mockfixture = self.useFixture(fixtures.MockPatchObject(obj, attr,
**kwargs))
return mockfixture.mock
# NOTE(pshchelo): this overrides the testtools.TestCase.patch method
# that does simple monkey-patching in favor of mock's patching
def patch(self, target, **kwargs):
mockfixture = self.useFixture(fixtures.MockPatch(target, **kwargs))
return mockfixture.mock
def assertJsonEqual(self, expected, observed):
"""Asserts that 2 complex data structures are json equivalent.
This code is from Nova.
"""
if isinstance(expected, str):
expected = jsonutils.loads(expected)
if isinstance(observed, str):
observed = jsonutils.loads(observed)
def sort_key(x):
if isinstance(x, (set, list)) or isinstance(x, datetime.datetime):
return str(x)
if isinstance(x, dict):
items = ((sort_key(k), sort_key(v)) for k, v in x.items())
return sorted(items)
return x
def inner(expected, observed):
if isinstance(expected, dict) and isinstance(observed, dict):
self.assertEqual(len(expected), len(observed))
expected_keys = sorted(expected)
observed_keys = sorted(observed)
self.assertEqual(expected_keys, observed_keys)
for key in list(expected.keys()):
inner(expected[key], observed[key])
elif (isinstance(expected, (list, tuple, set)) and
isinstance(observed, (list, tuple, set))):
self.assertEqual(len(expected), len(observed))
expected_values_iter = iter(sorted(expected, key=sort_key))
observed_values_iter = iter(sorted(observed, key=sort_key))
for i in range(len(expected)):
inner(next(expected_values_iter),
next(observed_values_iter))
else:
self.assertEqual(expected, observed)
try:
inner(expected, observed)
except testtools.matchers.MismatchError as e:
inner_mismatch = e.mismatch
# inverting the observed / expected because testtools
# error messages assume expected is second. Possibly makes
# reading the error messages less confusing.
raise testtools.matchers.MismatchError(
observed, expected, inner_mismatch, verbose=True)
| []
| []
| [
"OS_DEBUG"
]
| [] | ["OS_DEBUG"] | python | 1 | 0 | |
opacus/tests/ddp_hook_check.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import os
import sys
import unittest
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.nn as nn
import torch.optim as optim
from opacus import PrivacyEngine
from opacus.distributed import DifferentiallyPrivateDistributedDataParallel as DPDDP
from torch.nn.parallel import DistributedDataParallel as DDP
PRIVACY_ALPHAS = [1 + x / 10.0 for x in range(1, 100)] + list(range(12, 64))
def setup_and_get_device(rank, world_size, nonce=0):
"""
Initialize the torch.distributed process group.
If you run multiple groups in parallel or if you have zombie processes, you can add a nonce to avoid errors.
"""
device = 0
if sys.platform == "win32":
# Distributed package only covers collective communications with Gloo
# backend and FileStore on Windows platform. Set init_method parameter
# in init_process_group to a local file.
# Example init_method="file:///f:/libtmp/some_file"
init_method = "file:///{your local file path}"
# initialize the process group
dist.init_process_group(
"gloo", init_method=init_method, rank=rank, world_size=world_size
)
device = rank
elif os.environ.get("SLURM_NTASKS") is not None:
# Running on a Slurm cluster
os.environ["MASTER_ADDR"] = "127.0.0.1"
os.environ["MASTER_PORT"] = str(7440 + nonce)
local_rank = int(os.environ.get("SLURM_LOCALID"))
dist.init_process_group(backend="gloo", rank=rank, world_size=world_size)
# The device is the local rank (if you have 2 nodes with 8 GPUs each, you will have two "cuda:0" devices)
device = local_rank
else:
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = "12355"
os.environ["RANK"] = str(rank)
os.environ["WORLD_SIZE"] = str(world_size)
dist.init_process_group(
init_method="env://",
backend="nccl",
)
# Single node experiment
device = rank
return device
def cleanup():
dist.destroy_process_group()
class ToyModel(nn.Module):
def __init__(self):
super(ToyModel, self).__init__()
self.net1 = nn.Linear(10, 10)
self.relu = nn.ReLU()
self.net2 = nn.Linear(10, 5)
def forward(self, x):
return self.net2(self.relu(self.net1(x)))
def demo_basic(rank, world_size, weight, dp, noise_multiplier=0, max_grad_norm=1e8):
# We don't want the 2 GPUs to work on the same examples/labels in parallel
torch.manual_seed(rank)
batch_size = 32
withdp = "with" + ("out " if not dp else "")
print(f"Running basic DDP {withdp} differential privacy example on rank {rank}.")
device = setup_and_get_device(rank, world_size)
# create model and move it to GPU with id rank
model = ToyModel().to(device)
print(f"Initial weight: {model.net1.weight.data}")
# Freeze all the parameters except one, to ensure that the noise is the same
# (the DDP hook does not browse the layers in the same order as the naive implementation)
model.net1.bias.requires_grad = False
model.net2.bias.requires_grad = False
model.net2.weight.requires_grad = False
if dp:
ddp_model = DPDDP(model)
engine = PrivacyEngine(
ddp_model,
batch_size=batch_size,
sample_size=10 * batch_size,
alphas=PRIVACY_ALPHAS,
noise_multiplier=noise_multiplier,
max_grad_norm=[max_grad_norm],
)
engine.random_number_generator = engine._set_seed(0)
else:
ddp_model = DDP(model, device_ids=[device])
loss_fn = nn.MSELoss()
optimizer = optim.SGD(ddp_model.parameters(), lr=1)
if dp:
engine.attach(optimizer)
optimizer.zero_grad()
labels = torch.randn(batch_size, 5).to(device)
outputs = ddp_model(torch.randn(batch_size, 10).to(device))
loss_fn(outputs, labels).backward()
optimizer.step()
weight.copy_(model.net1.weight.data.cpu())
cleanup()
def demo_ddp_hook(rank, world_size, weight, dp, noise_multiplier, max_grad_norm):
torch.manual_seed(rank)
batch_size = 32
withdp = "with" + ("out " if not dp else "")
print(f"Running DDP hook {withdp} differential privacy example on rank {rank}.")
device = setup_and_get_device(rank, world_size, nonce=1)
# create model and move it to GPU with id rank
model = ToyModel().to(device)
model.net1.bias.requires_grad = False
model.net2.bias.requires_grad = False
model.net2.weight.requires_grad = False
ddp_model = DDP(model, device_ids=[device])
if dp:
engine = PrivacyEngine(
ddp_model,
batch_size=batch_size,
sample_size=10 * batch_size,
alphas=PRIVACY_ALPHAS,
noise_multiplier=noise_multiplier,
max_grad_norm=[max_grad_norm],
)
engine.random_number_generator = engine._set_seed(0)
loss_fn = nn.MSELoss()
optimizer = optim.SGD(ddp_model.parameters(), lr=1)
if dp:
engine.attach(optimizer)
optimizer.zero_grad()
labels = torch.randn(batch_size, 5).to(device)
outputs = ddp_model(torch.randn(batch_size, 10).to(device))
loss_fn(outputs, labels).backward()
optimizer.step()
weight.copy_(model.net1.weight.data.cpu())
del ddp_model
cleanup()
def add_remove_ddp_hooks(
rank, world_size, remaining_hooks, dp, noise_multiplier=0, max_grad_norm=1e8
):
device = setup_and_get_device(rank, world_size, nonce=2)
model = ToyModel().to(device)
ddp_model = nn.parallel.DistributedDataParallel(model, device_ids=[device])
engine = PrivacyEngine(
ddp_model,
batch_size=1,
sample_size=10,
alphas=PRIVACY_ALPHAS,
noise_multiplier=noise_multiplier,
max_grad_norm=[max_grad_norm],
)
optimizer = optim.SGD(ddp_model.parameters(), lr=1)
engine.attach(optimizer)
remaining_hooks["attached"] = {
p: p._backward_hooks for p in engine.module.parameters() if p._backward_hooks
}
engine.detach()
remaining_hooks["detached"] = {
p: p._backward_hooks for p in engine.module.parameters() if p._backward_hooks
}
cleanup()
def debug(rank, world_size, tensor, dp, noise_multiplier=0, max_grad_norm=1e8):
local_rank = setup_and_get_device(rank, world_size)
print(f"Rank: {rank},World size: {world_size}, local_rank: {local_rank}")
tensor = tensor.to(local_rank)
print(f"dp: {dp}")
print(tensor)
cleanup()
def run_function(local_function, tensor, dp, noise_multiplier=0, max_grad_norm=1e8):
if os.environ.get("SLURM_NTASKS") is not None:
world_size = int(os.environ.get("SLURM_NTASKS"))
rank = int(os.environ.get("SLURM_PROCID"))
print(f"Running on a Slurm cluster with {world_size} tasks.")
local_function(rank, world_size, tensor, dp, noise_multiplier, max_grad_norm)
else:
world_size = torch.cuda.device_count()
print(f"Spawning multiple processes on a local machine with {world_size} GPUs")
# The rank will be passed as the first argument
mp.spawn(
local_function,
args=(
world_size,
tensor,
dp,
noise_multiplier,
max_grad_norm,
),
nprocs=world_size,
join=True,
)
return world_size
class GradientComputationTest(unittest.TestCase):
def test_connection(self):
tensor = torch.zeros(10, 10)
world_size = run_function(debug, tensor, dp=True)
self.assertTrue(
world_size >= 2, f"Need at least 2 gpus but was provided only {world_size}."
)
def test_gradient_noclip_zeronoise(self):
# Tests that gradient is the same with DP or with DDP
weight_dp, weight_nodp = torch.zeros(10, 10), torch.zeros(10, 10)
run_function(demo_basic, weight_dp, dp=True)
run_function(demo_basic, weight_nodp, dp=False)
self.assertTrue(torch.norm(weight_dp - weight_nodp) < 1e-7)
def test_ddp_hook(self):
# Tests that the DDP hook does the same thing as naive aggregation with per layer clipping
weight_ddp_naive, weight_ddp_hook = torch.zeros(10, 10), torch.zeros(10, 10)
run_function(
demo_basic,
weight_ddp_naive,
dp=True,
noise_multiplier=0.1,
max_grad_norm=1.0,
)
run_function(
demo_ddp_hook,
weight_ddp_hook,
dp=True,
noise_multiplier=0.1,
max_grad_norm=1.0,
)
self.assertTrue(
torch.norm(weight_ddp_naive - weight_ddp_hook) < 1e-7,
f"DDP naive: {weight_ddp_naive}\nDDP hook: {weight_ddp_hook}",
)
def test_add_remove_ddp_hooks(self):
remaining_hooks = {
"attached": None,
"detached": None,
}
run_function(
add_remove_ddp_hooks,
remaining_hooks,
dp=True,
noise_multiplier=0.1,
max_grad_norm=1.0,
)
assert remaining_hooks["attached"], "There are no hooks."
assert not remaining_hooks[
"detached"
], f"Some hooks remain after .remove_hooks(): {remaining_hooks}"
| []
| []
| [
"SLURM_LOCALID",
"MASTER_ADDR",
"MASTER_PORT",
"SLURM_NTASKS",
"RANK",
"SLURM_PROCID",
"WORLD_SIZE"
]
| [] | ["SLURM_LOCALID", "MASTER_ADDR", "MASTER_PORT", "SLURM_NTASKS", "RANK", "SLURM_PROCID", "WORLD_SIZE"] | python | 7 | 0 | |
pkg/duplicate/ingress.go | package duplicate
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
v1 "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
_ "k8s.io/client-go/plugin/pkg/client/auth/oidc"
)
// DuplicateTestIngress is the function run when a user performs
// cloud-platform duplicate ingress -n <namespace> <resource>
// It requires a namespace name, the name of an ingress resource
// and will:
// - inspect the cluster
// - copy the ingress rule defined
// - make relevant changes
// - create a new rule
func DuplicateIngress(namespace, resourceName string) error {
// Set the filepath of the kubeconfig file. This assumes
// the user has either the envname set or stores their config file
// in the default location.
configFile := os.Getenv("KUBECONFIG")
if configFile == "" {
configFile = filepath.Join(homedir.HomeDir(), ".kube", "config")
}
// Build the Kubernetes client using the default context (user set).
config, err := clientcmd.BuildConfigFromFlags("", configFile)
if err != nil {
return err
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
return err
}
// Get the specified ingress resource
ing, err := getIngressResource(clientset, namespace, resourceName)
if err != nil {
return err
}
// Duplicate the specified ingress resource
duplicateIngress, err := copyAndChangeIngress(ing)
if err != nil {
return err
}
// Apply the duplicate ingress resource to the same namespace
err = applyIngress(clientset, duplicateIngress)
if err != nil {
return err
}
return nil
}
// getIngressResource takes a Kubernetes clientset, the name of the users namespace and ingress resource and inspect the
// cluster, returning a v1 ingress resource. There is no need to search for v1beta1 Ingress as the v1 API is backward
// compatible and would also fetch ingress resource with API version v1beta1.
func getIngressResource(clientset *kubernetes.Clientset, namespace, resourceName string) (*v1.Ingress, error) {
ingress, err := clientset.NetworkingV1().Ingresses(namespace).Get(context.TODO(), resourceName, metav1.GetOptions{})
if err != nil {
return nil, err
}
return ingress, nil
}
// copyAndChangeIngress gets an ingress, do a deep copy and change the values to the one needed for duplicating
func copyAndChangeIngress(inIngress *v1.Ingress) (*v1.Ingress, error) {
duplicateIngress := inIngress.DeepCopy()
// loop over Spec.Rules from the original ingress, add -duplicate string to the sub-domain i.e first part of domain
// and set that as the host rule for the duplicate ingress
for i := 0; i < len(inIngress.Spec.Rules) && len(inIngress.Spec.Rules) > 0; i++ {
subDomain := strings.SplitN(inIngress.Spec.Rules[i].Host, ".", 2)
duplicateIngress.Spec.Rules[i].Host = subDomain[0] + "-duplicate." + subDomain[1]
}
// Check if there is any TLS configuration, loop over the list of hosts from Spec.TLS of the original ingress,
// add -duplicate string to the sub-domain i.e first part of the domain
// and set that as the TLS host for the duplicate ingress
if len(inIngress.Spec.TLS) > 0 {
for i := 0; i < len(inIngress.Spec.TLS[0].Hosts) && len(inIngress.Spec.TLS) > 0; i++ {
subDomain := strings.SplitN(inIngress.Spec.TLS[0].Hosts[i], ".", 2)
duplicateIngress.Spec.TLS[0].Hosts[i] = subDomain[0] + "-duplicate." + subDomain[1]
}
}
// Discard the extra data returned by the k8s API which we don't need in the duplicate
duplicateIngress.Status = v1.IngressStatus{}
duplicateIngress.ObjectMeta.ResourceVersion = ""
duplicateIngress.ObjectMeta.SelfLink = ""
duplicateIngress.ObjectMeta.UID = ""
// Discard unwanted annotations that are copied from original ingress that are not needs in the duplicate
for k := range duplicateIngress.ObjectMeta.Annotations {
if strings.Contains(k, "meta.helm.sh") || strings.Contains(k, "kubectl.kubernetes.io/last-applied-configuration") {
delete(duplicateIngress.Annotations, k)
}
}
duplicateIngress.ObjectMeta.Name = inIngress.ObjectMeta.Name + "-duplicate"
duplicateIngress.ObjectMeta.Namespace = inIngress.ObjectMeta.Namespace
duplicateIngress.ObjectMeta.Annotations["external-dns.alpha.kubernetes.io/set-identifier"] = duplicateIngress.ObjectMeta.Name + "-" + duplicateIngress.ObjectMeta.Namespace + "-green"
duplicateIngress.ObjectMeta.Annotations["external-dns.alpha.kubernetes.io/aws-weight"] = "100"
return duplicateIngress, nil
}
// applyIngress takes a clientset and an ingress resource (which has been duplicated) and applies
// to the current cluster and namespace.
func applyIngress(clientset *kubernetes.Clientset, duplicateIngress *v1.Ingress) error {
_, err := clientset.NetworkingV1().Ingresses(duplicateIngress.Namespace).Create(context.TODO(), duplicateIngress, metav1.CreateOptions{})
if err != nil {
return err
}
fmt.Printf("ingress \"%v\" created\n", duplicateIngress.Name)
return nil
}
| [
"\"KUBECONFIG\""
]
| []
| [
"KUBECONFIG"
]
| [] | ["KUBECONFIG"] | go | 1 | 0 | |
Bot.py | # bot.py
#Import list
import os
import discord
import time
import datetime
import asyncio
from discord.ext import commands
from dotenv import load_dotenv
import pymongo
from pymongo import MongoClient
cluster = MongoClient("mongodb")
db = cluster["discord"]
collection = db["prefix"]
#________________________________________________
#File Configs
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='%', intents=intents, owner_id=786788350160797706, Help_command=None, case_insensitive=True)
bot = client
bot.remove_command('help')
#______________________________________________________________________________________________
@bot.command()
async def load(ctx, exstension):
client.load_extension(f'cogs.{exstension}')
@bot.command()
async def reload(ctx, extension):
if ctx.author.id != 786788350160797706: return
else:
client.reload_extension(f'cogs.{extension}')
await ctx.channel.send("Cog reloaded!")
client.load_extension("cogs.fun")
client.load_extension("cogs.events")
client.load_extension("cogs.commands")
client.load_extension("cogs.804864012184977438")
client.load_extension("cogs.leave")
client.load_extension("cogs.welcome")
client.run(TOKEN) | []
| []
| [
"DISCORD_TOKEN",
"DISCORD_GUILD"
]
| [] | ["DISCORD_TOKEN", "DISCORD_GUILD"] | python | 2 | 0 | |
frontend/extensions.py | """
This file contains all Flask extensions.
"""
import os
import grpc
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from frontend.pb import EnvironmentLookupServiceStub, EnvironmentProvisioningServiceStub
operator_channel_target = "localhost:1234"
if os.getenv("CTF_OPERATOR_SERVICE_HOST"):
host = os.getenv("CTF_OPERATOR_SERVICE_HOST")
operator_channel_target = f"{host}:1234"
db = SQLAlchemy()
migrate = Migrate()
operator_channel = grpc.insecure_channel(operator_channel_target)
lookup_service = EnvironmentLookupServiceStub(operator_channel)
provisioning_service = EnvironmentProvisioningServiceStub(operator_channel)
| []
| []
| [
"CTF_OPERATOR_SERVICE_HOST"
]
| [] | ["CTF_OPERATOR_SERVICE_HOST"] | python | 1 | 0 | |
eval/lib/libLF/conv-ModuleInfo-GitHubProject.py | #!/usr/bin/env python3
# Description:
# Convert a set of libLF.ModuleInfo's to libLF.GitHubProject's.
# Use defaults.
# Import libLF
import os
import sys
import re
sys.path.append('{}/lib'.format(os.environ['ECOSYSTEM_REGEXP_PROJECT_ROOT']))
import libLF
import argparse
import json
#################################################
def main(moduleInfoFile, outFile):
nAttempts = 0
nSuccesses = 0
nFailures = 0
with open(moduleInfoFile, 'r') as inStream, \
open(outFile, 'w') as outStream:
for line in inStream:
try:
line = line.strip()
if len(line) > 0:
nAttempts += 1
mi = libLF.ModuleInfo().initFromJSON(line)
ghp = libLF.GitHubProject().initFromRaw(
owner='UNKNOWN',
name='UNKNOWN',
registry=mi.registry,
modules=[mi.toNDJSON()],
tarballPath=mi.tarballPath
)
outStream.write(ghp.toNDJSON() + '\n')
nSuccesses += 1
except:
libLF.log('Discarding: {}'.format(line))
nFailures += 1
libLF.log('Out of {} ModuleInfo\'s: {} successful conversions, {} failures'.format(nAttempts, nSuccesses, nFailures))
###############################################
# Parse args
parser = argparse.ArgumentParser(description='Convert ModuleInfo to GitHubProject')
parser.add_argument('--module-info-file', help='in: NDJSON of ModuleInfo\'s', required=True, dest='moduleInfoFile')
parser.add_argument('--out-file', help='out: NDJSON of GitHubProject\'s', required=True, dest='outFile')
args = parser.parse_args()
# Here we go!
main(args.moduleInfoFile, args.outFile)
| []
| []
| [
"ECOSYSTEM_REGEXP_PROJECT_ROOT"
]
| [] | ["ECOSYSTEM_REGEXP_PROJECT_ROOT"] | python | 1 | 0 | |
tools/run_tests/run_interop_tests.py | #!/usr/bin/env python
# Copyright 2015 gRPC 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.
"""Run interop (cross-language) tests in parallel."""
from __future__ import print_function
import argparse
import atexit
import itertools
import json
import multiprocessing
import os
import re
import subprocess
import sys
import tempfile
import time
import uuid
import six
import traceback
import python_utils.dockerjob as dockerjob
import python_utils.jobset as jobset
import python_utils.report_utils as report_utils
# It's ok to not import because this is only necessary to upload results to BQ.
try:
from python_utils.upload_test_results import upload_interop_results_to_bq
except ImportError as e:
print(e)
# Docker doesn't clean up after itself, so we do it on exit.
atexit.register(lambda: subprocess.call(['stty', 'echo']))
ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
os.chdir(ROOT)
_DEFAULT_SERVER_PORT = 8080
_SKIP_CLIENT_COMPRESSION = [
'client_compressed_unary', 'client_compressed_streaming'
]
_SKIP_SERVER_COMPRESSION = [
'server_compressed_unary', 'server_compressed_streaming'
]
_SKIP_COMPRESSION = _SKIP_CLIENT_COMPRESSION + _SKIP_SERVER_COMPRESSION
_SKIP_ADVANCED = [
'status_code_and_message', 'custom_metadata', 'unimplemented_method',
'unimplemented_service'
]
_SKIP_SPECIAL_STATUS_MESSAGE = ['special_status_message']
_TEST_TIMEOUT = 3 * 60
# disable this test on core-based languages,
# see https://github.com/grpc/grpc/issues/9779
_SKIP_DATA_FRAME_PADDING = ['data_frame_padding']
# report suffix "sponge_log.xml" is important for reports to get picked up by internal CI
_DOCKER_BUILD_XML_REPORT = 'interop_docker_build/sponge_log.xml'
_TESTS_XML_REPORT = 'interop_test/sponge_log.xml'
class CXXLanguage:
def __init__(self):
self.client_cwd = None
self.server_cwd = None
self.http2_cwd = None
self.safename = 'cxx'
def client_cmd(self, args):
return ['bins/opt/interop_client'] + args
def client_cmd_http2interop(self, args):
return ['bins/opt/http2_client'] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return ['bins/opt/interop_server'] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_DATA_FRAME_PADDING + _SKIP_SPECIAL_STATUS_MESSAGE
def unimplemented_test_cases_server(self):
return []
def __str__(self):
return 'c++'
class CSharpLanguage:
def __init__(self):
self.client_cwd = 'src/csharp/Grpc.IntegrationTesting.Client/bin/Debug/net45'
self.server_cwd = 'src/csharp/Grpc.IntegrationTesting.Server/bin/Debug/net45'
self.safename = str(self)
def client_cmd(self, args):
return ['mono', 'Grpc.IntegrationTesting.Client.exe'] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return ['mono', 'Grpc.IntegrationTesting.Server.exe'] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_SERVER_COMPRESSION + _SKIP_DATA_FRAME_PADDING + _SKIP_SPECIAL_STATUS_MESSAGE
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'csharp'
class CSharpCoreCLRLanguage:
def __init__(self):
self.client_cwd = 'src/csharp/Grpc.IntegrationTesting.Client/bin/Debug/netcoreapp1.0'
self.server_cwd = 'src/csharp/Grpc.IntegrationTesting.Server/bin/Debug/netcoreapp1.0'
self.safename = str(self)
def client_cmd(self, args):
return ['dotnet', 'exec', 'Grpc.IntegrationTesting.Client.dll'] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return ['dotnet', 'exec', 'Grpc.IntegrationTesting.Server.dll'] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_SERVER_COMPRESSION + _SKIP_DATA_FRAME_PADDING + _SKIP_SPECIAL_STATUS_MESSAGE
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'csharpcoreclr'
class DartLanguage:
def __init__(self):
self.client_cwd = '../grpc-dart/interop'
self.server_cwd = '../grpc-dart/interop'
self.http2_cwd = '../grpc-dart/interop'
self.safename = str(self)
def client_cmd(self, args):
return ['dart', 'bin/client.dart'] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return ['dart', 'bin/server.dart'] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION + _SKIP_SPECIAL_STATUS_MESSAGE
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION + _SKIP_SPECIAL_STATUS_MESSAGE
def __str__(self):
return 'dart'
class JavaLanguage:
def __init__(self):
self.client_cwd = '../grpc-java'
self.server_cwd = '../grpc-java'
self.http2_cwd = '../grpc-java'
self.safename = str(self)
def client_cmd(self, args):
return ['./run-test-client.sh'] + args
def client_cmd_http2interop(self, args):
return [
'./interop-testing/build/install/grpc-interop-testing/bin/http2-client'
] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return ['./run-test-server.sh'] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return []
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'java'
class JavaOkHttpClient:
def __init__(self):
self.client_cwd = '../grpc-java'
self.safename = 'java'
def client_cmd(self, args):
return ['./run-test-client.sh', '--use_okhttp=true'] + args
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_DATA_FRAME_PADDING + _SKIP_SPECIAL_STATUS_MESSAGE
def __str__(self):
return 'javaokhttp'
class GoLanguage:
def __init__(self):
# TODO: this relies on running inside docker
self.client_cwd = '/go/src/google.golang.org/grpc/interop/client'
self.server_cwd = '/go/src/google.golang.org/grpc/interop/server'
self.http2_cwd = '/go/src/google.golang.org/grpc/interop/http2'
self.safename = str(self)
def client_cmd(self, args):
return ['go', 'run', 'client.go'] + args
def client_cmd_http2interop(self, args):
return ['go', 'run', 'negative_http2_client.go'] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return ['go', 'run', 'server.go'] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'go'
class Http2Server:
"""Represents the HTTP/2 Interop Test server
This pretends to be a language in order to be built and run, but really it
isn't.
"""
def __init__(self):
self.server_cwd = None
self.safename = str(self)
def server_cmd(self, args):
return ['python test/http2_test/http2_test_server.py']
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _TEST_CASES + _SKIP_DATA_FRAME_PADDING + _SKIP_SPECIAL_STATUS_MESSAGE
def unimplemented_test_cases_server(self):
return _TEST_CASES
def __str__(self):
return 'http2'
class Http2Client:
"""Represents the HTTP/2 Interop Test
This pretends to be a language in order to be built and run, but really it
isn't.
"""
def __init__(self):
self.client_cwd = None
self.safename = str(self)
def client_cmd(self, args):
return ['tools/http2_interop/http2_interop.test', '-test.v'] + args
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _TEST_CASES + _SKIP_SPECIAL_STATUS_MESSAGE
def unimplemented_test_cases_server(self):
return _TEST_CASES
def __str__(self):
return 'http2'
class NodeLanguage:
def __init__(self):
self.client_cwd = '../grpc-node'
self.server_cwd = '../grpc-node'
self.safename = str(self)
def client_cmd(self, args):
return [
'packages/grpc-native-core/deps/grpc/tools/run_tests/interop/with_nvm.sh',
'node', '--require', './test/fixtures/native_native',
'test/interop/interop_client.js'
] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return [
'packages/grpc-native-core/deps/grpc/tools/run_tests/interop/with_nvm.sh',
'node', '--require', './test/fixtures/native_native',
'test/interop/interop_server.js'
] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION + _SKIP_DATA_FRAME_PADDING
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'node'
class NodePureJSLanguage:
def __init__(self):
self.client_cwd = '../grpc-node'
self.server_cwd = '../grpc-node'
self.safename = str(self)
def client_cmd(self, args):
return [
'packages/grpc-native-core/deps/grpc/tools/run_tests/interop/with_nvm.sh',
'node', '--require', './test/fixtures/js_js',
'test/interop/interop_client.js'
] + args
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION + _SKIP_DATA_FRAME_PADDING
def unimplemented_test_cases_server(self):
return []
def __str__(self):
return 'nodepurejs'
class PHPLanguage:
def __init__(self):
self.client_cwd = None
self.safename = str(self)
def client_cmd(self, args):
return ['src/php/bin/interop_client.sh'] + args
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION + _SKIP_DATA_FRAME_PADDING + _SKIP_SPECIAL_STATUS_MESSAGE
def unimplemented_test_cases_server(self):
return []
def __str__(self):
return 'php'
class PHP7Language:
def __init__(self):
self.client_cwd = None
self.safename = str(self)
def client_cmd(self, args):
return ['src/php/bin/interop_client.sh'] + args
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION + _SKIP_DATA_FRAME_PADDING + _SKIP_SPECIAL_STATUS_MESSAGE
def unimplemented_test_cases_server(self):
return []
def __str__(self):
return 'php7'
class ObjcLanguage:
def __init__(self):
self.client_cwd = 'src/objective-c/tests'
self.safename = str(self)
def client_cmd(self, args):
# from args, extract the server port and craft xcodebuild command out of it
for arg in args:
port = re.search('--server_port=(\d+)', arg)
if port:
portnum = port.group(1)
cmdline = 'pod install && xcodebuild -workspace Tests.xcworkspace -scheme InteropTestsLocalSSL -destination name="iPhone 6" HOST_PORT_LOCALSSL=localhost:%s test' % portnum
return [cmdline]
def cloud_to_prod_env(self):
return {}
def global_env(self):
return {}
def unimplemented_test_cases(self):
# ObjC test runs all cases with the same command. It ignores the testcase
# cmdline argument. Here we return all but one test cases as unimplemented,
# and depend upon ObjC test's behavior that it runs all cases even when
# we tell it to run just one.
return _TEST_CASES[1:] + _SKIP_COMPRESSION + _SKIP_DATA_FRAME_PADDING + _SKIP_SPECIAL_STATUS_MESSAGE
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'objc'
class RubyLanguage:
def __init__(self):
self.client_cwd = None
self.server_cwd = None
self.safename = str(self)
def client_cmd(self, args):
return [
'tools/run_tests/interop/with_rvm.sh', 'ruby',
'src/ruby/pb/test/client.rb'
] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return [
'tools/run_tests/interop/with_rvm.sh', 'ruby',
'src/ruby/pb/test/server.rb'
] + args
def global_env(self):
return {}
def unimplemented_test_cases(self):
return _SKIP_SERVER_COMPRESSION + _SKIP_DATA_FRAME_PADDING + _SKIP_SPECIAL_STATUS_MESSAGE
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'ruby'
class PythonLanguage:
def __init__(self):
self.client_cwd = None
self.server_cwd = None
self.http2_cwd = None
self.safename = str(self)
def client_cmd(self, args):
return [
'py27_native/bin/python', 'src/python/grpcio_tests/setup.py',
'run_interop', '--client', '--args="{}"'.format(' '.join(args))
]
def client_cmd_http2interop(self, args):
return [
'py27_native/bin/python',
'src/python/grpcio_tests/tests/http2/negative_http2_client.py',
] + args
def cloud_to_prod_env(self):
return {}
def server_cmd(self, args):
return [
'py27_native/bin/python', 'src/python/grpcio_tests/setup.py',
'run_interop', '--server', '--args="{}"'.format(' '.join(args))
]
def global_env(self):
return {
'LD_LIBRARY_PATH': '{}/libs/opt'.format(DOCKER_WORKDIR_ROOT),
'PYTHONPATH': '{}/src/python/gens'.format(DOCKER_WORKDIR_ROOT)
}
def unimplemented_test_cases(self):
return _SKIP_COMPRESSION + _SKIP_DATA_FRAME_PADDING
def unimplemented_test_cases_server(self):
return _SKIP_COMPRESSION
def __str__(self):
return 'python'
_LANGUAGES = {
'c++': CXXLanguage(),
'csharp': CSharpLanguage(),
'csharpcoreclr': CSharpCoreCLRLanguage(),
'dart': DartLanguage(),
'go': GoLanguage(),
'java': JavaLanguage(),
'javaokhttp': JavaOkHttpClient(),
'node': NodeLanguage(),
'nodepurejs': NodePureJSLanguage(),
'php': PHPLanguage(),
'php7': PHP7Language(),
'objc': ObjcLanguage(),
'ruby': RubyLanguage(),
'python': PythonLanguage(),
}
# languages supported as cloud_to_cloud servers
_SERVERS = [
'c++', 'node', 'csharp', 'csharpcoreclr', 'java', 'go', 'ruby', 'python',
'dart'
]
_TEST_CASES = [
'large_unary', 'empty_unary', 'ping_pong', 'empty_stream',
'client_streaming', 'server_streaming', 'cancel_after_begin',
'cancel_after_first_response', 'timeout_on_sleeping_server',
'custom_metadata', 'status_code_and_message', 'unimplemented_method',
'client_compressed_unary', 'server_compressed_unary',
'client_compressed_streaming', 'server_compressed_streaming',
'unimplemented_service', 'special_status_message'
]
_AUTH_TEST_CASES = [
'compute_engine_creds', 'jwt_token_creds', 'oauth2_auth_token',
'per_rpc_creds'
]
_HTTP2_TEST_CASES = ['tls', 'framing']
_HTTP2_SERVER_TEST_CASES = [
'rst_after_header', 'rst_after_data', 'rst_during_data', 'goaway', 'ping',
'max_streams', 'data_frame_padding', 'no_df_padding_sanity_test'
]
_GRPC_CLIENT_TEST_CASES_FOR_HTTP2_SERVER_TEST_CASES = {
'data_frame_padding': 'large_unary',
'no_df_padding_sanity_test': 'large_unary'
}
_HTTP2_SERVER_TEST_CASES_THAT_USE_GRPC_CLIENTS = _GRPC_CLIENT_TEST_CASES_FOR_HTTP2_SERVER_TEST_CASES.keys(
)
_LANGUAGES_WITH_HTTP2_CLIENTS_FOR_HTTP2_SERVER_TEST_CASES = [
'java', 'go', 'python', 'c++'
]
_LANGUAGES_FOR_ALTS_TEST_CASES = ['java', 'go', 'c++']
_SERVERS_FOR_ALTS_TEST_CASES = ['java', 'go', 'c++']
_TRANSPORT_SECURITY_OPTIONS = [
'tls', 'alts', 'google_default_credentials', 'insecure'
]
DOCKER_WORKDIR_ROOT = '/var/local/git/grpc'
def docker_run_cmdline(cmdline, image, docker_args=[], cwd=None, environ=None):
"""Wraps given cmdline array to create 'docker run' cmdline from it."""
docker_cmdline = ['docker', 'run', '-i', '--rm=true']
# turn environ into -e docker args
if environ:
for k, v in environ.items():
docker_cmdline += ['-e', '%s=%s' % (k, v)]
# set working directory
workdir = DOCKER_WORKDIR_ROOT
if cwd:
workdir = os.path.join(workdir, cwd)
docker_cmdline += ['-w', workdir]
docker_cmdline += docker_args + [image] + cmdline
return docker_cmdline
def manual_cmdline(docker_cmdline, docker_image):
"""Returns docker cmdline adjusted for manual invocation."""
print_cmdline = []
for item in docker_cmdline:
if item.startswith('--name='):
continue
if item == docker_image:
item = "$docker_image"
item = item.replace('"', '\\"')
# add quotes when necessary
if any(character.isspace() for character in item):
item = "\"%s\"" % item
print_cmdline.append(item)
return ' '.join(print_cmdline)
def write_cmdlog_maybe(cmdlog, filename):
"""Returns docker cmdline adjusted for manual invocation."""
if cmdlog:
with open(filename, 'w') as logfile:
logfile.write('#!/bin/bash\n')
logfile.write('# DO NOT MODIFY\n')
logfile.write(
'# This file is generated by run_interop_tests.py/create_testcases.sh\n'
)
logfile.writelines("%s\n" % line for line in cmdlog)
print('Command log written to file %s' % filename)
def bash_cmdline(cmdline):
"""Creates bash -c cmdline from args list."""
# Use login shell:
# * makes error messages clearer if executables are missing
return ['bash', '-c', ' '.join(cmdline)]
def compute_engine_creds_required(language, test_case):
"""Returns True if given test requires access to compute engine creds."""
language = str(language)
if test_case == 'compute_engine_creds':
return True
if test_case == 'oauth2_auth_token' and language == 'c++':
# C++ oauth2 test uses GCE creds because C++ only supports JWT
return True
return False
def auth_options(language, test_case, service_account_key_file=None):
"""Returns (cmdline, env) tuple with cloud_to_prod_auth test options."""
language = str(language)
cmdargs = []
env = {}
if not service_account_key_file:
# this file path only works inside docker
service_account_key_file = '/root/service_account/GrpcTesting-726eb1347f15.json'
oauth_scope_arg = '--oauth_scope=https://www.googleapis.com/auth/xapi.zoo'
key_file_arg = '--service_account_key_file=%s' % service_account_key_file
default_account_arg = '--default_service_account=830293263384-compute@developer.gserviceaccount.com'
# TODO: When using google_default_credentials outside of cloud-to-prod, the environment variable
# 'GOOGLE_APPLICATION_CREDENTIALS' needs to be set for the test case
# 'jwt_token_creds' to work.
if test_case in ['jwt_token_creds', 'per_rpc_creds', 'oauth2_auth_token']:
if language in [
'csharp', 'csharpcoreclr', 'node', 'php', 'php7', 'python',
'ruby', 'nodepurejs'
]:
env['GOOGLE_APPLICATION_CREDENTIALS'] = service_account_key_file
else:
cmdargs += [key_file_arg]
if test_case in ['per_rpc_creds', 'oauth2_auth_token']:
cmdargs += [oauth_scope_arg]
if test_case == 'oauth2_auth_token' and language == 'c++':
# C++ oauth2 test uses GCE creds and thus needs to know the default account
cmdargs += [default_account_arg]
if test_case == 'compute_engine_creds':
cmdargs += [oauth_scope_arg, default_account_arg]
return (cmdargs, env)
def _job_kill_handler(job):
if job._spec.container_name:
dockerjob.docker_kill(job._spec.container_name)
# When the job times out and we decide to kill it,
# we need to wait a before restarting the job
# to prevent "container name already in use" error.
# TODO(jtattermusch): figure out a cleaner way to to this.
time.sleep(2)
def cloud_to_prod_jobspec(language,
test_case,
server_host_nickname,
server_host,
docker_image=None,
auth=False,
manual_cmd_log=None,
service_account_key_file=None,
transport_security='tls'):
"""Creates jobspec for cloud-to-prod interop test"""
container_name = None
cmdargs = [
'--server_host=%s' % server_host,
'--server_host_override=%s' % server_host, '--server_port=443',
'--test_case=%s' % test_case
]
if transport_security == 'tls':
transport_security_options = ['--use_tls=true']
elif transport_security == 'google_default_credentials' and str(
language) in ['c++', 'go', 'java', 'javaokhttp']:
transport_security_options = [
'--custom_credentials_type=google_default_credentials'
]
else:
print('Invalid transport security option %s in cloud_to_prod_jobspec.' %
transport_security)
sys.exit(1)
cmdargs = cmdargs + transport_security_options
environ = dict(language.cloud_to_prod_env(), **language.global_env())
if auth:
auth_cmdargs, auth_env = auth_options(language, test_case,
service_account_key_file)
cmdargs += auth_cmdargs
environ.update(auth_env)
cmdline = bash_cmdline(language.client_cmd(cmdargs))
cwd = language.client_cwd
if docker_image:
container_name = dockerjob.random_name(
'interop_client_%s' % language.safename)
cmdline = docker_run_cmdline(
cmdline,
image=docker_image,
cwd=cwd,
environ=environ,
docker_args=['--net=host',
'--name=%s' % container_name])
if manual_cmd_log is not None:
if manual_cmd_log == []:
manual_cmd_log.append(
'echo "Testing ${docker_image:=%s}"' % docker_image)
manual_cmd_log.append(manual_cmdline(cmdline, docker_image))
cwd = None
environ = None
suite_name = 'cloud_to_prod_auth' if auth else 'cloud_to_prod'
test_job = jobset.JobSpec(
cmdline=cmdline,
cwd=cwd,
environ=environ,
shortname='%s:%s:%s:%s:%s' %
(suite_name, language, server_host_nickname, test_case,
transport_security),
timeout_seconds=_TEST_TIMEOUT,
flake_retries=4 if args.allow_flakes else 0,
timeout_retries=2 if args.allow_flakes else 0,
kill_handler=_job_kill_handler)
if docker_image:
test_job.container_name = container_name
return test_job
def cloud_to_cloud_jobspec(language,
test_case,
server_name,
server_host,
server_port,
docker_image=None,
transport_security='tls',
manual_cmd_log=None):
"""Creates jobspec for cloud-to-cloud interop test"""
interop_only_options = [
'--server_host_override=foo.test.google.fr',
'--use_test_ca=true',
]
if transport_security == 'tls':
interop_only_options += ['--use_tls=true']
elif transport_security == 'alts':
interop_only_options += ['--use_tls=false', '--use_alts=true']
elif transport_security == 'insecure':
interop_only_options += ['--use_tls=false']
else:
print('Invalid transport security option %s in cloud_to_cloud_jobspec.'
% transport_security)
sys.exit(1)
client_test_case = test_case
if test_case in _HTTP2_SERVER_TEST_CASES_THAT_USE_GRPC_CLIENTS:
client_test_case = _GRPC_CLIENT_TEST_CASES_FOR_HTTP2_SERVER_TEST_CASES[
test_case]
if client_test_case in language.unimplemented_test_cases():
print('asking client %s to run unimplemented test case %s' %
(repr(language), client_test_case))
sys.exit(1)
common_options = [
'--test_case=%s' % client_test_case,
'--server_host=%s' % server_host,
'--server_port=%s' % server_port,
]
if test_case in _HTTP2_SERVER_TEST_CASES:
if test_case in _HTTP2_SERVER_TEST_CASES_THAT_USE_GRPC_CLIENTS:
client_options = interop_only_options + common_options
cmdline = bash_cmdline(language.client_cmd(client_options))
cwd = language.client_cwd
else:
cmdline = bash_cmdline(
language.client_cmd_http2interop(common_options))
cwd = language.http2_cwd
else:
cmdline = bash_cmdline(
language.client_cmd(common_options + interop_only_options))
cwd = language.client_cwd
environ = language.global_env()
if docker_image and language.safename != 'objc':
# we can't run client in docker for objc.
container_name = dockerjob.random_name(
'interop_client_%s' % language.safename)
cmdline = docker_run_cmdline(
cmdline,
image=docker_image,
environ=environ,
cwd=cwd,
docker_args=['--net=host',
'--name=%s' % container_name])
if manual_cmd_log is not None:
if manual_cmd_log == []:
manual_cmd_log.append(
'echo "Testing ${docker_image:=%s}"' % docker_image)
manual_cmd_log.append(manual_cmdline(cmdline, docker_image))
cwd = None
test_job = jobset.JobSpec(
cmdline=cmdline,
cwd=cwd,
environ=environ,
shortname='cloud_to_cloud:%s:%s_server:%s:%s' %
(language, server_name, test_case, transport_security),
timeout_seconds=_TEST_TIMEOUT,
flake_retries=4 if args.allow_flakes else 0,
timeout_retries=2 if args.allow_flakes else 0,
kill_handler=_job_kill_handler)
if docker_image:
test_job.container_name = container_name
return test_job
def server_jobspec(language,
docker_image,
transport_security='tls',
manual_cmd_log=None):
"""Create jobspec for running a server"""
container_name = dockerjob.random_name(
'interop_server_%s' % language.safename)
server_cmd = ['--port=%s' % _DEFAULT_SERVER_PORT]
if transport_security == 'tls':
server_cmd += ['--use_tls=true']
elif transport_security == 'alts':
server_cmd += ['--use_tls=false', '--use_alts=true']
elif transport_security == 'insecure':
server_cmd += ['--use_tls=false']
else:
print('Invalid transport security option %s in server_jobspec.' %
transport_security)
sys.exit(1)
cmdline = bash_cmdline(language.server_cmd(server_cmd))
environ = language.global_env()
docker_args = ['--name=%s' % container_name]
if language.safename == 'http2':
# we are running the http2 interop server. Open next N ports beginning
# with the server port. These ports are used for http2 interop test
# (one test case per port).
docker_args += list(
itertools.chain.from_iterable(
('-p', str(_DEFAULT_SERVER_PORT + i))
for i in range(len(_HTTP2_SERVER_TEST_CASES))))
# Enable docker's healthcheck mechanism.
# This runs a Python script inside the container every second. The script
# pings the http2 server to verify it is ready. The 'health-retries' flag
# specifies the number of consecutive failures before docker will report
# the container's status as 'unhealthy'. Prior to the first 'health_retries'
# failures or the first success, the status will be 'starting'. 'docker ps'
# or 'docker inspect' can be used to see the health of the container on the
# command line.
docker_args += [
'--health-cmd=python test/http2_test/http2_server_health_check.py '
'--server_host=%s --server_port=%d' % ('localhost',
_DEFAULT_SERVER_PORT),
'--health-interval=1s',
'--health-retries=5',
'--health-timeout=10s',
]
else:
docker_args += ['-p', str(_DEFAULT_SERVER_PORT)]
docker_cmdline = docker_run_cmdline(
cmdline,
image=docker_image,
cwd=language.server_cwd,
environ=environ,
docker_args=docker_args)
if manual_cmd_log is not None:
if manual_cmd_log == []:
manual_cmd_log.append(
'echo "Testing ${docker_image:=%s}"' % docker_image)
manual_cmd_log.append(manual_cmdline(docker_cmdline, docker_image))
server_job = jobset.JobSpec(
cmdline=docker_cmdline,
environ=environ,
shortname='interop_server_%s' % language,
timeout_seconds=30 * 60)
server_job.container_name = container_name
return server_job
def build_interop_image_jobspec(language, tag=None):
"""Creates jobspec for building interop docker image for a language"""
if not tag:
tag = 'grpc_interop_%s:%s' % (language.safename, uuid.uuid4())
env = {
'INTEROP_IMAGE': tag,
'BASE_NAME': 'grpc_interop_%s' % language.safename
}
if not args.travis:
env['TTY_FLAG'] = '-t'
# This env variable is used to get around the github rate limit
# error when running the PHP `composer install` command
host_file = '%s/.composer/auth.json' % os.environ['HOME']
if language.safename == 'php' and os.path.exists(host_file):
env['BUILD_INTEROP_DOCKER_EXTRA_ARGS'] = \
'-v %s:/root/.composer/auth.json:ro' % host_file
build_job = jobset.JobSpec(
cmdline=['tools/run_tests/dockerize/build_interop_image.sh'],
environ=env,
shortname='build_docker_%s' % (language),
timeout_seconds=30 * 60)
build_job.tag = tag
return build_job
def aggregate_http2_results(stdout):
match = re.search(r'\{"cases[^\]]*\]\}', stdout)
if not match:
return None
results = json.loads(match.group(0))
skipped = 0
passed = 0
failed = 0
failed_cases = []
for case in results['cases']:
if case.get('skipped', False):
skipped += 1
else:
if case.get('passed', False):
passed += 1
else:
failed += 1
failed_cases.append(case.get('name', "NONAME"))
return {
'passed': passed,
'failed': failed,
'skipped': skipped,
'failed_cases': ', '.join(failed_cases),
'percent': 1.0 * passed / (passed + failed)
}
# A dictionary of prod servers to test.
prod_servers = {
'default': 'grpc-test.sandbox.googleapis.com',
'gateway_v4': 'grpc-test4.sandbox.googleapis.com',
}
argp = argparse.ArgumentParser(description='Run interop tests.')
argp.add_argument(
'-l',
'--language',
choices=['all'] + sorted(_LANGUAGES),
nargs='+',
default=['all'],
help='Clients to run. Objc client can be only run on OSX.')
argp.add_argument('-j', '--jobs', default=multiprocessing.cpu_count(), type=int)
argp.add_argument(
'--cloud_to_prod',
default=False,
action='store_const',
const=True,
help='Run cloud_to_prod tests.')
argp.add_argument(
'--cloud_to_prod_auth',
default=False,
action='store_const',
const=True,
help='Run cloud_to_prod_auth tests.')
argp.add_argument(
'--prod_servers',
choices=prod_servers.keys(),
default=['default'],
nargs='+',
help=('The servers to run cloud_to_prod and '
'cloud_to_prod_auth tests against.'))
argp.add_argument(
'-s',
'--server',
choices=['all'] + sorted(_SERVERS),
nargs='+',
help='Run cloud_to_cloud servers in a separate docker ' +
'image. Servers can only be started automatically if ' +
'--use_docker option is enabled.',
default=[])
argp.add_argument(
'--override_server',
action='append',
type=lambda kv: kv.split('='),
help=
'Use servername=HOST:PORT to explicitly specify a server. E.g. csharp=localhost:50000',
default=[])
argp.add_argument(
'--service_account_key_file',
type=str,
help=
'Override the default service account key file to use for auth interop tests.',
default=None)
argp.add_argument(
'-t', '--travis', default=False, action='store_const', const=True)
argp.add_argument(
'-v', '--verbose', default=False, action='store_const', const=True)
argp.add_argument(
'--use_docker',
default=False,
action='store_const',
const=True,
help='Run all the interop tests under docker. That provides ' +
'additional isolation and prevents the need to install ' +
'language specific prerequisites. Only available on Linux.')
argp.add_argument(
'--allow_flakes',
default=False,
action='store_const',
const=True,
help=
'Allow flaky tests to show as passing (re-runs failed tests up to five times)'
)
argp.add_argument(
'--manual_run',
default=False,
action='store_const',
const=True,
help='Prepare things for running interop tests manually. ' +
'Preserve docker images after building them and skip '
'actually running the tests. Only print commands to run by ' + 'hand.')
argp.add_argument(
'--http2_interop',
default=False,
action='store_const',
const=True,
help='Enable HTTP/2 client edge case testing. (Bad client, good server)')
argp.add_argument(
'--http2_server_interop',
default=False,
action='store_const',
const=True,
help=
'Enable HTTP/2 server edge case testing. (Includes positive and negative tests'
)
argp.add_argument(
'--transport_security',
choices=_TRANSPORT_SECURITY_OPTIONS,
default='tls',
type=str,
nargs='?',
const=True,
help='Which transport security mechanism to use.')
argp.add_argument(
'--skip_compute_engine_creds',
default=False,
action='store_const',
const=True,
help='Skip auth tests requiring access to compute engine credentials.')
argp.add_argument(
'--internal_ci',
default=False,
action='store_const',
const=True,
help=(
'(Deprecated, has no effect) Put reports into subdirectories to improve '
'presentation of results by Internal CI.'))
argp.add_argument(
'--bq_result_table',
default='',
type=str,
nargs='?',
help='Upload test results to a specified BQ table.')
args = argp.parse_args()
servers = set(
s
for s in itertools.chain.from_iterable(
_SERVERS if x == 'all' else [x] for x in args.server))
# ALTS servers are only available for certain languages.
if args.transport_security == 'alts':
servers = servers.intersection(_SERVERS_FOR_ALTS_TEST_CASES)
if args.use_docker:
if not args.travis:
print('Seen --use_docker flag, will run interop tests under docker.')
print('')
print(
'IMPORTANT: The changes you are testing need to be locally committed'
)
print(
'because only the committed changes in the current branch will be')
print('copied to the docker environment.')
time.sleep(5)
if args.manual_run and not args.use_docker:
print('--manual_run is only supported with --use_docker option enabled.')
sys.exit(1)
if not args.use_docker and servers:
print(
'Running interop servers is only supported with --use_docker option enabled.'
)
sys.exit(1)
# we want to include everything but objc in 'all'
# because objc won't run on non-mac platforms
all_but_objc = set(six.iterkeys(_LANGUAGES)) - set(['objc'])
languages = set(_LANGUAGES[l]
for l in itertools.chain.from_iterable(
all_but_objc if x == 'all' else [x] for x in args.language))
# ALTS interop clients are only available for certain languages.
if args.transport_security == 'alts':
alts_languages = set(_LANGUAGES[l] for l in _LANGUAGES_FOR_ALTS_TEST_CASES)
languages = languages.intersection(alts_languages)
languages_http2_clients_for_http2_server_interop = set()
if args.http2_server_interop:
languages_http2_clients_for_http2_server_interop = set(
_LANGUAGES[l]
for l in _LANGUAGES_WITH_HTTP2_CLIENTS_FOR_HTTP2_SERVER_TEST_CASES
if 'all' in args.language or l in args.language)
http2Interop = Http2Client() if args.http2_interop else None
http2InteropServer = Http2Server() if args.http2_server_interop else None
docker_images = {}
if args.use_docker:
# languages for which to build docker images
languages_to_build = set(
_LANGUAGES[k]
for k in set([str(l) for l in languages] + [s for s in servers]))
languages_to_build = languages_to_build | languages_http2_clients_for_http2_server_interop
if args.http2_interop:
languages_to_build.add(http2Interop)
if args.http2_server_interop:
languages_to_build.add(http2InteropServer)
build_jobs = []
for l in languages_to_build:
if str(l) == 'objc':
# we don't need to build a docker image for objc
continue
job = build_interop_image_jobspec(l)
docker_images[str(l)] = job.tag
build_jobs.append(job)
if build_jobs:
jobset.message(
'START', 'Building interop docker images.', do_newline=True)
if args.verbose:
print('Jobs to run: \n%s\n' % '\n'.join(str(j) for j in build_jobs))
num_failures, build_resultset = jobset.run(
build_jobs, newline_on_success=True, maxjobs=args.jobs)
report_utils.render_junit_xml_report(build_resultset,
_DOCKER_BUILD_XML_REPORT)
if num_failures == 0:
jobset.message(
'SUCCESS',
'All docker images built successfully.',
do_newline=True)
else:
jobset.message(
'FAILED',
'Failed to build interop docker images.',
do_newline=True)
for image in six.itervalues(docker_images):
dockerjob.remove_image(image, skip_nonexistent=True)
sys.exit(1)
server_manual_cmd_log = [] if args.manual_run else None
client_manual_cmd_log = [] if args.manual_run else None
# Start interop servers.
server_jobs = {}
server_addresses = {}
try:
for s in servers:
lang = str(s)
spec = server_jobspec(
_LANGUAGES[lang],
docker_images.get(lang),
args.transport_security,
manual_cmd_log=server_manual_cmd_log)
if not args.manual_run:
job = dockerjob.DockerJob(spec)
server_jobs[lang] = job
server_addresses[lang] = ('localhost',
job.mapped_port(_DEFAULT_SERVER_PORT))
else:
# don't run the server, set server port to a placeholder value
server_addresses[lang] = ('localhost', '${SERVER_PORT}')
http2_server_job = None
if args.http2_server_interop:
# launch a HTTP2 server emulator that creates edge cases
lang = str(http2InteropServer)
spec = server_jobspec(
http2InteropServer,
docker_images.get(lang),
manual_cmd_log=server_manual_cmd_log)
if not args.manual_run:
http2_server_job = dockerjob.DockerJob(spec)
server_jobs[lang] = http2_server_job
else:
# don't run the server, set server port to a placeholder value
server_addresses[lang] = ('localhost', '${SERVER_PORT}')
jobs = []
if args.cloud_to_prod:
if args.transport_security not in ['tls', 'google_default_credentials']:
print(
'TLS or google default credential is always enabled for cloud_to_prod scenarios.'
)
for server_host_nickname in args.prod_servers:
for language in languages:
for test_case in _TEST_CASES:
if not test_case in language.unimplemented_test_cases():
if not test_case in _SKIP_ADVANCED + _SKIP_COMPRESSION + _SKIP_SPECIAL_STATUS_MESSAGE:
tls_test_job = cloud_to_prod_jobspec(
language,
test_case,
server_host_nickname,
prod_servers[server_host_nickname],
docker_image=docker_images.get(str(language)),
manual_cmd_log=client_manual_cmd_log,
service_account_key_file=args.
service_account_key_file,
transport_security='tls')
jobs.append(tls_test_job)
if str(language) in [
'c++', 'go', 'java', 'javaokhttp'
]:
google_default_creds_test_job = cloud_to_prod_jobspec(
language,
test_case,
server_host_nickname,
prod_servers[server_host_nickname],
docker_image=docker_images.get(
str(language)),
manual_cmd_log=client_manual_cmd_log,
service_account_key_file=args.
service_account_key_file,
transport_security=
'google_default_credentials')
jobs.append(google_default_creds_test_job)
if args.http2_interop:
for test_case in _HTTP2_TEST_CASES:
test_job = cloud_to_prod_jobspec(
http2Interop,
test_case,
server_host_nickname,
prod_servers[server_host_nickname],
docker_image=docker_images.get(str(http2Interop)),
manual_cmd_log=client_manual_cmd_log,
service_account_key_file=args.service_account_key_file,
transport_security=args.transport_security)
jobs.append(test_job)
if args.cloud_to_prod_auth:
if args.transport_security not in ['tls', 'google_default_credentials']:
print(
'TLS or google default credential is always enabled for cloud_to_prod scenarios.'
)
for server_host_nickname in args.prod_servers:
for language in languages:
for test_case in _AUTH_TEST_CASES:
if (not args.skip_compute_engine_creds or
not compute_engine_creds_required(
language, test_case)):
if not test_case in language.unimplemented_test_cases():
tls_test_job = cloud_to_prod_jobspec(
language,
test_case,
server_host_nickname,
prod_servers[server_host_nickname],
docker_image=docker_images.get(str(language)),
auth=True,
manual_cmd_log=client_manual_cmd_log,
service_account_key_file=args.
service_account_key_file,
transport_security='tls')
jobs.append(tls_test_job)
if str(language) in [
'go'
]: # Add more languages to the list to turn on tests.
google_default_creds_test_job = cloud_to_prod_jobspec(
language,
test_case,
server_host_nickname,
prod_servers[server_host_nickname],
docker_image=docker_images.get(
str(language)),
auth=True,
manual_cmd_log=client_manual_cmd_log,
service_account_key_file=args.
service_account_key_file,
transport_security=
'google_default_credentials')
jobs.append(google_default_creds_test_job)
for server in args.override_server:
server_name = server[0]
(server_host, server_port) = server[1].split(':')
server_addresses[server_name] = (server_host, server_port)
for server_name, server_address in server_addresses.items():
(server_host, server_port) = server_address
server_language = _LANGUAGES.get(server_name, None)
skip_server = [] # test cases unimplemented by server
if server_language:
skip_server = server_language.unimplemented_test_cases_server()
for language in languages:
for test_case in _TEST_CASES:
if not test_case in language.unimplemented_test_cases():
if not test_case in skip_server:
test_job = cloud_to_cloud_jobspec(
language,
test_case,
server_name,
server_host,
server_port,
docker_image=docker_images.get(str(language)),
transport_security=args.transport_security,
manual_cmd_log=client_manual_cmd_log)
jobs.append(test_job)
if args.http2_interop:
for test_case in _HTTP2_TEST_CASES:
if server_name == "go":
# TODO(carl-mastrangelo): Reenable after https://github.com/grpc/grpc-go/issues/434
continue
test_job = cloud_to_cloud_jobspec(
http2Interop,
test_case,
server_name,
server_host,
server_port,
docker_image=docker_images.get(str(http2Interop)),
transport_security=args.transport_security,
manual_cmd_log=client_manual_cmd_log)
jobs.append(test_job)
if args.http2_server_interop:
if not args.manual_run:
http2_server_job.wait_for_healthy(timeout_seconds=600)
for language in languages_http2_clients_for_http2_server_interop:
for test_case in set(_HTTP2_SERVER_TEST_CASES) - set(
_HTTP2_SERVER_TEST_CASES_THAT_USE_GRPC_CLIENTS):
offset = sorted(_HTTP2_SERVER_TEST_CASES).index(test_case)
server_port = _DEFAULT_SERVER_PORT + offset
if not args.manual_run:
server_port = http2_server_job.mapped_port(server_port)
test_job = cloud_to_cloud_jobspec(
language,
test_case,
str(http2InteropServer),
'localhost',
server_port,
docker_image=docker_images.get(str(language)),
manual_cmd_log=client_manual_cmd_log)
jobs.append(test_job)
for language in languages:
# HTTP2_SERVER_TEST_CASES_THAT_USE_GRPC_CLIENTS is a subset of
# HTTP_SERVER_TEST_CASES, in which clients use their gRPC interop clients rather
# than specialized http2 clients, reusing existing test implementations.
# For example, in the "data_frame_padding" test, use language's gRPC
# interop clients and make them think that theyre running "large_unary"
# test case. This avoids implementing a new test case in each language.
for test_case in _HTTP2_SERVER_TEST_CASES_THAT_USE_GRPC_CLIENTS:
if test_case not in language.unimplemented_test_cases():
offset = sorted(_HTTP2_SERVER_TEST_CASES).index(test_case)
server_port = _DEFAULT_SERVER_PORT + offset
if not args.manual_run:
server_port = http2_server_job.mapped_port(server_port)
if args.transport_security != 'insecure':
print(
('Creating grpc client to http2 server test case '
'with insecure connection, even though '
'args.transport_security is not insecure. Http2 '
'test server only supports insecure connections.'))
test_job = cloud_to_cloud_jobspec(
language,
test_case,
str(http2InteropServer),
'localhost',
server_port,
docker_image=docker_images.get(str(language)),
transport_security='insecure',
manual_cmd_log=client_manual_cmd_log)
jobs.append(test_job)
if not jobs:
print('No jobs to run.')
for image in six.itervalues(docker_images):
dockerjob.remove_image(image, skip_nonexistent=True)
sys.exit(1)
if args.manual_run:
print('All tests will skipped --manual_run option is active.')
if args.verbose:
print('Jobs to run: \n%s\n' % '\n'.join(str(job) for job in jobs))
num_failures, resultset = jobset.run(
jobs,
newline_on_success=True,
maxjobs=args.jobs,
skip_jobs=args.manual_run)
if args.bq_result_table and resultset:
upload_interop_results_to_bq(resultset, args.bq_result_table)
if num_failures:
jobset.message('FAILED', 'Some tests failed', do_newline=True)
else:
jobset.message('SUCCESS', 'All tests passed', do_newline=True)
write_cmdlog_maybe(server_manual_cmd_log, 'interop_server_cmds.sh')
write_cmdlog_maybe(client_manual_cmd_log, 'interop_client_cmds.sh')
report_utils.render_junit_xml_report(resultset, _TESTS_XML_REPORT)
for name, job in resultset.items():
if "http2" in name:
job[0].http2results = aggregate_http2_results(job[0].message)
http2_server_test_cases = (_HTTP2_SERVER_TEST_CASES
if args.http2_server_interop else [])
if num_failures:
sys.exit(1)
else:
sys.exit(0)
finally:
# Check if servers are still running.
for server, job in server_jobs.items():
if not job.is_running():
print('Server "%s" has exited prematurely.' % server)
dockerjob.finish_jobs([j for j in six.itervalues(server_jobs)])
for image in six.itervalues(docker_images):
if not args.manual_run:
print('Removing docker image %s' % image)
dockerjob.remove_image(image)
else:
print('Preserving docker image: %s' % image)
| []
| []
| [
"HOME"
]
| [] | ["HOME"] | python | 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 = "ddd_shop"
copyright = """2021, Duncan_Ireri"""
author = "Duncan_Ireri"
# -- 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 | |
episodes/040/live/vendor/cloud.google.com/go/profiler/profiler.go | // Copyright 2017 Google Inc. 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 profiler is a client for the Stackdriver Profiler service.
//
// This package is still experimental and subject to change.
//
// Usage example:
//
// import "cloud.google.com/go/profiler"
// ...
// if err := profiler.Start(profiler.Config{Service: "my-service"}); err != nil {
// // TODO: Handle error.
// }
//
// Calling Start will start a goroutine to collect profiles and upload to
// the profiler server, at the rhythm specified by the server.
//
// The caller must provide the service string in the config, and may provide
// other information as well. See Config for details.
//
// Profiler has CPU, heap and goroutine profiling enabled by default. Mutex
// profiling can be enabled in the config. Note that goroutine and mutex
// profiles are shown as "threads" and "contention" profiles in the profiler
// UI.
package profiler
import (
"bytes"
"errors"
"fmt"
"log"
"os"
"runtime"
"runtime/pprof"
"sync"
"time"
gcemd "cloud.google.com/go/compute/metadata"
"cloud.google.com/go/internal/version"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/google/pprof/profile"
gax "github.com/googleapis/gax-go"
"golang.org/x/net/context"
"google.golang.org/api/option"
gtransport "google.golang.org/api/transport/grpc"
pb "google.golang.org/genproto/googleapis/devtools/cloudprofiler/v2"
edpb "google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
grpcmd "google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
var (
config Config
startOnce sync.Once
mutexEnabled bool
// The functions below are stubbed to be overrideable for testing.
getProjectID = gcemd.ProjectID
getInstanceName = gcemd.InstanceName
getZone = gcemd.Zone
startCPUProfile = pprof.StartCPUProfile
stopCPUProfile = pprof.StopCPUProfile
writeHeapProfile = pprof.WriteHeapProfile
sleep = gax.Sleep
dialGRPC = gtransport.Dial
onGCE = gcemd.OnGCE
)
const (
apiAddress = "cloudprofiler.googleapis.com:443"
xGoogAPIMetadata = "x-goog-api-client"
zoneNameLabel = "zone"
versionLabel = "version"
instanceLabel = "instance"
scope = "https://www.googleapis.com/auth/monitoring.write"
initialBackoff = time.Second
// Ensure the agent will recover within 1 hour.
maxBackoff = time.Hour
backoffMultiplier = 1.3 // Backoff envelope increases by this factor on each retry.
retryInfoMetadata = "google.rpc.retryinfo-bin"
)
// Config is the profiler configuration.
type Config struct {
// Service (or deprecated Target) must be provided to start the profiler.
// It specifies the name of the service under which the profiled data
// will be recorded and exposed at the Profiler UI for the project.
// You can specify an arbitrary string, but see Deployment.target at
// https://github.com/googleapis/googleapis/blob/master/google/devtools/cloudprofiler/v2/profiler.proto
// for restrictions.
// NOTE: The string should be the same across different replicas of
// your service so that the globally constant profiling rate is
// maintained. Do not put things like PID or unique pod ID in the name.
Service string
// ServiceVersion is an optional field specifying the version of the
// service. It can be an arbitrary string. Profiler profiles
// once per minute for each version of each service in each zone.
// ServiceVersion defaults to an empty string.
ServiceVersion string
// DebugLogging enables detailed debug logging from profiler. It
// defaults to false.
DebugLogging bool
// MutexProfiling enables mutex profiling. It defaults to false.
// Note that mutex profiling is not supported by Go versions older
// than Go 1.8.
MutexProfiling bool
// When true, collecting the heap profiles is disabled.
NoHeapProfiling bool
// When true, collecting the goroutine profiles is disabled.
NoGoroutineProfiling bool
// ProjectID is the Cloud Console project ID to use instead of
// the one read from the VM metadata server.
//
// Set this if you are running the agent in your local environment
// or anywhere else outside of Google Cloud Platform.
ProjectID string
// APIAddr is the HTTP endpoint to use to connect to the profiler
// agent API. Defaults to the production environment, overridable
// for testing.
APIAddr string
// Target is deprecated, use Service instead.
Target string
instance string
zone string
}
// startError represents the error occured during the
// initializating and starting of the agent.
var startError error
// Start starts a goroutine to collect and upload profiles. The
// caller must provide the service string in the config. See
// Config for details. Start should only be called once. Any
// additional calls will be ignored.
func Start(cfg Config, options ...option.ClientOption) error {
startOnce.Do(func() {
startError = start(cfg, options...)
})
return startError
}
func start(cfg Config, options ...option.ClientOption) error {
if err := initializeConfig(cfg); err != nil {
debugLog("failed to initialize config: %v", err)
return err
}
if config.MutexProfiling {
if mutexEnabled = enableMutexProfiling(); !mutexEnabled {
return fmt.Errorf("mutex profiling is not supported by %s, requires Go 1.8 or later", runtime.Version())
}
}
ctx := context.Background()
opts := []option.ClientOption{
option.WithEndpoint(config.APIAddr),
option.WithScopes(scope),
}
opts = append(opts, options...)
conn, err := dialGRPC(ctx, opts...)
if err != nil {
debugLog("failed to dial GRPC: %v", err)
return err
}
a := initializeAgent(pb.NewProfilerServiceClient(conn))
go pollProfilerService(withXGoogHeader(ctx), a)
return nil
}
func debugLog(format string, e ...interface{}) {
if config.DebugLogging {
log.Printf(format, e...)
}
}
// agent polls the profiler server for instructions on behalf of a task,
// and collects and uploads profiles as requested.
type agent struct {
client pb.ProfilerServiceClient
deployment *pb.Deployment
profileLabels map[string]string
profileTypes []pb.ProfileType
}
// abortedBackoffDuration retrieves the retry duration from gRPC trailing
// metadata, which is set by the profiler server.
func abortedBackoffDuration(md grpcmd.MD) (time.Duration, error) {
elem := md[retryInfoMetadata]
if len(elem) <= 0 {
return 0, errors.New("no retry info")
}
var retryInfo edpb.RetryInfo
if err := proto.Unmarshal([]byte(elem[0]), &retryInfo); err != nil {
return 0, err
} else if time, err := ptypes.Duration(retryInfo.RetryDelay); err != nil {
return 0, err
} else {
if time < 0 {
return 0, errors.New("negative retry duration")
}
return time, nil
}
}
type retryer struct {
backoff gax.Backoff
md grpcmd.MD
}
func (r *retryer) Retry(err error) (time.Duration, bool) {
st, _ := status.FromError(err)
if st != nil && st.Code() == codes.Aborted {
dur, err := abortedBackoffDuration(r.md)
if err == nil {
return dur, true
}
debugLog("failed to get backoff duration: %v", err)
}
return r.backoff.Pause(), true
}
// createProfile talks to the profiler server to create profile. In
// case of error, the goroutine will sleep and retry. Sleep duration may
// be specified by the server. Otherwise it will be an exponentially
// increasing value, bounded by maxBackoff.
func (a *agent) createProfile(ctx context.Context) *pb.Profile {
req := pb.CreateProfileRequest{
Deployment: a.deployment,
ProfileType: a.profileTypes,
}
var p *pb.Profile
md := grpcmd.New(map[string]string{})
gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
var err error
p, err = a.client.CreateProfile(ctx, &req, grpc.Trailer(&md))
if err != nil {
debugLog("failed to create a profile, will retry: %v", err)
}
return err
}, gax.WithRetry(func() gax.Retryer {
return &retryer{
backoff: gax.Backoff{
Initial: initialBackoff,
Max: maxBackoff,
Multiplier: backoffMultiplier,
},
md: md,
}
}))
debugLog("successfully created profile %v", p.GetProfileType())
return p
}
func (a *agent) profileAndUpload(ctx context.Context, p *pb.Profile) {
var prof bytes.Buffer
pt := p.GetProfileType()
switch pt {
case pb.ProfileType_CPU:
duration, err := ptypes.Duration(p.Duration)
if err != nil {
debugLog("failed to get profile duration: %v", err)
return
}
if err := startCPUProfile(&prof); err != nil {
debugLog("failed to start CPU profile: %v", err)
return
}
sleep(ctx, duration)
stopCPUProfile()
case pb.ProfileType_HEAP:
if err := writeHeapProfile(&prof); err != nil {
debugLog("failed to write heap profile: %v", err)
return
}
case pb.ProfileType_THREADS:
if err := pprof.Lookup("goroutine").WriteTo(&prof, 0); err != nil {
debugLog("failed to create goroutine profile: %v", err)
return
}
case pb.ProfileType_CONTENTION:
duration, err := ptypes.Duration(p.Duration)
if err != nil {
debugLog("failed to get profile duration: %v", err)
return
}
if err := deltaMutexProfile(ctx, duration, &prof); err != nil {
debugLog("failed to create mutex profile: %v", err)
return
}
default:
debugLog("unexpected profile type: %v", pt)
return
}
// Starting Go 1.9 the profiles are symbolized by runtime/pprof.
// TODO(jianqiaoli): Remove the symbolization code when we decide to
// stop supporting Go 1.8.
if !shouldAssumeSymbolized && pt != pb.ProfileType_CONTENTION {
if err := parseAndSymbolize(&prof); err != nil {
debugLog("failed to symbolize profile: %v", err)
}
}
p.ProfileBytes = prof.Bytes()
p.Labels = a.profileLabels
req := pb.UpdateProfileRequest{Profile: p}
// Upload profile, discard profile in case of error.
debugLog("start uploading profile")
if _, err := a.client.UpdateProfile(ctx, &req); err != nil {
debugLog("failed to upload profile: %v", err)
}
}
// deltaMutexProfile writes mutex profile changes over a time period specified
// with 'duration' to 'prof'.
func deltaMutexProfile(ctx context.Context, duration time.Duration, prof *bytes.Buffer) error {
if !mutexEnabled {
return errors.New("mutex profiling is not enabled")
}
p0, err := mutexProfile()
if err != nil {
return err
}
sleep(ctx, duration)
p, err := mutexProfile()
if err != nil {
return err
}
// TODO(jianqiaoli): Remove this check when github.com/google/pprof/issues/242
// is fixed.
if len(p0.Mapping) > 0 {
p0.Scale(-1)
p, err = profile.Merge([]*profile.Profile{p0, p})
if err != nil {
return err
}
}
// The mutex profile is not symbolized by runtime.pprof until
// golang.org/issue/21474 is fixed in go1.10.
symbolize(p)
return p.Write(prof)
}
func mutexProfile() (*profile.Profile, error) {
p := pprof.Lookup("mutex")
if p == nil {
return nil, errors.New("mutex profiling is not supported")
}
var buf bytes.Buffer
if err := p.WriteTo(&buf, 0); err != nil {
return nil, err
}
return profile.Parse(&buf)
}
// withXGoogHeader sets the name and version of the application in
// the `x-goog-api-client` header passed on each request. Intended for
// use by Google-written clients.
func withXGoogHeader(ctx context.Context, keyval ...string) context.Context {
kv := append([]string{"gl-go", version.Go(), "gccl", version.Repo}, keyval...)
kv = append(kv, "gax", gax.Version, "grpc", grpc.Version)
md, _ := grpcmd.FromOutgoingContext(ctx)
md = md.Copy()
md[xGoogAPIMetadata] = []string{gax.XGoogHeader(kv...)}
return grpcmd.NewOutgoingContext(ctx, md)
}
func initializeAgent(c pb.ProfilerServiceClient) *agent {
labels := map[string]string{}
if config.zone != "" {
labels[zoneNameLabel] = config.zone
}
if config.ServiceVersion != "" {
labels[versionLabel] = config.ServiceVersion
}
d := &pb.Deployment{
ProjectId: config.ProjectID,
Target: config.Target,
Labels: labels,
}
profileLabels := map[string]string{}
if config.instance != "" {
profileLabels[instanceLabel] = config.instance
}
profileTypes := []pb.ProfileType{pb.ProfileType_CPU}
if !config.NoHeapProfiling {
profileTypes = append(profileTypes, pb.ProfileType_HEAP)
}
if !config.NoGoroutineProfiling {
profileTypes = append(profileTypes, pb.ProfileType_THREADS)
}
if mutexEnabled {
profileTypes = append(profileTypes, pb.ProfileType_CONTENTION)
}
return &agent{
client: c,
deployment: d,
profileLabels: profileLabels,
profileTypes: profileTypes,
}
}
func initializeConfig(cfg Config) error {
config = cfg
switch {
case config.Service != "":
config.Target = config.Service
case config.Target == "":
config.Target = os.Getenv("GAE_SERVICE")
}
if config.Target == "" {
return errors.New("service name must be specified in the configuration")
}
if config.ServiceVersion == "" {
config.ServiceVersion = os.Getenv("GAE_VERSION")
}
if projectID := os.Getenv("GOOGLE_CLOUD_PROJECT"); config.ProjectID == "" && projectID != "" {
// Cloud Shell and App Engine set this environment variable to the project
// ID, so use it if present. In case of App Engine the project ID is also
// available from the GCE metadata server, but by using the environment
// variable saves one request to the metadata server. The environment
// project ID is only used if no project ID is provided in the
// configuration.
config.ProjectID = projectID
}
if onGCE() {
var err error
if config.ProjectID == "" {
if config.ProjectID, err = getProjectID(); err != nil {
return fmt.Errorf("failed to get the project ID from Compute Engine: %v", err)
}
}
if config.zone, err = getZone(); err != nil {
return fmt.Errorf("failed to get zone from Compute Engine: %v", err)
}
if config.instance, err = getInstanceName(); err != nil {
return fmt.Errorf("failed to get instance from Compute Engine: %v", err)
}
} else {
if config.ProjectID == "" {
return fmt.Errorf("project ID must be specified in the configuration if running outside of GCP")
}
}
if config.APIAddr == "" {
config.APIAddr = apiAddress
}
return nil
}
// pollProfilerService starts an endless loop to poll the profiler
// server for instructions, and collects and uploads profiles as
// requested.
func pollProfilerService(ctx context.Context, a *agent) {
debugLog("profiler has started")
for {
p := a.createProfile(ctx)
a.profileAndUpload(ctx, p)
}
}
| [
"\"GAE_SERVICE\"",
"\"GAE_VERSION\"",
"\"GOOGLE_CLOUD_PROJECT\""
]
| []
| [
"GOOGLE_CLOUD_PROJECT",
"GAE_SERVICE",
"GAE_VERSION"
]
| [] | ["GOOGLE_CLOUD_PROJECT", "GAE_SERVICE", "GAE_VERSION"] | go | 3 | 0 | |
Alignment/APEEstimation/test/testApeestimator_cfg.py | import os
import FWCore.ParameterSet.Config as cms
##
## Setup command line options
##
import FWCore.ParameterSet.VarParsing as VarParsing
import sys
options = VarParsing.VarParsing ('standard')
options.register('sample', 'wlnu', VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.string, "Input sample")
options.register('isTest', True, VarParsing.VarParsing.multiplicity.singleton, VarParsing.VarParsing.varType.bool, "Test run")
# get and parse the command line arguments
if( hasattr(sys, "argv") ):
for args in sys.argv :
arg = args.split(',')
for val in arg:
val = val.split('=')
if(len(val)==2):
setattr(options,val[0], val[1])
print "Input sample: ", options.sample
print "Test run: ", options.isTest
##
## Process definition
##
process = cms.Process("ApeEstimator")
##
## Message Logger
##
process.load("FWCore.MessageService.MessageLogger_cfi")
process.MessageLogger.categories.append('SectorBuilder')
process.MessageLogger.categories.append('ResidualErrorBinning')
process.MessageLogger.categories.append('HitSelector')
process.MessageLogger.categories.append('CalculateAPE')
process.MessageLogger.categories.append('ApeEstimator')
#process.MessageLogger.categories.append('TrackRefitter')
process.MessageLogger.categories.append('AlignmentTrackSelector')
process.MessageLogger.cerr.INFO.limit = 0
process.MessageLogger.cerr.default.limit = -1 # Do not use =0, else all error messages (except those listed below) are supressed
process.MessageLogger.cerr.SectorBuilder = cms.untracked.PSet(limit = cms.untracked.int32(-1))
process.MessageLogger.cerr.HitSelector = cms.untracked.PSet(limit = cms.untracked.int32(-1))
process.MessageLogger.cerr.CalculateAPE = cms.untracked.PSet(limit = cms.untracked.int32(-1))
process.MessageLogger.cerr.ApeEstimator = cms.untracked.PSet(limit = cms.untracked.int32(-1))
process.MessageLogger.cerr.AlignmentTrackSelector = cms.untracked.PSet(limit = cms.untracked.int32(-1))
process.MessageLogger.cerr.FwkReport.reportEvery = 1000 ## really show only every 1000th
##
## Process options
##
process.options = cms.untracked.PSet(
wantSummary = cms.untracked.bool(True),
)
##
## Input sample definition
##
isData1 = isData2 = False
isData = False
isQcd = isWlnu = isZmumu = isZtautau = isZmumu10 = isZmumu20 = False
isMc = False
if options.sample == 'data1':
isData1 = True
isData = True
elif options.sample == 'data2':
isData2 = True
isData = True
elif options.sample == 'qcd':
isQcd = True
isMc = True
elif options.sample == 'wlnu':
isWlnu = True
isMc = True
elif options.sample == 'zmumu':
isZmumu = True
isMc = True
elif options.sample == 'ztautau':
isZtautau = True
isMc = True
elif options.sample == 'zmumu10':
isZmumu10 = True
isMc = True
elif options.sample == 'zmumu20':
isZmumu20 = True
isMc = True
else:
print 'ERROR --- incorrect data sammple: ', options.sample
exit(8888)
##
## Input Files
##
if isData1:
process.load("Alignment.APEEstimation.samples.Data_TkAlMuonIsolated_Run2011A_May10ReReco_ApeSkim_cff")
elif isData2:
process.load("Alignment.APEEstimationsamples.Data_TkAlMuonIsolated_Run2011A_PromptV4_ApeSkim_cff")
elif isQcd:
process.load("Alignment.APEEstimation.samples.Mc_TkAlMuonIsolated_Summer11_qcd_ApeSkim_cff")
elif isWlnu:
process.load("Alignment.APEEstimation.samples.Mc_WJetsToLNu_74XTest_ApeSkim_cff")
elif isZmumu10:
process.load("Alignment.APEEstimation.samples.Mc_TkAlMuonIsolated_Summer11_zmumu10_ApeSkim_cff")
elif isZmumu20:
process.load("Alignment.APEEstimation.samples.Mc_TkAlMuonIsolated_Summer11_zmumu20_ApeSkim_cff")
##
## Number of Events (should be after input file)
##
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )
if options.isTest: process.maxEvents.input = 10001
##
## Check run and event numbers for Dublicates --- only for real data
##
#process.source.duplicateCheckMode = cms.untracked.string("noDuplicateCheck")
#process.source.duplicateCheckMode = cms.untracked.string("checkEachFile")
process.source.duplicateCheckMode = cms.untracked.string("checkEachRealDataFile")
#process.source.duplicateCheckMode = cms.untracked.string("checkAllFilesOpened") # default value
##
## Whole Refitter Sequence
##
process.load("Alignment.APEEstimation.TrackRefitter_38T_cff")
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff')
from Configuration.AlCa.GlobalTag_condDBv2 import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_design', '')
##### To be used when running on Phys14MC with a CMSSW version > 72X
#process.GlobalTag.toGet = cms.VPSet(
# cms.PSet(
# record = cms.string("BeamSpotObjectsRcd"),
# tag = cms.string("Realistic8TeVCollisions_START50_V13_v1_mc"),
# connect = cms.untracked.string("frontier://FrontierProd/CMS_CONDITIONS"),
# )
#)
print "Using global tag "+process.GlobalTag.globaltag._value
##
## New pixel templates
##
process.GlobalTag.toGet = cms.VPSet(
cms.PSet(
record = cms.string("SiPixelTemplateDBObjectRcd"),
tag = cms.string("SiPixelTemplateDBObject_38T_v3_mc"),
connect = cms.untracked.string("frontier://FrontierProd/CMS_CONDITIONS"),
)
)
##
## Alignment and APE
##
import CalibTracker.Configuration.Common.PoolDBESSource_cfi
## Choose Alignment (w/o touching APE)
if isMc:
process.myTrackerAlignment = CalibTracker.Configuration.Common.PoolDBESSource_cfi.poolDBESSource.clone(
connect = 'frontier://FrontierProd/CMS_CONDITIONS', # or your sqlite file
toGet = [
cms.PSet(
record = cms.string('TrackerAlignmentRcd'),
tag = cms.string('TrackerIdealGeometry210_mc') # 'TrackerAlignment_2009_v2_offline'
),
],
)
process.es_prefer_trackerAlignment = cms.ESPrefer("PoolDBESSource","myTrackerAlignment")
process.es_prefer_trackerAlignment = cms.ESPrefer("PoolDBESSource","myTrackerAlignment")
if isData:
# Recent geometry
process.myTrackerAlignment = CalibTracker.Configuration.Common.PoolDBESSource_cfi.poolDBESSource.clone(
connect = 'frontier://FrontierProd/CMS_CONDITIONS',
toGet = [
cms.PSet(
record = cms.string('TrackerAlignmentRcd'),
tag = cms.string('TrackerAlignment_GR10_v6_offline'),
),
],
)
process.es_prefer_trackerAlignment = cms.ESPrefer("PoolDBESSource","myTrackerAlignment")
# Kinks and bows
process.myTrackerAlignmentKinksAndBows = CalibTracker.Configuration.Common.PoolDBESSource_cfi.poolDBESSource.clone(
connect = 'frontier://FrontierProd/CMS_CONDITIONS',
toGet = [
cms.PSet(
record = cms.string('TrackerSurfaceDeformationRcd'),
tag = cms.string('TrackerSurfaceDeformations_v1_offline'),
),
],
)
process.es_prefer_trackerAlignmentKinksAndBows = cms.ESPrefer("PoolDBESSource","myTrackerAlignmentKinksAndBows")
## APE (set to zero)
process.myTrackerAlignmentErr = CalibTracker.Configuration.Common.PoolDBESSource_cfi.poolDBESSource.clone(
connect = 'frontier://FrontierProd/CMS_CONDITIONS',
toGet = [
cms.PSet(
record = cms.string('TrackerAlignmentErrorExtendedRcd'),
tag = cms.string('TrackerIdealGeometryErrorsExtended210_mc')
),
],
)
process.es_prefer_trackerAlignmentErr = cms.ESPrefer("PoolDBESSource","myTrackerAlignmentErr")
##
## Trigger Selection
##
process.load("Alignment.APEEstimation.TriggerSelection_cff")
##
## ApeEstimator
##
from Alignment.APEEstimation.ApeEstimator_cff import *
process.ApeEstimator1 = ApeEstimator.clone(
#~ tjTkAssociationMapTag = "TrackRefitterHighPurityForApeEstimator",
tjTkAssociationMapTag = "TrackRefitterForApeEstimator",
maxTracksPerEvent = 0,
applyTrackCuts = False,
Sectors = RecentSectors,
analyzerMode = False,
calculateApe = True
)
process.ApeEstimator1.HitSelector.width = []
process.ApeEstimator1.HitSelector.maxIndex = []
process.ApeEstimator1.HitSelector.widthProj = []
process.ApeEstimator1.HitSelector.widthDiff = []
process.ApeEstimator1.HitSelector.edgeStrips = []
process.ApeEstimator1.HitSelector.sOverN = []
process.ApeEstimator1.HitSelector.maxCharge = []
process.ApeEstimator1.HitSelector.chargeOnEdges = []
process.ApeEstimator1.HitSelector.probX = []
process.ApeEstimator1.HitSelector.phiSensX = []
process.ApeEstimator1.HitSelector.phiSensY = []
process.ApeEstimator1.HitSelector.errXHit = []
process.ApeEstimator1.HitSelector.chargePixel = []
process.ApeEstimator1.HitSelector.widthX = []
process.ApeEstimator1.HitSelector.widthY = []
process.ApeEstimator1.HitSelector.logClusterProbability = []
process.ApeEstimator1.HitSelector.isOnEdge = []
process.ApeEstimator1.HitSelector.qBin = []
process.ApeEstimator2 = process.ApeEstimator1.clone(
Sectors = ValidationSectors,
analyzerMode = True,
calculateApe = False,
)
process.ApeEstimator3 = process.ApeEstimator2.clone(
zoomHists = False,
)
##
## Output File Configuration
##
outputName = os.environ['CMSSW_BASE'] + '/src/Alignment/APEEstimation/hists/'
if options.isTest:
outputName = outputName + 'test_'
outputName = outputName + options.sample + '.root'
process.TFileService = cms.Service("TFileService",
fileName = cms.string(outputName),
closeFileFast = cms.untracked.bool(True)
)
##
## Path
##
process.p = cms.Path(
process.TriggerSelectionSequence*
process.RefitterHighPuritySequence*
(process.ApeEstimator1+
process.ApeEstimator2+
process.ApeEstimator3
)
)
| []
| []
| [
"CMSSW_BASE"
]
| [] | ["CMSSW_BASE"] | python | 1 | 0 | |
minify_test.go | package minify
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"regexp"
"strings"
"testing"
"github.com/dtrenin7/test"
)
var errDummy = errors.New("dummy error")
// from os/exec/exec_test.go
func helperCommand(t *testing.T, s ...string) *exec.Cmd {
cs := []string{"-test.run=TestHelperProcess", "--"}
cs = append(cs, s...)
cmd := exec.Command(os.Args[0], cs...)
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
return cmd
}
////////////////////////////////////////////////////////////////
var m *M
func init() {
m = New()
m.AddFunc("dummy/copy", func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
io.Copy(w, r)
return nil
})
m.AddFunc("dummy/nil", func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
return nil
})
m.AddFunc("dummy/err", func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
return errDummy
})
m.AddFunc("dummy/charset", func(m *M, w io.Writer, r io.Reader, params map[string]string) error {
w.Write([]byte(params["charset"]))
return nil
})
m.AddFunc("dummy/params", func(m *M, w io.Writer, r io.Reader, params map[string]string) error {
return m.Minify(params["type"]+"/"+params["sub"], w, r)
})
m.AddFunc("type/sub", func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
w.Write([]byte("type/sub"))
return nil
})
m.AddFuncRegexp(regexp.MustCompile("^type/.+$"), func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
w.Write([]byte("type/*"))
return nil
})
m.AddFuncRegexp(regexp.MustCompile("^.+/.+$"), func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
w.Write([]byte("*/*"))
return nil
})
}
func TestMinify(t *testing.T) {
test.T(t, m.Minify("?", nil, nil), ErrNotExist, "minifier doesn't exist")
test.T(t, m.Minify("dummy/nil", nil, nil), nil)
test.T(t, m.Minify("dummy/err", nil, nil), errDummy)
b := []byte("test")
out, err := m.Bytes("dummy/nil", b)
test.T(t, err, nil)
test.Bytes(t, out, []byte{}, "dummy/nil returns empty byte slice")
out, err = m.Bytes("?", b)
test.T(t, err, ErrNotExist, "minifier doesn't exist")
test.Bytes(t, out, b, "return input when minifier doesn't exist")
s := "test"
out2, err := m.String("dummy/nil", s)
test.T(t, err, nil)
test.String(t, out2, "", "dummy/nil returns empty string")
out2, err = m.String("?", s)
test.T(t, err, ErrNotExist, "minifier doesn't exist")
test.String(t, out2, s, "return input when minifier doesn't exist")
}
type DummyMinifier struct{}
func (d *DummyMinifier) Minify(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
return errDummy
}
func TestAdd(t *testing.T) {
mAdd := New()
r := bytes.NewBufferString("test")
w := &bytes.Buffer{}
mAdd.Add("dummy/err", &DummyMinifier{})
test.T(t, mAdd.Minify("dummy/err", nil, nil), errDummy)
mAdd.AddRegexp(regexp.MustCompile("err1$"), &DummyMinifier{})
test.T(t, mAdd.Minify("dummy/err1", nil, nil), errDummy)
mAdd.AddFunc("dummy/err", func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
return errDummy
})
test.T(t, mAdd.Minify("dummy/err", nil, nil), errDummy)
mAdd.AddFuncRegexp(regexp.MustCompile("err2$"), func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
return errDummy
})
test.T(t, mAdd.Minify("dummy/err2", nil, nil), errDummy)
mAdd.AddCmd("dummy/copy", helperCommand(t, "dummy/copy"))
mAdd.AddCmd("dummy/err", helperCommand(t, "dummy/err"))
mAdd.AddCmdRegexp(regexp.MustCompile("err6$"), helperCommand(t, "werr6"))
test.T(t, mAdd.Minify("dummy/copy", w, r), nil)
test.String(t, w.String(), "test", "dummy/copy command returns input")
s := mAdd.Minify("dummy/err", w, r).Error()
test.String(t, s[len(s)-13:], "exit status 1", "command returns status 1 for dummy/err")
s = mAdd.Minify("werr6", w, r).Error()
test.String(t, s[len(s)-13:], "exit status 2", "command returns status 2 when minifier doesn't exist")
s = mAdd.Minify("stderr6", w, r).Error()
test.String(t, s[len(s)-13:], "exit status 2", "command returns status 2 when minifier doesn't exist")
}
func TestMatch(t *testing.T) {
pattern, params, _ := m.Match("dummy/copy; a=b")
test.String(t, pattern, "dummy/copy")
test.String(t, params["a"], "b")
pattern, _, _ = m.Match("type/foobar")
test.String(t, pattern, "^type/.+$")
_, _, minifier := m.Match("dummy/")
test.That(t, minifier == nil)
}
func TestWildcard(t *testing.T) {
mimetypeTests := []struct {
mimetype string
expected string
}{
{"type/sub", "type/sub"},
{"type/*", "type/*"},
{"*/*", "*/*"},
{"type/sub2", "type/*"},
{"type2/sub", "*/*"},
{"dummy/charset;charset=UTF-8", "UTF-8"},
{"dummy/charset; charset = UTF-8 ", "UTF-8"},
{"dummy/params;type=type;sub=two2", "type/*"},
}
for _, tt := range mimetypeTests {
r := bytes.NewBufferString("")
w := &bytes.Buffer{}
err := m.Minify(tt.mimetype, w, r)
test.Error(t, err)
test.Minify(t, tt.mimetype, nil, w.String(), tt.expected)
}
}
func TestReader(t *testing.T) {
m := New()
m.AddFunc("dummy/dummy", func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
_, err := io.Copy(w, r)
return err
})
m.AddFunc("dummy/err", func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
return errDummy
})
w := &bytes.Buffer{}
r := bytes.NewBufferString("test")
mr := m.Reader("dummy/dummy", r)
_, err := io.Copy(w, mr)
test.Error(t, err)
test.String(t, w.String(), "test", "equal input after dummy minify reader")
mr = m.Reader("dummy/err", r)
_, err = io.Copy(w, mr)
test.T(t, err, errDummy)
}
func TestWriter(t *testing.T) {
m := New()
m.AddFunc("dummy/dummy", func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
_, err := io.Copy(w, r)
return err
})
m.AddFunc("dummy/err", func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
return errDummy
})
m.AddFunc("dummy/late-err", func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
_, _ = ioutil.ReadAll(r)
return errDummy
})
w := &bytes.Buffer{}
mw := m.Writer("dummy/dummy", w)
_, _ = mw.Write([]byte("test"))
test.Error(t, mw.Close())
test.String(t, w.String(), "test", "equal input after dummy minify writer")
w = &bytes.Buffer{}
mw = m.Writer("dummy/err", w)
_, _ = mw.Write([]byte("test"))
test.T(t, mw.Close(), errDummy)
test.String(t, w.String(), "test", "equal input after dummy minify writer")
w = &bytes.Buffer{}
mw = m.Writer("dummy/late-err", w)
_, _ = mw.Write([]byte("test"))
test.T(t, mw.Close(), errDummy)
test.String(t, w.String(), "")
}
type responseWriter struct {
writer io.Writer
header http.Header
}
func (w *responseWriter) Header() http.Header {
return w.header
}
func (w *responseWriter) WriteHeader(_ int) {}
func (w *responseWriter) Write(b []byte) (int, error) {
return w.writer.Write(b)
}
func TestResponseWriter(t *testing.T) {
m := New()
m.AddFunc("text/html", func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
_, err := io.Copy(w, r)
return err
})
b := &bytes.Buffer{}
w := &responseWriter{b, http.Header{}}
r := &http.Request{RequestURI: "/index.html"}
mw := m.ResponseWriter(w, r)
test.Error(t, mw.Close())
_, _ = mw.Write([]byte("test"))
test.Error(t, mw.Close())
test.String(t, b.String(), "test", "equal input after dummy minify response writer")
b = &bytes.Buffer{}
w = &responseWriter{b, http.Header{}}
r = &http.Request{RequestURI: "/index"}
mw = m.ResponseWriter(w, r)
mw.Header().Add("Content-Type", "text/html")
_, _ = mw.Write([]byte("test"))
mw.WriteHeader(http.StatusForbidden)
test.Error(t, mw.Close())
test.String(t, b.String(), "test", "equal input after dummy minify response writer")
}
func TestMiddleware(t *testing.T) {
m := New()
m.AddFunc("text/html", func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
_, err := io.Copy(w, r)
return err
})
b := &bytes.Buffer{}
w := &responseWriter{b, http.Header{}}
r := &http.Request{RequestURI: "/index.html"}
m.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("test"))
})).ServeHTTP(w, r)
test.String(t, b.String(), "test", "equal input after dummy minify middleware")
}
func TestHelperProcess(*testing.T) {
if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
return
}
args := os.Args
for len(args) > 0 {
if args[0] == "--" {
args = args[1:]
break
}
args = args[1:]
}
if len(args) == 0 {
fmt.Fprintf(os.Stderr, "No command\n")
os.Exit(2)
}
switch args[0] {
case "dummy/copy":
io.Copy(os.Stdout, os.Stdin)
case "dummy/err":
os.Exit(1)
default:
os.Exit(2)
}
os.Exit(0)
}
////////////////////////////////////////////////////////////////
func ExampleM_Minify_custom() {
m := New()
m.AddFunc("text/plain", func(m *M, w io.Writer, r io.Reader, _ map[string]string) error {
// remove all newlines and spaces
rb := bufio.NewReader(r)
for {
line, err := rb.ReadString('\n')
if err != nil && err != io.EOF {
return err
}
if _, errws := io.WriteString(w, strings.Replace(line, " ", "", -1)); errws != nil {
return errws
}
if err == io.EOF {
break
}
}
return nil
})
in := "Because my coffee was too cold, I heated it in the microwave."
out, err := m.String("text/plain", in)
if err != nil {
panic(err)
}
fmt.Println(out)
// Output: Becausemycoffeewastoocold,Iheateditinthemicrowave.
}
func ExampleM_Reader() {
b := bytes.NewReader([]byte("input"))
m := New()
// add minfiers
r := m.Reader("mime/type", b)
if _, err := io.Copy(os.Stdout, r); err != nil {
if _, err := io.Copy(os.Stdout, b); err != nil {
panic(err)
}
}
}
func ExampleM_Writer() {
m := New()
// add minfiers
w := m.Writer("mime/type", os.Stdout)
if _, err := w.Write([]byte("input")); err != nil {
panic(err)
}
if err := w.Close(); err != nil {
panic(err)
}
}
| [
"\"GO_WANT_HELPER_PROCESS\""
]
| []
| [
"GO_WANT_HELPER_PROCESS"
]
| [] | ["GO_WANT_HELPER_PROCESS"] | go | 1 | 0 | |
vendor/k8s.io/kubernetes/pkg/kubectl/cmd/diff.go | /*
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 cmd
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"github.com/ghodss/yaml"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/genericclioptions/resource"
"k8s.io/client-go/dynamic"
api "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/kubectl/apply/parse"
"k8s.io/kubernetes/pkg/kubectl/apply/strategy"
"k8s.io/kubernetes/pkg/kubectl/cmd/templates"
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
"k8s.io/kubernetes/pkg/kubectl/util/i18n"
"k8s.io/utils/exec"
)
var (
diffLong = templates.LongDesc(i18n.T(`
Diff configurations specified by filename or stdin between their local,
last-applied, live and/or "merged" versions.
LOCAL and LIVE versions are diffed by default. Other available keywords
are MERGED and LAST.
Output is always YAML.
KUBERNETES_EXTERNAL_DIFF environment variable can be used to select your own
diff command. By default, the "diff" command available in your path will be
run with "-u" (unicode) and "-N" (treat new files as empty) options.`))
diffExample = templates.Examples(i18n.T(`
# Diff resources included in pod.json. By default, it will diff LOCAL and LIVE versions
kubectl alpha diff -f pod.json
# When one version is specified, diff that version against LIVE
cat service.yaml | kubectl alpha diff -f - MERGED
# Or specify both versions
kubectl alpha diff -f pod.json -f service.yaml LAST LOCAL`))
)
type DiffOptions struct {
FilenameOptions resource.FilenameOptions
}
func isValidArgument(arg string) error {
switch arg {
case "LOCAL", "LIVE", "LAST", "MERGED":
return nil
default:
return fmt.Errorf(`Invalid parameter %q, must be either "LOCAL", "LIVE", "LAST" or "MERGED"`, arg)
}
}
func parseDiffArguments(args []string) (string, string, error) {
if len(args) > 2 {
return "", "", fmt.Errorf("Invalid number of arguments: expected at most 2.")
}
// Default values
from := "LOCAL"
to := "LIVE"
if len(args) > 0 {
from = args[0]
}
if len(args) > 1 {
to = args[1]
}
if err := isValidArgument(to); err != nil {
return "", "", err
}
if err := isValidArgument(from); err != nil {
return "", "", err
}
return from, to, nil
}
func NewCmdDiff(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
var options DiffOptions
diff := DiffProgram{
Exec: exec.New(),
IOStreams: streams,
}
cmd := &cobra.Command{
Use: "diff -f FILENAME",
DisableFlagsInUseLine: true,
Short: i18n.T("Diff different versions of configurations"),
Long: diffLong,
Example: diffExample,
Run: func(cmd *cobra.Command, args []string) {
from, to, err := parseDiffArguments(args)
cmdutil.CheckErr(err)
cmdutil.CheckErr(RunDiff(f, &diff, &options, from, to))
},
}
usage := "contains the configuration to diff"
cmdutil.AddFilenameOptionFlags(cmd, &options.FilenameOptions, usage)
cmd.MarkFlagRequired("filename")
return cmd
}
// DiffProgram finds and run the diff program. The value of
// KUBERNETES_EXTERNAL_DIFF environment variable will be used a diff
// program. By default, `diff(1)` will be used.
type DiffProgram struct {
Exec exec.Interface
genericclioptions.IOStreams
}
func (d *DiffProgram) getCommand(args ...string) exec.Cmd {
diff := ""
if envDiff := os.Getenv("KUBERNETES_EXTERNAL_DIFF"); envDiff != "" {
diff = envDiff
} else {
diff = "diff"
args = append([]string{"-u", "-N"}, args...)
}
cmd := d.Exec.Command(diff, args...)
cmd.SetStdout(d.Out)
cmd.SetStderr(d.ErrOut)
return cmd
}
// Run runs the detected diff program. `from` and `to` are the directory to diff.
func (d *DiffProgram) Run(from, to string) error {
d.getCommand(from, to).Run() // Ignore diff return code
return nil
}
// Printer is used to print an object.
type Printer struct{}
// Print the object inside the writer w.
func (p *Printer) Print(obj map[string]interface{}, w io.Writer) error {
if obj == nil {
return nil
}
data, err := yaml.Marshal(obj)
if err != nil {
return err
}
_, err = w.Write(data)
return err
}
// DiffVersion gets the proper version of objects, and aggregate them into a directory.
type DiffVersion struct {
Dir *Directory
Name string
}
// NewDiffVersion creates a new DiffVersion with the named version.
func NewDiffVersion(name string) (*DiffVersion, error) {
dir, err := CreateDirectory(name)
if err != nil {
return nil, err
}
return &DiffVersion{
Dir: dir,
Name: name,
}, nil
}
func (v *DiffVersion) getObject(obj Object) (map[string]interface{}, error) {
switch v.Name {
case "LIVE":
return obj.Live()
case "MERGED":
return obj.Merged()
case "LOCAL":
return obj.Local()
case "LAST":
return obj.Last()
}
return nil, fmt.Errorf("Unknown version: %v", v.Name)
}
// Print prints the object using the printer into a new file in the directory.
func (v *DiffVersion) Print(obj Object, printer Printer) error {
vobj, err := v.getObject(obj)
if err != nil {
return err
}
f, err := v.Dir.NewFile(obj.Name())
if err != nil {
return err
}
defer f.Close()
return printer.Print(vobj, f)
}
// Directory creates a new temp directory, and allows to easily create new files.
type Directory struct {
Name string
}
// CreateDirectory does create the actual disk directory, and return a
// new representation of it.
func CreateDirectory(prefix string) (*Directory, error) {
name, err := ioutil.TempDir("", prefix+"-")
if err != nil {
return nil, err
}
return &Directory{
Name: name,
}, nil
}
// NewFile creates a new file in the directory.
func (d *Directory) NewFile(name string) (*os.File, error) {
return os.OpenFile(filepath.Join(d.Name, name), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0700)
}
// Delete removes the directory recursively.
func (d *Directory) Delete() error {
return os.RemoveAll(d.Name)
}
// Object is an interface that let's you retrieve multiple version of
// it.
type Object interface {
Local() (map[string]interface{}, error)
Live() (map[string]interface{}, error)
Last() (map[string]interface{}, error)
Merged() (map[string]interface{}, error)
Name() string
}
// InfoObject is an implementation of the Object interface. It gets all
// the information from the Info object.
type InfoObject struct {
Remote *unstructured.Unstructured
Info *resource.Info
Encoder runtime.Encoder
Parser *parse.Factory
}
var _ Object = &InfoObject{}
func (obj InfoObject) toMap(data []byte) (map[string]interface{}, error) {
m := map[string]interface{}{}
if len(data) == 0 {
return m, nil
}
err := json.Unmarshal(data, &m)
return m, err
}
func (obj InfoObject) Local() (map[string]interface{}, error) {
data, err := runtime.Encode(obj.Encoder, obj.Info.Object)
if err != nil {
return nil, err
}
return obj.toMap(data)
}
func (obj InfoObject) Live() (map[string]interface{}, error) {
if obj.Remote == nil {
return nil, nil // Object doesn't exist on cluster.
}
return obj.Remote.UnstructuredContent(), nil
}
func (obj InfoObject) Merged() (map[string]interface{}, error) {
local, err := obj.Local()
if err != nil {
return nil, err
}
live, err := obj.Live()
if err != nil {
return nil, err
}
last, err := obj.Last()
if err != nil {
return nil, err
}
if live == nil || last == nil {
return local, nil // We probably don't have a live version, merged is local.
}
elmt, err := obj.Parser.CreateElement(last, local, live)
if err != nil {
return nil, err
}
result, err := elmt.Merge(strategy.Create(strategy.Options{}))
return result.MergedResult.(map[string]interface{}), err
}
func (obj InfoObject) Last() (map[string]interface{}, error) {
if obj.Remote == nil {
return nil, nil // No object is live, return empty
}
accessor, err := meta.Accessor(obj.Remote)
if err != nil {
return nil, err
}
annots := accessor.GetAnnotations()
if annots == nil {
return nil, nil // Not an error, just empty.
}
return obj.toMap([]byte(annots[api.LastAppliedConfigAnnotation]))
}
func (obj InfoObject) Name() string {
return obj.Info.Name
}
// Differ creates two DiffVersion and diffs them.
type Differ struct {
From *DiffVersion
To *DiffVersion
}
func NewDiffer(from, to string) (*Differ, error) {
differ := Differ{}
var err error
differ.From, err = NewDiffVersion(from)
if err != nil {
return nil, err
}
differ.To, err = NewDiffVersion(to)
if err != nil {
differ.From.Dir.Delete()
return nil, err
}
return &differ, nil
}
// Diff diffs to versions of a specific object, and print both versions to directories.
func (d *Differ) Diff(obj Object, printer Printer) error {
if err := d.From.Print(obj, printer); err != nil {
return err
}
if err := d.To.Print(obj, printer); err != nil {
return err
}
return nil
}
// Run runs the diff program against both directories.
func (d *Differ) Run(diff *DiffProgram) error {
return diff.Run(d.From.Dir.Name, d.To.Dir.Name)
}
// TearDown removes both temporary directories recursively.
func (d *Differ) TearDown() {
d.From.Dir.Delete() // Ignore error
d.To.Dir.Delete() // Ignore error
}
type Downloader struct {
mapper meta.RESTMapper
dclient dynamic.Interface
ns string
}
func NewDownloader(f cmdutil.Factory) (*Downloader, error) {
var err error
var d Downloader
d.mapper, err = f.ToRESTMapper()
if err != nil {
return nil, err
}
d.dclient, err = f.DynamicClient()
if err != nil {
return nil, err
}
d.ns, _, _ = f.ToRawKubeConfigLoader().Namespace()
return &d, nil
}
func (d *Downloader) Download(info *resource.Info) (*unstructured.Unstructured, error) {
gvk := info.Object.GetObjectKind().GroupVersionKind()
mapping, err := d.mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
return nil, err
}
var resource dynamic.ResourceInterface
switch mapping.Scope.Name() {
case meta.RESTScopeNameNamespace:
if info.Namespace == "" {
info.Namespace = d.ns
}
resource = d.dclient.Resource(mapping.Resource).Namespace(info.Namespace)
case meta.RESTScopeNameRoot:
resource = d.dclient.Resource(mapping.Resource)
}
return resource.Get(info.Name, metav1.GetOptions{})
}
// RunDiff uses the factory to parse file arguments, find the version to
// diff, and find each Info object for each files, and runs against the
// differ.
func RunDiff(f cmdutil.Factory, diff *DiffProgram, options *DiffOptions, from, to string) error {
openapi, err := f.OpenAPISchema()
if err != nil {
return err
}
parser := &parse.Factory{Resources: openapi}
differ, err := NewDiffer(from, to)
if err != nil {
return err
}
defer differ.TearDown()
printer := Printer{}
cmdNamespace, enforceNamespace, err := f.ToRawKubeConfigLoader().Namespace()
if err != nil {
return err
}
r := f.NewBuilder().
Unstructured().
NamespaceParam(cmdNamespace).DefaultNamespace().
FilenameParam(enforceNamespace, &options.FilenameOptions).
Local().
Flatten().
Do()
if err := r.Err(); err != nil {
return err
}
dl, err := NewDownloader(f)
if err != nil {
return err
}
err = r.Visit(func(info *resource.Info, err error) error {
if err != nil {
return err
}
remote, _ := dl.Download(info)
obj := InfoObject{
Remote: remote,
Info: info,
Parser: parser,
Encoder: cmdutil.InternalVersionJSONEncoder(),
}
return differ.Diff(obj, printer)
})
if err != nil {
return err
}
differ.Run(diff)
return nil
}
| [
"\"KUBERNETES_EXTERNAL_DIFF\""
]
| []
| [
"KUBERNETES_EXTERNAL_DIFF"
]
| [] | ["KUBERNETES_EXTERNAL_DIFF"] | go | 1 | 0 | |
internal/provider/provider_test.go | // Copyright 2021 tsuru 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 provider
import (
"fmt"
"os"
"testing"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"github.com/stretchr/testify/require"
)
var testAccProvider *schema.Provider
var testAccProviderFactories = map[string]func() (*schema.Provider, error){
"tsuru": func() (*schema.Provider, error) {
return testAccProvider, nil
},
}
func init() {
testAccProvider = Provider()
}
func TestProvider(t *testing.T) {
provider := Provider()
if err := provider.InternalValidate(); err != nil {
t.Fatalf("err: %s", err)
}
}
func testAccPreCheck(t *testing.T) {
tsuruTarget := os.Getenv("TSURU_TARGET")
require.Contains(t, tsuruTarget, "http://127.0.0.1:")
}
func testAccResourceExists(resourceName string) resource.TestCheckFunc {
return func(s *terraform.State) error {
_, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("Not found: %s", resourceName)
}
return nil
}
}
| [
"\"TSURU_TARGET\""
]
| []
| [
"TSURU_TARGET"
]
| [] | ["TSURU_TARGET"] | go | 1 | 0 | |
pilot/kube/cache.go | package kube
import (
"fmt"
"os"
"github.com/caicloud/log-pilot/pilot/log"
"github.com/caicloud/clientset/kubernetes"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
)
type Cache interface {
// Start run informer in another goroutine, and wait for it synced.
Start(stopCh <-chan struct{}) error
GetReleaseMeta(namespace, pod string) map[string]string
GetLegacyLogSources(namespace, pod, container string) []string
}
// New create a new Cache
func New() (Cache, error) {
cfg, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
kc, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, err
}
nodeName := os.Getenv("NODE_NAME")
if nodeName == "" {
return nil, fmt.Errorf("NODE_NAME env not defined")
}
pc, err := newPodsCache(nodeName, kc)
if err != nil {
return nil, err
}
return &kubeCache{
pc: pc,
}, nil
}
type kubeCache struct {
pc *podsCache
}
func (c *kubeCache) Start(stopCh <-chan struct{}) error {
return c.pc.lwCache.Run(stopCh)
}
var (
releaseAnnotationKeys = map[string]string{
"helm.sh/namespace": "kubernetes.annotations.helm_sh/namespace",
"helm.sh/release": "kubernetes.annotations.helm_sh/release",
}
releaseLabelKeys = map[string]string{
"controller.caicloud.io/chart": "kubernetes.labels.controller_caicloud_io/chart",
}
)
func releaseMeta(pod *corev1.Pod) map[string]string {
ret := make(map[string]string)
if pod == nil {
return ret
}
for k, docKey := range releaseAnnotationKeys {
v := pod.GetAnnotations()[k]
if v != "" {
ret[docKey] = v
}
}
for k, docKey := range releaseLabelKeys {
v := pod.GetLabels()[k]
if v != "" {
ret[docKey] = v
}
}
return ret
}
func (c *kubeCache) GetReleaseMeta(namespace, name string) map[string]string {
pod, err := c.pc.Get(namespace, name)
if err != nil {
log.Errorf("error get pod from cache: %v", err)
return nil
}
return releaseMeta(pod)
}
func (c *kubeCache) GetLegacyLogSources(namespace, podName, containerName string) []string {
pod, err := c.pc.Get(namespace, podName)
if err != nil {
log.Errorf("error get pod from cache: %v", err)
return nil
}
if !requireFileLog(pod) {
return nil
}
sources, err := extractLogSources(pod, containerName)
if err != nil {
log.Errorf("error decode log sources from pod annotation: %v", err)
}
return sources
}
type podsCache struct {
lwCache *ListWatchCache
kc kubernetes.Interface
}
func newPodsCache(nodeName string, kc kubernetes.Interface) (*podsCache, error) {
c, e := NewListWatchCache(&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
options.FieldSelector = fmt.Sprintf("spec.nodeName=%s", nodeName)
return kc.Native().CoreV1().Pods("").List(options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.FieldSelector = fmt.Sprintf("spec.nodeName=%s", nodeName)
options.Watch = true
return kc.Native().CoreV1().Pods("").Watch(options)
},
}, &corev1.Pod{})
if e != nil {
return nil, e
}
return &podsCache{
lwCache: c,
kc: kc,
}, nil
}
func (tc *podsCache) Get(namespace, key string) (*corev1.Pod, error) {
if obj, exist, e := tc.lwCache.GetInNamespace(namespace, key); exist && obj != nil && e == nil {
if pod, _ := obj.(*corev1.Pod); pod != nil && pod.Name == key {
return pod.DeepCopy(), nil
}
}
pod, e := tc.kc.Native().CoreV1().Pods(namespace).Get(key, metav1.GetOptions{})
if e != nil {
return nil, e
}
return pod, nil
}
func (tc *podsCache) List() ([]corev1.Pod, error) {
if items := tc.lwCache.List(); len(items) > 0 {
re := make([]corev1.Pod, 0, len(items))
for _, obj := range items {
pod, _ := obj.(*corev1.Pod)
if pod != nil {
re = append(re, *pod)
}
}
if len(re) > 0 {
return re, nil
}
}
podList, e := tc.kc.Native().CoreV1().Pods("").List(metav1.ListOptions{})
if e != nil {
return nil, e
}
return podList.Items, nil
}
| [
"\"NODE_NAME\""
]
| []
| [
"NODE_NAME"
]
| [] | ["NODE_NAME"] | go | 1 | 0 | |
zerorobot/server/types/ServiceCreate.py | # DO NOT EDIT THIS FILE. This file will be overwritten when re-running go-raml.
"""
Auto-generated class for ServiceCreate
"""
from six import string_types
from . import client_support
class ServiceCreate(object):
"""
auto-generated. don't touch.
"""
@staticmethod
def create(**kwargs):
"""
:type data: dict
:type name: string_types
:type public: bool
:type template: string_types
:rtype: ServiceCreate
"""
return ServiceCreate(**kwargs)
def __init__(self, json=None, **kwargs):
if json is None and not kwargs:
raise ValueError('No data or kwargs present')
class_name = 'ServiceCreate'
data = json or kwargs
# set attributes
data_types = [dict]
self.data = client_support.set_property('data', data, data_types, False, [], False, False, class_name)
data_types = [string_types]
self.name = client_support.set_property('name', data, data_types, False, [], False, False, class_name)
data_types = [bool]
self.public = client_support.set_property('public', data, data_types, False, [], False, False, class_name)
data_types = [string_types]
self.template = client_support.set_property('template', data, data_types, False, [], False, True, class_name)
def __str__(self):
return self.as_json(indent=4)
def as_json(self, indent=0):
return client_support.to_json(self, indent=indent)
def as_dict(self):
return client_support.to_dict(self)
| []
| []
| []
| [] | [] | python | null | null | null |
controller/manager/manager_test.go | package manager
import (
"fmt"
"os"
"testing"
"time"
"github.com/hangyan/citadel"
"github.com/hangyan/shipyard"
)
func newManager() *Manager {
rHost := os.Getenv("RETHINKDB_TEST_PORT_28015_TCP_ADDR")
rPort := os.Getenv("RETHINKDB_TEST_PORT_28015_TCP_PORT")
rDb := os.Getenv("RETHINKDB_TEST_DATABASE")
rethinkdbAddr := ""
if rHost != "" && rPort != "" {
rethinkdbAddr = fmt.Sprintf("%s:%s", rHost, rPort)
}
dockerHostAddr := os.Getenv("DOCKER_TEST_ADDR")
if dockerHostAddr == "" || rethinkdbAddr == "" {
fmt.Println("env vars needed: RETHINKDB_TEST_PORT_28015_TCP_ADDR, RETHINKDB_TEST_PORT_28015_TCP_PORT, RETHINKDB_TEST_DATABASE, DOCKER_TEST_ADDR")
os.Exit(1)
}
m, err := NewManager(rethinkdbAddr, rDb, "", "test", true)
if err != nil {
fmt.Printf("unable to connect to test db: %s\n", err)
os.Exit(1)
}
health := &shipyard.Health{
Status: "up",
ResponseTime: 1,
}
eng := &shipyard.Engine{
ID: "test",
Engine: &citadel.Engine{
ID: "test",
Addr: dockerHostAddr,
Cpus: 4.0,
Memory: 4096,
Labels: []string{"tests"},
},
Health: health,
}
m.AddEngine(eng)
return m
}
func getTestImage() *citadel.Image {
img := &citadel.Image{
Name: "busybox",
Cpus: 0.1,
Memory: 8,
Type: "service",
Labels: []string{"tests"},
}
return img
}
func TestRun(t *testing.T) {
m := newManager()
img := getTestImage()
cTest, err := m.Run(img, 1, true)
if err != nil {
t.Error(err)
}
if len(cTest) != 1 {
t.Errorf("expected 1 container; received %d", len(cTest))
}
c := cTest[0]
if c.Image.Name != "busybox" {
t.Errorf("expected image %s; received %s", img.Name, c.Image.Name)
}
// cleanup
for _, c := range cTest {
if err := m.Destroy(c); err != nil {
t.Error(err)
}
}
time.Sleep(2 * time.Second)
}
func TestScaleUp(t *testing.T) {
m := newManager()
img := getTestImage()
cTest, err := m.Run(img, 1, true)
if err != nil {
t.Error(err)
}
c := cTest[0]
if err := m.Scale(c, 2); err != nil {
t.Error(err)
}
containers, err := m.IdenticalContainers(c, true)
if err != nil {
t.Error(err)
}
if len(containers) != 2 {
t.Errorf("expected 2 containers; received %d", len(containers))
}
// cleanup
for _, c := range containers {
if err := m.Destroy(c); err != nil {
t.Error(err)
}
}
time.Sleep(2 * time.Second)
}
func TestScaleDown(t *testing.T) {
m := newManager()
img := getTestImage()
cTest, err := m.Run(img, 4, true)
if err != nil {
t.Error(err)
}
if len(cTest) != 4 {
t.Errorf("expected to run 4 containers; received %d", len(cTest))
}
c := cTest[0]
if err := m.Scale(c, 1); err != nil {
t.Error(err)
}
containers, err := m.IdenticalContainers(c, true)
if err != nil {
t.Error(err)
}
if len(containers) != 1 {
t.Errorf("expected 1 container; received %d", len(containers))
}
// cleanup
for _, c := range containers {
if err := m.Destroy(c); err != nil {
t.Error(err)
}
}
time.Sleep(2 * time.Second)
}
| [
"\"RETHINKDB_TEST_PORT_28015_TCP_ADDR\"",
"\"RETHINKDB_TEST_PORT_28015_TCP_PORT\"",
"\"RETHINKDB_TEST_DATABASE\"",
"\"DOCKER_TEST_ADDR\""
]
| []
| [
"RETHINKDB_TEST_PORT_28015_TCP_PORT",
"RETHINKDB_TEST_DATABASE",
"DOCKER_TEST_ADDR",
"RETHINKDB_TEST_PORT_28015_TCP_ADDR"
]
| [] | ["RETHINKDB_TEST_PORT_28015_TCP_PORT", "RETHINKDB_TEST_DATABASE", "DOCKER_TEST_ADDR", "RETHINKDB_TEST_PORT_28015_TCP_ADDR"] | go | 4 | 0 | |
vendor/github.com/fsouza/go-dockerclient/auth.go | // Copyright 2015 go-dockerclient 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 docker
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"strings"
)
// ErrCannotParseDockercfg is the error returned by NewAuthConfigurations when the dockercfg cannot be parsed.
var ErrCannotParseDockercfg = errors.New("Failed to read authentication from dockercfg")
// AuthConfiguration represents authentication options to use in the PushImage
// method. It represents the authentication in the Docker index server.
type AuthConfiguration struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Email string `json:"email,omitempty"`
ServerAddress string `json:"serveraddress,omitempty"`
}
// AuthConfigurations represents authentication options to use for the
// PushImage method accommodating the new X-Registry-Config header
type AuthConfigurations struct {
Configs map[string]AuthConfiguration `json:"configs"`
}
// AuthConfigurations119 is used to serialize a set of AuthConfigurations
// for Docker API >= 1.19.
type AuthConfigurations119 map[string]AuthConfiguration
// dockerConfig represents a registry authentation configuration from the
// .dockercfg file.
type dockerConfig struct {
Auth string `json:"auth"`
Email string `json:"email"`
}
// NewAuthConfigurationsFromFile returns AuthConfigurations from a path containing JSON
// in the same format as the .dockercfg file.
func NewAuthConfigurationsFromFile(path string) (*AuthConfigurations, error) {
r, err := os.Open(path)
if err != nil {
return nil, err
}
return NewAuthConfigurations(r)
}
func cfgPaths(dockerConfigEnv string, homeEnv string) []string {
var paths []string
if dockerConfigEnv != "" {
paths = append(paths, path.Join(dockerConfigEnv, "config.json"))
}
if homeEnv != "" {
paths = append(paths, path.Join(homeEnv, ".docker", "config.json"))
paths = append(paths, path.Join(homeEnv, ".dockercfg"))
}
return paths
}
// NewAuthConfigurationsFromDockerCfg returns AuthConfigurations from
// system config files. The following files are checked in the order listed:
// - $DOCKER_CONFIG/config.json if DOCKER_CONFIG set in the environment,
// - $HOME/.docker/config.json
// - $HOME/.dockercfg
func NewAuthConfigurationsFromDockerCfg() (*AuthConfigurations, error) {
err := fmt.Errorf("No docker configuration found")
var auths *AuthConfigurations
pathsToTry := cfgPaths(os.Getenv("DOCKER_CONFIG"), os.Getenv("HOME"))
for _, path := range pathsToTry {
auths, err = NewAuthConfigurationsFromFile(path)
if err == nil {
return auths, nil
}
}
return auths, err
}
// NewAuthConfigurations returns AuthConfigurations from a JSON encoded string in the
// same format as the .dockercfg file.
func NewAuthConfigurations(r io.Reader) (*AuthConfigurations, error) {
var auth *AuthConfigurations
confs, err := parseDockerConfig(r)
if err != nil {
return nil, err
}
auth, err = authConfigs(confs)
if err != nil {
return nil, err
}
return auth, nil
}
func parseDockerConfig(r io.Reader) (map[string]dockerConfig, error) {
buf := new(bytes.Buffer)
buf.ReadFrom(r)
byteData := buf.Bytes()
confsWrapper := struct {
Auths map[string]dockerConfig `json:"auths"`
}{}
if err := json.Unmarshal(byteData, &confsWrapper); err == nil {
if len(confsWrapper.Auths) > 0 {
return confsWrapper.Auths, nil
}
}
var confs map[string]dockerConfig
if err := json.Unmarshal(byteData, &confs); err != nil {
return nil, err
}
return confs, nil
}
// authConfigs converts a dockerConfigs map to a AuthConfigurations object.
func authConfigs(confs map[string]dockerConfig) (*AuthConfigurations, error) {
c := &AuthConfigurations{
Configs: make(map[string]AuthConfiguration),
}
for reg, conf := range confs {
data, err := base64.StdEncoding.DecodeString(conf.Auth)
if err != nil {
return nil, err
}
userpass := strings.SplitN(string(data), ":", 2)
if len(userpass) != 2 {
return nil, ErrCannotParseDockercfg
}
c.Configs[reg] = AuthConfiguration{
Email: conf.Email,
Username: userpass[0],
Password: userpass[1],
ServerAddress: reg,
}
}
return c, nil
}
// AuthStatus returns the authentication status for Docker API versions >= 1.23.
type AuthStatus struct {
Status string `json:"Status,omitempty" yaml:"Status,omitempty" toml:"Status,omitempty"`
IdentityToken string `json:"IdentityToken,omitempty" yaml:"IdentityToken,omitempty" toml:"IdentityToken,omitempty"`
}
// AuthCheck validates the given credentials. It returns nil if successful.
//
// For Docker API versions >= 1.23, the AuthStatus struct will be populated, otherwise it will be empty.`
//
// See https://goo.gl/6nsZkH for more details.
func (c *Client) AuthCheck(conf *AuthConfiguration) (AuthStatus, error) {
var authStatus AuthStatus
if conf == nil {
return authStatus, errors.New("conf is nil")
}
resp, err := c.do("POST", "/auth", doOptions{data: conf})
if err != nil {
return authStatus, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return authStatus, err
}
if len(data) == 0 {
return authStatus, nil
}
if err := json.Unmarshal(data, &authStatus); err != nil {
return authStatus, err
}
return authStatus, nil
}
| [
"\"DOCKER_CONFIG\"",
"\"HOME\""
]
| []
| [
"DOCKER_CONFIG",
"HOME"
]
| [] | ["DOCKER_CONFIG", "HOME"] | go | 2 | 0 | |
pkg/iplayerservice_test.go | package steam
import (
"context"
"os"
"strconv"
"testing"
)
func TestIPlayerService_GetRecentlyPlayedGames(t *testing.T) {
type args struct {
ctx context.Context
params *GetRecentlyPlayedGamesParams
}
steam := NewClient(os.Getenv("STEAM_API_KEY"), nil)
ctx := context.Background()
steamID, _ := strconv.ParseUint(os.Getenv("STEAM_ID"), 10, 64)
tests := []struct {
name string
args args
}{{
name: "ALL",
args: args{
ctx: ctx,
params: &GetRecentlyPlayedGamesParams{
SteamID: steamID,
},
},
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := steam.IPlayerService.GetRecentlyPlayedGames(tt.args.ctx, tt.args.params)
if err != nil {
t.Error(err)
}
t.Logf("%+v", result)
})
}
}
func TestIPlayerService_GetOwnedGames(t *testing.T) {
type args struct {
ctx context.Context
params *GetOwnedGamesParams
}
steam := NewClient(os.Getenv("STEAM_API_KEY"), nil)
ctx := context.Background()
steamID, _ := strconv.ParseUint(os.Getenv("STEAM_ID"), 10, 64)
tests := []struct {
name string
args args
}{
{
name: "ALL",
args: args{
ctx: ctx,
params: &GetOwnedGamesParams{
SteamID: steamID,
IncludeAppInfo: true,
IncludePlayedFreeGames: true,
},
},
},
{
name: "IncludeAppInfo=false",
args: args{
ctx: ctx,
params: &GetOwnedGamesParams{
SteamID: steamID,
IncludeAppInfo: false,
IncludePlayedFreeGames: true,
},
},
},
{
name: "IncludePlayedFreeGames=false",
args: args{
ctx: ctx,
params: &GetOwnedGamesParams{
SteamID: steamID,
IncludeAppInfo: true,
IncludePlayedFreeGames: false,
},
},
},
{
name: "AppIDsFilter=[500]",
args: args{
ctx: ctx,
params: &GetOwnedGamesParams{
SteamID: steamID,
IncludeAppInfo: true,
IncludePlayedFreeGames: false,
AppIDsFilter: []uint32{500},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := steam.IPlayerService.GetOwnedGames(tt.args.ctx, tt.args.params)
if err != nil {
t.Error(err)
}
//t.Logf("%+v", result)
})
}
}
func TestIPlayerService_GetSteamLevel(t *testing.T) {
type args struct {
ctx context.Context
params *GetSteamLevelParams
}
steam := NewClient(os.Getenv("STEAM_API_KEY"), nil)
ctx := context.Background()
steamID, _ := strconv.ParseUint(os.Getenv("STEAM_ID"), 10, 64)
tests := []struct {
name string
args args
}{{
name: "ALL",
args: args{
ctx: ctx,
params: &GetSteamLevelParams{
SteamID: steamID,
},
},
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := steam.IPlayerService.GetSteamLevel(tt.args.ctx, tt.args.params)
if err != nil {
t.Error(err)
}
//t.Logf("%+v", result)
})
}
}
func TestIPlayerService_GetBadges(t *testing.T) {
type args struct {
ctx context.Context
params *GetBadgesParams
}
steam := NewClient(os.Getenv("STEAM_API_KEY"), nil)
ctx := context.Background()
steamID, _ := strconv.ParseUint(os.Getenv("STEAM_ID"), 10, 64)
tests := []struct {
name string
args args
}{{
name: "ALL",
args: args{
ctx: ctx,
params: &GetBadgesParams{
SteamID: steamID,
},
},
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := steam.IPlayerService.GetBadges(tt.args.ctx, tt.args.params)
if err != nil {
t.Error(err)
}
//t.Logf("%+v", result)
})
}
}
func TestIPlayerService_GetCommunityBadgeProgress(t *testing.T) {
type args struct {
ctx context.Context
params *GetCommunityBadgeProgressParams
}
steam := NewClient(os.Getenv("STEAM_API_KEY"), nil)
ctx := context.Background()
steamID, _ := strconv.ParseUint(os.Getenv("STEAM_ID"), 10, 64)
tests := []struct {
name string
args args
}{
{
name: "ALL",
args: args{
ctx: ctx,
params: &GetCommunityBadgeProgressParams{
SteamID: steamID,
},
},
},
{
name: "BadgeID=7",
args: args{
ctx: ctx,
params: &GetCommunityBadgeProgressParams{
SteamID: steamID,
BadgeID: 7,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := steam.IPlayerService.GetCommunityBadgeProgress(tt.args.ctx, tt.args.params)
if err != nil {
t.Error(err)
}
//t.Logf("%+v", result)
})
}
}
func TestIPlayerService_IsPlayingSharedGame(t *testing.T) {
type args struct {
ctx context.Context
params *IsPlayingSharedGameParams
}
steam := NewClient(os.Getenv("STEAM_API_KEY"), nil)
ctx := context.Background()
steamID, _ := strconv.ParseUint(os.Getenv("STEAM_ID"), 10, 64)
tests := []struct {
name string
args args
}{{
name: "ALL",
args: args{
ctx: ctx,
params: &IsPlayingSharedGameParams{
SteamID: steamID,
AppIDPlaying: 500,
},
},
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := steam.IPlayerService.IsPlayingSharedGame(tt.args.ctx, tt.args.params)
if err != nil {
t.Error(err)
}
//t.Logf("%+v", result)
})
}
}
| [
"\"STEAM_API_KEY\"",
"\"STEAM_ID\"",
"\"STEAM_API_KEY\"",
"\"STEAM_ID\"",
"\"STEAM_API_KEY\"",
"\"STEAM_ID\"",
"\"STEAM_API_KEY\"",
"\"STEAM_ID\"",
"\"STEAM_API_KEY\"",
"\"STEAM_ID\"",
"\"STEAM_API_KEY\"",
"\"STEAM_ID\""
]
| []
| [
"STEAM_ID",
"STEAM_API_KEY"
]
| [] | ["STEAM_ID", "STEAM_API_KEY"] | go | 2 | 0 | |
pkg/mongokit/client_test.go | package mongokit
import (
"context"
"os"
"github.com/NTHU-LSALAB/NTHU-Distributed-System/pkg/logkit"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("MongoClient", func() {
Describe("NewMongoClient", func() {
var (
mongoClient *MongoClient
ctx context.Context
mongoConfig *MongoConfig
)
BeforeEach(func() {
ctx = logkit.NewLogger(&logkit.LoggerConfig{
Development: true,
}).WithContext(context.Background())
mongoConfig = &MongoConfig{
URL: "mongodb://mongo:27017",
Database: "nthu_distributed_system",
}
if url := os.Getenv("MONGO_URL"); url != "" {
mongoConfig.URL = url
}
if database := os.Getenv("MONGO_DATABASE"); database != "" {
mongoConfig.Database = database
}
})
JustBeforeEach(func() {
mongoClient = NewMongoClient(ctx, mongoConfig)
})
AfterEach(func() {
Expect(mongoClient.Close()).NotTo(HaveOccurred())
})
When("success", func() {
It("returns new MongoClient without error", func() {
Expect(mongoClient).NotTo(BeNil())
})
})
})
})
| [
"\"MONGO_URL\"",
"\"MONGO_DATABASE\""
]
| []
| [
"MONGO_DATABASE",
"MONGO_URL"
]
| [] | ["MONGO_DATABASE", "MONGO_URL"] | go | 2 | 0 | |
go/mod/main.go | package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
)
const INDEX = `<!DOCTYPE html>
<html>
<head>
<title>Powered By Paketo Buildpacks</title>
</head>
<body>
<img style="display: block; margin-left: auto; margin-right: auto; width: 50%;" src="https://paketo.io/images/paketo-logo-full-color.png"></img>
</body>
</html>`
func main() {
router := mux.NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintln(w, INDEX)
})
log.Fatal(http.ListenAndServe(":"+os.Getenv("PORT"), router))
}
| [
"\"PORT\""
]
| []
| [
"PORT"
]
| [] | ["PORT"] | go | 1 | 0 | |
lxd/instance/drivers/driver_lxc.go | package drivers
import (
"bufio"
"bytes"
"database/sql"
"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/pborman/uuid"
"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/cgroup"
"github.com/lxc/lxd/lxd/daemon"
"github.com/lxc/lxd/lxd/db"
"github.com/lxc/lxd/lxd/device"
deviceConfig "github.com/lxc/lxd/lxd/device/config"
"github.com/lxc/lxd/lxd/device/nictype"
"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/lifecycle"
"github.com/lxc/lxd/lxd/metrics"
"github.com/lxc/lxd/lxd/network"
"github.com/lxc/lxd/lxd/project"
"github.com/lxc/lxd/lxd/revert"
"github.com/lxc/lxd/lxd/seccomp"
"github.com/lxc/lxd/lxd/state"
"github.com/lxc/lxd/lxd/storage"
storagePools "github.com/lxc/lxd/lxd/storage"
storageDrivers "github.com/lxc/lxd/lxd/storage/drivers"
"github.com/lxc/lxd/lxd/storage/filesystem"
"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/logging"
"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)]
}
// lxcCreate creates the DB storage records and sets up instance devices.
// Accepts a reverter that revert steps this function does will be added to. It is up to the caller to call the
// revert's Fail() or Success() function as needed.
func lxcCreate(s *state.State, args db.InstanceArgs, volumeConfig map[string]string, revert *revert.Reverter) (instance.Instance, error) {
// Create the container struct
d := &lxc{
common: common{
state: s,
architecture: args.Architecture,
creationDate: args.CreationDate,
dbType: args.Type,
description: args.Description,
ephemeral: args.Ephemeral,
expiryDate: args.ExpiryDate,
id: args.ID,
lastUsedDate: args.LastUsedDate,
localConfig: args.Config,
localDevices: args.Devices,
logger: logging.AddContext(logger.Log, log.Ctx{"instanceType": args.Type, "instance": args.Name, "project": args.Project}),
name: args.Name,
node: args.Node,
profiles: args.Profiles,
project: args.Project,
snapshot: args.Snapshot,
stateful: args.Stateful,
},
}
// Cleanup the zero values
if d.expiryDate.IsZero() {
d.expiryDate = time.Time{}
}
if d.creationDate.IsZero() {
d.creationDate = time.Time{}
}
if d.lastUsedDate.IsZero() {
d.lastUsedDate = time.Time{}
}
d.logger.Info("Creating container", log.Ctx{"ephemeral": d.ephemeral})
// Load the config.
err := d.init()
if err != nil {
return nil, errors.Wrap(err, "Failed to expand config")
}
// Validate expanded config (allows mixed instance types for profiles).
err = instance.ValidConfig(s.OS, d.expandedConfig, true, instancetype.Any)
if err != nil {
return nil, errors.Wrap(err, "Invalid config")
}
err = instance.ValidDevices(s, s.Cluster, d.Project(), d.Type(), d.expandedDevices, true)
if err != nil {
return nil, errors.Wrap(err, "Invalid devices")
}
// Retrieve the container's storage pool.
var storageInstance instance.Instance
if d.IsSnapshot() {
parentName, _, _ := shared.InstanceGetParentAndSnapshotName(d.name)
// Load the parent.
storageInstance, err = instance.LoadByProjectAndName(d.state, d.project, parentName)
if err != nil {
return nil, errors.Wrap(err, "Invalid parent")
}
} else {
storageInstance = d
}
_, rootDiskDevice, err := shared.GetRootDiskDevice(storageInstance.ExpandedDevices().CloneNative())
if err != nil {
return nil, err
}
if rootDiskDevice["pool"] == "" {
return nil, fmt.Errorf("The container's root device is missing the pool property")
}
// Initialize the storage pool.
d.storagePool, err = storagePools.GetPoolByName(d.state, rootDiskDevice["pool"])
if err != nil {
return nil, errors.Wrapf(err, "Failed loading storage pool")
}
volType, err := storagePools.InstanceTypeToVolumeType(d.Type())
if err != nil {
return nil, err
}
storagePoolSupported := false
for _, supportedType := range d.storagePool.Driver().Info().VolumeTypes {
if supportedType == volType {
storagePoolSupported = true
break
}
}
if !storagePoolSupported {
return nil, fmt.Errorf("Storage pool does not support instance type")
}
// Create a new storage volume database entry for the container's storage volume.
if d.IsSnapshot() {
// Copy volume config from parent.
parentName, _, _ := shared.InstanceGetParentAndSnapshotName(args.Name)
_, parentVol, err := s.Cluster.GetLocalStoragePoolVolume(args.Project, parentName, db.StoragePoolVolumeTypeContainer, d.storagePool.ID())
if err != nil {
return nil, errors.Wrapf(err, "Failed loading source volume for snapshot")
}
_, err = s.Cluster.CreateStorageVolumeSnapshot(args.Project, args.Name, "", db.StoragePoolVolumeTypeContainer, d.storagePool.ID(), parentVol.Config, time.Time{})
if err != nil {
return nil, errors.Wrapf(err, "Failed creating storage record for snapshot")
}
} else {
// Fill default config for new instances.
if volumeConfig == nil {
volumeConfig = make(map[string]string)
}
err = d.storagePool.FillInstanceConfig(d, volumeConfig)
if err != nil {
return nil, errors.Wrapf(err, "Failed filling default config")
}
_, err = s.Cluster.CreateStoragePoolVolume(args.Project, args.Name, "", db.StoragePoolVolumeTypeContainer, d.storagePool.ID(), volumeConfig, db.StoragePoolVolumeContentTypeFS)
if err != nil {
return nil, errors.Wrapf(err, "Failed creating storage record")
}
}
revert.Add(func() {
s.Cluster.RemoveStoragePoolVolume(args.Project, args.Name, db.StoragePoolVolumeTypeContainer, d.storagePool.ID())
})
// Setup initial idmap config
var idmap *idmap.IdmapSet
base := int64(0)
if !d.IsPrivileged() {
idmap, base, err = findIdmap(
s,
args.Name,
d.expandedConfig["security.idmap.isolated"],
d.expandedConfig["security.idmap.base"],
d.expandedConfig["security.idmap.size"],
d.expandedConfig["raw.idmap"],
)
if err != nil {
return nil, err
}
}
var jsonIdmap string
if idmap != nil {
idmapBytes, err := json.Marshal(idmap.Idmap)
if err != nil {
return nil, err
}
jsonIdmap = string(idmapBytes)
} else {
jsonIdmap = "[]"
}
err = d.VolatileSet(map[string]string{"volatile.idmap.next": jsonIdmap})
if err != nil {
return nil, err
}
err = d.VolatileSet(map[string]string{"volatile.idmap.base": fmt.Sprintf("%v", base)})
if err != nil {
return nil, err
}
// Invalid idmap cache.
d.idmapset = nil
// Set last_state if not currently set.
if d.localConfig["volatile.last_state.idmap"] == "" {
err = d.VolatileSet(map[string]string{"volatile.last_state.idmap": "[]"})
if err != nil {
return nil, err
}
}
// Re-run init to update the idmap.
err = d.init()
if err != nil {
return nil, err
}
if !d.IsSnapshot() {
// Add devices to container.
for k, m := range d.expandedDevices {
devName := k
devConfig := m
err = d.deviceAdd(devName, devConfig, false)
if err != nil && err != device.ErrUnsupportedDevType {
return nil, errors.Wrapf(err, "Failed to add device %q", devName)
}
revert.Add(func() { d.deviceRemove(devName, devConfig, false) })
}
// Update MAAS (must run after the MAC addresses have been generated).
err = d.maasUpdate(d, nil)
if err != nil {
return nil, err
}
revert.Add(func() { d.maasDelete(d) })
}
d.logger.Info("Created container", log.Ctx{"ephemeral": d.ephemeral})
if d.snapshot {
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceSnapshotCreated.Event(d, nil))
} else {
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceCreated.Event(d, nil))
}
return d, nil
}
func lxcLoad(s *state.State, args db.InstanceArgs, profiles []api.Profile) (instance.Instance, error) {
// Create the container struct
d := lxcInstantiate(s, args, nil)
// Setup finalizer
runtime.SetFinalizer(d, lxcUnload)
// Expand config and devices
err := d.(*lxc).expandConfig(profiles)
if err != nil {
return nil, err
}
err = d.(*lxc).expandDevices(profiles)
if err != nil {
return nil, err
}
return d, nil
}
// Unload is called by the garbage collector
func lxcUnload(d *lxc) {
runtime.SetFinalizer(d, nil)
d.release()
}
// release releases any internal reference to a liblxc container, invalidating the go-lxc cache.
func (d *lxc) release() {
if d.c != nil {
d.c.Release()
d.c = nil
}
}
// Create a container struct without initializing it.
func lxcInstantiate(s *state.State, args db.InstanceArgs, expandedDevices deviceConfig.Devices) instance.Instance {
d := &lxc{
common: common{
state: s,
architecture: args.Architecture,
creationDate: args.CreationDate,
dbType: args.Type,
description: args.Description,
ephemeral: args.Ephemeral,
expiryDate: args.ExpiryDate,
id: args.ID,
lastUsedDate: args.LastUsedDate,
localConfig: args.Config,
localDevices: args.Devices,
logger: logging.AddContext(logger.Log, log.Ctx{"instanceType": args.Type, "instance": args.Name, "project": args.Project}),
name: args.Name,
node: args.Node,
profiles: args.Profiles,
project: args.Project,
snapshot: args.Snapshot,
stateful: args.Stateful,
},
}
// Cleanup the zero values
if d.expiryDate.IsZero() {
d.expiryDate = time.Time{}
}
if d.creationDate.IsZero() {
d.creationDate = time.Time{}
}
if d.lastUsedDate.IsZero() {
d.lastUsedDate = time.Time{}
}
// This is passed during expanded config validation.
if expandedDevices != nil {
d.expandedDevices = expandedDevices
}
return d
}
// The LXC container driver.
type lxc struct {
common
// Config handling.
fromHook bool
// Cached handles.
// Do not use these variables directly, instead use their associated get functions so they
// will be initialised on demand.
c *liblxc.Container
cConfig bool
idmapset *idmap.IdmapSet
storagePool storagePools.Pool
}
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 := idmap.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 (d *lxc) init() error {
// Compute the expanded config and device list
err := d.expandConfig(nil)
if err != nil {
return err
}
err = d.expandDevices(nil)
if err != nil {
return err
}
return nil
}
func (d *lxc) initLXC(config bool) error {
// No need to go through all that for snapshots
if d.IsSnapshot() {
return nil
}
// Check if being called from a hook
if d.fromHook {
return fmt.Errorf("You can't use go-lxc from inside a LXC hook")
}
// Check if already initialized
if d.c != nil {
if !config || d.cConfig {
return nil
}
}
// Load the go-lxc struct
cname := project.Instance(d.Project(), d.Name())
cc, err := liblxc.NewContainer(cname, d.state.OS.LxcPath)
if err != nil {
return err
}
// Load cgroup abstraction
cg, err := d.cgroup(cc)
if err != nil {
return err
}
freeContainer := true
defer func() {
if freeContainer {
cc.Release()
}
}()
// Setup logging
logfile := d.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 := d.ConsoleBufferLogPath()
err = lxcSetConfigItem(cc, "lxc.console.logfile", consoleBufferLogFile)
if err != nil {
return err
}
}
if d.state.OS.ContainerCoreScheduling {
err = lxcSetConfigItem(cc, "lxc.sched.core", "1")
if err != nil {
return err
}
} else if d.state.OS.CoreScheduling {
err = lxcSetConfigItem(cc, "lxc.hook.start-host", fmt.Sprintf("/proc/%d/exe forkcoresched 1", os.Getpid()))
if err != nil {
return err
}
}
// Allow for lightweight init
d.cConfig = config
if !config {
if d.c != nil {
d.c.Release()
}
d.c = cc
freeContainer = false
return nil
}
if d.IsPrivileged() {
// Base config
toDrop := "sys_time sys_module sys_rawio"
if !d.state.OS.AppArmorStacking || d.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 d.IsPrivileged() && !d.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 d.IsPrivileged() && !d.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 d.IsPrivileged() && !d.state.OS.RunningInUserNS && d.state.OS.CGInfo.Supports(cgroup.Devices, cg) {
if d.state.OS.CGInfo.Layout == cgroup.CgroupsUnified {
err = lxcSetConfigItem(cc, "lxc.cgroup2.devices.deny", "a")
} else {
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 {
if d.state.OS.CGInfo.Layout == cgroup.CgroupsUnified {
err = lxcSetConfigItem(cc, "lxc.cgroup2.devices.allow", dev)
} else {
err = lxcSetConfigItem(cc, "lxc.cgroup.devices.allow", dev)
}
if err != nil {
return err
}
}
}
if d.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(d.architecture)
if err != nil {
personality, err = osarch.ArchitecturePersonality(d.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
}
// Call the onstart hook on start.
err = lxcSetConfigItem(cc, "lxc.hook.pre-start", fmt.Sprintf("/proc/%d/exe callhook %s %s %s start", os.Getpid(), shared.VarPath(""), strconv.Quote(d.Project()), strconv.Quote(d.Name())))
if err != nil {
return err
}
// Call the onstopns hook on stop but before namespaces are unmounted.
err = lxcSetConfigItem(cc, "lxc.hook.stop", fmt.Sprintf("%s callhook %s %s %s stopns", d.state.OS.ExecPath, shared.VarPath(""), strconv.Quote(d.Project()), strconv.Quote(d.Name())))
if err != nil {
return err
}
// Call the onstop hook on stop.
err = lxcSetConfigItem(cc, "lxc.hook.post-stop", fmt.Sprintf("%s callhook %s %s %s stop", d.state.OS.ExecPath, shared.VarPath(""), strconv.Quote(d.Project()), strconv.Quote(d.Name())))
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", d.Name())
if err != nil {
return err
}
// Setup devlxd
if d.expandedConfig["security.devlxd"] == "" || shared.IsTrue(d.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 d.state.OS.AppArmorAvailable {
if d.state.OS.AppArmorConfined || !d.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.InstanceProfileName(d)
/* 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 d.state.OS.AppArmorStacking && !d.state.OS.AppArmorStacked {
profile = fmt.Sprintf("%s//&:%s:", profile, apparmor.InstanceNamespaceName(d))
}
err := lxcSetConfigItem(cc, "lxc.apparmor.profile", profile)
if err != nil {
return err
}
}
}
// Setup Seccomp if necessary
if seccomp.InstanceNeedsPolicy(d) {
err = lxcSetConfigItem(cc, "lxc.seccomp.profile", seccomp.ProfilePath(d))
if err != nil {
return err
}
// Setup notification socket
// System requirement errors are handled during policy generation instead of here
ok, err := seccomp.InstanceNeedsIntercept(d.state, d)
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 := d.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 d.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(d.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 := d.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 := d.expandedConfig["nvidia.require.cuda"]
if nvidiaRequireCuda == "" {
err = lxcSetConfigItem(cc, "lxc.environment", fmt.Sprintf("NVIDIA_REQUIRE_CUDA=%s", nvidiaRequireCuda))
if err != nil {
return err
}
}
nvidiaRequireDriver := d.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 d.state.OS.CGInfo.Supports(cgroup.Memory, cg) {
memory := d.expandedConfig["limits.memory"]
memoryEnforce := d.expandedConfig["limits.memory.enforce"]
memorySwap := d.expandedConfig["limits.memory.swap"]
memorySwapPriority := d.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(valueInt)
if err != nil {
return err
}
} else {
if d.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) && (memorySwap == "" || shared.IsTrue(memorySwap)) {
err = cg.SetMemoryLimit(valueInt)
if err != nil {
return err
}
err = cg.SetMemorySwapLimit(0)
if err != nil {
return err
}
} else {
err = cg.SetMemoryLimit(valueInt)
if err != nil {
return err
}
}
// Set soft limit to value 10% less than hard limit
err = cg.SetMemorySoftLimit(int64(float64(valueInt) * 0.9))
if err != nil {
return err
}
}
}
if d.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
}
// Maximum priority (10) should be default swappiness (60).
err = cg.SetMemorySwappiness(int64(70 - priority))
if err != nil {
return err
}
}
}
}
// CPU limits
cpuPriority := d.expandedConfig["limits.cpu.priority"]
cpuAllowance := d.expandedConfig["limits.cpu.allowance"]
if (cpuPriority != "" || cpuAllowance != "") && d.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 && cpuCfsQuota != -1 {
err = cg.SetCPUCfsLimit(cpuCfsPeriod, cpuCfsQuota)
if err != nil {
return err
}
}
}
// Disk priority limits.
diskPriority := d.ExpandedConfig()["limits.disk.priority"]
if diskPriority != "" {
if d.state.OS.CGInfo.Supports(cgroup.BlkioWeight, nil) {
priorityInt, err := strconv.Atoi(diskPriority)
if err != nil {
return err
}
priority := priorityInt * 100
// Minimum valid value is 10
if priority == 0 {
priority = 10
}
err = cg.SetBlkioWeight(int64(priority))
if err != nil {
return err
}
} else {
return fmt.Errorf("Cannot apply limits.disk.priority as blkio.weight cgroup controller is missing")
}
}
// Processes
if d.state.OS.CGInfo.Supports(cgroup.Pids, cg) {
processes := d.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 d.state.OS.CGInfo.Supports(cgroup.Hugetlb, cg) {
for i, key := range shared.HugePageSizeKeys {
value := d.expandedConfig[key]
if value != "" {
value, err := units.ParseByteSizeString(value)
if err != nil {
return err
}
err = cg.SetHugepagesLimit(shared.HugePageSizeSuffix[i], value)
if err != nil {
return err
}
}
}
}
// Setup process limits
for k, v := range d.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 sysctls
for k, v := range d.expandedConfig {
if strings.HasPrefix(k, "linux.sysctl.") {
sysctlSuffix := strings.TrimPrefix(k, "linux.sysctl.")
sysctlKey := fmt.Sprintf("lxc.sysctl.%s", sysctlSuffix)
err = lxcSetConfigItem(cc, sysctlKey, v)
if err != nil {
return err
}
}
}
// Setup shmounts
if d.state.OS.LXCFeatures["mount_injection_file"] {
err = lxcSetConfigItem(cc, "lxc.mount.auto", fmt.Sprintf("shmounts:%s:/dev/.lxd-mounts", d.ShmountsPath()))
} else {
err = lxcSetConfigItem(cc, "lxc.mount.entry", fmt.Sprintf("%s dev/.lxd-mounts none bind,create=dir 0 0", d.ShmountsPath()))
}
if err != nil {
return err
}
if d.c != nil {
d.c.Release()
}
d.c = cc
freeContainer = false
return nil
}
var idmappedStorageMap map[unix.Fsid]idmap.IdmapStorageType = map[unix.Fsid]idmap.IdmapStorageType{}
var idmappedStorageMapLock sync.Mutex
// IdmappedStorage determines if the container can use idmapped mounts or shiftfs
func (d *lxc) IdmappedStorage(path string) idmap.IdmapStorageType {
var mode idmap.IdmapStorageType = idmap.IdmapStorageNone
if d.state.OS.Shiftfs {
// Fallback to shiftfs.
mode = idmap.IdmapStorageShiftfs
}
if !d.state.OS.LXCFeatures["idmapped_mounts_v2"] {
return mode
}
buf := &unix.Statfs_t{}
err := unix.Statfs(path, buf)
if err != nil {
// Log error but fallback to shiftfs
d.logger.Error("Failed to statfs", log.Ctx{"err": err})
return mode
}
idmappedStorageMapLock.Lock()
defer idmappedStorageMapLock.Unlock()
val, ok := idmappedStorageMap[buf.Fsid]
if ok {
// Return recorded idmapping type.
return val
}
if idmap.CanIdmapMount(path) {
// Use idmapped mounts.
mode = idmap.IdmapStorageIdmapped
}
idmappedStorageMap[buf.Fsid] = mode
return mode
}
func (d *lxc) devlxdEventSend(eventType string, eventMessage interface{}) error {
event := shared.Jmap{}
event["type"] = eventType
event["timestamp"] = time.Now()
event["metadata"] = eventMessage
return d.state.DevlxdEvents.Send(strconv.Itoa(d.ID()), eventType, eventMessage)
}
// RegisterDevices calls the Register() function on all of the instance's devices.
func (d *lxc) RegisterDevices() {
devices := d.ExpandedDevices()
for _, entry := range devices.Sorted() {
dev, _, err := d.deviceLoad(entry.Name, entry.Config)
if err == device.ErrUnsupportedDevType {
continue
}
if err != nil {
d.logger.Error("Failed to load device to register", log.Ctx{"err": err, "device": entry.Name})
continue
}
// Check whether device wants to register for any events.
err = dev.Register()
if err != nil {
d.logger.Error("Failed to register device", log.Ctx{"err": err, "device": entry.Name})
continue
}
}
}
// deviceLoad instantiates and validates a new device and returns it along with enriched config.
func (d *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 = d.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()
}
dev, err := device.New(d, d.state, deviceName, configCopy, d.deviceVolatileGetFunc(deviceName), d.deviceVolatileSetFunc(deviceName))
// Return device and config copy even if error occurs as caller may still use device.
return dev, configCopy, err
}
// deviceAdd loads a new device and calls its Add() function.
func (d *lxc) deviceAdd(deviceName string, rawConfig deviceConfig.Device, instanceRunning bool) error {
dev, _, err := d.deviceLoad(deviceName, rawConfig)
if err != nil {
return err
}
if instanceRunning && !dev.CanHotPlug() {
return fmt.Errorf("Device cannot be added when instance is running")
}
return dev.Add()
}
// deviceStart loads a new device and calls its Start() function.
func (d *lxc) deviceStart(deviceName string, rawConfig deviceConfig.Device, instanceRunning bool) (*deviceConfig.RunConfig, error) {
logger := logging.AddContext(d.logger, log.Ctx{"device": deviceName, "type": rawConfig["type"]})
logger.Debug("Starting device")
revert := revert.New()
defer revert.Fail()
dev, configCopy, err := d.deviceLoad(deviceName, rawConfig)
if err != nil {
return nil, err
}
if instanceRunning && !dev.CanHotPlug() {
return nil, fmt.Errorf("Device cannot be started when instance is running")
}
runConf, err := dev.Start()
if err != nil {
return nil, err
}
revert.Add(func() {
runConf, _ := dev.Stop()
if runConf != nil {
d.runHooks(runConf.PostHooks)
}
})
// 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 := d.deviceStaticShiftMounts(runConf.Mounts)
if err != nil {
return nil, err
}
}
// If container is running and then live attach device.
if instanceRunning {
// Attach mounts if requested.
if len(runConf.Mounts) > 0 {
err = d.deviceHandleMounts(runConf.Mounts)
if err != nil {
return nil, err
}
}
// Add cgroup rules if requested.
if len(runConf.CGroups) > 0 {
err = d.deviceAddCgroupRules(runConf.CGroups)
if err != nil {
return nil, err
}
}
// Attach network interface if requested.
if len(runConf.NetworkInterface) > 0 {
err = d.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 = d.runHooks(runConf.PostHooks)
if err != nil {
return nil, err
}
}
}
revert.Success()
return runConf, nil
}
// deviceStaticShiftMounts statically shift device mount files ownership to active idmap if needed.
func (d *lxc) deviceStaticShiftMounts(mounts []deviceConfig.MountEntryItem) error {
idmapSet, err := d.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 && !d.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.
d.logger.Debug("Failed to uidshift device", log.Ctx{"mountDevPath": mount.DevPath, "err": err})
}
}
}
return nil
}
// deviceAddCgroupRules live adds cgroup rules to a container.
func (d *lxc) deviceAddCgroupRules(cgroups []deviceConfig.RunConfigItem) error {
cg, err := d.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.") && (!d.isCurrentlyPrivileged() || d.state.OS.RunningInUserNS || !d.state.OS.CGInfo.Supports(cgroup.Devices, cg)) {
continue
}
// Add the new device cgroup rule.
err := d.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 (d *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 := d.initLXC(false)
if err != nil {
return err
}
// Add the interface to the container.
err = d.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 (d *lxc) deviceUpdate(deviceName string, rawConfig deviceConfig.Device, oldDevices deviceConfig.Devices, instanceRunning bool) error {
dev, _, err := d.deviceLoad(deviceName, rawConfig)
if err != nil {
return err
}
err = dev.Update(oldDevices, instanceRunning)
if err != nil {
return err
}
return nil
}
// deviceStop loads a new device and calls its Stop() function.
// Accepts a stopHookNetnsPath argument which is required when run from the onStopNS hook before the
// container's network namespace is unmounted (which is required for NIC device cleanup).
func (d *lxc) deviceStop(deviceName string, rawConfig deviceConfig.Device, instanceRunning bool, stopHookNetnsPath string) error {
logger := logging.AddContext(d.logger, log.Ctx{"device": deviceName, "type": rawConfig["type"]})
logger.Debug("Stopping device")
dev, configCopy, err := d.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 dev == nil {
return fmt.Errorf("Device stop validation failed for %q: %v", deviceName, err)
}
logger.Error("Device stop validation failed for", log.Ctx{"err": err})
}
if instanceRunning && !dev.CanHotPlug() {
return fmt.Errorf("Device cannot be stopped when instance is running")
}
runConf, err := dev.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 = d.deviceDetachNIC(configCopy, runConf.NetworkInterface, instanceRunning, stopHookNetnsPath)
if err != nil {
return err
}
}
// Add cgroup rules if requested and container is running.
if len(runConf.CGroups) > 0 && instanceRunning {
err = d.deviceAddCgroupRules(runConf.CGroups)
if err != nil {
return err
}
}
// Detach mounts if requested and container is running.
if len(runConf.Mounts) > 0 && instanceRunning {
err = d.deviceHandleMounts(runConf.Mounts)
if err != nil {
return err
}
}
// Run post stop hooks irrespective of run state of instance.
err = d.runHooks(runConf.PostHooks)
if err != nil {
return err
}
}
return nil
}
// deviceDetachNIC detaches a NIC device from a container.
// Accepts a stopHookNetnsPath argument which is required when run from the onStopNS hook before the
// container's network namespace is unmounted (which is required for NIC device cleanup).
func (d *lxc) deviceDetachNIC(configCopy map[string]string, netIF []deviceConfig.RunConfigItem, instanceRunning bool, 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 instanceRunning {
// For some reason, having network config confuses detach, so get our own go-lxc struct.
cname := project.Instance(d.Project(), d.Name())
cc, err := liblxc.NewContainer(cname, d.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: %q to %q", 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)) {
if stopHookNetnsPath == "" {
return fmt.Errorf("Cannot detach NIC device %q without stopHookNetnsPath being provided", devName)
}
err := d.detachInterfaceRename(stopHookNetnsPath, configCopy["name"], devName)
if err != nil {
return errors.Wrapf(err, "Failed to detach interface: %q to %q", configCopy["name"], devName)
}
d.logger.Debug("Detached NIC device interface", log.Ctx{"name": configCopy["name"], "devName": 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 (d *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
} else if opt == "ro" {
flags |= unix.MS_RDONLY
}
}
var idmapType idmap.IdmapStorageType = idmap.IdmapStorageNone
if mount.OwnerShift == deviceConfig.MountOwnerShiftDynamic {
idmapType = d.IdmappedStorage(mount.DevPath)
if idmapType == idmap.IdmapStorageNone {
return fmt.Errorf("Required idmapping abilities not available")
}
}
// Mount it into the container.
err := d.insertMount(mount.DevPath, mount.TargetPath, mount.FSType, flags, idmapType)
if err != nil {
return fmt.Errorf("Failed to add mount for device inside container: %s", err)
}
} else {
relativeTargetPath := strings.TrimPrefix(mount.TargetPath, "/")
if d.FileExists(relativeTargetPath) == nil {
err := d.removeMount(mount.TargetPath)
if err != nil {
return fmt.Errorf("Error unmounting the device path inside container: %s", err)
}
err = d.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.
d.logger.Warn("Could not remove the device path inside container", log.Ctx{"err": err})
}
}
}
}
return nil
}
// deviceRemove loads a new device and calls its Remove() function.
func (d *lxc) deviceRemove(deviceName string, rawConfig deviceConfig.Device, instanceRunning bool) error {
logger := logging.AddContext(d.logger, log.Ctx{"device": deviceName, "type": rawConfig["type"]})
dev, _, err := d.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 dev == nil {
return fmt.Errorf("Device remove validation failed for %q: %v", deviceName, err)
}
logger.Error("Device remove validation failed", log.Ctx{"err": err})
}
if instanceRunning && !dev.CanHotPlug() {
return fmt.Errorf("Device cannot be removed when instance is running")
}
return dev.Remove()
}
// DeviceEventHandler actions the results of a RunConfig after an event has occurred on a device.
func (d *lxc) DeviceEventHandler(runConf *deviceConfig.RunConfig) error {
// Device events can only be processed when the container is running.
if !d.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 := d.deviceStaticShiftMounts(runConf.Mounts)
if err != nil {
return err
}
err = d.deviceHandleMounts(runConf.Mounts)
if err != nil {
return err
}
}
// Add cgroup rules if requested.
if len(runConf.CGroups) > 0 {
err := d.deviceAddCgroupRules(runConf.CGroups)
if err != nil {
return err
}
}
// Run any post hooks requested.
err := d.runHooks(runConf.PostHooks)
if err != nil {
return err
}
// Generate uevent inside container if requested.
if len(runConf.Uevents) > 0 {
pidFdNr, pidFd := d.inheritInitPidFd()
if pidFdNr >= 0 {
defer pidFd.Close()
}
for _, eventParts := range runConf.Uevents {
ueventArray := make([]string, 6)
ueventArray[0] = "forkuevent"
ueventArray[1] = "inject"
ueventArray[2] = "--"
ueventArray[3] = fmt.Sprintf("%d", d.InitPID())
ueventArray[4] = fmt.Sprintf("%d", pidFdNr)
length := 0
for _, part := range eventParts {
length = length + len(part) + 1
}
ueventArray[5] = fmt.Sprintf("%d", length)
ueventArray = append(ueventArray, eventParts...)
_, _, err := shared.RunCommandSplit(nil, []*os.File{pidFd}, d.state.OS.ExecPath, ueventArray...)
if err != nil {
return err
}
}
}
return nil
}
func (d *lxc) handleIdmappedStorage() (idmap.IdmapStorageType, *idmap.IdmapSet, error) {
diskIdmap, err := d.DiskIdmap()
if err != nil {
return idmap.IdmapStorageNone, nil, errors.Wrap(err, "Set last ID map")
}
nextIdmap, err := d.NextIdmap()
if err != nil {
return idmap.IdmapStorageNone, nil, errors.Wrap(err, "Set ID map")
}
// Identical on-disk idmaps so no changes required.
if nextIdmap.Equals(diskIdmap) {
return idmap.IdmapStorageNone, nextIdmap, nil
}
// There's no on-disk idmap applied and the container can use idmapped
// storage.
idmapType := d.IdmappedStorage(d.RootfsPath())
if diskIdmap == nil && idmapType != idmap.IdmapStorageNone {
return idmapType, nextIdmap, nil
}
// We need to change the on-disk idmap but the container is protected
// against idmap changes.
if shared.IsTrue(d.expandedConfig["security.protection.shift"]) {
return idmap.IdmapStorageNone, nil, fmt.Errorf("Container is protected against filesystem shifting")
}
d.logger.Debug("Container idmap changed, remapping")
d.updateProgress("Remapping container filesystem")
storageType, err := d.getStorageType()
if err != nil {
return idmap.IdmapStorageNone, nil, errors.Wrap(err, "Storage type")
}
// Revert the currently applied on-disk idmap.
if diskIdmap != nil {
if storageType == "zfs" {
err = diskIdmap.UnshiftRootfs(d.RootfsPath(), storageDrivers.ShiftZFSSkipper)
} else if storageType == "btrfs" {
err = storageDrivers.UnshiftBtrfsRootfs(d.RootfsPath(), diskIdmap)
} else {
err = diskIdmap.UnshiftRootfs(d.RootfsPath(), nil)
}
if err != nil {
return idmap.IdmapStorageNone, nil, err
}
}
jsonDiskIdmap := "[]"
// If the container can't use idmapped storage apply the new on-disk
// idmap of the container now. Otherwise we will later instruct LXC to
// make use of idmapped storage.
if nextIdmap != nil && idmapType == idmap.IdmapStorageNone {
if storageType == "zfs" {
err = nextIdmap.ShiftRootfs(d.RootfsPath(), storageDrivers.ShiftZFSSkipper)
} else if storageType == "btrfs" {
err = storageDrivers.ShiftBtrfsRootfs(d.RootfsPath(), nextIdmap)
} else {
err = nextIdmap.ShiftRootfs(d.RootfsPath(), nil)
}
if err != nil {
return idmap.IdmapStorageNone, nil, err
}
idmapBytes, err := json.Marshal(nextIdmap.Idmap)
if err != nil {
return idmap.IdmapStorageNone, nil, err
}
jsonDiskIdmap = string(idmapBytes)
}
err = d.VolatileSet(map[string]string{"volatile.last_state.idmap": jsonDiskIdmap})
if err != nil {
return idmap.IdmapStorageNone, nextIdmap, errors.Wrapf(err, "Set volatile.last_state.idmap config key on container %q (id %d)", d.name, d.id)
}
d.updateProgress("")
return idmapType, nextIdmap, nil
}
// Start functions
func (d *lxc) startCommon() (string, []func() error, error) {
revert := revert.New()
defer revert.Fail()
// Load the go-lxc struct
err := d.initLXC(true)
if err != nil {
return "", nil, errors.Wrap(err, "Load go-lxc struct")
}
// Load any required kernel modules
kernelModules := d.expandedConfig["linux.kernel_modules"]
if kernelModules != "" {
for _, module := range strings.Split(kernelModules, ",") {
module = strings.TrimPrefix(module, " ")
err := util.LoadModule(module)
if err != nil {
return "", nil, fmt.Errorf("Failed to load kernel module '%s': %s", module, err)
}
}
}
// Rotate the log file.
logfile := d.LogFilePath()
if shared.PathExists(logfile) {
os.Remove(logfile + ".old")
err := os.Rename(logfile, logfile+".old")
if err != nil {
return "", nil, err
}
}
// Mount instance root volume.
_, err = d.mount()
if err != nil {
return "", nil, err
}
revert.Add(func() { d.unmount() })
idmapType, nextIdmap, err := d.handleIdmappedStorage()
if err != nil {
return "", nil, errors.Wrap(err, "Failed to handle idmapped storage")
}
var idmapBytes []byte
if nextIdmap == nil {
idmapBytes = []byte("[]")
} else {
idmapBytes, err = json.Marshal(nextIdmap.Idmap)
if err != nil {
return "", nil, err
}
}
if d.localConfig["volatile.idmap.current"] != string(idmapBytes) {
err = d.VolatileSet(map[string]string{"volatile.idmap.current": string(idmapBytes)})
if err != nil {
return "", nil, errors.Wrapf(err, "Set volatile.idmap.current config key on container %q (id %d)", d.name, d.id)
}
}
// Generate the Seccomp profile
if err := seccomp.CreateProfile(d.state, d); err != nil {
return "", nil, err
}
// Cleanup any existing leftover devices
d.removeUnixDevices()
d.removeDiskDevices()
// Create any missing directories.
err = os.MkdirAll(d.LogPath(), 0700)
if err != nil {
return "", nil, err
}
err = os.MkdirAll(d.DevicesPath(), 0711)
if err != nil {
return "", nil, err
}
err = os.MkdirAll(d.ShmountsPath(), 0711)
if err != nil {
return "", nil, err
}
volatileSet := make(map[string]string)
// Generate UUID if not present (do this before UpdateBackupFile() call).
instUUID := d.localConfig["volatile.uuid"]
if instUUID == "" {
instUUID = uuid.New()
volatileSet["volatile.uuid"] = instUUID
}
// Apply any volatile changes that need to be made.
err = d.VolatileSet(volatileSet)
if err != nil {
return "", nil, errors.Wrapf(err, "Failed setting volatile keys")
}
// Create the devices
postStartHooks := []func() error{}
nicID := -1
nvidiaDevices := []string{}
// Setup devices in sorted order, this ensures that device mounts are added in path order.
for _, entry := range d.expandedDevices.Sorted() {
dev := entry // Ensure device variable has local scope for revert.
// Start the device.
runConf, err := d.deviceStart(dev.Name, dev.Config, false)
if err != nil {
return "", nil, errors.Wrapf(err, "Failed to start device %q", dev.Name)
}
// Stop device on failure to setup container.
revert.Add(func() {
err := d.deviceStop(dev.Name, dev.Config, false, "")
if err != nil {
d.logger.Error("Failed to cleanup device", log.Ctx{"devName": dev.Name, "err": err})
}
})
if runConf == nil {
continue
}
if runConf.Revert != nil {
revert.Add(runConf.Revert.Fail)
}
// 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(d.c, "lxc.rootfs.backend", "dir")
if err == nil {
value := d.c.ConfigItem("lxc.rootfs.backend")
if len(value) == 0 || value[0] != "dir" {
lxcSetConfigItem(d.c, "lxc.rootfs.backend", "")
}
}
}
if util.RuntimeLiblxcVersionAtLeast(2, 1, 0) {
rootfsPath := fmt.Sprintf("dir:%s", runConf.RootFS.Path)
err = lxcSetConfigItem(d.c, "lxc.rootfs.path", rootfsPath)
} else {
err = lxcSetConfigItem(d.c, "lxc.rootfs", runConf.RootFS.Path)
}
if err != nil {
return "", nil, errors.Wrapf(err, "Failed to setup device rootfs '%s'", dev.Name)
}
if len(runConf.RootFS.Opts) > 0 {
err = lxcSetConfigItem(d.c, "lxc.rootfs.options", strings.Join(runConf.RootFS.Opts, ","))
if err != nil {
return "", nil, errors.Wrapf(err, "Failed to setup device rootfs '%s'", dev.Name)
}
}
if !d.IsPrivileged() {
if idmapType == idmap.IdmapStorageIdmapped {
err = lxcSetConfigItem(d.c, "lxc.rootfs.options", "idmap=container")
if err != nil {
return "", nil, errors.Wrapf(err, "Failed to set \"idmap=container\" rootfs option")
}
} else if idmapType == idmap.IdmapStorageShiftfs {
// Host side mark mount.
err = lxcSetConfigItem(d.c, "lxc.hook.pre-start", fmt.Sprintf("/bin/mount -t shiftfs -o mark,passthrough=3 %s %s", strconv.Quote(d.RootfsPath()), strconv.Quote(d.RootfsPath())))
if err != nil {
return "", nil, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
// Container side shift mount.
err = lxcSetConfigItem(d.c, "lxc.hook.pre-mount", fmt.Sprintf("/bin/mount -t shiftfs -o passthrough=3 %s %s", strconv.Quote(d.RootfsPath()), strconv.Quote(d.RootfsPath())))
if err != nil {
return "", nil, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
// Host side umount of mark mount.
err = lxcSetConfigItem(d.c, "lxc.hook.start-host", fmt.Sprintf("/bin/umount -l %s", strconv.Quote(d.RootfsPath())))
if err != nil {
return "", nil, 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 {
if strings.HasPrefix(rule.Key, "devices.") && (!d.isCurrentlyPrivileged() || d.state.OS.RunningInUserNS) {
continue
}
if d.state.OS.CGInfo.Layout == cgroup.CgroupsUnified {
err = lxcSetConfigItem(d.c, fmt.Sprintf("lxc.cgroup2.%s", rule.Key), rule.Value)
} else {
err = lxcSetConfigItem(d.c, fmt.Sprintf("lxc.cgroup.%s", rule.Key), rule.Value)
}
if err != nil {
return "", nil, 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 "", nil, errors.Wrapf(fmt.Errorf("liblxc 3.0 is required for mount propagation configuration"), "Failed to setup device mount '%s'", dev.Name)
}
mntOptions := strings.Join(mount.Opts, ",")
if mount.OwnerShift == deviceConfig.MountOwnerShiftDynamic && !d.IsPrivileged() {
switch d.IdmappedStorage(mount.DevPath) {
case idmap.IdmapStorageIdmapped:
mntOptions = strings.Join([]string{mntOptions, "idmap=container"}, ",")
case idmap.IdmapStorageShiftfs:
err = lxcSetConfigItem(d.c, "lxc.hook.pre-start", fmt.Sprintf("/bin/mount -t shiftfs -o mark,passthrough=3 %s %s", strconv.Quote(mount.DevPath), strconv.Quote(mount.DevPath)))
if err != nil {
return "", nil, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
err = lxcSetConfigItem(d.c, "lxc.hook.pre-mount", fmt.Sprintf("/bin/mount -t shiftfs -o passthrough=3 %s %s", strconv.Quote(mount.DevPath), strconv.Quote(mount.DevPath)))
if err != nil {
return "", nil, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
err = lxcSetConfigItem(d.c, "lxc.hook.start-host", fmt.Sprintf("/bin/umount -l %s", strconv.Quote(mount.DevPath)))
if err != nil {
return "", nil, errors.Wrapf(err, "Failed to setup device mount shiftfs '%s'", dev.Name)
}
case idmap.IdmapStorageNone:
return "", nil, errors.Wrapf(fmt.Errorf("idmapping abilities are required but aren't supported on system"), "Failed to setup device mount '%s'", dev.Name)
}
}
mntVal := fmt.Sprintf("%s %s %s %s %d %d", shared.EscapePathFstab(mount.DevPath), shared.EscapePathFstab(mount.TargetPath), mount.FSType, mntOptions, mount.Freq, mount.PassNo)
err = lxcSetConfigItem(d.c, "lxc.mount.entry", mntVal)
if err != nil {
return "", nil, 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(d.c, fmt.Sprintf("%s.%d.%s", networkKeyPrefix, nicID, nicItem.Key), nicItem.Value)
if err != nil {
return "", nil, 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...)
}
// Build list of NVIDIA GPUs (used for MIG).
if len(runConf.GPUDevice) > 0 {
for _, entry := range runConf.GPUDevice {
if entry.Key == device.GPUNvidiaDeviceKey {
nvidiaDevices = append(nvidiaDevices, entry.Value)
}
}
}
}
// Override NVIDIA_VISIBLE_DEVICES if we have devices that need it.
if len(nvidiaDevices) > 0 {
err = lxcSetConfigItem(d.c, "lxc.environment", fmt.Sprintf("NVIDIA_VISIBLE_DEVICES=%s", strings.Join(nvidiaDevices, ",")))
if err != nil {
return "", nil, errors.Wrapf(err, "Unable to set NVIDIA_VISIBLE_DEVICES in LXC environment")
}
}
// Load the LXC raw config.
err = d.loadRawLXCConfig()
if err != nil {
return "", nil, err
}
// Generate the LXC config
configPath := filepath.Join(d.LogPath(), "lxc.conf")
err = d.c.SaveConfigFile(configPath)
if err != nil {
os.Remove(configPath)
return "", nil, err
}
// Set ownership to match container root
currentIdmapset, err := d.CurrentIdmap()
if err != nil {
return "", nil, err
}
uid := int64(0)
if currentIdmapset != nil {
uid, _ = currentIdmapset.ShiftFromNs(0, 0)
}
err = os.Chown(d.Path(), int(uid), 0)
if err != nil {
return "", nil, err
}
// We only need traversal by root in the container
err = os.Chmod(d.Path(), 0100)
if err != nil {
return "", nil, err
}
// If starting stateless, wipe state
if !d.IsStateful() && shared.PathExists(d.StatePath()) {
os.RemoveAll(d.StatePath())
}
// Unmount any previously mounted shiftfs
unix.Unmount(d.RootfsPath(), unix.MNT_DETACH)
// Snapshot if needed.
err = d.startupSnapshot(d)
if err != nil {
return "", nil, err
}
revert.Success()
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 (d *lxc) detachInterfaceRename(netns string, ifName string, hostName string) error {
lxdPID := os.Getpid()
// Run forknet detach
_, err := shared.RunCommand(
d.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 (d *lxc) Start(stateful bool) error {
d.logger.Debug("Start started", log.Ctx{"stateful": stateful})
defer d.logger.Debug("Start finished", log.Ctx{"stateful": stateful})
// Check that we are startable before creating an operation lock, so if the instance is in the
// process of stopping we don't prevent the stop hooks from running due to our start operation lock.
err := d.isStartableStatusCode(d.statusCode())
if err != nil {
return err
}
var ctxMap log.Ctx
// Setup a new operation
op, err := operationlock.CreateWaitGet(d.Project(), d.Name(), operationlock.ActionStart, []operationlock.Action{operationlock.ActionRestart, operationlock.ActionRestore}, false, false)
if err != nil {
if errors.Is(err, operationlock.ErrNonReusuableSucceeded) {
// An existing matching operation has now succeeded, return.
return nil
}
return errors.Wrap(err, "Create container start operation")
}
defer op.Done(nil)
if !daemon.SharedMountsSetup {
err = fmt.Errorf("Daemon failed to setup shared mounts base. Does security.nesting need to be turned on?")
op.Done(err)
return err
}
// Run the shared start code
configPath, postStartHooks, err := d.startCommon()
if err != nil {
op.Done(err)
return err
}
ctxMap = log.Ctx{
"action": op.Action(),
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate,
"stateful": stateful}
if op.Action() == "start" {
d.logger.Info("Starting container", ctxMap)
}
// If stateful, restore now
if stateful {
if !d.stateful {
err = fmt.Errorf("Container has no existing state to restore")
op.Done(err)
return err
}
criuMigrationArgs := instance.CriuMigrationArgs{
Cmd: liblxc.MIGRATE_RESTORE,
StateDir: d.StatePath(),
Function: "snapshot",
Stop: false,
ActionScript: false,
DumpDir: "",
PreDumpDir: "",
}
err := d.Migrate(&criuMigrationArgs)
if err != nil && !d.IsRunning() {
op.Done(err)
return errors.Wrap(err, "Migrate")
}
os.RemoveAll(d.StatePath())
d.stateful = false
err = d.state.Cluster.UpdateInstanceStatefulFlag(d.id, false)
if err != nil {
op.Done(err)
return errors.Wrap(err, "Start container")
}
// Run any post start hooks.
err = d.runHooks(postStartHooks)
if err != nil {
op.Done(err) // Must come before Stop() otherwise stop will not proceed.
// Attempt to stop container.
d.Stop(false)
return err
}
if op.Action() == "start" {
d.logger.Info("Started container", ctxMap)
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceStarted.Event(d, nil))
}
return nil
} else if d.stateful {
/* stateless start required when we have state, let's delete it */
err := os.RemoveAll(d.StatePath())
if err != nil {
op.Done(err)
return err
}
d.stateful = false
err = d.state.Cluster.UpdateInstanceStatefulFlag(d.id, false)
if err != nil {
op.Done(err)
return errors.Wrap(err, "Persist stateful flag")
}
}
// Update the backup.yaml file just before starting the instance process, but after all devices have been
// setup, so that the backup file contains the volatile keys used for this instance start, so that they
// can be used for instance cleanup.
err = d.UpdateBackupFile()
if err != nil {
op.Done(err)
return err
}
name := project.Instance(d.Project(), d.name)
// Start the LXC container
_, err = shared.RunCommand(
d.state.OS.ExecPath,
"forkstart",
name,
d.state.OS.LxcPath,
configPath)
if err != nil && !d.IsRunning() {
// Attempt to extract the LXC errors
lxcLog := ""
logPath := filepath.Join(d.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:], " "))
}
}
}
d.logger.Error("Failed starting container", ctxMap)
// Return the actual error
op.Done(err)
return err
}
// Run any post start hooks.
err = d.runHooks(postStartHooks)
if err != nil {
op.Done(err) // Must come before Stop() otherwise stop will not proceed.
// Attempt to stop container.
d.Stop(false)
return err
}
if op.Action() == "start" {
d.logger.Info("Started container", ctxMap)
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceStarted.Event(d, nil))
}
return nil
}
// OnHook is the top-level hook handler.
func (d *lxc) OnHook(hookName string, args map[string]string) error {
switch hookName {
case instance.HookStart:
return d.onStart(args)
case instance.HookStopNS:
return d.onStopNS(args)
case instance.HookStop:
return d.onStop(args)
default:
return instance.ErrNotImplemented
}
}
// onStart implements the start hook.
func (d *lxc) onStart(_ map[string]string) error {
// Make sure we can't call go-lxc functions by mistake
d.fromHook = true
// Load the container AppArmor profile
err := apparmor.InstanceLoad(d.state, d)
if err != nil {
return err
}
// Template anything that needs templating
key := "volatile.apply_template"
if d.localConfig[key] != "" {
// Run any template that needs running
err = d.templateApplyNow(instance.TemplateTrigger(d.localConfig[key]))
if err != nil {
apparmor.InstanceUnload(d.state, d)
return err
}
// Remove the volatile key from the DB
err := d.state.Cluster.DeleteInstanceConfigKey(d.id, key)
if err != nil {
apparmor.InstanceUnload(d.state, d)
return err
}
}
err = d.templateApplyNow("start")
if err != nil {
apparmor.InstanceUnload(d.state, d)
return err
}
// Trigger a rebalance
cgroup.TaskSchedulerTrigger("container", d.name, "started")
// Apply network priority
if d.expandedConfig["limits.network.priority"] != "" {
go func(d *lxc) {
d.fromHook = false
err := d.setNetworkPriority()
if err != nil {
d.logger.Error("Failed to apply network priority", log.Ctx{"err": err})
}
}(d)
}
// Record last start state.
err = d.recordLastState()
if err != nil {
return err
}
return nil
}
// Stop functions
func (d *lxc) Stop(stateful bool) error {
d.logger.Debug("Stop started", log.Ctx{"stateful": stateful})
defer d.logger.Debug("Stop finished", log.Ctx{"stateful": stateful})
// Must be run prior to creating the operation lock.
if !d.IsRunning() {
return ErrInstanceIsStopped
}
// Setup a new operation
op, err := operationlock.CreateWaitGet(d.Project(), d.Name(), operationlock.ActionStop, []operationlock.Action{operationlock.ActionRestart, operationlock.ActionRestore}, false, true)
if err != nil {
if errors.Is(err, operationlock.ErrNonReusuableSucceeded) {
// An existing matching operation has now succeeded, return.
return nil
}
return err
}
ctxMap := log.Ctx{
"action": op.Action(),
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate,
"stateful": stateful}
if op.Action() == "stop" {
d.logger.Info("Stopping container", ctxMap)
}
// Handle stateful stop
if stateful {
// Cleanup any existing state
stateDir := d.StatePath()
os.RemoveAll(stateDir)
err := os.MkdirAll(stateDir, 0700)
if err != nil {
op.Done(err)
return err
}
criuMigrationArgs := instance.CriuMigrationArgs{
Cmd: liblxc.MIGRATE_DUMP,
StateDir: stateDir,
Function: "snapshot",
Stop: true,
ActionScript: false,
DumpDir: "",
PreDumpDir: "",
}
// Checkpoint
err = d.Migrate(&criuMigrationArgs)
if err != nil {
op.Done(err)
return err
}
err = op.Wait()
if err != nil && d.IsRunning() {
return err
}
d.stateful = true
err = d.state.Cluster.UpdateInstanceStatefulFlag(d.id, true)
if err != nil {
d.logger.Error("Failed stopping container", ctxMap)
return err
}
d.logger.Info("Stopped container", ctxMap)
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceStopped.Event(d, nil))
return nil
} else if shared.PathExists(d.StatePath()) {
os.RemoveAll(d.StatePath())
}
// Release liblxc container once done.
defer func() {
d.release()
}()
// Load the go-lxc struct
if d.expandedConfig["raw.lxc"] != "" {
err = d.initLXC(true)
if err != nil {
op.Done(err)
return err
}
// Load the config.
err = d.loadRawLXCConfig()
if err != nil {
return err
}
} else {
err = d.initLXC(false)
if err != nil {
op.Done(err)
return err
}
}
// Load cgroup abstraction
cg, err := d.cgroup(nil)
if err != nil {
op.Done(err)
return err
}
// Fork-bomb mitigation, prevent forking from this point on
if d.state.OS.CGInfo.Supports(cgroup.Pids, cg) {
// Attempt to disable forking new processes
cg.SetMaxProcesses(0)
} else if d.state.OS.CGInfo.Supports(cgroup.Freezer, cg) {
// Attempt to freeze the container
freezer := make(chan bool, 1)
go func() {
d.Freeze()
freezer <- true
}()
select {
case <-freezer:
case <-time.After(time.Second * 5):
d.Unfreeze()
}
}
err = d.c.Stop()
if err != nil {
op.Done(err)
return err
}
// Wait for operation lock to be Done. This is normally completed by onStop which picks up the same
// operation lock and then marks it as Done after the instance stops and the devices have been cleaned up.
// However if the operation has failed for another reason we will collect the error here.
err = op.Wait()
status := d.statusCode()
if status != api.Stopped {
errPrefix := fmt.Errorf("Failed stopping instance, status is %q", status)
if err != nil {
return fmt.Errorf("%s: %w", errPrefix.Error(), err)
}
return errPrefix
} else if op.Action() == "stop" {
// If instance stopped, send lifecycle event (even if there has been an error cleaning up).
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceStopped.Event(d, nil))
}
// Now handle errors from stop sequence and return to caller if wasn't completed cleanly.
if err != nil {
return err
}
return nil
}
// Shutdown stops the instance.
func (d *lxc) Shutdown(timeout time.Duration) error {
d.logger.Debug("Shutdown started", log.Ctx{"timeout": timeout})
defer d.logger.Debug("Shutdown finished", log.Ctx{"timeout": timeout})
// Must be run prior to creating the operation lock.
statusCode := d.statusCode()
if !d.isRunningStatusCode(statusCode) {
if statusCode == api.Error {
return fmt.Errorf("The instance cannot be cleanly shutdown as in %s status", statusCode)
}
return ErrInstanceIsStopped
}
// Setup a new operation
op, err := operationlock.CreateWaitGet(d.Project(), d.Name(), operationlock.ActionStop, []operationlock.Action{operationlock.ActionRestart}, true, true)
if err != nil {
if errors.Is(err, operationlock.ErrNonReusuableSucceeded) {
// An existing matching operation has now succeeded, return.
return nil
}
return err
}
// If frozen, resume so the signal can be handled.
if d.IsFrozen() {
err := d.Unfreeze()
if err != nil {
return err
}
}
ctxMap := log.Ctx{
"action": "shutdown",
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate,
"timeout": timeout}
if op.Action() == "stop" {
d.logger.Info("Shutting down container", ctxMap)
}
// Release liblxc container once done.
defer func() {
d.release()
}()
// Load the go-lxc struct
if d.expandedConfig["raw.lxc"] != "" {
err = d.initLXC(true)
if err != nil {
op.Done(err)
return err
}
err = d.loadRawLXCConfig()
if err != nil {
return err
}
} else {
err = d.initLXC(false)
if err != nil {
op.Done(err)
return err
}
}
chResult := make(chan error)
go func() {
chResult <- d.c.Shutdown(timeout)
}()
d.logger.Debug("Shutdown request sent to instance")
for {
select {
case err = <-chResult:
// Shutdown request has returned with a result.
if err != nil {
// If shutdown failed, cancel operation with the error, otherwise expect the
// onStop() hook to cancel operation when done.
op.Done(err)
}
case <-time.After((operationlock.TimeoutSeconds / 2) * time.Second):
// Keep the operation alive so its around for onStop() if the instance takes
// longer than the default 30s that the operation is kept alive for.
op.Reset()
continue
}
break
}
// Wait for operation lock to be Done. This is normally completed by onStop which picks up the same
// operation lock and then marks it as Done after the instance stops and the devices have been cleaned up.
// However if the operation has failed for another reason we will collect the error here.
err = op.Wait()
status := d.statusCode()
if status != api.Stopped {
errPrefix := fmt.Errorf("Failed shutting down instance, status is %q", status)
if err != nil {
return fmt.Errorf("%s: %w", errPrefix.Error(), err)
}
return errPrefix
} else if op.Action() == "stop" {
// If instance stopped, send lifecycle event (even if there has been an error cleaning up).
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceShutdown.Event(d, nil))
}
// Now handle errors from shutdown sequence and return to caller if wasn't completed cleanly.
if err != nil {
return err
}
return nil
}
// Restart restart the instance.
func (d *lxc) Restart(timeout time.Duration) error {
ctxMap := log.Ctx{
"action": "shutdown",
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate,
"timeout": timeout}
d.logger.Info("Restarting container", ctxMap)
err := d.restartCommon(d, timeout)
if err != nil {
return err
}
d.logger.Info("Restarted container", ctxMap)
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceRestarted.Event(d, 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 (d *lxc) onStopNS(args map[string]string) error {
target := args["target"]
netns := args["netns"]
// Validate target.
if !shared.StringInSlice(target, []string{"stop", "reboot"}) {
d.logger.Error("Container sent invalid target to OnStopNS", log.Ctx{"target": target})
return fmt.Errorf("Invalid stop target %q", target)
}
// Create/pick up operation, but don't complete it as we leave operation running for the onStop hook below.
_, _, err := d.onStopOperationSetup(target)
if err != nil {
return err
}
// Clean up devices.
d.cleanupDevices(false, 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 (d *lxc) onStop(args map[string]string) error {
target := args["target"]
// Validate target
if !shared.StringInSlice(target, []string{"stop", "reboot"}) {
d.logger.Error("Container sent invalid target to OnStop", log.Ctx{"target": target})
return fmt.Errorf("Invalid stop target: %s", target)
}
// Create/pick up operation.
op, instanceInitiated, err := d.onStopOperationSetup(target)
if err != nil {
return err
}
// Make sure we can't call go-lxc functions by mistake
d.fromHook = true
// Record power state.
err = d.VolatileSet(map[string]string{"volatile.last_state.power": "STOPPED"})
if err != nil {
// Don't return an error here as we still want to cleanup the instance even if DB not available.
d.logger.Error("Failed recording last power state", log.Ctx{"err": err})
}
go func(d *lxc, target string, op *operationlock.InstanceOperation) {
d.fromHook = false
err = nil
// Unlock on return
defer op.Done(nil)
// Wait for other post-stop actions to be done and the container actually stopping.
d.IsRunning()
d.logger.Debug("Container stopped, cleaning up")
// Clean up devices.
d.cleanupDevices(false, "")
// Remove directory ownership (to avoid issue if uidmap is re-used)
err := os.Chown(d.Path(), 0, 0)
if err != nil {
op.Done(errors.Wrap(err, "Failed clearing ownership"))
return
}
err = os.Chmod(d.Path(), 0100)
if err != nil {
op.Done(errors.Wrap(err, "Failed clearing permissions"))
return
}
// Stop the storage for this container
op.Reset()
_, err = d.unmount()
if err != nil {
err = fmt.Errorf("Failed unmounting instance: %w", err)
op.Done(err)
return
}
// Unload the apparmor profile
err = apparmor.InstanceUnload(d.state, d)
if err != nil {
op.Done(errors.Wrap(err, "Failed to destroy apparmor namespace"))
return
}
// Clean all the unix devices
err = d.removeUnixDevices()
if err != nil {
op.Done(errors.Wrap(err, "Failed to remove unix devices"))
return
}
// Clean all the disk devices
err = d.removeDiskDevices()
if err != nil {
op.Done(errors.Wrap(err, "Failed to remove disk devices"))
return
}
// Log and emit lifecycle if not user triggered
if instanceInitiated {
ctxMap := log.Ctx{
"action": target,
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate,
"stateful": false,
}
d.logger.Info("Shut down container", ctxMap)
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceShutdown.Event(d, nil))
}
// Reboot the container
if target == "reboot" {
// Start the container again
err = d.Start(false)
if err != nil {
op.Done(errors.Wrap(err, "Failed restarting container"))
return
}
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceRestarted.Event(d, nil))
return
}
// Trigger a rebalance
cgroup.TaskSchedulerTrigger("container", d.name, "stopped")
// Destroy ephemeral containers
if d.ephemeral {
err = d.Delete(true)
if err != nil {
op.Done(errors.Wrap(err, "Failed deleting ephemeral container"))
return
}
}
}(d, target, op)
return nil
}
// cleanupDevices performs any needed device cleanup steps when container is stopped.
// Accepts a stopHookNetnsPath argument which is required when run from the onStopNS hook before the
// container's network namespace is unmounted (which is required for NIC device cleanup).
func (d *lxc) cleanupDevices(instanceRunning bool, stopHookNetnsPath string) {
for _, dev := range d.expandedDevices.Reversed() {
// Only stop NIC devices when run from the onStopNS hook, and stop all other devices when run from
// the onStop hook. This way disk devices are stopped after the instance has been fully stopped.
if (stopHookNetnsPath != "" && dev.Config["type"] != "nic") || (stopHookNetnsPath == "" && dev.Config["type"] == "nic") {
continue
}
// Use the device interface if device supports it.
err := d.deviceStop(dev.Name, dev.Config, instanceRunning, stopHookNetnsPath)
if err == device.ErrUnsupportedDevType {
continue
} else if err != nil {
d.logger.Error("Failed to stop device", log.Ctx{"devName": dev.Name, "err": err})
}
}
}
// Freeze functions.
func (d *lxc) Freeze() error {
ctxMap := log.Ctx{
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate}
// Check that we're running
if !d.IsRunning() {
return fmt.Errorf("The container isn't running")
}
cg, err := d.cgroup(nil)
if err != nil {
return err
}
// Check if the CGroup is available
if !d.state.OS.CGInfo.Supports(cgroup.Freezer, cg) {
d.logger.Info("Unable to freeze container (lack of kernel support)", ctxMap)
return nil
}
// Check that we're not already frozen
if d.IsFrozen() {
return fmt.Errorf("The container is already frozen")
}
d.logger.Info("Freezing container", ctxMap)
// Load the go-lxc struct
err = d.initLXC(false)
if err != nil {
ctxMap["err"] = err
d.logger.Error("Failed freezing container", ctxMap)
return err
}
err = d.c.Freeze()
if err != nil {
ctxMap["err"] = err
d.logger.Error("Failed freezing container", ctxMap)
return err
}
d.logger.Info("Froze container", ctxMap)
d.state.Events.SendLifecycle(d.project, lifecycle.InstancePaused.Event(d, nil))
return err
}
// Unfreeze unfreezes the instance.
func (d *lxc) Unfreeze() error {
ctxMap := log.Ctx{
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate}
// Check that we're running
if !d.IsRunning() {
return fmt.Errorf("The container isn't running")
}
cg, err := d.cgroup(nil)
if err != nil {
return err
}
// Check if the CGroup is available
if !d.state.OS.CGInfo.Supports(cgroup.Freezer, cg) {
d.logger.Info("Unable to unfreeze container (lack of kernel support)", ctxMap)
return nil
}
// Check that we're frozen
if !d.IsFrozen() {
return fmt.Errorf("The container is already running")
}
d.logger.Info("Unfreezing container", ctxMap)
// Load the go-lxc struct
err = d.initLXC(false)
if err != nil {
d.logger.Error("Failed unfreezing container", ctxMap)
return err
}
err = d.c.Unfreeze()
if err != nil {
d.logger.Error("Failed unfreezing container", ctxMap)
}
d.logger.Info("Unfroze container", ctxMap)
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceResumed.Event(d, nil))
return err
}
// Get lxc container state, with 1 second timeout.
// If we don't get a reply, assume the lxc monitor is unresponsive.
func (d *lxc) getLxcState() (liblxc.State, error) {
if d.IsSnapshot() {
return liblxc.StateMap["STOPPED"], nil
}
// Load the go-lxc struct
err := d.initLXC(false)
if err != nil {
return liblxc.StateMap["STOPPED"], err
}
if d.c == nil {
return liblxc.StateMap["STOPPED"], nil
}
monitor := make(chan liblxc.State, 1)
go func(c *liblxc.Container) {
monitor <- c.State()
}(d.c)
select {
case state := <-monitor:
return state, nil
case <-time.After(5 * time.Second):
return liblxc.StateMap["FROZEN"], fmt.Errorf("Monitor is unresponsive")
}
}
// Render renders the state of the instance.
func (d *lxc) Render(options ...func(response interface{}) error) (interface{}, interface{}, error) {
// Ignore err as the arch string on error is correct (unknown)
architectureName, _ := osarch.ArchitectureName(d.architecture)
if d.IsSnapshot() {
// Prepare the ETag
etag := []interface{}{d.expiryDate}
snapState := api.InstanceSnapshot{
CreatedAt: d.creationDate,
ExpandedConfig: d.expandedConfig,
ExpandedDevices: d.expandedDevices.CloneNative(),
LastUsedAt: d.lastUsedDate,
Name: strings.SplitN(d.name, "/", 2)[1],
Stateful: d.stateful,
Size: -1, // Default to uninitialised/error state (0 means no CoW usage).
}
snapState.Architecture = architectureName
snapState.Config = d.localConfig
snapState.Devices = d.localDevices.CloneNative()
snapState.Ephemeral = d.ephemeral
snapState.Profiles = d.profiles
snapState.ExpiresAt = d.expiryDate
for _, option := range options {
err := option(&snapState)
if err != nil {
return nil, nil, err
}
}
return &snapState, etag, nil
}
// Prepare the ETag
etag := []interface{}{d.architecture, d.localConfig, d.localDevices, d.ephemeral, d.profiles}
statusCode := d.statusCode()
instState := api.Instance{
ExpandedConfig: d.expandedConfig,
ExpandedDevices: d.expandedDevices.CloneNative(),
Name: d.name,
Status: statusCode.String(),
StatusCode: statusCode,
Location: d.node,
Type: d.Type().String(),
}
instState.Description = d.description
instState.Architecture = architectureName
instState.Config = d.localConfig
instState.CreatedAt = d.creationDate
instState.Devices = d.localDevices.CloneNative()
instState.Ephemeral = d.ephemeral
instState.LastUsedAt = d.lastUsedDate
instState.Profiles = d.profiles
instState.Stateful = d.stateful
instState.Project = d.project
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 (d *lxc) RenderFull() (*api.InstanceFull, interface{}, error) {
if d.IsSnapshot() {
return nil, nil, fmt.Errorf("RenderFull only works with containers")
}
// Get the Container struct
base, etag, err := d.Render()
if err != nil {
return nil, nil, err
}
// Convert to ContainerFull
ct := api.InstanceFull{Instance: *base.(*api.Instance)}
// Add the ContainerState
ct.State, err = d.renderState(ct.StatusCode)
if err != nil {
return nil, nil, err
}
// Add the ContainerSnapshots
snaps, err := d.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 := d.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 (d *lxc) renderState(statusCode api.StatusCode) (*api.InstanceState, error) {
status := api.InstanceState{
Status: statusCode.String(),
StatusCode: statusCode,
}
if d.isRunningStatusCode(statusCode) {
pid := d.InitPID()
status.CPU = d.cpuState()
status.Memory = d.memoryState()
status.Network = d.networkState()
status.Pid = int64(pid)
status.Processes = d.processesState()
}
status.Disk = d.diskState()
d.release()
return &status, nil
}
// RenderState renders just the running state of the instance.
func (d *lxc) RenderState() (*api.InstanceState, error) {
return d.renderState(d.statusCode())
}
// Snapshot takes a new snapshot.
func (d *lxc) Snapshot(name string, expiry time.Time, stateful bool) error {
// Deal with state.
if stateful {
// Quick checks.
if !d.IsRunning() {
return fmt.Errorf("Unable to create a stateful snapshot. The instance isn't running")
}
_, err := exec.LookPath("criu")
if err != nil {
return fmt.Errorf("Unable to create a stateful snapshot. CRIU isn't installed")
}
/* TODO: ideally we would freeze here and unfreeze below after
* we've copied the filesystem, to make sure there are no
* changes by the container while snapshotting. Unfortunately
* there is abug in CRIU where it doesn't leave the container
* in the same state it found it w.r.t. freezing, i.e. CRIU
* freezes too, and then /always/ thaws, even if the container
* was frozen. Until that's fixed, all calls to Unfreeze()
* after snapshotting will fail.
*/
criuMigrationArgs := instance.CriuMigrationArgs{
Cmd: liblxc.MIGRATE_DUMP,
StateDir: d.StatePath(),
Function: "snapshot",
Stop: false,
ActionScript: false,
DumpDir: "",
PreDumpDir: "",
}
// Create the state path and Make sure we don't keep state around after the snapshot has been made.
err = os.MkdirAll(d.StatePath(), 0700)
if err != nil {
return err
}
defer os.RemoveAll(d.StatePath())
// Dump the state.
err = d.Migrate(&criuMigrationArgs)
if err != nil {
return err
}
}
return d.snapshotCommon(d, name, expiry, stateful)
}
// Restore restores a snapshot.
func (d *lxc) Restore(sourceContainer instance.Instance, stateful bool) error {
var ctxMap log.Ctx
op, err := operationlock.Create(d.Project(), d.Name(), operationlock.ActionRestore, false, false)
if err != nil {
return errors.Wrap(err, "Create restore operation")
}
defer op.Done(nil)
// Stop the container.
wasRunning := false
if d.IsRunning() {
wasRunning = true
ephemeral := d.IsEphemeral()
if ephemeral {
// Unset ephemeral flag.
args := db.InstanceArgs{
Architecture: d.Architecture(),
Config: d.LocalConfig(),
Description: d.Description(),
Devices: d.LocalDevices(),
Ephemeral: false,
Profiles: d.Profiles(),
Project: d.Project(),
Type: d.Type(),
Snapshot: d.IsSnapshot(),
}
err := d.Update(args, false)
if err != nil {
op.Done(err)
return err
}
// On function return, set the flag back on.
defer func() {
args.Ephemeral = ephemeral
d.Update(args, false)
}()
}
// This will unmount the container storage.
err := d.Stop(false)
if err != nil {
op.Done(err)
return err
}
// Refresh the operation as that one is now complete.
op, err = operationlock.Create(d.Project(), d.Name(), operationlock.ActionRestore, false, false)
if err != nil {
return errors.Wrap(err, "Create restore operation")
}
defer op.Done(nil)
}
ctxMap = log.Ctx{
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate,
"source": sourceContainer.Name()}
d.logger.Info("Restoring container", ctxMap)
// Initialize storage interface for the container and mount the rootfs for criu state check.
pool, err := storagePools.GetPoolByInstance(d.state, d)
if err != nil {
op.Done(err)
return err
}
d.logger.Debug("Mounting instance to check for CRIU state path existence")
// Ensure that storage is mounted for state path checks and for backup.yaml updates.
_, err = pool.MountInstance(d, nil)
if err != nil {
op.Done(err)
return err
}
// Check for CRIU if necessary, before doing a bunch of filesystem manipulations.
// Requires container be mounted to check StatePath exists.
if shared.PathExists(d.StatePath()) {
_, err := exec.LookPath("criu")
if err != nil {
err = fmt.Errorf("Failed to restore container state. CRIU isn't installed")
op.Done(err)
return err
}
}
_, err = pool.UnmountInstance(d, nil)
if err != nil {
op.Done(err)
return err
}
// Restore the rootfs.
err = pool.RestoreInstanceSnapshot(d, sourceContainer, nil)
if err != nil {
op.Done(err)
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.
// This will call d.UpdateBackupFile() to ensure snapshot list is up to date.
err = d.Update(args, false)
if err != nil {
op.Done(err)
return err
}
// If the container wasn't running but was stateful, should we restore it as running?
if stateful == true {
if !shared.PathExists(d.StatePath()) {
err = fmt.Errorf("Stateful snapshot restore requested by snapshot is stateless")
op.Done(err)
return err
}
d.logger.Debug("Performing stateful restore", ctxMap)
d.stateful = true
criuMigrationArgs := instance.CriuMigrationArgs{
Cmd: liblxc.MIGRATE_RESTORE,
StateDir: d.StatePath(),
Function: "snapshot",
Stop: false,
ActionScript: false,
DumpDir: "",
PreDumpDir: "",
}
// Checkpoint.
err := d.Migrate(&criuMigrationArgs)
if err != nil {
op.Done(err)
return err
}
// Remove the state from the parent container; we only keep this in snapshots.
err2 := os.RemoveAll(d.StatePath())
if err2 != nil && !os.IsNotExist(err) {
op.Done(err)
return err
}
if err != nil {
op.Done(err)
return err
}
d.logger.Debug("Performed stateful restore", ctxMap)
d.logger.Info("Restored container", ctxMap)
return nil
}
// Restart the container.
if wasRunning {
d.logger.Debug("Starting instance after snapshot restore")
err = d.Start(false)
if err != nil {
op.Done(err)
return err
}
}
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceRestored.Event(d, map[string]interface{}{"snapshot": sourceContainer.Name()}))
d.logger.Info("Restored container", ctxMap)
return nil
}
func (d *lxc) cleanup() {
// Unmount any leftovers
d.removeUnixDevices()
d.removeDiskDevices()
// Remove the security profiles
apparmor.InstanceDelete(d.state, d)
seccomp.DeleteProfile(d)
// Remove the devices path
os.Remove(d.DevicesPath())
// Remove the shmounts path
os.RemoveAll(d.ShmountsPath())
}
// Delete deletes the instance.
func (d *lxc) Delete(force bool) error {
ctxMap := log.Ctx{
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate}
d.logger.Info("Deleting container", ctxMap)
if !force && shared.IsTrue(d.expandedConfig["security.protection.delete"]) && !d.IsSnapshot() {
err := fmt.Errorf("Container is protected")
d.logger.Warn("Failed to delete container", log.Ctx{"err": err})
return err
}
// Delete any persistent warnings for instance.
err := d.warningsDelete()
if err != nil {
return err
}
pool, err := storagePools.GetPoolByInstance(d.state, d)
if err != nil && errors.Cause(err) != db.ErrNoSuchObject {
return err
} else if pool != nil {
if d.IsSnapshot() {
// Remove snapshot volume and database record.
err = pool.DeleteInstanceSnapshot(d, 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(d.state, d.Project(), d.Name())
if err != nil {
d.logger.Error("Failed to delete instance snapshots", log.Ctx{"err": err})
return err
}
// Remove the storage volume, snapshot volumes and database records.
err = pool.DeleteInstance(d, nil)
if err != nil {
return err
}
}
}
// Perform other cleanup steps if not snapshot.
if !d.IsSnapshot() {
// Remove all backups.
backups, err := d.Backups()
if err != nil {
return err
}
for _, backup := range backups {
err = backup.Delete()
if err != nil {
return err
}
}
// Delete the MAAS entry.
err = d.maasDelete(d)
if err != nil {
d.logger.Error("Failed deleting container MAAS record", log.Ctx{"err": err})
return err
}
// Remove devices from container.
for k, m := range d.expandedDevices {
err = d.deviceRemove(k, m, false)
if err != nil && err != device.ErrUnsupportedDevType {
return errors.Wrapf(err, "Failed to remove device %q", k)
}
}
// Clean things up.
d.cleanup()
}
// Remove the database record of the instance or snapshot instance.
if err := d.state.Cluster.DeleteInstance(d.project, d.Name()); err != nil {
d.logger.Error("Failed deleting container entry", log.Ctx{"err": err})
return err
}
// If dealing with a snapshot, refresh the backup file on the parent.
if d.IsSnapshot() {
parentName, _, _ := shared.InstanceGetParentAndSnapshotName(d.name)
// Load the parent.
parent, err := instance.LoadByProjectAndName(d.state, d.project, parentName)
if err != nil {
return errors.Wrap(err, "Invalid parent")
}
// Update the backup file.
err = parent.UpdateBackupFile()
if err != nil {
return err
}
}
d.logger.Info("Deleted container", ctxMap)
if d.snapshot {
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceSnapshotDeleted.Event(d, nil))
} else {
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceDeleted.Event(d, nil))
}
return nil
}
// Rename renames the instance. Accepts an argument to enable applying deferred TemplateTriggerRename.
func (d *lxc) Rename(newName string, applyTemplateTrigger bool) error {
oldName := d.Name()
ctxMap := log.Ctx{
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate,
"newname": newName}
d.logger.Info("Renaming container", ctxMap)
// Quick checks.
err := instance.ValidName(newName, d.IsSnapshot())
if err != nil {
return err
}
if d.IsRunning() {
return fmt.Errorf("Renaming of running container not allowed")
}
// Clean things up.
d.cleanup()
pool, err := storagePools.GetPoolByInstance(d.state, d)
if err != nil {
return errors.Wrap(err, "Failed loading instance storage pool")
}
if d.IsSnapshot() {
_, newSnapName, _ := shared.InstanceGetParentAndSnapshotName(newName)
err = pool.RenameInstanceSnapshot(d, newSnapName, nil)
if err != nil {
return errors.Wrap(err, "Rename instance snapshot")
}
} else {
err = pool.RenameInstance(d, newName, nil)
if err != nil {
return errors.Wrap(err, "Rename instance")
}
if applyTemplateTrigger {
err = d.DeferTemplateApply(instance.TemplateTriggerRename)
if err != nil {
return err
}
}
}
if !d.IsSnapshot() {
// Rename all the instance snapshot database entries.
results, err := d.state.Cluster.GetInstanceSnapshotsNames(d.project, oldName)
if err != nil {
d.logger.Error("Failed to get container snapshots", ctxMap)
return errors.Wrapf(err, "Failed to get container snapshots")
}
for _, sname := range results {
// Rename the snapshot.
oldSnapName := strings.SplitN(sname, shared.SnapshotDelimiter, 2)[1]
baseSnapName := filepath.Base(sname)
err := d.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
return tx.RenameInstanceSnapshot(d.project, oldName, oldSnapName, baseSnapName)
})
if err != nil {
d.logger.Error("Failed renaming snapshot", ctxMap)
return errors.Wrapf(err, "Failed renaming snapshot")
}
}
}
// Rename the instance database entry.
err = d.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
if d.IsSnapshot() {
oldParts := strings.SplitN(oldName, shared.SnapshotDelimiter, 2)
newParts := strings.SplitN(newName, shared.SnapshotDelimiter, 2)
return tx.RenameInstanceSnapshot(d.project, oldParts[0], oldParts[1], newParts[1])
}
return tx.RenameInstance(d.project, oldName, newName)
})
if err != nil {
d.logger.Error("Failed renaming container", ctxMap)
return errors.Wrapf(err, "Failed renaming container")
}
// Rename the logging path.
newFullName := project.Instance(d.Project(), d.Name())
os.RemoveAll(shared.LogPath(newFullName))
if shared.PathExists(d.LogPath()) {
err := os.Rename(d.LogPath(), shared.LogPath(newFullName))
if err != nil {
d.logger.Error("Failed renaming container", ctxMap)
return errors.Wrapf(err, "Failed renaming container")
}
}
// Rename the MAAS entry.
if !d.IsSnapshot() {
err = d.maasRename(d, newName)
if err != nil {
return err
}
}
revert := revert.New()
defer revert.Fail()
// Set the new name in the struct.
d.name = newName
revert.Add(func() { d.name = oldName })
// Rename the backups.
backups, err := d.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.
d.release()
d.cConfig = false
// Update lease files.
network.UpdateDNSMasqStatic(d.state, "")
err = d.UpdateBackupFile()
if err != nil {
return err
}
d.logger.Info("Renamed container", ctxMap)
if d.snapshot {
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceSnapshotRenamed.Event(d, map[string]interface{}{"old_name": oldName}))
} else {
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceRenamed.Event(d, map[string]interface{}{"old_name": oldName}))
}
revert.Success()
return nil
}
// CGroupSet sets a cgroup value for the instance.
func (d *lxc) CGroupSet(key string, value string) error {
// Load the go-lxc struct
err := d.initLXC(false)
if err != nil {
return err
}
// Make sure the container is running
if !d.IsRunning() {
return fmt.Errorf("Can't set cgroups on a stopped container")
}
err = d.c.SetCgroupItem(key, value)
if err != nil {
return fmt.Errorf("Failed to set cgroup %s=\"%s\": %s", key, value, err)
}
return nil
}
// Update applies updated config.
func (d *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 = d.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(d.state.OS, args.Config, false, d.dbType)
if err != nil {
return errors.Wrap(err, "Invalid config")
}
// Validate the new devices without using expanded devices validation (expensive checks disabled).
err = instance.ValidDevices(d.state, d.state.Cluster, d.Project(), d.Type(), args.Devices, false)
if err != nil {
return errors.Wrap(err, "Invalid devices")
}
}
// Validate the new profiles
profiles, err := d.state.Cluster.GetProfileNames(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 := d.Description()
oldArchitecture := 0
err = shared.DeepCopy(&d.architecture, &oldArchitecture)
if err != nil {
return err
}
oldEphemeral := false
err = shared.DeepCopy(&d.ephemeral, &oldEphemeral)
if err != nil {
return err
}
oldExpandedDevices := deviceConfig.Devices{}
err = shared.DeepCopy(&d.expandedDevices, &oldExpandedDevices)
if err != nil {
return err
}
oldExpandedConfig := map[string]string{}
err = shared.DeepCopy(&d.expandedConfig, &oldExpandedConfig)
if err != nil {
return err
}
oldLocalDevices := deviceConfig.Devices{}
err = shared.DeepCopy(&d.localDevices, &oldLocalDevices)
if err != nil {
return err
}
oldLocalConfig := map[string]string{}
err = shared.DeepCopy(&d.localConfig, &oldLocalConfig)
if err != nil {
return err
}
oldProfiles := []string{}
err = shared.DeepCopy(&d.profiles, &oldProfiles)
if err != nil {
return err
}
oldExpiryDate := d.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 {
d.description = oldDescription
d.architecture = oldArchitecture
d.ephemeral = oldEphemeral
d.expandedConfig = oldExpandedConfig
d.expandedDevices = oldExpandedDevices
d.localConfig = oldLocalConfig
d.localDevices = oldLocalDevices
d.profiles = oldProfiles
d.expiryDate = oldExpiryDate
d.release()
d.cConfig = false
d.initLXC(true)
cgroup.TaskSchedulerTrigger("container", d.name, "changed")
}
}()
// Apply the various changes
d.description = args.Description
d.architecture = args.Architecture
d.ephemeral = args.Ephemeral
d.localConfig = args.Config
d.localDevices = args.Devices
d.profiles = args.Profiles
d.expiryDate = args.ExpiryDate
// Expand the config and refresh the LXC config
err = d.expandConfig(nil)
if err != nil {
return errors.Wrap(err, "Expand config")
}
err = d.expandDevices(nil)
if err != nil {
return errors.Wrap(err, "Expand devices")
}
// Diff the configurations
changedConfig := []string{}
for key := range oldExpandedConfig {
if oldExpandedConfig[key] != d.expandedConfig[key] {
if !shared.StringInSlice(key, changedConfig) {
changedConfig = append(changedConfig, key)
}
}
}
for key := range d.expandedConfig {
if oldExpandedConfig[key] != d.expandedConfig[key] {
if !shared.StringInSlice(key, changedConfig) {
changedConfig = append(changedConfig, key)
}
}
}
// Diff the devices
removeDevices, addDevices, updateDevices, allUpdatedKeys := oldExpandedDevices.Update(d.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".
oldDevType, err := device.LoadByType(d.state, d.Project(), oldDevice)
if err != nil {
return []string{} // Couldn't create Device, so this cannot be an update.
}
newDevType, err := device.LoadByType(d.state, d.Project(), newDevice)
if err != nil {
return []string{} // Couldn't create Device, so this cannot be an update.
}
return newDevType.UpdatableFields(oldDevType)
})
if userRequested {
// Do some validation of the config diff (allows mixed instance types for profiles).
err = instance.ValidConfig(d.state.OS, d.expandedConfig, true, instancetype.Any)
if err != nil {
return errors.Wrap(err, "Invalid expanded config")
}
// Do full expanded validation of the devices diff.
err = instance.ValidDevices(d.state, d.state.Cluster, d.Project(), d.Type(), d.expandedDevices, true)
if err != nil {
return errors.Wrap(err, "Invalid expanded devices")
}
}
// Run through initLXC to catch anything we missed
if userRequested {
d.release()
d.cConfig = false
err = d.initLXC(true)
if err != nil {
return errors.Wrap(err, "Initialize LXC")
}
}
cg, err := d.cgroup(nil)
if err != nil {
return err
}
// If raw.lxc changed, re-validate the config.
if shared.StringInSlice("raw.lxc", changedConfig) && d.expandedConfig["raw.lxc"] != "" {
// Get a new liblxc instance.
cc, err := liblxc.NewContainer(d.name, d.state.OS.LxcPath)
if err != nil {
return err
}
err = d.loadRawLXCConfig()
if err != nil {
return err
}
// Release the liblxc instance.
cc.Release()
}
// If apparmor changed, re-validate the apparmor profile (even if not running).
if shared.StringInSlice("raw.apparmor", changedConfig) || shared.StringInSlice("security.nesting", changedConfig) {
err = apparmor.InstanceValidate(d.state, d)
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 !d.IsPrivileged() {
// update the idmap
idmap, base, err = findIdmap(
d.state,
d.Name(),
d.expandedConfig["security.idmap.isolated"],
d.expandedConfig["security.idmap.base"],
d.expandedConfig["security.idmap.size"],
d.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 = "[]"
}
d.localConfig["volatile.idmap.next"] = jsonIdmap
d.localConfig["volatile.idmap.base"] = fmt.Sprintf("%v", base)
// Invalid idmap cache
d.idmapset = nil
}
isRunning := d.IsRunning()
// Use the device interface to apply update changes.
err = d.updateDevices(removeDevices, addDevices, updateDevices, oldExpandedDevices, isRunning, userRequested)
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, allUpdatedKeys) {
updateMAAS = true
break
}
}
if !d.IsSnapshot() && updateMAAS {
err = d.maasUpdate(d, oldExpandedDevices.CloneNative())
if err != nil {
return err
}
}
// Apply the live changes
if isRunning {
// Live update the container config
for _, key := range changedConfig {
value := d.expandedConfig[key]
if key == "raw.apparmor" || key == "security.nesting" {
// Update the AppArmor profile
err = apparmor.InstanceLoad(d.state, d)
if err != nil {
return err
}
} else if key == "security.devlxd" {
if value == "" || shared.IsTrue(value) {
err = d.insertMount(shared.VarPath("devlxd"), "/dev/lxd", "none", unix.MS_BIND, idmap.IdmapStorageNone)
if err != nil {
return err
}
} else if d.FileExists("/dev/lxd") == nil {
err = d.removeMount("/dev/lxd")
if err != nil {
return err
}
err = d.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 !d.state.OS.CGInfo.Supports(cgroup.Blkio, cg) {
continue
}
priorityInt := 5
diskPriority := d.expandedConfig["limits.disk.priority"]
if diskPriority != "" {
priorityInt, err = strconv.Atoi(diskPriority)
if err != nil {
return err
}
}
// Minimum valid value is 10
priority := int64(priorityInt * 100)
if priority == 0 {
priority = 10
}
cg.SetBlkioWeight(priority)
if err != nil {
return err
}
} else if key == "limits.memory" || strings.HasPrefix(key, "limits.memory.") {
// Skip if no memory CGroup
if !d.state.OS.CGInfo.Supports(cgroup.Memory, cg) {
continue
}
// Set the new memory limit
memory := d.expandedConfig["limits.memory"]
memoryEnforce := d.expandedConfig["limits.memory.enforce"]
memorySwap := d.expandedConfig["limits.memory.swap"]
var memoryInt int64
// Parse memory
if memory == "" {
memoryInt = -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
}
memoryInt = int64((memoryTotal / 100) * percent)
} else {
memoryInt, err = units.ParseByteSizeString(memory)
if err != nil {
return err
}
}
// Store the old values for revert
oldMemswLimit := int64(-1)
if d.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) {
oldMemswLimit, err = cg.GetMemorySwapLimit()
if err != nil {
oldMemswLimit = -1
}
}
oldLimit, err := cg.GetMemoryLimit()
if err != nil {
oldLimit = -1
}
oldSoftLimit, err := cg.GetMemorySoftLimit()
if err != nil {
oldSoftLimit = -1
}
revertMemory := func() {
if oldSoftLimit != -1 {
cg.SetMemorySoftLimit(oldSoftLimit)
}
if oldLimit != -1 {
cg.SetMemoryLimit(oldLimit)
}
if oldMemswLimit != -1 {
cg.SetMemorySwapLimit(oldMemswLimit)
}
}
// Reset everything
if d.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) {
err = cg.SetMemorySwapLimit(-1)
if err != nil {
revertMemory()
return err
}
}
err = cg.SetMemoryLimit(-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(memoryInt)
if err != nil {
revertMemory()
return err
}
} else {
if d.state.OS.CGInfo.Supports(cgroup.MemorySwap, cg) && (memorySwap == "" || shared.IsTrue(memorySwap)) {
err = cg.SetMemoryLimit(memoryInt)
if err != nil {
revertMemory()
return err
}
err = cg.SetMemorySwapLimit(0)
if err != nil {
revertMemory()
return err
}
} else {
err = cg.SetMemoryLimit(memoryInt)
if err != nil {
revertMemory()
return err
}
}
// Set soft limit to value 10% less than hard limit
err = cg.SetMemorySoftLimit(int64(float64(memoryInt) * 0.9))
if err != nil {
revertMemory()
return err
}
}
if !d.state.OS.CGInfo.Supports(cgroup.MemorySwappiness, cg) {
continue
}
// Configure the swappiness
if key == "limits.memory.swap" || key == "limits.memory.swap.priority" {
memorySwap := d.expandedConfig["limits.memory.swap"]
memorySwapPriority := d.expandedConfig["limits.memory.swap.priority"]
if memorySwap != "" && !shared.IsTrue(memorySwap) {
err = cg.SetMemorySwappiness(0)
if err != nil {
return err
}
} else {
priority := 10
if memorySwapPriority != "" {
priority, err = strconv.Atoi(memorySwapPriority)
if err != nil {
return err
}
}
// Maximum priority (10) should be default swappiness (60).
err = cg.SetMemorySwappiness(int64(70 - priority))
if err != nil {
return err
}
}
}
} else if key == "limits.network.priority" {
err := d.setNetworkPriority()
if err != nil {
return err
}
} else if key == "limits.cpu" {
// Trigger a scheduler re-run
cgroup.TaskSchedulerTrigger("container", d.name, "changed")
} else if key == "limits.cpu.priority" || key == "limits.cpu.allowance" {
// Skip if no cpu CGroup
if !d.state.OS.CGInfo.Supports(cgroup.CPU, cg) {
continue
}
// Apply new CPU limits
cpuShares, cpuCfsQuota, cpuCfsPeriod, err := cgroup.ParseCPU(d.expandedConfig["limits.cpu.allowance"], d.expandedConfig["limits.cpu.priority"])
if err != nil {
return err
}
err = cg.SetCPUShare(cpuShares)
if err != nil {
return err
}
err = cg.SetCPUCfsLimit(cpuCfsPeriod, cpuCfsQuota)
if err != nil {
return err
}
} else if key == "limits.processes" {
if !d.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 !d.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"
}
valueInt := int64(-1)
if value != "" {
valueInt, err = units.ParseByteSizeString(value)
if err != nil {
return err
}
}
err = cg.SetHugepagesLimit(pageType, valueInt)
if err != nil {
return err
}
}
}
}
// Finally, apply the changes to the database
err = d.state.Cluster.Transaction(func(tx *db.ClusterTx) error {
// Snapshots should update only their descriptions and expiry date.
if d.IsSnapshot() {
return tx.UpdateInstanceSnapshot(d.id, d.description, d.expiryDate)
}
object, err := tx.GetInstance(d.project, d.name)
if err != nil {
return err
}
object.Description = d.description
object.Architecture = d.architecture
object.Ephemeral = d.ephemeral
object.ExpiryDate = sql.NullTime{Time: d.expiryDate, Valid: true}
object.Config = d.localConfig
object.Profiles = d.profiles
devices, err := db.APIToDevices(d.localDevices.CloneNative())
if err != nil {
return err
}
object.Devices = devices
return tx.UpdateInstance(d.project, d.name, *object)
})
if err != nil {
return errors.Wrap(err, "Failed to update database")
}
err = d.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": d.expandedConfig[key],
}
err = d.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 = d.devlxdEventSend("device", msg)
if err != nil {
return err
}
}
for k, m := range updateDevices {
msg := map[string]interface{}{
"action": "updated",
"name": k,
"config": m,
}
err = d.devlxdEventSend("device", msg)
if err != nil {
return err
}
}
for k, m := range addDevices {
msg := map[string]interface{}{
"action": "added",
"name": k,
"config": m,
}
err = d.devlxdEventSend("device", msg)
if err != nil {
return err
}
}
}
// Success, update the closure to mark that the changes should be kept.
undoChanges = false
if userRequested {
if d.snapshot {
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceSnapshotUpdated.Event(d, nil))
} else {
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceUpdated.Event(d, nil))
}
}
return nil
}
func (d *lxc) updateDevices(removeDevices deviceConfig.Devices, addDevices deviceConfig.Devices, updateDevices deviceConfig.Devices, oldExpandedDevices deviceConfig.Devices, instanceRunning bool, userRequested bool) error {
revert := revert.New()
defer revert.Fail()
// Remove devices in reverse order to how they were added.
for _, dev := range removeDevices.Reversed() {
if instanceRunning {
err := d.deviceStop(dev.Name, dev.Config, instanceRunning, "")
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 := d.deviceRemove(dev.Name, dev.Config, instanceRunning)
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 = d.deviceVolatileReset(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 _, dd := range addDevices.Sorted() {
dev := dd // Local var for loop revert.
err := d.deviceAdd(dev.Name, dev.Config, instanceRunning)
if err == device.ErrUnsupportedDevType {
continue // No point in trying to start device below.
} else if err != nil {
if userRequested {
return errors.Wrapf(err, "Failed to add device %q", dev.Name)
}
// If update is non-user requested (i.e from a snapshot restore), there's nothing we can
// do to fix the config and we don't want to prevent the snapshot restore so log and allow.
d.logger.Error("Failed to add device, skipping as non-user requested", log.Ctx{"device": dev.Name, "err": err})
continue
}
revert.Add(func() { d.deviceRemove(dev.Name, dev.Config, instanceRunning) })
if instanceRunning {
_, err := d.deviceStart(dev.Name, dev.Config, instanceRunning)
if err != nil && err != device.ErrUnsupportedDevType {
return errors.Wrapf(err, "Failed to start device %q", dev.Name)
}
revert.Add(func() { d.deviceStop(dev.Name, dev.Config, instanceRunning, "") })
}
}
for _, dev := range updateDevices.Sorted() {
err := d.deviceUpdate(dev.Name, dev.Config, oldExpandedDevices, instanceRunning)
if err != nil && err != device.ErrUnsupportedDevType {
return errors.Wrapf(err, "Failed to update device %q", dev.Name)
}
}
revert.Success()
return nil
}
// Export backs up the instance.
func (d *lxc) Export(w io.Writer, properties map[string]string, expiration time.Time) (api.ImageMetadata, error) {
ctxMap := log.Ctx{
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.lastUsedDate}
meta := api.ImageMetadata{}
if d.IsRunning() {
return meta, fmt.Errorf("Cannot export a running instance as an image")
}
d.logger.Info("Exporting instance", ctxMap)
// Start the storage.
_, err := d.mount()
if err != nil {
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
defer d.unmount()
// Get IDMap to unshift container as the tarball is created.
idmap, err := d.DiskIdmap()
if err != nil {
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
// Create the tarball.
tarWriter := instancewriter.NewInstanceTarWriter(w, idmap)
// Keep track of the first path we saw for each path with nlink>1.
cDir := d.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 {
d.logger.Debug("Error tarring up", log.Ctx{"path": path, "err": 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()
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
defer os.RemoveAll(tempDir)
// Get the instance's architecture.
var arch string
if d.IsSnapshot() {
parentName, _, _ := shared.InstanceGetParentAndSnapshotName(d.name)
parent, err := instance.LoadByProjectAndName(d.state, d.project, parentName)
if err != nil {
tarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
arch, _ = osarch.ArchitectureName(parent.Architecture())
} else {
arch, _ = osarch.ArchitectureName(d.architecture)
}
if arch == "" {
arch, err = osarch.ArchitectureName(d.state.OS.Architectures[0])
if err != nil {
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
}
// Fill in the metadata.
meta.Architecture = arch
meta.CreationDate = time.Now().UTC().Unix()
meta.Properties = properties
if !expiration.IsZero() {
meta.ExpiryDate = expiration.UTC().Unix()
}
data, err := yaml.Marshal(&meta)
if err != nil {
tarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
// Write the actual file.
fnam = filepath.Join(tempDir, "metadata.yaml")
err = ioutil.WriteFile(fnam, data, 0644)
if err != nil {
tarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
fi, err := os.Lstat(fnam)
if err != nil {
tarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
tmpOffset := len(path.Dir(fnam)) + 1
if err := tarWriter.WriteFile(fnam[tmpOffset:], fnam, fi, false); err != nil {
tarWriter.Close()
d.logger.Debug("Error writing to tarfile", log.Ctx{"err": err})
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
} else {
// Parse the metadata.
content, err := ioutil.ReadFile(fnam)
if err != nil {
tarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
err = yaml.Unmarshal(content, &meta)
if err != nil {
tarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
if !expiration.IsZero() {
meta.ExpiryDate = expiration.UTC().Unix()
}
if properties != nil {
meta.Properties = properties
}
if properties != nil || !expiration.IsZero() {
// Generate a new metadata.yaml.
tempDir, err := ioutil.TempDir("", "lxd_lxd_metadata_")
if err != nil {
tarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
defer os.RemoveAll(tempDir)
data, err := yaml.Marshal(&meta)
if err != nil {
tarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
// Write the actual file.
fnam = filepath.Join(tempDir, "metadata.yaml")
err = ioutil.WriteFile(fnam, data, 0644)
if err != nil {
tarWriter.Close()
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
}
// Include metadata.yaml in the tarball.
fi, err := os.Lstat(fnam)
if err != nil {
tarWriter.Close()
d.logger.Debug("Error statting during export", log.Ctx{"fileName": fnam})
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
if properties != nil || !expiration.IsZero() {
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()
d.logger.Debug("Error writing to tarfile", log.Ctx{"err": err})
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
}
// Include all the rootfs files.
fnam = d.RootfsPath()
err = filepath.Walk(fnam, writeToTar)
if err != nil {
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
// Include all the templates.
fnam = d.TemplatesPath()
if shared.PathExists(fnam) {
err = filepath.Walk(fnam, writeToTar)
if err != nil {
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
}
err = tarWriter.Close()
if err != nil {
d.logger.Error("Failed exporting instance", ctxMap)
return meta, err
}
d.logger.Info("Exported instance", ctxMap)
return meta, nil
}
func collectCRIULogFile(d instance.Instance, imagesDir string, function string, method string) error {
t := time.Now().Format(time.RFC3339)
newPath := filepath.Join(d.LogPath(), 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 (d *lxc) Migrate(args *instance.CriuMigrationArgs) error {
ctxMap := log.Ctx{
"created": d.creationDate,
"ephemeral": d.ephemeral,
"used": d.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")
}
d.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"
d.logger.Warn("Unknown migrate call", log.Ctx{"cmd": args.Cmd})
}
pool, err := d.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 {
// Check that we're not already running.
if d.IsRunning() {
return fmt.Errorf("The container is already running")
}
// Run the shared start
_, postStartHooks, err := d.startCommon()
if err != nil {
return errors.Wrap(err, "Failed preparing container for start")
}
/*
* 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 := d.CurrentIdmap()
if err != nil {
return err
}
if idmapset != nil {
storageType, err := d.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 err != nil {
return err
}
}
configPath := filepath.Join(d.LogPath(), "lxc.conf")
if args.DumpDir != "" {
finalStateDir = fmt.Sprintf("%s/%s", args.StateDir, args.DumpDir)
}
// Update the backup.yaml file just before starting the instance process, but after all devices
// have been setup, so that the backup file contains the volatile keys used for this instance
// start, so that they can be used for instance cleanup.
err = d.UpdateBackupFile()
if err != nil {
return err
}
_, migrateErr = shared.RunCommand(
d.state.OS.ExecPath,
"forkmigrate",
d.name,
d.state.OS.LxcPath,
configPath,
finalStateDir,
fmt.Sprintf("%v", preservesInodes))
if migrateErr == nil {
// Run any post start hooks.
err := d.runHooks(postStartHooks)
if err != nil {
// Attempt to stop container.
d.Stop(false)
return err
}
}
} else if args.Cmd == liblxc.MIGRATE_FEATURE_CHECK {
err := d.initLXC(true)
if err != nil {
return err
}
opts := liblxc.MigrateOptions{
FeaturesToCheck: args.Features,
}
migrateErr = d.c.Migrate(args.Cmd, opts)
if migrateErr != nil {
d.logger.Info("CRIU feature check failed", ctxMap)
return migrateErr
}
return nil
} else {
err := d.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 !d.IsRunning() {
// otherwise the migration will needlessly fail
args.Stop = false
}
migrateErr = d.c.Migrate(args.Cmd, opts)
}
collectErr := collectCRIULogFile(d, finalStateDir, args.Function, prettyCmd)
if collectErr != nil {
d.logger.Error("Error collecting checkpoint log file", log.Ctx{"err": collectErr})
}
if migrateErr != nil {
log, err2 := getCRIULogErrors(finalStateDir, prettyCmd)
if err2 == nil {
d.logger.Info("Failed migrating container", ctxMap)
migrateErr = fmt.Errorf("%s %s failed\n%s", args.Function, prettyCmd, log)
}
return migrateErr
}
d.logger.Info("Migrated container", ctxMap)
return nil
}
func (d *lxc) templateApplyNow(trigger instance.TemplateTrigger) error {
// If there's no metadata, just return
fname := filepath.Join(d.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 := d.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(d.architecture)
if err != nil {
arch, err = osarch.ArchitectureName(d.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"] = d.name
containerMeta["type"] = "container"
containerMeta["architecture"] = arch
if d.ephemeral {
containerMeta["ephemeral"] = "true"
} else {
containerMeta["ephemeral"] = "false"
}
if d.IsPrivileged() {
containerMeta["privileged"] = "true"
} else {
containerMeta["privileged"] = "false"
}
// Go through the templates
for tplPath, tpl := range metadata.Templates {
err = func(tplPath string, tpl *api.ImageMetadataTemplate) error {
var w *os.File
// Check if the template should be applied now
found := false
for _, tplTrigger := range tpl.When {
if tplTrigger == string(trigger) {
found = true
break
}
}
if !found {
return nil
}
// Open the file to template, create if needed
fullpath := filepath.Join(d.RootfsPath(), strings.TrimLeft(tplPath, "/"))
if shared.PathExists(fullpath) {
if tpl.CreateOnly {
return nil
}
// 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(d.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", d.name, tpl.Template), template.ChrootLoader{Path: d.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 := d.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": d.expandedConfig,
"devices": d.expandedDevices,
"properties": tpl.Properties,
"config_get": configGet}, w)
return nil
}(tplPath, tpl)
if err != nil {
return err
}
}
return nil
}
func (d *lxc) inheritInitPidFd() (int, *os.File) {
if d.state.OS.PidFds {
pidFdFile, err := d.InitPidFd()
if err != nil {
return -1, nil
}
return 3, pidFdFile
}
return -1, nil
}
// FileExists returns whether file exists inside instance.
func (d *lxc) FileExists(path string) error {
// Check for ongoing operations (that may involve shifting).
operationlock.Get(d.Project(), d.Name()).Wait()
if !d.IsRunning() {
// Setup container storage if needed.
_, err := d.mount()
if err != nil {
return err
}
defer d.unmount()
}
pidFdNr, pidFd := d.inheritInitPidFd()
if pidFdNr >= 0 {
defer pidFd.Close()
}
// Check if the file exists in the container
_, stderr, err := shared.RunCommandSplit(
nil,
[]*os.File{pidFd},
d.state.OS.ExecPath,
"forkfile",
"exists",
d.RootfsPath(),
fmt.Sprintf("%d", d.InitPID()),
fmt.Sprintf("%d", pidFdNr),
path,
)
// 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") {
d.logger.Debug("forkcheckfile", log.Ctx{"line": line})
}
}
if err != nil {
return err
}
return nil
}
// FilePull gets a file from the instance.
func (d *lxc) FilePull(srcpath string, dstpath string) (int64, int64, os.FileMode, string, []string, error) {
// Check for ongoing operations (that may involve shifting).
operationlock.Get(d.Project(), d.Name()).Wait()
if !d.IsRunning() {
// Setup container storage if needed.
_, err := d.mount()
if err != nil {
return -1, -1, 0, "", nil, err
}
defer d.unmount()
}
pidFdNr, pidFd := d.inheritInitPidFd()
if pidFdNr >= 0 {
defer pidFd.Close()
}
// Get the file from the container
_, stderr, err := shared.RunCommandSplit(
nil,
[]*os.File{pidFd},
d.state.OS.ExecPath,
"forkfile",
"pull",
d.RootfsPath(),
fmt.Sprintf("%d", d.InitPID()),
fmt.Sprintf("%d", pidFdNr),
srcpath,
dstpath,
)
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
}
d.logger.Debug("forkgetfile", log.Ctx{"line": line})
}
if err != nil {
return -1, -1, 0, "", nil, err
}
// Unmap uid and gid if needed
if !d.IsRunning() {
idmapset, err := d.DiskIdmap()
if err != nil {
return -1, -1, 0, "", nil, err
}
if idmapset != nil {
uid, gid = idmapset.ShiftFromNs(uid, gid)
}
}
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceFileRetrieved.Event(d, log.Ctx{"file-source": srcpath, "file-destination": dstpath}))
return uid, gid, os.FileMode(mode), fileType, dirEnts, nil
}
// FilePush sends a file into the instance.
func (d *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).
operationlock.Get(d.Project(), d.Name()).Wait()
var rootUID int64
var rootGID int64
var errStr string
if !d.IsRunning() {
// Map uid and gid if needed.
idmapset, err := d.DiskIdmap()
if err != nil {
return err
}
if idmapset != nil {
uid, gid = idmapset.ShiftIntoNs(uid, gid)
rootUID, rootGID = idmapset.ShiftIntoNs(0, 0)
}
// Setup container storage if needed.
_, err = d.mount()
if err != nil {
return err
}
defer d.unmount()
}
defaultMode := 0640
if fileType == "directory" {
defaultMode = 0750
}
pidFdNr, pidFd := d.inheritInitPidFd()
if pidFdNr >= 0 {
defer pidFd.Close()
}
// Push the file to the container
_, stderr, err := shared.RunCommandSplit(
nil,
[]*os.File{pidFd},
d.state.OS.ExecPath,
"forkfile",
"push",
d.RootfsPath(),
fmt.Sprintf("%d", d.InitPID()),
fmt.Sprintf("%d", pidFdNr),
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,
)
// 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
}
ctx := log.Ctx{"file-source": srcpath, "file-destination": dstpath, "gid": gid, "mode": mode, "file-type": fileType, "uid": uid, "write-mode": write}
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceFilePushed.Event(d, ctx))
return nil
}
// FileRemove removes a file inside the instance.
func (d *lxc) FileRemove(path string) error {
// Check for ongoing operations (that may involve shifting).
operationlock.Get(d.Project(), d.Name()).Wait()
var errStr string
// Setup container storage if needed
_, err := d.mount()
if err != nil {
return err
}
defer d.unmount()
pidFdNr, pidFd := d.inheritInitPidFd()
if pidFdNr >= 0 {
defer pidFd.Close()
}
// Remove the file from the container
_, stderr, err := shared.RunCommandSplit(
nil,
[]*os.File{pidFd},
d.state.OS.ExecPath,
"forkfile",
"remove",
d.RootfsPath(),
fmt.Sprintf("%d", d.InitPID()),
fmt.Sprintf("%d", pidFdNr),
path,
)
// 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
}
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceFileDeleted.Event(d, log.Ctx{"file": path}))
return nil
}
// Console attaches to the instance console.
func (d *lxc) Console(protocol string) (*os.File, chan error, error) {
if protocol != instance.ConsoleTypeConsole {
return nil, nil, fmt.Errorf("Container instances don't support %q output", protocol)
}
chDisconnect := make(chan error, 1)
args := []string{
d.state.OS.ExecPath,
"forkconsole",
project.Instance(d.Project(), d.Name()),
d.state.OS.LxcPath,
filepath.Join(d.LogPath(), "lxc.conf"),
"tty=0",
"escape=-1"}
idmapset, err := d.CurrentIdmap()
if err != nil {
return nil, nil, err
}
var rootUID, rootGID int64
if idmapset != nil {
rootUID, rootGID = idmapset.ShiftIntoNs(0, 0)
}
ptx, pty, err := shared.OpenPty(rootUID, rootGID)
if err != nil {
return nil, nil, err
}
cmd := exec.Cmd{}
cmd.Path = d.state.OS.ExecPath
cmd.Args = args
cmd.Stdin = pty
cmd.Stdout = pty
cmd.Stderr = pty
err = cmd.Start()
if err != nil {
return nil, nil, err
}
go func() {
err = cmd.Wait()
ptx.Close()
pty.Close()
}()
go func() {
<-chDisconnect
cmd.Process.Kill()
}()
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceConsole.Event(d, log.Ctx{"type": instance.ConsoleTypeConsole}))
return ptx, chDisconnect, nil
}
// ConsoleLog returns console log.
func (d *lxc) ConsoleLog(opts liblxc.ConsoleLogOptions) (string, error) {
msg, err := d.c.ConsoleLog(opts)
if err != nil {
return "", err
}
if opts.ClearLog {
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceConsoleReset.Event(d, nil))
} else if opts.ReadLog && opts.WriteToLogFile {
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceConsoleRetrieved.Event(d, nil))
}
return string(msg), nil
}
// Exec executes a command inside the instance.
func (d *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(d.LogPath(), "forkexec.log")
logFile, err := os.OpenFile(logPath, os.O_WRONLY|os.O_CREATE|os.O_SYNC, 0644)
if err != nil {
return nil, err
}
defer logFile.Close()
// Prepare the subcommand
cname := project.Instance(d.Project(), d.Name())
args := []string{
d.state.OS.ExecPath,
"forkexec",
cname,
d.state.OS.LxcPath,
filepath.Join(d.LogPath(), "lxc.conf"),
req.Cwd,
fmt.Sprintf("%d", req.User),
fmt.Sprintf("%d", req.Group),
}
if d.state.OS.CoreScheduling && !d.state.OS.ContainerCoreScheduling {
args = append(args, "1")
} else {
args = append(args, "0")
}
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 = d.state.OS.ExecPath
cmd.Args = args
cmd.Stdin = nil
cmd.Stdout = logFile
cmd.Stderr = logFile
// Mitigation for CVE-2019-5736
useRexec := false
if d.expandedConfig["raw.idmap"] != "" {
err := instance.AllowedUnprivilegedOnlyMap(d.expandedConfig["raw.idmap"])
if err != nil {
useRexec = true
}
}
if shared.IsTrue(d.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()
wStatus.Close()
if err != nil {
return nil, err
}
attachedPid := shared.ReadPid(rStatus)
if attachedPid <= 0 {
cmd.Wait()
d.logger.Error("Failed to retrieve PID of executing child process")
return nil, fmt.Errorf("Failed to retrieve PID of executing child process")
}
d.logger.Debug("Retrieved PID of executing child process", log.Ctx{"attachedPid": attachedPid})
d.state.Events.SendLifecycle(d.project, lifecycle.InstanceExec.Event(d, log.Ctx{"command": req.Command}))
instCmd := &lxcCmd{
cmd: &cmd,
attachedChildPid: int(attachedPid),
}
return instCmd, nil
}
func (d *lxc) cpuState() api.InstanceStateCPU {
cpu := api.InstanceStateCPU{}
// CPU usage in seconds
cg, err := d.cgroup(nil)
if err != nil {
return cpu
}
if !d.state.OS.CGInfo.Supports(cgroup.CPUAcct, cg) {
return cpu
}
value, err := cg.GetCPUAcctUsage()
if err != nil {
cpu.Usage = -1
return cpu
}
cpu.Usage = value
return cpu
}
func (d *lxc) diskState() map[string]api.InstanceStateDisk {
disk := map[string]api.InstanceStateDisk{}
for _, dev := range d.expandedDevices.Sorted() {
if dev.Config["type"] != "disk" {
continue
}
var usage int64
if dev.Config["path"] == "/" {
pool, err := storagePools.GetPoolByInstance(d.state, d)
if err != nil {
d.logger.Error("Error loading storage pool", log.Ctx{"err": err})
continue
}
usage, err = pool.GetInstanceUsage(d)
if err != nil {
if errors.Cause(err) != storageDrivers.ErrNotSupported {
d.logger.Error("Error getting disk usage", log.Ctx{"err": err})
}
continue
}
} else if dev.Config["pool"] != "" {
pool, err := storagePools.GetPoolByName(d.state, dev.Config["pool"])
if err != nil {
d.logger.Error("Error loading storage pool", log.Ctx{"poolName": dev.Config["pool"], "err": err})
continue
}
usage, err = pool.GetCustomVolumeUsage(d.Project(), dev.Config["source"])
if err != nil {
if errors.Cause(err) != storageDrivers.ErrNotSupported {
d.logger.Error("Error getting volume usage", log.Ctx{"volume": dev.Config["source"], "err": err})
}
continue
}
} else {
continue
}
disk[dev.Name] = api.InstanceStateDisk{Usage: usage}
}
return disk
}
func (d *lxc) memoryState() api.InstanceStateMemory {
memory := api.InstanceStateMemory{}
cg, err := d.cgroup(nil)
if err != nil {
return memory
}
if !d.state.OS.CGInfo.Supports(cgroup.Memory, cg) {
return memory
}
// Memory in bytes
value, err := cg.GetMemoryUsage()
if err == nil {
memory.Usage = value
}
// Memory peak in bytes
if d.state.OS.CGInfo.Supports(cgroup.MemoryMaxUsage, cg) {
value, err = cg.GetMemoryMaxUsage()
if err == nil {
memory.UsagePeak = value
}
}
if d.state.OS.CGInfo.Supports(cgroup.MemorySwapUsage, cg) {
// Swap in bytes
if memory.Usage > 0 {
value, err := cg.GetMemorySwapUsage()
if err == nil {
memory.SwapUsage = value
}
}
// Swap peak in bytes
if memory.UsagePeak > 0 {
value, err = cg.GetMemorySwapMaxUsage()
if err == nil {
memory.SwapUsagePeak = value
}
}
}
return memory
}
func (d *lxc) networkState() map[string]api.InstanceStateNetwork {
result := map[string]api.InstanceStateNetwork{}
pid := d.InitPID()
if pid < 1 {
return result
}
couldUseNetnsGetifaddrs := d.state.OS.NetnsGetifaddrs
if couldUseNetnsGetifaddrs {
nw, err := netutils.NetnsGetifaddrs(int32(pid))
if err != nil {
couldUseNetnsGetifaddrs = false
d.logger.Error("Failed to retrieve network information via netlink", log.Ctx{"pid": pid})
} else {
result = nw
}
}
if !couldUseNetnsGetifaddrs {
pidFdNr, pidFd := d.inheritInitPidFd()
if pidFdNr >= 0 {
defer pidFd.Close()
}
// Get the network state from the container
out, _, err := shared.RunCommandSplit(
nil,
[]*os.File{pidFd},
d.state.OS.ExecPath,
"forknet",
"info",
"--",
fmt.Sprintf("%d", pid),
fmt.Sprintf("%d", pidFdNr))
// Process forkgetnet response
if err != nil {
d.logger.Error("Error calling 'lxd forknet", log.Ctx{"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.
d.state.OS.NetnsGetifaddrs = false
nw := map[string]api.InstanceStateNetwork{}
err = json.Unmarshal([]byte(out), &nw)
if err != nil {
d.logger.Error("Failure to read forknet json", log.Ctx{"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 = d.localConfig[fmt.Sprintf("volatile.%s.host_name", name)]
result[name] = dev
}
}
return result
}
func (d *lxc) processesState() int64 {
// Return 0 if not running
pid := d.InitPID()
if pid == -1 {
return 0
}
cg, err := d.cgroup(nil)
if err != nil {
return 0
}
if d.state.OS.CGInfo.Supports(cgroup.Pids, cg) {
value, err := cg.GetProcessesUsage()
if err != nil {
return -1
}
return value
}
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 (d *lxc) getStoragePool() (storagePools.Pool, error) {
if d.storagePool != nil {
return d.storagePool, nil
}
pool, err := storagePools.GetPoolByInstance(d.state, d)
if err != nil {
return nil, err
}
d.storagePool = pool
return d.storagePool, nil
}
// getStorageType returns the storage type of the instance's storage pool.
func (d *lxc) getStorageType() (string, error) {
pool, err := d.getStoragePool()
if err != nil {
return "", err
}
return pool.Driver().Info().Name, nil
}
// mount the instance's rootfs volume if needed.
func (d *lxc) mount() (*storagePools.MountInfo, error) {
pool, err := d.getStoragePool()
if err != nil {
return nil, err
}
if d.IsSnapshot() {
mountInfo, err := pool.MountInstanceSnapshot(d, nil)
if err != nil {
return nil, err
}
return mountInfo, nil
}
mountInfo, err := pool.MountInstance(d, nil)
if err != nil {
return nil, err
}
return mountInfo, nil
}
// unmount the instance's rootfs volume if needed.
func (d *lxc) unmount() (bool, error) {
pool, err := d.getStoragePool()
if err != nil {
return false, err
}
if d.IsSnapshot() {
unmounted, err := pool.UnmountInstanceSnapshot(d, nil)
if err != nil {
return false, err
}
return unmounted, nil
}
// Workaround for liblxc failures on startup when shiftfs is used.
diskIdmap, err := d.DiskIdmap()
if err != nil {
return false, err
}
if d.IdmappedStorage(d.RootfsPath()) == idmap.IdmapStorageShiftfs && !d.IsPrivileged() && diskIdmap == nil {
unix.Unmount(d.RootfsPath(), unix.MNT_DETACH)
}
unmounted, err := pool.UnmountInstance(d, nil)
if err != nil {
return false, err
}
return unmounted, nil
}
// insertMountLXD inserts a mount into a LXD container.
// This function is used for the seccomp notifier and so cannot call any
// functions that would cause LXC to talk to the container's monitor. Otherwise
// we'll have a deadlock (with a timeout but still). The InitPID() call here is
// the exception since the seccomp notifier will make sure to always pass a
// valid PID.
func (d *lxc) insertMountLXD(source, target, fstype string, flags int, mntnsPID int, idmapType idmap.IdmapStorageType) error {
pid := mntnsPID
if pid <= 0 {
// Get the init PID
pid = d.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(d.ShmountsPath(), "lxdmount_")
if err != nil {
return fmt.Errorf("Failed to create shmounts path: %s", err)
}
} else {
f, err := ioutil.TempFile(d.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)
// Ensure that only flags modifying mount _properties_ make it through.
// Strip things such as MS_BIND which would cause the creation of a
// shiftfs mount to be skipped.
// (Fyi, this is just one of the reasons why multiplexers are bad;
// specifically when they do heinous things such as confusing flags
// with commands.)
// This is why multiplexers are bad
shiftfsFlags := (flags & (unix.MS_RDONLY |
unix.MS_NOSUID |
unix.MS_NODEV |
unix.MS_NOEXEC |
unix.MS_DIRSYNC |
unix.MS_NOATIME |
unix.MS_NODIRATIME))
// Setup host side shiftfs as needed
switch idmapType {
case idmap.IdmapStorageShiftfs:
err = unix.Mount(tmpMount, tmpMount, "shiftfs", uintptr(shiftfsFlags), "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)
case idmap.IdmapStorageIdmapped:
case idmap.IdmapStorageNone:
default:
return fmt.Errorf("Invalid idmap value specified")
}
// Move the mount inside the container
mntsrc := filepath.Join("/dev/.lxd-mounts", filepath.Base(tmpMount))
pidStr := fmt.Sprintf("%d", pid)
pidFdNr, pidFd := seccomp.MakePidFd(pid, d.state)
if pidFdNr >= 0 {
defer pidFd.Close()
}
if !strings.HasPrefix(target, "/") {
target = "/" + target
}
_, err = shared.RunCommandInheritFds(
[]*os.File{pidFd},
d.state.OS.ExecPath,
"forkmount",
"lxd-mount",
"--",
pidStr,
fmt.Sprintf("%d", pidFdNr),
mntsrc,
target,
string(idmapType),
fmt.Sprintf("%d", shiftfsFlags))
if err != nil {
return err
}
return nil
}
func (d *lxc) insertMountLXC(source, target, fstype string, flags int) error {
cname := project.Instance(d.Project(), d.Name())
configPath := filepath.Join(d.LogPath(), "lxc.conf")
if fstype == "" {
fstype = "none"
}
if !strings.HasPrefix(target, "/") {
target = "/" + target
}
_, err := shared.RunCommand(
d.state.OS.ExecPath,
"forkmount",
"lxc-mount",
"--",
cname,
d.state.OS.LxcPath,
configPath,
source,
target,
fstype,
fmt.Sprintf("%d", flags))
if err != nil {
return err
}
return nil
}
func (d *lxc) insertMount(source, target, fstype string, flags int, idmapType idmap.IdmapStorageType) error {
if d.state.OS.LXCFeatures["mount_injection_file"] && idmapType == idmap.IdmapStorageNone {
return d.insertMountLXC(source, target, fstype, flags)
}
return d.insertMountLXD(source, target, fstype, flags, -1, idmapType)
}
func (d *lxc) removeMount(mount string) error {
// Get the init PID
pid := d.InitPID()
if pid == -1 {
// Container isn't running
return fmt.Errorf("Can't remove mount from stopped container")
}
if d.state.OS.LXCFeatures["mount_injection_file"] {
configPath := filepath.Join(d.LogPath(), "lxc.conf")
cname := project.Instance(d.Project(), d.Name())
if !strings.HasPrefix(mount, "/") {
mount = "/" + mount
}
_, err := shared.RunCommand(
d.state.OS.ExecPath,
"forkmount",
"lxc-umount",
"--",
cname,
d.state.OS.LxcPath,
configPath,
mount)
if err != nil {
return err
}
} else {
// Remove the mount from the container
pidFdNr, pidFd := d.inheritInitPidFd()
if pidFdNr >= 0 {
defer pidFd.Close()
}
_, err := shared.RunCommandInheritFds(
[]*os.File{pidFd},
d.state.OS.ExecPath,
"forkmount",
"lxd-umount",
"--",
fmt.Sprintf("%d", pid),
fmt.Sprintf("%d", pidFdNr),
mount)
if err != nil {
return err
}
}
return nil
}
// InsertSeccompUnixDevice inserts a seccomp device.
func (d *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 := d.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 := d.CurrentIdmap()
if err != nil {
return err
}
dev, err := device.UnixDeviceCreate(d.state, idmapSet, d.DevicesPath(), prefix, m, true)
if err != nil {
return fmt.Errorf("Failed to setup device: %s", err)
}
devPath := dev.HostPath
tgtPath := dev.RelativePath
// Bind-mount it into the container
defer os.Remove(devPath)
return d.insertMountLXD(devPath, tgtPath, "none", unix.MS_BIND, pid, idmap.IdmapStorageNone)
}
func (d *lxc) removeUnixDevices() error {
// Check that we indeed have devices to remove
if !shared.PathExists(d.DevicesPath()) {
return nil
}
// Load the directory listing
dents, err := ioutil.ReadDir(d.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(d.DevicesPath(), f.Name())
err := os.Remove(devicePath)
if err != nil {
d.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 (d *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 d.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 d.expandedConfig {
if !strings.HasPrefix(k, shared.ConfigVolatilePrefix) {
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(d.Project(), d.Name())
cc, err := liblxc.NewContainer(cname, d.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++
}
}
nicType, err := nictype.NICType(d.state, d.Project(), m)
if err != nil {
return nil, err
}
// Fill in the MAC address.
if !shared.StringInSlice(nicType, []string{"physical", "ipvlan", "sriov"}) && m["hwaddr"] == "" {
configKey := fmt.Sprintf("volatile.%s.hwaddr", name)
volatileHwaddr := d.localConfig[configKey]
if volatileHwaddr == "" {
// Generate a new MAC address.
volatileHwaddr, err = instance.DeviceNextInterfaceHWAddr()
if err != nil || volatileHwaddr == "" {
return nil, errors.Wrapf(err, "Failed generating %q", configKey)
}
// Update the database and update volatileHwaddr with stored value.
volatileHwaddr, err = d.insertConfigkey(configKey, volatileHwaddr)
if err != nil {
return nil, errors.Wrapf(err, "Failed storing generated config key %q", configKey)
}
// Set stored value into current instance config.
d.localConfig[configKey] = volatileHwaddr
d.expandedConfig[configKey] = volatileHwaddr
}
if volatileHwaddr == "" {
return nil, fmt.Errorf("Failed getting %q", configKey)
}
newDevice["hwaddr"] = volatileHwaddr
}
// Fill in the interface name.
if m["name"] == "" {
configKey := fmt.Sprintf("volatile.%s.name", name)
volatileName := d.localConfig[configKey]
if volatileName == "" {
// Generate a new interface name.
volatileName, err = nextInterfaceName()
if err != nil || volatileName == "" {
return nil, errors.Wrapf(err, "Failed generating %q", configKey)
}
// Update the database and update volatileName with stored value.
volatileName, err = d.insertConfigkey(configKey, volatileName)
if err != nil {
return nil, errors.Wrapf(err, "Failed storing generated config key %q", configKey)
}
// Set stored value into current instance config.
d.localConfig[configKey] = volatileName
d.expandedConfig[configKey] = volatileName
}
if volatileName == "" {
return nil, fmt.Errorf("Failed getting %q", configKey)
}
newDevice["name"] = volatileName
}
return newDevice, nil
}
func (d *lxc) removeDiskDevices() error {
// Check that we indeed have devices to remove
if !shared.PathExists(d.DevicesPath()) {
return nil
}
// Load the directory listing
dents, err := ioutil.ReadDir(d.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(d.DevicesPath(), f.Name()), unix.MNT_DETACH)
// Remove the entry
diskPath := filepath.Join(d.DevicesPath(), f.Name())
err := os.Remove(diskPath)
if err != nil {
d.logger.Error("Failed to remove disk device path", log.Ctx{"err": err, "path": diskPath})
}
}
return nil
}
// Network I/O limits
func (d *lxc) setNetworkPriority() error {
// Load the go-lxc struct.
err := d.initLXC(false)
if err != nil {
return err
}
// Load the cgroup struct.
cg, err := d.cgroup(nil)
if err != nil {
return err
}
// Check that the container is running
if !d.IsRunning() {
return fmt.Errorf("Can't set network priority on stopped container")
}
// Don't bother if the cgroup controller doesn't exist
if !d.state.OS.CGInfo.Supports(cgroup.NetPrio, cg) {
return nil
}
// Extract the current priority
networkPriority := d.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
}
// IsFrozen returns if instance is frozen.
func (d *lxc) IsFrozen() bool {
return d.statusCode() == api.Frozen
}
// IsNesting returns if instance is nested.
func (d *lxc) IsNesting() bool {
return shared.IsTrue(d.expandedConfig["security.nesting"])
}
func (d *lxc) isCurrentlyPrivileged() bool {
if !d.IsRunning() {
return d.IsPrivileged()
}
idmap, err := d.CurrentIdmap()
if err != nil {
return d.IsPrivileged()
}
return idmap == nil
}
// IsPrivileged returns if instance is privileged.
func (d *lxc) IsPrivileged() bool {
return shared.IsTrue(d.expandedConfig["security.privileged"])
}
// IsRunning returns if instance is running.
func (d *lxc) IsRunning() bool {
return d.isRunningStatusCode(d.statusCode())
}
// CanMigrate returns whether the instance can be migrated.
func (d *lxc) CanMigrate() bool {
return d.canMigrate(d)
}
// InitPID returns PID of init process.
func (d *lxc) InitPID() int {
// Load the go-lxc struct
err := d.initLXC(false)
if err != nil {
return -1
}
return d.c.InitPid()
}
// InitPidFd returns pidfd of init process.
func (d *lxc) InitPidFd() (*os.File, error) {
// Load the go-lxc struct
err := d.initLXC(false)
if err != nil {
return nil, err
}
return d.c.InitPidFd()
}
// DevptsFd returns dirfd of devpts mount.
func (d *lxc) DevptsFd() (*os.File, error) {
// Load the go-lxc struct
err := d.initLXC(false)
if err != nil {
return nil, err
}
defer d.release()
if !liblxc.HasApiExtension("devpts_fd") {
return nil, fmt.Errorf("Missing devpts_fd extension")
}
return d.c.DevptsFd()
}
// CurrentIdmap returns current IDMAP.
func (d *lxc) CurrentIdmap() (*idmap.IdmapSet, error) {
jsonIdmap, ok := d.LocalConfig()["volatile.idmap.current"]
if !ok {
return d.DiskIdmap()
}
return idmap.JSONUnmarshal(jsonIdmap)
}
// DiskIdmap returns DISK IDMAP.
func (d *lxc) DiskIdmap() (*idmap.IdmapSet, error) {
jsonIdmap, ok := d.LocalConfig()["volatile.last_state.idmap"]
if !ok {
return nil, nil
}
return idmap.JSONUnmarshal(jsonIdmap)
}
// NextIdmap returns next IDMAP.
func (d *lxc) NextIdmap() (*idmap.IdmapSet, error) {
jsonIdmap, ok := d.LocalConfig()["volatile.idmap.next"]
if !ok {
return d.CurrentIdmap()
}
return idmap.JSONUnmarshal(jsonIdmap)
}
// statusCode returns instance status code.
func (d *lxc) statusCode() api.StatusCode {
state, err := d.getLxcState()
if err != nil {
return api.Error
}
return lxcStatusCode(state)
}
// State returns instance state.
func (d *lxc) State() string {
return strings.ToUpper(d.statusCode().String())
}
// LogFilePath log file path.
func (d *lxc) LogFilePath() string {
return filepath.Join(d.LogPath(), "lxc.log")
}
// StoragePool storage pool name.
func (d *lxc) StoragePool() (string, error) {
poolName, err := d.state.Cluster.GetInstancePool(d.Project(), d.Name())
if err != nil {
return "", err
}
return poolName, nil
}
func (d *lxc) CGroup() (*cgroup.CGroup, error) {
// Load the go-lxc struct
err := d.initLXC(false)
if err != nil {
return nil, err
}
return d.cgroup(nil)
}
func (d *lxc) cgroup(cc *liblxc.Container) (*cgroup.CGroup, error) {
rw := lxcCgroupReadWriter{}
if cc != nil {
rw.cc = cc
rw.conf = true
} else {
rw.cc = d.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 (d *lxc) UpdateBackupFile() error {
pool, err := d.getStoragePool()
if err != nil {
return err
}
return pool.UpdateInstanceBackupFile(d, nil)
}
// SaveConfigFile generates the LXC config file on disk.
func (d *lxc) SaveConfigFile() error {
err := d.initLXC(true)
if err != nil {
return errors.Wrapf(err, "Failed to generate LXC config")
}
// Generate the LXC config.
configPath := filepath.Join(d.LogPath(), "lxc.conf")
err = d.c.SaveConfigFile(configPath)
if err != nil {
os.Remove(configPath)
return errors.Wrapf(err, "Failed to save LXC config to file %q", configPath)
}
return nil
}
// Info returns "lxc" and the currently loaded version of LXC
func (d *lxc) Info() instance.Info {
return instance.Info{
Name: "lxc",
Version: liblxc.Version(),
Type: instancetype.Container,
Error: nil,
}
}
func (d *lxc) Metrics() (*metrics.MetricSet, error) {
out := metrics.NewMetricSet(map[string]string{"project": d.project, "name": d.name, "type": instancetype.Container.String()})
// Load cgroup abstraction
cg, err := d.cgroup(nil)
if err != nil {
return nil, err
}
// Get Memory metrics
memStats, err := cg.GetMemoryStats()
if err != nil {
logger.Warn("Failed to get memory stats", log.Ctx{"err": err})
} else {
for k, v := range memStats {
var metricType metrics.MetricType
switch k {
case "active_anon":
metricType = metrics.MemoryActiveAnonBytes
case "active_file":
metricType = metrics.MemoryActiveFileBytes
case "active":
metricType = metrics.MemoryActiveBytes
case "inactive_anon":
metricType = metrics.MemoryInactiveAnonBytes
case "inactive_file":
metricType = metrics.MemoryInactiveFileBytes
case "inactive":
metricType = metrics.MemoryInactiveBytes
case "unevictable":
metricType = metrics.MemoryUnevictableBytes
case "writeback":
metricType = metrics.MemoryWritebackBytes
case "dirty":
metricType = metrics.MemoryDirtyBytes
case "mapped":
metricType = metrics.MemoryMappedBytes
case "rss":
metricType = metrics.MemoryRSSBytes
case "shmem":
metricType = metrics.MemoryShmemBytes
case "cache":
metricType = metrics.MemoryCachedBytes
}
out.AddSamples(metricType, metrics.Sample{Value: v})
}
}
memoryUsage, err := cg.GetMemoryUsage()
if err != nil {
logger.Warn("Failed to get memory usage", log.Ctx{"err": err})
} else {
out.AddSamples(metrics.MemoryMemTotalBytes, metrics.Sample{Value: uint64(memoryUsage)})
}
memoryLimit := uint64(0)
// Get total memory
totalMemory, err := shared.DeviceTotalMemory()
if err != nil {
logger.Warn("Failed to get total memory", log.Ctx{"err": err})
} else {
// Get memory limit
limit, err := cg.GetMemoryLimit()
if err != nil || limit > totalMemory {
// If the memory limit couldn't be determined, use the total memory.
// If the value of limit is larger than the total memory, there is no limit set.
// In this case, also use the total memory as the limit.
memoryLimit = uint64(totalMemory)
} else {
memoryLimit = uint64(limit)
}
}
if memoryLimit > 0 {
out.AddSamples(metrics.MemoryMemAvailableBytes, metrics.Sample{Value: memoryLimit})
out.AddSamples(metrics.MemoryMemFreeBytes, metrics.Sample{Value: memoryLimit - uint64(memoryUsage)})
}
if d.state.OS.CGInfo.Supports(cgroup.MemorySwapUsage, cg) {
swapUsage, err := cg.GetMemorySwapUsage()
if err != nil {
logger.Warn("Failed to get swap usage", log.Ctx{"err": err})
} else {
out.AddSamples(metrics.MemorySwapBytes, metrics.Sample{Value: uint64(swapUsage)})
}
}
// Get CPU stats
usage, err := cg.GetCPUAcctUsageAll()
if err != nil {
logger.Warn("Failed to get CPU usage", log.Ctx{"err": err})
} else {
for cpu, stats := range usage {
out.AddSamples(metrics.CPUSecondsTotal, metrics.Sample{Value: uint64(stats.System / 1000000), Labels: map[string]string{"mode": "system", "cpu": strconv.Itoa(int(cpu))}})
out.AddSamples(metrics.CPUSecondsTotal, metrics.Sample{Value: uint64(stats.User / 1000000), Labels: map[string]string{"mode": "user", "cpu": strconv.Itoa(int(cpu))}})
}
}
// Get disk stats
diskStats, err := cg.GetIOStats()
if err != nil {
logger.Warn("Failed to get disk stats", log.Ctx{"err": err})
} else {
for disk, stats := range diskStats {
out.AddSamples(metrics.DiskReadBytesTotal, metrics.Sample{Value: stats.ReadBytes, Labels: map[string]string{"device": disk}})
out.AddSamples(metrics.DiskReadsCompletedTotal, metrics.Sample{Value: stats.ReadsCompleted, Labels: map[string]string{"device": disk}})
out.AddSamples(metrics.DiskWrittenBytesTotal, metrics.Sample{Value: stats.WrittenBytes, Labels: map[string]string{"device": disk}})
out.AddSamples(metrics.DiskWritesCompletedTotal, metrics.Sample{Value: stats.WritesCompleted, Labels: map[string]string{"device": disk}})
}
}
// Get filesystem stats
fsStats, err := d.getFSStats()
if err != nil {
logger.Warn("Failed to get fs stats", log.Ctx{"err": err})
} else {
out.Merge(fsStats)
}
// Get network stats
networkState := d.networkState()
for name, state := range networkState {
out.AddSamples(metrics.NetworkReceiveBytesTotal, metrics.Sample{Value: uint64(state.Counters.BytesReceived), Labels: map[string]string{"device": name}})
out.AddSamples(metrics.NetworkReceivePacketsTotal, metrics.Sample{Value: uint64(state.Counters.PacketsReceived), Labels: map[string]string{"device": name}})
out.AddSamples(metrics.NetworkTransmitBytesTotal, metrics.Sample{Value: uint64(state.Counters.BytesSent), Labels: map[string]string{"device": name}})
out.AddSamples(metrics.NetworkTransmitPacketsTotal, metrics.Sample{Value: uint64(state.Counters.PacketsSent), Labels: map[string]string{"device": name}})
out.AddSamples(metrics.NetworkReceiveErrsTotal, metrics.Sample{Value: uint64(state.Counters.ErrorsReceived), Labels: map[string]string{"device": name}})
out.AddSamples(metrics.NetworkTransmitErrsTotal, metrics.Sample{Value: uint64(state.Counters.ErrorsSent), Labels: map[string]string{"device": name}})
out.AddSamples(metrics.NetworkReceiveDropTotal, metrics.Sample{Value: uint64(state.Counters.PacketsDroppedInbound), Labels: map[string]string{"device": name}})
out.AddSamples(metrics.NetworkTransmitDropTotal, metrics.Sample{Value: uint64(state.Counters.PacketsDroppedOutbound), Labels: map[string]string{"device": name}})
}
// Get number of processes
pids, err := cg.GetTotalProcesses()
if err != nil {
logger.Warn("Failed to get total number of processes", log.Ctx{"err": err})
} else {
out.AddSamples(metrics.ProcsTotal, metrics.Sample{Value: uint64(pids)})
}
return out, nil
}
func (d *lxc) getFSStats() (*metrics.MetricSet, error) {
type mountInfo struct {
Mountpoint string
FSType string
}
out := metrics.NewMetricSet(map[string]string{"project": d.project, "name": d.name})
mounts, err := ioutil.ReadFile("/proc/mounts")
if err != nil {
return nil, errors.Wrap(err, "Failed to read /proc/mounts")
}
mountMap := make(map[string]mountInfo)
scanner := bufio.NewScanner(bytes.NewReader(mounts))
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
mountMap[fields[0]] = mountInfo{Mountpoint: fields[1], FSType: fields[2]}
}
// Get disk devices
for _, dev := range d.expandedDevices {
if dev["type"] != "disk" || dev["path"] == "" {
continue
}
var statfs *unix.Statfs_t
labels := make(map[string]string)
realDev := ""
if dev["pool"] != "" {
// Storage pool volume
pool, err := storage.GetPoolByName(d.state, dev["pool"])
if err != nil {
return nil, errors.Wrap(err, "Failed to get pool")
}
volumes, err := pool.Driver().ListVolumes()
if err != nil {
return nil, errors.Wrap(err, "Failed to list volumes")
}
mountpoint := ""
for _, vol := range volumes {
// Skip all non-custom volumes
if vol.Type() != storageDrivers.VolumeTypeCustom || vol.Name() == "" {
continue
}
projectName, volName := project.StorageVolumeParts(vol.Name())
// Find the correct volume
if dev["source"] != volName || d.project != projectName {
continue
}
mountpoint = vol.MountPath()
break
}
if mountpoint == "" {
continue
}
statfs, err = filesystem.StatVFS(mountpoint)
if err != nil {
return nil, errors.Wrapf(err, "Failed to stat %s", mountpoint)
}
isMounted := false
// Check if mountPath is in mountMap
for mountDev, mountInfo := range mountMap {
if mountInfo.Mountpoint != mountpoint {
continue
}
isMounted = true
realDev = mountDev
break
}
if !isMounted {
realDev = dev["source"]
}
} else {
statfs, err = filesystem.StatVFS(dev["source"])
if err != nil {
return nil, errors.Wrapf(err, "Failed to stat %s", dev["source"])
}
isMounted := false
// Check if mountPath is in mountMap
for mountDev, mountInfo := range mountMap {
if mountInfo.Mountpoint != dev["source"] {
continue
}
isMounted = true
stat := unix.Stat_t{}
// Check if dev has a backing file
err = unix.Stat(dev["source"], &stat)
if err != nil {
return nil, errors.Wrapf(err, "Failed to stat %s", dev["source"])
}
backingFilePath := fmt.Sprintf("/sys/dev/block/%d:%d/loop/backing_file", unix.Major(stat.Dev), unix.Minor(stat.Dev))
if shared.PathExists(backingFilePath) {
// Read backing file
backingFile, err := ioutil.ReadFile(backingFilePath)
if err != nil {
return nil, errors.Wrapf(err, "Failed to read %s", backingFilePath)
}
realDev = string(backingFile)
} else {
// Use dev as device
realDev = mountDev
}
break
}
if !isMounted {
realDev = dev["source"]
}
}
// Add labels
labels["device"] = realDev
labels["mountpoint"] = dev["path"]
fsType, err := filesystem.FSTypeToName(int32(statfs.Type))
if err == nil {
labels["fstype"] = fsType
}
// Add sample
out.AddSamples(metrics.FilesystemSizeBytes, metrics.Sample{Value: statfs.Blocks * uint64(statfs.Bsize), Labels: labels})
out.AddSamples(metrics.FilesystemAvailBytes, metrics.Sample{Value: statfs.Bavail * uint64(statfs.Bsize), Labels: labels})
out.AddSamples(metrics.FilesystemFreeBytes, metrics.Sample{Value: statfs.Bfree * uint64(statfs.Bsize), Labels: labels})
}
return out, nil
}
func (d *lxc) loadRawLXCConfig() error {
// Load the LXC raw config.
lxcConfig, ok := d.expandedConfig["raw.lxc"]
if !ok {
return nil
}
// Write to temp config file.
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
}
// Load the config.
err = d.c.LoadConfigFile(f.Name())
if err != nil {
return fmt.Errorf("Failed to load config file %q: %w", f.Name(), err)
}
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 | |
compiler/tests/03_ptx_4finger_nmos_test.py | #!/usr/bin/env python3
# See LICENSE for licensing information.
#
# Copyright (c) 2016-2019 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
import unittest
from testutils import *
import sys,os
sys.path.append(os.getenv("OPENRAM_HOME"))
import globals
from globals import OPTS
from sram_factory import factory
import debug
class ptx_4finger_nmos_test(openram_test):
def runTest(self):
config_file = "{}/tests/configs/config".format(os.getenv("OPENRAM_HOME"))
globals.init_openram(config_file)
import tech
debug.info(2, "Checking three fingers NMOS")
fet = factory.create(module_type="ptx",
width= tech.drc["minwidth_tx"],
mults=4,
tx_type="nmos",
connect_source_active=True,
connect_drain_active=True,
connect_poly=True)
self.local_drc_check(fet)
globals.end_openram()
# run the test from the command line
if __name__ == "__main__":
(OPTS, args) = globals.parse_args()
del sys.argv[1:]
header(__file__, OPTS.tech_name)
unittest.main(testRunner=debugTestRunner())
| []
| []
| [
"OPENRAM_HOME"
]
| [] | ["OPENRAM_HOME"] | python | 1 | 0 | |
internal/gitaly/rubyserver/rubyserver.go | package rubyserver
import (
"context"
"fmt"
"net"
"os"
"path/filepath"
"strconv"
"sync"
"time"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_prometheus "github.com/grpc-ecosystem/go-grpc-prometheus"
"gitlab.com/gitlab-org/gitaly/internal/command"
"gitlab.com/gitlab-org/gitaly/internal/git/hooks"
"gitlab.com/gitlab-org/gitaly/internal/gitaly/config"
"gitlab.com/gitlab-org/gitaly/internal/gitaly/rubyserver/balancer"
"gitlab.com/gitlab-org/gitaly/internal/helper"
"gitlab.com/gitlab-org/gitaly/internal/supervisor"
"gitlab.com/gitlab-org/gitaly/internal/version"
"gitlab.com/gitlab-org/gitaly/proto/go/gitalypb"
"gitlab.com/gitlab-org/gitaly/streamio"
grpccorrelation "gitlab.com/gitlab-org/labkit/correlation/grpc"
grpctracing "gitlab.com/gitlab-org/labkit/tracing/grpc"
"google.golang.org/grpc"
)
var (
// ConnectTimeout is the timeout for establishing a connection to the gitaly-ruby process.
ConnectTimeout = 40 * time.Second
)
func init() {
timeout64, err := strconv.ParseInt(os.Getenv("GITALY_RUBY_CONNECT_TIMEOUT"), 10, 32)
if err == nil && timeout64 > 0 {
ConnectTimeout = time.Duration(timeout64) * time.Second
}
}
func setupEnv(cfg config.Cfg) []string {
env := append(
os.Environ(),
"GITALY_LOG_DIR="+cfg.Logging.Dir,
"GITALY_RUBY_GIT_BIN_PATH="+cfg.Git.BinPath,
fmt.Sprintf("GITALY_RUBY_WRITE_BUFFER_SIZE=%d", streamio.WriteBufferSize),
fmt.Sprintf("GITALY_RUBY_MAX_COMMIT_OR_TAG_MESSAGE_SIZE=%d", helper.MaxCommitOrTagMessageSize),
"GITALY_RUBY_GITALY_BIN_DIR="+cfg.BinDir,
"GITALY_VERSION="+version.GetVersion(),
"GITALY_GIT_HOOKS_DIR="+hooks.Path(cfg),
"GITALY_SOCKET="+cfg.GitalyInternalSocketPath(),
"GITALY_TOKEN="+cfg.Auth.Token,
"GITALY_RUGGED_GIT_CONFIG_SEARCH_PATH="+cfg.Ruby.RuggedGitConfigSearchPath,
)
env = append(env, command.GitEnv...)
if dsn := cfg.Logging.RubySentryDSN; dsn != "" {
env = append(env, "SENTRY_DSN="+dsn)
}
if sentryEnvironment := cfg.Logging.Sentry.Environment; sentryEnvironment != "" {
env = append(env, "SENTRY_ENVIRONMENT="+sentryEnvironment)
}
return env
}
// Server represents a gitaly-ruby helper process.
type Server struct {
cfg config.Cfg
startOnce sync.Once
startErr error
workers []*worker
clientConnMu sync.Mutex
clientConn *grpc.ClientConn
}
// New returns a new instance of the server.
func New(cfg config.Cfg) *Server {
return &Server{cfg: cfg}
}
// Stop shuts down the gitaly-ruby helper process and cleans up resources.
func (s *Server) Stop() {
if s != nil {
s.clientConnMu.Lock()
defer s.clientConnMu.Unlock()
if s.clientConn != nil {
s.clientConn.Close()
}
for _, w := range s.workers {
w.stopMonitor()
w.Process.Stop()
}
}
}
// Start spawns the Ruby server.
func (s *Server) Start() error {
s.startOnce.Do(func() { s.startErr = s.start() })
return s.startErr
}
func (s *Server) start() error {
wd, err := os.Getwd()
if err != nil {
return err
}
cfg := s.cfg
env := setupEnv(cfg)
gitalyRuby := filepath.Join(cfg.Ruby.Dir, "bin", "gitaly-ruby")
numWorkers := cfg.Ruby.NumWorkers
balancer.ConfigureBuilder(numWorkers, 0, time.Now)
for i := 0; i < numWorkers; i++ {
name := fmt.Sprintf("gitaly-ruby.%d", i)
socketPath := filepath.Join(cfg.InternalSocketDir, fmt.Sprintf("ruby.%d", i))
// Use 'ruby-cd' to make sure gitaly-ruby has the same working directory
// as the current process. This is a hack to sort-of support relative
// Unix socket paths.
args := []string{"bundle", "exec", "bin/ruby-cd", wd, gitalyRuby, strconv.Itoa(os.Getpid()), socketPath}
events := make(chan supervisor.Event)
check := func() error { return ping(socketPath) }
p, err := supervisor.New(name, env, args, cfg.Ruby.Dir, cfg.Ruby.MaxRSS, events, check)
if err != nil {
return err
}
restartDelay := cfg.Ruby.RestartDelay.Duration()
gracefulRestartTimeout := cfg.Ruby.GracefulRestartTimeout.Duration()
s.workers = append(s.workers, newWorker(p, socketPath, restartDelay, gracefulRestartTimeout, events, false))
}
return nil
}
// CommitServiceClient returns a CommitServiceClient instance that is
// configured to connect to the running Ruby server. This assumes Start()
// has been called already.
func (s *Server) CommitServiceClient(ctx context.Context) (gitalypb.CommitServiceClient, error) {
conn, err := s.getConnection(ctx)
return gitalypb.NewCommitServiceClient(conn), err
}
// DiffServiceClient returns a DiffServiceClient instance that is
// configured to connect to the running Ruby server. This assumes Start()
// has been called already.
func (s *Server) DiffServiceClient(ctx context.Context) (gitalypb.DiffServiceClient, error) {
conn, err := s.getConnection(ctx)
return gitalypb.NewDiffServiceClient(conn), err
}
// RefServiceClient returns a RefServiceClient instance that is
// configured to connect to the running Ruby server. This assumes Start()
// has been called already.
func (s *Server) RefServiceClient(ctx context.Context) (gitalypb.RefServiceClient, error) {
conn, err := s.getConnection(ctx)
return gitalypb.NewRefServiceClient(conn), err
}
// OperationServiceClient returns a OperationServiceClient instance that is
// configured to connect to the running Ruby server. This assumes Start()
// has been called already.
func (s *Server) OperationServiceClient(ctx context.Context) (gitalypb.OperationServiceClient, error) {
conn, err := s.getConnection(ctx)
return gitalypb.NewOperationServiceClient(conn), err
}
// RepositoryServiceClient returns a RefServiceClient instance that is
// configured to connect to the running Ruby server. This assumes Start()
// has been called already.
func (s *Server) RepositoryServiceClient(ctx context.Context) (gitalypb.RepositoryServiceClient, error) {
conn, err := s.getConnection(ctx)
return gitalypb.NewRepositoryServiceClient(conn), err
}
// WikiServiceClient returns a WikiServiceClient instance that is
// configured to connect to the running Ruby server. This assumes Start()
// has been called already.
func (s *Server) WikiServiceClient(ctx context.Context) (gitalypb.WikiServiceClient, error) {
conn, err := s.getConnection(ctx)
return gitalypb.NewWikiServiceClient(conn), err
}
// RemoteServiceClient returns a RemoteServiceClient instance that is
// configured to connect to the running Ruby server. This assumes Start()
// has been called already.
func (s *Server) RemoteServiceClient(ctx context.Context) (gitalypb.RemoteServiceClient, error) {
conn, err := s.getConnection(ctx)
return gitalypb.NewRemoteServiceClient(conn), err
}
// BlobServiceClient returns a BlobServiceClient instance that is
// configured to connect to the running Ruby server. This assumes Start()
// has been called already.
func (s *Server) BlobServiceClient(ctx context.Context) (gitalypb.BlobServiceClient, error) {
conn, err := s.getConnection(ctx)
return gitalypb.NewBlobServiceClient(conn), err
}
func (s *Server) getConnection(ctx context.Context) (*grpc.ClientConn, error) {
s.clientConnMu.Lock()
conn := s.clientConn
s.clientConnMu.Unlock()
if conn != nil {
return conn, nil
}
return s.createConnection(ctx)
}
func (s *Server) createConnection(ctx context.Context) (*grpc.ClientConn, error) {
s.clientConnMu.Lock()
defer s.clientConnMu.Unlock()
if conn := s.clientConn; conn != nil {
return conn, nil
}
dialCtx, cancel := context.WithTimeout(ctx, ConnectTimeout)
defer cancel()
conn, err := grpc.DialContext(dialCtx, balancer.Scheme+":///gitaly-ruby", dialOptions()...)
if err != nil {
return nil, fmt.Errorf("failed to connect to gitaly-ruby worker: %v", err)
}
s.clientConn = conn
return s.clientConn, nil
}
func dialOptions() []grpc.DialOption {
return []grpc.DialOption{
grpc.WithBlock(), // With this we get retries. Without, connections fail fast.
grpc.WithInsecure(),
// Use a custom dialer to ensure that we don't experience
// issues in environments that have proxy configurations
// https://gitlab.com/gitlab-org/gitaly/merge_requests/1072#note_140408512
grpc.WithContextDialer(func(ctx context.Context, addr string) (conn net.Conn, err error) {
d := net.Dialer{}
return d.DialContext(ctx, "unix", addr)
}),
grpc.WithUnaryInterceptor(
grpc_middleware.ChainUnaryClient(
grpc_prometheus.UnaryClientInterceptor,
grpctracing.UnaryClientTracingInterceptor(),
grpccorrelation.UnaryClientCorrelationInterceptor(),
),
),
grpc.WithStreamInterceptor(
grpc_middleware.ChainStreamClient(
grpc_prometheus.StreamClientInterceptor,
grpctracing.StreamClientTracingInterceptor(),
grpccorrelation.StreamClientCorrelationInterceptor(),
),
),
}
}
| [
"\"GITALY_RUBY_CONNECT_TIMEOUT\""
]
| []
| [
"GITALY_RUBY_CONNECT_TIMEOUT"
]
| [] | ["GITALY_RUBY_CONNECT_TIMEOUT"] | go | 1 | 0 | |
setup.py | #! /usr/bin/env python
import os
from setuptools import setup
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.settings')
CLASSIFIERS = [
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules']
setup(
name='django-prices-taxjar',
author='7222C',
description='taxjar.com support for django',
license='BSD',
version='0.0.1',
url='https://github.com/722C/django-prices-taxjar',
packages=[
'django_prices_taxjar', 'django_prices_taxjar.migrations',
'django_prices_taxjar.management',
'django_prices_taxjar.management.commands'],
include_package_data=True,
classifiers=CLASSIFIERS,
install_requires=[
'Django>=1.11', 'prices>=1.0.0', 'requests', 'jsonfield'],
platforms=['any'],
zip_safe=False)
| []
| []
| []
| [] | [] | python | 0 | 0 | |
vendor/fyne.io/fyne/app/app_mobile_and.go | // +build !ci
// +build android
package app
/*
#cgo LDFLAGS: -landroid -llog
#include <stdlib.h>
void sendNotification(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx, char *title, char *content);
*/
import "C"
import (
"log"
"net/url"
"os"
"unsafe"
mobileApp "github.com/fyne-io/mobile/app"
"fyne.io/fyne"
"fyne.io/fyne/theme"
)
func defaultTheme() fyne.Theme {
return theme.LightTheme()
}
func (app *fyneApp) OpenURL(url *url.URL) error {
cmd := app.exec("/system/bin/am", "start", "-a", "android.intent.action.VIEW", "--user", "0",
"-d", url.String())
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
return cmd.Run()
}
func (app *fyneApp) SendNotification(n *fyne.Notification) {
titleStr := C.CString(n.Title)
defer C.free(unsafe.Pointer(titleStr))
contentStr := C.CString(n.Content)
defer C.free(unsafe.Pointer(contentStr))
mobileApp.RunOnJVM(func(vm, env, ctx uintptr) error {
C.sendNotification(C.uintptr_t(vm), C.uintptr_t(env), C.uintptr_t(ctx), titleStr, contentStr)
return nil
})
}
func rootConfigDir() string {
filesDir := os.Getenv("FILESDIR")
if filesDir == "" {
log.Println("FILESDIR env was not set by android native code")
return "/data/data" // probably won't work, but we can't make a better guess
}
return filesDir
}
| [
"\"FILESDIR\""
]
| []
| [
"FILESDIR"
]
| [] | ["FILESDIR"] | go | 1 | 0 | |
checkov/serverless/runner.py | import logging
import os
from typing import List, Dict, Tuple
from checkov.cloudformation import cfn_utils
from checkov.cloudformation.context_parser import ContextParser as CfnContextParser
from checkov.common.parallelizer.parallel_runner import parallel_runner
from checkov.serverless.base_registry import EntityDetails
from checkov.serverless.parsers.context_parser import ContextParser as SlsContextParser
from checkov.cloudformation.checks.resource.registry import cfn_registry
from checkov.serverless.checks.complete.registry import complete_registry
from checkov.serverless.checks.custom.registry import custom_registry
from checkov.serverless.checks.function.registry import function_registry
from checkov.serverless.checks.layer.registry import layer_registry
from checkov.serverless.checks.package.registry import package_registry
from checkov.serverless.checks.plugin.registry import plugin_registry
from checkov.serverless.checks.provider.registry import provider_registry
from checkov.serverless.checks.service.registry import service_registry
from checkov.common.runners.base_runner import BaseRunner, filter_ignored_paths
from checkov.runner_filter import RunnerFilter
from checkov.common.output.record import Record
from checkov.common.output.report import Report, CheckType
from checkov.serverless.parsers.parser import parse
from checkov.common.parsers.node import DictNode
from checkov.serverless.parsers.parser import CFN_RESOURCES_TOKEN
SLS_FILE_MASK = os.getenv(
"CKV_SLS_FILE_MASK", "serverless.yml,serverless.yaml").split(",")
MULTI_ITEM_SECTIONS = [
("functions", function_registry),
("layers", layer_registry)
]
SINGLE_ITEM_SECTIONS = [
("custom", custom_registry),
("package", package_registry),
("plugins", plugin_registry),
("provider", provider_registry),
("service", service_registry)
]
class Runner(BaseRunner):
check_type = CheckType.SERVERLESS
def run(self, root_folder, external_checks_dir=None, files=None, runner_filter=RunnerFilter(), collect_skip_comments=True):
report = Report(self.check_type)
files_list = []
filepath_fn = None
if external_checks_dir:
for directory in external_checks_dir:
function_registry.load_external_checks(directory)
if files:
files_list = [file for file in files if os.path.basename(file) in SLS_FILE_MASK]
if root_folder:
filepath_fn = lambda f: f'/{os.path.relpath(f, os.path.commonprefix((root_folder, f)))}'
for root, d_names, f_names in os.walk(root_folder):
# Don't walk in to "node_modules" directories under the root folder. If –for some reason–
# scanning one of these is desired, it can be directly specified.
if "node_modules" in d_names:
d_names.remove("node_modules")
filter_ignored_paths(root, d_names, runner_filter.excluded_paths)
filter_ignored_paths(root, f_names, runner_filter.excluded_paths)
for file in f_names:
if file in SLS_FILE_MASK:
full_path = os.path.join(root, file)
if "/." not in full_path:
# skip temp directories
files_list.append(full_path)
definitions, definitions_raw = get_files_definitions(files_list, filepath_fn)
# Filter out empty files that have not been parsed successfully
definitions = {k: v for k, v in definitions.items() if v}
definitions_raw = {k: v for k, v in definitions_raw.items() if k in definitions.keys()}
for sls_file, sls_file_data in definitions.items():
# There are a few cases here. If -f was used, there could be a leading / because it's an absolute path,
# or there will be no leading slash; root_folder will always be none.
# If -d is used, root_folder will be the value given, and -f will start with a / (hardcoded above).
# The goal here is simply to get a valid path to the file (which sls_file does not always give).
if sls_file[0] == '/':
path_to_convert = (root_folder + sls_file) if root_folder else sls_file
else:
path_to_convert = (os.path.join(root_folder, sls_file)) if root_folder else sls_file
file_abs_path = os.path.abspath(path_to_convert)
if not isinstance(sls_file_data, DictNode):
continue
if CFN_RESOURCES_TOKEN in sls_file_data and isinstance(sls_file_data[CFN_RESOURCES_TOKEN], DictNode):
cf_sub_template = sls_file_data[CFN_RESOURCES_TOKEN]
if cf_sub_template.get("Resources"):
cf_context_parser = CfnContextParser(sls_file, cf_sub_template, definitions_raw[sls_file])
logging.debug(f"Template Dump for {sls_file}: {sls_file_data}")
cf_context_parser.evaluate_default_refs()
for resource_name, resource in cf_sub_template['Resources'].items():
if not isinstance(resource, DictNode):
continue
cf_resource_id = cf_context_parser.extract_cf_resource_id(resource, resource_name)
if not cf_resource_id:
# Not Type attribute for resource
continue
report.add_resource(f'{file_abs_path}:{cf_resource_id}')
entity_lines_range, entity_code_lines = cf_context_parser.extract_cf_resource_code_lines(
resource)
if entity_lines_range and entity_code_lines:
skipped_checks = CfnContextParser.collect_skip_comments(entity_code_lines)
# TODO - Variable Eval Message!
variable_evaluations = {}
entity = {resource_name: resource}
results = cfn_registry.scan(sls_file, entity, skipped_checks, runner_filter)
tags = cfn_utils.get_resource_tags(entity, cfn_registry)
for check, check_result in results.items():
record = Record(check_id=check.id, bc_check_id=check.bc_id, check_name=check.name, check_result=check_result,
code_block=entity_code_lines, file_path=sls_file,
file_line_range=entity_lines_range,
resource=cf_resource_id, evaluations=variable_evaluations,
check_class=check.__class__.__module__, file_abs_path=file_abs_path,
entity_tags=tags)
record.set_guideline(check.guideline)
report.add_record(record=record)
sls_context_parser = SlsContextParser(sls_file, sls_file_data, definitions_raw[sls_file])
# Sub-sections that have multiple items under them
for token, registry in MULTI_ITEM_SECTIONS:
template_items = sls_file_data.get(token)
if not template_items or not isinstance(template_items, dict):
continue
for item_name, item_content in template_items.items():
if not isinstance(item_content, DictNode):
continue
entity_lines_range, entity_code_lines = sls_context_parser.extract_code_lines(item_content)
if entity_lines_range and entity_code_lines:
skipped_checks = CfnContextParser.collect_skip_comments(entity_code_lines)
variable_evaluations = {}
if token == "functions": #nosec
# "Enriching" copies things like "environment" and "stackTags" down into the
# function data from the provider block since logically that's what serverless
# does. This allows checks to see what the complete data would be.
sls_context_parser.enrich_function_with_provider(item_name)
entity = EntityDetails(sls_context_parser.provider_type, item_content)
results = registry.scan(sls_file, entity, skipped_checks, runner_filter)
tags = cfn_utils.get_resource_tags(entity, registry)
for check, check_result in results.items():
record = Record(check_id=check.id, check_name=check.name, check_result=check_result,
code_block=entity_code_lines, file_path=sls_file,
file_line_range=entity_lines_range,
resource=item_name, evaluations=variable_evaluations,
check_class=check.__class__.__module__, file_abs_path=file_abs_path,
entity_tags=tags)
record.set_guideline(check.guideline)
report.add_record(record=record)
# Sub-sections that are a single item
for token, registry in SINGLE_ITEM_SECTIONS:
item_content = sls_file_data.get(token)
if not item_content:
continue
entity_lines_range, entity_code_lines = sls_context_parser.extract_code_lines(item_content)
if not entity_lines_range:
entity_lines_range, entity_code_lines = sls_context_parser.extract_code_lines(sls_file_data)
skipped_checks = CfnContextParser.collect_skip_comments(entity_code_lines)
variable_evaluations = {}
entity = EntityDetails(sls_context_parser.provider_type, item_content)
results = registry.scan(sls_file, entity, skipped_checks, runner_filter)
tags = cfn_utils.get_resource_tags(entity, registry)
for check, check_result in results.items():
record = Record(check_id=check.id, check_name=check.name, check_result=check_result,
code_block=entity_code_lines, file_path=sls_file,
file_line_range=entity_lines_range,
resource=token, evaluations=variable_evaluations,
check_class=check.__class__.__module__, file_abs_path=file_abs_path,
entity_tags=tags)
record.set_guideline(check.guideline)
report.add_record(record=record)
# "Complete" checks
# NOTE: Ignore code content, no point in showing (could be long)
entity_lines_range, entity_code_lines = sls_context_parser.extract_code_lines(sls_file_data)
if entity_lines_range:
skipped_checks = CfnContextParser.collect_skip_comments(entity_code_lines)
variable_evaluations = {}
entity = EntityDetails(sls_context_parser.provider_type, sls_file_data)
results = complete_registry.scan(sls_file, entity, skipped_checks, runner_filter)
tags = cfn_utils.get_resource_tags(entity, complete_registry)
for check, check_result in results.items():
record = Record(check_id=check.id, check_name=check.name, check_result=check_result,
code_block=[], # Don't show, could be large
file_path=sls_file,
file_line_range=entity_lines_range,
resource="complete", # Weird, not sure what to put where
evaluations=variable_evaluations,
check_class=check.__class__.__module__, file_abs_path=file_abs_path,
entity_tags=tags)
record.set_guideline(check.guideline)
report.add_record(record=record)
return report
def get_files_definitions(files: List[str], filepath_fn=None) \
-> Tuple[Dict[str, DictNode], Dict[str, List[Tuple[int, str]]]]:
results = parallel_runner.run_function(lambda f: (f, parse(f)), files)
definitions = {}
definitions_raw = {}
for file, result in results:
if result:
path = filepath_fn(file) if filepath_fn else file
definitions[path], definitions_raw[path] = result
return definitions, definitions_raw
| []
| []
| [
"CKV_SLS_FILE_MASK"
]
| [] | ["CKV_SLS_FILE_MASK"] | python | 1 | 0 | |
config/config.go | package config
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
//"crypto/rand"
//"encoding/hex"
)
var APP_DIR = os.Getenv("HOME") + "/.tendermint"
/* Global & initialization */
var Config Config_
func init() {
configFile := APP_DIR + "/config.json"
// try to read configuration. if missing, write default
configBytes, err := ioutil.ReadFile(configFile)
if err != nil {
defaultConfig.write(configFile)
fmt.Println("Config file written to config.json. Please edit & run again")
os.Exit(1)
return
}
// try to parse configuration. on error, die
Config = Config_{}
err = json.Unmarshal(configBytes, &Config)
if err != nil {
log.Panicf("Invalid configuration file %s: %v", configFile, err)
}
err = Config.validate()
if err != nil {
log.Panicf("Invalid configuration file %s: %v", configFile, err)
}
}
/* Default configuration */
var defaultConfig = Config_{
Host: "127.0.0.1",
Port: 8770,
Db: DbConfig{
Type: "level",
Dir: APP_DIR + "/data",
},
Twilio: TwilioConfig{},
}
/* Configuration types */
type Config_ struct {
Host string
Port int
Db DbConfig
Twilio TwilioConfig
}
type TwilioConfig struct {
Sid string
Token string
From string
To string
MinInterval int
}
type DbConfig struct {
Type string
Dir string
}
func (cfg *Config_) validate() error {
if cfg.Host == "" {
return errors.New("Host must be set")
}
if cfg.Port == 0 {
return errors.New("Port must be set")
}
if cfg.Db.Type == "" {
return errors.New("Db.Type must be set")
}
return nil
}
func (cfg *Config_) bytes() []byte {
configBytes, err := json.Marshal(cfg)
if err != nil {
panic(err)
}
return configBytes
}
func (cfg *Config_) write(configFile string) {
if strings.Index(configFile, "/") != -1 {
err := os.MkdirAll(filepath.Dir(configFile), 0700)
if err != nil {
panic(err)
}
}
err := ioutil.WriteFile(configFile, cfg.bytes(), 0600)
if err != nil {
panic(err)
}
}
/* TODO: generate priv/pub keys
func generateKeys() string {
bytes := &[30]byte{}
rand.Read(bytes[:])
return hex.EncodeToString(bytes[:])
}
*/
| [
"\"HOME\""
]
| []
| [
"HOME"
]
| [] | ["HOME"] | go | 1 | 0 | |
pkg/controller/multiclusterhub/multiclusterhub_controller.go | // Copyright (c) 2021 Red Hat, Inc.
// Copyright Contributors to the Open Cluster Management project
package multiclusterhub
import (
"context"
"fmt"
"os"
"strings"
"time"
hive "github.com/openshift/hive/pkg/apis/hive/v1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/util/workqueue"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
"github.com/go-logr/logr"
clustermanager "github.com/open-cluster-management/api/operator/v1"
appsubv1 "github.com/open-cluster-management/multicloud-operators-subscription/pkg/apis/apps/v1"
operatorsv1 "github.com/open-cluster-management/multiclusterhub-operator/pkg/apis/operator/v1"
"github.com/open-cluster-management/multiclusterhub-operator/pkg/channel"
"github.com/open-cluster-management/multiclusterhub-operator/pkg/deploying"
"github.com/open-cluster-management/multiclusterhub-operator/pkg/foundation"
"github.com/open-cluster-management/multiclusterhub-operator/pkg/helmrepo"
"github.com/open-cluster-management/multiclusterhub-operator/pkg/imageoverrides"
"github.com/open-cluster-management/multiclusterhub-operator/pkg/manifest"
"github.com/open-cluster-management/multiclusterhub-operator/pkg/predicate"
"github.com/open-cluster-management/multiclusterhub-operator/pkg/rendering"
"github.com/open-cluster-management/multiclusterhub-operator/pkg/subscription"
"github.com/open-cluster-management/multiclusterhub-operator/pkg/utils"
"github.com/open-cluster-management/multiclusterhub-operator/version"
netv1 "github.com/openshift/api/config/v1"
apiregistrationv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1"
)
const hubFinalizer = "finalizer.operator.open-cluster-management.io"
var log = logf.Log.WithName("controller_multiclusterhub")
var resyncPeriod = time.Second * 20
/**
* USER ACTION REQUIRED: This is a scaffold file intended for the user to modify with their own Controller
* business logic. Delete these comments after modifying this file.*
*/
// Add creates a new MultiClusterHub Controller and adds it to the Manager. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
func Add(mgr manager.Manager) error {
return add(mgr, newReconciler(mgr))
}
// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager) reconcile.Reconciler {
return &ReconcileMultiClusterHub{client: mgr.GetClient(), scheme: mgr.GetScheme()}
}
// add adds a new Controller to mgr with r as the reconcile.Reconciler
func add(mgr manager.Manager, r reconcile.Reconciler) error {
// Create a new controller
c, err := controller.New("multiclusterhub-controller", mgr, controller.Options{Reconciler: r})
if err != nil {
return err
}
// Watch for changes to primary resource MultiClusterHub
err = c.Watch(&source.Kind{Type: &operatorsv1.MultiClusterHub{}}, &handler.EnqueueRequestForObject{}, predicate.GenerationChangedPredicate{})
if err != nil {
return err
}
// Watch for changes to secondary resource Pods and requeue the owner MultiClusterHub
err = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: &operatorsv1.MultiClusterHub{},
})
if err != nil {
return err
}
// Watch application subscriptions
err = c.Watch(&source.Kind{Type: &appsubv1.Subscription{}}, &handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: &operatorsv1.MultiClusterHub{},
})
if err != nil {
return err
}
err = c.Watch(&source.Kind{Type: &corev1.ConfigMap{}}, &handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: &operatorsv1.MultiClusterHub{},
})
if err != nil {
return err
}
err = c.Watch(
&source.Kind{Type: &apiregistrationv1.APIService{}},
handler.Funcs{
DeleteFunc: func(e event.DeleteEvent, q workqueue.RateLimitingInterface) {
labels := e.Meta.GetLabels()
q.Add(reconcile.Request{NamespacedName: types.NamespacedName{
Name: labels["installer.name"],
Namespace: labels["installer.namespace"],
}})
},
},
predicate.DeletePredicate{},
)
if err != nil {
return err
}
err = c.Watch(
&source.Kind{Type: &hive.HiveConfig{}},
&handler.Funcs{
DeleteFunc: func(e event.DeleteEvent, q workqueue.RateLimitingInterface) {
labels := e.Meta.GetLabels()
q.Add(reconcile.Request{NamespacedName: types.NamespacedName{
Name: labels["installer.name"],
Namespace: labels["installer.namespace"],
}})
},
},
predicate.InstallerLabelPredicate{},
)
if err != nil {
return err
}
err = c.Watch(
&source.Kind{Type: &clustermanager.ClusterManager{}},
&handler.Funcs{
DeleteFunc: func(e event.DeleteEvent, q workqueue.RateLimitingInterface) {
labels := e.Meta.GetLabels()
q.Add(reconcile.Request{NamespacedName: types.NamespacedName{
Name: labels["installer.name"],
Namespace: labels["installer.namespace"],
}})
},
UpdateFunc: func(e event.UpdateEvent, q workqueue.RateLimitingInterface) {
labels := e.MetaOld.GetLabels()
q.Add(reconcile.Request{NamespacedName: types.NamespacedName{
Name: labels["installer.name"],
Namespace: labels["installer.namespace"],
}})
},
},
predicate.InstallerLabelPredicate{},
)
if err != nil {
return err
}
err = c.Watch(
&source.Kind{Type: &appsv1.Deployment{}},
&handler.EnqueueRequestsFromMapFunc{
ToRequests: handler.ToRequestsFunc(func(a handler.MapObject) []reconcile.Request {
return []reconcile.Request{
{NamespacedName: types.NamespacedName{
Name: a.Meta.GetLabels()["installer.name"],
Namespace: a.Meta.GetLabels()["installer.namespace"],
}},
}
}),
},
predicate.InstallerLabelPredicate{},
)
if err != nil {
return err
}
return nil
}
// blank assignment to verify that ReconcileMultiClusterHub implements reconcile.Reconciler
var _ reconcile.Reconciler = &ReconcileMultiClusterHub{}
// ReconcileMultiClusterHub reconciles a MultiClusterHub object
type ReconcileMultiClusterHub struct {
// This client, initialized using mgr.Client() above, is a split client
// that reads objects from the cache and writes to the apiserver
client client.Client
CacheSpec CacheSpec
scheme *runtime.Scheme
}
// Reconcile reads that state of the cluster for a MultiClusterHub object and makes changes based on the state read
// and what is in the MultiClusterHub.Spec
// Note:
// The Controller will requeue the Request to be processed again if the returned error is non-nil or
// Result.Requeue is true, otherwise upon completion it will remove the work from the queue.
func (r *ReconcileMultiClusterHub) Reconcile(request reconcile.Request) (retQueue reconcile.Result, retError error) {
reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name)
reqLogger.Info("Reconciling MultiClusterHub")
// Fetch the MultiClusterHub instance
multiClusterHub := &operatorsv1.MultiClusterHub{}
err := r.client.Get(context.TODO(), request.NamespacedName, multiClusterHub)
if err != nil {
if errors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile request.
// Owned objects are automatically garbage collected. For additional cleanup logic use finalizers.
// Return and don't requeue
reqLogger.Info("MultiClusterHub resource not found. Ignoring since object must be deleted")
return reconcile.Result{}, nil
}
// Error reading the object - requeue the request.
reqLogger.Error(err, "Failed to get MultiClusterHub CR")
return reconcile.Result{}, err
}
trackedNamespaces := utils.TrackedNamespaces(multiClusterHub)
allDeploys, err := r.listDeployments(trackedNamespaces)
if err != nil {
return reconcile.Result{}, err
}
allHRs, err := r.listHelmReleases(trackedNamespaces)
if err != nil {
return reconcile.Result{}, err
}
allCRs, err := r.listCustomResources()
if err != nil {
return reconcile.Result{}, err
}
originalStatus := multiClusterHub.Status.DeepCopy()
defer func() {
statusQueue, statusError := r.syncHubStatus(multiClusterHub, originalStatus, allDeploys, allHRs, allCRs)
if statusError != nil {
log.Error(retError, "Error updating status")
}
if empty := (reconcile.Result{}); retQueue == empty {
retQueue = statusQueue
}
if retError == nil {
retError = statusError
}
}()
// Check if the multiClusterHub instance is marked to be deleted, which is
// indicated by the deletion timestamp being set.
isHubMarkedToBeDeleted := multiClusterHub.GetDeletionTimestamp() != nil
if isHubMarkedToBeDeleted {
terminating := NewHubCondition(operatorsv1.Terminating, metav1.ConditionTrue, DeleteTimestampReason, "Multiclusterhub is being cleaned up.")
SetHubCondition(&multiClusterHub.Status, *terminating)
if contains(multiClusterHub.GetFinalizers(), hubFinalizer) {
// Run finalization logic. If the finalization
// logic fails, don't remove the finalizer so
// that we can retry during the next reconciliation.
if err := r.finalizeHub(reqLogger, multiClusterHub); err != nil {
// Logging err and returning nil to ensure 45 second wait
log.Info(fmt.Sprintf("Finalizing: %s", err.Error()))
return reconcile.Result{RequeueAfter: resyncPeriod}, nil
}
// Remove hubFinalizer. Once all finalizers have been
// removed, the object will be deleted.
multiClusterHub.SetFinalizers(remove(multiClusterHub.GetFinalizers(), hubFinalizer))
err := r.client.Update(context.TODO(), multiClusterHub)
if err != nil {
return reconcile.Result{}, err
}
}
return reconcile.Result{}, nil
}
// Add finalizer for this CR
if !contains(multiClusterHub.GetFinalizers(), hubFinalizer) {
if err := r.addFinalizer(reqLogger, multiClusterHub); err != nil {
return reconcile.Result{}, err
}
}
var result *reconcile.Result
result, err = r.setDefaults(multiClusterHub)
if result != nil {
return *result, err
}
// Read image overrides
// First, attempt to read image overrides from environmental variables
imageOverrides := imageoverrides.GetImageOverrides()
if len(imageOverrides) == 0 {
// If imageoverrides are not set from environmental variables, read from manifest
reqLogger.Info("Image Overrides not set from environment variables. Checking for overrides in manifest")
imageOverrides, err = manifest.GetImageOverrides(multiClusterHub)
if err != nil {
reqLogger.Error(err, "Could not get map of image overrides")
return reconcile.Result{}, err
}
}
if imageRepo := utils.GetImageRepository(multiClusterHub); imageRepo != "" {
reqLogger.Info(fmt.Sprintf("Overriding Image Repository from annotation 'mch-imageRepository': %s", imageRepo))
imageOverrides = utils.OverrideImageRepository(imageOverrides, imageRepo)
}
// Check for developer overrides
if imageOverridesConfigmap := utils.GetImageOverridesConfigmap(multiClusterHub); imageOverridesConfigmap != "" {
imageOverrides, err = r.OverrideImagesFromConfigmap(imageOverrides, multiClusterHub.GetNamespace(), imageOverridesConfigmap)
if err != nil {
reqLogger.Error(err, fmt.Sprintf("Could not find image override configmap: %s/%s", multiClusterHub.GetNamespace(), imageOverridesConfigmap))
return reconcile.Result{}, err
}
}
r.CacheSpec.ImageOverrides = imageOverrides
r.CacheSpec.ManifestVersion = version.Version
r.CacheSpec.ImageRepository = utils.GetImageRepository(multiClusterHub)
r.CacheSpec.ImageOverridesCM = utils.GetImageOverridesConfigmap(multiClusterHub)
err = r.maintainImageManifestConfigmap(multiClusterHub)
if err != nil {
reqLogger.Error(err, "Error storing image manifests in configmap")
return reconcile.Result{}, err
}
CustomUpgradeRequired, err := r.CustomSelfMgmtHubUpgradeRequired(multiClusterHub)
if err != nil {
reqLogger.Error(err, "Error determining if upgrade specific logic is required")
return reconcile.Result{}, err
}
if CustomUpgradeRequired {
result, err = r.BeginEnsuringHubIsUpgradeable(multiClusterHub)
if err != nil {
log.Info(fmt.Sprintf("Error starting to ensure local-cluster hub is upgradeable: %s", err.Error()))
return reconcile.Result{RequeueAfter: resyncPeriod}, nil
}
}
// Add installer labels to Helm-owned deployments
myHelmReleases := getAppSubOwnedHelmReleases(allHRs, getAppsubs(multiClusterHub))
myHRDeployments := getHelmReleaseOwnedDeployments(allDeploys, myHelmReleases)
if err := r.labelDeployments(multiClusterHub, myHRDeployments); err != nil {
return reconcile.Result{}, nil
}
// Do not reconcile objects if this instance of mch is labeled "paused"
updatePausedCondition(multiClusterHub)
if utils.IsPaused(multiClusterHub) {
reqLogger.Info("MultiClusterHub reconciliation is paused. Nothing more to do.")
return reconcile.Result{}, nil
}
result, err = r.ensureSubscriptionOperatorIsRunning(multiClusterHub, allDeploys)
if result != nil {
return *result, err
}
// Render CRD templates
err = r.installCRDs(reqLogger, multiClusterHub)
if err != nil {
return reconcile.Result{}, err
}
if utils.ProxyEnvVarsAreSet() {
log.Info(fmt.Sprintf("Proxy configuration environment variables are set. HTTP_PROXY: %s, HTTPS_PROXY: %s, NO_PROXY: %s", os.Getenv("HTTP_PROXY"), os.Getenv("HTTPS_PROXY"), os.Getenv("NO_PROXY")))
}
result, err = r.ensureDeployment(multiClusterHub, helmrepo.Deployment(multiClusterHub, r.CacheSpec.ImageOverrides))
if result != nil {
return *result, err
}
result, err = r.ensureService(multiClusterHub, helmrepo.Service(multiClusterHub))
if result != nil {
return *result, err
}
result, err = r.ensureChannel(multiClusterHub, channel.Channel(multiClusterHub))
if result != nil {
return *result, err
}
result, err = r.ingressDomain(multiClusterHub)
if result != nil {
return *result, err
}
//Render the templates with a specified CR
renderer := rendering.NewRenderer(multiClusterHub)
toDeploy, err := renderer.Render(r.client)
if err != nil {
reqLogger.Error(err, "Failed to render MultiClusterHub templates")
return reconcile.Result{}, err
}
//Deploy the resources
for _, res := range toDeploy {
if res.GetNamespace() == multiClusterHub.Namespace {
if err := controllerutil.SetControllerReference(multiClusterHub, res, r.scheme); err != nil {
reqLogger.Error(err, "Failed to set controller reference")
}
}
err, ok := deploying.Deploy(r.client, res)
if err != nil {
reqLogger.Error(err, fmt.Sprintf("Failed to deploy %s %s/%s", res.GetKind(), multiClusterHub.Namespace, res.GetName()))
return reconcile.Result{}, err
}
if ok {
condition := NewHubCondition(operatorsv1.Progressing, metav1.ConditionTrue, NewComponentReason, "Created new resource")
SetHubCondition(&multiClusterHub.Status, *condition)
}
}
result, err = r.ensureDeployment(multiClusterHub, foundation.WebhookDeployment(multiClusterHub, r.CacheSpec.ImageOverrides))
if result != nil {
return *result, err
}
result, err = r.ensureService(multiClusterHub, foundation.WebhookService(multiClusterHub))
if result != nil {
return *result, err
}
// Wait for ocm-webhook to be fully available before applying rest of subscriptions
if !(multiClusterHub.Status.Components["ocm-webhook"].Type == "Available" && multiClusterHub.Status.Components["ocm-webhook"].Status == metav1.ConditionTrue) {
reqLogger.Info(fmt.Sprintf("Waiting for component 'ocm-webhook' to be available"))
return reconcile.Result{RequeueAfter: resyncPeriod}, nil
}
// Install the rest of the subscriptions in no particular order
result, err = r.ensureSubscription(multiClusterHub, subscription.ManagementIngress(multiClusterHub, r.CacheSpec.ImageOverrides, r.CacheSpec.IngressDomain))
if result != nil {
return *result, err
}
result, err = r.ensureSubscription(multiClusterHub, subscription.ApplicationUI(multiClusterHub, r.CacheSpec.ImageOverrides))
if result != nil {
return *result, err
}
result, err = r.ensureSubscription(multiClusterHub, subscription.Console(multiClusterHub, r.CacheSpec.ImageOverrides, r.CacheSpec.IngressDomain))
if result != nil {
return *result, err
}
result, err = r.ensureSubscription(multiClusterHub, subscription.Insights(multiClusterHub, r.CacheSpec.ImageOverrides, r.CacheSpec.IngressDomain))
if result != nil {
return *result, err
}
result, err = r.ensureSubscription(multiClusterHub, subscription.Discovery(multiClusterHub, r.CacheSpec.ImageOverrides))
if result != nil {
return *result, err
}
result, err = r.ensureSubscription(multiClusterHub, subscription.GRC(multiClusterHub, r.CacheSpec.ImageOverrides))
if result != nil {
return *result, err
}
result, err = r.ensureSubscription(multiClusterHub, subscription.KUIWebTerminal(multiClusterHub, r.CacheSpec.ImageOverrides, r.CacheSpec.IngressDomain))
if result != nil {
return *result, err
}
result, err = r.ensureSubscription(multiClusterHub, subscription.ClusterLifecycle(multiClusterHub, r.CacheSpec.ImageOverrides))
if result != nil {
return *result, err
}
result, err = r.ensureSubscription(multiClusterHub, subscription.Search(multiClusterHub, r.CacheSpec.ImageOverrides))
if result != nil {
return *result, err
}
result, err = r.ensureSubscription(multiClusterHub, subscription.AssistedService(multiClusterHub, r.CacheSpec.ImageOverrides))
if result != nil {
return *result, err
}
//OCM proxy server deployment
result, err = r.ensureDeployment(multiClusterHub, foundation.OCMProxyServerDeployment(multiClusterHub, r.CacheSpec.ImageOverrides))
if result != nil {
return *result, err
}
//OCM proxy server service
result, err = r.ensureService(multiClusterHub, foundation.OCMProxyServerService(multiClusterHub))
if result != nil {
return *result, err
}
// OCM proxy apiService
result, err = r.ensureAPIService(multiClusterHub, foundation.OCMProxyAPIService(multiClusterHub))
if result != nil {
return *result, err
}
// OCM clusterView v1 apiService
result, err = r.ensureAPIService(multiClusterHub, foundation.OCMClusterViewV1APIService(multiClusterHub))
if result != nil {
return *result, err
}
// OCM clusterView v1alpha1 apiService
result, err = r.ensureAPIService(multiClusterHub, foundation.OCMClusterViewV1alpha1APIService(multiClusterHub))
if result != nil {
return *result, err
}
//OCM controller deployment
result, err = r.ensureDeployment(multiClusterHub, foundation.OCMControllerDeployment(multiClusterHub, r.CacheSpec.ImageOverrides))
if result != nil {
return *result, err
}
result, err = r.ensureUnstructuredResource(multiClusterHub, foundation.ClusterManager(multiClusterHub, r.CacheSpec.ImageOverrides))
if result != nil {
return *result, err
}
if !multiClusterHub.Spec.DisableHubSelfManagement {
result, err = r.ensureHubIsImported(multiClusterHub)
if result != nil {
return *result, err
}
} else {
result, err = r.ensureHubIsExported(multiClusterHub)
if result != nil {
return *result, err
}
}
// Cleanup unused resources once components up-to-date
if r.ComponentsAreRunning(multiClusterHub) {
result, err = r.ensureRemovalsGone(multiClusterHub)
if result != nil {
return *result, err
}
}
return retQueue, retError
}
// setDefaults updates MultiClusterHub resource with proper defaults
func (r *ReconcileMultiClusterHub) setDefaults(m *operatorsv1.MultiClusterHub) (*reconcile.Result, error) {
if utils.MchIsValid(m) {
return nil, nil
}
log.Info("MultiClusterHub is Invalid. Updating with proper defaults")
if len(m.Spec.Ingress.SSLCiphers) == 0 {
m.Spec.Ingress.SSLCiphers = utils.DefaultSSLCiphers
}
if !utils.AvailabilityConfigIsValid(m.Spec.AvailabilityConfig) {
m.Spec.AvailabilityConfig = operatorsv1.HAHigh
}
// Apply defaults to server
err := r.client.Update(context.TODO(), m)
if err != nil {
log.Error(err, "Failed to update MultiClusterHub", "MultiClusterHub.Namespace", m.Namespace, "MultiClusterHub.Name", m.Name)
return &reconcile.Result{}, err
}
log.Info("MultiClusterHub successfully updated")
return &reconcile.Result{Requeue: true}, nil
}
// ingressDomain is discovered from Openshift cluster configuration resources
func (r *ReconcileMultiClusterHub) ingressDomain(m *operatorsv1.MultiClusterHub) (*reconcile.Result, error) {
if r.CacheSpec.IngressDomain != "" {
return nil, nil
}
ingress := &netv1.Ingress{}
err := r.client.Get(context.TODO(), types.NamespacedName{
Name: "cluster",
}, ingress)
// Don't fail on a unit test (Fake client won't find "cluster" Ingress)
if err != nil && !utils.IsUnitTest() {
log.Error(err, "Failed to get Ingress")
return &reconcile.Result{}, err
}
r.CacheSpec.IngressDomain = ingress.Spec.Domain
return nil, nil
}
func (r *ReconcileMultiClusterHub) finalizeHub(reqLogger logr.Logger, m *operatorsv1.MultiClusterHub) error {
if _, err := r.ensureHubIsExported(m); err != nil {
return err
}
if err := r.cleanupAppSubscriptions(reqLogger, m); err != nil {
return err
}
if err := r.cleanupFoundation(reqLogger, m); err != nil {
return err
}
if err := r.cleanupHiveConfigs(reqLogger, m); err != nil {
return err
}
if err := r.cleanupAPIServices(reqLogger, m); err != nil {
return err
}
if err := r.cleanupClusterRoles(reqLogger, m); err != nil {
return err
}
if err := r.cleanupClusterRoleBindings(reqLogger, m); err != nil {
return err
}
if err := r.cleanupMutatingWebhooks(reqLogger, m); err != nil {
return err
}
if err := r.cleanupValidatingWebhooks(reqLogger, m); err != nil {
return err
}
if err := r.cleanupCRDs(reqLogger, m); err != nil {
return err
}
if err := r.cleanupClusterManagers(reqLogger, m); err != nil {
return err
}
if m.Spec.SeparateCertificateManagement {
if err := r.cleanupPullSecret(reqLogger, m); err != nil {
return err
}
}
reqLogger.Info("Successfully finalized multiClusterHub")
return nil
}
func (r *ReconcileMultiClusterHub) addFinalizer(reqLogger logr.Logger, m *operatorsv1.MultiClusterHub) error {
reqLogger.Info("Adding Finalizer for the multiClusterHub")
m.SetFinalizers(append(m.GetFinalizers(), hubFinalizer))
// Update CR
err := r.client.Update(context.TODO(), m)
if err != nil {
reqLogger.Error(err, "Failed to update MultiClusterHub with finalizer")
return err
}
return nil
}
func (r *ReconcileMultiClusterHub) installCRDs(reqLogger logr.Logger, m *operatorsv1.MultiClusterHub) error {
crdRenderer, err := rendering.NewCRDRenderer(m)
if err != nil {
condition := NewHubCondition(operatorsv1.Progressing, metav1.ConditionFalse, ResourceRenderReason, fmt.Sprintf("Error creating CRD renderer: %s", err.Error()))
SetHubCondition(&m.Status, *condition)
return fmt.Errorf("failed to setup CRD templates: %w", err)
}
crdResources, errs := crdRenderer.Render()
if errs != nil && len(errs) > 0 {
message := mergeErrors(errs)
condition := NewHubCondition(operatorsv1.Progressing, metav1.ConditionFalse, ResourceRenderReason, fmt.Sprintf("Error rendering CRD templates: %s", message))
SetHubCondition(&m.Status, *condition)
return fmt.Errorf("failed to render CRD templates: %s", message)
}
for _, crd := range crdResources {
err, ok := deploying.Deploy(r.client, crd)
if err != nil {
message := fmt.Sprintf("Failed to deploy %s %s", crd.GetKind(), crd.GetName())
reqLogger.Error(err, message)
condition := NewHubCondition(operatorsv1.Progressing, metav1.ConditionFalse, DeployFailedReason, message)
SetHubCondition(&m.Status, *condition)
return err
}
if ok {
condition := NewHubCondition(operatorsv1.Progressing, metav1.ConditionTrue, NewComponentReason, "Created new resource")
SetHubCondition(&m.Status, *condition)
}
}
return nil
}
func updatePausedCondition(m *operatorsv1.MultiClusterHub) {
c := GetHubCondition(m.Status, operatorsv1.Progressing)
if utils.IsPaused(m) {
// Pause condition needs to go on
if c == nil || c.Reason != PausedReason {
condition := NewHubCondition(operatorsv1.Progressing, metav1.ConditionUnknown, PausedReason, "Multiclusterhub is paused")
SetHubCondition(&m.Status, *condition)
}
} else {
// Pause condition needs to come off
if c != nil && c.Reason == PausedReason {
condition := NewHubCondition(operatorsv1.Progressing, metav1.ConditionTrue, ResumedReason, "Multiclusterhub is resumed")
SetHubCondition(&m.Status, *condition)
}
}
}
func contains(list []string, s string) bool {
for _, v := range list {
if v == s {
return true
}
}
return false
}
func remove(list []string, s string) []string {
for i, v := range list {
if v == s {
list = append(list[:i], list[i+1:]...)
}
}
return list
}
// mergeErrors combines errors into a single string
func mergeErrors(errs []error) string {
errStrings := []string{}
for _, e := range errs {
errStrings = append(errStrings, e.Error())
}
return strings.Join(errStrings, " ; ")
}
| [
"\"HTTP_PROXY\"",
"\"HTTPS_PROXY\"",
"\"NO_PROXY\""
]
| []
| [
"HTTP_PROXY",
"HTTPS_PROXY",
"NO_PROXY"
]
| [] | ["HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY"] | go | 3 | 0 | |
nevergrad/optimization/test_callbacks.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import time
from pathlib import Path
import logging
import os
import numpy as np
import nevergrad as ng
import nevergrad.common.typing as tp
from . import optimizerlib
from . import callbacks
# pylint: disable=unused-argument
def _func(x: tp.Any, y: tp.Any, blublu: str, array: tp.Any, multiobjective: bool = False) -> tp.Loss:
return 12 if not multiobjective else [12, 12]
def test_log_parameters(tmp_path: Path) -> None:
filepath = tmp_path / "logs.txt"
cases = [0, np.int_(1), np.float_(2.0), np.nan, float("inf"), np.inf]
instrum = ng.p.Instrumentation(
ng.ops.mutations.Translation()(ng.p.Array(shape=(1,))),
ng.p.Scalar(),
blublu=ng.p.Choice(cases),
array=ng.p.Array(shape=(3, 2)),
)
optimizer = optimizerlib.NoisyOnePlusOne(parametrization=instrum, budget=32)
optimizer.register_callback("tell", ng.callbacks.ParametersLogger(filepath, append=False))
optimizer.minimize(_func, verbosity=2)
# pickling
logger = callbacks.ParametersLogger(filepath)
logs = logger.load_flattened()
assert len(logs) == 32
assert isinstance(logs[-1]["1"], float)
assert len(logs[-1]) == 32
logs = logger.load_flattened(max_list_elements=2)
assert len(logs[-1]) == 28
# deletion
logger = callbacks.ParametersLogger(filepath, append=False)
assert not logger.load()
def test_multiobjective_log_parameters(tmp_path: Path) -> None:
filepath = tmp_path / "logs.txt"
instrum = ng.p.Instrumentation(
None, 2.0, blublu="blublu", array=ng.p.Array(shape=(3, 2)), multiobjective=True
)
optimizer = optimizerlib.OnePlusOne(parametrization=instrum, budget=2)
optimizer.register_callback("tell", ng.callbacks.ParametersLogger(filepath, append=False))
optimizer.minimize(_func, verbosity=2)
# pickling
logger = callbacks.ParametersLogger(filepath)
logs = logger.load_flattened()
assert len(logs) == 2
def test_chaining_log_parameters(tmp_path: Path) -> None:
filepath = tmp_path / "logs.txt"
params = ng.p.Instrumentation(
None, 2.0, blublu="blublu", array=ng.p.Array(shape=(3, 2)), multiobjective=False
)
zmethods = ["CauchyLHSSearch", "DE", "CMA"]
ztmp1 = [ng.optimizers.registry[zmet] for zmet in zmethods]
optmodel = ng.families.Chaining(ztmp1, [50, 50]) #
optim = optmodel(parametrization=params, budget=100, num_workers=3)
logger = ng.callbacks.ParametersLogger(filepath)
optim.register_callback("tell", logger)
optim.minimize(_func, verbosity=2)
# read
logger = callbacks.ParametersLogger(filepath)
logs = logger.load_flattened()
assert len(logs) == 100
def test_dump_callback(tmp_path: Path) -> None:
filepath = tmp_path / "pickle.pkl"
optimizer = optimizerlib.OnePlusOne(parametrization=2, budget=32)
optimizer.register_callback("tell", ng.callbacks.OptimizerDump(filepath))
cand = optimizer.ask()
assert not filepath.exists()
optimizer.tell(cand, 0)
assert filepath.exists()
def test_progressbar_dump(tmp_path: Path) -> None:
filepath = tmp_path / "pickle.pkl"
optimizer = optimizerlib.OnePlusOne(parametrization=2, budget=32)
optimizer.register_callback("tell", ng.callbacks.ProgressBar())
for _ in range(8):
cand = optimizer.ask()
optimizer.tell(cand, 0)
optimizer.dump(filepath)
# should keep working after dump
cand = optimizer.ask()
optimizer.tell(cand, 0)
# and be reloadable
optimizer = optimizerlib.OnePlusOne.load(filepath)
for _ in range(12):
cand = optimizer.ask()
optimizer.tell(cand, 0)
class _EarlyStoppingTestee:
def __init__(self) -> None:
self.num_calls = 0
def __call__(self, *args, **kwds) -> float:
self.num_calls += 1
return np.random.rand()
def test_early_stopping() -> None:
instrum = ng.p.Instrumentation(None, 2.0, blublu="blublu", array=ng.p.Array(shape=(3, 2)))
func = _EarlyStoppingTestee()
optimizer = optimizerlib.OnePlusOne(parametrization=instrum, budget=100)
early_stopping = ng.callbacks.EarlyStopping(lambda opt: opt.num_ask > 3)
optimizer.register_callback("ask", early_stopping)
optimizer.register_callback("ask", ng.callbacks.EarlyStopping.timer(100)) # should not get triggered
optimizer.minimize(func, verbosity=2)
# num_ask is set at the end of ask, so the callback sees the old value.
assert func.num_calls == 4
# below functions are included in the docstring of EarlyStopping
assert optimizer.current_bests["minimum"].mean < 12
assert optimizer.recommend().loss < 12 # type: ignore
def test_duration_criterion() -> None:
optim = optimizerlib.OnePlusOne(2, budget=100)
crit = ng.callbacks._DurationCriterion(0.01)
assert not crit(optim)
assert not crit(optim)
assert not crit(optim)
time.sleep(0.01)
assert crit(optim)
def test_optimization_logger(caplog) -> None:
instrum = ng.p.Instrumentation(
None, 2.0, blublu="blublu", array=ng.p.Array(shape=(3, 2)), multiobjective=False
)
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
logger = logging.getLogger(__name__)
optimizer = optimizerlib.OnePlusOne(parametrization=instrum, budget=3)
optimizer.register_callback(
"tell",
callbacks.OptimizationLogger(
logger=logger, log_level=logging.INFO, log_interval_tells=10, log_interval_seconds=0.1
),
)
with caplog.at_level(logging.INFO):
optimizer.minimize(_func, verbosity=2)
assert (
"After 0, recommendation is Instrumentation(Tuple(None,2.0),Dict(array=Array{(3,2)},blublu=blublu,multiobjective=False))"
in caplog.text
)
def test_optimization_logger_MOO(caplog) -> None:
instrum = ng.p.Instrumentation(
None, 2.0, blublu="blublu", array=ng.p.Array(shape=(3, 2)), multiobjective=True
)
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
logger = logging.getLogger(__name__)
optimizer = optimizerlib.OnePlusOne(parametrization=instrum, budget=3)
optimizer.register_callback(
"tell",
callbacks.OptimizationLogger(
logger=logger, log_level=logging.INFO, log_interval_tells=10, log_interval_seconds=0.1
),
)
with caplog.at_level(logging.INFO):
optimizer.minimize(_func, verbosity=2)
assert (
"After 0, the respective minimum loss for each objective in the pareto front is [12. 12.]"
in caplog.text
)
| []
| []
| [
"LOGLEVEL"
]
| [] | ["LOGLEVEL"] | python | 1 | 0 | |
shopping-cart-pandas.py | # shopping_cart_pandas.py
from __future__ import print_function
import datetime
import os
import pandas as pd
import csv
from dotenv import load_dotenv
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
import functools
now = datetime.datetime.now()
pd.options.display.float_format = '${:,.2f}'.format
# load_dotenv()
# api_key = os.getenv("SENDGRID_API_KEY", "Oops, please set env var called SENDGRID_API_KEY")
# sendgrid_template = os.getenv("SENDGRID_TEMPLATE", "Oops, please set env var called SENDGRID_TEMPLATE" )
# my_address = os.getenv("MY_EMAIL_ADDRESS", "Oops, please set env var called MY_EMAIL_ADDRESS")
# products = [
# {"id":1, "name": "Chocolate Sandwich Cookies", "department": "snacks", "aisle": "cookies cakes", "price": 3.50},
# {"id":2, "name": "All-Seasons Salt", "department": "pantry", "aisle": "spices seasonings", "price": 4.99},
# {"id":3, "name": "Robust Golden Unsweetened Oolong Tea", "department": "beverages", "aisle": "tea", "price": 2.49},
# {"id":4, "name": "Smart Ones Classic Favorites Mini Rigatoni With Vodka Cream Sauce", "department": "frozen", "aisle": "frozen meals", "price": 6.99},
# {"id":5, "name": "Green Chile Anytime Sauce", "department": "pantry", "aisle": "marinades meat preparation", "price": 7.99},
# {"id":6, "name": "Dry Nose Oil", "department": "personal care", "aisle": "cold flu allergy", "price": 21.99},
# {"id":7, "name": "Pure Coconut Water With Orange", "department": "beverages", "aisle": "juice nectars", "price": 3.50},
# {"id":8, "name": "Cut Russet Potatoes Steam N' Mash", "department": "frozen", "aisle": "frozen produce", "price": 4.25},
# {"id":9, "name": "Light Strawberry Blueberry Yogurt", "department": "dairy eggs", "aisle": "yogurt", "price": 6.50},
# {"id":10, "name": "Sparkling Orange Juice & Prickly Pear Beverage", "department": "beverages", "aisle": "water seltzer sparkling water", "price": 2.99},
# {"id":11, "name": "Peach Mango Juice", "department": "beverages", "aisle": "refrigerated", "price": 1.99},
# {"id":12, "name": "Chocolate Fudge Layer Cake", "department": "frozen", "aisle": "frozen dessert", "price": 18.50},
# {"id":13, "name": "Saline Nasal Mist", "department": "personal care", "aisle": "cold flu allergy", "price": 16.00},
# {"id":14, "name": "Fresh Scent Dishwasher Cleaner", "department": "household", "aisle": "dish detergents", "price": 4.99},
# {"id":15, "name": "Overnight Diapers Size 6", "department": "babies", "aisle": "diapers wipes", "price": 25.50},
# {"id":16, "name": "Mint Chocolate Flavored Syrup", "department": "snacks", "aisle": "ice cream toppings", "price": 4.50},
# {"id":17, "name": "Rendered Duck Fat", "department": "meat seafood", "aisle": "poultry counter", "price": 9.99},
# {"id":18, "name": "Pizza for One Suprema Frozen Pizza", "department": "frozen", "aisle": "frozen pizza", "price": 12.50},
# {"id":19, "name": "Gluten Free Quinoa Three Cheese & Mushroom Blend", "department": "dry goods pasta", "aisle": "grains rice dried goods", "price": 3.99},
# {"id":20, "name": "Pomegranate Cranberry & Aloe Vera Enrich Drink", "department": "beverages", "aisle": "juice nectars", "price": 4.25}
# ] # based on data from Instacart: https://www.instacart.com/datasets/grocery-shopping-2017
# df = pd.DataFrame(products)
# df.to_csv('product_list.csv')
product_filepath = os.path.join(os.path.dirname(__file__), "product_list.csv")
product_filename = "product_list.csv"
products = pd.read_csv(product_filename)
def to_usd(my_price):
return f"${my_price:,.2f}" #> $12,000.71
#User inputs
total_price = 0
product_ids = []
valid_ids = products["id"]
# print(valid_ids)
while True:
product_id = input("Please input a product identifier, or enter DONE when finished: ")
if product_id == "DONE":
break
elif int(product_id) in valid_ids:
product_ids.append(int(product_id))
else:
print("Identifier not recognized, please try again.")
idx = []
for i in product_ids:
idx.append(i - 1)
p2 = products.iloc[idx].rename(columns={'id': 'id','name': 'Name','department': 'department','aisle': 'aisle','price': 'Price'}).reset_index()
#Program Outputs
print("---------------------------------")
print("THANK YOU FOR SHOPPING AT NOOK'S CRANNY")
print("www.nooks.com")
print("---------------------------------")
print("CHECKOUT AT: " + str(now))
print("---------------------------------")
print("SELECTED PRODUCTS:")
print((p2[['Name', 'Price']]).to_string(index=False, header=True, justify={'left'}))
print("---------------------------------")
subtotal_p = p2['Price'].sum()
stotal = to_usd(subtotal_p)
tax = 0.0875
tax_price = float(subtotal_p) * tax
tprice = to_usd(tax_price)
total_price = (float(subtotal_p) * tax) + float(subtotal_p)
print("SUBTOTAL: " + str(stotal))
print("TAX (8.75%):" + str(tprice))
def final_total(total_price, tax):
return (total_price * tax) + total_price
f_total = to_usd(total_price)
print(f"TOTAL: {f_total}")
print("---------------------------------")
print("THANK YOU, PLEASE COME AGAIN")
print("---------------------------------") | []
| []
| [
"MY_EMAIL_ADDRESS",
"SENDGRID_API_KEY",
"SENDGRID_TEMPLATE"
]
| [] | ["MY_EMAIL_ADDRESS", "SENDGRID_API_KEY", "SENDGRID_TEMPLATE"] | python | 3 | 0 | |
apps/microtvm/reference-vm/base-box-tool.py | #!/usr/bin/env python3
# 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 argparse
from ast import arg
import copy
import json
import logging
import os
import re
import shlex
import shutil
import subprocess
import sys
import pathlib
_LOG = logging.getLogger(__name__)
THIS_DIR = os.path.realpath(os.path.dirname(__file__) or ".")
# List of vagrant providers supported by this tool
ALL_PROVIDERS = (
"parallels",
"virtualbox",
"vmware_desktop",
)
# List of supported electronics platforms. Each must correspond
# to a sub-directory of this directory.
ALL_PLATFORMS = (
"arduino",
"zephyr",
)
# Extra scripts required to execute on provisioning
# in [platform]/base-box/base_box_provision.sh
EXTRA_SCRIPTS = {
"arduino": (),
"zephyr": (
"docker/install/ubuntu_init_zephyr_project.sh",
"docker/install/ubuntu_install_zephyr_sdk.sh",
),
}
PACKER_FILE_NAME = "packer.json"
# List of identifying strings for microTVM boards for testing.
with open(pathlib.Path(THIS_DIR) / ".." / "zephyr" / "template_project" / "boards.json") as f:
zephyr_boards = json.load(f)
with open(pathlib.Path(THIS_DIR) / ".." / "arduino" / "template_project" / "boards.json") as f:
arduino_boards = json.load(f)
ALL_MICROTVM_BOARDS = {
"arduino": arduino_boards.keys(),
"zephyr": zephyr_boards.keys(),
}
def parse_virtualbox_devices():
output = subprocess.check_output(["VBoxManage", "list", "usbhost"], encoding="utf-8")
devices = []
current_dev = {}
for line in output.split("\n"):
if not line.strip():
if current_dev:
if "VendorId" in current_dev and "ProductId" in current_dev:
devices.append(current_dev)
current_dev = {}
continue
key, value = line.split(":", 1)
value = value.lstrip(" ")
current_dev[key] = value
if current_dev:
devices.append(current_dev)
return devices
VIRTUALBOX_USB_DEVICE_RE = (
"USBAttachVendorId[0-9]+=0x([0-9a-z]{4})\n" + "USBAttachProductId[0-9]+=0x([0-9a-z]{4})"
)
def parse_virtualbox_attached_usb_devices(vm_uuid):
output = subprocess.check_output(
["VBoxManage", "showvminfo", "--machinereadable", vm_uuid], encoding="utf-8"
)
r = re.compile(VIRTUALBOX_USB_DEVICE_RE)
attached_usb_devices = r.findall(output, re.MULTILINE)
# List of couples (VendorId, ProductId) for all attached USB devices
return attached_usb_devices
VIRTUALBOX_VID_PID_RE = re.compile(r"0x([0-9A-Fa-f]{4}).*")
def attach_virtualbox(vm_uuid, vid_hex=None, pid_hex=None, serial=None):
usb_devices = parse_virtualbox_devices()
for dev in usb_devices:
m = VIRTUALBOX_VID_PID_RE.match(dev["VendorId"])
if not m:
_LOG.warning("Malformed VendorId: %s", dev["VendorId"])
continue
dev_vid_hex = m.group(1).lower()
m = VIRTUALBOX_VID_PID_RE.match(dev["ProductId"])
if not m:
_LOG.warning("Malformed ProductId: %s", dev["ProductId"])
continue
dev_pid_hex = m.group(1).lower()
if (
vid_hex == dev_vid_hex
and pid_hex == dev_pid_hex
and (serial is None or serial == dev["SerialNumber"])
):
attached_devices = parse_virtualbox_attached_usb_devices(vm_uuid)
for vid, pid in parse_virtualbox_attached_usb_devices(vm_uuid):
if vid_hex == vid and pid_hex == pid:
print(f"USB dev {vid_hex}:{pid_hex} already attached. Skipping attach.")
return
rule_args = [
"VBoxManage",
"usbfilter",
"add",
"0",
"--action",
"hold",
"--name",
"test device",
"--target",
vm_uuid,
"--vendorid",
vid_hex,
"--productid",
pid_hex,
]
if serial is not None:
rule_args.extend(["--serialnumber", serial])
subprocess.check_call(rule_args)
subprocess.check_call(["VBoxManage", "controlvm", vm_uuid, "usbattach", dev["UUID"]])
return
raise Exception(
f"Device with vid={vid_hex}, pid={pid_hex}, serial={serial!r} not found:\n{usb_devices!r}"
)
def attach_parallels(uuid, vid_hex=None, pid_hex=None, serial=None):
usb_devices = json.loads(
subprocess.check_output(["prlsrvctl", "usb", "list", "-j"], encoding="utf-8")
)
for dev in usb_devices:
_, dev_vid_hex, dev_pid_hex, _, _, dev_serial = dev["System name"].split("|")
dev_vid_hex = dev_vid_hex.lower()
dev_pid_hex = dev_pid_hex.lower()
if (
vid_hex == dev_vid_hex
and pid_hex == dev_pid_hex
and (serial is None or serial == dev_serial)
):
subprocess.check_call(["prlsrvctl", "usb", "set", dev["Name"], uuid])
if "Used-By-Vm-Name" in dev:
subprocess.check_call(
["prlctl", "set", dev["Used-By-Vm-Name"], "--device-disconnect", dev["Name"]]
)
subprocess.check_call(["prlctl", "set", uuid, "--device-connect", dev["Name"]])
return
raise Exception(
f"Device with vid={vid_hex}, pid={pid_hex}, serial={serial!r} not found:\n{usb_devices!r}"
)
def attach_vmware(uuid, vid_hex=None, pid_hex=None, serial=None):
print("NOTE: vmware doesn't seem to support automatic attaching of devices :(")
print("The VMWare VM UUID is {uuid}")
print("Please attach the following usb device using the VMWare GUI:")
if vid_hex is not None:
print(f" - VID: {vid_hex}")
if pid_hex is not None:
print(f" - PID: {pid_hex}")
if serial is not None:
print(f" - Serial: {serial}")
if vid_hex is None and pid_hex is None and serial is None:
print(" - (no specifications given for USB device)")
print()
print("Press [Enter] when the USB device is attached")
input()
ATTACH_USB_DEVICE = {
"parallels": attach_parallels,
"virtualbox": attach_virtualbox,
"vmware_desktop": attach_vmware,
}
def generate_packer_config(platform, file_path, providers):
builders = []
provisioners = []
for provider_name in providers:
builders.append(
{
"name": f"{provider_name}",
"type": "vagrant",
"box_name": f"microtvm-base-{provider_name}",
"output_dir": f"output-packer-{provider_name}",
"communicator": "ssh",
"source_path": "generic/ubuntu1804",
"provider": provider_name,
"template": "Vagrantfile.packer-template",
}
)
repo_root = subprocess.check_output(
["git", "rev-parse", "--show-toplevel"], encoding="utf-8"
).strip()
for script in EXTRA_SCRIPTS[platform]:
script_path = os.path.join(repo_root, script)
filename = os.path.basename(script_path)
provisioners.append({"type": "file", "source": script_path, "destination": f"~/{filename}"})
provisioners.append(
{
"type": "shell",
"script": "base_box_setup.sh",
}
)
provisioners.append(
{
"type": "shell",
"script": "base_box_provision.sh",
}
)
with open(file_path, "w") as f:
json.dump(
{
"builders": builders,
"provisioners": provisioners,
},
f,
sort_keys=True,
indent=2,
)
def build_command(args):
generate_packer_config(
args.platform,
os.path.join(THIS_DIR, args.platform, "base-box", PACKER_FILE_NAME),
args.provider or ALL_PROVIDERS,
)
env = copy.copy(os.environ)
packer_args = ["packer", "build"]
env["PACKER_LOG"] = "1"
env["PACKER_LOG_PATH"] = "packer.log"
if args.debug_packer:
packer_args += ["-debug"]
packer_args += [PACKER_FILE_NAME]
subprocess.check_call(
packer_args, cwd=os.path.join(THIS_DIR, args.platform, "base-box"), env=env
)
REQUIRED_TEST_CONFIG_KEYS = {
"vid_hex": str,
"pid_hex": str,
}
VM_BOX_RE = re.compile(r'(.*\.vm\.box) = "(.*)"')
# Paths, relative to the platform box directory, which will not be copied to release-test dir.
SKIP_COPY_PATHS = [".vagrant", "base-box"]
def do_build_release_test_vm(
release_test_dir, user_box_dir: pathlib.Path, base_box_dir: pathlib.Path, provider_name
):
if os.path.exists(release_test_dir):
try:
subprocess.check_call(["vagrant", "destroy", "-f"], cwd=release_test_dir)
except subprocess.CalledProcessError:
_LOG.warning("vagrant destroy failed--removing dirtree anyhow", exc_info=True)
shutil.rmtree(release_test_dir)
for dirpath, _, filenames in os.walk(user_box_dir):
rel_path = os.path.relpath(dirpath, user_box_dir)
if any(
rel_path == scp or rel_path.startswith(f"{scp}{os.path.sep}") for scp in SKIP_COPY_PATHS
):
continue
dest_dir = os.path.join(release_test_dir, rel_path)
os.makedirs(dest_dir)
for filename in filenames:
shutil.copy2(os.path.join(dirpath, filename), os.path.join(dest_dir, filename))
release_test_vagrantfile = os.path.join(release_test_dir, "Vagrantfile")
with open(release_test_vagrantfile) as f:
lines = list(f)
found_box_line = False
with open(release_test_vagrantfile, "w") as f:
for line in lines:
m = VM_BOX_RE.match(line)
if not m:
f.write(line)
continue
box_package = os.path.join(
base_box_dir, f"output-packer-{provider_name}", "package.box"
)
box_relpath = os.path.relpath(box_package, release_test_dir)
f.write(f'{m.group(1)} = "{box_relpath}"\n')
found_box_line = True
if not found_box_line:
_LOG.error(
"testing provider %s: couldn't find config.box.vm = line in Vagrantfile; unable to test",
provider_name,
)
return False
# Delete the old box registered with Vagrant, which may lead to a falsely-passing release test.
remove_args = ["vagrant", "box", "remove", box_relpath]
return_code = subprocess.call(remove_args, cwd=release_test_dir)
assert return_code in (0, 1), f'{" ".join(remove_args)} returned exit code {return_code}'
subprocess.check_call(["vagrant", "up", f"--provider={provider_name}"], cwd=release_test_dir)
return True
def do_run_release_test(release_test_dir, platform, provider_name, test_config, test_device_serial):
with open(
os.path.join(release_test_dir, ".vagrant", "machines", "default", provider_name, "id")
) as f:
machine_uuid = f.read()
# Check if target is not QEMU
if test_config["vid_hex"] and test_config["pid_hex"]:
ATTACH_USB_DEVICE[provider_name](
machine_uuid,
vid_hex=test_config["vid_hex"],
pid_hex=test_config["pid_hex"],
serial=test_device_serial,
)
tvm_home = os.path.realpath(os.path.join(THIS_DIR, "..", "..", ".."))
def _quote_cmd(cmd):
return " ".join(shlex.quote(a) for a in cmd)
test_cmd = (
_quote_cmd(["cd", tvm_home])
+ " && "
+ _quote_cmd(
[
f"apps/microtvm/reference-vm/{platform}/base-box/base_box_test.sh",
test_config["microtvm_board"],
]
)
)
subprocess.check_call(["vagrant", "ssh", "-c", f"bash -ec '{test_cmd}'"], cwd=release_test_dir)
def test_command(args):
user_box_dir = pathlib.Path(THIS_DIR) / args.platform
base_box_dir = user_box_dir / "base-box"
boards_file = pathlib.Path(THIS_DIR) / ".." / args.platform / "template_project" / "boards.json"
with open(boards_file) as f:
test_config = json.load(f)
# select microTVM test config
microtvm_test_config = test_config[args.microtvm_board]
for key, expected_type in REQUIRED_TEST_CONFIG_KEYS.items():
assert key in microtvm_test_config and isinstance(
microtvm_test_config[key], expected_type
), f"Expected key {key} of type {expected_type} in {boards_file}: {test_config!r}"
microtvm_test_config["vid_hex"] = microtvm_test_config["vid_hex"].lower()
microtvm_test_config["pid_hex"] = microtvm_test_config["pid_hex"].lower()
microtvm_test_config["microtvm_board"] = args.microtvm_board
providers = args.provider
release_test_dir = os.path.join(THIS_DIR, f"release-test-{args.platform}")
if args.skip_build or args.skip_destroy:
assert (
len(providers) == 1
), "--skip-build and/or --skip-destroy was given, but >1 provider specified"
test_failed = False
for provider_name in providers:
try:
if not args.skip_build:
do_build_release_test_vm(
release_test_dir, user_box_dir, base_box_dir, provider_name
)
do_run_release_test(
release_test_dir,
args.platform,
provider_name,
microtvm_test_config,
args.test_device_serial,
)
except subprocess.CalledProcessError:
test_failed = True
sys.exit(
f"\n\nERROR: Provider '{provider_name}' failed the release test. "
"You can re-run it to reproduce the issue without building everything "
"again by passing the --skip-build and specifying only the provider that failed. "
"The VM is still running in case you want to connect it via SSH to "
"investigate further the issue, thus it's necessary to destroy it manually "
"to release the resources back to the host, like a USB device attached to the VM."
)
finally:
# if we reached out here do_run_release_test() succeeded, hence we can
# destroy the VM and release the resources back to the host if user haven't
# requested to not destroy it.
if not (args.skip_destroy or test_failed):
subprocess.check_call(["vagrant", "destroy", "-f"], cwd=release_test_dir)
shutil.rmtree(release_test_dir)
print(f'\n\nThe release tests passed on all specified providers: {", ".join(providers)}.')
def release_command(args):
if args.release_full_name:
vm_name = args.release_full_name
else:
vm_name = f"tlcpack/microtvm-{args.platform}-{args.platform_version}"
if not args.skip_creating_release_version:
subprocess.check_call(
[
"vagrant",
"cloud",
"version",
"create",
vm_name,
args.release_version,
]
)
if not args.release_version:
sys.exit(f"--release-version must be specified")
for provider_name in args.provider:
subprocess.check_call(
[
"vagrant",
"cloud",
"publish",
"-f",
vm_name,
args.release_version,
provider_name,
os.path.join(
THIS_DIR,
args.platform,
"base-box",
f"output-packer-{provider_name}/package.box",
),
]
)
def parse_args():
parser = argparse.ArgumentParser(
description="Automates building, testing, and releasing a base box"
)
subparsers = parser.add_subparsers(help="Action to perform.")
subparsers.required = True
subparsers.dest = "action"
parser.add_argument(
"--provider",
choices=ALL_PROVIDERS,
action="append",
required=True,
help="Name of the provider or providers to act on",
)
# "test" has special options for different platforms, and "build", "release" might
# in the future, so we'll add the platform argument to each one individually.
platform_help_str = "Platform to use (e.g. Arduino, Zephyr)"
# Options for build subcommand
parser_build = subparsers.add_parser("build", help="Build a base box.")
parser_build.set_defaults(func=build_command)
parser_build.add_argument("platform", help=platform_help_str, choices=ALL_PLATFORMS)
parser_build.add_argument(
"--debug-packer",
action="store_true",
help=("Run packer in debug mode, and write log to the base-box directory."),
)
# Options for test subcommand
parser_test = subparsers.add_parser("test", help="Test a base box before release.")
parser_test.set_defaults(func=test_command)
parser_test.add_argument(
"--skip-build",
action="store_true",
help=(
"If given, assume a box has already been built in the release-test subdirectory, "
"so use that box to execute the release test script. If the tests fail the VM used "
"for testing will be left running for further investigation and will need to be "
"destroyed manually. If all tests pass on all specified providers no VM is left running, "
"unless --skip-destroy is given too."
),
)
parser_test.add_argument(
"--skip-destroy",
action="store_true",
help=(
"Skip destroying the test VM even if all tests pass. Can only be used if a single "
"provider is specified. Default is to destroy the VM if all tests pass (and always "
"skip destroying it if a test fails)."
),
)
parser_test.add_argument(
"--test-device-serial",
help=(
"If given, attach the test device with this USB serial number. Corresponds to the "
"iSerial field from `lsusb -v` output."
),
)
parser_test_platform_subparsers = parser_test.add_subparsers(help=platform_help_str)
for platform in ALL_PLATFORMS:
platform_specific_parser = parser_test_platform_subparsers.add_parser(platform)
platform_specific_parser.set_defaults(platform=platform)
platform_specific_parser.add_argument(
"--microtvm-board",
choices=ALL_MICROTVM_BOARDS[platform],
required=True,
help="MicroTVM board used for testing.",
)
# Options for release subcommand
parser_release = subparsers.add_parser("release", help="Release base box to cloud.")
parser_release.set_defaults(func=release_command)
parser_release.add_argument("platform", help=platform_help_str, choices=ALL_PLATFORMS)
parser_release.add_argument(
"--release-version",
required=True,
help="Version to release, in the form 'x.y.z'. Must be specified with release.",
)
parser_release.add_argument(
"--skip-creating-release-version",
action="store_true",
help="Skip creating the version and just upload for this provider.",
)
parser_release.add_argument(
"--platform-version",
required=False,
help=(
"For Zephyr, the platform version to release, in the form 'x.y'. "
"For Arduino, the version of arduino-cli that's being used, in the form 'x.y.z'."
),
)
parser_release.add_argument(
"--release-full-name",
required=False,
type=str,
default=None,
help=(
"If set, it will use this as the full release name and version for the box. "
"If this set, it will ignore `--platform-version` and `--release-version`."
),
)
args = parser.parse_args()
if args.action == "release" and not args.release_full_name:
parser.error("--platform-version is requireed.")
return args
def main():
args = parse_args()
if os.path.sep in args.platform or not os.path.isdir(os.path.join(THIS_DIR, args.platform)):
sys.exit(f"<platform> must be a sub-direcotry of {THIS_DIR}; got {args.platform}")
args.func(args)
if __name__ == "__main__":
main()
| []
| []
| []
| [] | [] | python | 0 | 0 | |
lambda/lambda.py | from elasticsearch import Elasticsearch
import datetime
import os
cluster = os.environ['ENDPOINT'].split('/')[-1]
index_prefix = os.environ['INDEX']
keep = os.environ['KEEP']
earliest_to_keep = datetime.date.today() - datetime.timedelta(days=int(keep))
def main():
es = Elasticsearch([f'https://{cluster}:443'])
indexes = es.indices.get_alias(f'{index_prefix}-*')
earliest_to_keep_date = earliest_to_keep.strftime("%Y.%m.%d")
for i in sorted(indexes):
index_date = i.split('-')[-1]
if i.startswith(index_prefix) and index_date < earliest_to_keep_date:
print(f'Deleting index: {i}')
es.indices.delete(index=i, ignore=[400, 404])
def handler(event, context):
main()
if __name__ == "__main__":
main()
| []
| []
| [
"ENDPOINT",
"KEEP",
"INDEX"
]
| [] | ["ENDPOINT", "KEEP", "INDEX"] | python | 3 | 0 | |
pkg/docker_registry/api.go | package docker_registry
import (
"context"
"crypto/tls"
"fmt"
"math/rand"
"net/http"
"os"
"strings"
"time"
dockerReference "github.com/docker/distribution/reference"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/mutate"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/werf/logboek"
"github.com/werf/werf/pkg/docker_registry/container_registry_extensions"
"github.com/werf/werf/pkg/image"
)
type api struct {
InsecureRegistry bool
SkipTlsVerifyRegistry bool
}
type apiOptions struct {
InsecureRegistry bool
SkipTlsVerifyRegistry bool
}
func newAPI(options apiOptions) *api {
return &api{
InsecureRegistry: options.InsecureRegistry,
SkipTlsVerifyRegistry: options.SkipTlsVerifyRegistry,
}
}
func (api *api) Tags(ctx context.Context, reference string) ([]string, error) {
return api.tags(ctx, reference)
}
func (api *api) tags(_ context.Context, reference string, extraListOptions ...remote.Option) ([]string, error) {
tags, err := api.list(reference, extraListOptions...)
if err != nil {
if IsNameUnknownError(err) {
return []string{}, nil
}
return nil, err
}
return tags, nil
}
func (api *api) tagImage(reference, tag string) error {
ref, err := name.ParseReference(reference, api.parseReferenceOptions()...)
if err != nil {
return fmt.Errorf("parsing reference %q: %v", reference, err)
}
desc, err := remote.Get(ref, api.defaultRemoteOptions()...)
if err != nil {
return fmt.Errorf("getting reference %q: %v", reference, err)
}
dst := ref.Context().Tag(tag)
return remote.Tag(dst, desc, api.defaultRemoteOptions()...)
}
func (api *api) IsRepoImageExists(ctx context.Context, reference string) (bool, error) {
if imgInfo, err := api.TryGetRepoImage(ctx, reference); err != nil {
return false, err
} else {
return imgInfo != nil, nil
}
}
func (api *api) TryGetRepoImage(ctx context.Context, reference string) (*image.Info, error) {
if imgInfo, err := api.GetRepoImage(ctx, reference); err != nil {
if IsBlobUnknownError(err) || IsManifestUnknownError(err) || IsNameUnknownError(err) || IsHarbor404Error(err) {
// TODO: 1. auto reject images with manifest-unknown or blob-unknown errors
// TODO: 2. why TryGetRepoImage for rejected image records gives manifest-unknown errors?
// TODO: 3. make sure werf never ever creates rejected image records for name-unknown errors.
// TODO: 4. werf-cleanup should remove broken images
if os.Getenv("WERF_DOCKER_REGISTRY_DEBUG") == "1" {
logboek.Context(ctx).Error().LogF("WARNING: Got an error when inspecting repo image %q: %s\n", reference, err)
}
return nil, nil
}
return imgInfo, err
} else {
return imgInfo, nil
}
}
func (api *api) GetRepoImage(_ context.Context, reference string) (*image.Info, error) {
imageInfo, _, err := api.image(reference)
if err != nil {
return nil, err
}
digest, err := imageInfo.Digest()
if err != nil {
return nil, err
}
manifest, err := imageInfo.Manifest()
if err != nil {
return nil, err
}
configFile, err := imageInfo.ConfigFile()
if err != nil {
return nil, err
}
var totalSize int64
if layers, err := imageInfo.Layers(); err != nil {
return nil, err
} else {
for _, l := range layers {
if lSize, err := l.Size(); err != nil {
return nil, err
} else {
totalSize += lSize
}
}
}
referenceParts, err := api.ParseReferenceParts(reference)
if err != nil {
return nil, fmt.Errorf("unable to parse reference %q: %s", reference, err)
}
repoImage := &image.Info{
Name: reference,
Repository: strings.Join([]string{referenceParts.registry, referenceParts.repository}, "/"),
ID: manifest.Config.Digest.String(),
Tag: referenceParts.tag,
RepoDigest: digest.String(),
ParentID: configFile.Config.Image,
Labels: configFile.Config.Labels,
Size: totalSize,
}
repoImage.SetCreatedAtUnix(configFile.Created.Unix())
return repoImage, nil
}
func (api *api) list(reference string, extraListOptions ...remote.Option) ([]string, error) {
repo, err := name.NewRepository(reference, api.newRepositoryOptions()...)
if err != nil {
return nil, fmt.Errorf("parsing repo %q: %v", reference, err)
}
listOptions := append(
api.defaultRemoteOptions(),
extraListOptions...,
)
tags, err := remote.List(repo, listOptions...)
if err != nil {
return nil, fmt.Errorf("reading tags for %q: %v", repo, err)
}
return tags, nil
}
func (api *api) deleteImageByReference(reference string) error {
r, err := name.ParseReference(reference, api.parseReferenceOptions()...)
if err != nil {
return fmt.Errorf("parsing reference %q: %v", reference, err)
}
if err := remote.Delete(r, api.defaultRemoteOptions()...); err != nil {
return fmt.Errorf("deleting image %q: %v", r, err)
}
return nil
}
func (api *api) MutateAndPushImage(_ context.Context, sourceReference, destinationReference string, mutateConfigFunc func(cfg v1.Config) (v1.Config, error)) error {
img, _, err := api.image(sourceReference)
if err != nil {
return err
}
cfgFile, err := img.ConfigFile()
if err != nil {
return err
}
newConf, err := mutateConfigFunc(cfgFile.Config)
if err != nil {
return err
}
newImg, err := mutate.Config(img, newConf)
if err != nil {
return err
}
ref, err := name.ParseReference(destinationReference, api.parseReferenceOptions()...)
if err != nil {
return fmt.Errorf("parsing reference %q: %v", destinationReference, err)
}
if err = remote.Write(ref, newImg, remote.WithAuthFromKeychain(authn.DefaultKeychain)); err != nil {
return err
}
return nil
}
func (api *api) PushImage(ctx context.Context, reference string, opts *PushImageOptions) error {
retriesLimit := 5
attemptLoop:
for attempt := 1; attempt <= retriesLimit; attempt++ {
if err := api.pushImage(ctx, reference, opts); err != nil {
for _, substr := range []string{
"REDACTED: UNKNOWN",
"http2: server sent GOAWAY and closed the connection",
"http2: Transport received Server's graceful shutdown GOAWAY",
} {
if strings.Contains(err.Error(), substr) {
seconds := rand.Intn(5) + 1
msg := fmt.Sprintf("Retrying publishing in %d seconds (%d/%d) ...\n", seconds, attempt, retriesLimit)
logboek.Context(ctx).Warn().LogLn(msg)
time.Sleep(time.Duration(seconds) * time.Second)
continue attemptLoop
}
}
return err
}
return nil
}
return nil
}
func (api *api) pushImage(_ context.Context, reference string, opts *PushImageOptions) error {
ref, err := name.ParseReference(reference, api.parseReferenceOptions()...)
if err != nil {
return fmt.Errorf("parsing reference %q: %v", reference, err)
}
labels := map[string]string{}
if opts != nil {
labels = opts.Labels
}
img := container_registry_extensions.NewManifestOnlyImage(labels)
oldDefaultTransport := http.DefaultTransport
http.DefaultTransport = api.getHttpTransport()
err = remote.Write(ref, img, remote.WithAuthFromKeychain(authn.DefaultKeychain))
http.DefaultTransport = oldDefaultTransport
if err != nil {
return fmt.Errorf("write to the remote %s have failed: %s", ref.String(), err)
}
return nil
}
func (api *api) image(reference string) (v1.Image, name.Reference, error) {
ref, err := name.ParseReference(reference, api.parseReferenceOptions()...)
if err != nil {
return nil, nil, fmt.Errorf("parsing reference %q: %v", reference, err)
}
// FIXME: Hack for the go-containerregistry library,
// FIXME: that uses default transport without options to change transport to custom.
// FIXME: Needed for the insecure https registry to work.
oldDefaultTransport := http.DefaultTransport
http.DefaultTransport = api.getHttpTransport()
img, err := remote.Image(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain))
http.DefaultTransport = oldDefaultTransport
if err != nil {
return nil, nil, fmt.Errorf("reading image %q: %v", ref, err)
}
return img, ref, nil
}
func (api *api) newRepositoryOptions() []name.Option {
return api.parseReferenceOptions()
}
func (api *api) parseReferenceOptions() []name.Option {
var options []name.Option
options = append(options, name.WeakValidation)
if api.InsecureRegistry {
options = append(options, name.Insecure)
}
return options
}
func (api *api) defaultRemoteOptions() []remote.Option {
return []remote.Option{remote.WithAuthFromKeychain(authn.DefaultKeychain), remote.WithTransport(api.getHttpTransport())}
}
func (api *api) getHttpTransport() (transport http.RoundTripper) {
transport = http.DefaultTransport
if api.SkipTlsVerifyRegistry {
defaultTransport := http.DefaultTransport.(*http.Transport)
newTransport := &http.Transport{
Proxy: defaultTransport.Proxy,
DialContext: defaultTransport.DialContext,
MaxIdleConns: defaultTransport.MaxIdleConns,
IdleConnTimeout: defaultTransport.IdleConnTimeout,
TLSHandshakeTimeout: defaultTransport.TLSHandshakeTimeout,
ExpectContinueTimeout: defaultTransport.ExpectContinueTimeout,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
TLSNextProto: make(map[string]func(authority string, c *tls.Conn) http.RoundTripper),
}
transport = newTransport
}
return
}
type referenceParts struct {
registry string
repository string
tag string
digest string
}
func (api *api) ParseReferenceParts(reference string) (referenceParts, error) {
// validate reference
parsedReference, err := name.ParseReference(reference, api.parseReferenceOptions()...)
if err != nil {
return referenceParts{}, fmt.Errorf("unable to parse reference: %s", err)
}
res := dockerReference.ReferenceRegexp.FindStringSubmatch(reference)
// res[0] full match
// res[1] repository
// res[2] tag
// res[3] digest
if len(res) != 4 {
panic(fmt.Sprintf("unexpected regexp find submatch result %v (%d)", res, len(res)))
}
referenceParts := referenceParts{}
referenceParts.registry = parsedReference.Context().RegistryStr()
referenceParts.repository = parsedReference.Context().RepositoryStr()
referenceParts.tag = res[2]
if referenceParts.tag == "" {
referenceParts.tag = name.DefaultTag
}
referenceParts.digest = res[3]
return referenceParts, nil
}
| [
"\"WERF_DOCKER_REGISTRY_DEBUG\""
]
| []
| [
"WERF_DOCKER_REGISTRY_DEBUG"
]
| [] | ["WERF_DOCKER_REGISTRY_DEBUG"] | go | 1 | 0 | |
cmd/pod-defaulter/pod-defaulter.go | package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"github.com/softonic/pod-defaulter/pkg/admission"
h "github.com/softonic/pod-defaulter/pkg/http"
"github.com/softonic/pod-defaulter/pkg/version"
//This supports JSON tags
"github.com/ghodss/yaml"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/klog"
"net/http"
"os"
)
type params struct {
version bool
certificate string
privateKey string
LogLevel int
}
const DEFAULT_BIND_ADDRESS = ":8443"
var handler *h.HttpHandler
func init() {
klog.InitFlags(nil)
}
func main() {
var params params
if len(os.Args) < 2 {
klog.Fatalf("Minimum arguments are 2")
os.Exit(1)
}
flag.StringVar(¶ms.certificate, "tls-cert", "bar", "a string var")
flag.StringVar(¶ms.privateKey, "tls-key", "bar", "a string var")
flag.Parse()
// Read ConfigMap
config, err := rest.InClusterConfig()
if err != nil {
panic(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
namespace := os.Getenv("POD_NAMESPACE")
cmName := os.Getenv("CONFIGMAP_NAME")
//@TODO: extract this to its own class
cm, err := clientset.CoreV1().ConfigMaps(namespace).Get(context.TODO(), cmName, metav1.GetOptions{})
if err != nil {
klog.Fatalf("Invalid config %s/%s : %v", namespace, cmName, err)
}
configPodTemplate := &v1.PodTemplateSpec{}
err = yaml.Unmarshal([]byte(cm.Data["config"]), configPodTemplate)
if err != nil {
klog.Fatalf("Invalid config %v", err)
}
handler = getHttpHandler(configPodTemplate)
if params.version {
fmt.Println("Version:", version.Version)
} else {
run(¶ms)
}
}
func run(params *params) {
mux := http.NewServeMux()
_, err := tls.LoadX509KeyPair(params.certificate, params.privateKey)
if err != nil {
klog.Errorf("Failed to load key pair: %v", err)
}
mux.HandleFunc("/mutate", func(w http.ResponseWriter, r *http.Request) {
handler.MutationHandler(w, r)
})
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
handler.HealthCheckHandler(w, r)
})
cfg := &tls.Config{
MinVersion: tls.VersionTLS12,
CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
PreferServerCipherSuites: true,
CipherSuites: []uint16{
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
},
}
address := os.Getenv("BIND_ADDRESS")
if address == "" {
address = DEFAULT_BIND_ADDRESS
}
klog.V(2).Infof("Starting server, bound at %v", address)
klog.Infof("Listening to address %v", address)
srv := &http.Server{
Addr: address,
Handler: mux,
TLSConfig: cfg,
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
}
klog.Fatalf("Could not start server: %v", srv.ListenAndServeTLS(params.certificate, params.privateKey))
}
func getHttpHandler(cm *v1.PodTemplateSpec) *h.HttpHandler {
return h.NewHttpHanlder(getPodDefaultValuesAdmissionReviewer(cm))
}
func getPodDefaultValuesAdmissionReviewer(cm *v1.PodTemplateSpec) *admission.AdmissionReviewer {
return admission.NewPodDefaultValuesAdmissionReviewer(cm)
}
| [
"\"POD_NAMESPACE\"",
"\"CONFIGMAP_NAME\"",
"\"BIND_ADDRESS\""
]
| []
| [
"POD_NAMESPACE",
"CONFIGMAP_NAME",
"BIND_ADDRESS"
]
| [] | ["POD_NAMESPACE", "CONFIGMAP_NAME", "BIND_ADDRESS"] | go | 3 | 0 | |
vendor/github.com/ONSdigital/go-ns/log/log.go | package log
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"os"
"strconv"
"sync"
"time"
"github.com/ONSdigital/go-ns/common"
"github.com/mgutz/ansi"
)
// Namespace is the service namespace used for logging
var Namespace = "service-namespace"
// HumanReadable represents a flag to determine if log events
// will be in a human readable format
var HumanReadable bool
var hrMutex sync.Mutex
func init() {
configureHumanReadable()
}
func configureHumanReadable() {
HumanReadable, _ = strconv.ParseBool(os.Getenv("HUMAN_LOG"))
}
// Data contains structured log data
type Data map[string]interface{}
// GetRequestID returns the request ID from a request (using X-Request-Id)
func GetRequestID(req *http.Request) string {
return req.Header.Get(common.RequestHeaderKey)
}
// Handler wraps a http.Handler and logs the status code and total response time
func Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
rc := &responseCapture{w, 0}
s := time.Now()
h.ServeHTTP(rc, req)
e := time.Now()
d := e.Sub(s)
data := Data{
"start": s,
"end": e,
"duration": d,
"status": rc.statusCode,
"method": req.Method,
"path": req.URL.Path,
}
if len(req.URL.RawQuery) > 0 {
data["query"] = req.URL.Query()
}
Event("request", GetRequestID(req), data)
})
}
type responseCapture struct {
http.ResponseWriter
statusCode int
}
func (r *responseCapture) WriteHeader(status int) {
r.statusCode = status
r.ResponseWriter.WriteHeader(status)
}
func (r *responseCapture) Flush() {
if f, ok := r.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
func (r *responseCapture) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if h, ok := r.ResponseWriter.(http.Hijacker); ok {
return h.Hijack()
}
return nil, nil, errors.New("log: response does not implement http.Hijacker")
}
// Event records an event
var Event = event
func event(name string, correlationKey string, data Data) {
m := map[string]interface{}{
"created": time.Now(),
"event": name,
"namespace": Namespace,
}
if len(correlationKey) > 0 {
m["correlation_key"] = correlationKey
}
if data != nil {
m["data"] = data
}
if HumanReadable {
printHumanReadable(name, correlationKey, data, m)
return
}
b, err := json.Marshal(&m)
if err != nil {
// This should never happen
// We'll log the error (which for our purposes, can't fail), which
// gives us an indication we have something to investigate
b, _ = json.Marshal(map[string]interface{}{
"created": time.Now(),
"event": "log_error",
"namespace": Namespace,
"correlation_key": correlationKey,
"data": map[string]interface{}{"error": err.Error()},
})
}
fmt.Fprintf(os.Stdout, "%s\n", b)
}
func printHumanReadable(name, correlationKey string, data Data, m map[string]interface{}) {
hrMutex.Lock()
defer hrMutex.Unlock()
ctx := ""
if len(correlationKey) > 0 {
ctx = "[" + correlationKey + "] "
}
msg := ""
if message, ok := data["message"]; ok {
msg = ": " + fmt.Sprintf("%s", message)
delete(data, "message")
}
if name == "error" && len(msg) == 0 {
if err, ok := data["error"]; ok {
msg = ": " + fmt.Sprintf("%s", err)
delete(data, "error")
}
}
col := ansi.DefaultFG
switch name {
case "error":
col = ansi.LightRed
case "info":
col = ansi.LightCyan
case "trace":
col = ansi.Blue
case "debug":
col = ansi.Green
case "request":
col = ansi.Cyan
}
fmt.Fprintf(os.Stdout, "%s%s %s%s%s%s\n", col, m["created"], ctx, name, msg, ansi.DefaultFG)
if data != nil {
for k, v := range data {
fmt.Fprintf(os.Stdout, " -> %s: %+v\n", k, v)
}
}
}
// ErrorC is a structured error message with correlationKey
func ErrorC(correlationKey string, err error, data Data) {
if data == nil {
data = Data{}
}
if err != nil {
data["message"] = err.Error()
data["error"] = err
}
Event("error", correlationKey, data)
}
// ErrorCtx is a structured error message and retrieves the correlationKey from go context
func ErrorCtx(ctx context.Context, err error, data Data) {
correlationKey := common.GetRequestId(ctx)
ErrorC(correlationKey, err, data)
}
// ErrorR is a structured error message for a request
func ErrorR(req *http.Request, err error, data Data) {
ErrorC(GetRequestID(req), err, data)
}
// Error is a structured error message
func Error(err error, data Data) {
ErrorC("", err, data)
}
// DebugC is a structured debug message with correlationKey
func DebugC(correlationKey string, message string, data Data) {
if data == nil {
data = Data{}
}
if len(message) > 0 {
data["message"] = message
}
Event("debug", correlationKey, data)
}
// DebugCtx is a structured debug message and retrieves the correlationKey from go context
func DebugCtx(ctx context.Context, message string, data Data) {
correlationKey := common.GetRequestId(ctx)
DebugC(correlationKey, message, data)
}
// DebugR is a structured debug message for a request
func DebugR(req *http.Request, message string, data Data) {
DebugC(GetRequestID(req), message, data)
}
// Debug is a structured trace message
func Debug(message string, data Data) {
DebugC("", message, data)
}
// TraceC is a structured trace message with correlationKey
func TraceC(correlationKey string, message string, data Data) {
if data == nil {
data = Data{}
}
if len(message) > 0 {
data["message"] = message
}
Event("trace", correlationKey, data)
}
// TraceCtx is a structured trace message and retrieves the correlationKey from go context
func TraceCtx(ctx context.Context, message string, data Data) {
correlationKey := common.GetRequestId(ctx)
TraceC(correlationKey, message, data)
}
// TraceR is a structured trace message for a request
func TraceR(req *http.Request, message string, data Data) {
TraceC(GetRequestID(req), message, data)
}
// Trace is a structured trace message
func Trace(message string, data Data) {
TraceC("", message, data)
}
// InfoC is a structured info message with correlationKey
func InfoC(correlationKey string, message string, data Data) {
if data == nil {
data = Data{}
}
if len(message) > 0 {
data["message"] = message
}
Event("info", correlationKey, data)
}
// InfoCtx is a structured info message and retrieves the correlationKey from go context
func InfoCtx(ctx context.Context, message string, data Data) {
correlationKey := common.GetRequestId(ctx)
InfoC(correlationKey, message, data)
}
// InfoR is a structured info message for a request
func InfoR(req *http.Request, message string, data Data) {
InfoC(GetRequestID(req), message, data)
}
// Info is a structured info message
func Info(message string, data Data) {
InfoC("", message, data)
}
| [
"\"HUMAN_LOG\""
]
| []
| [
"HUMAN_LOG"
]
| [] | ["HUMAN_LOG"] | go | 1 | 0 | |
api/services/emailverification/email-verification.go | package emailverification
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/smtp"
"os"
"time"
"github.com/sarmerer/forum/api/config"
"github.com/sarmerer/forum/api/logger"
"github.com/sarmerer/forum/api/models"
"github.com/sarmerer/forum/api/repository"
"github.com/sarmerer/forum/api/repository/crud"
)
type manager struct {
Pending map[string]string
Emails map[string]string
}
func NewManager() *manager {
return &manager{Pending: make(map[string]string), Emails: make(map[string]string)}
}
var Manager = NewManager()
func (m *manager) SendVerificationEmail(user *models.User) error {
var (
code string
message string
err error
)
if m.emailPending(user.Email) {
return errors.New("email already pending verification")
}
if code, err = generateCode(6); err != nil {
return err
}
go m.deleteUnverifiedUser(user.ID, code, user.Email, config.VerificationCodeExpiriation)
m.addPending(code, user.Email)
message = fmt.Sprintf("Your verification code: %s", code)
if err = m.sendMail(user.Email, message); err != nil {
return err
}
return nil
}
func (m *manager) ResendVerificationEmail(email string) (int, error) {
var (
code string = m.getCodeByEmail(email)
message string
err error
httpTokenExpired int = 498
)
if code == "" {
return httpTokenExpired, errors.New("invalid or expired code")
}
message = fmt.Sprintf("Your verification code: %s", code)
if err = m.sendMail(email, message); err != nil {
return http.StatusInternalServerError, err
}
return http.StatusOK, nil
}
func (m *manager) Verify(email, code string) (int, error) {
var httpTokenExpired int = 498
if m.getCodeByEmail(m.getEmailByCode(code)) != code {
return httpTokenExpired, errors.New("invalid or expired token")
}
return http.StatusOK, nil
}
func (m *manager) sendMail(to, body string) error {
var (
username string = os.Getenv("AWS_SES_USERNAME")
password string = os.Getenv("AWS_SES_PASSWORD")
smtpServer string = os.Getenv("AWS_SES_SMTP_SERVER")
from string = "[email protected]"
subject string = "Verify Email"
message string
headers map[string]string = make(map[string]string)
mimeVersion string = "1.0"
contentType string = "text/plain; charset=\"utf-8\""
encoding string = "base64"
)
if username == "" || password == "" || smtpServer == "" {
return errors.New("could not find credinentials environment vars")
}
auth := smtp.PlainAuth("", username, password, smtpServer)
headers["From"] = from
headers["To"] = to
headers["Subject"] = subject
headers["MIME-Version"] = mimeVersion
headers["Content-Type"] = contentType
headers["Content-Transfer-Encoding"] = encoding
for k, v := range headers {
message += fmt.Sprintf("%s: %s\r\n", k, v)
}
message += "\r\n" + base64.StdEncoding.EncodeToString([]byte(body))
if err := smtp.SendMail(smtpServer+":587", auth, from, []string{to}, []byte(message)); err != nil {
return err
}
return nil
}
func (m *manager) getEmailByCode(code string) string {
return m.Pending[code]
}
func (m *manager) getCodeByEmail(email string) string {
return m.Emails[email]
}
func (m *manager) addPending(code, email string) {
m.Pending[code] = email
m.Emails[email] = code
}
func (m *manager) removePending(code, email string) {
delete(m.Pending, code)
delete(m.Emails, email)
}
func (m *manager) deleteUnverifiedUser(userID int64, code, email string, after time.Duration) {
var (
errText string = "deleting unverified user error"
instance string = "Email verification manager"
)
time.Sleep(after)
var (
repo repository.UserRepo = crud.NewUserRepoCRUD()
user *models.User
err error
)
if user, _, err = repo.FindByID(userID); err != nil {
logger.CheckErrAndLog(instance, errText, err)
return
}
if !user.Verified {
m.removePending(code, email)
if _, err = repo.Delete(user.ID); err != nil {
logger.CheckErrAndLog(instance, errText, err)
return
}
logger.CheckErrAndLog(instance, "deleted unverified user", nil)
}
}
func (m *manager) emailPending(email string) bool {
return m.Emails[email] != ""
}
func generateCode(length int) (string, error) {
buffer := make([]byte, length)
_, err := rand.Read(buffer)
if err != nil {
return "", err
}
const otpChars = "1234567890"
otpCharsLength := len(otpChars)
for i := 0; i < length; i++ {
buffer[i] = otpChars[int(buffer[i])%otpCharsLength]
}
return string(buffer), nil
}
| [
"\"AWS_SES_USERNAME\"",
"\"AWS_SES_PASSWORD\"",
"\"AWS_SES_SMTP_SERVER\""
]
| []
| [
"AWS_SES_SMTP_SERVER",
"AWS_SES_PASSWORD",
"AWS_SES_USERNAME"
]
| [] | ["AWS_SES_SMTP_SERVER", "AWS_SES_PASSWORD", "AWS_SES_USERNAME"] | go | 3 | 0 | |
Godeps/_workspace/src/google.golang.org/appengine/remote_api/client_test.go | package remote_api
import (
"testing"
)
func TestAppIDRE(t *testing.T) {
appID := "s~my-appid-539"
tests := []string{
"{rtok: 8306111115908860449, app_id: s~my-appid-539}\n",
"{rtok: 8306111115908860449, app_id: 's~my-appid-539'}\n",
`{rtok: 8306111115908860449, app_id: "s~my-appid-539"}`,
`{rtok: 8306111115908860449, "app_id":"s~my-appid-539"}`,
}
for _, v := range tests {
if g := appIDRE.FindStringSubmatch(v); g == nil || g[1] != appID {
t.Errorf("appIDRE.FindStringSubmatch(%s) got %q, want %q", v, g, appID)
}
}
}
| []
| []
| []
| [] | [] | go | null | null | null |
server/server.go | package main
import (
"log"
"net/http"
"os"
"github.com/99designs/gqlgen/handler"
prisma "github.com/Sach97/prisma-go-hackernews/prisma-client"
)
const defaultPort = "4000"
func main() {
port := os.Getenv("PORT")
if port == "" {
port = defaultPort
}
client := prisma.New(nil)
resolver := Resolver{
Prisma: client,
}
http.Handle("/", handler.Playground("GraphQL playground", "/query"))
http.Handle("/query", handler.GraphQL(NewExecutableSchema(Config{Resolvers: &resolver})))
log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
| [
"\"PORT\""
]
| []
| [
"PORT"
]
| [] | ["PORT"] | go | 1 | 0 | |
backend/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', 'pay_calculator_33046.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 | |
lib/file_io.py | import mypy, os
from typing import List, Tuple
from lib.Sequence import Sequence
###
# Data file manipulation: reading in sequence data and PDB file references.
###
def exe(name: str) -> str:
"""
For distribution, once I've merged into master: look for ROSETTA in
os.environ and return exe path based on that.
"""
import os
if os.path.exists("/home/andy"):
return "/home/andy/Rosetta/main/source/bin/" + name
else:
return "/Users/amw579/dev_ui/Rosetta/main/source/bin/" + name
def my_loc() -> str:
"""
Since moving this to a library file... now it gives an undesired path.
"""
import os
return os.path.dirname(os.path.realpath(__file__)).replace('lib', '')
def get_seqs_mfa(fn: str) -> List[Tuple[str, Sequence]]:
"""
Get sequences out of the tRNAdb mfa
"""
lines = [] # type: List[str]
with open(fn) as f:
lines = f.readlines()
sequences = [('', Sequence(l.strip())) for l in lines[1::2]]
return sequences
def get_seqs(fn: str) -> List[Tuple[str, Sequence]]:
lines = [] # type: List[str]
with open(fn) as f:
lines = f.readlines()
#sequences = {l.strip().split()[0]: l.strip().split()[1] for l in lines if "ALIGNED_TO" in l }
sequences = [(l.strip().split()[0], Sequence(l.strip().split()[1]))
for l in lines if "PDB_SEQ" in l]
return sequences
| []
| []
| []
| [] | [] | python | 0 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.